repo_name stringlengths 5 100 | path stringlengths 4 294 | copies stringclasses 990
values | size stringlengths 4 7 | content stringlengths 666 1M | license stringclasses 15
values |
|---|---|---|---|---|---|
Matt-Deacalion/django | django/contrib/gis/geos/prototypes/prepared.py | 288 | 1214 | from ctypes import c_char
from django.contrib.gis.geos.libgeos import (
GEOM_PTR, PREPGEOM_PTR, GEOSFuncFactory,
)
from django.contrib.gis.geos.prototypes.errcheck import check_predicate
# Prepared geometry constructor and destructors.
geos_prepare = GEOSFuncFactory('GEOSPrepare', argtypes=[GEOM_PTR], restype=PREPGEOM_PTR)
prepared_destroy = GEOSFuncFactory('GEOSPreparedGeom_destroy', argtpes=[PREPGEOM_PTR])
# Prepared geometry binary predicate support.
class PreparedPredicate(GEOSFuncFactory):
argtypes = [PREPGEOM_PTR, GEOM_PTR]
restype = c_char
errcheck = staticmethod(check_predicate)
prepared_contains = PreparedPredicate('GEOSPreparedContains')
prepared_contains_properly = PreparedPredicate('GEOSPreparedContainsProperly')
prepared_covers = PreparedPredicate('GEOSPreparedCovers')
prepared_intersects = PreparedPredicate('GEOSPreparedIntersects')
# Functions added in GEOS 3.3
prepared_crosses = PreparedPredicate('GEOSPreparedCrosses')
prepared_disjoint = PreparedPredicate('GEOSPreparedDisjoint')
prepared_overlaps = PreparedPredicate('GEOSPreparedOverlaps')
prepared_touches = PreparedPredicate('GEOSPreparedTouches')
prepared_within = PreparedPredicate('GEOSPreparedWithin')
| bsd-3-clause |
johnbachman/indra | indra/benchmarks/benchmark_trips.py | 6 | 12953 | from __future__ import absolute_import, print_function, unicode_literals
import os
from os.path import dirname, join
import sys
import indra.statements
from indra.sources import trips
from indra.assemblers.pysb import PysbAssembler
def test_bind():
fname = sys._getframe().f_code.co_name + '.xml'
txt = 'The receptor tyrosine kinase EGFR binds the growth factor ligand EGF.'
tp = trips.process_text(txt, fname, False)
assert(len(tp.statements) == 1)
st = tp.statements[0]
assert(is_complex(st))
assert(len(st.members) == 2)
assert(has_hgnc_ref(st.members[0]))
assert(has_hgnc_ref(st.members[1]))
os.remove(fname)
def test_complex_bind():
fname = sys._getframe().f_code.co_name + '.xml'
txt = 'The EGFR-EGF complex binds another EGFR-EGF complex.'
tp = trips.process_text(txt, fname, False)
assert(len(tp.statements) == 1)
st = tp.statements[0]
assert(is_complex(st))
assert(len(st.members) == 2)
assert(has_hgnc_ref(st.members[0]))
assert(has_hgnc_ref(st.members[1]))
assert(st.members[0].bound_conditions)
assert(st.members[1].bound_conditions)
os.remove(fname)
def test_complex_bind2():
fname = sys._getframe().f_code.co_name + '.xml'
txt = 'The EGFR-EGFR complex binds GRB2.'
tp = trips.process_text(txt, fname, False)
assert(len(tp.statements) == 1)
st = tp.statements[0]
assert(is_complex(st))
assert(len(st.members) == 2)
assert(st.members[0].name == 'EGFR')
assert(st.members[1].name == 'GRB2')
assert(len(st.members[0].bound_conditions) == 1)
assert(st.members[0].bound_conditions[0].agent.name == 'EGFR')
os.remove(fname)
def test_complex_bind3():
fname = sys._getframe().f_code.co_name + '.xml'
txt = 'RAF binds to the RAS-GTP complex.'
tp = trips.process_text(txt, fname, False)
assert(len(tp.statements) == 1)
st = tp.statements[0]
assert(is_complex(st))
assert(len(st.members) == 2)
assert(st.members[0].name == 'RAF')
assert(st.members[1].name == 'RAS')
assert(len(st.members[1].bound_conditions) == 1)
assert(st.members[1].bound_conditions[0].agent.name == 'GTP')
os.remove(fname)
def test_complex_bind4():
fname = sys._getframe().f_code.co_name + '.xml'
txt = 'The RAF-RAS complex binds another RAF-RAS complex.'
tp = trips.process_text(txt, fname, False)
assert(len(tp.statements) == 1)
st = tp.statements[0]
assert(is_complex(st))
assert(len(st.members) == 2)
assert(st.members[0].name == 'RAF')
assert(st.members[1].name == 'RAF')
assert(len(st.members[0].bound_conditions) == 1)
assert(st.members[0].bound_conditions[0].agent.name == 'RAS')
assert(len(st.members[1].bound_conditions) == 1)
assert(st.members[1].bound_conditions[0].agent.name == 'RAS')
os.remove(fname)
def test_bound_mod():
fname = sys._getframe().f_code.co_name + '.xml'
txt = 'The adaptor protein GRB2 can bind EGFR that is phosphorylated on tyrosine.'
tp = trips.process_text(txt, fname, False)
assert(len(tp.statements) == 1)
st = tp.statements[0]
assert(is_complex(st))
assert(len(st.members) == 2)
assert(has_hgnc_ref(st.members[0]))
assert(has_hgnc_ref(st.members[1]))
assert(st.members[1].mods)
assert(st.members[1].mods[0].mod_type == 'phosphorylation')
assert(st.members[1].mods[0].residue == 'Y')
os.remove(fname)
def test_not_bound_to():
fname = sys._getframe().f_code.co_name + '.xml'
txt = 'BRAF that is not bound to Vemurafenib binds MEK1.'
tp = trips.process_text(txt, fname, False)
assert(len(tp.statements) == 1)
st = tp.statements[0]
assert(is_complex(st))
assert(len(st.members) == 2)
assert(st.members[0].name == 'BRAF')
assert(has_hgnc_ref(st.members[0]))
assert(st.members[1].name == 'MAP2K1')
assert(has_hgnc_ref(st.members[1]))
assert(len(st.members[0].bound_conditions) == 1)
assert(st.members[0].bound_conditions[0].agent.name.lower() == 'vemurafenib')
assert(st.members[0].bound_conditions[0].is_bound == False)
os.remove(fname)
def test_not_bound_to2():
fname = sys._getframe().f_code.co_name + '.xml'
txt = 'BRAF, not bound to Vemurafenib, phosphorylates MEK1.'
tp = trips.process_text(txt, fname, False)
assert(len(tp.statements) == 1)
st = tp.statements[0]
assert(is_phosphorylation(st))
assert(st.enz is not None)
assert(st.sub is not None)
assert(st.enz.name == 'BRAF')
assert(has_hgnc_ref(st.enz))
assert(st.sub.name == 'MAP2K1')
assert(has_hgnc_ref(st.sub))
assert(len(st.enz.bound_conditions) == 1)
assert(st.enz.bound_conditions[0].agent.name.lower() == 'vemurafenib')
assert(st.enz.bound_conditions[0].is_bound == False)
os.remove(fname)
def test_not_bound_to3():
fname = sys._getframe().f_code.co_name + '.xml'
txt = 'SOS1 bound to GRB2 binds NRAS that is not bound to BRAF and GTP.'
tp = trips.process_text(txt, fname, False)
assert(len(tp.statements) == 1)
st = tp.statements[0]
assert(is_complex(st))
assert(st.members[0].name == 'SOS1')
assert(st.members[1].name == 'NRAS')
assert(len(st.members[0].bound_conditions) == 1)
assert(len(st.members[1].bound_conditions) == 2)
os.remove(fname)
def test_not_bound_to4():
fname = sys._getframe().f_code.co_name + '.xml'
txt = 'BRAF that is not bound to NRAS and Vemurafenib binds BRAF ' +\
'that is not bound to Vemurafenib.'
tp = trips.process_text(txt, fname, False)
assert(len(tp.statements) == 1)
st = tp.statements[0]
assert(is_complex(st))
assert(st.members[0].name == 'BRAF')
assert(st.members[1].name == 'BRAF')
assert(len(st.members[0].bound_conditions) == 2)
assert(len(st.members[1].bound_conditions) == 1)
os.remove(fname)
def test_bound_to():
fname = sys._getframe().f_code.co_name + '.xml'
txt = 'NRAS, bound to GTP, binds BRAF.'
tp = trips.process_text(txt, fname, False)
assert(len(tp.statements) == 1)
st = tp.statements[0]
assert(is_complex(st))
assert(len(st.members) == 2)
assert(st.members[0].name == 'NRAS')
assert(has_hgnc_ref(st.members[0]))
assert(st.members[1].name == 'BRAF')
assert(has_hgnc_ref(st.members[1]))
assert(len(st.members[0].bound_conditions) == 1)
assert(st.members[0].bound_conditions[0].agent.name == 'GTP')
os.remove(fname)
def test_bound_to2():
fname = sys._getframe().f_code.co_name + '.xml'
txt = 'EGFR-bound GRB2 binds SOS1.'
tp = trips.process_text(txt, fname, False)
assert(len(tp.statements) == 1)
st = tp.statements[0]
assert(is_complex(st))
assert(len(st.members) == 2)
assert(st.members[0].name == 'GRB2')
assert(has_hgnc_ref(st.members[0]))
assert(st.members[1].name == 'SOS1')
assert(has_hgnc_ref(st.members[1]))
assert(len(st.members[0].bound_conditions) == 1)
assert(st.members[0].bound_conditions[0].agent.name == 'EGFR')
os.remove(fname)
def test_bound_to3():
fname = sys._getframe().f_code.co_name + '.xml'
txt = 'SOS1, bound to GRB2 binds RAS.'
tp = trips.process_text(txt, fname, False)
assert(len(tp.statements) == 1)
st = tp.statements[0]
assert(is_complex(st))
assert(len(st.members) == 2)
assert(st.members[0].name == 'SOS1')
assert(has_hgnc_ref(st.members[0]))
assert(st.members[1].name == 'RAS')
assert(len(st.members[0].bound_conditions) == 1)
assert(st.members[0].bound_conditions[0].agent.name == 'GRB2')
os.remove(fname)
def test_bound_to4():
fname = sys._getframe().f_code.co_name + '.xml'
txt = 'RAS, bound to SOS1, binds GTP.'
tp = trips.process_text(txt, fname, False)
assert(len(tp.statements) == 1)
st = tp.statements[0]
assert(is_complex(st))
assert(len(st.members) == 2)
assert(st.members[0].name == 'RAS')
assert(st.members[1].name == 'GTP')
assert(len(st.members[0].bound_conditions) == 1)
assert(st.members[0].bound_conditions[0].agent.name == 'SOS1')
os.remove(fname)
def test_bound_to5():
fname = sys._getframe().f_code.co_name + '.xml'
txt = 'BRAF that is bound to NRAS and Vemurafenib binds ' +\
'BRAF that is bound to NRAS and Vemurafenib.'
tp = trips.process_text(txt, fname, False)
assert(len(tp.statements) == 1)
st = tp.statements[0]
assert(is_complex(st))
assert(len(st.members) == 2)
assert(st.members[0].name == 'BRAF')
assert(st.members[1].name == 'BRAF')
assert(len(st.members[0].bound_conditions) == 2)
assert(len(st.members[1].bound_conditions) == 2)
os.remove(fname)
def test_transphosphorylate():
fname = sys._getframe().f_code.co_name + '.xml'
txt = 'EGFR, bound to EGFR, transphosphorylates itself.'
tp = trips.process_text(txt, fname, False)
assert(len(tp.statements) == 1)
st = tp.statements[0]
assert(is_transphosphorylation(st))
assert(st.enz is not None)
assert(st.enz.name == 'EGFR')
assert(has_hgnc_ref(st.enz))
assert(st.residue == None)
assert(len(st.enz.bound_conditions) == 1)
assert(st.enz.bound_conditions[0].agent.name == 'EGFR')
os.remove(fname)
def test_transphosphorylate2():
fname = sys._getframe().f_code.co_name + '.xml'
txt = 'EGFR, bound to EGFR, transphosphorylates itself on a tyrosine residue.'
tp = trips.process_text(txt, fname, False)
assert(len(tp.statements) == 1)
st = tp.statements[0]
assert(is_transphosphorylation(st))
assert(st.enz is not None)
assert(st.enz.name == 'EGFR')
assert(has_hgnc_ref(st.enz))
assert(st.residue == 'Y')
assert(len(st.enz.bound_conditions) == 1)
assert(st.enz.bound_conditions[0].agent.name == 'EGFR')
os.remove(fname)
def test_act_mod():
fname = sys._getframe().f_code.co_name + '.xml'
txt = 'MEK1, phosphorylated at Ser218 and Ser222, is activated.'
tp = trips.process_text(txt, fname, False)
assert(len(tp.statements) == 1)
st = tp.statements[0]
assert(is_actmod(st))
assert(st.agent is not None)
assert(st.agent.name == 'MAP2K1')
residues = [m.residue for m in st.agent.mods]
positions = [m.position for m in st.agent.mods]
assert(residues == ['S', 'S'])
assert(positions == ['218', '222'])
assert(st.is_active)
os.remove(fname)
def test_bound_phosphorylate():
fname = sys._getframe().f_code.co_name + '.xml'
txt = 'RAF, bound to RAF, phosphorylates MEK1.'
tp = trips.process_text(txt, fname, False)
assert(len(tp.statements) == 1)
st = tp.statements[0]
assert(is_phosphorylation(st))
assert(st.enz is not None)
assert(st.enz.name == 'RAF')
assert(st.sub is not None)
assert(st.sub.name == 'MAP2K1')
assert(st.residue == None)
os.remove(fname)
'''
def test_bound_not_bound_phosphorylate():
fname = sys._getframe().f_code.co_name + '.xml'
txt = 'BRAF-bound BRAF that is not bound to Vemurafenib phosphorylates MEK1.'
tp = trips.process_text(txt, fname, False)
assert(len(tp.statements) == 1)
st = tp.statements[0]
assert(is_phosphorylation(st))
assert(st.enz is not None)
assert(st.enz.name == 'MAP2K1')
assert(st.monomer.mod == ['PhosphorylationSerine', 'PhosphorylationSerine'])
assert(st.monomer.mod_pos == ['218', '222'])
assert(st.relationship == 'increases')
os.remove(fname)
'''
def test_act_phosphorylate():
fname = sys._getframe().f_code.co_name + '.xml'
txt = 'Active MEK1 phosphorylates ERK2 at Tyr187.'
tp = trips.process_text(txt, fname, False)
assert(len(tp.statements) == 1)
st = tp.statements[0]
assert(is_phosphorylation(st))
assert(st.enz is not None)
assert(st.enz.name == 'MAP2K1')
assert(st.sub is not None)
assert(st.sub.name == 'MAPK1')
assert(st.residue == 'Y')
assert(st.position == '187')
os.remove(fname)
def test_dephosphorylate():
fname = sys._getframe().f_code.co_name + '.xml'
txt = 'DUSP6 dephosphorylates ERK2 at Tyr187.'
tp = trips.process_text(txt, fname, False)
assert(len(tp.statements) == 1)
st = tp.statements[0]
assert(is_dephosphorylation(st))
assert(st.enz is not None)
assert(st.enz.name == 'DUSP6')
assert(st.sub is not None)
assert(st.sub.name == 'MAPK1')
assert(st.residue == 'Y')
assert(st.position == '187')
os.remove(fname)
def is_complex(statement):
return isinstance(statement, indra.statements.Complex)
def is_phosphorylation(statement):
return isinstance(statement, indra.statements.Phosphorylation)
def is_transphosphorylation(statement):
return isinstance(statement, indra.statements.Transphosphorylation)
def is_actmod(statement):
return isinstance(statement, indra.statements.ActiveForm)
def is_dephosphorylation(statement):
return isinstance(statement, indra.statements.Dephosphorylation)
def has_hgnc_ref(agent):
return ('HGNC' in agent.db_refs.keys())
| bsd-2-clause |
lojack/wagtail | wagtail/wagtailsearch/tests/test_backends.py | 6 | 6066 | from six import StringIO
import warnings
from django.test import TestCase
from django.test.utils import override_settings
from django.conf import settings
from django.core import management
from wagtail.tests.utils import unittest, WagtailTestUtils
from wagtail.tests import models
from wagtail.wagtailsearch.backends import get_search_backend, InvalidSearchBackendError
from wagtail.wagtailsearch.backends.db import DBSearch
class BackendTests(WagtailTestUtils):
# To test a specific backend, subclass BackendTests and define self.backend_path.
def setUp(self):
# Search WAGTAILSEARCH_BACKENDS for an entry that uses the given backend path
for backend_name, backend_conf in settings.WAGTAILSEARCH_BACKENDS.items():
if backend_conf['BACKEND'] == self.backend_path:
self.backend = get_search_backend(backend_name)
break
else:
# no conf entry found - skip tests for this backend
raise unittest.SkipTest("No WAGTAILSEARCH_BACKENDS entry for the backend %s" % self.backend_path)
self.load_test_data()
def load_test_data(self):
# Reset the index
self.backend.reset_index()
self.backend.add_type(models.SearchTest)
self.backend.add_type(models.SearchTestChild)
# Create a test database
testa = models.SearchTest()
testa.title = "Hello World"
testa.save()
self.backend.add(testa)
self.testa = testa
testb = models.SearchTest()
testb.title = "Hello"
testb.live = True
testb.save()
self.backend.add(testb)
testc = models.SearchTestChild()
testc.title = "Hello"
testc.live = True
testc.save()
self.backend.add(testc)
testd = models.SearchTestChild()
testd.title = "World"
testd.save()
self.backend.add(testd)
# Refresh the index
self.backend.refresh_index()
def test_blank_search(self):
# Get results for blank terms
results = self.backend.search("", models.SearchTest)
# Should return no results
self.assertEqual(len(results), 0)
def test_search(self):
# Get results for "Hello"
results = self.backend.search("Hello", models.SearchTest)
# Should return three results
self.assertEqual(len(results), 3)
# Get results for "World"
results = self.backend.search("World", models.SearchTest)
# Should return two results
self.assertEqual(len(results), 2)
@unittest.skip("Need something to prefetch")
def test_prefetch_related(self):
# Get results
results = self.backend.search("Hello", models.SearchTest, prefetch_related=['prefetch_field'])
# Test both single result and multiple result (different code for each), only checking that this doesnt crash
single_result = results[0]
multi_result = results[:2]
def test_callable_indexed_field(self):
# Get results
results = self.backend.search("Callable", models.SearchTest)
# Should get all 4 results as they all have the callable indexed field
self.assertEqual(len(results), 4)
def test_filters(self):
# Get only results with live=True set
results = self.backend.search("Hello", models.SearchTest, filters=dict(live=True))
# Should return two results
self.assertEqual(len(results), 2)
def test_single_result(self):
# Get a single result
result = self.backend.search("Hello", models.SearchTest)[0]
# Check that the result is a SearchTest object
self.assertIsInstance(result, models.SearchTest)
def test_sliced_results(self):
# Get results and slice them
sliced_results = self.backend.search("Hello", models.SearchTest)[1:3]
# Slice must have a length of 2
self.assertEqual(len(sliced_results), 2)
# Check that the results are SearchTest objects
for result in sliced_results:
self.assertIsInstance(result, models.SearchTest)
def test_child_model(self):
# Get results for child model
results = self.backend.search("Hello", models.SearchTestChild)
# Should return one object
self.assertEqual(len(results), 1)
def test_delete(self):
# Delete one of the objects
self.backend.delete(self.testa)
self.testa.delete()
# Refresh index
self.backend.refresh_index()
# Check that there are only two results
results = self.backend.search("Hello", models.SearchTest)
self.assertEqual(len(results), 2)
def test_update_index_command(self):
# Reset the index, this should clear out the index
self.backend.reset_index()
# Run update_index command
with self.ignore_deprecation_warnings(): # ignore any DeprecationWarnings thrown by models with old-style indexed_fields definitions
management.call_command('update_index', backend=self.backend, interactive=False, stdout=StringIO())
# Check that there are still 3 results
results = self.backend.search("Hello", models.SearchTest)
self.assertEqual(len(results), 3)
@override_settings(WAGTAILSEARCH_BACKENDS={
'default': {'BACKEND': 'wagtail.wagtailsearch.backends.db.DBSearch'}
})
class TestBackendLoader(TestCase):
def test_import_by_name(self):
db = get_search_backend(backend='default')
self.assertIsInstance(db, DBSearch)
def test_import_by_path(self):
db = get_search_backend(backend='wagtail.wagtailsearch.backends.db.DBSearch')
self.assertIsInstance(db, DBSearch)
def test_nonexistant_backend_import(self):
self.assertRaises(InvalidSearchBackendError, get_search_backend, backend='wagtail.wagtailsearch.backends.doesntexist.DoesntExist')
def test_invalid_backend_import(self):
self.assertRaises(InvalidSearchBackendError, get_search_backend, backend="I'm not a backend!")
| bsd-3-clause |
extremewaysback/django | django/contrib/gis/db/backends/mysql/operations.py | 328 | 2746 | from django.contrib.gis.db.backends.base.adapter import WKTAdapter
from django.contrib.gis.db.backends.base.operations import \
BaseSpatialOperations
from django.contrib.gis.db.backends.utils import SpatialOperator
from django.contrib.gis.db.models import aggregates
from django.db.backends.mysql.operations import DatabaseOperations
from django.utils.functional import cached_property
class MySQLOperations(BaseSpatialOperations, DatabaseOperations):
mysql = True
name = 'mysql'
select = 'AsText(%s)'
from_wkb = 'GeomFromWKB'
from_text = 'GeomFromText'
Adapter = WKTAdapter
Adaptor = Adapter # Backwards-compatibility alias.
gis_operators = {
'bbcontains': SpatialOperator(func='MBRContains'), # For consistency w/PostGIS API
'bboverlaps': SpatialOperator(func='MBROverlaps'), # .. ..
'contained': SpatialOperator(func='MBRWithin'), # .. ..
'contains': SpatialOperator(func='MBRContains'),
'disjoint': SpatialOperator(func='MBRDisjoint'),
'equals': SpatialOperator(func='MBREqual'),
'exact': SpatialOperator(func='MBREqual'),
'intersects': SpatialOperator(func='MBRIntersects'),
'overlaps': SpatialOperator(func='MBROverlaps'),
'same_as': SpatialOperator(func='MBREqual'),
'touches': SpatialOperator(func='MBRTouches'),
'within': SpatialOperator(func='MBRWithin'),
}
function_names = {
'Distance': 'ST_Distance',
'Length': 'GLength',
'Union': 'ST_Union',
}
disallowed_aggregates = (
aggregates.Collect, aggregates.Extent, aggregates.Extent3D,
aggregates.MakeLine, aggregates.Union,
)
@cached_property
def unsupported_functions(self):
unsupported = {
'AsGeoJSON', 'AsGML', 'AsKML', 'AsSVG', 'BoundingCircle',
'Difference', 'ForceRHR', 'GeoHash', 'Intersection', 'MemSize',
'Perimeter', 'PointOnSurface', 'Reverse', 'Scale', 'SnapToGrid',
'SymDifference', 'Transform', 'Translate',
}
if self.connection.mysql_version < (5, 6, 1):
unsupported.update({'Distance', 'Union'})
return unsupported
def geo_db_type(self, f):
return f.geom_type
def get_geom_placeholder(self, f, value, compiler):
"""
The placeholder here has to include MySQL's WKT constructor. Because
MySQL does not support spatial transformations, there is no need to
modify the placeholder based on the contents of the given value.
"""
if hasattr(value, 'as_sql'):
placeholder, _ = compiler.compile(value)
else:
placeholder = '%s(%%s)' % self.from_text
return placeholder
| bsd-3-clause |
aferr/TemporalPartitioningMemCtl | src/arch/x86/X86TLB.py | 18 | 2654 | # 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
from m5.params import *
from m5.proxy import *
from BaseTLB import BaseTLB
from MemObject import MemObject
class X86PagetableWalker(MemObject):
type = 'X86PagetableWalker'
cxx_class = 'X86ISA::Walker'
port = MasterPort("Port for the hardware table walker")
system = Param.System(Parent.any, "system object")
class X86TLB(BaseTLB):
type = 'X86TLB'
cxx_class = 'X86ISA::TLB'
size = Param.Int(64, "TLB size")
walker = Param.X86PagetableWalker(\
X86PagetableWalker(), "page table walker")
| bsd-3-clause |
btallman/incubator-airflow | airflow/contrib/operators/bigquery_to_gcs.py | 20 | 4137 | # -*- coding: utf-8 -*-
#
# 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 logging
from airflow.contrib.hooks.bigquery_hook import BigQueryHook
from airflow.models import BaseOperator
from airflow.utils.decorators import apply_defaults
class BigQueryToCloudStorageOperator(BaseOperator):
"""
Transfers a BigQuery table to a Google Cloud Storage bucket.
"""
template_fields = ('source_project_dataset_table', 'destination_cloud_storage_uris')
template_ext = ('.sql',)
ui_color = '#e4e6f0'
@apply_defaults
def __init__(
self,
source_project_dataset_table,
destination_cloud_storage_uris,
compression='NONE',
export_format='CSV',
field_delimiter=',',
print_header=True,
bigquery_conn_id='bigquery_default',
delegate_to=None,
*args,
**kwargs):
"""
Create a new BigQueryToCloudStorage to move data from BigQuery to
Google Cloud Storage. See here:
https://cloud.google.com/bigquery/docs/reference/v2/jobs
For more details about these parameters.
:param source_project_dataset_table: The dotted
(<project>.|<project>:)<dataset>.<table> BigQuery table to use as the source
data. If <project> is not included, project will be the project defined in
the connection json.
:type source_project_dataset_table: string
:param destination_cloud_storage_uris: The destination Google Cloud
Storage URI (e.g. gs://some-bucket/some-file.txt). Follows
convention defined here:
https://cloud.google.com/bigquery/exporting-data-from-bigquery#exportingmultiple
:type destination_cloud_storage_uris: list
:param compression: Type of compression to use.
:type compression: string
:param export_format: File format to export.
:type field_delimiter: string
:param field_delimiter: The delimiter to use when extracting to a CSV.
:type field_delimiter: string
:param print_header: Whether to print a header for a CSV file extract.
:type print_header: boolean
:param bigquery_conn_id: reference to a specific BigQuery hook.
:type bigquery_conn_id: string
:param delegate_to: The account to impersonate, if any.
For this to work, the service account making the request must have domain-wide
delegation enabled.
:type delegate_to: string
"""
super(BigQueryToCloudStorageOperator, self).__init__(*args, **kwargs)
self.source_project_dataset_table = source_project_dataset_table
self.destination_cloud_storage_uris = destination_cloud_storage_uris
self.compression = compression
self.export_format = export_format
self.field_delimiter = field_delimiter
self.print_header = print_header
self.bigquery_conn_id = bigquery_conn_id
self.delegate_to = delegate_to
def execute(self, context):
logging.info('Executing extract of %s into: %s',
self.source_project_dataset_table,
self.destination_cloud_storage_uris)
hook = BigQueryHook(bigquery_conn_id=self.bigquery_conn_id,
delegate_to=self.delegate_to)
conn = hook.get_conn()
cursor = conn.cursor()
cursor.run_extract(
self.source_project_dataset_table,
self.destination_cloud_storage_uris,
self.compression,
self.export_format,
self.field_delimiter,
self.print_header)
| apache-2.0 |
1013553207/django | tests/utils_tests/test_regex_helper.py | 448 | 1784 | from __future__ import unicode_literals
import unittest
from django.utils import regex_helper
class NormalizeTests(unittest.TestCase):
def test_empty(self):
pattern = r""
expected = [('', [])]
result = regex_helper.normalize(pattern)
self.assertEqual(result, expected)
def test_escape(self):
pattern = r"\\\^\$\.\|\?\*\+\(\)\["
expected = [('\\^$.|?*+()[', [])]
result = regex_helper.normalize(pattern)
self.assertEqual(result, expected)
def test_group_positional(self):
pattern = r"(.*)-(.+)"
expected = [('%(_0)s-%(_1)s', ['_0', '_1'])]
result = regex_helper.normalize(pattern)
self.assertEqual(result, expected)
def test_group_ignored(self):
pattern = r"(?i)(?L)(?m)(?s)(?u)(?#)"
expected = [('', [])]
result = regex_helper.normalize(pattern)
self.assertEqual(result, expected)
def test_group_noncapturing(self):
pattern = r"(?:non-capturing)"
expected = [('non-capturing', [])]
result = regex_helper.normalize(pattern)
self.assertEqual(result, expected)
def test_group_named(self):
pattern = r"(?P<first_group_name>.*)-(?P<second_group_name>.*)"
expected = [('%(first_group_name)s-%(second_group_name)s',
['first_group_name', 'second_group_name'])]
result = regex_helper.normalize(pattern)
self.assertEqual(result, expected)
def test_group_backreference(self):
pattern = r"(?P<first_group_name>.*)-(?P=first_group_name)"
expected = [('%(first_group_name)s-%(first_group_name)s',
['first_group_name'])]
result = regex_helper.normalize(pattern)
self.assertEqual(result, expected)
| bsd-3-clause |
priyankadeswal/network-address-translator | src/mesh/bindings/callbacks_list.py | 138 | 2278 | callback_classes = [
['void', 'ns3::Mac48Address', 'ns3::Mac48Address', 'unsigned int', 'bool', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty'],
['void', 'unsigned int', 'ns3::Mac48Address', 'ns3::Mac48Address', 'ns3::dot11s::PeerLink::PeerState', 'ns3::dot11s::PeerLink::PeerState', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty'],
['void', 'ns3::Ptr<ns3::NetDevice>', 'ns3::Ptr<ns3::Packet const>', 'unsigned short', 'ns3::Address const&', 'ns3::Address const&', 'ns3::NetDevice::PacketType', 'ns3::empty', 'ns3::empty', 'ns3::empty'],
['std::vector<ns3::Mac48Address, std::allocator<ns3::Mac48Address> >', 'unsigned int', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty'],
['void', 'bool', 'ns3::Ptr<ns3::Packet>', 'ns3::Mac48Address', 'ns3::Mac48Address', 'unsigned short', 'unsigned int', 'ns3::empty', 'ns3::empty', 'ns3::empty'],
['unsigned int', 'ns3::Mac48Address', 'ns3::Ptr<ns3::MeshWifiInterfaceMac>', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty'],
['void', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty'],
['void', 'ns3::WifiMacHeader const&', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty'],
['void', 'ns3::Ptr<ns3::Packet>', 'ns3::Mac48Address', 'ns3::Mac48Address', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty'],
['void', 'ns3::Mac48Address', 'unsigned char', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty'],
['void', 'ns3::Mac48Address', 'unsigned char', 'bool', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty'],
['bool', 'ns3::Ptr<ns3::NetDevice>', 'ns3::Ptr<ns3::Packet const>', 'unsigned short', 'ns3::Address const&', 'ns3::Address const&', 'ns3::NetDevice::PacketType', 'ns3::empty', 'ns3::empty', 'ns3::empty'],
['bool', 'ns3::Ptr<ns3::NetDevice>', 'ns3::Ptr<ns3::Packet const>', 'unsigned short', 'ns3::Address const&', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty'],
]
| gpl-2.0 |
y-zeng/grpc | src/python/grpcio/grpc/_credential_composition.py | 16 | 2109 | # Copyright 2016, 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.
from grpc._cython import cygrpc
def _call(call_credentialses):
call_credentials_iterator = iter(call_credentialses)
composition = next(call_credentials_iterator)
for additional_call_credentials in call_credentials_iterator:
composition = cygrpc.call_credentials_composite(
composition, additional_call_credentials)
return composition
def call(call_credentialses):
return _call(call_credentialses)
def channel(channel_credentials, call_credentialses):
return cygrpc.channel_credentials_composite(
channel_credentials, _call(call_credentialses))
| bsd-3-clause |
divio/django | tests/conditional_processing/tests.py | 322 | 9157 | # -*- coding:utf-8 -*-
from __future__ import unicode_literals
from datetime import datetime
from django.test import SimpleTestCase, override_settings
FULL_RESPONSE = 'Test conditional get response'
LAST_MODIFIED = datetime(2007, 10, 21, 23, 21, 47)
LAST_MODIFIED_STR = 'Sun, 21 Oct 2007 23:21:47 GMT'
LAST_MODIFIED_NEWER_STR = 'Mon, 18 Oct 2010 16:56:23 GMT'
LAST_MODIFIED_INVALID_STR = 'Mon, 32 Oct 2010 16:56:23 GMT'
EXPIRED_LAST_MODIFIED_STR = 'Sat, 20 Oct 2007 23:21:47 GMT'
ETAG = 'b4246ffc4f62314ca13147c9d4f76974'
EXPIRED_ETAG = '7fae4cd4b0f81e7d2914700043aa8ed6'
@override_settings(ROOT_URLCONF='conditional_processing.urls')
class ConditionalGet(SimpleTestCase):
def assertFullResponse(self, response, check_last_modified=True, check_etag=True):
self.assertEqual(response.status_code, 200)
self.assertEqual(response.content, FULL_RESPONSE.encode())
if check_last_modified:
self.assertEqual(response['Last-Modified'], LAST_MODIFIED_STR)
if check_etag:
self.assertEqual(response['ETag'], '"%s"' % ETAG)
def assertNotModified(self, response):
self.assertEqual(response.status_code, 304)
self.assertEqual(response.content, b'')
def test_without_conditions(self):
response = self.client.get('/condition/')
self.assertFullResponse(response)
def test_if_modified_since(self):
self.client.defaults['HTTP_IF_MODIFIED_SINCE'] = LAST_MODIFIED_STR
response = self.client.get('/condition/')
self.assertNotModified(response)
self.client.defaults['HTTP_IF_MODIFIED_SINCE'] = LAST_MODIFIED_NEWER_STR
response = self.client.get('/condition/')
self.assertNotModified(response)
self.client.defaults['HTTP_IF_MODIFIED_SINCE'] = LAST_MODIFIED_INVALID_STR
response = self.client.get('/condition/')
self.assertFullResponse(response)
self.client.defaults['HTTP_IF_MODIFIED_SINCE'] = EXPIRED_LAST_MODIFIED_STR
response = self.client.get('/condition/')
self.assertFullResponse(response)
def test_if_unmodified_since(self):
self.client.defaults['HTTP_IF_UNMODIFIED_SINCE'] = LAST_MODIFIED_STR
response = self.client.get('/condition/')
self.assertFullResponse(response)
self.client.defaults['HTTP_IF_UNMODIFIED_SINCE'] = LAST_MODIFIED_NEWER_STR
response = self.client.get('/condition/')
self.assertFullResponse(response)
self.client.defaults['HTTP_IF_UNMODIFIED_SINCE'] = LAST_MODIFIED_INVALID_STR
response = self.client.get('/condition/')
self.assertFullResponse(response)
self.client.defaults['HTTP_IF_UNMODIFIED_SINCE'] = EXPIRED_LAST_MODIFIED_STR
response = self.client.get('/condition/')
self.assertEqual(response.status_code, 412)
def test_if_none_match(self):
self.client.defaults['HTTP_IF_NONE_MATCH'] = '"%s"' % ETAG
response = self.client.get('/condition/')
self.assertNotModified(response)
self.client.defaults['HTTP_IF_NONE_MATCH'] = '"%s"' % EXPIRED_ETAG
response = self.client.get('/condition/')
self.assertFullResponse(response)
# Several etags in If-None-Match is a bit exotic but why not?
self.client.defaults['HTTP_IF_NONE_MATCH'] = '"%s", "%s"' % (ETAG, EXPIRED_ETAG)
response = self.client.get('/condition/')
self.assertNotModified(response)
def test_if_match(self):
self.client.defaults['HTTP_IF_MATCH'] = '"%s"' % ETAG
response = self.client.put('/condition/etag/')
self.assertEqual(response.status_code, 200)
self.client.defaults['HTTP_IF_MATCH'] = '"%s"' % EXPIRED_ETAG
response = self.client.put('/condition/etag/')
self.assertEqual(response.status_code, 412)
def test_both_headers(self):
# see http://www.w3.org/Protocols/rfc2616/rfc2616-sec13.html#sec13.3.4
self.client.defaults['HTTP_IF_MODIFIED_SINCE'] = LAST_MODIFIED_STR
self.client.defaults['HTTP_IF_NONE_MATCH'] = '"%s"' % ETAG
response = self.client.get('/condition/')
self.assertNotModified(response)
self.client.defaults['HTTP_IF_MODIFIED_SINCE'] = EXPIRED_LAST_MODIFIED_STR
self.client.defaults['HTTP_IF_NONE_MATCH'] = '"%s"' % ETAG
response = self.client.get('/condition/')
self.assertFullResponse(response)
self.client.defaults['HTTP_IF_MODIFIED_SINCE'] = LAST_MODIFIED_STR
self.client.defaults['HTTP_IF_NONE_MATCH'] = '"%s"' % EXPIRED_ETAG
response = self.client.get('/condition/')
self.assertFullResponse(response)
self.client.defaults['HTTP_IF_MODIFIED_SINCE'] = EXPIRED_LAST_MODIFIED_STR
self.client.defaults['HTTP_IF_NONE_MATCH'] = '"%s"' % EXPIRED_ETAG
response = self.client.get('/condition/')
self.assertFullResponse(response)
def test_both_headers_2(self):
self.client.defaults['HTTP_IF_UNMODIFIED_SINCE'] = LAST_MODIFIED_STR
self.client.defaults['HTTP_IF_MATCH'] = '"%s"' % ETAG
response = self.client.get('/condition/')
self.assertFullResponse(response)
self.client.defaults['HTTP_IF_UNMODIFIED_SINCE'] = EXPIRED_LAST_MODIFIED_STR
self.client.defaults['HTTP_IF_MATCH'] = '"%s"' % EXPIRED_ETAG
response = self.client.get('/condition/')
self.assertEqual(response.status_code, 412)
self.client.defaults['HTTP_IF_UNMODIFIED_SINCE'] = LAST_MODIFIED_STR
self.client.defaults['HTTP_IF_MATCH'] = '"%s"' % EXPIRED_ETAG
response = self.client.get('/condition/')
self.assertEqual(response.status_code, 412)
self.client.defaults['HTTP_IF_UNMODIFIED_SINCE'] = EXPIRED_LAST_MODIFIED_STR
self.client.defaults['HTTP_IF_MATCH'] = '"%s"' % ETAG
response = self.client.get('/condition/')
self.assertEqual(response.status_code, 412)
def test_single_condition_1(self):
self.client.defaults['HTTP_IF_MODIFIED_SINCE'] = LAST_MODIFIED_STR
response = self.client.get('/condition/last_modified/')
self.assertNotModified(response)
response = self.client.get('/condition/etag/')
self.assertFullResponse(response, check_last_modified=False)
def test_single_condition_2(self):
self.client.defaults['HTTP_IF_NONE_MATCH'] = '"%s"' % ETAG
response = self.client.get('/condition/etag/')
self.assertNotModified(response)
response = self.client.get('/condition/last_modified/')
self.assertFullResponse(response, check_etag=False)
def test_single_condition_3(self):
self.client.defaults['HTTP_IF_MODIFIED_SINCE'] = EXPIRED_LAST_MODIFIED_STR
response = self.client.get('/condition/last_modified/')
self.assertFullResponse(response, check_etag=False)
def test_single_condition_4(self):
self.client.defaults['HTTP_IF_NONE_MATCH'] = '"%s"' % EXPIRED_ETAG
response = self.client.get('/condition/etag/')
self.assertFullResponse(response, check_last_modified=False)
def test_single_condition_5(self):
self.client.defaults['HTTP_IF_MODIFIED_SINCE'] = LAST_MODIFIED_STR
response = self.client.get('/condition/last_modified2/')
self.assertNotModified(response)
response = self.client.get('/condition/etag2/')
self.assertFullResponse(response, check_last_modified=False)
def test_single_condition_6(self):
self.client.defaults['HTTP_IF_NONE_MATCH'] = '"%s"' % ETAG
response = self.client.get('/condition/etag2/')
self.assertNotModified(response)
response = self.client.get('/condition/last_modified2/')
self.assertFullResponse(response, check_etag=False)
def test_single_condition_7(self):
self.client.defaults['HTTP_IF_UNMODIFIED_SINCE'] = EXPIRED_LAST_MODIFIED_STR
response = self.client.get('/condition/last_modified/')
self.assertEqual(response.status_code, 412)
response = self.client.get('/condition/etag/')
self.assertFullResponse(response, check_last_modified=False)
def test_single_condition_8(self):
self.client.defaults['HTTP_IF_UNMODIFIED_SINCE'] = LAST_MODIFIED_STR
response = self.client.get('/condition/last_modified/')
self.assertFullResponse(response, check_etag=False)
def test_single_condition_9(self):
self.client.defaults['HTTP_IF_UNMODIFIED_SINCE'] = EXPIRED_LAST_MODIFIED_STR
response = self.client.get('/condition/last_modified2/')
self.assertEqual(response.status_code, 412)
response = self.client.get('/condition/etag2/')
self.assertFullResponse(response, check_last_modified=False)
def test_single_condition_head(self):
self.client.defaults['HTTP_IF_MODIFIED_SINCE'] = LAST_MODIFIED_STR
response = self.client.head('/condition/')
self.assertNotModified(response)
def test_invalid_etag(self):
self.client.defaults['HTTP_IF_NONE_MATCH'] = r'"\"'
response = self.client.get('/condition/etag/')
self.assertFullResponse(response, check_last_modified=False)
| bsd-3-clause |
briancurtin/python-openstacksdk | openstack/tests/unit/orchestration/v1/test_resource.py | 1 | 2457 | # 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 testtools
from openstack.orchestration.v1 import resource
FAKE_ID = '32e39358-2422-4ad0-a1b5-dd60696bf564'
FAKE_NAME = 'test_stack'
FAKE = {
'links': [{
'href': 'http://res_link',
'rel': 'self'
}, {
'href': 'http://stack_link',
'rel': 'stack'
}],
'logical_resource_id': 'the_resource',
'name': 'the_resource',
'physical_resource_id': '9f38ab5a-37c8-4e40-9702-ce27fc5f6954',
'required_by': [],
'resource_type': 'OS::Heat::FakeResource',
'status': 'CREATE_COMPLETE',
'status_reason': 'state changed',
'updated_time': '2015-03-09T12:15:57.233772',
}
class TestResource(testtools.TestCase):
def test_basic(self):
sot = resource.Resource()
self.assertEqual('resource', sot.resource_key)
self.assertEqual('resources', sot.resources_key)
self.assertEqual('/stacks/%(stack_name)s/%(stack_id)s/resources',
sot.base_path)
self.assertEqual('orchestration', sot.service.service_type)
self.assertFalse(sot.allow_create)
self.assertFalse(sot.allow_retrieve)
self.assertFalse(sot.allow_update)
self.assertFalse(sot.allow_delete)
self.assertTrue(sot.allow_list)
def test_make_it(self):
sot = resource.Resource(**FAKE)
self.assertEqual(FAKE['links'], sot.links)
self.assertEqual(FAKE['logical_resource_id'], sot.logical_resource_id)
self.assertEqual(FAKE['name'], sot.name)
self.assertEqual(FAKE['physical_resource_id'],
sot.physical_resource_id)
self.assertEqual(FAKE['required_by'], sot.required_by)
self.assertEqual(FAKE['resource_type'], sot.resource_type)
self.assertEqual(FAKE['status'], sot.status)
self.assertEqual(FAKE['status_reason'], sot.status_reason)
self.assertEqual(FAKE['updated_time'], sot.updated_at)
| apache-2.0 |
shootsoft/practice | lintcode/NineChapters/03/binary-tree-zigzag-level-order-traversal.py | 2 | 1120 | __author__ = 'yinjun'
"""
Definition of TreeNode:
class TreeNode:
def __init__(self, val):
this.val = val
this.left, this.right = None, None
"""
class Solution:
"""
@param root: The root of binary tree.
@return: A list of list of integer include
the zig zag level order traversal of its nodes' values
"""
def zigzagLevelOrder(self, root):
# write your code here
result = []
if root == None:
return result
queue = []
queue.append(root)
l = 1
b = True
while l >0:
level = []
for i in range(l):
n = queue.pop(0)
l -= 1
if b:
level.append(n.val)
else:
level.insert(0, n.val)
if n.left!=None:
queue.append(n.left)
l+=1
if n.right!=None:
queue.append(n.right)
l+=1
b = not b
result.append(level)
return result | apache-2.0 |
dcroc16/skunk_works | google_appengine/lib/django-0.96/django/contrib/sitemaps/__init__.py | 32 | 3128 | from django.core import urlresolvers
import urllib
PING_URL = "http://www.google.com/webmasters/sitemaps/ping"
class SitemapNotFound(Exception):
pass
def ping_google(sitemap_url=None, ping_url=PING_URL):
"""
Alerts Google that the sitemap for the current site has been updated.
If sitemap_url is provided, it should be an absolute path to the sitemap
for this site -- e.g., '/sitemap.xml'. If sitemap_url is not provided, this
function will attempt to deduce it by using urlresolvers.reverse().
"""
if sitemap_url is None:
try:
# First, try to get the "index" sitemap URL.
sitemap_url = urlresolvers.reverse('django.contrib.sitemaps.views.index')
except urlresolvers.NoReverseMatch:
try:
# Next, try for the "global" sitemap URL.
sitemap_url = urlresolvers.reverse('django.contrib.sitemaps.views.sitemap')
except urlresolvers.NoReverseMatch:
pass
if sitemap_url is None:
raise SitemapNotFound("You didn't provide a sitemap_url, and the sitemap URL couldn't be auto-detected.")
from django.contrib.sites.models import Site
current_site = Site.objects.get_current()
url = "%s%s" % (current_site.domain, sitemap_url)
params = urllib.urlencode({'sitemap':url})
urllib.urlopen("%s?%s" % (ping_url, params))
class Sitemap:
def __get(self, name, obj, default=None):
try:
attr = getattr(self, name)
except AttributeError:
return default
if callable(attr):
return attr(obj)
return attr
def items(self):
return []
def location(self, obj):
return obj.get_absolute_url()
def get_urls(self):
from django.contrib.sites.models import Site
current_site = Site.objects.get_current()
urls = []
for item in self.items():
loc = "http://%s%s" % (current_site.domain, self.__get('location', item))
url_info = {
'location': loc,
'lastmod': self.__get('lastmod', item, None),
'changefreq': self.__get('changefreq', item, None),
'priority': self.__get('priority', item, None)
}
urls.append(url_info)
return urls
class FlatPageSitemap(Sitemap):
def items(self):
from django.contrib.sites.models import Site
current_site = Site.objects.get_current()
return current_site.flatpage_set.all()
class GenericSitemap(Sitemap):
priority = None
changefreq = None
def __init__(self, info_dict, priority=None, changefreq=None):
self.queryset = info_dict['queryset']
self.date_field = info_dict.get('date_field', None)
self.priority = priority
self.changefreq = changefreq
def items(self):
# Make sure to return a clone; we don't want premature evaluation.
return self.queryset.filter()
def lastmod(self, item):
if self.date_field is not None:
return getattr(item, self.date_field)
return None
| mit |
zubie7a/Algorithms | HackerRank/Algorithms/02_Implementation/17_Append_And_Delete.py | 3 | 1191 | # https://www.hackerrank.com/challenges/append-and-delete
s, t, k = raw_input(), raw_input(), int(raw_input())
i = 0
# Advance an iterator until the last point both strings
# have sequential characters in common from the start.
while i < len(s) and i < len(t) and s[i] == t[i]:
i += 1
# spareS/T are the amount of characters from the point
# where the common sequence stops for both strings.
spareS, spareT = len(s) - i, len(t) - i
# A way to match S and T, is to delete the spares from
# S and insert the spares from T.
needed = spareS + spareT
# To match this way, the needed amount has to be less or
# equal than k, and if there's a remaining amount, it
# has to be even so it can be done away with repeated
# deletions and insertions of the last character.
withSpares = (needed <= k and (k - needed) % 2 == 0)
# A match can also be made by completely erasing one
# string, this may be particularly useful to consume a
# large k until making it even or odd as needed because
# deletions on empty space keep giving empty space. Then
# with the remaining k recreate the other string.
withEmpty = k - len(s) >= len(t)
if withSpares or withEmpty:
print "Yes"
else:
print "No"
| mit |
hjhsalo/analysispreservation.cern.ch | cap/modules/cache/ext.py | 9 | 1553 | # -*- coding: utf-8 -*-
#
# This file is part of CERN Analysis Preservation Framework.
# Copyright (C) 2016 CERN.
#
# CERN Analysis Preservation Framework 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.
#
# CERN Analysis Preservation Framework 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 CERN Analysis Preservation Framework; if not, write to the
# Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,
# MA 02111-1307, USA.
#
# In applying this license, CERN does not
# waive the privileges and immunities granted to it by virtue of its status
# as an Intergovernmental Organization or submit itself to any jurisdiction.
#
"""Cache for CAP."""
from __future__ import absolute_import, print_function
from flask_cache import Cache
class CAPCache(object):
"""CAP cache extension."""
def __init__(self, app=None):
"""Extension initialization."""
if app:
self.init_app(app)
def init_app(self, app):
"""Flask application initialization."""
self.cache = Cache(app)
self.app = app
app.extensions['cap-cache'] = self
| gpl-2.0 |
kostaspl/SpiderMonkey38 | python/requests/requests/packages/chardet/hebrewprober.py | 2929 | 13359 | ######################## BEGIN LICENSE BLOCK ########################
# The Original Code is Mozilla Universal charset detector code.
#
# The Initial Developer of the Original Code is
# Shy Shalom
# Portions created by the Initial Developer are Copyright (C) 2005
# the Initial Developer. All Rights Reserved.
#
# Contributor(s):
# Mark Pilgrim - port to Python
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
# 02110-1301 USA
######################### END LICENSE BLOCK #########################
from .charsetprober import CharSetProber
from .constants import eNotMe, eDetecting
from .compat import wrap_ord
# This prober doesn't actually recognize a language or a charset.
# It is a helper prober for the use of the Hebrew model probers
### General ideas of the Hebrew charset recognition ###
#
# Four main charsets exist in Hebrew:
# "ISO-8859-8" - Visual Hebrew
# "windows-1255" - Logical Hebrew
# "ISO-8859-8-I" - Logical Hebrew
# "x-mac-hebrew" - ?? Logical Hebrew ??
#
# Both "ISO" charsets use a completely identical set of code points, whereas
# "windows-1255" and "x-mac-hebrew" are two different proper supersets of
# these code points. windows-1255 defines additional characters in the range
# 0x80-0x9F as some misc punctuation marks as well as some Hebrew-specific
# diacritics and additional 'Yiddish' ligature letters in the range 0xc0-0xd6.
# x-mac-hebrew defines similar additional code points but with a different
# mapping.
#
# As far as an average Hebrew text with no diacritics is concerned, all four
# charsets are identical with respect to code points. Meaning that for the
# main Hebrew alphabet, all four map the same values to all 27 Hebrew letters
# (including final letters).
#
# The dominant difference between these charsets is their directionality.
# "Visual" directionality means that the text is ordered as if the renderer is
# not aware of a BIDI rendering algorithm. The renderer sees the text and
# draws it from left to right. The text itself when ordered naturally is read
# backwards. A buffer of Visual Hebrew generally looks like so:
# "[last word of first line spelled backwards] [whole line ordered backwards
# and spelled backwards] [first word of first line spelled backwards]
# [end of line] [last word of second line] ... etc' "
# adding punctuation marks, numbers and English text to visual text is
# naturally also "visual" and from left to right.
#
# "Logical" directionality means the text is ordered "naturally" according to
# the order it is read. It is the responsibility of the renderer to display
# the text from right to left. A BIDI algorithm is used to place general
# punctuation marks, numbers and English text in the text.
#
# Texts in x-mac-hebrew are almost impossible to find on the Internet. From
# what little evidence I could find, it seems that its general directionality
# is Logical.
#
# To sum up all of the above, the Hebrew probing mechanism knows about two
# charsets:
# Visual Hebrew - "ISO-8859-8" - backwards text - Words and sentences are
# backwards while line order is natural. For charset recognition purposes
# the line order is unimportant (In fact, for this implementation, even
# word order is unimportant).
# Logical Hebrew - "windows-1255" - normal, naturally ordered text.
#
# "ISO-8859-8-I" is a subset of windows-1255 and doesn't need to be
# specifically identified.
# "x-mac-hebrew" is also identified as windows-1255. A text in x-mac-hebrew
# that contain special punctuation marks or diacritics is displayed with
# some unconverted characters showing as question marks. This problem might
# be corrected using another model prober for x-mac-hebrew. Due to the fact
# that x-mac-hebrew texts are so rare, writing another model prober isn't
# worth the effort and performance hit.
#
#### The Prober ####
#
# The prober is divided between two SBCharSetProbers and a HebrewProber,
# all of which are managed, created, fed data, inquired and deleted by the
# SBCSGroupProber. The two SBCharSetProbers identify that the text is in
# fact some kind of Hebrew, Logical or Visual. The final decision about which
# one is it is made by the HebrewProber by combining final-letter scores
# with the scores of the two SBCharSetProbers to produce a final answer.
#
# The SBCSGroupProber is responsible for stripping the original text of HTML
# tags, English characters, numbers, low-ASCII punctuation characters, spaces
# and new lines. It reduces any sequence of such characters to a single space.
# The buffer fed to each prober in the SBCS group prober is pure text in
# high-ASCII.
# The two SBCharSetProbers (model probers) share the same language model:
# Win1255Model.
# The first SBCharSetProber uses the model normally as any other
# SBCharSetProber does, to recognize windows-1255, upon which this model was
# built. The second SBCharSetProber is told to make the pair-of-letter
# lookup in the language model backwards. This in practice exactly simulates
# a visual Hebrew model using the windows-1255 logical Hebrew model.
#
# The HebrewProber is not using any language model. All it does is look for
# final-letter evidence suggesting the text is either logical Hebrew or visual
# Hebrew. Disjointed from the model probers, the results of the HebrewProber
# alone are meaningless. HebrewProber always returns 0.00 as confidence
# since it never identifies a charset by itself. Instead, the pointer to the
# HebrewProber is passed to the model probers as a helper "Name Prober".
# When the Group prober receives a positive identification from any prober,
# it asks for the name of the charset identified. If the prober queried is a
# Hebrew model prober, the model prober forwards the call to the
# HebrewProber to make the final decision. In the HebrewProber, the
# decision is made according to the final-letters scores maintained and Both
# model probers scores. The answer is returned in the form of the name of the
# charset identified, either "windows-1255" or "ISO-8859-8".
# windows-1255 / ISO-8859-8 code points of interest
FINAL_KAF = 0xea
NORMAL_KAF = 0xeb
FINAL_MEM = 0xed
NORMAL_MEM = 0xee
FINAL_NUN = 0xef
NORMAL_NUN = 0xf0
FINAL_PE = 0xf3
NORMAL_PE = 0xf4
FINAL_TSADI = 0xf5
NORMAL_TSADI = 0xf6
# Minimum Visual vs Logical final letter score difference.
# If the difference is below this, don't rely solely on the final letter score
# distance.
MIN_FINAL_CHAR_DISTANCE = 5
# Minimum Visual vs Logical model score difference.
# If the difference is below this, don't rely at all on the model score
# distance.
MIN_MODEL_DISTANCE = 0.01
VISUAL_HEBREW_NAME = "ISO-8859-8"
LOGICAL_HEBREW_NAME = "windows-1255"
class HebrewProber(CharSetProber):
def __init__(self):
CharSetProber.__init__(self)
self._mLogicalProber = None
self._mVisualProber = None
self.reset()
def reset(self):
self._mFinalCharLogicalScore = 0
self._mFinalCharVisualScore = 0
# The two last characters seen in the previous buffer,
# mPrev and mBeforePrev are initialized to space in order to simulate
# a word delimiter at the beginning of the data
self._mPrev = ' '
self._mBeforePrev = ' '
# These probers are owned by the group prober.
def set_model_probers(self, logicalProber, visualProber):
self._mLogicalProber = logicalProber
self._mVisualProber = visualProber
def is_final(self, c):
return wrap_ord(c) in [FINAL_KAF, FINAL_MEM, FINAL_NUN, FINAL_PE,
FINAL_TSADI]
def is_non_final(self, c):
# The normal Tsadi is not a good Non-Final letter due to words like
# 'lechotet' (to chat) containing an apostrophe after the tsadi. This
# apostrophe is converted to a space in FilterWithoutEnglishLetters
# causing the Non-Final tsadi to appear at an end of a word even
# though this is not the case in the original text.
# The letters Pe and Kaf rarely display a related behavior of not being
# a good Non-Final letter. Words like 'Pop', 'Winamp' and 'Mubarak'
# for example legally end with a Non-Final Pe or Kaf. However, the
# benefit of these letters as Non-Final letters outweighs the damage
# since these words are quite rare.
return wrap_ord(c) in [NORMAL_KAF, NORMAL_MEM, NORMAL_NUN, NORMAL_PE]
def feed(self, aBuf):
# Final letter analysis for logical-visual decision.
# Look for evidence that the received buffer is either logical Hebrew
# or visual Hebrew.
# The following cases are checked:
# 1) A word longer than 1 letter, ending with a final letter. This is
# an indication that the text is laid out "naturally" since the
# final letter really appears at the end. +1 for logical score.
# 2) A word longer than 1 letter, ending with a Non-Final letter. In
# normal Hebrew, words ending with Kaf, Mem, Nun, Pe or Tsadi,
# should not end with the Non-Final form of that letter. Exceptions
# to this rule are mentioned above in isNonFinal(). This is an
# indication that the text is laid out backwards. +1 for visual
# score
# 3) A word longer than 1 letter, starting with a final letter. Final
# letters should not appear at the beginning of a word. This is an
# indication that the text is laid out backwards. +1 for visual
# score.
#
# The visual score and logical score are accumulated throughout the
# text and are finally checked against each other in GetCharSetName().
# No checking for final letters in the middle of words is done since
# that case is not an indication for either Logical or Visual text.
#
# We automatically filter out all 7-bit characters (replace them with
# spaces) so the word boundary detection works properly. [MAP]
if self.get_state() == eNotMe:
# Both model probers say it's not them. No reason to continue.
return eNotMe
aBuf = self.filter_high_bit_only(aBuf)
for cur in aBuf:
if cur == ' ':
# We stand on a space - a word just ended
if self._mBeforePrev != ' ':
# next-to-last char was not a space so self._mPrev is not a
# 1 letter word
if self.is_final(self._mPrev):
# case (1) [-2:not space][-1:final letter][cur:space]
self._mFinalCharLogicalScore += 1
elif self.is_non_final(self._mPrev):
# case (2) [-2:not space][-1:Non-Final letter][
# cur:space]
self._mFinalCharVisualScore += 1
else:
# Not standing on a space
if ((self._mBeforePrev == ' ') and
(self.is_final(self._mPrev)) and (cur != ' ')):
# case (3) [-2:space][-1:final letter][cur:not space]
self._mFinalCharVisualScore += 1
self._mBeforePrev = self._mPrev
self._mPrev = cur
# Forever detecting, till the end or until both model probers return
# eNotMe (handled above)
return eDetecting
def get_charset_name(self):
# Make the decision: is it Logical or Visual?
# If the final letter score distance is dominant enough, rely on it.
finalsub = self._mFinalCharLogicalScore - self._mFinalCharVisualScore
if finalsub >= MIN_FINAL_CHAR_DISTANCE:
return LOGICAL_HEBREW_NAME
if finalsub <= -MIN_FINAL_CHAR_DISTANCE:
return VISUAL_HEBREW_NAME
# It's not dominant enough, try to rely on the model scores instead.
modelsub = (self._mLogicalProber.get_confidence()
- self._mVisualProber.get_confidence())
if modelsub > MIN_MODEL_DISTANCE:
return LOGICAL_HEBREW_NAME
if modelsub < -MIN_MODEL_DISTANCE:
return VISUAL_HEBREW_NAME
# Still no good, back to final letter distance, maybe it'll save the
# day.
if finalsub < 0.0:
return VISUAL_HEBREW_NAME
# (finalsub > 0 - Logical) or (don't know what to do) default to
# Logical.
return LOGICAL_HEBREW_NAME
def get_state(self):
# Remain active as long as any of the model probers are active.
if (self._mLogicalProber.get_state() == eNotMe) and \
(self._mVisualProber.get_state() == eNotMe):
return eNotMe
return eDetecting
| mpl-2.0 |
uskudnik/ggrc-core | src/ggrc/converters/base.py | 2 | 10693 | # Copyright (C) 2013 Google Inc., authors, and contributors <see AUTHORS file>
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
# Created By: dan@reciprocitylabs.com
# Maintained By: dan@reciprocitylabs.com
import csv
from .common import *
from ggrc import db
from ggrc.fulltext import get_indexer
from ggrc.fulltext.recordbuilder import fts_record_for
from ggrc.services.common import log_event
from flask import redirect, flash
from ggrc.services.common import get_modified_objects, update_index
from ggrc.services.common import update_memcache_before_commit, update_memcache_after_commit
from ggrc.utils import benchmark
from ggrc.models import CustomAttributeDefinition
CACHE_EXPIRY_IMPORT=600
class BaseConverter(object):
def __init__(self, rows_or_objects, **options):
self.options = options.copy()
if self.options.get('export'):
self.objects = rows_or_objects
self.rows = []
else:
self.objects = []
self.rows = rows_or_objects[:]
self.all_objects = {}
self.errors = []
self.warnings = []
self.slugs = []
self.final_results = []
self.import_exception = None
self.import_slug = None
self.total_imported = 0
self.objects_created = 0
self.objects_updated = 0
self.custom_attribute_definitions = {}
self.create_metadata_map()
self.create_object_map()
def create_metadata_map(self):
self.metadata_map = self._metadata_map
def create_object_map(self):
# Moving object_map to an instance attribute rather than a class attribute
# because when CustomAttribute definitions change on a type, exports/imports
# that occur after the change and before a server restart will have an object_map
# that will include the attributes defined before the change merged with the new
# attributes. To avoid this we scope the object map to the instance and not to
# the class.
self.object_map = self._object_map
definitions = db.session.query(CustomAttributeDefinition).\
filter(CustomAttributeDefinition.definition_type==self.row_converter.model_class.__name__).all()
for definition in definitions:
# Remember the definition title for use when exporting
self.object_map[definition.title] = definition.title
# Remember the definition for use when importing.
self.custom_attribute_definitions[definition.title] = definition
def results(self):
return self.objects
def add_slug_to_slugs(self, slug):
self.slugs.append(slug)
def get_slugs(self):
return self.slugs
def find_object(self, model_class, key):
all_model_objs = self.all_objects.get(model_class.__class__.__name__)
return all_model_objs.get(key) if all_model_objs else None
def add_object(self, model_class, key, newObject):
self.all_objects[model_class.__name__] = self.all_objects.setdefault(model_class.__name__, dict())
self.all_objects[model_class.__name__][key] = newObject
def created_objects(self):
return [result for result in self.objects if result.obj.id is None]
def updated_objects(self):
pass
def changed_objects(self):
pass
def has_errors(self):
return bool(self.errors) or self.has_object_errors()
def has_object_errors(self):
return any([obj.has_errors() for obj in self.objects])
def has_warnings(self):
return bool(self.warnings) or self.has_object_warnings()
def has_object_warnings(self):
return any([obj.has_warnings() for obj in self.objects])
@classmethod
def from_rows(cls, rows, **options):
return cls(rows, **options)
def import_metadata(self):
if len(self.rows) < 6:
self.errors.append(u"There is no data to import in this CSV file")
raise ImportException("", show_preview=True, converter=self)
optional_metadata = []
if hasattr(self, 'optional_metadata'):
optional_metadata = self.optional_metadata
headers = self.read_headers(self.metadata_map, self.rows.pop(0),
optional_headers=optional_metadata)
values = self.read_values(headers, self.rows.pop(0))
self.import_slug = values.get('slug')
self.rows.pop(0)
self.rows.pop(0)
self.validate_metadata(values)
def read_values(self, headers, row):
attrs = dict(zip(headers, row))
attrs.pop(None, None) # None key could have been inserted in extreme edge case
return attrs
def get_header_for_column(self, header_map, column_name):
for header in header_map:
if header_map[header] == column_name:
return header
return ''
def get_header_for_object_column(self, column_name):
return self.get_header_for_column(self.object_map, column_name)
def get_header_for_metadata_column(self, column_name):
return self.get_header_for_column(self.metadata_map, column_name)
def read_headers(
self, import_map, row, required_headers=[], optional_headers=[]):
ignored_colums = []
self.trim_list(row)
keys = []
for heading in row:
heading = heading.strip()
if heading == "<skip>":
continue
elif not (heading in import_map):
ignored_colums.append(heading)
keys.append(None) # Placeholder None to prevent position problems when headers are zipped with values
continue
elif heading != "start_date" and heading != "end_date": #
keys.append(import_map[heading])
if any(ignored_colums):
ignored_text = ", ".join(ignored_colums)
self.warnings.append("Ignored column{plural}: {ignored_text}".format(
plural='s' if len(ignored_colums) > 1 else '', ignored_text=ignored_text))
missing_columns = import_map.values()
[missing_columns.remove(element) for element in keys if element]
optional_headers.extend(['created_at', 'updated_at'])
missing_columns = [column for column in missing_columns if not (column in optional_headers)]
for header in required_headers:
if header in missing_columns:
self.errors.append(u"Missing required column: {}".format(self.get_header_for_column(import_map, header)))
missing_columns.remove(header)
if any(missing_columns):
missing_headers = [ self.get_header_for_column(import_map, temp) for temp in missing_columns if temp ]
missing_text = ", ".join([missing_header for missing_header in missing_headers if missing_header ])
self.warnings.append(u"Missing column{plural}: {missing}".format(
plural='s' if len(missing_columns) > 1 else '', missing = missing_text))
return keys
def trim_list(self, a):
while len(a) > 0 and self.is_blank(a[-1]):
a.pop()
def is_blank(self, string):
return not len(string) or string.isspace()
def is_blank_row(self, row_attrs):
return all(self.is_blank(value) for key, value in row_attrs.iteritems())
def do_import(self, dry_run = True, **options):
self.import_metadata()
object_headers = self.read_headers(self.object_map, self.rows.pop(0), required_headers=['title'])
row_attrs = self.read_objects(object_headers, self.rows)
for index, row_attrs in enumerate(row_attrs):
if self.is_blank_row(row_attrs):
continue # ignore blank lines entirely
row = self.row_converter(self, row_attrs, index, **options)
row.setup()
row.reify()
row.reify_custom_attributes()
self.objects.append(row)
self.set_import_stats()
if not dry_run:
if self.has_errors():
raise ImportException(u"Attempted import with errors")
self.save_import()
return self
def save_import(self):
for row_converter in self.objects:
row_converter.save(db.session, **self.options)
db.session.flush()
for row_converter in self.objects:
row_converter.run_after_save_hooks(db.session, **self.options)
modified_objects = get_modified_objects(db.session)
log_event(db.session)
with benchmark("Update memcache before commit for import"):
update_memcache_before_commit(self, modified_objects, CACHE_EXPIRY_IMPORT)
db.session.commit()
with benchmark("Update memcache after commit for import"):
update_memcache_after_commit(self)
update_index(db.session, modified_objects)
def set_import_stats(self):
self.total_imported = len(self.objects)
new_objects = self.created_objects()
self.objects_created = len(new_objects)
self.objects_updated = self.total_imported - self.objects_created
def read_objects(self, headers, rows):
attrs_collection = []
for row in rows:
if not len(row):
continue
attrs_collection.append(self.read_values(headers, row))
return attrs_collection
def validate_metadata(self, attrs):
if self.options.get('directive'):
self.validate_metadata_type(
attrs, self.directive().__class__.__name__)
self.validate_code(attrs)
elif self.__class__.__name__ == 'SystemsConverter':
model_name = "Processes" if self.options.get('is_biz_process') else "Systems"
self.validate_metadata_type(attrs, model_name)
elif self.__class__.__name__ == "PeopleConverter":
self.validate_metadata_type(attrs, "People")
def validate_code(self, attrs):
if not attrs.get('slug'):
self.errors.append(u'Missing "{}" Code heading'.format(self.directive().kind))
elif attrs['slug'] != self.directive().slug:
self.errors.append(u'{} Code must be {}'.format(self.directive().kind, self.directive().slug))
def validate_metadata_type(self, attrs, required_type):
if attrs.get('type') is None:
self.errors.append(u'Missing "Type" heading')
elif attrs['type'] != required_type:
self.errors.append(u'Type must be "{}"'.format(required_type))
def do_export(self, csv_writer):
for i,obj in enumerate(self.objects):
row = self.row_converter(self, obj, i, export = True)
row.setup()
row.reify()
row.reify_custom_attributes()
if row and any(row.attrs.values()):
self.rows.append(row.attrs)
row_header_map = self.object_map
for row in self.rows:
csv_row = []
for key in row_header_map.keys():
field = row_header_map[key]
field_val = row.get(field, '')
# Ensure non-basestrings are rendered on export
if not isinstance(field_val, basestring):
if field_val is None:
field_val = ''
else:
field_val = str(field_val)
csv_row.append(field_val)
csv_writer.writerow([ele.encode("utf-8") if ele else ''.encode("utf-8") for ele in csv_row])
def metadata_map(self):
return self.metadata_map
def object_map(self):
return self.object_map
def row_converter(self):
return self.row_converter
| apache-2.0 |
KousikaGanesh/purchaseandInventory | openerp/addons/l10n_us/__init__.py | 893 | 1045 | # -*- 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/>.
#
##############################################################################
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
| agpl-3.0 |
dlamotte/krankshaft | tests/krankshaft/test_serializer.py | 1 | 8087 | from __future__ import absolute_import
from datetime import date, datetime, time, timedelta
from decimal import Decimal
from django.core.handlers.wsgi import WSGIRequest
from django.test.client import FakePayload
from krankshaft.serializer import Serializer
from tests.base import TestCaseNoDB
from urlparse import urlparse
import pytz
class SerializerConvertTest(TestCaseNoDB):
dt = datetime(2013, 6, 8, 14, 34, 28, 121251)
dt_expect = '2013-06-08T14:34:28.121251'
td = timedelta(1, 2, 3)
tz = pytz.timezone('America/Chicago')
def do(self, obj, expect):
self.assertEquals(expect, self.serializer.convert(obj))
def setUp(self):
self.serializer = Serializer()
def test_date(self):
self.do(self.dt.date(), self.value(self.dt_expect.split('T')[0]))
def test_datetime(self):
self.do(self.dt, self.value(self.dt_expect))
def test_datetime_with_timezone(self):
self.do(
self.tz.normalize(self.tz.localize(self.dt)),
self.value(self.dt_expect + '-05:00')
)
def test_decimal(self):
self.do(Decimal('1.7921579150'), self.value('1.7921579150'))
def test_dict(self):
self.do(
{'key': self.dt},
{'key': self.dt_expect}
)
def test_list(self):
self.do(
[self.dt],
[self.dt_expect]
)
def test_primitive(self):
for value in self.serializer.primitive_values + (1, 1L, 1.1, 'a', u'a'):
self.assertEquals(value, self.serializer.convert(value))
def test_serializer_default_content_type(self):
serializer = Serializer(
default_content_type='application/json'
)
content, content_type = serializer.serialize({'key': 'value'})
self.assertEquals(content, '{"key": "value"}')
self.assertEquals(content_type, 'application/json')
def test_time(self):
self.do(self.dt.time(), self.value(self.dt_expect.split('T')[1]))
def test_timedelta(self):
self.do(self.td, self.value(86402.000003))
def test_tuple(self):
self.do(
(self.dt,),
[self.dt_expect]
)
def test_unserializable(self):
self.assertRaises(TypeError, self.serializer.convert, object())
def value(self, val):
return val
class SerializerJSONTest(SerializerConvertTest):
def do(self, obj, expect):
self.assertEquals(expect, self.serializer.to_json(obj))
def setUp(self):
self.serializer = Serializer()
def test_dict(self):
self.do(
{'key': self.dt},
'{"key": "%s"}' % self.dt_expect
)
def test_list(self):
self.do(
[self.dt],
'["%s"]' % self.dt_expect
)
def test_tuple(self):
self.do(
(self.dt,),
'["%s"]' % self.dt_expect
)
def test_unserializable(self):
self.assertRaises(TypeError, self.serializer.to_json, object())
def value(self, val):
if isinstance(val, basestring):
return '"%s"' % val
else:
return str(val)
class SerializerSerializeTest(TestCaseNoDB):
def setUp(self):
self.dt = SerializerConvertTest.dt
self.dt_expect = SerializerConvertTest.dt_expect
self.serializer = Serializer()
self.data = {'key': self.dt}
def test_application_json(self):
content, content_type = \
self.serializer.serialize(self.data, 'application/json')
self.assertEquals(content_type, 'application/json')
self.assertEquals(
content,
'{"key": "%s"}' % self.dt_expect
)
def test_application_json_indent(self):
content, content_type = \
self.serializer.serialize(self.data, 'application/json; indent=4')
self.assertEquals(content_type, 'application/json')
self.assertEquals(
content,
'{\n "key": "%s"\n}' % self.dt_expect
)
def test_application_json_indent_invalid(self):
content, content_type = \
self.serializer.serialize(self.data, 'application/json; indent=a')
self.assertEquals(content_type, 'application/json')
self.assertEquals(
content,
'{"key": "%s"}' % self.dt_expect
)
def test_application_json_q(self):
content, content_type = \
self.serializer.serialize(self.data, 'application/json; q=0.5')
self.assertEquals(content_type, 'application/json')
self.assertEquals(
content,
'{"key": "%s"}' % self.dt_expect
)
def test_default(self):
content, content_type = \
self.serializer.serialize(self.data)
self.assertEquals(content_type, self.serializer.default_content_type)
self.assertEquals(
content,
'{"key": "%s"}' % self.dt_expect
)
def test_unsupported(self):
self.assertRaises(
self.serializer.Unsupported,
self.serializer.get_format,
'unsupported/content-type'
)
class SerializerDeserializeTest(TestCaseNoDB):
def setUp(self):
self.data = {'key': 'value'}
self.serializer = Serializer()
def test_application_json(self):
self.assertEquals(
self.data,
self.serializer.deserialize('{"key": "value"}', 'application/json')
)
def test_application_json_indent(self):
self.assertEquals(
self.data,
self.serializer \
.deserialize('{"key": "value"}', 'application/json; indent=4')
)
def test_invalid_data(self):
for content_type in self.serializer.content_types.keys():
if content_type.startswith('multipart/'):
continue
self.assertRaises(
ValueError,
self.serializer.deserialize,
'invalid body data',
content_type
)
def test_invalid_multipart_boundary(self):
data = 'data'
boundary = '\xffinvalid boundary'
parsed = urlparse('/path/')
environ = self.client._base_environ(**{
'CONTENT_TYPE': 'multipart/form-data; boundary=%s' % boundary,
'CONTENT_LENGTH': len(data),
'PATH_INFO': self.client._get_path(parsed),
'QUERY_STRING': parsed[4],
'REQUEST_METHOD': 'POST',
'wsgi.input': FakePayload(data),
})
request = WSGIRequest(environ)
for content_type in self.serializer.content_types.keys():
if not content_type.startswith('multipart/'):
continue
self.assertRaises(
ValueError,
self.serializer.deserialize_request,
request,
request.META['CONTENT_TYPE']
)
def test_invalid_multipart_content_length(self):
data = 'data'
boundary = 'boundary'
parsed = urlparse('/path/')
environ = self.client._base_environ(**{
'CONTENT_TYPE': 'multipart/form-data; boundary=%s' % boundary,
'CONTENT_LENGTH': -1,
'PATH_INFO': self.client._get_path(parsed),
'QUERY_STRING': parsed[4],
'REQUEST_METHOD': 'POST',
'wsgi.input': FakePayload(data),
})
request = WSGIRequest(environ)
for content_type in self.serializer.content_types.keys():
if not content_type.startswith('multipart/'):
continue
self.assertRaises(
ValueError,
self.serializer.deserialize_request,
request,
request.META['CONTENT_TYPE']
)
class SerializerFormatTest(TestCaseNoDB):
def setUp(self):
self.serializer = Serializer()
def test_get_content_type_json(self):
self.assertEquals(
self.serializer.get_content_type('json'),
'application/json'
)
| mit |
GoSteven/Diary | django/contrib/localflavor/br/forms.py | 12 | 5966 | # -*- coding: utf-8 -*-
"""
BR-specific Form helpers
"""
from django.core.validators import EMPTY_VALUES
from django.forms import ValidationError
from django.forms.fields import Field, RegexField, CharField, Select
from django.utils.encoding import smart_unicode
from django.utils.translation import ugettext_lazy as _
import re
phone_digits_re = re.compile(r'^(\d{2})[-\.]?(\d{4})[-\.]?(\d{4})$')
class BRZipCodeField(RegexField):
default_error_messages = {
'invalid': _('Enter a zip code in the format XXXXX-XXX.'),
}
def __init__(self, *args, **kwargs):
super(BRZipCodeField, self).__init__(r'^\d{5}-\d{3}$',
max_length=None, min_length=None, *args, **kwargs)
class BRPhoneNumberField(Field):
default_error_messages = {
'invalid': _('Phone numbers must be in XX-XXXX-XXXX format.'),
}
def clean(self, value):
super(BRPhoneNumberField, self).clean(value)
if value in EMPTY_VALUES:
return u''
value = re.sub('(\(|\)|\s+)', '', smart_unicode(value))
m = phone_digits_re.search(value)
if m:
return u'%s-%s-%s' % (m.group(1), m.group(2), m.group(3))
raise ValidationError(self.error_messages['invalid'])
class BRStateSelect(Select):
"""
A Select widget that uses a list of Brazilian states/territories
as its choices.
"""
def __init__(self, attrs=None):
from br_states import STATE_CHOICES
super(BRStateSelect, self).__init__(attrs, choices=STATE_CHOICES)
class BRStateChoiceField(Field):
"""
A choice field that uses a list of Brazilian states as its choices.
"""
widget = Select
default_error_messages = {
'invalid': _(u'Select a valid brazilian state. That state is not one of the available states.'),
}
def __init__(self, required=True, widget=None, label=None,
initial=None, help_text=None):
super(BRStateChoiceField, self).__init__(required, widget, label,
initial, help_text)
from br_states import STATE_CHOICES
self.widget.choices = STATE_CHOICES
def clean(self, value):
value = super(BRStateChoiceField, self).clean(value)
if value in EMPTY_VALUES:
value = u''
value = smart_unicode(value)
if value == u'':
return value
valid_values = set([smart_unicode(k) for k, v in self.widget.choices])
if value not in valid_values:
raise ValidationError(self.error_messages['invalid'])
return value
def DV_maker(v):
if v >= 2:
return 11 - v
return 0
class BRCPFField(CharField):
"""
This field validate a CPF number or a CPF string. A CPF number is
compounded by XXX.XXX.XXX-VD. The two last digits are check digits.
More information:
http://en.wikipedia.org/wiki/Cadastro_de_Pessoas_F%C3%ADsicas
"""
default_error_messages = {
'invalid': _("Invalid CPF number."),
'max_digits': _("This field requires at most 11 digits or 14 characters."),
'digits_only': _("This field requires only numbers."),
}
def __init__(self, *args, **kwargs):
super(BRCPFField, self).__init__(max_length=14, min_length=11, *args, **kwargs)
def clean(self, value):
"""
Value can be either a string in the format XXX.XXX.XXX-XX or an
11-digit number.
"""
value = super(BRCPFField, self).clean(value)
if value in EMPTY_VALUES:
return u''
orig_value = value[:]
if not value.isdigit():
value = re.sub("[-\.]", "", value)
try:
int(value)
except ValueError:
raise ValidationError(self.error_messages['digits_only'])
if len(value) != 11:
raise ValidationError(self.error_messages['max_digits'])
orig_dv = value[-2:]
new_1dv = sum([i * int(value[idx]) for idx, i in enumerate(range(10, 1, -1))])
new_1dv = DV_maker(new_1dv % 11)
value = value[:-2] + str(new_1dv) + value[-1]
new_2dv = sum([i * int(value[idx]) for idx, i in enumerate(range(11, 1, -1))])
new_2dv = DV_maker(new_2dv % 11)
value = value[:-1] + str(new_2dv)
if value[-2:] != orig_dv:
raise ValidationError(self.error_messages['invalid'])
return orig_value
class BRCNPJField(Field):
default_error_messages = {
'invalid': _("Invalid CNPJ number."),
'digits_only': _("This field requires only numbers."),
'max_digits': _("This field requires at least 14 digits"),
}
def clean(self, value):
"""
Value can be either a string in the format XX.XXX.XXX/XXXX-XX or a
group of 14 characters.
"""
value = super(BRCNPJField, self).clean(value)
if value in EMPTY_VALUES:
return u''
orig_value = value[:]
if not value.isdigit():
value = re.sub("[-/\.]", "", value)
try:
int(value)
except ValueError:
raise ValidationError(self.error_messages['digits_only'])
if len(value) != 14:
raise ValidationError(self.error_messages['max_digits'])
orig_dv = value[-2:]
new_1dv = sum([i * int(value[idx]) for idx, i in enumerate(range(5, 1, -1) + range(9, 1, -1))])
new_1dv = DV_maker(new_1dv % 11)
value = value[:-2] + str(new_1dv) + value[-1]
new_2dv = sum([i * int(value[idx]) for idx, i in enumerate(range(6, 1, -1) + range(9, 1, -1))])
new_2dv = DV_maker(new_2dv % 11)
value = value[:-1] + str(new_2dv)
if value[-2:] != orig_dv:
raise ValidationError(self.error_messages['invalid'])
return orig_value
| bsd-3-clause |
bankonme/OpenBazaar-Server | networkcli.py | 2 | 26455 | __author__ = 'chris'
import sys
import argparse
import json
import time
from twisted.internet import reactor
from txjsonrpc.netstring.jsonrpc import Proxy
from binascii import hexlify, unhexlify
from dht.utils import digest
from txjsonrpc.netstring import jsonrpc
from market.profile import Profile
from protos import objects, countries
from db.datastore import HashMap
from keyutils.keys import KeyChain
from market.contracts import Contract
from collections import OrderedDict
from interfaces import MessageListener
from zope.interface import implements
from dht.node import Node
def do_continue(value):
pass
def print_value(value):
print json.dumps(value, indent=4)
reactor.stop()
def print_error(error):
print 'error', error
reactor.stop()
class Parser(object):
def __init__(self, proxy_obj):
parser = argparse.ArgumentParser(
description='OpenBazaar Network CLI',
usage='''
python networkcli.py command [<arguments>]
commands:
follow follow a user
unfollow unfollow a user
getinfo returns an object containing various state info
getpeers returns the id of all the peers in the routing table
get fetches the given keyword from the dht
set sets the given keyword/key in the dht
delete deletes the keyword/key from the dht
getnode returns a node's ip address given its guid.
getcontract fetchs a contract from a node given its hash and guid
getcontractmetadata fetches the metadata (including thumbnail image) for the contract
getimage fetches an image from a node given its hash and guid
getprofile fetches the profile from the given node.
getmoderators fetches a list of moderators
getusermetadata fetches the metadata (shortened profile) for the node
getlistings fetches metadata about the store's listings
getfollowers fetches a list of followers of a node
getfollowing fetches a list of users a node is following
getmessages fetches messages from the dht
sendnotification sends a notification to all your followers
setcontract sets a contract in the filesystem and db
setimage maps an image hash to a filepath in the db
setasmoderator sets a node as a moderator
setprofile sets the given profile data in the database
shutdown closes all outstanding connections.
''')
parser.add_argument('command', help='Execute the given command')
args = parser.parse_args(sys.argv[1:2])
if not hasattr(self, args.command):
parser.print_help()
exit(1)
getattr(self, args.command)()
self.proxy = proxy_obj
@staticmethod
def get():
parser = argparse.ArgumentParser(
description="Fetch the given keyword from the dht and return all the entries",
usage='''usage:
networkcli.py get [-kw KEYWORD]''')
parser.add_argument('-kw', '--keyword', required=True, help="the keyword to fetch")
args = parser.parse_args(sys.argv[2:])
keyword = args.keyword
d = proxy.callRemote('get', keyword)
d.addCallbacks(print_value, print_error)
reactor.run()
@staticmethod
def set():
parser = argparse.ArgumentParser(
description='Set the given keyword/key pair in the dht. The value will be your '
'serialized node information.',
usage='''usage:
networkcli.py set [-kw KEYWORD] [-k KEY]''')
parser.add_argument('-kw', '--keyword', required=True, help="the keyword to set in the dht")
parser.add_argument('-k', '--key', required=True, help="the key to set at the keyword")
args = parser.parse_args(sys.argv[2:])
keyword = args.keyword
key = args.key
d = proxy.callRemote('set', keyword, key)
d.addCallbacks(print_value, print_error)
reactor.run()
@staticmethod
def delete():
parser = argparse.ArgumentParser(
description="Deletes the given keyword/key from the dht. Signature will be automatically generated.",
usage='''usage:
networkcli.py delete [-kw KEYWORD] [-k KEY]''')
parser.add_argument('-kw', '--keyword', required=True, help="where to find the key")
parser.add_argument('-k', '--key', required=True, help="the key to delete")
args = parser.parse_args(sys.argv[2:])
keyword = args.keyword
key = args.key
d = proxy.callRemote('delete', keyword, key)
d.addCallbacks(print_value, print_error)
reactor.run()
@staticmethod
def getinfo():
parser = argparse.ArgumentParser(
description="Returns an object containing various state info",
usage='''usage:
networkcli getinfo''')
parser.parse_args(sys.argv[2:])
d = proxy.callRemote('getinfo')
d.addCallbacks(print_value, print_error)
reactor.run()
@staticmethod
def shutdown():
parser = argparse.ArgumentParser(
description="Terminates all outstanding connections.",
usage='''usage:
networkcli shutdown''')
parser.parse_args(sys.argv[2:])
d = proxy.callRemote('shutdown')
d.addCallbacks(print_value, print_error)
reactor.run()
@staticmethod
def getpubkey():
parser = argparse.ArgumentParser(
description="Returns this node's public key.",
usage='''usage:
networkcli getpubkey''')
parser.parse_args(sys.argv[2:])
d = proxy.callRemote('getpubkey')
d.addCallbacks(print_value, print_error)
reactor.run()
@staticmethod
def getcontract():
parser = argparse.ArgumentParser(
description="Fetch a contract given its hash and guid.",
usage='''usage:
networkcli.py getcontract [-c HASH] [-g GUID]''')
parser.add_argument('-c', '--hash', required=True, help="the hash of the contract")
parser.add_argument('-g', '--guid', required=True, help="the guid to query")
args = parser.parse_args(sys.argv[2:])
hash_value = args.hash
guid = args.guid
d = proxy.callRemote('getcontract', hash_value, guid)
d.addCallbacks(print_value, print_error)
reactor.run()
@staticmethod
def getimage():
parser = argparse.ArgumentParser(
description="Fetch an image given its hash and guid.",
usage='''usage:
networkcli.py getcontract [-i HASH] [-g GUID]''')
parser.add_argument('-i', '--hash', required=True, help="the hash of the image")
parser.add_argument('-g', '--guid', required=True, help="the guid to query")
args = parser.parse_args(sys.argv[2:])
hash_value = args.hash
guid = args.guid
d = proxy.callRemote('getimage', hash_value, guid)
d.addCallbacks(print_value, print_error)
reactor.run()
@staticmethod
def getpeers():
parser = argparse.ArgumentParser(
description="Returns id of all peers in the routing table",
usage='''usage:
networkcli getpeers''')
parser.parse_args(sys.argv[2:])
d = proxy.callRemote('getpeers')
d.addCallbacks(print_value, print_error)
reactor.run()
@staticmethod
def getnode():
parser = argparse.ArgumentParser(
description="Fetch the ip address for a node given its guid.",
usage='''usage:
networkcli.py getnode [-g GUID]''')
parser.add_argument('-g', '--guid', required=True, help="the guid to find")
args = parser.parse_args(sys.argv[2:])
guid = args.guid
d = proxy.callRemote('getnode', guid)
d.addCallbacks(print_value, print_error)
reactor.run()
@staticmethod
def setprofile():
parser = argparse.ArgumentParser(
description="Sets a profile in the database.",
usage='''usage:
networkcli.py setprofile [options]''')
parser.add_argument('-n', '--name', help="the name of the user/store")
parser.add_argument('-o', '--onename', help="the onename id")
parser.add_argument('-a', '--avatar', help="the file path to the avatar image")
parser.add_argument('-hd', '--header', help="the file path to the header image")
parser.add_argument('-c', '--country',
help="a string consisting of country from protos.countries.CountryCode")
# we could add all the fields here but this is good enough to test.
args = parser.parse_args(sys.argv[2:])
p = Profile()
u = objects.Profile()
h = HashMap()
if args.name is not None:
u.name = args.name
if args.country is not None:
u.location = countries.CountryCode.Value(args.country.upper())
if args.onename is not None:
u.handle = args.onename
if args.avatar is not None:
with open(args.avatar, "r") as filename:
image = filename.read()
hash_value = digest(image)
u.avatar_hash = hash_value
h.insert(hash_value, args.avatar)
if args.header is not None:
with open(args.header, "r") as filename:
image = filename.read()
hash_value = digest(image)
u.header_hash = hash_value
h.insert(hash_value, args.header)
u.encryption_key = KeyChain().encryption_pubkey
p.update(u)
@staticmethod
def getprofile():
parser = argparse.ArgumentParser(
description="Fetch the profile from the given node. Images will be saved in cache.",
usage='''usage:
networkcli.py getprofile [-g GUID]''')
parser.add_argument('-g', '--guid', required=True, help="the guid to query")
args = parser.parse_args(sys.argv[2:])
guid = args.guid
d = proxy.callRemote('getprofile', guid)
d.addCallbacks(print_value, print_error)
reactor.run()
@staticmethod
def getusermetadata():
parser = argparse.ArgumentParser(
description="Fetches the metadata (small profile) from"
"a given node. The images will be saved in cache.",
usage='''usage:
networkcli.py getusermetadata [-g GUID]''')
parser.add_argument('-g', '--guid', required=True, help="the guid to query")
args = parser.parse_args(sys.argv[2:])
guid = args.guid
d = proxy.callRemote('getusermetadata', guid)
d.addCallbacks(print_value, print_error)
reactor.run()
@staticmethod
def setcontract():
parser = argparse.ArgumentParser(
description="Sets a new contract in the database and filesystem.",
usage='''usage:
networkcli.py setcontract [-f FILEPATH]''')
parser.add_argument('-f', '--filepath', help="a path to a completed json contract")
args = parser.parse_args(sys.argv[2:])
with open(args.filepath) as data_file:
contract = json.load(data_file, object_pairs_hook=OrderedDict)
Contract(contract).save()
@staticmethod
def setimage():
parser = argparse.ArgumentParser(
description="Maps a image hash to a file path in the database",
usage='''usage:
networkcli.py setimage [-f FILEPATH]''')
parser.add_argument('-f', '--filepath', help="a path to the image")
args = parser.parse_args(sys.argv[2:])
with open(args.filepath, "r") as f:
image = f.read()
d = digest(image)
h = HashMap()
h.insert(d, args.filepath)
print h.get_file(d)
@staticmethod
def getlistings():
parser = argparse.ArgumentParser(
description="Fetches metadata about the store's listings",
usage='''usage:
networkcli.py getmetadata [-g GUID]''')
parser.add_argument('-g', '--guid', required=True, help="the guid to query")
args = parser.parse_args(sys.argv[2:])
guid = args.guid
d = proxy.callRemote('getlistings', guid)
d.addCallbacks(print_value, print_error)
reactor.run()
@staticmethod
def getcontractmetadata():
parser = argparse.ArgumentParser(
description="Fetches the metadata for the given contract. The thumbnail images will be saved in cache.",
usage='''usage:
networkcli.py getcontractmetadata [-g GUID] [-c CONTRACT]''')
parser.add_argument('-g', '--guid', required=True, help="the guid to query")
parser.add_argument('-c', '--contract', required=True, help="the contract hash")
args = parser.parse_args(sys.argv[2:])
guid = args.guid
contract = args.contract
d = proxy.callRemote('getcontractmetadata', guid, contract)
d.addCallbacks(print_value, print_error)
reactor.run()
@staticmethod
def setasmoderator():
parser = argparse.ArgumentParser(
description="Sets the given node as a moderator.",
usage='''usage:
networkcli.py setasmoderator''')
parser.parse_args(sys.argv[2:])
d = proxy.callRemote('setasmoderator')
d.addCallbacks(print_value, print_error)
reactor.run()
@staticmethod
def getmoderators():
parser = argparse.ArgumentParser(
description="Fetches a list of moderators",
usage='''usage:
networkcli.py getmoderators ''')
parser.parse_args(sys.argv[2:])
d = proxy.callRemote('getmoderators')
d.addCallbacks(print_value, print_error)
reactor.run()
@staticmethod
def follow():
parser = argparse.ArgumentParser(
description="Follow a user",
usage='''usage:
networkcli.py follow [-g GUID]''')
parser.add_argument('-g', '--guid', required=True, help="the guid to follow")
args = parser.parse_args(sys.argv[2:])
guid = args.guid
d = proxy.callRemote('follow', guid)
d.addCallbacks(print_value, print_error)
reactor.run()
@staticmethod
def unfollow():
parser = argparse.ArgumentParser(
description="Unfollow a user",
usage='''usage:
networkcli.py unfollow [-g GUID]''')
parser.add_argument('-g', '--guid', required=True, help="the guid to unfollow")
args = parser.parse_args(sys.argv[2:])
guid = args.guid
d = proxy.callRemote('unfollow', guid)
d.addCallbacks(print_value, print_error)
reactor.run()
@staticmethod
def getfollowers():
parser = argparse.ArgumentParser(
description="Get a list of followers of a node",
usage='''usage:
networkcli.py getfollowers [-g GUID]''')
parser.add_argument('-g', '--guid', required=True, help="the guid to query")
args = parser.parse_args(sys.argv[2:])
guid = args.guid
d = proxy.callRemote('getfollowers', guid)
d.addCallbacks(print_value, print_error)
reactor.run()
@staticmethod
def getfollowing():
parser = argparse.ArgumentParser(
description="Get a list users a node is following",
usage='''usage:
networkcli.py getfollowing [-g GUID]''')
parser.add_argument('-g', '--guid', required=True, help="the guid to query")
args = parser.parse_args(sys.argv[2:])
guid = args.guid
d = proxy.callRemote('getfollowing', guid)
d.addCallbacks(print_value, print_error)
reactor.run()
@staticmethod
def sendnotification():
parser = argparse.ArgumentParser(
description="Send a notification to all your followers",
usage='''usage:
networkcli.py sendnotification [-m MESSAGE]''')
parser.add_argument('-m', '--message', required=True, help="the message to send")
args = parser.parse_args(sys.argv[2:])
message = args.message
d = proxy.callRemote('sendnotification', message)
d.addCallbacks(print_value, print_error)
reactor.run()
@staticmethod
def sendmessage():
parser = argparse.ArgumentParser(
description="Send a message to another node",
usage='''usage:
networkcli.py sendmessage [-g GUID] [-p PUBKEY] [-m MESSAGE] [-o]''')
parser.add_argument('-g', '--guid', required=True, help="the guid to send to")
parser.add_argument('-p', '--pubkey', required=True, help="the encryption key of the node")
parser.add_argument('-m', '--message', required=True, help="the message to send")
parser.add_argument('-o', '--offline', action='store_true', help="sends to offline recipient")
args = parser.parse_args(sys.argv[2:])
message = args.message
guid = args.guid
pubkey = args.pubkey
offline = args.offline
d = proxy.callRemote('sendmessage', guid, pubkey, message, offline)
d.addCallbacks(print_value, print_error)
reactor.run()
@staticmethod
def getmessages():
parser = argparse.ArgumentParser(
description="Get messages from the dht",
usage='''usage:
networkcli.py getmessages''')
parser.parse_args(sys.argv[2:])
d = proxy.callRemote('getmessages')
d.addCallbacks(print_value, print_error)
reactor.run()
# RPC-Server
class RPCCalls(jsonrpc.JSONRPC):
def __init__(self, kserver, mserver, keys):
jsonrpc.JSONRPC.__init__(self)
self.kserver = kserver
self.mserver = mserver
self.keys = keys
def jsonrpc_getpubkey(self):
return hexlify(self.keys.guid_signed_pubkey)
def jsonrpc_getinfo(self):
info = {"version": "0.1"}
num_peers = 0
for bucket in self.kserver.protocol.router.buckets:
num_peers += bucket.__len__()
info["known peers"] = num_peers
info["stored messages"] = len(self.kserver.storage.data)
size = sys.getsizeof(self.kserver.storage.data)
size += sum(map(sys.getsizeof, self.kserver.storage.data.itervalues())) + sum(
map(sys.getsizeof, self.kserver.storage.data.iterkeys()))
info["db size"] = size
return info
def jsonrpc_set(self, keyword, key):
def handle_result(result):
print "JSONRPC result:", result
d = self.kserver.set(str(keyword), digest(key), self.kserver.node.getProto().SerializeToString())
d.addCallback(handle_result)
return "Sending store request..."
def jsonrpc_get(self, keyword):
def handle_result(result):
print "JSONRPC result:", result
for mod in result:
try:
val = objects.Value()
val.ParseFromString(mod)
node = objects.Node()
node.ParseFromString(val.serializedData)
print node
except Exception as e:
print 'malformed protobuf', e.message
d = self.kserver.get(keyword)
d.addCallback(handle_result)
return "Sent get request. Check log output for result"
def jsonrpc_delete(self, keyword, key):
def handle_result(result):
print "JSONRPC result:", result
signature = self.keys.signing_key.sign(digest(key))
d = self.kserver.delete(str(keyword), digest(key), signature[:64])
d.addCallback(handle_result)
return "Sending delete request..."
def jsonrpc_shutdown(self):
for addr in self.kserver.protocol:
connection = self.kserver.protocol._active_connections.get(addr)
if connection is not None:
connection.shutdown()
return "Closing all connections."
def jsonrpc_getpeers(self):
peers = []
for bucket in self.kserver.protocol.router.buckets:
for node in bucket.getNodes():
peers.append(node.id.encode("hex"))
return peers
def jsonrpc_getnode(self, guid):
def print_node(node):
print node.ip, node.port
d = self.kserver.resolve(unhexlify(guid))
d.addCallback(print_node)
return "finding node..."
def jsonrpc_getcontract(self, contract_hash, guid):
def get_node(node):
def print_resp(resp):
print resp
if node is not None:
d = self.mserver.get_contract(node, unhexlify(contract_hash))
d.addCallback(print_resp)
d = self.kserver.resolve(unhexlify(guid))
d.addCallback(get_node)
return "getting contract..."
def jsonrpc_getimage(self, image_hash, guid):
def get_node(node):
def print_resp(resp):
print resp
if node is not None:
d = self.mserver.get_image(node, unhexlify(image_hash))
d.addCallback(print_resp)
d = self.kserver.resolve(unhexlify(guid))
d.addCallback(get_node)
return "getting image..."
def jsonrpc_getprofile(self, guid):
start = time.time()
def get_node(node):
def print_resp(resp):
print time.time() - start
print resp
print hexlify(resp.encryption_key)
if node is not None:
d = self.mserver.get_profile(node)
d.addCallback(print_resp)
d = self.kserver.resolve(unhexlify(guid))
d.addCallback(get_node)
return "getting profile..."
def jsonrpc_getusermetadata(self, guid):
start = time.time()
def get_node(node):
def print_resp(resp):
print time.time() - start
print resp
if node is not None:
d = self.mserver.get_user_metadata(node)
d.addCallback(print_resp)
d = self.kserver.resolve(unhexlify(guid))
d.addCallback(get_node)
return "getting user metadata..."
def jsonrpc_getlistings(self, guid):
start = time.time()
def get_node(node):
def print_resp(resp):
print time.time() - start
if resp:
for l in resp.listing:
resp.listing.remove(l)
h = l.contract_hash
l.contract_hash = hexlify(h)
resp.listing.extend([l])
print resp
if node is not None:
d = self.mserver.get_listings(node)
d.addCallback(print_resp)
d = self.kserver.resolve(unhexlify(guid))
d.addCallback(get_node)
return "getting listing metadata..."
def jsonrpc_getcontractmetadata(self, guid, contract_hash):
start = time.time()
def get_node(node):
def print_resp(resp):
print time.time() - start
print resp
if node is not None:
d = self.mserver.get_contract_metadata(node, unhexlify(contract_hash))
d.addCallback(print_resp)
d = self.kserver.resolve(unhexlify(guid))
d.addCallback(get_node)
return "getting contract metadata..."
def jsonrpc_setasmoderator(self):
self.mserver.make_moderator()
def jsonrpc_getmoderators(self):
def print_mods(mods):
print mods
self.mserver.get_moderators().addCallback(print_mods)
return "finding moderators in dht..."
def jsonrpc_follow(self, guid):
def get_node(node):
if node is not None:
def print_resp(resp):
print resp
d = self.mserver.follow(node)
d.addCallback(print_resp)
d = self.kserver.resolve(unhexlify(guid))
d.addCallback(get_node)
return "following node..."
def jsonrpc_unfollow(self, guid):
def get_node(node):
if node is not None:
def print_resp(resp):
print resp
d = self.mserver.unfollow(node)
d.addCallback(print_resp)
d = self.kserver.resolve(unhexlify(guid))
d.addCallback(get_node)
return "unfollowing node..."
def jsonrpc_getfollowers(self, guid):
def get_node(node):
if node is not None:
def print_resp(resp):
print resp
d = self.mserver.get_followers(node)
d.addCallback(print_resp)
d = self.kserver.resolve(unhexlify(guid))
d.addCallback(get_node)
return "getting followers..."
def jsonrpc_getfollowing(self, guid):
def get_node(node):
if node is not None:
def print_resp(resp):
print resp
d = self.mserver.get_following(node)
d.addCallback(print_resp)
d = self.kserver.resolve(unhexlify(guid))
d.addCallback(get_node)
return "getting following..."
def jsonrpc_sendnotification(self, message):
def get_count(count):
print "Notification reached %i follower(s)" % count
d = self.mserver.send_notification(message)
d.addCallback(get_count)
return "sendng notification..."
def jsonrpc_sendmessage(self, guid, pubkey, message, offline=False):
def get_node(node):
if node is not None or offline is True:
if offline is True:
node = Node(unhexlify(guid), "127.0.0.1", 1234, digest("adsf"))
self.mserver.send_message(node, pubkey, objects.Plaintext_Message.CHAT, message)
d = self.kserver.resolve(unhexlify(guid))
d.addCallback(get_node)
return "sending message..."
def jsonrpc_getmessages(self):
class GetMyMessages(object):
implements(MessageListener)
@staticmethod
def notify(sender_guid, encryption_pubkey, subject, message_type, message):
print message
self.mserer.get_messages(GetMyMessages())
return "getting messages..."
if __name__ == "__main__":
proxy = Proxy('127.0.0.1', 18465)
Parser(proxy)
| mit |
appliedx/python-saml | src/onelogin/saml2/utils.py | 1 | 33926 | # -*- coding: utf-8 -*-
""" OneLogin_Saml2_Utils class
Copyright (c) 2014, OneLogin, Inc.
All rights reserved.
Auxiliary class of OneLogin's Python Toolkit.
"""
import base64
from datetime import datetime
import calendar
from hashlib import sha1, sha256, sha384, sha512
from isodate import parse_duration as duration_parser
from lxml import etree
from defusedxml.lxml import tostring, fromstring
from os.path import basename, dirname, join
import re
from sys import stderr
from tempfile import NamedTemporaryFile
from textwrap import wrap
from urllib import quote_plus
from uuid import uuid4
from xml.dom.minidom import Document, Element
from defusedxml.minidom import parseString
import zlib
import dm.xmlsec.binding as xmlsec
from dm.xmlsec.binding.tmpl import EncData, Signature
from onelogin.saml2.constants import OneLogin_Saml2_Constants
from onelogin.saml2.errors import OneLogin_Saml2_Error
def print_xmlsec_errors(filename, line, func, error_object, error_subject, reason, msg):
"""
Auxiliary method. It override the default xmlsec debug message.
"""
info = []
if error_object != "unknown":
info.append("obj=" + error_object)
if error_subject != "unknown":
info.append("subject=" + error_subject)
if msg.strip():
info.append("msg=" + msg)
if reason != 1:
info.append("errno=%d" % reason)
if info:
print "%s:%d(%s)" % (filename, line, func), " ".join(info)
class OneLogin_Saml2_Utils(object):
"""
Auxiliary class that contains several utility methods to parse time,
urls, add sign, encrypt, decrypt, sign validation, handle xml ...
"""
@staticmethod
def decode_base64_and_inflate(value):
"""
base64 decodes and then inflates according to RFC1951
:param value: a deflated and encoded string
:type value: string
:returns: the string after decoding and inflating
:rtype: string
"""
return zlib.decompress(base64.b64decode(value), -15)
@staticmethod
def deflate_and_base64_encode(value):
"""
Deflates and the base64 encodes a string
:param value: The string to deflate and encode
:type value: string
:returns: The deflated and encoded string
:rtype: string
"""
return base64.b64encode(zlib.compress(value)[2:-4])
@staticmethod
def validate_xml(xml, schema, debug=False):
"""
Validates a xml against a schema
:param xml: The xml that will be validated
:type: string|DomDocument
:param schema: The schema
:type: string
:param debug: If debug is active, the parse-errors will be showed
:type: bool
:returns: Error code or the DomDocument of the xml
:rtype: string
"""
assert isinstance(xml, basestring) or isinstance(xml, Document) or isinstance(xml, etree._Element)
assert isinstance(schema, basestring)
if isinstance(xml, Document):
xml = xml.toxml()
elif isinstance(xml, etree._Element):
xml = tostring(xml)
# Switch to lxml for schema validation
try:
dom = fromstring(str(xml))
except Exception:
return 'unloaded_xml'
schema_file = join(dirname(__file__), 'schemas', schema)
f_schema = open(schema_file, 'r')
schema_doc = etree.parse(f_schema)
f_schema.close()
xmlschema = etree.XMLSchema(schema_doc)
if not xmlschema.validate(dom):
if debug:
stderr.write('Errors validating the metadata')
stderr.write(':\n\n')
for error in xmlschema.error_log:
stderr.write('%s\n' % error.message)
return 'invalid_xml'
return parseString(etree.tostring(dom))
@staticmethod
def format_cert(cert, heads=True):
"""
Returns a x509 cert (adding header & footer if required).
:param cert: A x509 unformated cert
:type: string
:param heads: True if we want to include head and footer
:type: boolean
:returns: Formated cert
:rtype: string
"""
x509_cert = cert.replace('\x0D', '')
x509_cert = x509_cert.replace('\r', '')
x509_cert = x509_cert.replace('\n', '')
if len(x509_cert) > 0:
x509_cert = x509_cert.replace('-----BEGIN CERTIFICATE-----', '')
x509_cert = x509_cert.replace('-----END CERTIFICATE-----', '')
x509_cert = x509_cert.replace(' ', '')
if heads:
x509_cert = "-----BEGIN CERTIFICATE-----\n" + "\n".join(wrap(x509_cert, 64)) + "\n-----END CERTIFICATE-----\n"
return x509_cert
@staticmethod
def format_private_key(key, heads=True):
"""
Returns a private key (adding header & footer if required).
:param key A private key
:type: string
:param heads: True if we want to include head and footer
:type: boolean
:returns: Formated private key
:rtype: string
"""
private_key = key.replace('\x0D', '')
private_key = private_key.replace('\r', '')
private_key = private_key.replace('\n', '')
if len(private_key) > 0:
if private_key.find('-----BEGIN PRIVATE KEY-----') != -1:
private_key = private_key.replace('-----BEGIN PRIVATE KEY-----', '')
private_key = private_key.replace('-----END PRIVATE KEY-----', '')
private_key = private_key.replace(' ', '')
if heads:
private_key = "-----BEGIN PRIVATE KEY-----\n" + "\n".join(wrap(private_key, 64)) + "\n-----END PRIVATE KEY-----\n"
else:
private_key = private_key.replace('-----BEGIN RSA PRIVATE KEY-----', '')
private_key = private_key.replace('-----END RSA PRIVATE KEY-----', '')
private_key = private_key.replace(' ', '')
if heads:
private_key = "-----BEGIN RSA PRIVATE KEY-----\n" + "\n".join(wrap(private_key, 64)) + "\n-----END RSA PRIVATE KEY-----\n"
return private_key
@staticmethod
def redirect(url, parameters={}, request_data={}):
"""
Executes a redirection to the provided url (or return the target url).
:param url: The target url
:type: string
:param parameters: Extra parameters to be passed as part of the url
:type: dict
:param request_data: The request as a dict
:type: dict
:returns: Url
:rtype: string
"""
assert isinstance(url, basestring)
assert isinstance(parameters, dict)
if url.startswith('/'):
url = '%s%s' % (OneLogin_Saml2_Utils.get_self_url_host(request_data), url)
# Verify that the URL is to a http or https site.
if re.search('^https?://', url) is None:
raise OneLogin_Saml2_Error(
'Redirect to invalid URL: ' + url,
OneLogin_Saml2_Error.REDIRECT_INVALID_URL
)
# Add encoded parameters
if url.find('?') < 0:
param_prefix = '?'
else:
param_prefix = '&'
for name, value in parameters.items():
if value is None:
param = quote_plus(name)
elif isinstance(value, list):
param = ''
for val in value:
param += quote_plus(name) + '[]=' + quote_plus(val) + '&'
if len(param) > 0:
param = param[0:-1]
else:
param = quote_plus(name) + '=' + quote_plus(value)
if param:
url += param_prefix + param
param_prefix = '&'
return url
@staticmethod
def get_self_url_host(request_data):
"""
Returns the protocol + the current host + the port (if different than
common ports).
:param request_data: The request as a dict
:type: dict
:return: Url
:rtype: string
"""
current_host = OneLogin_Saml2_Utils.get_self_host(request_data)
port = ''
if OneLogin_Saml2_Utils.is_https(request_data):
protocol = 'https'
else:
protocol = 'http'
if 'server_port' in request_data:
port_number = str(request_data['server_port'])
port = ':' + port_number
if protocol == 'http' and port_number == '80':
port = ''
elif protocol == 'https' and port_number == '443':
port = ''
return '%s://%s%s' % (protocol, current_host, port)
@staticmethod
def get_self_host(request_data):
"""
Returns the current host.
:param request_data: The request as a dict
:type: dict
:return: The current host
:rtype: string
"""
if 'http_host' in request_data:
current_host = request_data['http_host']
elif 'server_name' in request_data:
current_host = request_data['server_name']
else:
raise Exception('No hostname defined')
if ':' in current_host:
current_host_data = current_host.split(':')
possible_port = current_host_data[-1]
try:
possible_port = float(possible_port)
current_host = current_host_data[0]
except ValueError:
current_host = ':'.join(current_host_data)
return current_host
@staticmethod
def is_https(request_data):
"""
Checks if https or http.
:param request_data: The request as a dict
:type: dict
:return: False if https is not active
:rtype: boolean
"""
is_https = 'https' in request_data and request_data['https'] != 'off'
is_https = is_https or ('server_port' in request_data and str(request_data['server_port']) == '443')
return is_https
@staticmethod
def get_self_url_no_query(request_data):
"""
Returns the URL of the current host + current view.
:param request_data: The request as a dict
:type: dict
:return: The url of current host + current view
:rtype: string
"""
self_url_host = OneLogin_Saml2_Utils.get_self_url_host(request_data)
script_name = request_data['script_name']
if script_name:
if script_name[0] != '/':
script_name = '/' + script_name
else:
script_name = ''
self_url_no_query = self_url_host + script_name
if 'path_info' in request_data:
self_url_no_query += request_data['path_info']
return self_url_no_query
@staticmethod
def get_self_routed_url_no_query(request_data):
"""
Returns the routed URL of the current host + current view.
:param request_data: The request as a dict
:type: dict
:return: The url of current host + current view
:rtype: string
"""
self_url_host = OneLogin_Saml2_Utils.get_self_url_host(request_data)
route = ''
if 'request_uri' in request_data.keys() and request_data['request_uri']:
route = request_data['request_uri']
if 'query_string' in request_data.keys() and request_data['query_string']:
route = route.replace(request_data['query_string'], '')
return self_url_host + route
@staticmethod
def get_self_url(request_data):
"""
Returns the URL of the current host + current view + query.
:param request_data: The request as a dict
:type: dict
:return: The url of current host + current view + query
:rtype: string
"""
self_url_host = OneLogin_Saml2_Utils.get_self_url_host(request_data)
request_uri = ''
if 'request_uri' in request_data:
request_uri = request_data['request_uri']
if not request_uri.startswith('/'):
match = re.search('^https?://[^/]*(/.*)', request_uri)
if match is not None:
request_uri = match.groups()[0]
return self_url_host + request_uri
@staticmethod
def generate_unique_id():
"""
Generates an unique string (used for example as ID for assertions).
:return: A unique string
:rtype: string
"""
return 'ONELOGIN_%s' % sha1(uuid4().hex).hexdigest()
@staticmethod
def parse_time_to_SAML(time):
"""
Converts a UNIX timestamp to SAML2 timestamp on the form
yyyy-mm-ddThh:mm:ss(\.s+)?Z.
:param time: The time we should convert (DateTime).
:type: string
:return: SAML2 timestamp.
:rtype: string
"""
data = datetime.utcfromtimestamp(float(time))
return data.strftime('%Y-%m-%dT%H:%M:%SZ')
@staticmethod
def parse_SAML_to_time(timestr):
"""
Converts a SAML2 timestamp on the form yyyy-mm-ddThh:mm:ss(\.s+)?Z
to a UNIX timestamp. The sub-second part is ignored.
:param time: The time we should convert (SAML Timestamp).
:type: string
:return: Converted to a unix timestamp.
:rtype: int
"""
try:
data = datetime.strptime(timestr, '%Y-%m-%dT%H:%M:%SZ')
except ValueError:
data = datetime.strptime(timestr, '%Y-%m-%dT%H:%M:%S.%fZ')
return calendar.timegm(data.utctimetuple())
@staticmethod
def now():
"""
:return: unix timestamp of actual time.
:rtype: int
"""
return calendar.timegm(datetime.utcnow().utctimetuple())
@staticmethod
def parse_duration(duration, timestamp=None):
"""
Interprets a ISO8601 duration value relative to a given timestamp.
:param duration: The duration, as a string.
:type: string
:param timestamp: The unix timestamp we should apply the duration to.
Optional, default to the current time.
:type: string
:return: The new timestamp, after the duration is applied.
:rtype: int
"""
assert isinstance(duration, basestring)
assert timestamp is None or isinstance(timestamp, int)
timedelta = duration_parser(duration)
if timestamp is None:
data = datetime.utcnow() + timedelta
else:
data = datetime.utcfromtimestamp(timestamp) + timedelta
return calendar.timegm(data.utctimetuple())
@staticmethod
def get_expire_time(cache_duration=None, valid_until=None):
"""
Compares 2 dates and returns the earliest.
:param cache_duration: The duration, as a string.
:type: string
:param valid_until: The valid until date, as a string or as a timestamp
:type: string
:return: The expiration time.
:rtype: int
"""
expire_time = None
if cache_duration is not None:
expire_time = OneLogin_Saml2_Utils.parse_duration(cache_duration)
if valid_until is not None:
if isinstance(valid_until, int):
valid_until_time = valid_until
else:
valid_until_time = OneLogin_Saml2_Utils.parse_SAML_to_time(valid_until)
if expire_time is None or expire_time > valid_until_time:
expire_time = valid_until_time
if expire_time is not None:
return '%d' % expire_time
return None
@staticmethod
def query(dom, query, context=None):
"""
Extracts nodes that match the query from the Element
:param dom: The root of the lxml objet
:type: Element
:param query: Xpath Expresion
:type: string
:param context: Context Node
:type: DOMElement
:returns: The queried nodes
:rtype: list
"""
if context is None:
return dom.xpath(query, namespaces=OneLogin_Saml2_Constants.NSMAP)
else:
return context.xpath(query, namespaces=OneLogin_Saml2_Constants.NSMAP)
@staticmethod
def delete_local_session(callback=None):
"""
Deletes the local session.
"""
if callback is not None:
callback()
@staticmethod
def calculate_x509_fingerprint(x509_cert, alg='sha1'):
"""
Calculates the fingerprint of a x509cert.
:param x509_cert: x509 cert
:type: string
:param alg: The algorithm to build the fingerprint
:type: string
:returns: fingerprint
:rtype: string
"""
assert isinstance(x509_cert, basestring)
lines = x509_cert.split('\n')
data = ''
for line in lines:
# Remove '\r' from end of line if present.
line = line.rstrip()
if line == '-----BEGIN CERTIFICATE-----':
# Delete junk from before the certificate.
data = ''
elif line == '-----END CERTIFICATE-----':
# Ignore data after the certificate.
break
elif line == '-----BEGIN PUBLIC KEY-----' or line == '-----BEGIN RSA PRIVATE KEY-----':
# This isn't an X509 certificate.
return None
else:
# Append the current line to the certificate data.
data += line
decoded_data = base64.b64decode(data)
if alg == 'sha512':
fingerprint = sha512(decoded_data)
elif alg == 'sha384':
fingerprint = sha384(decoded_data)
elif alg == 'sha256':
fingerprint = sha256(decoded_data)
else:
fingerprint = sha1(decoded_data)
return fingerprint.hexdigest().lower()
@staticmethod
def format_finger_print(fingerprint):
"""
Formates a fingerprint.
:param fingerprint: fingerprint
:type: string
:returns: Formated fingerprint
:rtype: string
"""
formated_fingerprint = fingerprint.replace(':', '')
return formated_fingerprint.lower()
@staticmethod
def generate_name_id(value, sp_nq, sp_format, cert=None, debug=False):
"""
Generates a nameID.
:param value: fingerprint
:type: string
:param sp_nq: SP Name Qualifier
:type: string
:param sp_format: SP Format
:type: string
:param cert: IdP Public Cert to encrypt the nameID
:type: string
:param debug: Activate the xmlsec debug
:type: bool
:returns: DOMElement | XMLSec nameID
:rtype: string
"""
doc = Document()
name_id_container = doc.createElementNS(OneLogin_Saml2_Constants.NS_SAML, 'container')
name_id_container.setAttribute("xmlns:saml", OneLogin_Saml2_Constants.NS_SAML)
name_id = doc.createElement('saml:NameID')
name_id.setAttribute('SPNameQualifier', sp_nq)
name_id.setAttribute('Format', sp_format)
name_id.appendChild(doc.createTextNode(value))
name_id_container.appendChild(name_id)
if cert is not None:
xml = name_id_container.toxml()
elem = fromstring(xml)
xmlsec.initialize()
if debug:
xmlsec.set_error_callback(print_xmlsec_errors)
# Load the public cert
mngr = xmlsec.KeysMngr()
file_cert = OneLogin_Saml2_Utils.write_temp_file(cert)
key_data = xmlsec.Key.load(file_cert.name, xmlsec.KeyDataFormatCertPem, None)
key_data.name = basename(file_cert.name)
mngr.addKey(key_data)
file_cert.close()
# Prepare for encryption
enc_data = EncData(xmlsec.TransformAes128Cbc, type=xmlsec.TypeEncElement)
enc_data.ensureCipherValue()
key_info = enc_data.ensureKeyInfo()
# enc_key = key_info.addEncryptedKey(xmlsec.TransformRsaPkcs1)
enc_key = key_info.addEncryptedKey(xmlsec.TransformRsaOaep)
enc_key.ensureCipherValue()
# Encrypt!
enc_ctx = xmlsec.EncCtx(mngr)
enc_ctx.encKey = xmlsec.Key.generate(xmlsec.KeyDataAes, 128, xmlsec.KeyDataTypeSession)
edata = enc_ctx.encryptXml(enc_data, elem[0])
newdoc = parseString(etree.tostring(edata))
if newdoc.hasChildNodes():
child = newdoc.firstChild
child.removeAttribute('xmlns')
child.removeAttribute('xmlns:saml')
child.setAttribute('xmlns:xenc', OneLogin_Saml2_Constants.NS_XENC)
child.setAttribute('xmlns:dsig', OneLogin_Saml2_Constants.NS_DS)
nodes = newdoc.getElementsByTagName("*")
for node in nodes:
if node.tagName == 'ns0:KeyInfo':
node.tagName = 'dsig:KeyInfo'
node.removeAttribute('xmlns:ns0')
node.setAttribute('xmlns:dsig', OneLogin_Saml2_Constants.NS_DS)
else:
node.tagName = 'xenc:' + node.tagName
encrypted_id = newdoc.createElement('saml:EncryptedID')
encrypted_data = newdoc.replaceChild(encrypted_id, newdoc.firstChild)
encrypted_id.appendChild(encrypted_data)
return newdoc.saveXML(encrypted_id)
else:
return doc.saveXML(name_id)
@staticmethod
def get_status(dom):
"""
Gets Status from a Response.
:param dom: The Response as XML
:type: Document
:returns: The Status, an array with the code and a message.
:rtype: dict
"""
status = {}
status_entry = OneLogin_Saml2_Utils.query(dom, '/samlp:Response/samlp:Status')
if len(status_entry) == 0:
raise Exception('Missing Status on response')
code_entry = OneLogin_Saml2_Utils.query(dom, '/samlp:Response/samlp:Status/samlp:StatusCode', status_entry[0])
if len(code_entry) == 0:
raise Exception('Missing Status Code on response')
code = code_entry[0].values()[0]
status['code'] = code
message_entry = OneLogin_Saml2_Utils.query(dom, '/samlp:Response/samlp:Status/samlp:StatusMessage', status_entry[0])
if len(message_entry) == 0:
subcode_entry = OneLogin_Saml2_Utils.query(dom, '/samlp:Response/samlp:Status/samlp:StatusCode/samlp:StatusCode', status_entry[0])
if len(subcode_entry) > 0:
status['msg'] = subcode_entry[0].values()[0]
else:
status['msg'] = ''
else:
status['msg'] = message_entry[0].text
return status
@staticmethod
def decrypt_element(encrypted_data, key, debug=False):
"""
Decrypts an encrypted element.
:param encrypted_data: The encrypted data.
:type: lxml.etree.Element | DOMElement | basestring
:param key: The key.
:type: string
:param debug: Activate the xmlsec debug
:type: bool
:returns: The decrypted element.
:rtype: lxml.etree.Element
"""
if isinstance(encrypted_data, Element):
encrypted_data = fromstring(str(encrypted_data.toxml()))
elif isinstance(encrypted_data, basestring):
encrypted_data = fromstring(str(encrypted_data))
xmlsec.initialize()
if debug:
xmlsec.set_error_callback(print_xmlsec_errors)
mngr = xmlsec.KeysMngr()
key = xmlsec.Key.loadMemory(key, xmlsec.KeyDataFormatPem, None)
mngr.addKey(key)
enc_ctx = xmlsec.EncCtx(mngr)
return enc_ctx.decrypt(encrypted_data)
@staticmethod
def write_temp_file(content):
"""
Writes some content into a temporary file and returns it.
:param content: The file content
:type: string
:returns: The temporary file
:rtype: file-like object
"""
f_temp = NamedTemporaryFile(delete=True)
f_temp.file.write(content)
f_temp.file.flush()
return f_temp
@staticmethod
def add_sign(xml, key, cert, debug=False, sign_algorithm=OneLogin_Saml2_Constants.RSA_SHA1):
"""
Adds signature key and senders certificate to an element (Message or
Assertion).
:param xml: The element we should sign
:type: string | Document
:param key: The private key
:type: string
:param cert: The public
:type: string
:param debug: Activate the xmlsec debug
:type: bool
:param sign_algorithm: Signature algorithm method
:type sign_algorithm: string
"""
if xml is None or xml == '':
raise Exception('Empty string supplied as input')
elif isinstance(xml, etree._Element):
elem = xml
elif isinstance(xml, Document):
xml = xml.toxml()
elem = fromstring(str(xml))
elif isinstance(xml, Element):
xml.setAttributeNS(
unicode(OneLogin_Saml2_Constants.NS_SAMLP),
'xmlns:samlp',
unicode(OneLogin_Saml2_Constants.NS_SAMLP)
)
xml.setAttributeNS(
unicode(OneLogin_Saml2_Constants.NS_SAML),
'xmlns:saml',
unicode(OneLogin_Saml2_Constants.NS_SAML)
)
xml = xml.toxml()
elem = fromstring(str(xml))
elif isinstance(xml, basestring):
elem = fromstring(str(xml))
else:
raise Exception('Error parsing xml string')
xmlsec.initialize()
if debug:
xmlsec.set_error_callback(print_xmlsec_errors)
# Sign the metadata with our private key.
sign_algorithm_transform_map = {
OneLogin_Saml2_Constants.DSA_SHA1: xmlsec.TransformDsaSha1,
OneLogin_Saml2_Constants.RSA_SHA1: xmlsec.TransformRsaSha1,
OneLogin_Saml2_Constants.RSA_SHA256: xmlsec.TransformRsaSha256,
OneLogin_Saml2_Constants.RSA_SHA384: xmlsec.TransformRsaSha384,
OneLogin_Saml2_Constants.RSA_SHA512: xmlsec.TransformRsaSha512
}
sign_algorithm_transform = sign_algorithm_transform_map.get(sign_algorithm, xmlsec.TransformRsaSha1)
signature = Signature(xmlsec.TransformExclC14N, sign_algorithm_transform)
issuer = OneLogin_Saml2_Utils.query(elem, '//saml:Issuer')
if len(issuer) > 0:
issuer = issuer[0]
issuer.addnext(signature)
else:
elem[0].insert(0, signature)
ref = signature.addReference(xmlsec.TransformSha1)
ref.addTransform(xmlsec.TransformEnveloped)
ref.addTransform(xmlsec.TransformExclC14N)
key_info = signature.ensureKeyInfo()
key_info.addX509Data()
dsig_ctx = xmlsec.DSigCtx()
sign_key = xmlsec.Key.loadMemory(key, xmlsec.KeyDataFormatPem, None)
file_cert = OneLogin_Saml2_Utils.write_temp_file(cert)
sign_key.loadCert(file_cert.name, xmlsec.KeyDataFormatCertPem)
file_cert.close()
dsig_ctx.signKey = sign_key
dsig_ctx.sign(signature)
newdoc = parseString(etree.tostring(elem))
signature_nodes = newdoc.getElementsByTagName("Signature")
for signature in signature_nodes:
signature.removeAttribute('xmlns')
signature.setAttribute('xmlns:ds', OneLogin_Saml2_Constants.NS_DS)
if not signature.tagName.startswith('ds:'):
signature.tagName = 'ds:' + signature.tagName
nodes = signature.getElementsByTagName("*")
for node in nodes:
if not node.tagName.startswith('ds:'):
node.tagName = 'ds:' + node.tagName
return newdoc.saveXML(newdoc.firstChild)
@staticmethod
def validate_sign(xml, cert=None, fingerprint=None, fingerprintalg='sha1', validatecert=False, debug=False):
"""
Validates a signature (Message or Assertion).
:param xml: The element we should validate
:type: string | Document
:param cert: The pubic cert
:type: string
:param fingerprint: The fingerprint of the public cert
:type: string
:param fingerprintalg: The algorithm used to build the fingerprint
:type: string
:param validatecert: If true, will verify the signature and if the cert is valid.
:type: bool
:param debug: Activate the xmlsec debug
:type: bool
"""
try:
if xml is None or xml == '':
raise Exception('Empty string supplied as input')
elif isinstance(xml, etree._Element):
elem = xml
elif isinstance(xml, Document):
xml = xml.toxml()
elem = fromstring(str(xml))
elif isinstance(xml, Element):
xml.setAttributeNS(
unicode(OneLogin_Saml2_Constants.NS_SAMLP),
'xmlns:samlp',
unicode(OneLogin_Saml2_Constants.NS_SAMLP)
)
xml.setAttributeNS(
unicode(OneLogin_Saml2_Constants.NS_SAML),
'xmlns:saml',
unicode(OneLogin_Saml2_Constants.NS_SAML)
)
xml = xml.toxml()
elem = fromstring(str(xml))
elif isinstance(xml, basestring):
elem = fromstring(str(xml))
else:
raise Exception('Error parsing xml string')
xmlsec.initialize()
if debug:
xmlsec.set_error_callback(print_xmlsec_errors)
xmlsec.addIDs(elem, ["ID"])
signature_nodes = OneLogin_Saml2_Utils.query(elem, '//ds:Signature')
if len(signature_nodes) > 0:
signature_node = signature_nodes[0]
if (cert is None or cert == '') and fingerprint:
x509_certificate_nodes = OneLogin_Saml2_Utils.query(signature_node, '//ds:Signature/ds:KeyInfo/ds:X509Data/ds:X509Certificate')
if len(x509_certificate_nodes) > 0:
x509_certificate_node = x509_certificate_nodes[0]
x509_cert_value = x509_certificate_node.text
x509_fingerprint_value = OneLogin_Saml2_Utils.calculate_x509_fingerprint(x509_cert_value, fingerprintalg)
if fingerprint == x509_fingerprint_value:
cert = OneLogin_Saml2_Utils.format_cert(x509_cert_value)
if cert is None or cert == '':
return False
# Check if Reference URI is empty
reference_elem = OneLogin_Saml2_Utils.query(signature_node, '//ds:Reference')
if len(reference_elem) > 0:
if reference_elem[0].get('URI') == '':
reference_elem[0].set('URI', '#%s' % signature_node.getparent().get('ID'))
dsig_ctx = xmlsec.DSigCtx()
file_cert = OneLogin_Saml2_Utils.write_temp_file(cert)
if validatecert:
mngr = xmlsec.KeysMngr()
mngr.loadCert(file_cert.name, xmlsec.KeyDataFormatCertPem, xmlsec.KeyDataTypeTrusted)
dsig_ctx = xmlsec.DSigCtx(mngr)
else:
dsig_ctx = xmlsec.DSigCtx()
dsig_ctx.signKey = xmlsec.Key.load(file_cert.name, xmlsec.KeyDataFormatCertPem, None)
file_cert.close()
dsig_ctx.setEnabledKeyData([xmlsec.KeyDataX509])
dsig_ctx.verify(signature_node)
return True
else:
return False
except Exception:
return False
@staticmethod
def validate_binary_sign(signed_query, signature, cert=None, algorithm=OneLogin_Saml2_Constants.RSA_SHA1, debug=False):
"""
Validates signed bynary data (Used to validate GET Signature).
:param signed_query: The element we should validate
:type: string
:param signature: The signature that will be validate
:type: string
:param cert: The pubic cert
:type: string
:param algorithm: Signature algorithm
:type: string
:param debug: Activate the xmlsec debug
:type: bool
"""
try:
xmlsec.initialize()
if debug:
xmlsec.set_error_callback(print_xmlsec_errors)
dsig_ctx = xmlsec.DSigCtx()
file_cert = OneLogin_Saml2_Utils.write_temp_file(cert)
dsig_ctx.signKey = xmlsec.Key.load(file_cert.name, xmlsec.KeyDataFormatCertPem, None)
file_cert.close()
# Sign the metadata with our private key.
sign_algorithm_transform_map = {
OneLogin_Saml2_Constants.DSA_SHA1: xmlsec.TransformDsaSha1,
OneLogin_Saml2_Constants.RSA_SHA1: xmlsec.TransformRsaSha1,
OneLogin_Saml2_Constants.RSA_SHA256: xmlsec.TransformRsaSha256,
OneLogin_Saml2_Constants.RSA_SHA384: xmlsec.TransformRsaSha384,
OneLogin_Saml2_Constants.RSA_SHA512: xmlsec.TransformRsaSha512
}
sign_algorithm_transform = sign_algorithm_transform_map.get(algorithm, xmlsec.TransformRsaSha1)
dsig_ctx.verifyBinary(signed_query, sign_algorithm_transform, signature)
return True
except Exception:
return False
| bsd-3-clause |
adamgreenhall/scikit-learn | examples/manifold/plot_compare_methods.py | 259 | 4031 | """
=========================================
Comparison of Manifold Learning methods
=========================================
An illustration of dimensionality reduction on the S-curve dataset
with various manifold learning methods.
For a discussion and comparison of these algorithms, see the
:ref:`manifold module page <manifold>`
For a similar example, where the methods are applied to a
sphere dataset, see :ref:`example_manifold_plot_manifold_sphere.py`
Note that the purpose of the MDS is to find a low-dimensional
representation of the data (here 2D) in which the distances respect well
the distances in the original high-dimensional space, unlike other
manifold-learning algorithms, it does not seeks an isotropic
representation of the data in the low-dimensional space.
"""
# Author: Jake Vanderplas -- <vanderplas@astro.washington.edu>
print(__doc__)
from time import time
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from matplotlib.ticker import NullFormatter
from sklearn import manifold, datasets
# Next line to silence pyflakes. This import is needed.
Axes3D
n_points = 1000
X, color = datasets.samples_generator.make_s_curve(n_points, random_state=0)
n_neighbors = 10
n_components = 2
fig = plt.figure(figsize=(15, 8))
plt.suptitle("Manifold Learning with %i points, %i neighbors"
% (1000, n_neighbors), fontsize=14)
try:
# compatibility matplotlib < 1.0
ax = fig.add_subplot(251, projection='3d')
ax.scatter(X[:, 0], X[:, 1], X[:, 2], c=color, cmap=plt.cm.Spectral)
ax.view_init(4, -72)
except:
ax = fig.add_subplot(251, projection='3d')
plt.scatter(X[:, 0], X[:, 2], c=color, cmap=plt.cm.Spectral)
methods = ['standard', 'ltsa', 'hessian', 'modified']
labels = ['LLE', 'LTSA', 'Hessian LLE', 'Modified LLE']
for i, method in enumerate(methods):
t0 = time()
Y = manifold.LocallyLinearEmbedding(n_neighbors, n_components,
eigen_solver='auto',
method=method).fit_transform(X)
t1 = time()
print("%s: %.2g sec" % (methods[i], t1 - t0))
ax = fig.add_subplot(252 + i)
plt.scatter(Y[:, 0], Y[:, 1], c=color, cmap=plt.cm.Spectral)
plt.title("%s (%.2g sec)" % (labels[i], t1 - t0))
ax.xaxis.set_major_formatter(NullFormatter())
ax.yaxis.set_major_formatter(NullFormatter())
plt.axis('tight')
t0 = time()
Y = manifold.Isomap(n_neighbors, n_components).fit_transform(X)
t1 = time()
print("Isomap: %.2g sec" % (t1 - t0))
ax = fig.add_subplot(257)
plt.scatter(Y[:, 0], Y[:, 1], c=color, cmap=plt.cm.Spectral)
plt.title("Isomap (%.2g sec)" % (t1 - t0))
ax.xaxis.set_major_formatter(NullFormatter())
ax.yaxis.set_major_formatter(NullFormatter())
plt.axis('tight')
t0 = time()
mds = manifold.MDS(n_components, max_iter=100, n_init=1)
Y = mds.fit_transform(X)
t1 = time()
print("MDS: %.2g sec" % (t1 - t0))
ax = fig.add_subplot(258)
plt.scatter(Y[:, 0], Y[:, 1], c=color, cmap=plt.cm.Spectral)
plt.title("MDS (%.2g sec)" % (t1 - t0))
ax.xaxis.set_major_formatter(NullFormatter())
ax.yaxis.set_major_formatter(NullFormatter())
plt.axis('tight')
t0 = time()
se = manifold.SpectralEmbedding(n_components=n_components,
n_neighbors=n_neighbors)
Y = se.fit_transform(X)
t1 = time()
print("SpectralEmbedding: %.2g sec" % (t1 - t0))
ax = fig.add_subplot(259)
plt.scatter(Y[:, 0], Y[:, 1], c=color, cmap=plt.cm.Spectral)
plt.title("SpectralEmbedding (%.2g sec)" % (t1 - t0))
ax.xaxis.set_major_formatter(NullFormatter())
ax.yaxis.set_major_formatter(NullFormatter())
plt.axis('tight')
t0 = time()
tsne = manifold.TSNE(n_components=n_components, init='pca', random_state=0)
Y = tsne.fit_transform(X)
t1 = time()
print("t-SNE: %.2g sec" % (t1 - t0))
ax = fig.add_subplot(250)
plt.scatter(Y[:, 0], Y[:, 1], c=color, cmap=plt.cm.Spectral)
plt.title("t-SNE (%.2g sec)" % (t1 - t0))
ax.xaxis.set_major_formatter(NullFormatter())
ax.yaxis.set_major_formatter(NullFormatter())
plt.axis('tight')
plt.show()
| bsd-3-clause |
mrosenbladt/yaml-cpp.core | test/gmock-1.7.0/scripts/generator/cpp/ast.py | 268 | 62296 | #!/usr/bin/env python
#
# Copyright 2007 Neal Norwitz
# Portions Copyright 2007 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Generate an Abstract Syntax Tree (AST) for C++."""
__author__ = 'nnorwitz@google.com (Neal Norwitz)'
# TODO:
# * Tokens should never be exported, need to convert to Nodes
# (return types, parameters, etc.)
# * Handle static class data for templatized classes
# * Handle casts (both C++ and C-style)
# * Handle conditions and loops (if/else, switch, for, while/do)
#
# TODO much, much later:
# * Handle #define
# * exceptions
try:
# Python 3.x
import builtins
except ImportError:
# Python 2.x
import __builtin__ as builtins
import sys
import traceback
from cpp import keywords
from cpp import tokenize
from cpp import utils
if not hasattr(builtins, 'reversed'):
# Support Python 2.3 and earlier.
def reversed(seq):
for i in range(len(seq)-1, -1, -1):
yield seq[i]
if not hasattr(builtins, 'next'):
# Support Python 2.5 and earlier.
def next(obj):
return obj.next()
VISIBILITY_PUBLIC, VISIBILITY_PROTECTED, VISIBILITY_PRIVATE = range(3)
FUNCTION_NONE = 0x00
FUNCTION_CONST = 0x01
FUNCTION_VIRTUAL = 0x02
FUNCTION_PURE_VIRTUAL = 0x04
FUNCTION_CTOR = 0x08
FUNCTION_DTOR = 0x10
FUNCTION_ATTRIBUTE = 0x20
FUNCTION_UNKNOWN_ANNOTATION = 0x40
FUNCTION_THROW = 0x80
"""
These are currently unused. Should really handle these properly at some point.
TYPE_MODIFIER_INLINE = 0x010000
TYPE_MODIFIER_EXTERN = 0x020000
TYPE_MODIFIER_STATIC = 0x040000
TYPE_MODIFIER_CONST = 0x080000
TYPE_MODIFIER_REGISTER = 0x100000
TYPE_MODIFIER_VOLATILE = 0x200000
TYPE_MODIFIER_MUTABLE = 0x400000
TYPE_MODIFIER_MAP = {
'inline': TYPE_MODIFIER_INLINE,
'extern': TYPE_MODIFIER_EXTERN,
'static': TYPE_MODIFIER_STATIC,
'const': TYPE_MODIFIER_CONST,
'register': TYPE_MODIFIER_REGISTER,
'volatile': TYPE_MODIFIER_VOLATILE,
'mutable': TYPE_MODIFIER_MUTABLE,
}
"""
_INTERNAL_TOKEN = 'internal'
_NAMESPACE_POP = 'ns-pop'
# TODO(nnorwitz): use this as a singleton for templated_types, etc
# where we don't want to create a new empty dict each time. It is also const.
class _NullDict(object):
__contains__ = lambda self: False
keys = values = items = iterkeys = itervalues = iteritems = lambda self: ()
# TODO(nnorwitz): move AST nodes into a separate module.
class Node(object):
"""Base AST node."""
def __init__(self, start, end):
self.start = start
self.end = end
def IsDeclaration(self):
"""Returns bool if this node is a declaration."""
return False
def IsDefinition(self):
"""Returns bool if this node is a definition."""
return False
def IsExportable(self):
"""Returns bool if this node exportable from a header file."""
return False
def Requires(self, node):
"""Does this AST node require the definition of the node passed in?"""
return False
def XXX__str__(self):
return self._StringHelper(self.__class__.__name__, '')
def _StringHelper(self, name, suffix):
if not utils.DEBUG:
return '%s(%s)' % (name, suffix)
return '%s(%d, %d, %s)' % (name, self.start, self.end, suffix)
def __repr__(self):
return str(self)
class Define(Node):
def __init__(self, start, end, name, definition):
Node.__init__(self, start, end)
self.name = name
self.definition = definition
def __str__(self):
value = '%s %s' % (self.name, self.definition)
return self._StringHelper(self.__class__.__name__, value)
class Include(Node):
def __init__(self, start, end, filename, system):
Node.__init__(self, start, end)
self.filename = filename
self.system = system
def __str__(self):
fmt = '"%s"'
if self.system:
fmt = '<%s>'
return self._StringHelper(self.__class__.__name__, fmt % self.filename)
class Goto(Node):
def __init__(self, start, end, label):
Node.__init__(self, start, end)
self.label = label
def __str__(self):
return self._StringHelper(self.__class__.__name__, str(self.label))
class Expr(Node):
def __init__(self, start, end, expr):
Node.__init__(self, start, end)
self.expr = expr
def Requires(self, node):
# TODO(nnorwitz): impl.
return False
def __str__(self):
return self._StringHelper(self.__class__.__name__, str(self.expr))
class Return(Expr):
pass
class Delete(Expr):
pass
class Friend(Expr):
def __init__(self, start, end, expr, namespace):
Expr.__init__(self, start, end, expr)
self.namespace = namespace[:]
class Using(Node):
def __init__(self, start, end, names):
Node.__init__(self, start, end)
self.names = names
def __str__(self):
return self._StringHelper(self.__class__.__name__, str(self.names))
class Parameter(Node):
def __init__(self, start, end, name, parameter_type, default):
Node.__init__(self, start, end)
self.name = name
self.type = parameter_type
self.default = default
def Requires(self, node):
# TODO(nnorwitz): handle namespaces, etc.
return self.type.name == node.name
def __str__(self):
name = str(self.type)
suffix = '%s %s' % (name, self.name)
if self.default:
suffix += ' = ' + ''.join([d.name for d in self.default])
return self._StringHelper(self.__class__.__name__, suffix)
class _GenericDeclaration(Node):
def __init__(self, start, end, name, namespace):
Node.__init__(self, start, end)
self.name = name
self.namespace = namespace[:]
def FullName(self):
prefix = ''
if self.namespace and self.namespace[-1]:
prefix = '::'.join(self.namespace) + '::'
return prefix + self.name
def _TypeStringHelper(self, suffix):
if self.namespace:
names = [n or '<anonymous>' for n in self.namespace]
suffix += ' in ' + '::'.join(names)
return self._StringHelper(self.__class__.__name__, suffix)
# TODO(nnorwitz): merge with Parameter in some way?
class VariableDeclaration(_GenericDeclaration):
def __init__(self, start, end, name, var_type, initial_value, namespace):
_GenericDeclaration.__init__(self, start, end, name, namespace)
self.type = var_type
self.initial_value = initial_value
def Requires(self, node):
# TODO(nnorwitz): handle namespaces, etc.
return self.type.name == node.name
def ToString(self):
"""Return a string that tries to reconstitute the variable decl."""
suffix = '%s %s' % (self.type, self.name)
if self.initial_value:
suffix += ' = ' + self.initial_value
return suffix
def __str__(self):
return self._StringHelper(self.__class__.__name__, self.ToString())
class Typedef(_GenericDeclaration):
def __init__(self, start, end, name, alias, namespace):
_GenericDeclaration.__init__(self, start, end, name, namespace)
self.alias = alias
def IsDefinition(self):
return True
def IsExportable(self):
return True
def Requires(self, node):
# TODO(nnorwitz): handle namespaces, etc.
name = node.name
for token in self.alias:
if token is not None and name == token.name:
return True
return False
def __str__(self):
suffix = '%s, %s' % (self.name, self.alias)
return self._TypeStringHelper(suffix)
class _NestedType(_GenericDeclaration):
def __init__(self, start, end, name, fields, namespace):
_GenericDeclaration.__init__(self, start, end, name, namespace)
self.fields = fields
def IsDefinition(self):
return True
def IsExportable(self):
return True
def __str__(self):
suffix = '%s, {%s}' % (self.name, self.fields)
return self._TypeStringHelper(suffix)
class Union(_NestedType):
pass
class Enum(_NestedType):
pass
class Class(_GenericDeclaration):
def __init__(self, start, end, name, bases, templated_types, body, namespace):
_GenericDeclaration.__init__(self, start, end, name, namespace)
self.bases = bases
self.body = body
self.templated_types = templated_types
def IsDeclaration(self):
return self.bases is None and self.body is None
def IsDefinition(self):
return not self.IsDeclaration()
def IsExportable(self):
return not self.IsDeclaration()
def Requires(self, node):
# TODO(nnorwitz): handle namespaces, etc.
if self.bases:
for token_list in self.bases:
# TODO(nnorwitz): bases are tokens, do name comparision.
for token in token_list:
if token.name == node.name:
return True
# TODO(nnorwitz): search in body too.
return False
def __str__(self):
name = self.name
if self.templated_types:
name += '<%s>' % self.templated_types
suffix = '%s, %s, %s' % (name, self.bases, self.body)
return self._TypeStringHelper(suffix)
class Struct(Class):
pass
class Function(_GenericDeclaration):
def __init__(self, start, end, name, return_type, parameters,
modifiers, templated_types, body, namespace):
_GenericDeclaration.__init__(self, start, end, name, namespace)
converter = TypeConverter(namespace)
self.return_type = converter.CreateReturnType(return_type)
self.parameters = converter.ToParameters(parameters)
self.modifiers = modifiers
self.body = body
self.templated_types = templated_types
def IsDeclaration(self):
return self.body is None
def IsDefinition(self):
return self.body is not None
def IsExportable(self):
if self.return_type and 'static' in self.return_type.modifiers:
return False
return None not in self.namespace
def Requires(self, node):
if self.parameters:
# TODO(nnorwitz): parameters are tokens, do name comparision.
for p in self.parameters:
if p.name == node.name:
return True
# TODO(nnorwitz): search in body too.
return False
def __str__(self):
# TODO(nnorwitz): add templated_types.
suffix = ('%s %s(%s), 0x%02x, %s' %
(self.return_type, self.name, self.parameters,
self.modifiers, self.body))
return self._TypeStringHelper(suffix)
class Method(Function):
def __init__(self, start, end, name, in_class, return_type, parameters,
modifiers, templated_types, body, namespace):
Function.__init__(self, start, end, name, return_type, parameters,
modifiers, templated_types, body, namespace)
# TODO(nnorwitz): in_class could also be a namespace which can
# mess up finding functions properly.
self.in_class = in_class
class Type(_GenericDeclaration):
"""Type used for any variable (eg class, primitive, struct, etc)."""
def __init__(self, start, end, name, templated_types, modifiers,
reference, pointer, array):
"""
Args:
name: str name of main type
templated_types: [Class (Type?)] template type info between <>
modifiers: [str] type modifiers (keywords) eg, const, mutable, etc.
reference, pointer, array: bools
"""
_GenericDeclaration.__init__(self, start, end, name, [])
self.templated_types = templated_types
if not name and modifiers:
self.name = modifiers.pop()
self.modifiers = modifiers
self.reference = reference
self.pointer = pointer
self.array = array
def __str__(self):
prefix = ''
if self.modifiers:
prefix = ' '.join(self.modifiers) + ' '
name = str(self.name)
if self.templated_types:
name += '<%s>' % self.templated_types
suffix = prefix + name
if self.reference:
suffix += '&'
if self.pointer:
suffix += '*'
if self.array:
suffix += '[]'
return self._TypeStringHelper(suffix)
# By definition, Is* are always False. A Type can only exist in
# some sort of variable declaration, parameter, or return value.
def IsDeclaration(self):
return False
def IsDefinition(self):
return False
def IsExportable(self):
return False
class TypeConverter(object):
def __init__(self, namespace_stack):
self.namespace_stack = namespace_stack
def _GetTemplateEnd(self, tokens, start):
count = 1
end = start
while 1:
token = tokens[end]
end += 1
if token.name == '<':
count += 1
elif token.name == '>':
count -= 1
if count == 0:
break
return tokens[start:end-1], end
def ToType(self, tokens):
"""Convert [Token,...] to [Class(...), ] useful for base classes.
For example, code like class Foo : public Bar<x, y> { ... };
the "Bar<x, y>" portion gets converted to an AST.
Returns:
[Class(...), ...]
"""
result = []
name_tokens = []
reference = pointer = array = False
def AddType(templated_types):
# Partition tokens into name and modifier tokens.
names = []
modifiers = []
for t in name_tokens:
if keywords.IsKeyword(t.name):
modifiers.append(t.name)
else:
names.append(t.name)
name = ''.join(names)
result.append(Type(name_tokens[0].start, name_tokens[-1].end,
name, templated_types, modifiers,
reference, pointer, array))
del name_tokens[:]
i = 0
end = len(tokens)
while i < end:
token = tokens[i]
if token.name == '<':
new_tokens, new_end = self._GetTemplateEnd(tokens, i+1)
AddType(self.ToType(new_tokens))
# If there is a comma after the template, we need to consume
# that here otherwise it becomes part of the name.
i = new_end
reference = pointer = array = False
elif token.name == ',':
AddType([])
reference = pointer = array = False
elif token.name == '*':
pointer = True
elif token.name == '&':
reference = True
elif token.name == '[':
pointer = True
elif token.name == ']':
pass
else:
name_tokens.append(token)
i += 1
if name_tokens:
# No '<' in the tokens, just a simple name and no template.
AddType([])
return result
def DeclarationToParts(self, parts, needs_name_removed):
name = None
default = []
if needs_name_removed:
# Handle default (initial) values properly.
for i, t in enumerate(parts):
if t.name == '=':
default = parts[i+1:]
name = parts[i-1].name
if name == ']' and parts[i-2].name == '[':
name = parts[i-3].name
i -= 1
parts = parts[:i-1]
break
else:
if parts[-1].token_type == tokenize.NAME:
name = parts.pop().name
else:
# TODO(nnorwitz): this is a hack that happens for code like
# Register(Foo<T>); where it thinks this is a function call
# but it's actually a declaration.
name = '???'
modifiers = []
type_name = []
other_tokens = []
templated_types = []
i = 0
end = len(parts)
while i < end:
p = parts[i]
if keywords.IsKeyword(p.name):
modifiers.append(p.name)
elif p.name == '<':
templated_tokens, new_end = self._GetTemplateEnd(parts, i+1)
templated_types = self.ToType(templated_tokens)
i = new_end - 1
# Don't add a spurious :: to data members being initialized.
next_index = i + 1
if next_index < end and parts[next_index].name == '::':
i += 1
elif p.name in ('[', ']', '='):
# These are handled elsewhere.
other_tokens.append(p)
elif p.name not in ('*', '&', '>'):
# Ensure that names have a space between them.
if (type_name and type_name[-1].token_type == tokenize.NAME and
p.token_type == tokenize.NAME):
type_name.append(tokenize.Token(tokenize.SYNTAX, ' ', 0, 0))
type_name.append(p)
else:
other_tokens.append(p)
i += 1
type_name = ''.join([t.name for t in type_name])
return name, type_name, templated_types, modifiers, default, other_tokens
def ToParameters(self, tokens):
if not tokens:
return []
result = []
name = type_name = ''
type_modifiers = []
pointer = reference = array = False
first_token = None
default = []
def AddParameter():
if default:
del default[0] # Remove flag.
end = type_modifiers[-1].end
parts = self.DeclarationToParts(type_modifiers, True)
(name, type_name, templated_types, modifiers,
unused_default, unused_other_tokens) = parts
parameter_type = Type(first_token.start, first_token.end,
type_name, templated_types, modifiers,
reference, pointer, array)
p = Parameter(first_token.start, end, name,
parameter_type, default)
result.append(p)
template_count = 0
for s in tokens:
if not first_token:
first_token = s
if s.name == '<':
template_count += 1
elif s.name == '>':
template_count -= 1
if template_count > 0:
type_modifiers.append(s)
continue
if s.name == ',':
AddParameter()
name = type_name = ''
type_modifiers = []
pointer = reference = array = False
first_token = None
default = []
elif s.name == '*':
pointer = True
elif s.name == '&':
reference = True
elif s.name == '[':
array = True
elif s.name == ']':
pass # Just don't add to type_modifiers.
elif s.name == '=':
# Got a default value. Add any value (None) as a flag.
default.append(None)
elif default:
default.append(s)
else:
type_modifiers.append(s)
AddParameter()
return result
def CreateReturnType(self, return_type_seq):
if not return_type_seq:
return None
start = return_type_seq[0].start
end = return_type_seq[-1].end
_, name, templated_types, modifiers, default, other_tokens = \
self.DeclarationToParts(return_type_seq, False)
names = [n.name for n in other_tokens]
reference = '&' in names
pointer = '*' in names
array = '[' in names
return Type(start, end, name, templated_types, modifiers,
reference, pointer, array)
def GetTemplateIndices(self, names):
# names is a list of strings.
start = names.index('<')
end = len(names) - 1
while end > 0:
if names[end] == '>':
break
end -= 1
return start, end+1
class AstBuilder(object):
def __init__(self, token_stream, filename, in_class='', visibility=None,
namespace_stack=[]):
self.tokens = token_stream
self.filename = filename
# TODO(nnorwitz): use a better data structure (deque) for the queue.
# Switching directions of the "queue" improved perf by about 25%.
# Using a deque should be even better since we access from both sides.
self.token_queue = []
self.namespace_stack = namespace_stack[:]
self.in_class = in_class
if in_class is None:
self.in_class_name_only = None
else:
self.in_class_name_only = in_class.split('::')[-1]
self.visibility = visibility
self.in_function = False
self.current_token = None
# Keep the state whether we are currently handling a typedef or not.
self._handling_typedef = False
self.converter = TypeConverter(self.namespace_stack)
def HandleError(self, msg, token):
printable_queue = list(reversed(self.token_queue[-20:]))
sys.stderr.write('Got %s in %s @ %s %s\n' %
(msg, self.filename, token, printable_queue))
def Generate(self):
while 1:
token = self._GetNextToken()
if not token:
break
# Get the next token.
self.current_token = token
# Dispatch on the next token type.
if token.token_type == _INTERNAL_TOKEN:
if token.name == _NAMESPACE_POP:
self.namespace_stack.pop()
continue
try:
result = self._GenerateOne(token)
if result is not None:
yield result
except:
self.HandleError('exception', token)
raise
def _CreateVariable(self, pos_token, name, type_name, type_modifiers,
ref_pointer_name_seq, templated_types, value=None):
reference = '&' in ref_pointer_name_seq
pointer = '*' in ref_pointer_name_seq
array = '[' in ref_pointer_name_seq
var_type = Type(pos_token.start, pos_token.end, type_name,
templated_types, type_modifiers,
reference, pointer, array)
return VariableDeclaration(pos_token.start, pos_token.end,
name, var_type, value, self.namespace_stack)
def _GenerateOne(self, token):
if token.token_type == tokenize.NAME:
if (keywords.IsKeyword(token.name) and
not keywords.IsBuiltinType(token.name)):
method = getattr(self, 'handle_' + token.name)
return method()
elif token.name == self.in_class_name_only:
# The token name is the same as the class, must be a ctor if
# there is a paren. Otherwise, it's the return type.
# Peek ahead to get the next token to figure out which.
next = self._GetNextToken()
self._AddBackToken(next)
if next.token_type == tokenize.SYNTAX and next.name == '(':
return self._GetMethod([token], FUNCTION_CTOR, None, True)
# Fall through--handle like any other method.
# Handle data or function declaration/definition.
syntax = tokenize.SYNTAX
temp_tokens, last_token = \
self._GetVarTokensUpTo(syntax, '(', ';', '{', '[')
temp_tokens.insert(0, token)
if last_token.name == '(':
# If there is an assignment before the paren,
# this is an expression, not a method.
expr = bool([e for e in temp_tokens if e.name == '='])
if expr:
new_temp = self._GetTokensUpTo(tokenize.SYNTAX, ';')
temp_tokens.append(last_token)
temp_tokens.extend(new_temp)
last_token = tokenize.Token(tokenize.SYNTAX, ';', 0, 0)
if last_token.name == '[':
# Handle array, this isn't a method, unless it's an operator.
# TODO(nnorwitz): keep the size somewhere.
# unused_size = self._GetTokensUpTo(tokenize.SYNTAX, ']')
temp_tokens.append(last_token)
if temp_tokens[-2].name == 'operator':
temp_tokens.append(self._GetNextToken())
else:
temp_tokens2, last_token = \
self._GetVarTokensUpTo(tokenize.SYNTAX, ';')
temp_tokens.extend(temp_tokens2)
if last_token.name == ';':
# Handle data, this isn't a method.
parts = self.converter.DeclarationToParts(temp_tokens, True)
(name, type_name, templated_types, modifiers, default,
unused_other_tokens) = parts
t0 = temp_tokens[0]
names = [t.name for t in temp_tokens]
if templated_types:
start, end = self.converter.GetTemplateIndices(names)
names = names[:start] + names[end:]
default = ''.join([t.name for t in default])
return self._CreateVariable(t0, name, type_name, modifiers,
names, templated_types, default)
if last_token.name == '{':
self._AddBackTokens(temp_tokens[1:])
self._AddBackToken(last_token)
method_name = temp_tokens[0].name
method = getattr(self, 'handle_' + method_name, None)
if not method:
# Must be declaring a variable.
# TODO(nnorwitz): handle the declaration.
return None
return method()
return self._GetMethod(temp_tokens, 0, None, False)
elif token.token_type == tokenize.SYNTAX:
if token.name == '~' and self.in_class:
# Must be a dtor (probably not in method body).
token = self._GetNextToken()
# self.in_class can contain A::Name, but the dtor will only
# be Name. Make sure to compare against the right value.
if (token.token_type == tokenize.NAME and
token.name == self.in_class_name_only):
return self._GetMethod([token], FUNCTION_DTOR, None, True)
# TODO(nnorwitz): handle a lot more syntax.
elif token.token_type == tokenize.PREPROCESSOR:
# TODO(nnorwitz): handle more preprocessor directives.
# token starts with a #, so remove it and strip whitespace.
name = token.name[1:].lstrip()
if name.startswith('include'):
# Remove "include".
name = name[7:].strip()
assert name
# Handle #include \<newline> "header-on-second-line.h".
if name.startswith('\\'):
name = name[1:].strip()
assert name[0] in '<"', token
assert name[-1] in '>"', token
system = name[0] == '<'
filename = name[1:-1]
return Include(token.start, token.end, filename, system)
if name.startswith('define'):
# Remove "define".
name = name[6:].strip()
assert name
value = ''
for i, c in enumerate(name):
if c.isspace():
value = name[i:].lstrip()
name = name[:i]
break
return Define(token.start, token.end, name, value)
if name.startswith('if') and name[2:3].isspace():
condition = name[3:].strip()
if condition.startswith('0') or condition.startswith('(0)'):
self._SkipIf0Blocks()
return None
def _GetTokensUpTo(self, expected_token_type, expected_token):
return self._GetVarTokensUpTo(expected_token_type, expected_token)[0]
def _GetVarTokensUpTo(self, expected_token_type, *expected_tokens):
last_token = self._GetNextToken()
tokens = []
while (last_token.token_type != expected_token_type or
last_token.name not in expected_tokens):
tokens.append(last_token)
last_token = self._GetNextToken()
return tokens, last_token
# TODO(nnorwitz): remove _IgnoreUpTo() it shouldn't be necesary.
def _IgnoreUpTo(self, token_type, token):
unused_tokens = self._GetTokensUpTo(token_type, token)
def _SkipIf0Blocks(self):
count = 1
while 1:
token = self._GetNextToken()
if token.token_type != tokenize.PREPROCESSOR:
continue
name = token.name[1:].lstrip()
if name.startswith('endif'):
count -= 1
if count == 0:
break
elif name.startswith('if'):
count += 1
def _GetMatchingChar(self, open_paren, close_paren, GetNextToken=None):
if GetNextToken is None:
GetNextToken = self._GetNextToken
# Assumes the current token is open_paren and we will consume
# and return up to the close_paren.
count = 1
token = GetNextToken()
while 1:
if token.token_type == tokenize.SYNTAX:
if token.name == open_paren:
count += 1
elif token.name == close_paren:
count -= 1
if count == 0:
break
yield token
token = GetNextToken()
yield token
def _GetParameters(self):
return self._GetMatchingChar('(', ')')
def GetScope(self):
return self._GetMatchingChar('{', '}')
def _GetNextToken(self):
if self.token_queue:
return self.token_queue.pop()
return next(self.tokens)
def _AddBackToken(self, token):
if token.whence == tokenize.WHENCE_STREAM:
token.whence = tokenize.WHENCE_QUEUE
self.token_queue.insert(0, token)
else:
assert token.whence == tokenize.WHENCE_QUEUE, token
self.token_queue.append(token)
def _AddBackTokens(self, tokens):
if tokens:
if tokens[-1].whence == tokenize.WHENCE_STREAM:
for token in tokens:
token.whence = tokenize.WHENCE_QUEUE
self.token_queue[:0] = reversed(tokens)
else:
assert tokens[-1].whence == tokenize.WHENCE_QUEUE, tokens
self.token_queue.extend(reversed(tokens))
def GetName(self, seq=None):
"""Returns ([tokens], next_token_info)."""
GetNextToken = self._GetNextToken
if seq is not None:
it = iter(seq)
GetNextToken = lambda: next(it)
next_token = GetNextToken()
tokens = []
last_token_was_name = False
while (next_token.token_type == tokenize.NAME or
(next_token.token_type == tokenize.SYNTAX and
next_token.name in ('::', '<'))):
# Two NAMEs in a row means the identifier should terminate.
# It's probably some sort of variable declaration.
if last_token_was_name and next_token.token_type == tokenize.NAME:
break
last_token_was_name = next_token.token_type == tokenize.NAME
tokens.append(next_token)
# Handle templated names.
if next_token.name == '<':
tokens.extend(self._GetMatchingChar('<', '>', GetNextToken))
last_token_was_name = True
next_token = GetNextToken()
return tokens, next_token
def GetMethod(self, modifiers, templated_types):
return_type_and_name = self._GetTokensUpTo(tokenize.SYNTAX, '(')
assert len(return_type_and_name) >= 1
return self._GetMethod(return_type_and_name, modifiers, templated_types,
False)
def _GetMethod(self, return_type_and_name, modifiers, templated_types,
get_paren):
template_portion = None
if get_paren:
token = self._GetNextToken()
assert token.token_type == tokenize.SYNTAX, token
if token.name == '<':
# Handle templatized dtors.
template_portion = [token]
template_portion.extend(self._GetMatchingChar('<', '>'))
token = self._GetNextToken()
assert token.token_type == tokenize.SYNTAX, token
assert token.name == '(', token
name = return_type_and_name.pop()
# Handle templatized ctors.
if name.name == '>':
index = 1
while return_type_and_name[index].name != '<':
index += 1
template_portion = return_type_and_name[index:] + [name]
del return_type_and_name[index:]
name = return_type_and_name.pop()
elif name.name == ']':
rt = return_type_and_name
assert rt[-1].name == '[', return_type_and_name
assert rt[-2].name == 'operator', return_type_and_name
name_seq = return_type_and_name[-2:]
del return_type_and_name[-2:]
name = tokenize.Token(tokenize.NAME, 'operator[]',
name_seq[0].start, name.end)
# Get the open paren so _GetParameters() below works.
unused_open_paren = self._GetNextToken()
# TODO(nnorwitz): store template_portion.
return_type = return_type_and_name
indices = name
if return_type:
indices = return_type[0]
# Force ctor for templatized ctors.
if name.name == self.in_class and not modifiers:
modifiers |= FUNCTION_CTOR
parameters = list(self._GetParameters())
del parameters[-1] # Remove trailing ')'.
# Handling operator() is especially weird.
if name.name == 'operator' and not parameters:
token = self._GetNextToken()
assert token.name == '(', token
parameters = list(self._GetParameters())
del parameters[-1] # Remove trailing ')'.
token = self._GetNextToken()
while token.token_type == tokenize.NAME:
modifier_token = token
token = self._GetNextToken()
if modifier_token.name == 'const':
modifiers |= FUNCTION_CONST
elif modifier_token.name == '__attribute__':
# TODO(nnorwitz): handle more __attribute__ details.
modifiers |= FUNCTION_ATTRIBUTE
assert token.name == '(', token
# Consume everything between the (parens).
unused_tokens = list(self._GetMatchingChar('(', ')'))
token = self._GetNextToken()
elif modifier_token.name == 'throw':
modifiers |= FUNCTION_THROW
assert token.name == '(', token
# Consume everything between the (parens).
unused_tokens = list(self._GetMatchingChar('(', ')'))
token = self._GetNextToken()
elif modifier_token.name == modifier_token.name.upper():
# HACK(nnorwitz): assume that all upper-case names
# are some macro we aren't expanding.
modifiers |= FUNCTION_UNKNOWN_ANNOTATION
else:
self.HandleError('unexpected token', modifier_token)
assert token.token_type == tokenize.SYNTAX, token
# Handle ctor initializers.
if token.name == ':':
# TODO(nnorwitz): anything else to handle for initializer list?
while token.name != ';' and token.name != '{':
token = self._GetNextToken()
# Handle pointer to functions that are really data but look
# like method declarations.
if token.name == '(':
if parameters[0].name == '*':
# name contains the return type.
name = parameters.pop()
# parameters contains the name of the data.
modifiers = [p.name for p in parameters]
# Already at the ( to open the parameter list.
function_parameters = list(self._GetMatchingChar('(', ')'))
del function_parameters[-1] # Remove trailing ')'.
# TODO(nnorwitz): store the function_parameters.
token = self._GetNextToken()
assert token.token_type == tokenize.SYNTAX, token
assert token.name == ';', token
return self._CreateVariable(indices, name.name, indices.name,
modifiers, '', None)
# At this point, we got something like:
# return_type (type::*name_)(params);
# This is a data member called name_ that is a function pointer.
# With this code: void (sq_type::*field_)(string&);
# We get: name=void return_type=[] parameters=sq_type ... field_
# TODO(nnorwitz): is return_type always empty?
# TODO(nnorwitz): this isn't even close to being correct.
# Just put in something so we don't crash and can move on.
real_name = parameters[-1]
modifiers = [p.name for p in self._GetParameters()]
del modifiers[-1] # Remove trailing ')'.
return self._CreateVariable(indices, real_name.name, indices.name,
modifiers, '', None)
if token.name == '{':
body = list(self.GetScope())
del body[-1] # Remove trailing '}'.
else:
body = None
if token.name == '=':
token = self._GetNextToken()
assert token.token_type == tokenize.CONSTANT, token
assert token.name == '0', token
modifiers |= FUNCTION_PURE_VIRTUAL
token = self._GetNextToken()
if token.name == '[':
# TODO(nnorwitz): store tokens and improve parsing.
# template <typename T, size_t N> char (&ASH(T (&seq)[N]))[N];
tokens = list(self._GetMatchingChar('[', ']'))
token = self._GetNextToken()
assert token.name == ';', (token, return_type_and_name, parameters)
# Looks like we got a method, not a function.
if len(return_type) > 2 and return_type[-1].name == '::':
return_type, in_class = \
self._GetReturnTypeAndClassName(return_type)
return Method(indices.start, indices.end, name.name, in_class,
return_type, parameters, modifiers, templated_types,
body, self.namespace_stack)
return Function(indices.start, indices.end, name.name, return_type,
parameters, modifiers, templated_types, body,
self.namespace_stack)
def _GetReturnTypeAndClassName(self, token_seq):
# Splitting the return type from the class name in a method
# can be tricky. For example, Return::Type::Is::Hard::To::Find().
# Where is the return type and where is the class name?
# The heuristic used is to pull the last name as the class name.
# This includes all the templated type info.
# TODO(nnorwitz): if there is only One name like in the
# example above, punt and assume the last bit is the class name.
# Ignore a :: prefix, if exists so we can find the first real name.
i = 0
if token_seq[0].name == '::':
i = 1
# Ignore a :: suffix, if exists.
end = len(token_seq) - 1
if token_seq[end-1].name == '::':
end -= 1
# Make a copy of the sequence so we can append a sentinel
# value. This is required for GetName will has to have some
# terminating condition beyond the last name.
seq_copy = token_seq[i:end]
seq_copy.append(tokenize.Token(tokenize.SYNTAX, '', 0, 0))
names = []
while i < end:
# Iterate through the sequence parsing out each name.
new_name, next = self.GetName(seq_copy[i:])
assert new_name, 'Got empty new_name, next=%s' % next
# We got a pointer or ref. Add it to the name.
if next and next.token_type == tokenize.SYNTAX:
new_name.append(next)
names.append(new_name)
i += len(new_name)
# Now that we have the names, it's time to undo what we did.
# Remove the sentinel value.
names[-1].pop()
# Flatten the token sequence for the return type.
return_type = [e for seq in names[:-1] for e in seq]
# The class name is the last name.
class_name = names[-1]
return return_type, class_name
def handle_bool(self):
pass
def handle_char(self):
pass
def handle_int(self):
pass
def handle_long(self):
pass
def handle_short(self):
pass
def handle_double(self):
pass
def handle_float(self):
pass
def handle_void(self):
pass
def handle_wchar_t(self):
pass
def handle_unsigned(self):
pass
def handle_signed(self):
pass
def _GetNestedType(self, ctor):
name = None
name_tokens, token = self.GetName()
if name_tokens:
name = ''.join([t.name for t in name_tokens])
# Handle forward declarations.
if token.token_type == tokenize.SYNTAX and token.name == ';':
return ctor(token.start, token.end, name, None,
self.namespace_stack)
if token.token_type == tokenize.NAME and self._handling_typedef:
self._AddBackToken(token)
return ctor(token.start, token.end, name, None,
self.namespace_stack)
# Must be the type declaration.
fields = list(self._GetMatchingChar('{', '}'))
del fields[-1] # Remove trailing '}'.
if token.token_type == tokenize.SYNTAX and token.name == '{':
next = self._GetNextToken()
new_type = ctor(token.start, token.end, name, fields,
self.namespace_stack)
# A name means this is an anonymous type and the name
# is the variable declaration.
if next.token_type != tokenize.NAME:
return new_type
name = new_type
token = next
# Must be variable declaration using the type prefixed with keyword.
assert token.token_type == tokenize.NAME, token
return self._CreateVariable(token, token.name, name, [], '', None)
def handle_struct(self):
# Special case the handling typedef/aliasing of structs here.
# It would be a pain to handle in the class code.
name_tokens, var_token = self.GetName()
if name_tokens:
next_token = self._GetNextToken()
is_syntax = (var_token.token_type == tokenize.SYNTAX and
var_token.name[0] in '*&')
is_variable = (var_token.token_type == tokenize.NAME and
next_token.name == ';')
variable = var_token
if is_syntax and not is_variable:
variable = next_token
temp = self._GetNextToken()
if temp.token_type == tokenize.SYNTAX and temp.name == '(':
# Handle methods declared to return a struct.
t0 = name_tokens[0]
struct = tokenize.Token(tokenize.NAME, 'struct',
t0.start-7, t0.start-2)
type_and_name = [struct]
type_and_name.extend(name_tokens)
type_and_name.extend((var_token, next_token))
return self._GetMethod(type_and_name, 0, None, False)
assert temp.name == ';', (temp, name_tokens, var_token)
if is_syntax or (is_variable and not self._handling_typedef):
modifiers = ['struct']
type_name = ''.join([t.name for t in name_tokens])
position = name_tokens[0]
return self._CreateVariable(position, variable.name, type_name,
modifiers, var_token.name, None)
name_tokens.extend((var_token, next_token))
self._AddBackTokens(name_tokens)
else:
self._AddBackToken(var_token)
return self._GetClass(Struct, VISIBILITY_PUBLIC, None)
def handle_union(self):
return self._GetNestedType(Union)
def handle_enum(self):
return self._GetNestedType(Enum)
def handle_auto(self):
# TODO(nnorwitz): warn about using auto? Probably not since it
# will be reclaimed and useful for C++0x.
pass
def handle_register(self):
pass
def handle_const(self):
pass
def handle_inline(self):
pass
def handle_extern(self):
pass
def handle_static(self):
pass
def handle_virtual(self):
# What follows must be a method.
token = token2 = self._GetNextToken()
if token.name == 'inline':
# HACK(nnorwitz): handle inline dtors by ignoring 'inline'.
token2 = self._GetNextToken()
if token2.token_type == tokenize.SYNTAX and token2.name == '~':
return self.GetMethod(FUNCTION_VIRTUAL + FUNCTION_DTOR, None)
assert token.token_type == tokenize.NAME or token.name == '::', token
return_type_and_name = self._GetTokensUpTo(tokenize.SYNTAX, '(')
return_type_and_name.insert(0, token)
if token2 is not token:
return_type_and_name.insert(1, token2)
return self._GetMethod(return_type_and_name, FUNCTION_VIRTUAL,
None, False)
def handle_volatile(self):
pass
def handle_mutable(self):
pass
def handle_public(self):
assert self.in_class
self.visibility = VISIBILITY_PUBLIC
def handle_protected(self):
assert self.in_class
self.visibility = VISIBILITY_PROTECTED
def handle_private(self):
assert self.in_class
self.visibility = VISIBILITY_PRIVATE
def handle_friend(self):
tokens = self._GetTokensUpTo(tokenize.SYNTAX, ';')
assert tokens
t0 = tokens[0]
return Friend(t0.start, t0.end, tokens, self.namespace_stack)
def handle_static_cast(self):
pass
def handle_const_cast(self):
pass
def handle_dynamic_cast(self):
pass
def handle_reinterpret_cast(self):
pass
def handle_new(self):
pass
def handle_delete(self):
tokens = self._GetTokensUpTo(tokenize.SYNTAX, ';')
assert tokens
return Delete(tokens[0].start, tokens[0].end, tokens)
def handle_typedef(self):
token = self._GetNextToken()
if (token.token_type == tokenize.NAME and
keywords.IsKeyword(token.name)):
# Token must be struct/enum/union/class.
method = getattr(self, 'handle_' + token.name)
self._handling_typedef = True
tokens = [method()]
self._handling_typedef = False
else:
tokens = [token]
# Get the remainder of the typedef up to the semi-colon.
tokens.extend(self._GetTokensUpTo(tokenize.SYNTAX, ';'))
# TODO(nnorwitz): clean all this up.
assert tokens
name = tokens.pop()
indices = name
if tokens:
indices = tokens[0]
if not indices:
indices = token
if name.name == ')':
# HACK(nnorwitz): Handle pointers to functions "properly".
if (len(tokens) >= 4 and
tokens[1].name == '(' and tokens[2].name == '*'):
tokens.append(name)
name = tokens[3]
elif name.name == ']':
# HACK(nnorwitz): Handle arrays properly.
if len(tokens) >= 2:
tokens.append(name)
name = tokens[1]
new_type = tokens
if tokens and isinstance(tokens[0], tokenize.Token):
new_type = self.converter.ToType(tokens)[0]
return Typedef(indices.start, indices.end, name.name,
new_type, self.namespace_stack)
def handle_typeid(self):
pass # Not needed yet.
def handle_typename(self):
pass # Not needed yet.
def _GetTemplatedTypes(self):
result = {}
tokens = list(self._GetMatchingChar('<', '>'))
len_tokens = len(tokens) - 1 # Ignore trailing '>'.
i = 0
while i < len_tokens:
key = tokens[i].name
i += 1
if keywords.IsKeyword(key) or key == ',':
continue
type_name = default = None
if i < len_tokens:
i += 1
if tokens[i-1].name == '=':
assert i < len_tokens, '%s %s' % (i, tokens)
default, unused_next_token = self.GetName(tokens[i:])
i += len(default)
else:
if tokens[i-1].name != ',':
# We got something like: Type variable.
# Re-adjust the key (variable) and type_name (Type).
key = tokens[i-1].name
type_name = tokens[i-2]
result[key] = (type_name, default)
return result
def handle_template(self):
token = self._GetNextToken()
assert token.token_type == tokenize.SYNTAX, token
assert token.name == '<', token
templated_types = self._GetTemplatedTypes()
# TODO(nnorwitz): for now, just ignore the template params.
token = self._GetNextToken()
if token.token_type == tokenize.NAME:
if token.name == 'class':
return self._GetClass(Class, VISIBILITY_PRIVATE, templated_types)
elif token.name == 'struct':
return self._GetClass(Struct, VISIBILITY_PUBLIC, templated_types)
elif token.name == 'friend':
return self.handle_friend()
self._AddBackToken(token)
tokens, last = self._GetVarTokensUpTo(tokenize.SYNTAX, '(', ';')
tokens.append(last)
self._AddBackTokens(tokens)
if last.name == '(':
return self.GetMethod(FUNCTION_NONE, templated_types)
# Must be a variable definition.
return None
def handle_true(self):
pass # Nothing to do.
def handle_false(self):
pass # Nothing to do.
def handle_asm(self):
pass # Not needed yet.
def handle_class(self):
return self._GetClass(Class, VISIBILITY_PRIVATE, None)
def _GetBases(self):
# Get base classes.
bases = []
while 1:
token = self._GetNextToken()
assert token.token_type == tokenize.NAME, token
# TODO(nnorwitz): store kind of inheritance...maybe.
if token.name not in ('public', 'protected', 'private'):
# If inheritance type is not specified, it is private.
# Just put the token back so we can form a name.
# TODO(nnorwitz): it would be good to warn about this.
self._AddBackToken(token)
else:
# Check for virtual inheritance.
token = self._GetNextToken()
if token.name != 'virtual':
self._AddBackToken(token)
else:
# TODO(nnorwitz): store that we got virtual for this base.
pass
base, next_token = self.GetName()
bases_ast = self.converter.ToType(base)
assert len(bases_ast) == 1, bases_ast
bases.append(bases_ast[0])
assert next_token.token_type == tokenize.SYNTAX, next_token
if next_token.name == '{':
token = next_token
break
# Support multiple inheritance.
assert next_token.name == ',', next_token
return bases, token
def _GetClass(self, class_type, visibility, templated_types):
class_name = None
class_token = self._GetNextToken()
if class_token.token_type != tokenize.NAME:
assert class_token.token_type == tokenize.SYNTAX, class_token
token = class_token
else:
# Skip any macro (e.g. storage class specifiers) after the
# 'class' keyword.
next_token = self._GetNextToken()
if next_token.token_type == tokenize.NAME:
self._AddBackToken(next_token)
else:
self._AddBackTokens([class_token, next_token])
name_tokens, token = self.GetName()
class_name = ''.join([t.name for t in name_tokens])
bases = None
if token.token_type == tokenize.SYNTAX:
if token.name == ';':
# Forward declaration.
return class_type(class_token.start, class_token.end,
class_name, None, templated_types, None,
self.namespace_stack)
if token.name in '*&':
# Inline forward declaration. Could be method or data.
name_token = self._GetNextToken()
next_token = self._GetNextToken()
if next_token.name == ';':
# Handle data
modifiers = ['class']
return self._CreateVariable(class_token, name_token.name,
class_name,
modifiers, token.name, None)
else:
# Assume this is a method.
tokens = (class_token, token, name_token, next_token)
self._AddBackTokens(tokens)
return self.GetMethod(FUNCTION_NONE, None)
if token.name == ':':
bases, token = self._GetBases()
body = None
if token.token_type == tokenize.SYNTAX and token.name == '{':
assert token.token_type == tokenize.SYNTAX, token
assert token.name == '{', token
ast = AstBuilder(self.GetScope(), self.filename, class_name,
visibility, self.namespace_stack)
body = list(ast.Generate())
if not self._handling_typedef:
token = self._GetNextToken()
if token.token_type != tokenize.NAME:
assert token.token_type == tokenize.SYNTAX, token
assert token.name == ';', token
else:
new_class = class_type(class_token.start, class_token.end,
class_name, bases, None,
body, self.namespace_stack)
modifiers = []
return self._CreateVariable(class_token,
token.name, new_class,
modifiers, token.name, None)
else:
if not self._handling_typedef:
self.HandleError('non-typedef token', token)
self._AddBackToken(token)
return class_type(class_token.start, class_token.end, class_name,
bases, templated_types, body, self.namespace_stack)
def handle_namespace(self):
token = self._GetNextToken()
# Support anonymous namespaces.
name = None
if token.token_type == tokenize.NAME:
name = token.name
token = self._GetNextToken()
self.namespace_stack.append(name)
assert token.token_type == tokenize.SYNTAX, token
# Create an internal token that denotes when the namespace is complete.
internal_token = tokenize.Token(_INTERNAL_TOKEN, _NAMESPACE_POP,
None, None)
internal_token.whence = token.whence
if token.name == '=':
# TODO(nnorwitz): handle aliasing namespaces.
name, next_token = self.GetName()
assert next_token.name == ';', next_token
self._AddBackToken(internal_token)
else:
assert token.name == '{', token
tokens = list(self.GetScope())
# Replace the trailing } with the internal namespace pop token.
tokens[-1] = internal_token
# Handle namespace with nothing in it.
self._AddBackTokens(tokens)
return None
def handle_using(self):
tokens = self._GetTokensUpTo(tokenize.SYNTAX, ';')
assert tokens
return Using(tokens[0].start, tokens[0].end, tokens)
def handle_explicit(self):
assert self.in_class
# Nothing much to do.
# TODO(nnorwitz): maybe verify the method name == class name.
# This must be a ctor.
return self.GetMethod(FUNCTION_CTOR, None)
def handle_this(self):
pass # Nothing to do.
def handle_operator(self):
# Pull off the next token(s?) and make that part of the method name.
pass
def handle_sizeof(self):
pass
def handle_case(self):
pass
def handle_switch(self):
pass
def handle_default(self):
token = self._GetNextToken()
assert token.token_type == tokenize.SYNTAX
assert token.name == ':'
def handle_if(self):
pass
def handle_else(self):
pass
def handle_return(self):
tokens = self._GetTokensUpTo(tokenize.SYNTAX, ';')
if not tokens:
return Return(self.current_token.start, self.current_token.end, None)
return Return(tokens[0].start, tokens[0].end, tokens)
def handle_goto(self):
tokens = self._GetTokensUpTo(tokenize.SYNTAX, ';')
assert len(tokens) == 1, str(tokens)
return Goto(tokens[0].start, tokens[0].end, tokens[0].name)
def handle_try(self):
pass # Not needed yet.
def handle_catch(self):
pass # Not needed yet.
def handle_throw(self):
pass # Not needed yet.
def handle_while(self):
pass
def handle_do(self):
pass
def handle_for(self):
pass
def handle_break(self):
self._IgnoreUpTo(tokenize.SYNTAX, ';')
def handle_continue(self):
self._IgnoreUpTo(tokenize.SYNTAX, ';')
def BuilderFromSource(source, filename):
"""Utility method that returns an AstBuilder from source code.
Args:
source: 'C++ source code'
filename: 'file1'
Returns:
AstBuilder
"""
return AstBuilder(tokenize.GetTokens(source), filename)
def PrintIndentifiers(filename, should_print):
"""Prints all identifiers for a C++ source file.
Args:
filename: 'file1'
should_print: predicate with signature: bool Function(token)
"""
source = utils.ReadFile(filename, False)
if source is None:
sys.stderr.write('Unable to find: %s\n' % filename)
return
#print('Processing %s' % actual_filename)
builder = BuilderFromSource(source, filename)
try:
for node in builder.Generate():
if should_print(node):
print(node.name)
except KeyboardInterrupt:
return
except:
pass
def PrintAllIndentifiers(filenames, should_print):
"""Prints all identifiers for each C++ source file in filenames.
Args:
filenames: ['file1', 'file2', ...]
should_print: predicate with signature: bool Function(token)
"""
for path in filenames:
PrintIndentifiers(path, should_print)
def main(argv):
for filename in argv[1:]:
source = utils.ReadFile(filename)
if source is None:
continue
print('Processing %s' % filename)
builder = BuilderFromSource(source, filename)
try:
entire_ast = filter(None, builder.Generate())
except KeyboardInterrupt:
return
except:
# Already printed a warning, print the traceback and continue.
traceback.print_exc()
else:
if utils.DEBUG:
for ast in entire_ast:
print(ast)
if __name__ == '__main__':
main(sys.argv)
| mit |
v-iam/azure-sdk-for-python | azure-mgmt-recoveryservicesbackup/azure/mgmt/recoveryservicesbackup/models/export_jobs_operation_result_info.py | 4 | 1521 | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
# --------------------------------------------------------------------------
from .operation_result_info_base import OperationResultInfoBase
class ExportJobsOperationResultInfo(OperationResultInfoBase):
"""This class is used to send blob details after exporting jobs.
:param object_type: Polymorphic Discriminator
:type object_type: str
:param blob_url: URL of the blob into which the serialized string of list
of jobs is exported.
:type blob_url: str
:param blob_sas_key: SAS key to access the blob. It expires in 15 mins.
:type blob_sas_key: str
"""
_validation = {
'object_type': {'required': True},
}
_attribute_map = {
'object_type': {'key': 'objectType', 'type': 'str'},
'blob_url': {'key': 'blobUrl', 'type': 'str'},
'blob_sas_key': {'key': 'blobSasKey', 'type': 'str'},
}
def __init__(self, blob_url=None, blob_sas_key=None):
super(ExportJobsOperationResultInfo, self).__init__()
self.blob_url = blob_url
self.blob_sas_key = blob_sas_key
self.object_type = 'ExportJobsOperationResultInfo'
| mit |
Sinar/mapit | setup.py | 1 | 1464 | from setuptools import setup, find_packages
import os
file_dir = os.path.abspath(os.path.dirname(__file__))
def read_file(filename):
filepath = os.path.join(file_dir, filename)
return open(filepath).read()
def install_requires():
reqs = read_file('requirements.txt')
reqs = reqs.splitlines()
reqs = [ x for x in reqs if x and x[0] != '#' and x[0:2] != '-e' ]
return reqs
setup(
name='django-mapit',
version='1.0.3',
description='A web service for mapping postcodes and points to current or past administrative area information and polygons.',
long_description=read_file('README.rst'),
author='mySociety',
author_email='mapit@mysociety.org',
url='https://github.com/mysociety/mapit',
license='LICENSE.txt',
packages=find_packages(exclude=['project']),
scripts = [ 'bin/mapit_make_css', 'bin/mapit_osm_to_kml' ],
include_package_data=True,
install_requires=install_requires(),
classifiers=[
'Development Status :: 5 - Production/Stable',
'Environment :: Web Environment',
'Framework :: Django',
'License :: OSI Approved :: GNU Affero General Public License v3',
'Intended Audience :: Developers',
'Programming Language :: Python',
'Topic :: Database :: Front-Ends',
'Topic :: Internet :: WWW/HTTP',
'Topic :: Scientific/Engineering :: GIS',
],
zip_safe=False, # So that easy_install doesn't make an egg
)
| agpl-3.0 |
t0in4/django | django/contrib/gis/gdal/prototypes/raster.py | 320 | 4013 | """
This module houses the ctypes function prototypes for GDAL DataSource (raster)
related data structures.
"""
from ctypes import POINTER, c_char_p, c_double, c_int, c_void_p
from functools import partial
from django.contrib.gis.gdal.libgdal import GDAL_VERSION, std_call
from django.contrib.gis.gdal.prototypes.generation import (
const_string_output, double_output, int_output, void_output,
voidptr_output,
)
# For more detail about c function names and definitions see
# http://gdal.org/gdal_8h.html
# http://gdal.org/gdalwarper_8h.html
# Prepare partial functions that use cpl error codes
void_output = partial(void_output, cpl=True)
const_string_output = partial(const_string_output, cpl=True)
double_output = partial(double_output, cpl=True)
# Raster Driver Routines
register_all = void_output(std_call('GDALAllRegister'), [])
get_driver = voidptr_output(std_call('GDALGetDriver'), [c_int])
get_driver_by_name = voidptr_output(std_call('GDALGetDriverByName'), [c_char_p], errcheck=False)
get_driver_count = int_output(std_call('GDALGetDriverCount'), [])
get_driver_description = const_string_output(std_call('GDALGetDescription'), [c_void_p])
# Raster Data Source Routines
create_ds = voidptr_output(std_call('GDALCreate'), [c_void_p, c_char_p, c_int, c_int, c_int, c_int, c_void_p])
open_ds = voidptr_output(std_call('GDALOpen'), [c_char_p, c_int])
if GDAL_VERSION >= (2, 0):
close_ds = voidptr_output(std_call('GDALClose'), [c_void_p])
else:
close_ds = void_output(std_call('GDALClose'), [c_void_p])
flush_ds = int_output(std_call('GDALFlushCache'), [c_void_p])
copy_ds = voidptr_output(std_call('GDALCreateCopy'),
[c_void_p, c_char_p, c_void_p, c_int, POINTER(c_char_p), c_void_p, c_void_p]
)
add_band_ds = void_output(std_call('GDALAddBand'), [c_void_p, c_int])
get_ds_description = const_string_output(std_call('GDALGetDescription'), [c_void_p])
get_ds_driver = voidptr_output(std_call('GDALGetDatasetDriver'), [c_void_p])
get_ds_xsize = int_output(std_call('GDALGetRasterXSize'), [c_void_p])
get_ds_ysize = int_output(std_call('GDALGetRasterYSize'), [c_void_p])
get_ds_raster_count = int_output(std_call('GDALGetRasterCount'), [c_void_p])
get_ds_raster_band = voidptr_output(std_call('GDALGetRasterBand'), [c_void_p, c_int])
get_ds_projection_ref = const_string_output(std_call('GDALGetProjectionRef'), [c_void_p])
set_ds_projection_ref = void_output(std_call('GDALSetProjection'), [c_void_p, c_char_p])
get_ds_geotransform = void_output(std_call('GDALGetGeoTransform'), [c_void_p, POINTER(c_double * 6)], errcheck=False)
set_ds_geotransform = void_output(std_call('GDALSetGeoTransform'), [c_void_p, POINTER(c_double * 6)])
# Raster Band Routines
band_io = void_output(std_call('GDALRasterIO'),
[c_void_p, c_int, c_int, c_int, c_int, c_int, c_void_p, c_int, c_int, c_int, c_int, c_int]
)
get_band_xsize = int_output(std_call('GDALGetRasterBandXSize'), [c_void_p])
get_band_ysize = int_output(std_call('GDALGetRasterBandYSize'), [c_void_p])
get_band_index = int_output(std_call('GDALGetBandNumber'), [c_void_p])
get_band_description = const_string_output(std_call('GDALGetDescription'), [c_void_p])
get_band_ds = voidptr_output(std_call('GDALGetBandDataset'), [c_void_p])
get_band_datatype = int_output(std_call('GDALGetRasterDataType'), [c_void_p])
get_band_nodata_value = double_output(std_call('GDALGetRasterNoDataValue'), [c_void_p, POINTER(c_int)])
set_band_nodata_value = void_output(std_call('GDALSetRasterNoDataValue'), [c_void_p, c_double])
get_band_minimum = double_output(std_call('GDALGetRasterMinimum'), [c_void_p, POINTER(c_int)])
get_band_maximum = double_output(std_call('GDALGetRasterMaximum'), [c_void_p, POINTER(c_int)])
# Reprojection routine
reproject_image = void_output(std_call('GDALReprojectImage'),
[c_void_p, c_char_p, c_void_p, c_char_p, c_int, c_double, c_double, c_void_p, c_void_p, c_void_p]
)
auto_create_warped_vrt = voidptr_output(std_call('GDALAutoCreateWarpedVRT'),
[c_void_p, c_char_p, c_char_p, c_int, c_double, c_void_p]
)
| bsd-3-clause |
liorvh/phantomjs | src/qt/qtwebkit/Tools/Scripts/webkitpy/tool/steps/closebugforlanddiff_unittest.py | 122 | 2151 | # Copyright (C) 2009 Google Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following disclaimer
# in the documentation and/or other materials provided with the
# distribution.
# * Neither the name of Google Inc. nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import unittest2 as unittest
from webkitpy.common.system.outputcapture import OutputCapture
from webkitpy.tool.mocktool import MockOptions, MockTool
from webkitpy.tool.steps.closebugforlanddiff import CloseBugForLandDiff
class CloseBugForLandDiffTest(unittest.TestCase):
def test_empty_state(self):
capture = OutputCapture()
step = CloseBugForLandDiff(MockTool(), MockOptions())
expected_logs = "Committed r49824: <http://trac.webkit.org/changeset/49824>\nNo bug id provided.\n"
capture.assert_outputs(self, step.run, [{"commit_text": "Mock commit text"}], expected_logs=expected_logs)
| bsd-3-clause |
Grogdor/CouchPotatoServer | libs/six.py | 322 | 22857 | """Utilities for writing code that runs on Python 2 and 3"""
# Copyright (c) 2010-2014 Benjamin Peterson
#
# 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.
import operator
import sys
import types
__author__ = "Benjamin Peterson <benjamin@python.org>"
__version__ = "1.5.2"
# Useful for very coarse version differentiation.
PY2 = sys.version_info[0] == 2
PY3 = sys.version_info[0] == 3
if PY3:
string_types = str,
integer_types = int,
class_types = type,
text_type = str
binary_type = bytes
MAXSIZE = sys.maxsize
else:
string_types = basestring,
integer_types = (int, long)
class_types = (type, types.ClassType)
text_type = unicode
binary_type = str
if sys.platform.startswith("java"):
# Jython always uses 32 bits.
MAXSIZE = int((1 << 31) - 1)
else:
# It's possible to have sizeof(long) != sizeof(Py_ssize_t).
class X(object):
def __len__(self):
return 1 << 31
try:
len(X())
except OverflowError:
# 32-bit
MAXSIZE = int((1 << 31) - 1)
else:
# 64-bit
MAXSIZE = int((1 << 63) - 1)
del X
def _add_doc(func, doc):
"""Add documentation to a function."""
func.__doc__ = doc
def _import_module(name):
"""Import module, returning the module after the last dot."""
__import__(name)
return sys.modules[name]
class _LazyDescr(object):
def __init__(self, name):
self.name = name
def __get__(self, obj, tp):
result = self._resolve()
setattr(obj, self.name, result) # Invokes __set__.
# This is a bit ugly, but it avoids running this again.
delattr(obj.__class__, self.name)
return result
class MovedModule(_LazyDescr):
def __init__(self, name, old, new=None):
super(MovedModule, self).__init__(name)
if PY3:
if new is None:
new = name
self.mod = new
else:
self.mod = old
def _resolve(self):
return _import_module(self.mod)
def __getattr__(self, attr):
# Hack around the Django autoreloader. The reloader tries to get
# __file__ or __name__ of every module in sys.modules. This doesn't work
# well if this MovedModule is for an module that is unavailable on this
# machine (like winreg on Unix systems). Thus, we pretend __file__ and
# __name__ don't exist if the module hasn't been loaded yet. See issues
# #51 and #53.
if attr in ("__file__", "__name__") and self.mod not in sys.modules:
raise AttributeError
_module = self._resolve()
value = getattr(_module, attr)
setattr(self, attr, value)
return value
class _LazyModule(types.ModuleType):
def __init__(self, name):
super(_LazyModule, self).__init__(name)
self.__doc__ = self.__class__.__doc__
def __dir__(self):
attrs = ["__doc__", "__name__"]
attrs += [attr.name for attr in self._moved_attributes]
return attrs
# Subclasses should override this
_moved_attributes = []
class MovedAttribute(_LazyDescr):
def __init__(self, name, old_mod, new_mod, old_attr=None, new_attr=None):
super(MovedAttribute, self).__init__(name)
if PY3:
if new_mod is None:
new_mod = name
self.mod = new_mod
if new_attr is None:
if old_attr is None:
new_attr = name
else:
new_attr = old_attr
self.attr = new_attr
else:
self.mod = old_mod
if old_attr is None:
old_attr = name
self.attr = old_attr
def _resolve(self):
module = _import_module(self.mod)
return getattr(module, self.attr)
class _MovedItems(_LazyModule):
"""Lazy loading of moved objects"""
_moved_attributes = [
MovedAttribute("cStringIO", "cStringIO", "io", "StringIO"),
MovedAttribute("filter", "itertools", "builtins", "ifilter", "filter"),
MovedAttribute("filterfalse", "itertools", "itertools", "ifilterfalse", "filterfalse"),
MovedAttribute("input", "__builtin__", "builtins", "raw_input", "input"),
MovedAttribute("map", "itertools", "builtins", "imap", "map"),
MovedAttribute("range", "__builtin__", "builtins", "xrange", "range"),
MovedAttribute("reload_module", "__builtin__", "imp", "reload"),
MovedAttribute("reduce", "__builtin__", "functools"),
MovedAttribute("StringIO", "StringIO", "io"),
MovedAttribute("UserString", "UserString", "collections"),
MovedAttribute("xrange", "__builtin__", "builtins", "xrange", "range"),
MovedAttribute("zip", "itertools", "builtins", "izip", "zip"),
MovedAttribute("zip_longest", "itertools", "itertools", "izip_longest", "zip_longest"),
MovedModule("builtins", "__builtin__"),
MovedModule("configparser", "ConfigParser"),
MovedModule("copyreg", "copy_reg"),
MovedModule("dbm_gnu", "gdbm", "dbm.gnu"),
MovedModule("http_cookiejar", "cookielib", "http.cookiejar"),
MovedModule("http_cookies", "Cookie", "http.cookies"),
MovedModule("html_entities", "htmlentitydefs", "html.entities"),
MovedModule("html_parser", "HTMLParser", "html.parser"),
MovedModule("http_client", "httplib", "http.client"),
MovedModule("email_mime_multipart", "email.MIMEMultipart", "email.mime.multipart"),
MovedModule("email_mime_text", "email.MIMEText", "email.mime.text"),
MovedModule("email_mime_base", "email.MIMEBase", "email.mime.base"),
MovedModule("BaseHTTPServer", "BaseHTTPServer", "http.server"),
MovedModule("CGIHTTPServer", "CGIHTTPServer", "http.server"),
MovedModule("SimpleHTTPServer", "SimpleHTTPServer", "http.server"),
MovedModule("cPickle", "cPickle", "pickle"),
MovedModule("queue", "Queue"),
MovedModule("reprlib", "repr"),
MovedModule("socketserver", "SocketServer"),
MovedModule("_thread", "thread", "_thread"),
MovedModule("tkinter", "Tkinter"),
MovedModule("tkinter_dialog", "Dialog", "tkinter.dialog"),
MovedModule("tkinter_filedialog", "FileDialog", "tkinter.filedialog"),
MovedModule("tkinter_scrolledtext", "ScrolledText", "tkinter.scrolledtext"),
MovedModule("tkinter_simpledialog", "SimpleDialog", "tkinter.simpledialog"),
MovedModule("tkinter_tix", "Tix", "tkinter.tix"),
MovedModule("tkinter_ttk", "ttk", "tkinter.ttk"),
MovedModule("tkinter_constants", "Tkconstants", "tkinter.constants"),
MovedModule("tkinter_dnd", "Tkdnd", "tkinter.dnd"),
MovedModule("tkinter_colorchooser", "tkColorChooser",
"tkinter.colorchooser"),
MovedModule("tkinter_commondialog", "tkCommonDialog",
"tkinter.commondialog"),
MovedModule("tkinter_tkfiledialog", "tkFileDialog", "tkinter.filedialog"),
MovedModule("tkinter_font", "tkFont", "tkinter.font"),
MovedModule("tkinter_messagebox", "tkMessageBox", "tkinter.messagebox"),
MovedModule("tkinter_tksimpledialog", "tkSimpleDialog",
"tkinter.simpledialog"),
MovedModule("urllib_parse", __name__ + ".moves.urllib_parse", "urllib.parse"),
MovedModule("urllib_error", __name__ + ".moves.urllib_error", "urllib.error"),
MovedModule("urllib", __name__ + ".moves.urllib", __name__ + ".moves.urllib"),
MovedModule("urllib_robotparser", "robotparser", "urllib.robotparser"),
MovedModule("xmlrpc_client", "xmlrpclib", "xmlrpc.client"),
MovedModule("winreg", "_winreg"),
]
for attr in _moved_attributes:
setattr(_MovedItems, attr.name, attr)
if isinstance(attr, MovedModule):
sys.modules[__name__ + ".moves." + attr.name] = attr
del attr
_MovedItems._moved_attributes = _moved_attributes
moves = sys.modules[__name__ + ".moves"] = _MovedItems(__name__ + ".moves")
class Module_six_moves_urllib_parse(_LazyModule):
"""Lazy loading of moved objects in six.moves.urllib_parse"""
_urllib_parse_moved_attributes = [
MovedAttribute("ParseResult", "urlparse", "urllib.parse"),
MovedAttribute("parse_qs", "urlparse", "urllib.parse"),
MovedAttribute("parse_qsl", "urlparse", "urllib.parse"),
MovedAttribute("urldefrag", "urlparse", "urllib.parse"),
MovedAttribute("urljoin", "urlparse", "urllib.parse"),
MovedAttribute("urlparse", "urlparse", "urllib.parse"),
MovedAttribute("urlsplit", "urlparse", "urllib.parse"),
MovedAttribute("urlunparse", "urlparse", "urllib.parse"),
MovedAttribute("urlunsplit", "urlparse", "urllib.parse"),
MovedAttribute("quote", "urllib", "urllib.parse"),
MovedAttribute("quote_plus", "urllib", "urllib.parse"),
MovedAttribute("unquote", "urllib", "urllib.parse"),
MovedAttribute("unquote_plus", "urllib", "urllib.parse"),
MovedAttribute("urlencode", "urllib", "urllib.parse"),
]
for attr in _urllib_parse_moved_attributes:
setattr(Module_six_moves_urllib_parse, attr.name, attr)
del attr
Module_six_moves_urllib_parse._moved_attributes = _urllib_parse_moved_attributes
sys.modules[__name__ + ".moves.urllib_parse"] = sys.modules[__name__ + ".moves.urllib.parse"] = Module_six_moves_urllib_parse(__name__ + ".moves.urllib_parse")
class Module_six_moves_urllib_error(_LazyModule):
"""Lazy loading of moved objects in six.moves.urllib_error"""
_urllib_error_moved_attributes = [
MovedAttribute("URLError", "urllib2", "urllib.error"),
MovedAttribute("HTTPError", "urllib2", "urllib.error"),
MovedAttribute("ContentTooShortError", "urllib", "urllib.error"),
]
for attr in _urllib_error_moved_attributes:
setattr(Module_six_moves_urllib_error, attr.name, attr)
del attr
Module_six_moves_urllib_error._moved_attributes = _urllib_error_moved_attributes
sys.modules[__name__ + ".moves.urllib_error"] = sys.modules[__name__ + ".moves.urllib.error"] = Module_six_moves_urllib_error(__name__ + ".moves.urllib.error")
class Module_six_moves_urllib_request(_LazyModule):
"""Lazy loading of moved objects in six.moves.urllib_request"""
_urllib_request_moved_attributes = [
MovedAttribute("urlopen", "urllib2", "urllib.request"),
MovedAttribute("install_opener", "urllib2", "urllib.request"),
MovedAttribute("build_opener", "urllib2", "urllib.request"),
MovedAttribute("pathname2url", "urllib", "urllib.request"),
MovedAttribute("url2pathname", "urllib", "urllib.request"),
MovedAttribute("getproxies", "urllib", "urllib.request"),
MovedAttribute("Request", "urllib2", "urllib.request"),
MovedAttribute("OpenerDirector", "urllib2", "urllib.request"),
MovedAttribute("HTTPDefaultErrorHandler", "urllib2", "urllib.request"),
MovedAttribute("HTTPRedirectHandler", "urllib2", "urllib.request"),
MovedAttribute("HTTPCookieProcessor", "urllib2", "urllib.request"),
MovedAttribute("ProxyHandler", "urllib2", "urllib.request"),
MovedAttribute("BaseHandler", "urllib2", "urllib.request"),
MovedAttribute("HTTPPasswordMgr", "urllib2", "urllib.request"),
MovedAttribute("HTTPPasswordMgrWithDefaultRealm", "urllib2", "urllib.request"),
MovedAttribute("AbstractBasicAuthHandler", "urllib2", "urllib.request"),
MovedAttribute("HTTPBasicAuthHandler", "urllib2", "urllib.request"),
MovedAttribute("ProxyBasicAuthHandler", "urllib2", "urllib.request"),
MovedAttribute("AbstractDigestAuthHandler", "urllib2", "urllib.request"),
MovedAttribute("HTTPDigestAuthHandler", "urllib2", "urllib.request"),
MovedAttribute("ProxyDigestAuthHandler", "urllib2", "urllib.request"),
MovedAttribute("HTTPHandler", "urllib2", "urllib.request"),
MovedAttribute("HTTPSHandler", "urllib2", "urllib.request"),
MovedAttribute("FileHandler", "urllib2", "urllib.request"),
MovedAttribute("FTPHandler", "urllib2", "urllib.request"),
MovedAttribute("CacheFTPHandler", "urllib2", "urllib.request"),
MovedAttribute("UnknownHandler", "urllib2", "urllib.request"),
MovedAttribute("HTTPErrorProcessor", "urllib2", "urllib.request"),
MovedAttribute("urlretrieve", "urllib", "urllib.request"),
MovedAttribute("urlcleanup", "urllib", "urllib.request"),
MovedAttribute("URLopener", "urllib", "urllib.request"),
MovedAttribute("FancyURLopener", "urllib", "urllib.request"),
MovedAttribute("proxy_bypass", "urllib", "urllib.request"),
]
for attr in _urllib_request_moved_attributes:
setattr(Module_six_moves_urllib_request, attr.name, attr)
del attr
Module_six_moves_urllib_request._moved_attributes = _urllib_request_moved_attributes
sys.modules[__name__ + ".moves.urllib_request"] = sys.modules[__name__ + ".moves.urllib.request"] = Module_six_moves_urllib_request(__name__ + ".moves.urllib.request")
class Module_six_moves_urllib_response(_LazyModule):
"""Lazy loading of moved objects in six.moves.urllib_response"""
_urllib_response_moved_attributes = [
MovedAttribute("addbase", "urllib", "urllib.response"),
MovedAttribute("addclosehook", "urllib", "urllib.response"),
MovedAttribute("addinfo", "urllib", "urllib.response"),
MovedAttribute("addinfourl", "urllib", "urllib.response"),
]
for attr in _urllib_response_moved_attributes:
setattr(Module_six_moves_urllib_response, attr.name, attr)
del attr
Module_six_moves_urllib_response._moved_attributes = _urllib_response_moved_attributes
sys.modules[__name__ + ".moves.urllib_response"] = sys.modules[__name__ + ".moves.urllib.response"] = Module_six_moves_urllib_response(__name__ + ".moves.urllib.response")
class Module_six_moves_urllib_robotparser(_LazyModule):
"""Lazy loading of moved objects in six.moves.urllib_robotparser"""
_urllib_robotparser_moved_attributes = [
MovedAttribute("RobotFileParser", "robotparser", "urllib.robotparser"),
]
for attr in _urllib_robotparser_moved_attributes:
setattr(Module_six_moves_urllib_robotparser, attr.name, attr)
del attr
Module_six_moves_urllib_robotparser._moved_attributes = _urllib_robotparser_moved_attributes
sys.modules[__name__ + ".moves.urllib_robotparser"] = sys.modules[__name__ + ".moves.urllib.robotparser"] = Module_six_moves_urllib_robotparser(__name__ + ".moves.urllib.robotparser")
class Module_six_moves_urllib(types.ModuleType):
"""Create a six.moves.urllib namespace that resembles the Python 3 namespace"""
parse = sys.modules[__name__ + ".moves.urllib_parse"]
error = sys.modules[__name__ + ".moves.urllib_error"]
request = sys.modules[__name__ + ".moves.urllib_request"]
response = sys.modules[__name__ + ".moves.urllib_response"]
robotparser = sys.modules[__name__ + ".moves.urllib_robotparser"]
def __dir__(self):
return ['parse', 'error', 'request', 'response', 'robotparser']
sys.modules[__name__ + ".moves.urllib"] = Module_six_moves_urllib(__name__ + ".moves.urllib")
def add_move(move):
"""Add an item to six.moves."""
setattr(_MovedItems, move.name, move)
def remove_move(name):
"""Remove item from six.moves."""
try:
delattr(_MovedItems, name)
except AttributeError:
try:
del moves.__dict__[name]
except KeyError:
raise AttributeError("no such move, %r" % (name,))
if PY3:
_meth_func = "__func__"
_meth_self = "__self__"
_func_closure = "__closure__"
_func_code = "__code__"
_func_defaults = "__defaults__"
_func_globals = "__globals__"
_iterkeys = "keys"
_itervalues = "values"
_iteritems = "items"
_iterlists = "lists"
else:
_meth_func = "im_func"
_meth_self = "im_self"
_func_closure = "func_closure"
_func_code = "func_code"
_func_defaults = "func_defaults"
_func_globals = "func_globals"
_iterkeys = "iterkeys"
_itervalues = "itervalues"
_iteritems = "iteritems"
_iterlists = "iterlists"
try:
advance_iterator = next
except NameError:
def advance_iterator(it):
return it.next()
next = advance_iterator
try:
callable = callable
except NameError:
def callable(obj):
return any("__call__" in klass.__dict__ for klass in type(obj).__mro__)
if PY3:
def get_unbound_function(unbound):
return unbound
create_bound_method = types.MethodType
Iterator = object
else:
def get_unbound_function(unbound):
return unbound.im_func
def create_bound_method(func, obj):
return types.MethodType(func, obj, obj.__class__)
class Iterator(object):
def next(self):
return type(self).__next__(self)
callable = callable
_add_doc(get_unbound_function,
"""Get the function out of a possibly unbound function""")
get_method_function = operator.attrgetter(_meth_func)
get_method_self = operator.attrgetter(_meth_self)
get_function_closure = operator.attrgetter(_func_closure)
get_function_code = operator.attrgetter(_func_code)
get_function_defaults = operator.attrgetter(_func_defaults)
get_function_globals = operator.attrgetter(_func_globals)
def iterkeys(d, **kw):
"""Return an iterator over the keys of a dictionary."""
return iter(getattr(d, _iterkeys)(**kw))
def itervalues(d, **kw):
"""Return an iterator over the values of a dictionary."""
return iter(getattr(d, _itervalues)(**kw))
def iteritems(d, **kw):
"""Return an iterator over the (key, value) pairs of a dictionary."""
return iter(getattr(d, _iteritems)(**kw))
def iterlists(d, **kw):
"""Return an iterator over the (key, [values]) pairs of a dictionary."""
return iter(getattr(d, _iterlists)(**kw))
if PY3:
def b(s):
return s.encode("latin-1")
def u(s):
return s
unichr = chr
if sys.version_info[1] <= 1:
def int2byte(i):
return bytes((i,))
else:
# This is about 2x faster than the implementation above on 3.2+
int2byte = operator.methodcaller("to_bytes", 1, "big")
byte2int = operator.itemgetter(0)
indexbytes = operator.getitem
iterbytes = iter
import io
StringIO = io.StringIO
BytesIO = io.BytesIO
else:
def b(s):
return s
# Workaround for standalone backslash
def u(s):
return unicode(s.replace(r'\\', r'\\\\'), "unicode_escape")
unichr = unichr
int2byte = chr
def byte2int(bs):
return ord(bs[0])
def indexbytes(buf, i):
return ord(buf[i])
def iterbytes(buf):
return (ord(byte) for byte in buf)
import StringIO
StringIO = BytesIO = StringIO.StringIO
_add_doc(b, """Byte literal""")
_add_doc(u, """Text literal""")
if PY3:
exec_ = getattr(moves.builtins, "exec")
def reraise(tp, value, tb=None):
if value.__traceback__ is not tb:
raise value.with_traceback(tb)
raise value
else:
def exec_(_code_, _globs_=None, _locs_=None):
"""Execute code in a namespace."""
if _globs_ is None:
frame = sys._getframe(1)
_globs_ = frame.f_globals
if _locs_ is None:
_locs_ = frame.f_locals
del frame
elif _locs_ is None:
_locs_ = _globs_
exec("""exec _code_ in _globs_, _locs_""")
exec_("""def reraise(tp, value, tb=None):
raise tp, value, tb
""")
print_ = getattr(moves.builtins, "print", None)
if print_ is None:
def print_(*args, **kwargs):
"""The new-style print function for Python 2.4 and 2.5."""
fp = kwargs.pop("file", sys.stdout)
if fp is None:
return
def write(data):
if not isinstance(data, basestring):
data = str(data)
# If the file has an encoding, encode unicode with it.
if (isinstance(fp, file) and
isinstance(data, unicode) and
fp.encoding is not None):
errors = getattr(fp, "errors", None)
if errors is None:
errors = "strict"
data = data.encode(fp.encoding, errors)
fp.write(data)
want_unicode = False
sep = kwargs.pop("sep", None)
if sep is not None:
if isinstance(sep, unicode):
want_unicode = True
elif not isinstance(sep, str):
raise TypeError("sep must be None or a string")
end = kwargs.pop("end", None)
if end is not None:
if isinstance(end, unicode):
want_unicode = True
elif not isinstance(end, str):
raise TypeError("end must be None or a string")
if kwargs:
raise TypeError("invalid keyword arguments to print()")
if not want_unicode:
for arg in args:
if isinstance(arg, unicode):
want_unicode = True
break
if want_unicode:
newline = unicode("\n")
space = unicode(" ")
else:
newline = "\n"
space = " "
if sep is None:
sep = space
if end is None:
end = newline
for i, arg in enumerate(args):
if i:
write(sep)
write(arg)
write(end)
_add_doc(reraise, """Reraise an exception.""")
def with_metaclass(meta, *bases):
"""Create a base class with a metaclass."""
return meta("NewBase", bases, {})
def add_metaclass(metaclass):
"""Class decorator for creating a class with a metaclass."""
def wrapper(cls):
orig_vars = cls.__dict__.copy()
orig_vars.pop('__dict__', None)
orig_vars.pop('__weakref__', None)
slots = orig_vars.get('__slots__')
if slots is not None:
if isinstance(slots, str):
slots = [slots]
for slots_var in slots:
orig_vars.pop(slots_var)
return metaclass(cls.__name__, cls.__bases__, orig_vars)
return wrapper
| gpl-3.0 |
HackerExperience/asynqp | src/asynqp/routing.py | 1 | 3385 | import asyncio
import collections
from . import frames
from . import spec
_TEST = False
class Dispatcher(object):
def __init__(self):
self.queue_writers = {}
self.closing = asyncio.Future()
def add_writer(self, channel_id, writer):
self.queue_writers[channel_id] = writer
def remove_writer(self, channel_id):
del self.queue_writers[channel_id]
def dispatch(self, frame):
if isinstance(frame, frames.HeartbeatFrame):
return
if self.closing.done() and not isinstance(frame.payload, (spec.ConnectionClose, spec.ConnectionCloseOK)):
return
writer = self.queue_writers[frame.channel_id]
writer.enqueue(frame)
class Synchroniser(object):
def __init__(self):
self._futures = OrderedManyToManyMap()
def await(self, *expected_methods):
fut = asyncio.Future()
self._futures.add_item(expected_methods, fut)
return fut
def notify(self, method, result=None):
fut = self._futures.get_leftmost(method)
fut.set_result(result)
self._futures.remove_item(fut)
def create_reader_and_writer(handler):
q = asyncio.Queue()
reader = QueueReader(handler, q)
writer = QueueWriter(q)
return reader, writer
# When ready() is called, wait for a frame to arrive on the queue.
# When the frame does arrive, dispatch it to the handler and do nothing
# until someone calls ready() again.
class QueueReader(object):
def __init__(self, handler, q):
self.handler = handler
self.q = q
self.is_waiting = False
def ready(self):
assert not self.is_waiting, "ready() got called while waiting for a frame to be read"
self.is_waiting = True
t = asyncio.async(self._read_next())
if _TEST: # this feels hacky to me
t._log_destroy_pending = False
@asyncio.coroutine
def _read_next(self):
assert self.is_waiting, "a frame got read without ready() having been called"
frame = yield from self.q.get()
self.is_waiting = False
self.handler.handle(frame)
class QueueWriter(object):
def __init__(self, q):
self.q = q
def enqueue(self, frame):
self.q.put_nowait(frame)
class OrderedManyToManyMap(object):
def __init__(self):
self._items = collections.defaultdict(OrderedSet)
def add_item(self, keys, item):
for key in keys:
self._items[key].add(item)
def remove_item(self, item):
for ordered_set in self._items.values():
ordered_set.discard(item)
def get_leftmost(self, key):
return self._items[key].first()
class OrderedSet(collections.MutableSet):
def __init__(self):
self._map = collections.OrderedDict()
def __contains__(self, item):
return item in self._map
def __iter__(self):
return iter(self._map.keys())
def __getitem__(self, ix):
return
def __len__(self):
return len(self._map)
def add(self, item):
self._map[item] = None
def discard(self, item):
try:
del self._map[item]
except KeyError:
pass
def first(self):
return next(iter(self._map))
| mit |
gklyne/annalist | src/annalist_root/annalist/tests/test_entityeditdupfield.py | 1 | 12005 | from __future__ import unicode_literals
from __future__ import absolute_import, division, print_function
"""
Entity editing tests for duplicated fields
"""
__author__ = "Graham Klyne (GK@ACM.ORG)"
__copyright__ = "Copyright 2014, G. Klyne"
__license__ = "MIT (http://opensource.org/licenses/MIT)"
import os
import unittest
import logging
log = logging.getLogger(__name__)
from django.conf import settings
from django.db import models
from django.http import QueryDict
from django.contrib.auth.models import User
from django.test import TestCase # cf. https://docs.djangoproject.com/en/dev/topics/testing/tools/#assertions
from django.test.client import Client
from utils.SuppressLoggingContext import SuppressLogging
from annalist.identifiers import RDF, RDFS, ANNAL
from annalist import layout
from annalist.models.entitytypeinfo import EntityTypeInfo
from annalist.models.site import Site
from annalist.models.collection import Collection
from annalist.models.recordtype import RecordType
from annalist.models.recordlist import RecordList
from annalist.models.recordview import RecordView
from annalist.models.recordfield import RecordField
from annalist.models.recordtypedata import RecordTypeData
from annalist.models.entitydata import EntityData
from annalist.views.form_utils.fieldchoice import FieldChoice
from .AnnalistTestCase import AnnalistTestCase
from .tests import (
test_layout,
TestHost, TestHostUri, TestBasePath, TestBaseUri, TestBaseDir
)
from .init_tests import (
init_annalist_test_site, init_annalist_test_coll, resetSitedata
)
from .entity_testfielddesc import get_field_description, get_bound_field
from .entity_testutils import (
collection_create_values,
continuation_url_param,
create_test_user,
context_view_field,
context_bind_fields,
context_field_row
)
from .entity_testtypedata import (
recordtype_url,
recordtype_edit_url,
recordtype_create_values,
)
from .entity_testviewdata import (
recordview_url,
recordview_create_values, recordview_values, recordview_values_add_field,
)
from .entity_testentitydata import (
entity_url, entitydata_edit_url,
entitydata_value_keys,
entitydata_create_values, entitydata_values, entitydata_values_add_field,
default_view_form_data, entitydata_form_add_field,
default_view_context_data,
default_comment
)
from .entity_testsitedata import (
get_site_types, get_site_types_sorted, get_site_types_linked,
get_site_lists, get_site_lists_sorted,
get_site_list_types, get_site_list_types_sorted,
get_site_views, get_site_views_sorted,
get_site_field_groups, get_site_field_groups_sorted,
get_site_fields, get_site_fields_sorted,
get_site_field_types, get_site_field_types_sorted,
)
# -----------------------------------------------------------------------------
#
# Helper function to buiold tyest context value
#
# -----------------------------------------------------------------------------
def dupfield_view_context_data(
entity_id=None, orig_id=None,
coll_id="testcoll", type_id="testtype",
type_ref=None, type_choices=None, type_ids=[],
entity_label=None,
entity_descr=None,
entity_descr2=None,
entity_descr3=None,
record_type="annal:EntityData",
action=None, update="Entity", view_label="RecordView testcoll/DupField_view",
continuation_url=None
):
context_dict = default_view_context_data(
entity_id=entity_id, orig_id=orig_id,
coll_id=coll_id, type_id=type_id,
type_ref=type_ref, type_choices=type_choices, type_ids=type_ids,
entity_label=entity_label, entity_descr=entity_descr,
record_type=record_type,
action=action, update=update, view_label=view_label,
continuation_url=continuation_url
)
context_dict['fields'].append(
context_field_row(
get_bound_field("Entity_comment", entity_descr2,
name="Entity_comment__2",
prop_uri="rdfs:comment__2"
)
)
)
context_dict['fields'].append(
context_field_row(
get_bound_field("Entity_comment", entity_descr3,
name="Entity_comment__3",
prop_uri="rdfs:comment_alt"
)
)
)
return context_dict
# -----------------------------------------------------------------------------
#
# Entity edit duplicated field tests
#
# -----------------------------------------------------------------------------
class EntityEditDupFieldTest(AnnalistTestCase):
def setUp(self):
init_annalist_test_site()
self.testsite = Site(TestBaseUri, TestBaseDir)
self.testcoll = Collection.create(self.testsite, "testcoll",
collection_create_values("testcoll")
)
self.testtype = RecordType.create(self.testcoll, "testtype",
recordtype_create_values("testcoll", "testtype")
)
self.testdata = RecordTypeData.create(self.testcoll, "testtype", {})
# Create view with repeated field id
self.viewdata = recordview_create_values(view_id="DupField_view")
recordview_values_add_field(
self.viewdata,
field_id="Entity_comment",
field_placement="small:0,12"
)
recordview_values_add_field(
self.viewdata,
field_id="Entity_comment",
field_property_uri="rdfs:comment_alt",
field_placement="small:0,12"
)
self.testview = RecordView.create(self.testcoll, "DupField_view", self.viewdata)
# Other data
self.type_ids = get_site_types_linked("testcoll")
self.type_ids.append(FieldChoice("_type/testtype",
label="RecordType testcoll/_type/testtype",
link=recordtype_url("testcoll", "testtype")
))
# Login and permissions
create_test_user(self.testcoll, "testuser", "testpassword")
self.client = Client(HTTP_HOST=TestHost)
loggedin = self.client.login(username="testuser", password="testpassword")
self.assertTrue(loggedin)
return
def tearDown(self):
# resetSitedata(scope="collections")
return
@classmethod
def tearDownClass(cls):
return
@classmethod
def tearDownClass(cls):
super(EntityEditDupFieldTest, cls).tearDownClass()
resetSitedata(scope="collections") #@@checkme@@
return
# -----------------------------------------------------------------------------
# Helpers
# -----------------------------------------------------------------------------
def _check_record_view_values(self, view_id, view_values):
"Helper function checks content of record view entry with supplied view_id"
self.assertTrue(RecordView.exists(self.testcoll, view_id))
t = RecordView.load(self.testcoll, view_id)
self.assertEqual(t.get_id(), view_id)
self.assertDictionaryMatch(t.get_values(), view_values)
return t
def _create_entity_data(self,
entity_id, type_id="testtype", update="Entity",
comment2="Comment field 2",
comment3="Comment field 3"
):
"Helper function creates entity data with supplied entity_id"
v = entitydata_create_values(entity_id, type_id=type_id, update=update)
v = entitydata_values_add_field(v, "rdfs:comment", 2, comment2)
v = entitydata_values_add_field(v, "rdfs:comment_alt", 3, comment3)
e = EntityData.create(self.testdata, entity_id, v)
return e
def _check_entity_data_values(self,
entity_id, type_id="testtype", update="Entity",
comment2="Comment field 2",
comment3="Comment field 3"
):
"Helper function checks content of form-updated record type entry with supplied entity_id"
# log.info("_check_entity_data_values: type_id %s, entity_id %s"%(type_id, entity_id))
typeinfo = EntityTypeInfo(self.testcoll, type_id)
self.assertTrue(typeinfo.entityclass.exists(typeinfo.entityparent, entity_id))
e = typeinfo.entityclass.load(typeinfo.entityparent, entity_id)
self.assertEqual(e.get_id(), entity_id)
v = entitydata_values(entity_id, type_id=type_id, update=update)
v = entitydata_values_add_field(v, "rdfs:comment", 2, comment2)
v = entitydata_values_add_field(v, "rdfs:comment_alt", 3, comment3)
self.assertDictionaryMatch(e.get_values(), v)
return e
# -----------------------------------------------------------------------------
# Form response tests
# -----------------------------------------------------------------------------
def test_view_dup_field_values(self):
self._check_record_view_values("DupField_view", self.viewdata)
return
def test_dup_field_display(self):
# Create entity with duplicate fields
self._create_entity_data("entitydupfield")
self._check_entity_data_values(
"entitydupfield", type_id="testtype", update="Entity",
comment2="Comment field 2",
comment3="Comment field 3"
)
# Display entity in view with duplicate fields
u = entitydata_edit_url(
"edit", "testcoll", "testtype",
entity_id="entitydupfield",
view_id="DupField_view"
)
r = self.client.get(u)
self.assertEqual(r.status_code, 200)
self.assertEqual(r.reason_phrase, "OK")
# Check display context
expect_context = dupfield_view_context_data(
coll_id="testcoll", type_id="testtype",
entity_id="entitydupfield", orig_id=None,
type_ref="testtype", type_choices=self.type_ids,
entity_label="Entity testcoll/testtype/entitydupfield",
entity_descr="Entity coll testcoll, type testtype, entity entitydupfield",
entity_descr2="Comment field 2",
entity_descr3="Comment field 3",
record_type="/testsite/c/testcoll/d/_type/testtype/",
action="edit",
update="Entity",
continuation_url=""
)
self.assertEqual(len(r.context['fields']), 5)
self.assertDictionaryMatch(context_bind_fields(r.context), expect_context)
def test_dup_field_update(self):
# Create entity with duplicate fields
self._create_entity_data("entitydupfield")
self._check_entity_data_values(
"entitydupfield", type_id="testtype", update="Entity",
comment2="Comment field 2",
comment3="Comment field 3"
)
# Post form data to update entity
u = entitydata_edit_url(
"edit", "testcoll", "testtype",
entity_id="entitydupfield",
view_id="DupField_view"
)
f = default_view_form_data(
entity_id="entitydupfield",
type_id="testtype",
coll_id="testcoll",
action="edit", update="Updated Entity"
)
f = entitydata_form_add_field(f, "Entity_comment", 2, "Update comment 2")
f = entitydata_form_add_field(f, "Entity_comment", 3, "Update comment 3")
r = self.client.post(u, f)
self.assertEqual(r.status_code, 302)
self.assertEqual(r.reason_phrase, "Found")
# Test resulting entity value
self._check_entity_data_values(
"entitydupfield", type_id="testtype", update="Updated Entity",
comment2="Update comment 2",
comment3="Update comment 3"
)
return
# End.
| mit |
kidphys/yakexchange | matching_test.py | 1 | 4549 | import pytest
from matching import SortedOrders
from matching import Order
from matching import Side
from matching import ContinuousMatch
from matching import StaticContinuousMatch
def test_opposite_side():
assert Side.Buy == Side.opposite_of(Side.Sell)
assert Side.Sell == Side.opposite_of(Side.Buy)
def test_empty_when_created():
s = SortedOrders()
assert s.size() == 0
def test_peek_return_none_when_empty():
assert None == SortedOrders().peek()
def test_first_order():
s = SortedOrders()
o = Order(price=16.0)
s.push(o)
assert o == s.peek()
def test_best_price_float_to_top():
s = SortedOrders()
o1 = Order(price=16.0)
o2 = Order(price=15.0)
s.push(o1)
s.push(o2)
assert o1 == s.peek()
def test_late_buy_has_lower_priority():
s = SortedOrders()
o1 = Order(price=16.0)
o2 = Order(price=16.0)
s.push(o1)
s.push(o2)
assert o1 == s.peek()
def test_late_buy_has_higher_priority_than_lower_price():
s = SortedOrders()
o1 = Order(price=16.0)
o2 = Order(price=16.0)
o3 = Order(price=15.0)
s.push(o3)
s.push(o2)
s.push(o1)
assert o2 == s.peek()
def test_low_sell_float_to_the_top():
s = SortedOrders(side=Side.Sell)
o1 = Order(price=16.0)
o2 = Order(price=15.0)
s.push(o1)
s.push(o2)
assert o2 == s.peek()
def test_late_sell_lower_priority():
s = SortedOrders(side=Side.Sell)
o1 = Order(price=16.0)
o2 = Order(price=16.0)
s.push(o1)
s.push(o2)
assert o1 == s.peek()
@pytest.fixture(params=['ContinuousMatch', 'StaticContinuousMatch'])
def matcher(request):
if request.param == 'ContinuousMatch':
return ContinuousMatch()
else:
return StaticContinuousMatch()
def test_match_none_when_have_only_one_order(matcher):
reports = matcher.push(Order(price=16.0, volume=1000, side=Side.Buy))
assert len(reports) == 0
def test_match_one_buy_one_sell(matcher):
matcher.push(Order(price=16.0, volume=1000, side=Side.Buy))
reports = matcher.push(Order(price=16.0, volume=1000, side=Side.Sell))
assert len(reports) == 1
def test_after_full_match_order_is_removed(matcher):
matcher.push(Order(price=16.0, volume=1000, side=Side.Buy))
matcher.push(Order(price=16.0, volume=1000, side=Side.Sell))
assert 0 == matcher.order_count(Side.Buy)
assert 0 == matcher.order_count(Side.Sell)
def test_match_again_after_empty(matcher):
matcher.push(Order(price=16.0, volume=1000, side=Side.Buy))
matcher.push(Order(price=16.0, volume=1000, side=Side.Sell))
matcher.push(Order(price=17.0, volume=500, side=Side.Buy))
reports = matcher.push(Order(price=17.0, volume=500, side=Side.Sell))
assert len(reports) == 1
def test_partial_match_leave_order_in_list(matcher):
matcher.push(Order(price=16.0, volume=500, side=Side.Buy))
matcher.push(Order(price=16.0, volume=1000, side=Side.Sell))
assert 1 == matcher.order_count(Side.Sell)
def test_match_one_buy_two_sell(matcher):
matcher.push(Order(price=16.0, volume=200, side=Side.Sell))
matcher.push(Order(price=16.0, volume=200, side=Side.Sell))
reports = matcher.push(Order(price=16.0, volume=1000, side=Side.Buy))
assert len(reports) == 2
def test_match_with_better_price(matcher):
matcher.push(Order(price=16.0, volume=200, side=Side.Sell))
reports = matcher.push(Order(price=17.0, volume=1000, side=Side.Buy))
assert len(reports) == 1
def test_earlier_order_matched_in_better_price(matcher):
matcher.push(Order(price=16.0, volume=200, side=Side.Sell))
reports = matcher.push(Order(price=17.0, volume=1000, side=Side.Buy))
assert reports[0].price == 17.0
def test_match_correct_order_id(matcher):
matcher.push(Order(id=1, price=16.0, volume=200, side=Side.Sell))
reports = matcher.push(Order(id=2, price=17.0, volume=1000, side=Side.Buy))
assert reports[0].sell_id == 1
assert reports[0].buy_id == 2
def test_match_across_multiple_price(matcher):
matcher.push(Order(id=1, price=16.0, volume=200, side=Side.Sell))
matcher.push(Order(id=2, price=15.0, volume=200, side=Side.Sell))
reports = matcher.push(Order(id=3, price=17.0, volume=1000, side=Side.Buy))
assert len(reports) == 2
def test_large_quantity_match(matcher):
for _ in range(999):
matcher.push(Order(price=16.0, volume=2, side=Side.Buy))
matcher.push(Order(price=16.0, volume=2000, side=Side.Sell))
assert matcher.order_count(Side.Buy) == 0
assert matcher.order_count(Side.Sell) == 1
| apache-2.0 |
Moriadry/tensorflow | tensorflow/contrib/saved_model/python/saved_model/utils.py | 31 | 3844 | # Copyright 2017 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""SavedModel utility functions."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensorflow.python.framework import ops
from tensorflow.python.saved_model import builder
from tensorflow.python.saved_model import signature_constants
from tensorflow.python.saved_model import signature_def_utils
from tensorflow.python.saved_model import tag_constants
def simple_save(session, export_dir, inputs, outputs, legacy_init_op=None):
"""Convenience function to build a SavedModel suitable for serving.
In many common cases, saving models for serving will be as simple as:
simple_save(session,
export_dir,
inputs={"x": x, "y": y},
outputs={"z": z})
Although in many cases it's not necessary to understand all of the many ways
to configure a SavedModel, this method has a few practical implications:
- It will be treated as a graph for inference / serving (i.e. uses the tag
`tag_constants.SERVING`)
- The saved model will load in TensorFlow Serving and supports the
[Predict API](https://github.com/tensorflow/serving/blob/master/tensorflow_serving/apis/predict.proto).
To use the Classify, Regress, or MultiInference APIs, please
use either
[tf.Estimator](https://www.tensorflow.org/api_docs/python/tf/estimator/Estimator)
or the lower level
[SavedModel APIs](https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/saved_model/README.md).
- Some TensorFlow ops depend on information on disk or other information
called "assets". These are generally handled automatically by adding the
assets to the `GraphKeys.ASSET_FILEPATHS` collection. Only assets in that
collection are exported; if you need more custom behavior, you'll need to
use the [SavedModelBuilder](https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/saved_model/builder.py).
More information about SavedModel and signatures can be found here:
https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/saved_model/README.md.
Args:
session: The TensorFlow session from which to save the meta graph and
variables.
export_dir: The path to which the SavedModel will be stored.
inputs: dict mapping string input names to tensors. These are added
to the SignatureDef as the inputs.
outputs: dict mapping string output names to tensors. These are added
to the SignatureDef as the outputs.
legacy_init_op: Legacy support for op or group of ops to execute after the
restore op upon a load.
"""
signature_def_map = {
signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY:
signature_def_utils.predict_signature_def(inputs, outputs)
}
b = builder.SavedModelBuilder(export_dir)
b.add_meta_graph_and_variables(
session,
tags=[tag_constants.SERVING],
signature_def_map=signature_def_map,
assets_collection=ops.get_collection(ops.GraphKeys.ASSET_FILEPATHS),
legacy_init_op=legacy_init_op,
clear_devices=True)
b.save()
| apache-2.0 |
SpaceKatt/CSPLN | apps/scaffolding/mac/web2py/web2py.app/Contents/Resources/applications/admin/languages/zh.py | 16 | 14092 | # -*- coding: utf-8 -*-
{
'!langcode!': 'zh-cn',
'!langname!': '中文',
'"browse"': '游览',
'"save"': '"保存"',
'"submit"': '"提交"',
'"update" is an optional expression like "field1=\'newvalue\'". You cannot update or delete the results of a JOIN': '"更新"是可配置项 如 "field1=\'newvalue\'",你无法在JOIN 中更新或删除',
'%Y-%m-%d': '%Y-%m-%d',
'%Y-%m-%d %H:%M:%S': '%Y-%m-%d %H:%M:%S',
'%s %%{row} deleted': '%s 行已删',
'%s %%{row} updated': '%s 行更新',
'(requires internet access)': '(requires internet access)',
'(something like "it-it")': '(就酱 "it-it")',
'@markmin\x01Searching: **%s** %%{file}': 'Searching: **%s** files',
'A new version of web2py is available': '新版本web2py已经可用',
'A new version of web2py is available: %s': '新版本web2py已经可用: %s',
'ATTENTION: Login requires a secure (HTTPS) connection or running on localhost.': '',
'ATTENTION: TESTING IS NOT THREAD SAFE SO DO NOT PERFORM MULTIPLE TESTS CONCURRENTLY.': '',
'ATTENTION: you cannot edit the running application!': '注意: 不能修改正在运行中的应用!',
'About': '关于',
'About application': '关于这个应用',
'Admin is disabled because insecure channel': '管理因不安全通道而关闭',
'Admin is disabled because unsecure channel': '管理因不稳定通道而关闭',
'Admin language': 'Admin language',
'Administrator Password:': '管理员密码:',
'Application name:': 'Application name:',
'Are you sure you want to delete file "%s"?': '你真想删除文件"%s"?',
'Are you sure you want to delete plugin "%s"?': 'Are you sure you want to delete plugin "%s"?',
'Are you sure you want to delete this object?': 'Are you sure you want to delete this object?',
'Are you sure you want to uninstall application "%s"': '你真确定要卸载应用 "%s"',
'Are you sure you want to uninstall application "%s"?': '你真确定要卸载应用 "%s" ?',
'Are you sure you want to upgrade web2py now?': 'Are you sure you want to upgrade web2py now?',
'Available databases and tables': '可用数据库/表',
'Cannot be empty': '不能不填',
'Cannot compile: there are errors in your app. Debug it, correct errors and try again.': '无法编译: 应用中有错误,请修订后再试.',
'Cannot compile: there are errors in your app:': 'Cannot compile: there are errors in your app:',
'Change Password': '修改密码',
'Change admin password': 'change admin password',
'Check for upgrades': 'check for upgrades',
'Check to delete': '检验删除',
'Checking for upgrades...': '是否有升级版本检查ing...',
'Clean': '清除',
'Client IP': '客户端IP',
'Compile': '编译',
'Controllers': '控制器s',
'Create': 'create',
'Create new simple application': '创建一个新应用',
'Current request': '当前请求',
'Current response': '当前返回',
'Current session': '当前会话',
'DESIGN': '设计',
'Date and Time': '时间日期',
'Debug': 'Debug',
'Delete': '删除',
'Delete:': '删除:',
'Deploy': 'deploy',
'Deploy on Google App Engine': '部署到GAE',
'Deploy to OpenShift': 'Deploy to OpenShift',
'Description': '描述',
'Design for': '设计:',
'Disable': 'Disable',
'E-mail': '邮箱:',
'EDIT': '编辑',
'Edit': '修改',
'Edit Profile': '修订配置',
'Edit application': '修订应用',
'Edit current record': '修订当前记录',
'Editing Language file': '修订语言文件',
'Editing file': '修订文件',
'Editing file "%s"': '修订文件 %s',
'Enterprise Web Framework': '强悍的网络开发框架',
'Error logs for "%(app)s"': '"%(app)s" 的错误日志',
'Errors': '错误',
'Exception instance attributes': 'Exception instance attributes',
'First name': '姓',
'Functions with no doctests will result in [passed] tests.': '',
'Get from URL:': 'Get from URL:',
'Group ID': '组ID',
'Hello World': '道可道,非常道;名可名,非常名',
'Help': '帮助',
'If the report above contains a ticket number it indicates a failure in executing the controller, before any attempt to execute the doctests. This is usually due to an indentation error or an error outside function code.\nA green title indicates that all tests (if defined) passed. In this case test results are not shown.': 'If the report above contains a ticket number it indicates a failure in executing the controller, before any attempt to execute the doctests. This is usually due to an indentation error or an error outside function code.\nA green title indicates that all tests (if defined) passed. In this case test results are not shown.',
'Import/Export': '导入/导出',
'Install': 'install',
'Installed applications': '已安装的应用',
'Internal State': '内部状态',
'Invalid Query': '无效查询',
'Invalid action': '无效动作',
'Invalid email': '无效的email',
'Language files (static strings) updated': '语言文件(静态部分)已更新',
'Languages': '语言',
'Last name': '名',
'Last saved on:': '最后保存于:',
'License for': '许可证',
'Login': '登录',
'Login to the Administrative Interface': '登录到管理员界面',
'Logout': '注销',
'Lost Password': '忘记密码',
'Models': '模型s',
'Modules': '模块s',
'NO': '不',
'Name': '姓名',
'New Record': '新记录',
'New application wizard': 'New application wizard',
'New simple application': 'New simple application',
'No databases in this application': '这应用没有数据库',
'Origin': '起源',
'Original/Translation': '原始文件/翻译文件',
'Overwrite installed app': 'overwrite installed app',
'PAM authenticated user, cannot change password here': 'PAM authenticated user, cannot change password here',
'Pack all': '全部打包',
'Pack compiled': '包编译完',
'Password': '密码',
'Peeking at file': '选个文件',
'Plugin "%s" in application': 'Plugin "%s" in application',
'Plugins': 'Plugins',
'Powered by': '',
'Query:': '查询',
'Record ID': '记录ID',
'Register': '注册',
'Registration key': '注册密匙',
'Reload routes': 'Reload routes',
'Remove compiled': '已移除',
'Resolve Conflict file': '解决冲突文件',
'Role': '角色',
'Rows in table': '表行',
'Rows selected': '行选择',
'Running on %s': 'Running on %s',
'Saved file hash:': '已存文件Hash:',
'Site': '总站',
'Start wizard': 'start wizard',
'Static files': '静态文件',
'Sure you want to delete this object?': '真的要删除这个对象?',
'TM': '',
'Table name': '表名',
'Testing application': '应用测试',
'The "query" is a condition like "db.table1.field1==\'value\'". Something like "db.table1.field1==db.table2.field2" results in a SQL JOIN.': '',
'There are no controllers': '冇控制器',
'There are no models': '冇模型s',
'There are no modules': '冇模块s',
'There are no static files': '冇静态文件',
'There are no translators, only default language is supported': '没有找到相应翻译,只能使用默认语言',
'There are no views': '冇视图',
'This is the %(filename)s template': '这是 %(filename)s 模板',
'Ticket': '传票',
'Timestamp': '时间戳',
'To create a plugin, name a file/folder plugin_[name]': 'To create a plugin, name a file/folder plugin_[name]',
'Unable to check for upgrades': '无法检查是否需要升级',
'Unable to download': '无法下载',
'Unable to download app': '无法下载应用',
'Unable to download app because:': 'Unable to download app because:',
'Unable to download because': 'Unable to download because',
'Uninstall': '卸载',
'Update:': '更新:',
'Upload & install packed application': 'Upload & install packed application',
'Upload a package:': 'Upload a package:',
'Upload and install packed application': 'Upload and install packed application',
'Upload existing application': '上传已有应用',
'Use (...)&(...) for AND, (...)|(...) for OR, and ~(...) for NOT to build more complex queries.': 'Use (...)&(...) for AND, (...)|(...) for OR, and ~(...) for NOT to build more complex queries.',
'Use (...)&(...) for AND, (...)|(...) for OR, and ~(...) for NOT to build more complex queries.': '',
'Use an url:': 'Use an url:',
'User ID': '用户ID',
'Version': '版本',
'Views': '视图',
'Welcome to web2py': '欢迎使用web2py',
'YES': '是',
'additional code for your application': '给你的应用附加代码',
'admin disabled because no admin password': '管理员需要设定密码,否则无法管理',
'admin disabled because not supported on google app engine': '未支持GAE,无法管理',
'admin disabled because unable to access password file': '需要可以操作密码文件,否则无法进行管理',
'administrative interface': 'administrative interface',
'and rename it (required):': '重命名为 (必须):',
'and rename it:': ' 重命名为:',
'appadmin': '应用管理',
'appadmin is disabled because insecure channel': '应用管理因非法通道失效',
'application "%s" uninstalled': '应用"%s" 已被卸载',
'application compiled': '应用已编译完',
'application is compiled and cannot be designed': '应用已编译完无法设计',
'arguments': 'arguments',
'back': 'back',
'cache': 'cache',
'cache, errors and sessions cleaned': '缓存、错误、sesiones已被清空',
'cannot create file': '无法创建文件',
'cannot upload file "%(filename)s"': '无法上传文件 "%(filename)s"',
'check all': '检查所有',
'click here for online examples': '猛击此处,查看在线实例',
'click here for the administrative interface': '猛击此处,进入管理界面',
'click to check for upgrades': '猛击查看是否有升级版本',
'code': 'code',
'compiled application removed': '已编译应用已移走',
'controllers': '控制器',
'create file with filename:': '创建文件用这名:',
'create new application:': '创建新应用:',
'created by': '创建自',
'crontab': '定期事务',
'currently running': 'currently running',
'currently saved or': '保存当前的或',
'customize me!': '定制俺!',
'data uploaded': '数据已上传',
'database': '数据库',
'database %s select': '数据库 %s 选择',
'database administration': '数据库管理',
'db': '',
'defines tables': '已定义表',
'delete': '删除',
'delete all checked': '删除所有选择的',
'delete plugin': 'delete plugin',
'design': '设计',
'direction: ltr': 'direction: ltr',
'done!': '搞定!',
'edit controller': '修订控制器',
'edit views:': 'edit views:',
'export as csv file': '导出为CSV文件',
'exposes': '暴露',
'extends': '扩展',
'failed to reload module': '重新加载模块失败',
'failed to reload module because:': 'failed to reload module because:',
'file "%(filename)s" created': '文件 "%(filename)s" 已创建',
'file "%(filename)s" deleted': '文件 "%(filename)s" 已删除',
'file "%(filename)s" uploaded': '文件 "%(filename)s" 已上传',
'file "%(filename)s" was not deleted': '文件 "%(filename)s" 没删除',
'file "%s" of %s restored': '文件"%s" 有关 %s 已重存',
'file changed on disk': '硬盘上的文件已经修改',
'file does not exist': '文件并不存在',
'file saved on %(time)s': '文件保存于 %(time)s',
'file saved on %s': '文件保存在 %s',
'htmledit': 'html编辑',
'includes': '包含',
'insert new': '新插入',
'insert new %s': '新插入 %s',
'internal error': '内部错误',
'invalid password': '无效密码',
'invalid request': '无效请求',
'invalid ticket': '无效传票',
'language file "%(filename)s" created/updated': '语言文件 "%(filename)s"被创建/更新',
'languages': '语言',
'languages updated': '语言已被刷新',
'loading...': '载入中...',
'login': '登录',
'merge': '合并',
'models': '模型s',
'modules': '模块s',
'new application "%s" created': '新应用 "%s"已被创建',
'new plugin installed': 'new plugin installed',
'new record inserted': '新记录被插入',
'next 100 rows': '后100行',
'no match': 'no match',
'or import from csv file': '或者,从csv文件导入',
'or provide app url:': 'or provide app url:',
'or provide application url:': '或者,提供应用所在地址链接:',
'pack plugin': 'pack plugin',
'password changed': 'password changed',
'plugin "%(plugin)s" deleted': 'plugin "%(plugin)s" deleted',
'previous 100 rows': '前100行',
'record': 'record',
'record does not exist': '记录并不存在',
'record id': '记录ID',
'restore': '重存',
'revert': '恢复',
'save': '保存',
'selected': '已选',
'session expired': '会话过期',
'shell': '',
'some files could not be removed': '有些文件无法被移除',
'state': '状态',
'static': '静态文件',
'submit': '提交',
'table': '表',
'test': '测试',
'the application logic, each URL path is mapped in one exposed function in the controller': '应用逻辑:每个URL由控制器暴露的函式完成映射',
'the data representation, define database tables and sets': '数据表达式,定义数据库/表',
'the presentations layer, views are also known as templates': '提交层/视图都在模板中可知',
'these files are served without processing, your images go here': '',
'to previous version.': 'to previous version.',
'to previous version.': '退回前一版本',
'translation strings for the application': '应用的翻译字串',
'try': '尝试',
'try something like': '尝试',
'unable to create application "%s"': '无法创建应用 "%s"',
'unable to delete file "%(filename)s"': '无法删除文件 "%(filename)s"',
'unable to delete file plugin "%(plugin)s"': 'unable to delete file plugin "%(plugin)s"',
'unable to parse csv file': '无法生成 cvs',
'unable to uninstall "%s"': '无法卸载 "%s"',
'unable to upgrade because "%s"': 'unable to upgrade because "%s"',
'uncheck all': '反选全部',
'update': '更新',
'update all languages': '更新所有语言',
'upgrade web2py now': 'upgrade web2py now',
'upload application:': '提交已有的应用:',
'upload file:': '提交文件:',
'upload plugin file:': 'upload plugin file:',
'variables': 'variables',
'versioning': '版本',
'view': '视图',
'views': '视图s',
'web2py Recent Tweets': 'twitter上的web2py进展实播',
'web2py is up to date': 'web2py现在已经是最新的版本了',
'web2py upgraded; please restart it': 'web2py upgraded; please restart it',
}
| gpl-3.0 |
wwgong/CVoltDB | src/catgen/catalog_utils/strings.py | 4 | 1611 | #!/usr/bin/env python
# This file is part of VoltDB.
# Copyright (C) 2008-2011 VoltDB Inc.
#
# VoltDB 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.
#
# VoltDB 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 VoltDB. If not, see <http://www.gnu.org/licenses/>.
gpl_header = \
"""/* This file is part of VoltDB.
* Copyright (C) 2008-2011 VoltDB Inc.
*
* VoltDB 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.
*
* VoltDB 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 VoltDB. If not, see <http://www.gnu.org/licenses/>.
*/
"""
auto_gen_warning = \
"""/* WARNING: THIS FILE IS AUTO-GENERATED
DO NOT MODIFY THIS SOURCE
ALL CHANGES MUST BE MADE IN THE CATALOG GENERATOR */
"""
| gpl-3.0 |
kimjaejoong/nova | nova/tests/unit/api/openstack/compute/contrib/test_extended_ips_mac.py | 19 | 6008 | # Copyright 2013 IBM Corp.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from oslo_serialization import jsonutils
import six
import webob
from nova.api.openstack.compute.contrib import extended_ips_mac
from nova import compute
from nova import objects
from nova.objects import instance as instance_obj
from nova import test
from nova.tests.unit.api.openstack import fakes
from nova.tests.unit import fake_instance
UUID1 = '00000000-0000-0000-0000-000000000001'
UUID2 = '00000000-0000-0000-0000-000000000002'
UUID3 = '00000000-0000-0000-0000-000000000003'
NW_CACHE = [
{
'address': 'aa:aa:aa:aa:aa:aa',
'id': 1,
'network': {
'bridge': 'br0',
'id': 1,
'label': 'private',
'subnets': [
{
'cidr': '192.168.1.0/24',
'ips': [
{
'address': '192.168.1.100',
'type': 'fixed',
'floating_ips': [
{'address': '5.0.0.1', 'type': 'floating'},
],
},
],
},
]
}
},
{
'address': 'bb:bb:bb:bb:bb:bb',
'id': 2,
'network': {
'bridge': 'br1',
'id': 2,
'label': 'public',
'subnets': [
{
'cidr': '10.0.0.0/24',
'ips': [
{
'address': '10.0.0.100',
'type': 'fixed',
'floating_ips': [
{'address': '5.0.0.2', 'type': 'floating'},
],
}
],
},
]
}
}
]
ALL_IPS = []
for cache in NW_CACHE:
for subnet in cache['network']['subnets']:
for fixed in subnet['ips']:
sanitized = dict(fixed)
sanitized['mac_address'] = cache['address']
sanitized.pop('floating_ips')
sanitized.pop('type')
ALL_IPS.append(sanitized)
for floating in fixed['floating_ips']:
sanitized = dict(floating)
sanitized['mac_address'] = cache['address']
sanitized.pop('type')
ALL_IPS.append(sanitized)
ALL_IPS.sort()
def fake_compute_get(*args, **kwargs):
inst = fakes.stub_instance(1, uuid=UUID3, nw_cache=NW_CACHE)
return fake_instance.fake_instance_obj(args[1],
expected_attrs=instance_obj.INSTANCE_DEFAULT_FIELDS, **inst)
def fake_compute_get_all(*args, **kwargs):
db_list = [
fakes.stub_instance(1, uuid=UUID1, nw_cache=NW_CACHE),
fakes.stub_instance(2, uuid=UUID2, nw_cache=NW_CACHE),
]
fields = instance_obj.INSTANCE_DEFAULT_FIELDS
return instance_obj._make_instance_list(args[1],
objects.InstanceList(),
db_list, fields)
class ExtendedIpsMacTestV21(test.TestCase):
content_type = 'application/json'
prefix = '%s:' % extended_ips_mac.Extended_ips_mac.alias
def setUp(self):
super(ExtendedIpsMacTestV21, self).setUp()
fakes.stub_out_nw_api(self.stubs)
self.stubs.Set(compute.api.API, 'get', fake_compute_get)
self.stubs.Set(compute.api.API, 'get_all', fake_compute_get_all)
def _make_request(self, url):
req = webob.Request.blank(url)
req.headers['Accept'] = self.content_type
res = req.get_response(fakes.wsgi_app_v21(init_only=('servers',)))
return res
def _get_server(self, body):
return jsonutils.loads(body).get('server')
def _get_servers(self, body):
return jsonutils.loads(body).get('servers')
def _get_ips(self, server):
for network in six.itervalues(server['addresses']):
for ip in network:
yield ip
def assertServerStates(self, server):
results = []
for ip in self._get_ips(server):
results.append({'address': ip.get('addr'),
'mac_address': ip.get('%smac_addr' % self.prefix)})
self.assertEqual(ALL_IPS, sorted(results))
def test_show(self):
url = '/v2/fake/servers/%s' % UUID3
res = self._make_request(url)
self.assertEqual(res.status_int, 200)
self.assertServerStates(self._get_server(res.body))
def test_detail(self):
url = '/v2/fake/servers/detail'
res = self._make_request(url)
self.assertEqual(res.status_int, 200)
for _i, server in enumerate(self._get_servers(res.body)):
self.assertServerStates(server)
class ExtendedIpsMacTestV2(ExtendedIpsMacTestV21):
content_type = 'application/json'
prefix = '%s:' % extended_ips_mac.Extended_ips_mac.alias
def setUp(self):
super(ExtendedIpsMacTestV2, self).setUp()
self.flags(
osapi_compute_extension=[
'nova.api.openstack.compute.contrib.select_extensions'],
osapi_compute_ext_list=['Extended_ips_mac'])
def _make_request(self, url):
req = webob.Request.blank(url)
req.headers['Accept'] = self.content_type
res = req.get_response(fakes.wsgi_app(init_only=('servers',)))
return res
| apache-2.0 |
SpectreJan/gnuradio | gr-uhd/apps/uhd_app.py | 7 | 18736 | #!/usr/bin/env python
#
# Copyright 2015-2016 Free Software Foundation, Inc.
#
# This file is part of GNU Radio
#
# GNU Radio is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3, or (at your option)
# any later version.
#
# GNU Radio is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with GNU Radio; see the file COPYING. If not, write to
# the Free Software Foundation, Inc., 51 Franklin Street,
# Boston, MA 02110-1301, USA.
#
"""
USRP Helper Module: Common tasks for uhd-based apps.
"""
from __future__ import print_function
import sys
import time
import argparse
from gnuradio import eng_arg
from gnuradio import uhd
from gnuradio import gr
from gnuradio import gru
COMMAND_DELAY = .2 # Seconds
COMPACT_TPL = "{mb_id} ({mb_serial}), {db_subdev} ({subdev}, {ant}{db_serial})"
LONG_TPL = """{prefix} Motherboard: {mb_id} ({mb_serial})
{prefix} Daughterboard: {db_subdev}{db_serial}
{prefix} Subdev: {subdev}
{prefix} Antenna: {ant}
"""
class UHDApp(object):
" Base class for simple UHD-based applications "
def __init__(self, prefix=None, args=None):
self.prefix = prefix
self.args = args
self.verbose = args.verbose or 0
if self.args.sync == 'auto' and len(self.args.channels) > 1:
self.args.sync = 'pps'
self.antenna = None
self.gain_range = None
self.samp_rate = None
self.has_lo_sensor = None
self.async_msgq = None
self.async_src = None
self.async_rcv = None
self.tr = None
self.gain = None
self.freq = None
self.channels = None
self.cpu_format = None
self.spec = None
self.clock_source = None
self.time_source = None
self.lo_source = None
self.lo_export = None
def vprint(self, *args):
"""
Print 'string' with 'prefix' prepended if self.verbose is True
"""
if self.verbose:
print("[{prefix}]".format(prefix=self.prefix), *args)
def get_usrp_info_string(self,
compact=False,
tx_or_rx='rx',
chan=0,
mboard=0,
):
"""
Return a nice textual description of the USRP we're using.
"""
assert tx_or_rx == 'rx' or tx_or_rx == 'tx'
try:
info_pp = {}
if self.prefix is None:
info_pp['prefix'] = ""
else:
info_pp['prefix'] = "[{prefix}] ".format(prefix=self.prefix)
usrp_info = self.usrp.get_usrp_info(chan)
info_pp['mb_id'] = usrp_info['mboard_id']
info_pp['mb_serial'] = usrp_info['mboard_serial']
if info_pp['mb_serial'] == "":
info_pp['mb_serial'] = "no serial"
info_pp['db_subdev'] = usrp_info["{xx}_subdev_name".format(xx=tx_or_rx)]
info_pp['db_serial'] = ", " + usrp_info["{xx}_serial".format(xx=tx_or_rx)]
if info_pp['db_serial'] == "":
info_pp['db_serial'] = "no serial"
info_pp['subdev'] = self.usrp.get_subdev_spec(mboard)
info_pp['ant'] = self.usrp.get_antenna(chan)
if info_pp['mb_id'] in ("B200", "B210", "E310"):
# In this case, this is meaningless
info_pp['db_serial'] = ""
tpl = LONG_TPL
if compact:
tpl = COMPACT_TPL
return tpl.format(**info_pp)
except:
return "Can't establish USRP info."
def normalize_sel(self, num_name, arg_name, num, arg):
"""
num_name: meaningful name why we need num arguments
arg_name: name of current argument
num: required number of arguments
arg: actual argument
"""
if arg is None:
return None
args = [x.strip() for x in arg.split(",")]
if len(args) == 1:
args = args * num
if len(args) != num:
raise ValueError("Invalid {m} setting for {n} {b}: {a}".format(
m=arg_name, n=num, a=arg, b=num_name
))
return args
def async_callback(self, msg):
"""
Call this when USRP async metadata needs printing.
"""
metadata = self.async_src.msg_to_async_metadata_t(msg)
print("[{prefix}] Channel: {chan} Time: {t} Event: {e}".format(
prefix=self.prefix,
chan=metadata.channel,
t=metadata.time_spec.get_real_secs(),
e=metadata.event_code,
))
def setup_usrp(self, ctor, args, cpu_format='fc32'):
"""
Instantiate a USRP object; takes care of all kinds of corner cases and settings.
Pop it and some args onto the class that calls this.
"""
self.channels = args.channels
self.cpu_format = cpu_format
# Create a UHD device object:
self.usrp = ctor(
device_addr=args.args,
stream_args=uhd.stream_args(
cpu_format,
args.otw_format,
args=args.stream_args,
channels=self.channels,
)
)
# Set the subdevice spec:
self.spec = self.normalize_sel("mboards", "subdev",
self.usrp.get_num_mboards(), args.spec)
if self.spec:
for mb_idx in xrange(self.usrp.get_num_mboards()):
self.usrp.set_subdev_spec(self.spec[mb_idx], mb_idx)
# Set the clock and/or time source:
if args.clock_source is not None:
self.clock_source = self.normalize_sel("mboards", "clock-source",
self.usrp.get_num_mboards(), args.clock_source)
for mb_idx in xrange(self.usrp.get_num_mboards()):
self.usrp.set_clock_source(self.clock_source[mb_idx], mb_idx)
if args.time_source is not None:
self.time_source = self.normalize_sel("mboards", "time-source",
self.usrp.get_num_mboards(), args.time_source)
for mb_idx in xrange(self.usrp.get_num_mboards()):
self.usrp.set_time_source(self.time_source[mb_idx], mb_idx)
# Sampling rate:
self.usrp.set_samp_rate(args.samp_rate)
self.samp_rate = self.usrp.get_samp_rate()
self.vprint("Using sampling rate: {rate}".format(rate=self.samp_rate))
# Set the antenna:
self.antenna = self.normalize_sel("channels", "antenna", len(args.channels), args.antenna)
if self.antenna is not None:
for i, chan in enumerate(self.channels):
if not self.antenna[i] in self.usrp.get_antennas(i):
print("[ERROR] {} is not a valid antenna name for this USRP device!".format(self.antenna[i]))
exit(1)
self.usrp.set_antenna(self.antenna[i], i)
self.vprint("[{prefix}] Channel {chan}: Using antenna {ant}.".format(
prefix=self.prefix, chan=chan, ant=self.usrp.get_antenna(i)
))
self.antenna = self.usrp.get_antenna(0)
# Set receive daughterboard gain:
self.set_gain(args.gain)
self.gain_range = self.usrp.get_gain_range(0)
# Set frequency (tune request takes lo_offset):
if hasattr(args, 'lo_offset') and args.lo_offset is not None:
treq = uhd.tune_request(args.freq, args.lo_offset)
else:
treq = uhd.tune_request(args.freq)
self.has_lo_sensor = 'lo_locked' in self.usrp.get_sensor_names()
# Set LO export and LO source operation
if (args.lo_export is not None) and (args.lo_source is not None):
self.lo_source = self.normalize_sel("channels", "lo-source", len(self.channels), args.lo_source)
self.lo_export = self.normalize_sel("channels", "lo-export", len(self.channels), args.lo_export)
for chan, lo_source, lo_export in zip(self.channels, self.lo_source, self.lo_export):
if (lo_source == "None") or (lo_export == "None"):
continue
if lo_export == "True":
#If channel is LO source set frequency and store response
self.usrp.set_lo_export_enabled(True, uhd.ALL_LOS, chan)
if lo_source == "internal":
self.lo_source_channel = chan
tune_resp = self.usrp.set_center_freq(treq,chan)
self.usrp.set_lo_source(lo_source, uhd.ALL_LOS,chan)
# Use lo source tune response to tune dsp_freq on remaining channels
if getattr(args, 'lo_offset', None) is not None:
treq = uhd.tune_request(target_freq=args.freq, rf_freq=args.freq+args.lo_offset, rf_freq_policy=uhd.tune_request.POLICY_MANUAL,
dsp_freq=tune_resp.actual_dsp_freq,
dsp_freq_policy=uhd.tune_request.POLICY_MANUAL)
else:
treq = uhd.tune_request(target_freq=args.freq, rf_freq=args.freg, rf_freq_policy=uhd.tune_request.POLICY_MANUAL,
dsp_freq=tune_resp.actual_dsp_freq,
dsp_freq_policy=uhd.tune_request.POLICY_MANUAL)
for chan in args.channels:
if chan == self.lo_source_channel:
continue
self.usrp.set_center_freq(treq,chan)
# Make sure tuning is synched:
command_time_set = False
if len(self.channels) > 1:
if args.sync == 'pps':
self.usrp.set_time_unknown_pps(uhd.time_spec())
cmd_time = self.usrp.get_time_now() + uhd.time_spec(COMMAND_DELAY)
try:
for mb_idx in xrange(self.usrp.get_num_mboards()):
self.usrp.set_command_time(cmd_time, mb_idx)
command_time_set = True
except RuntimeError:
sys.stderr.write('[{prefix}] [WARNING] Failed to set command times.\n'.format(prefix=self.prefix))
for i, chan in enumerate(self.channels):
self.tr = self.usrp.set_center_freq(treq, i)
if self.tr == None:
sys.stderr.write('[{prefix}] [ERROR] Failed to set center frequency on channel {chan}\n'.format(
prefix=self.prefix, chan=chan
))
exit(1)
if command_time_set:
for mb_idx in xrange(self.usrp.get_num_mboards()):
self.usrp.clear_command_time(mb_idx)
self.vprint("Syncing channels...".format(prefix=self.prefix))
time.sleep(COMMAND_DELAY)
self.freq = self.usrp.get_center_freq(0)
if args.show_async_msg:
self.async_msgq = gr.msg_queue(0)
self.async_src = uhd.amsg_source("", self.async_msgq)
self.async_rcv = gru.msgq_runner(self.async_msgq, self.async_callback)
def set_gain(self, gain):
"""
Safe gain-setter. Catches some special cases:
- If gain is None, set to mid-point in dB.
- If the USRP is multi-channel, set it on all channels.
"""
if gain is None:
if self.args.verbose:
self.vprint("Defaulting to mid-point gains:".format(prefix=self.prefix))
for i, chan in enumerate(self.channels):
self.usrp.set_normalized_gain(.5, i)
if self.args.verbose:
self.vprint("Channel {chan} gain: {g} dB".format(
prefix=self.prefix, chan=chan, g=self.usrp.get_gain(i)
))
else:
self.vprint("Setting gain to {g} dB.".format(g=gain))
for chan in range( len( self.channels ) ):
self.usrp.set_gain(gain, chan)
self.gain = self.usrp.get_gain(0)
def set_freq(self, freq, skip_sync=False):
"""
Safely tune all channels to freq.
"""
self.vprint("Tuning all channels to {freq} MHz.".format(freq=freq/1e6))
# Set frequency (tune request takes lo_offset):
if hasattr(self.args, 'lo_offset') and self.args.lo_offset is not None:
treq = uhd.tune_request(freq, self.args.lo_offset)
else:
treq = uhd.tune_request(freq)
# Special TwinRX tuning due to LO sharing
if getattr(self, 'lo_source_channel', None) is not None:
tune_resp = self.usrp.set_center_freq(treq, self.lo_source_channel)
if getattr(self.args, 'lo_offset', None) is not None:
treq = uhd.tune_request(target_freq=freq, rf_freq=freq+self.args.lo_offset, rf_freq_policy=uhd.tune_request.POLICY_MANUAL,
dsp_freq=tune_resp.actual_dsp_freq,
dsp_freq_policy=uhd.tune_request.POLICY_MANUAL)
else:
treq = uhd.tune_request(target_freq=freq, rf_freq=freq, rf_freq_policy=uhd.tune_reqest.POLICY_MANUAL,
dsp_freq=tune_resp.actual_dsp_freq,
dsp_freq_policy=uhd.tune_request.POLICY_MANUAL)
for chan in self.channels:
if chan == self.lo_source_channel:
continue
self.usrp.set_center_freq(treq,chan)
# Make sure tuning is synched:
command_time_set = False
if len(self.channels) > 1 and not skip_sync:
cmd_time = self.usrp.get_time_now() + uhd.time_spec(COMMAND_DELAY)
try:
for mb_idx in xrange(self.usrp.get_num_mboards()):
self.usrp.set_command_time(cmd_time, mb_idx)
command_time_set = True
except RuntimeError:
sys.stderr.write('[{prefix}] [WARNING] Failed to set command times.\n'.format(prefix=self.prefix))
for i, chan in enumerate(self.channels ):
self.tr = self.usrp.set_center_freq(treq, i)
if self.tr == None:
sys.stderr.write('[{prefix}] [ERROR] Failed to set center frequency on channel {chan}\n'.format(
prefix=self.prefix, chan=chan
))
exit(1)
if command_time_set:
for mb_idx in xrange(self.usrp.get_num_mboards()):
self.usrp.clear_command_time(mb_idx)
self.vprint("Syncing channels...".format(prefix=self.prefix))
time.sleep(COMMAND_DELAY)
self.freq = self.usrp.get_center_freq(0)
self.vprint("First channel has freq: {freq} MHz.".format(freq=self.freq/1e6))
@staticmethod
def setup_argparser(
parser=None,
description='USRP App',
allow_mimo=True,
tx_or_rx="",
skip_freq=False,
):
"""
Create or amend an argument parser with typical USRP options.
"""
def cslist(string):
"""
For ArgParser: Turn a comma separated list into an actual list.
"""
try:
return [int(x.strip()) for x in string.split(",")]
except:
raise argparse.ArgumentTypeError("Not a comma-separated list: {string}".format(string=string))
if parser is None:
parser = argparse.ArgumentParser(
description=description,
)
tx_or_rx = tx_or_rx.strip() + " "
group = parser.add_argument_group('USRP Arguments')
group.add_argument("-a", "--args", default="", help="UHD device address args")
group.add_argument("--spec", help="Subdevice(s) of UHD device where appropriate. Use a comma-separated list to set different boards to different specs.")
group.add_argument("-A", "--antenna", help="Select {xx}antenna(s) where appropriate".format(xx=tx_or_rx))
group.add_argument("-s", "--samp-rate", type=eng_arg.eng_float, default=1e6,
help="Sample rate")
group.add_argument("-g", "--gain", type=eng_arg.eng_float, default=None,
help="Gain (default is midpoint)")
group.add_argument("--gain-type", choices=('db', 'normalized'), default='db',
help="Gain Type (applies to -g)")
if not skip_freq:
group.add_argument("-f", "--freq", type=eng_arg.eng_float, default=None, required=True,
help="Set carrier frequency to FREQ",
metavar="FREQ")
group.add_argument("--lo-offset", type=eng_arg.eng_float, default=0.0,
help="Set daughterboard LO offset to OFFSET [default=hw default]")
if allow_mimo:
group.add_argument("-c", "--channels", default=[0,], type=cslist,
help="Select {xx} Channels".format(xx=tx_or_rx))
group.add_argument("--lo-export", help="Set TwinRX LO export {None, True, False} for each channel with a comma-separated list. None skips a channel.")
group.add_argument("--lo-source", help="Set TwinRX LO source {None, internal, companion, external} for each channel with a comma-separated list. None skips this channel. ")
group.add_argument("--otw-format", choices=['sc16', 'sc12', 'sc8'], default='sc16',
help="Choose over-the-wire data format")
group.add_argument("--stream-args", default="", help="Set additional stream arguments")
group.add_argument("-m", "--amplitude", type=eng_arg.eng_float, default=0.15,
help="Set output amplitude to AMPL (0.0-1.0)", metavar="AMPL")
group.add_argument("-v", "--verbose", action="count", help="Use verbose console output")
group.add_argument("--show-async-msg", action="store_true",
help="Show asynchronous message notifications from UHD")
group.add_argument("--sync", choices=('default', 'pps', 'auto'),
default='auto', help="Set to 'pps' to sync devices to PPS")
group.add_argument("--clock-source",
help="Set the clock source; typically 'internal', 'external' or 'gpsdo'")
group.add_argument("--time-source",
help="Set the time source")
return parser
| gpl-3.0 |
xunmengfeng/engine | third_party/jinja2/tests.py | 638 | 3444 | # -*- coding: utf-8 -*-
"""
jinja2.tests
~~~~~~~~~~~~
Jinja test functions. Used with the "is" operator.
:copyright: (c) 2010 by the Jinja Team.
:license: BSD, see LICENSE for more details.
"""
import re
from jinja2.runtime import Undefined
from jinja2._compat import text_type, string_types, mapping_types
number_re = re.compile(r'^-?\d+(\.\d+)?$')
regex_type = type(number_re)
test_callable = callable
def test_odd(value):
"""Return true if the variable is odd."""
return value % 2 == 1
def test_even(value):
"""Return true if the variable is even."""
return value % 2 == 0
def test_divisibleby(value, num):
"""Check if a variable is divisible by a number."""
return value % num == 0
def test_defined(value):
"""Return true if the variable is defined:
.. sourcecode:: jinja
{% if variable is defined %}
value of variable: {{ variable }}
{% else %}
variable is not defined
{% endif %}
See the :func:`default` filter for a simple way to set undefined
variables.
"""
return not isinstance(value, Undefined)
def test_undefined(value):
"""Like :func:`defined` but the other way round."""
return isinstance(value, Undefined)
def test_none(value):
"""Return true if the variable is none."""
return value is None
def test_lower(value):
"""Return true if the variable is lowercased."""
return text_type(value).islower()
def test_upper(value):
"""Return true if the variable is uppercased."""
return text_type(value).isupper()
def test_string(value):
"""Return true if the object is a string."""
return isinstance(value, string_types)
def test_mapping(value):
"""Return true if the object is a mapping (dict etc.).
.. versionadded:: 2.6
"""
return isinstance(value, mapping_types)
def test_number(value):
"""Return true if the variable is a number."""
return isinstance(value, (int, float, complex))
def test_sequence(value):
"""Return true if the variable is a sequence. Sequences are variables
that are iterable.
"""
try:
len(value)
value.__getitem__
except:
return False
return True
def test_sameas(value, other):
"""Check if an object points to the same memory address than another
object:
.. sourcecode:: jinja
{% if foo.attribute is sameas false %}
the foo attribute really is the `False` singleton
{% endif %}
"""
return value is other
def test_iterable(value):
"""Check if it's possible to iterate over an object."""
try:
iter(value)
except TypeError:
return False
return True
def test_escaped(value):
"""Check if the value is escaped."""
return hasattr(value, '__html__')
TESTS = {
'odd': test_odd,
'even': test_even,
'divisibleby': test_divisibleby,
'defined': test_defined,
'undefined': test_undefined,
'none': test_none,
'lower': test_lower,
'upper': test_upper,
'string': test_string,
'mapping': test_mapping,
'number': test_number,
'sequence': test_sequence,
'iterable': test_iterable,
'callable': test_callable,
'sameas': test_sameas,
'escaped': test_escaped
}
| bsd-3-clause |
ddamiani/pyqtgraph | pyqtgraph/pixmaps/pixmapData_3.py | 56 | 53111 | import numpy as np; pixmapData={'lock.png': b'\x80\x03cnumpy.core.multiarray\n_reconstruct\nq\x00cnumpy\nndarray\nq\x01K\x00\x85q\x02C\x01bq\x03\x87q\x04Rq\x05(K\x01K K K\x04\x87q\x06cnumpy\ndtype\nq\x07X\x02\x00\x00\x00u1q\x08K\x00K\x01\x87q\tRq\n(K\x03X\x01\x00\x00\x00|q\x0bNNNJ\xff\xff\xff\xffJ\xff\xff\xff\xffK\x00tq\x0cb\x89B\x00\x10\x00\x00\xff\xff\xff\x00\xff\xff\xff\x00\xff\xff\xff\x00\xad\xad\xad\x19\xa8\xa8\xa8\x8d\xa9\xa9\xa9\xc1\xa9\xa9\xa9\xf1\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xf1\xaa\xaa\xaa\xc2\xa9\xa9\xa9\x8e\xad\xad\xad\x19\xff\xff\xff\x00\xff\xff\xff\x00\xff\xff\xff\x00\xff\xff\xff\x00\xff\xff\xff\x00\xa8\xa8\xa8X\xa9\xa9\xa9\xed\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xed\xa8\xa8\xa8X\xff\xff\xff\x00\xff\xff\xff\x00\xff\xff\xff\x00\xaa\xaa\xaaW\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa6\xa6\xa6\xff\x9a\x9a\x9a\xff\x9a\x9a\x9a\xff\x9a\x9a\x9a\xff\x9a\x9a\x9a\xff\x9a\x9a\x9a\xff\x9a\x9a\x9a\xff\x9a\x9a\x9a\xff\x9a\x9a\x9a\xff\x9a\x9a\x9a\xff\x9a\x9a\x9a\xff\x9a\x9a\x9a\xff\x9a\x9a\x9a\xff\x9a\x9a\x9a\xff\x9a\x9a\x9a\xff\x9a\x9a\x9a\xff\x9a\x9a\x9a\xff\x9a\x9a\x9a\xff\x9a\x9a\x9a\xff\xa6\xa6\xa6\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xaa\xaa\xaaW\xff\xff\xff\x00\xaa\xaa\xaa\x15\xa9\xa9\xa9\xeb\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\x88\x88\x88\xff)))\xff\x05\x05\x05\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x05\x05\x05\xff)))\xff\x88\x88\x88\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xeb\xaa\xaa\xaa\x15\xa9\xa9\xa9\x88\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\x88\x88\x88\xff\x03\x03\x03\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x03\x03\x03\xff\x88\x88\x88\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\x88\xa9\xa9\xa9\xbe\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff)))\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff)))\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xbe\xa9\xa9\xa9\xf1\xa9\xa9\xa9\xff\xa6\xa6\xa6\xff\x05\x05\x05\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x05\x05\x05\xff\x16\x16\x16\xff\x16\x16\x16\xff\x16\x16\x16\xff\x16\x16\x16\xff\x16\x16\x16\xff\x16\x16\x16\xff\x16\x16\x16\xff\x16\x16\x16\xff\x0c\x0c\x0c\xff\x00\x00\x00\xff\x00\x00\x00\xff\x05\x05\x05\xff\xa6\xa6\xa6\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xf1\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\x9a\x9a\x9a\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff@@@\xff\xd2\xd2\xd2\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe1\xe1\xe1\xff{{{\xff\x00\x00\x00\xff\x00\x00\x00\xff\x9a\x9a\x9a\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\x9a\x9a\x9a\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x0e\x0e\x0e\xff***\xff+++\xff+++\xff\xaf\xaf\xaf\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe2\xe2\xe2\xff\x10\x10\x10\xff\x00\x00\x00\xff\x9a\x9a\x9a\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\x9a\x9a\x9a\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x1e\x1e\x1e\xff\x93\x93\x93\xff\xc6\xc6\xc6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\x1d\x1d\x1d\xff\x00\x00\x00\xff\x9a\x9a\x9a\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\x9a\x9a\x9a\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xffaaa\xff\xdc\xdc\xdc\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\x1d\x1d\x1d\xff\x00\x00\x00\xff\x9a\x9a\x9a\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\x9a\x9a\x9a\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\\\\\\\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe2\xe2\xe2\xff\xbb\xbb\xbb\xff\x9f\x9f\x9f\xff\x9f\x9f\x9f\xff\x9f\x9f\x9f\xff\xd7\xd7\xd7\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\x1d\x1d\x1d\xff\x00\x00\x00\xff\x9a\x9a\x9a\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\x9a\x9a\x9a\xff\x00\x00\x00\xff\x00\x00\x00\xff\x1c\x1c\x1c\xff\xda\xda\xda\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\x91\x91\x91\xff\x0f\x0f\x0f\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\xb4\xb4\xb4\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\x1d\x1d\x1d\xff\x00\x00\x00\xff\x9a\x9a\x9a\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\x9a\x9a\x9a\xff\x00\x00\x00\xff\x00\x00\x00\xff\x87\x87\x87\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\x98\x98\x98\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\xb4\xb4\xb4\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\x1d\x1d\x1d\xff\x00\x00\x00\xff\x9a\x9a\x9a\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\x9a\x9a\x9a\xff\x00\x00\x00\xff\x00\x00\x00\xff\xba\xba\xba\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\x19\x19\x19\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\xb4\xb4\xb4\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\x1d\x1d\x1d\xff\x00\x00\x00\xff\x9a\x9a\x9a\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\x9a\x9a\x9a\xff\x00\x00\x00\xff\x08\x08\x08\xff\xe2\xe2\xe2\xff\xe6\xe6\xe6\xff\xcc\xcc\xcc\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\xb4\xb4\xb4\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\x1d\x1d\x1d\xff\x00\x00\x00\xff\x9a\x9a\x9a\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\x9a\x9a\x9a\xff\x00\x00\x00\xff\x08\x08\x08\xff\xe2\xe2\xe2\xff\xe6\xe6\xe6\xff\xcc\xcc\xcc\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\xb4\xb4\xb4\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\x1d\x1d\x1d\xff\x00\x00\x00\xff\x9a\x9a\x9a\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\x9a\x9a\x9a\xff\x00\x00\x00\xff\x00\x00\x00\xff\xba\xba\xba\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\x19\x19\x19\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\xb4\xb4\xb4\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\x1d\x1d\x1d\xff\x00\x00\x00\xff\x9a\x9a\x9a\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\x9a\x9a\x9a\xff\x00\x00\x00\xff\x00\x00\x00\xff\x85\x85\x85\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\x98\x98\x98\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\xb4\xb4\xb4\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\x1d\x1d\x1d\xff\x00\x00\x00\xff\x9a\x9a\x9a\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\x9a\x9a\x9a\xff\x00\x00\x00\xff\x00\x00\x00\xff\x19\x19\x19\xff\xd9\xd9\xd9\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\x91\x91\x91\xff\x0f\x0f\x0f\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\xb4\xb4\xb4\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\x1d\x1d\x1d\xff\x00\x00\x00\xff\x9a\x9a\x9a\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\x9a\x9a\x9a\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xffZZZ\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe2\xe2\xe2\xff\xbc\xbc\xbc\xff\x9f\x9f\x9f\xff\x9f\x9f\x9f\xff\x9f\x9f\x9f\xff\xd7\xd7\xd7\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\x1d\x1d\x1d\xff\x00\x00\x00\xff\x9a\x9a\x9a\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\x9a\x9a\x9a\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xffaaa\xff\xdc\xdc\xdc\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\x1d\x1d\x1d\xff\x00\x00\x00\xff\x9a\x9a\x9a\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\x9a\x9a\x9a\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x1e\x1e\x1e\xff\x93\x93\x93\xff\xc6\xc6\xc6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\x1d\x1d\x1d\xff\x00\x00\x00\xff\x9a\x9a\x9a\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\x9a\x9a\x9a\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x0e\x0e\x0e\xff***\xff+++\xff+++\xff\xaf\xaf\xaf\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe2\xe2\xe2\xff\x10\x10\x10\xff\x00\x00\x00\xff\x9a\x9a\x9a\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\x9a\x9a\x9a\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff@@@\xff\xd2\xd2\xd2\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe1\xe1\xe1\xff{{{\xff\x00\x00\x00\xff\x00\x00\x00\xff\x9a\x9a\x9a\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xf1\xa9\xa9\xa9\xff\xa6\xa6\xa6\xff\x05\x05\x05\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x05\x05\x05\xff\x16\x16\x16\xff\x16\x16\x16\xff\x16\x16\x16\xff\x16\x16\x16\xff\x16\x16\x16\xff\x16\x16\x16\xff\x16\x16\x16\xff\x16\x16\x16\xff\x0c\x0c\x0c\xff\x00\x00\x00\xff\x00\x00\x00\xff\x05\x05\x05\xff\xa6\xa6\xa6\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xf1\xa9\xa9\xa9\xbd\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff)))\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff)))\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xbd\xa9\xa9\xa9\x88\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\x88\x88\x88\xff\x03\x03\x03\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x03\x03\x03\xff\x88\x88\x88\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\x88\xaa\xaa\xaa\x15\xa9\xa9\xa9\xeb\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\x88\x88\x88\xff)))\xff\x05\x05\x05\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x05\x05\x05\xff)))\xff\x88\x88\x88\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xeb\xaa\xaa\xaa\x15\xff\xff\xff\x00\xaa\xaa\xaaW\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa6\xa6\xa6\xff\x9a\x9a\x9a\xff\x9a\x9a\x9a\xff\x9a\x9a\x9a\xff\x9a\x9a\x9a\xff\x9a\x9a\x9a\xff\x9a\x9a\x9a\xff\x9a\x9a\x9a\xff\x9a\x9a\x9a\xff\x9a\x9a\x9a\xff\x9a\x9a\x9a\xff\x9a\x9a\x9a\xff\x9a\x9a\x9a\xff\x9a\x9a\x9a\xff\x9a\x9a\x9a\xff\x9a\x9a\x9a\xff\x9a\x9a\x9a\xff\x9a\x9a\x9a\xff\x9a\x9a\x9a\xff\xa6\xa6\xa6\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xaa\xaa\xaaW\xff\xff\xff\x00\xff\xff\xff\x00\xff\xff\xff\x00\xaa\xaa\xaaW\xa9\xa9\xa9\xeb\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xeb\xaa\xaa\xaaW\xff\xff\xff\x00\xff\xff\xff\x00\xff\xff\xff\x00\xff\xff\xff\x00\xff\xff\xff\x00\xaa\xaa\xaa\x15\xa9\xa9\xa9\x88\xa9\xa9\xa9\xbd\xa9\xa9\xa9\xf1\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xf1\xa9\xa9\xa9\xbe\xa9\xa9\xa9\x88\xaa\xaa\xaa\x15\xff\xff\xff\x00\xff\xff\xff\x00\xff\xff\xff\x00q\rtq\x0eb.', 'default.png': b'\x80\x03cnumpy.core.multiarray\n_reconstruct\nq\x00cnumpy\nndarray\nq\x01K\x00\x85q\x02C\x01bq\x03\x87q\x04Rq\x05(K\x01K\x10K\x10K\x04\x87q\x06cnumpy\ndtype\nq\x07X\x02\x00\x00\x00u1q\x08K\x00K\x01\x87q\tRq\n(K\x03X\x01\x00\x00\x00|q\x0bNNNJ\xff\xff\xff\xffJ\xff\xff\xff\xffK\x00tq\x0cb\x89B\x00\x04\x00\x00\x00\x7f\xa6\x1b\x0c\x8a\xad\xdc\r\x91\xb0\xf3\r\x91\xb0\xf3\r\x91\xb0\xf4\r\x91\xb1\xf4\r\x90\xb0\xf4\x05\x85\xa9\xef\x00\x7f\xa6<\xff\xff\xff\x00\xff\xff\xff\x00\xff\xff\xff\x00\xff\xff\xff\x00\xff\xff\xff\x00\xff\xff\xff\x00\xff\xff\xff\x00\x00\x7f\xa6!\x1d\x9c\xb9\xf5g\xd9\xf1\xffi\xd9\xf3\xffd\xd1\xee\xff]\xcb\xeb\xff@\xbb\xe3\xff\x16\x9c\xc2\xf8\x00\x7f\xa6\xb4\xff\xff\xff\x00\xff\xff\xff\x00\xff\xff\xff\x00\xff\xff\xff\x00\xff\xff\xff\x00\xff\xff\xff\x00\xff\xff\xff\x00\xff\xff\xff\x00\x00\x7f\xa6U\'\xac\xc5\xf9i\xd9\xf3\xffc\xd3\xef\xff\\\xcf\xeb\xffP\xc8\xe6\xff\x17\x9f\xc4\xfd\x00\x7f\xa6\xfc\xff\xff\xff\x00\xff\xff\xff\x00\xff\xff\xff\x00\xff\xff\xff\x00\xff\xff\xff\x00\xff\xff\xff\x00\xff\xff\xff\x00\xff\xff\xff\x00\x02\x83\xa8lH\xc5\xdd\xfah\xdc\xf3\xffc\xd4\xef\xffV\xce\xe9\xffN\xcf\xe7\xff&\xaa\xca\xfd\x00\x7f\xa6\xff\x03\x81\xc7\x01\x04\x8d\xda\x01\t\x94\xd9\x01\xff\xff\xff\x00\xff\xff\xff\x00\xff\xff\xff\x00\xff\xff\xff\x00\x00\x7f\xa6"$\xa9\xc4\xf7g\xdf\xf5\xfff\xdb\xf3\xffU\xcd\xeb\xff\x16\xb3\xda\xff.\xc9\xe1\xff(\xb2\xd0\xfe\x01\x7f\xa6\xff\x04\x84\xc9\x05\t\x94\xd9\x06\x10\x9c\xd7\x01\x16\xa2\xd6\x01\xff\xff\xff\x00\xff\xff\xff\x00\xff\xff\xff\x00\x02\x83\xa9\x81T\xd3\xeb\xffg\xe5\xf7\xffe\xda\xf3\xff!\xaa\xde\xff\x11\x9d\xc3\xfe\x11\xba\xd7\xff \xb9\xd5\xfe\x00\x7f\xa6\xff\x16u\x8d\x03\x14\x84\xae\x05\xff\xff\xff\x00\xff\xff\xff\x00\xff\xff\xff\x00\xff\xff\xff\x00\xff\xff\xff\x00\x10\x92\xb4\xc0d\xde\xf3\xffg\xe5\xf7\xff_\xcc\xef\xff\x0e\x9c\xd5\xff\rx\x95\xf6\x0e\x89\xab\xf4\x18\xb2\xd1\xfc\x00\x7f\xa6\xff\xff\xff\xff\x00\x1a~\x91\x01\x1d\xa5\xce\x01\xff\xff\xff\x00\xff\xff\xff\x00\xff\xff\xff\x00\xff\xff\xff\x005\xa9\xc3\xefq\xec\xf9\xffg\xe5\xf7\xff>\xb7\xe8\xff\x14\x96\xc8\xfe\x02}\xa3\xb1\x00\x7f\xa6Q\x03\x82\xa9\xe8\x00\x7f\xa6\xe9\xff\xff\xff\x00\x00\x7f\xa6\x11\x1c\x98\xb8\x04%\xb5\xd3\x01\xff\xff\xff\x00\xff\xff\xff\x00\xff\xff\xff\x00D\xad\xc8\xf3r\xec\xf9\xffg\xe5\xf7\xff:\xb7\xe8\xff\x19\x90\xc5\xfe\x03{\xa0\xa6\xff\xff\xff\x00\x00\x7f\xa6*\x00\x7f\xa6*\xff\xff\xff\x00\x00\x7f\xa6\x98\x0f\x8f\xb1\x13&\xb5\xd3\x04.\xc0\xd1\x01\xff\xff\xff\x00\xff\xff\xff\x00\x19\x93\xb7\xc6i\xdf\xf4\xffg\xe5\xf7\xffT\xc8\xee\xff\x06\x88\xcd\xff\x08g\x85\xf7\x00\x7f\xa6\x15\xff\xff\xff\x00\xff\xff\xff\x00\x00\x7f\xa6\x1b\x01\x80\xa7\xeb\x1d\xa3\xca\x16#\xb2\xd4\n*\xbb\xd2\x04.\xbc\xd7\x01\xff\xff\xff\x00\x01\x81\xa7\x88Y\xd1\xee\xffg\xe5\xf7\xfff\xd9\xf3\xff\'\xa2\xe2\xff\x05e\x99\xf9\x06~\xa5\xf3\x01\x81\xa8\x9c\x01\x80\xa8\x9f\x04\x85\xad\xef\x08\x8f\xb9\x92\x17\xa4\xd6*\x1e\xac\xd5\x1a$\xb3\xd3\x0c\x19\xa7\xd5\x02\xff\xff\xff\x00\x00\x7f\xa6+!\xa3\xc8\xf5i\xe0\xf5\xffe\xd9\xf3\xff\\\xca\xee\xff\x1f\x9c\xe0\xfa\x03\x84\xca\xd6\x07\x8b\xc5\xca\x06\x88\xc1\xb8\x08\x8e\xd0l\x0b\x96\xd8I\x11\x9e\xd74\x17\xa5\xd6 \xab\xd7\x0b\x17\xa2\xdc\x01\xff\xff\xff\x00\xff\xff\xff\x00\x01\x80\xa8~?\xb9\xe0\xf9h\xda\xf3\xff_\xcc\xef\xffV\xc1\xec\xfd3\xa7\xe3\xe3\x1a\x96\xde\xae\x04\x8b\xdb\x89\x00\x89\xdao\x05\x8f\xd9T\x0b\x96\xd8<\x11\x9b\xd7\x1d\x18\x95\xc9\x0c\x00\x80\xd5\x00\xff\xff\xff\x00\xff\xff\xff\x00\x00\x7f\xa6\x04\x03\x83\xaa\xcd5\xa2\xc9\xf9[\xc6\xea\xffU\xc1\xec\xffH\xb4\xe8\xf39\xa8\xe4\xc5\x0b\x8f\xdc\x9f\x00\x89\xda{\x00\x89\xda_\x07\x87\xc4I\x05|\xa5s\x05m\xa3\x02\xff\xff\xff\x00\xff\xff\xff\x00\xff\xff\xff\x00\xff\xff\xff\x00\x00\x7f\xa6\x06\x01\x7f\xa6\x89\x12x\x9e\xf63\x88\xae\xfe6\x93\xc3\xfe4\x9d\xd6\xdf\x08\x82\xc7\xb8\x03k\xa2\xab\x04k\x97\xa8\x02w\x9e\xeb\x00\x7f\xa6j\xff\xff\xff\x00\xff\xff\xff\x00\xff\xff\xff\x00\xff\xff\xff\x00\xff\xff\xff\x00\xff\xff\xff\x00\xff\xff\xff\x00\x00\x7f\xa67\x00~\xa5\x95\x03v\x9c\xd4\x03h\x8c\xfa\x02i\x8e\xf9\x01x\x9f\xcc\x00\x7f\xa6\x92\x00\x7f\xa63\xff\xff\xff\x00\xff\xff\xff\x00\xff\xff\xff\x00\xff\xff\xff\x00q\rtq\x0eb.', 'ctrl.png': b'\x80\x03cnumpy.core.multiarray\n_reconstruct\nq\x00cnumpy\nndarray\nq\x01K\x00\x85q\x02C\x01bq\x03\x87q\x04Rq\x05(K\x01K K K\x04\x87q\x06cnumpy\ndtype\nq\x07X\x02\x00\x00\x00u1q\x08K\x00K\x01\x87q\tRq\n(K\x03X\x01\x00\x00\x00|q\x0bNNNJ\xff\xff\xff\xffJ\xff\xff\xff\xffK\x00tq\x0cb\x89B\x00\x10\x00\x00\xff\xff\xff\x00\xff\xff\xff\x00\xff\xff\xff\x00\xad\xad\xad\x19\xa8\xa8\xa8\x8d\xa9\xa9\xa9\xc1\xa9\xa9\xa9\xf1\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xf1\xaa\xaa\xaa\xc2\xa9\xa9\xa9\x8e\xad\xad\xad\x19\xff\xff\xff\x00\xff\xff\xff\x00\xff\xff\xff\x00\xff\xff\xff\x00\xff\xff\xff\x00\xa8\xa8\xa8X\xa9\xa9\xa9\xed\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xed\xa8\xa8\xa8X\xff\xff\xff\x00\xff\xff\xff\x00\xff\xff\xff\x00\xaa\xaa\xaaW\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa6\xa6\xa6\xff\x9a\x9a\x9a\xff\x9a\x9a\x9a\xff\x9a\x9a\x9a\xff\x9a\x9a\x9a\xff\x9a\x9a\x9a\xff\x9a\x9a\x9a\xff\x9a\x9a\x9a\xff\x9a\x9a\x9a\xff\x9a\x9a\x9a\xff\x9a\x9a\x9a\xff\x9a\x9a\x9a\xff\x9a\x9a\x9a\xff\x9a\x9a\x9a\xff\x9a\x9a\x9a\xff\x9a\x9a\x9a\xff\x9a\x9a\x9a\xff\x9a\x9a\x9a\xff\x9a\x9a\x9a\xff\xa6\xa6\xa6\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xaa\xaa\xaaW\xff\xff\xff\x00\xaa\xaa\xaa\x15\xa9\xa9\xa9\xeb\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\x88\x88\x88\xff)))\xff\x05\x05\x05\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x05\x05\x05\xff)))\xff\x88\x88\x88\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xeb\xaa\xaa\xaa\x15\xa9\xa9\xa9\x88\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\x88\x88\x88\xff\x03\x03\x03\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x03\x03\x03\xff\x88\x88\x88\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\x88\xa9\xa9\xa9\xbe\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff)))\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff555\xffPPP\xff\x13\x13\x13\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff)))\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xbe\xa9\xa9\xa9\xf1\xa9\xa9\xa9\xff\xa6\xa6\xa6\xff\x05\x05\x05\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x01\x01\x01\xff\xb2\xb2\xb2\xff\xe3\xe3\xe3\xff\xd9\xd9\xd9\xff]]]\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x05\x05\x05\xff\xa6\xa6\xa6\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xf1\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\x9a\x9a\x9a\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x13\x13\x13\xff\xbb\xbb\xbb\xff\xe3\xe3\xe3\xff\xe3\xe3\xe3\xffFFF\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x9a\x9a\x9a\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\x9a\x9a\x9a\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x13\x13\x13\xff\xbb\xbb\xbb\xff\xe3\xe3\xe3\xff\xc4\xc4\xc4\xff\x06\x06\x06\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x9a\x9a\x9a\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\x9a\x9a\x9a\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff```\xff\xe3\xe3\xe3\xff\xe3\xe3\xe3\xff:::\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x9a\x9a\x9a\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\x9a\x9a\x9a\xff\x00\x00\x00\xff\x00\x00\x00\xff666\xff\xaf\xaf\xaf\xff\x10\x10\x10\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x9b\x9b\x9b\xff\xe3\xe3\xe3\xff\xe3\xe3\xe3\xff@@@\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x9a\x9a\x9a\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\x9a\x9a\x9a\xff\x00\x00\x00\xff\x00\x00\x00\xffSSS\xff\xe3\xe3\xe3\xff\xb7\xb7\xb7\xff\x10\x10\x10\xff\x00\x00\x00\xff\x00\x00\x00\xff\x04\x04\x04\xff\xd5\xd5\xd5\xff\xe3\xe3\xe3\xff\xe3\xe3\xe3\xffXXX\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x9a\x9a\x9a\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\x9a\x9a\x9a\xff\x00\x00\x00\xff\x00\x00\x00\xff\x17\x17\x17\xff\xdb\xdb\xdb\xff\xe3\xe3\xe3\xff\xb7\xb7\xb7\xff[[[\xff\x97\x97\x97\xff\xd4\xd4\xd4\xff\xe3\xe3\xe3\xff\xe3\xe3\xe3\xff\xe3\xe3\xe3\xff\xda\xda\xda\xff;;;\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x9a\x9a\x9a\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\x9a\x9a\x9a\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff```\xff\xe3\xe3\xe3\xff\xe3\xe3\xe3\xff\xe3\xe3\xe3\xff\xe3\xe3\xe3\xff\xe3\xe3\xe3\xff\xe3\xe3\xe3\xff\xe3\xe3\xe3\xff\xe3\xe3\xe3\xff\xe3\xe3\xe3\xff\xda\xda\xda\xff;;;\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x9a\x9a\x9a\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\x9a\x9a\x9a\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xffHHH\xff\xc6\xc6\xc6\xff\xe3\xe3\xe3\xff\xe3\xe3\xe3\xff\xe3\xe3\xe3\xff\xe3\xe3\xe3\xff\xe3\xe3\xe3\xff\xe3\xe3\xe3\xff\xe3\xe3\xe3\xff\xe3\xe3\xe3\xff\xda\xda\xda\xff;;;\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x9a\x9a\x9a\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\x9a\x9a\x9a\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x07\x07\x07\xff;;;\xffAAA\xff\\\\\\\xff\xdd\xdd\xdd\xff\xe3\xe3\xe3\xff\xe3\xe3\xe3\xff\xe3\xe3\xe3\xff\xe3\xe3\xe3\xff\xe3\xe3\xe3\xff\xda\xda\xda\xff;;;\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x9a\x9a\x9a\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\x9a\x9a\x9a\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff@@@\xff\xdd\xdd\xdd\xff\xe3\xe3\xe3\xff\xe3\xe3\xe3\xff\xe3\xe3\xe3\xff\xe3\xe3\xe3\xff\xe3\xe3\xe3\xff\xda\xda\xda\xff;;;\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x9a\x9a\x9a\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\x9a\x9a\x9a\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff@@@\xff\xdd\xdd\xdd\xff\xe3\xe3\xe3\xff\xe3\xe3\xe3\xff\xe3\xe3\xe3\xff\xe3\xe3\xe3\xff\xe3\xe3\xe3\xff\xda\xda\xda\xff;;;\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x9a\x9a\x9a\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\x9a\x9a\x9a\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff@@@\xff\xdd\xdd\xdd\xff\xe3\xe3\xe3\xff\xe3\xe3\xe3\xff\xe3\xe3\xe3\xff\xe3\xe3\xe3\xff\xe3\xe3\xe3\xff\xda\xda\xda\xff;;;\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x9a\x9a\x9a\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\x9a\x9a\x9a\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff@@@\xff\xdd\xdd\xdd\xff\xe3\xe3\xe3\xff\xe3\xe3\xe3\xff\xe3\xe3\xe3\xff\xe3\xe3\xe3\xff\xe3\xe3\xe3\xff\xda\xda\xda\xff;;;\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x9a\x9a\x9a\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\x9a\x9a\x9a\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff@@@\xff\xdd\xdd\xdd\xff\xe3\xe3\xe3\xff\xe3\xe3\xe3\xff\xe3\xe3\xe3\xff\xe3\xe3\xe3\xff\xe3\xe3\xe3\xff\xda\xda\xda\xff;;;\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x9a\x9a\x9a\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\x9a\x9a\x9a\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff@@@\xff\xdd\xdd\xdd\xff\xe3\xe3\xe3\xff\xe3\xe3\xe3\xff\xe3\xe3\xe3\xff\xe3\xe3\xe3\xff\xe3\xe3\xe3\xff\xda\xda\xda\xff;;;\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x9a\x9a\x9a\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\x9a\x9a\x9a\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff@@@\xff\xdd\xdd\xdd\xff\xe3\xe3\xe3\xff\xe3\xe3\xe3\xff\xc7\xc7\xc7\xffZZZ\xff~~~\xff\xd9\xd9\xd9\xff\x10\x10\x10\xff\x00\x00\x00\xff\x00\x00\x00\xff\x9a\x9a\x9a\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\x9a\x9a\x9a\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff@@@\xff\xdd\xdd\xdd\xff\xe3\xe3\xe3\xffXXX\xff\x00\x00\x00\xff\x00\x00\x00\xff\xb0\xb0\xb0\xfffff\xff\x00\x00\x00\xff\x00\x00\x00\xff\x9a\x9a\x9a\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\x9a\x9a\x9a\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff@@@\xff\xdd\xdd\xdd\xffyyy\xff\x00\x00\x00\xff\x06\x06\x06\xff\xcd\xcd\xcd\xfffff\xff\x00\x00\x00\xff\x00\x00\x00\xff\x9a\x9a\x9a\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xf1\xa9\xa9\xa9\xff\xa6\xa6\xa6\xff\x05\x05\x05\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff@@@\xff\xda\xda\xda\xff\xaf\xaf\xaf\xff\xcd\xcd\xcd\xff\xd7\xd7\xd7\xff\x10\x10\x10\xff\x00\x00\x00\xff\x05\x05\x05\xff\xa6\xa6\xa6\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xf1\xa9\xa9\xa9\xbd\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff)))\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x12\x12\x12\xffiii\xffccc\xff\x0e\x0e\x0e\xff\x00\x00\x00\xff\x00\x00\x00\xff)))\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xbd\xa9\xa9\xa9\x88\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\x88\x88\x88\xff\x03\x03\x03\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x03\x03\x03\xff\x88\x88\x88\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\x88\xaa\xaa\xaa\x15\xa9\xa9\xa9\xeb\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\x88\x88\x88\xff)))\xff\x05\x05\x05\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x05\x05\x05\xff)))\xff\x88\x88\x88\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xeb\xaa\xaa\xaa\x15\xff\xff\xff\x00\xaa\xaa\xaaW\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa6\xa6\xa6\xff\x9a\x9a\x9a\xff\x9a\x9a\x9a\xff\x9a\x9a\x9a\xff\x9a\x9a\x9a\xff\x9a\x9a\x9a\xff\x9a\x9a\x9a\xff\x9a\x9a\x9a\xff\x9a\x9a\x9a\xff\x9a\x9a\x9a\xff\x9a\x9a\x9a\xff\x9a\x9a\x9a\xff\x9a\x9a\x9a\xff\x9a\x9a\x9a\xff\x9a\x9a\x9a\xff\x9a\x9a\x9a\xff\x9a\x9a\x9a\xff\x9a\x9a\x9a\xff\x9a\x9a\x9a\xff\xa6\xa6\xa6\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xaa\xaa\xaaW\xff\xff\xff\x00\xff\xff\xff\x00\xff\xff\xff\x00\xaa\xaa\xaaW\xa9\xa9\xa9\xeb\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xeb\xaa\xaa\xaaW\xff\xff\xff\x00\xff\xff\xff\x00\xff\xff\xff\x00\xff\xff\xff\x00\xff\xff\xff\x00\xaa\xaa\xaa\x15\xa9\xa9\xa9\x88\xa9\xa9\xa9\xbd\xa9\xa9\xa9\xf1\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xf1\xa9\xa9\xa9\xbe\xa9\xa9\xa9\x88\xaa\xaa\xaa\x15\xff\xff\xff\x00\xff\xff\xff\x00\xff\xff\xff\x00q\rtq\x0eb.', 'auto.png': b'\x80\x03cnumpy.core.multiarray\n_reconstruct\nq\x00cnumpy\nndarray\nq\x01K\x00\x85q\x02C\x01bq\x03\x87q\x04Rq\x05(K\x01K K K\x04\x87q\x06cnumpy\ndtype\nq\x07X\x02\x00\x00\x00u1q\x08K\x00K\x01\x87q\tRq\n(K\x03X\x01\x00\x00\x00|q\x0bNNNJ\xff\xff\xff\xffJ\xff\xff\xff\xffK\x00tq\x0cb\x89B\x00\x10\x00\x00\xff\xff\xff\x00\xff\xff\xff\x00\xff\xff\xff\x00\xad\xad\xad\x19\xa8\xa8\xa8\x8d\xa9\xa9\xa9\xc1\xa9\xa9\xa9\xf1\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xf1\xaa\xaa\xaa\xc2\xa9\xa9\xa9\x8e\xad\xad\xad\x19\xff\xff\xff\x00\xff\xff\xff\x00\xff\xff\xff\x00\xff\xff\xff\x00\xff\xff\xff\x00\xa8\xa8\xa8X\xa9\xa9\xa9\xed\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xed\xa8\xa8\xa8X\xff\xff\xff\x00\xff\xff\xff\x00\xff\xff\xff\x00\xaa\xaa\xaaW\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa6\xa6\xa6\xff\x9a\x9a\x9a\xff\x9a\x9a\x9a\xff\x9a\x9a\x9a\xff\x9a\x9a\x9a\xff\x9a\x9a\x9a\xff\x9a\x9a\x9a\xff\x9a\x9a\x9a\xff\x9a\x9a\x9a\xff\x9a\x9a\x9a\xff\x9a\x9a\x9a\xff\x9a\x9a\x9a\xff\x9a\x9a\x9a\xff\x9a\x9a\x9a\xff\x9a\x9a\x9a\xff\x9a\x9a\x9a\xff\x9a\x9a\x9a\xff\x9a\x9a\x9a\xff\x9a\x9a\x9a\xff\xa6\xa6\xa6\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xaa\xaa\xaaW\xff\xff\xff\x00\xaa\xaa\xaa\x15\xa9\xa9\xa9\xeb\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\x88\x88\x88\xff)))\xff\x05\x05\x05\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x05\x05\x05\xff)))\xff\x88\x88\x88\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xeb\xaa\xaa\xaa\x15\xa9\xa9\xa9\x88\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\x88\x88\x88\xff\x03\x03\x03\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x19\x19\x19\xff\x03\x03\x03\xff\x88\x88\x88\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\x88\xa9\xa9\xa9\xbe\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff)))\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x04\x04\x04\xffHHH\xff\xa4\xa4\xa4\xff\xe5\xe5\xe5\xff\x00\x00\x00\xff)))\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xbe\xa9\xa9\xa9\xf1\xa9\xa9\xa9\xff\xa6\xa6\xa6\xff\x05\x05\x05\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff \xffyyy\xff\xd1\xd1\xd1\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\x00\x00\x00\xff\x05\x05\x05\xff\xa6\xa6\xa6\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xf1\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\x9a\x9a\x9a\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x06\x06\x06\xffPPP\xff\xab\xab\xab\xff\xe6\xe6\xe6\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\x00\x00\x00\xff\x00\x00\x00\xff\x9a\x9a\x9a\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\x9a\x9a\x9a\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff&&&\xff\x82\x82\x82\xff\xd6\xd6\xd6\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\x00\x00\x00\xff\x00\x00\x00\xff\x9a\x9a\x9a\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\x9a\x9a\x9a\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\t\t\t\xffWWW\xff\xb2\xb2\xb2\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe5\xe5\xe5\xff\xa8\xa8\xa8\xff\x00\x00\x00\xff\x00\x00\x00\xff\x9a\x9a\x9a\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\x9a\x9a\x9a\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff---\xff\x89\x89\x89\xff\xda\xda\xda\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xc1\xc1\xc1\xfflll\xff\x18\x18\x18\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x9a\x9a\x9a\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\x9a\x9a\x9a\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\r\r\r\xff^^^\xff\xba\xba\xba\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xda\xda\xda\xff...\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x9a\x9a\x9a\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\x9a\x9a\x9a\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff555\xff\x90\x90\x90\xff\xde\xde\xde\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe2\xe2\xe2\xff\xe3\xe3\xe3\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xd2\xd2\xd2\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x9a\x9a\x9a\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\x9a\x9a\x9a\xff\x00\x00\x00\xff;;;\xff\xc1\xc1\xc1\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xb7\xb7\xb7\xffbbb\xff\x12\x12\x12\xff\xcb\xcb\xcb\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xd2\xd2\xd2\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x9a\x9a\x9a\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\x9a\x9a\x9a\xff\x00\x00\x00\xffmmm\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xcd\xcd\xcd\xffyyy\xff$$$\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\xcb\xcb\xcb\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xd2\xd2\xd2\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x9a\x9a\x9a\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\x9a\x9a\x9a\xff\x00\x00\x00\xffmmm\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe3\xe3\xe3\xff\x91\x91\x91\xff<<<\xff\x01\x01\x01\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\xcb\xcb\xcb\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xd2\xd2\xd2\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x9a\x9a\x9a\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\x9a\x9a\x9a\xff\x00\x00\x00\xffmmm\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xc3\xc3\xc3\xfflll\xff\x18\x18\x18\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\xcb\xcb\xcb\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xd2\xd2\xd2\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x9a\x9a\x9a\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\x9a\x9a\x9a\xff\x00\x00\x00\xffmmm\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe4\xe4\xe4\xff\xa6\xa6\xa6\xffOOO\xff\x07\x07\x07\xff\x00\x00\x00\xff\x00\x00\x00\xff\xcb\xcb\xcb\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xd2\xd2\xd2\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x9a\x9a\x9a\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\x9a\x9a\x9a\xff\x00\x00\x00\xff555\xff\xb4\xb4\xb4\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xd9\xd9\xd9\xff\x8a\x8a\x8a\xff333\xff\xcb\xcb\xcb\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xd2\xd2\xd2\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x9a\x9a\x9a\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\x9a\x9a\x9a\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff+++\xff\x88\x88\x88\xff\xda\xda\xda\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xd2\xd2\xd2\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x9a\x9a\x9a\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\x9a\x9a\x9a\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\n\n\n\xff[[[\xff\xb8\xb8\xb8\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xdc\xdc\xdc\xffAAA\xff\x02\x02\x02\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x9a\x9a\x9a\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\x9a\x9a\x9a\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff...\xff\x8c\x8c\x8c\xff\xdc\xdc\xdc\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xcc\xcc\xcc\xffsss\xff\x1a\x1a\x1a\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x9a\x9a\x9a\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\x9a\x9a\x9a\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x0c\x0c\x0c\xff___\xff\xbc\xbc\xbc\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe5\xe5\xe5\xff\xa5\xa5\xa5\xff\x00\x00\x00\xff\x00\x00\x00\xff\x9a\x9a\x9a\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\x9a\x9a\x9a\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff222\xff\x8f\x8f\x8f\xff\xde\xde\xde\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\x00\x00\x00\xff\x00\x00\x00\xff\x9a\x9a\x9a\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\x9a\x9a\x9a\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x0e\x0e\x0e\xffccc\xff\xc0\xc0\xc0\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\x00\x00\x00\xff\x00\x00\x00\xff\x9a\x9a\x9a\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xf1\xa9\xa9\xa9\xff\xa6\xa6\xa6\xff\x05\x05\x05\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff555\xff\x94\x94\x94\xff\xe0\xe0\xe0\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\x00\x00\x00\xff\x05\x05\x05\xff\xa6\xa6\xa6\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xf1\xa9\xa9\xa9\xbd\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff)))\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x10\x10\x10\xfffff\xff\xc4\xc4\xc4\xff\xe7\xe7\xe7\xff\x00\x00\x00\xff)))\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xbd\xa9\xa9\xa9\x88\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\x88\x88\x88\xff\x03\x03\x03\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff:::\xff\x03\x03\x03\xff\x88\x88\x88\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\x88\xaa\xaa\xaa\x15\xa9\xa9\xa9\xeb\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\x88\x88\x88\xff)))\xff\x05\x05\x05\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x05\x05\x05\xff)))\xff\x88\x88\x88\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xeb\xaa\xaa\xaa\x15\xff\xff\xff\x00\xaa\xaa\xaaW\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa6\xa6\xa6\xff\x9a\x9a\x9a\xff\x9a\x9a\x9a\xff\x9a\x9a\x9a\xff\x9a\x9a\x9a\xff\x9a\x9a\x9a\xff\x9a\x9a\x9a\xff\x9a\x9a\x9a\xff\x9a\x9a\x9a\xff\x9a\x9a\x9a\xff\x9a\x9a\x9a\xff\x9a\x9a\x9a\xff\x9a\x9a\x9a\xff\x9a\x9a\x9a\xff\x9a\x9a\x9a\xff\x9a\x9a\x9a\xff\x9a\x9a\x9a\xff\x9a\x9a\x9a\xff\x9a\x9a\x9a\xff\xa6\xa6\xa6\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xaa\xaa\xaaW\xff\xff\xff\x00\xff\xff\xff\x00\xff\xff\xff\x00\xaa\xaa\xaaW\xa9\xa9\xa9\xeb\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xeb\xaa\xaa\xaaW\xff\xff\xff\x00\xff\xff\xff\x00\xff\xff\xff\x00\xff\xff\xff\x00\xff\xff\xff\x00\xaa\xaa\xaa\x15\xa9\xa9\xa9\x88\xa9\xa9\xa9\xbd\xa9\xa9\xa9\xf1\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xf1\xa9\xa9\xa9\xbe\xa9\xa9\xa9\x88\xaa\xaa\xaa\x15\xff\xff\xff\x00\xff\xff\xff\x00\xff\xff\xff\x00q\rtq\x0eb.'} | mit |
cloudera/hue | desktop/libs/notebook/src/notebook/conf.py | 2 | 14842 | #!/usr/bin/env python
# Licensed to Cloudera, Inc. under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. Cloudera, Inc. 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 json
import logging
import sys
from collections import OrderedDict
from django.test.client import Client
from django.urls import reverse
from desktop import appmanager
from desktop.conf import is_oozie_enabled, has_connectors, is_cm_managed, ENABLE_UNIFIED_ANALYTICS
from desktop.lib.conf import Config, UnspecifiedConfigSection, ConfigSection, coerce_json_dict, coerce_bool, coerce_csv
if sys.version_info[0] > 2:
from django.utils.translation import gettext_lazy as _t, gettext as _
else:
from django.utils.translation import ugettext_lazy as _t, ugettext as _
LOG = logging.getLogger(__name__)
# Not used when connector are on
INTERPRETERS_CACHE = None
SHOW_NOTEBOOKS = Config(
key="show_notebooks",
help=_t("Show the notebook menu or not"),
type=coerce_bool,
default=True
)
def _remove_duplications(a_list):
return list(OrderedDict.fromkeys(a_list))
def check_has_missing_permission(user, interpreter, user_apps=None):
# TODO: port to cluster config
if user_apps is None:
user_apps = appmanager.get_apps_dict(user) # Expensive method
return (interpreter == 'hive' and 'hive' not in user_apps) or \
(interpreter == 'impala' and 'impala' not in user_apps) or \
(interpreter == 'pig' and 'pig' not in user_apps) or \
(interpreter == 'solr' and 'search' not in user_apps) or \
(interpreter in ('spark', 'pyspark', 'r', 'jar', 'py', 'sparksql') and 'spark' not in user_apps) or \
(interpreter in ('java', 'spark2', 'mapreduce', 'shell', 'sqoop1', 'distcp') and 'oozie' not in user_apps)
def _connector_to_interpreter(connector):
return {
'name': connector['nice_name'],
'type': connector['name'], # Aka id
'dialect': connector['dialect'],
'category': connector['category'],
'is_sql': connector['dialect_properties']['is_sql'],
'interface': connector['interface'],
'options': {setting['name']: setting['value'] for setting in connector['settings']},
'dialect_properties': connector['dialect_properties'],
}
def get_ordered_interpreters(user=None):
global INTERPRETERS_CACHE
if has_connectors():
from desktop.lib.connectors.api import _get_installed_connectors
interpreters = [
_connector_to_interpreter(connector)
for connector in _get_installed_connectors(categories=['editor', 'catalogs'], user=user)
]
else:
if INTERPRETERS_CACHE is None:
none_user = None # for getting full list of interpreters
if is_cm_managed():
extra_interpreters = INTERPRETERS.get() # Combine the other apps interpreters
_default_interpreters(none_user)
else:
extra_interpreters = {}
if not INTERPRETERS.get():
_default_interpreters(none_user)
INTERPRETERS_CACHE = INTERPRETERS.get()
INTERPRETERS_CACHE.update(extra_interpreters)
user_apps = appmanager.get_apps_dict(user)
user_interpreters = []
for interpreter in INTERPRETERS_CACHE:
if check_has_missing_permission(user, interpreter, user_apps=user_apps):
pass # Not allowed
else:
user_interpreters.append(interpreter)
interpreters_shown_on_wheel = _remove_duplications(INTERPRETERS_SHOWN_ON_WHEEL.get())
unknown_interpreters = set(interpreters_shown_on_wheel) - set(user_interpreters)
if unknown_interpreters:
# Just filtering it out might be better than failing for this user
raise ValueError("Interpreters from interpreters_shown_on_wheel is not in the list of Interpreters %s" % unknown_interpreters)
reordered_interpreters = interpreters_shown_on_wheel + [i for i in user_interpreters if i not in interpreters_shown_on_wheel]
interpreters = [{
'name': INTERPRETERS_CACHE[i].NAME.get(),
'type': i,
'interface': INTERPRETERS_CACHE[i].INTERFACE.get(),
'options': INTERPRETERS_CACHE[i].OPTIONS.get()
}
for i in reordered_interpreters
]
return [{
"name": i.get('nice_name', i['name']),
'displayName': 'Unified Analytics' if ENABLE_UNIFIED_ANALYTICS.get() and i.get('dialect', i['name']).lower() == 'hive' else i.get('nice_name', i['name']),
"type": i['type'],
"interface": i['interface'],
"options": i['options'],
'dialect': i.get('dialect', i['name']).lower(),
'dialect_properties': i.get('dialect_properties') or {}, # Empty when connectors off
'category': i.get('category', 'editor'),
"is_sql": i.get('is_sql') or \
i['interface'] in ["hiveserver2", "rdbms", "jdbc", "solr", "sqlalchemy", "ksql", "flink"] or \
i['type'] == 'sql',
"is_catalog": i['interface'] in ["hms",],
}
for i in interpreters
]
# cf. admin wizard too
INTERPRETERS = UnspecifiedConfigSection(
"interpreters",
help="One entry for each type of snippet.",
each=ConfigSection(
help=_t("Define the name and how to connect and execute the language."),
members=dict(
NAME=Config(
"name",
help=_t("The name of the snippet."),
default="SQL",
type=str,
),
INTERFACE=Config(
"interface",
help="The backend connection to use to communicate with the server.",
default="hiveserver2",
type=str,
),
OPTIONS=Config(
key='options',
help=_t('Specific options for connecting to the server.'),
type=coerce_json_dict,
default='{}'
)
)
)
)
INTERPRETERS_SHOWN_ON_WHEEL = Config(
key="interpreters_shown_on_wheel",
help=_t("Comma separated list of interpreters that should be shown on the wheel. "
"This list takes precedence over the order in which the interpreter entries appear. "
"Only the first 5 interpreters will appear on the wheel."),
type=coerce_csv,
default=[]
)
DEFAULT_LIMIT = Config(
"default_limit",
help="Default limit to use in SELECT statements if not present. Set to 0 to disable.",
default=5000,
type=int
)
ENABLE_DBPROXY_SERVER = Config(
key="enable_dbproxy_server",
help=_t("Main flag to override the automatic starting of the DBProxy server."),
type=coerce_bool,
default=True
)
DBPROXY_EXTRA_CLASSPATH = Config(
key="dbproxy_extra_classpath",
help=_t("Additional classes to put on the dbproxy classpath when starting. Values separated by ':'"),
type=str,
default=''
)
ENABLE_QUERY_BUILDER = Config(
key="enable_query_builder",
help=_t("Flag to enable the SQL query builder of the table assist."),
type=coerce_bool,
default=False
)
ENABLE_NOTEBOOK_2 = Config(
key="enable_notebook_2",
help=_t("Feature flag to enable Notebook 2."),
type=coerce_bool,
default=False
)
# Note: requires Oozie app
ENABLE_QUERY_SCHEDULING = Config(
key="enable_query_scheduling",
help=_t("Flag to enable the creation of a coordinator for the current SQL query."),
type=coerce_bool,
default=False
)
ENABLE_EXTERNAL_STATEMENT = Config(
key="enable_external_statements",
help=_t("Flag to enable the selection of queries from files, saved queries into the editor or as snippet."),
type=coerce_bool,
default=False
)
ENABLE_BATCH_EXECUTE = Config(
key="enable_batch_execute",
help=_t("Flag to enable the bulk submission of queries as a background task through Oozie."),
type=coerce_bool,
dynamic_default=is_oozie_enabled
)
ENABLE_SQL_INDEXER = Config(
key="enable_sql_indexer",
help=_t("Flag to turn on the SQL indexer."),
type=coerce_bool,
default=False
)
ENABLE_PRESENTATION = Config(
key="enable_presentation",
help=_t("Flag to turn on the Presentation mode of the editor."),
type=coerce_bool,
default=True
)
ENABLE_QUERY_ANALYSIS = Config(
key="enable_query_analysis",
help=_t("Flag to turn on the built-in hints on Impala queries in the editor."),
type=coerce_bool,
default=False
)
EXAMPLES = ConfigSection(
key='examples',
help=_t('Define which query and table examples can be automatically setup for the available dialects.'),
members=dict(
AUTO_LOAD=Config(
'auto_load',
help=_t('If installing the examples automatically at startup.'),
type=coerce_bool,
default=False
),
AUTO_OPEN=Config(
'auto_open',
help=_t('If automatically loading the dialect example at Editor opening.'),
type=coerce_bool,
default=False
),
QUERIES=Config(
'queries',
help='Names of the saved queries to install. All if empty.',
type=coerce_csv,
default=[]
),
TABLES=Config(
key='tables',
help=_t('Names of the tables to install. All if empty.'),
type=coerce_csv,
default=[]
)
)
)
def _default_interpreters(user):
interpreters = []
apps = appmanager.get_apps_dict(user)
if 'hive' in apps:
from beeswax.hive_site import get_hive_execution_engine
interpreter_name = 'Impala' if get_hive_execution_engine() == 'impala' else 'Hive' # Until using a proper dialect for 'FENG'
interpreters.append(('hive', {
'name': interpreter_name, 'interface': 'hiveserver2', 'options': {}
}),)
if 'impala' in apps:
interpreters.append(('impala', {
'name': 'Impala', 'interface': 'hiveserver2', 'options': {}
}),)
if 'pig' in apps:
interpreters.append(('pig', {
'name': 'Pig', 'interface': 'oozie', 'options': {}
}))
if 'oozie' in apps and 'jobsub' in apps:
interpreters.extend((
('java', {
'name': 'Java', 'interface': 'oozie', 'options': {}
}),
('spark2', {
'name': 'Spark', 'interface': 'oozie', 'options': {}
}),
('mapreduce', {
'name': 'MapReduce', 'interface': 'oozie', 'options': {}
}),
('shell', {
'name': 'Shell', 'interface': 'oozie', 'options': {}
}),
('sqoop1', {
'name': 'Sqoop 1', 'interface': 'oozie', 'options': {}
}),
('distcp', {
'name': 'Distcp', 'interface': 'oozie', 'options': {}
}),
))
from dashboard.conf import get_properties # Cyclic dependency
dashboards = get_properties()
if dashboards.get('solr') and dashboards['solr']['analytics']:
interpreters.append(('solr', {
'name': 'Solr SQL', 'interface': 'solr', 'options': {}
}),)
from desktop.models import Cluster # Cyclic dependency
cluster = Cluster(user)
if cluster and cluster.get_type() == 'dataeng':
interpreters.append(('dataeng', {
'name': 'DataEng', 'interface': 'dataeng', 'options': {}
}))
if 'spark' in apps:
interpreters.extend((
('spark', {
'name': 'Scala', 'interface': 'livy', 'options': {}
}),
('pyspark', {
'name': 'PySpark', 'interface': 'livy', 'options': {}
}),
('r', {
'name': 'R', 'interface': 'livy', 'options': {}
}),
('jar', {
'name': 'Spark Submit Jar', 'interface': 'livy-batch', 'options': {}
}),
('py', {
'name': 'Spark Submit Python', 'interface': 'livy-batch', 'options': {}
}),
('text', {
'name': 'Text', 'interface': 'text', 'options': {}
}),
('markdown', {
'name': 'Markdown', 'interface': 'text', 'options': {}
})
))
INTERPRETERS.set_for_testing(OrderedDict(interpreters))
def config_validator(user, interpreters=None):
res = []
if not has_connectors():
return res
client = Client()
client.force_login(user=user)
if not user.is_authenticated:
res.append(('Editor', _('Could not authenticate with user %s to validate interpreters') % user))
if interpreters is None:
interpreters = get_ordered_interpreters(user=user)
for interpreter in interpreters:
if interpreter.get('is_sql'):
connector_id = interpreter['type']
try:
response = _excute_test_query(client, connector_id, interpreter=interpreter)
data = json.loads(response.content)
if data['status'] != 0:
raise Exception(data)
except Exception as e:
trace = str(e)
msg = "Testing the connector connection failed."
if 'Error validating the login' in trace or 'TSocket read 0 bytes' in trace:
msg += ' Failed to authenticate, check authentication configurations.'
LOG.exception(msg)
res.append(
(
'%(name)s - %(dialect)s (%(type)s)' % interpreter,
_(msg) + (' %s' % trace[:100] + ('...' if len(trace) > 50 else ''))
)
)
return res
def _excute_test_query(client, connector_id, interpreter=None):
'''
Helper utils until the API gets simplified.
'''
notebook_json = """
{
"selectedSnippet": "hive",
"showHistory": false,
"description": "Test Query",
"name": "Test Query",
"sessions": [
{
"type": "hive",
"properties": [],
"id": null
}
],
"type": "hive",
"id": null,
"snippets": [{"id":"2b7d1f46-17a0-30af-efeb-33d4c29b1055","type":"%(connector_id)s","status":"running","statement":"select * from web_logs","properties":{"settings":[],"variables":[],"files":[],"functions":[]},"result":{"id":"b424befa-f4f5-8799-a0b4-79753f2552b1","type":"table","handle":{"log_context":null,"statements_count":1,"end":{"column":21,"row":0},"statement_id":0,"has_more_statements":false,"start":{"column":0,"row":0},"secret":"rVRWw7YPRGqPT7LZ/TeFaA==an","has_result_set":true,"statement":"select * from web_logs","operation_type":0,"modified_row_count":null,"guid":"7xm6+epkRx6dyvYvGNYePA==an"}},"lastExecuted": 1462554843817,"database":"default"}],
"uuid": "d9efdee1-ef25-4d43-b8f9-1a170f69a05a"
}
""" % {
'connector_id': connector_id,
}
snippet = json.loads(notebook_json)['snippets'][0]
snippet['interpreter'] = interpreter
return client.post(
reverse('notebook:api_sample_data', kwargs={'database': 'default', 'table': 'default'}), {
'notebook': notebook_json,
'snippet': json.dumps(snippet),
'is_async': json.dumps(True),
'operation': json.dumps('hello')
})
| apache-2.0 |
nickwallen/metron | metron-deployment/ansible/extra_modules/ambari_service_state.py | 24 | 13329 | #!/usr/bin/python
#
# 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.
#
DOCUMENTATION = '''
---
module: ambari_service_state
version_added: "2.1"
author: Apache Metron (https://metron.apache.org)
short_description: Start/Stop/Change Service or Component State
description:
- Start/Stop/Change Service or Component State
options:
host:
description:
The hostname for the ambari web server
port:
description:
The port for the ambari web server
username:
description:
The username for the ambari web server
password:
description:
The name of the cluster in web server
required: yes
cluster_name:
description:
The name of the cluster in ambari
required: yes
service_name:
description:
The name of the service to alter
required: no
component_name:
description:
The name of the component to alter
required: no
component_host:
description:
The host running the targeted component. Required when component_name is used.
required: no
state:
description:
The desired service/component state.
wait_for_complete:
description:
Whether to wait for the request to complete before returning. Default is False.
required: no
requirements: [ 'requests']
'''
EXAMPLES = '''
# must use full relative path to any files in stored in roles/role_name/files/
- name: Create a new ambari cluster
ambari_cluster_state:
host: localhost
port: 8080
username: admin
password: admin
cluster_name: my_cluster
cluster_state: present
blueprint_var: roles/my_role/files/blueprint.yml
blueprint_name: hadoop
wait_for_complete: True
- name: Start the ambari cluster
ambari_cluster_state:
host: localhost
port: 8080
username: admin
password: admin
cluster_name: my_cluster
cluster_state: started
wait_for_complete: True
- name: Stop the ambari cluster
ambari_cluster_state:
host: localhost
port: 8080
username: admin
password: admin
cluster_name: my_cluster
cluster_state: stopped
wait_for_complete: True
- name: Delete the ambari cluster
ambari_cluster_state:
host: localhost
port: 8080
username: admin
password: admin
cluster_name: my_cluster
cluster_state: absent
'''
RETURN = '''
results:
description: The content of the requests object returned from the RESTful call
returned: success
type: string
'''
__author__ = 'apachemetron'
import json
try:
import requests
except ImportError:
REQUESTS_FOUND = False
else:
REQUESTS_FOUND = True
def main():
argument_spec = dict(
host=dict(type='str', default=None, required=True),
port=dict(type='int', default=None, required=True),
username=dict(type='str', default=None, required=True),
password=dict(type='str', default=None, required=True),
cluster_name=dict(type='str', default=None, required=True),
state=dict(type='str', default=None, required=True,
choices=['started', 'stopped', 'deleted']),
service_name=dict(type='str', required=False),
component_name=dict(type='str', default=None, required=False),
component_host=dict(type='str', default=None, required=False),
wait_for_complete=dict(default=False, required=False, type='bool'),
)
required_together = ['component_name', 'component_host']
module = AnsibleModule(
argument_spec=argument_spec,
required_together=required_together
)
if not REQUESTS_FOUND:
module.fail_json(
msg='requests library is required for this module')
p = module.params
host = p.get('host')
port = p.get('port')
username = p.get('username')
password = p.get('password')
cluster_name = p.get('cluster_name')
state = p.get('state')
service_name = p.get('service_name')
component_name = p.get('component_name')
component_host = p.get('component_host')
wait_for_complete = p.get('wait_for_complete')
component_mode = False
ambari_url = 'http://{0}:{1}'.format(host, port)
if component_name:
component_mode = True
try:
if not cluster_exists(ambari_url, username, password, cluster_name):
module.fail_json(msg="Cluster name {0} does not exist".format(cluster_name))
if state in ['started', 'stopped', 'installed']:
desired_state = ''
if state == 'started':
desired_state = 'STARTED'
elif state in ['stopped','installed']:
desired_state = 'INSTALLED'
if component_mode:
if desired_state == 'INSTALLED':
if(can_add_component(ambari_url, username, password, cluster_name, component_name, component_host)):
add_component_to_host(ambari_url, username, password, cluster_name, component_name, component_host)
request = set_component_state(ambari_url, username, password, cluster_name, component_name, component_host, desired_state)
else:
request = set_service_state(ambari_url,username,password,cluster_name,service_name, desired_state)
if wait_for_complete:
try:
request_id = json.loads(request.content)['Requests']['id']
except ValueError:
module.exit_json(changed=True, results=request.content)
status = wait_for_request_complete(ambari_url, username, password, cluster_name, request_id, 2)
if status != 'COMPLETED':
module.fail_json(msg="Request failed with status {0}".format(status))
module.exit_json(changed=True, results=request.content)
elif state == 'deleted':
if component_mode:
request = delete_component(ambari_url, username, password, cluster_name, component_name, component_host)
else:
request = delete_service(ambari_url,username,password,cluster_name,service_name)
module.exit_json(changed=True, results=request.content)
except requests.ConnectionError, e:
module.fail_json(msg="Could not connect to Ambari client: " + str(e.message))
except Exception, e:
module.fail_json(msg="Ambari client exception occurred: " + str(e.message))
def get_clusters(ambari_url, user, password):
r = get(ambari_url, user, password, '/api/v1/clusters')
if r.status_code != 200:
msg = 'Could not get cluster list: request code {0}, \
request message {1}'.format(r.status_code, r.content)
raise Exception(msg)
clusters = json.loads(r.content)
return clusters['items']
def cluster_exists(ambari_url, user, password, cluster_name):
clusters = get_clusters(ambari_url, user, password)
return cluster_name in [item['Clusters']['cluster_name'] for item in clusters]
def get_request_status(ambari_url, user, password, cluster_name, request_id):
path = '/api/v1/clusters/{0}/requests/{1}'.format(cluster_name, request_id)
r = get(ambari_url, user, password, path)
if r.status_code != 200:
msg = 'Could not get cluster request status: request code {0}, \
request message {1}'.format(r.status_code, r.content)
raise Exception(msg)
service = json.loads(r.content)
return service['Requests']['request_status']
def wait_for_request_complete(ambari_url, user, password, cluster_name, request_id, sleep_time):
while True:
status = get_request_status(ambari_url, user, password, cluster_name, request_id)
if status == 'COMPLETED':
return status
elif status in ['FAILED', 'TIMEDOUT', 'ABORTED', 'SKIPPED_FAILED']:
return status
else:
time.sleep(sleep_time)
def set_service_state(ambari_url, user, password, cluster_name, service_name, desired_state):
path = '/api/v1/clusters/{0}/services/{1}'.format(cluster_name,service_name)
request = {"RequestInfo": {"context": "Setting {0} to {1} via REST".format(service_name,desired_state)},
"Body": {"ServiceInfo": {"state": "{0}".format(desired_state)}}}
payload = json.dumps(request)
r = put(ambari_url, user, password, path, payload)
if r.status_code not in [202, 200]:
msg = 'Could not set service state: request code {0}, \
request message {1}'.format(r.status_code, r.content)
raise Exception(msg)
return r
def set_component_state(ambari_url, user, password, cluster_name, component_name, component_host, desired_state):
path = '/api/v1/clusters/{0}/hosts/{1}/host_components/{2}'.format(cluster_name,component_host,component_name)
request = {"RequestInfo": {"context": "Setting {0} to {1} via REST".format(component_name,desired_state)},
"Body": {"HostRoles": {"state": "{0}".format(desired_state)}}}
payload = json.dumps(request)
r = put(ambari_url, user, password, path, payload)
if r.status_code not in [202, 200]:
msg = 'Could not set component state: request code {0}, \
request message {1}'.format(r.status_code, r.content)
raise Exception(msg)
return r
def delete_component(ambari_url, user, password, cluster_name, component_name, component_host):
enable_maint_mode(ambari_url, user, password, cluster_name, component_name, component_host)
path = '/api/v1/clusters/{0}/hosts/{1}/host_components/{2}'.format(cluster_name,component_host,component_name)
r = delete(ambari_url,user,password,path)
if r.status_code not in [202, 200]:
msg = 'Could not set service state: request code {0}, \
request message {1}'.format(r.status_code, r.content)
raise Exception(msg)
return r
def enable_maint_mode(ambari_url, user, password, cluster_name, component_name, component_host):
path = '/api/v1/clusters/{0}/hosts/{1}/host_components/{2}'.format(cluster_name,component_host,component_name)
request = {"RequestInfo":{"context":"Turn On Maintenance Mode for {0}".format(component_name)},
"Body":{"HostRoles":{"maintenance_state":"ON"}}}
payload = json.dumps(request)
r = put(ambari_url, user, password, path, payload)
if r.status_code not in [202, 200]:
msg = 'Could not set maintenance mode: request code {0}, \
request message {1}'.format(r.status_code, r.content)
raise Exception(msg)
return r
def delete_service(ambari_url, user, password, cluster_name, service_name):
path = '/api/v1/clusters/{0}/services/{1}'.format(cluster_name,service_name)
r = delete(ambari_url,user,password,path)
if r.status_code not in [202, 200]:
msg = 'Could not delete service: request code {0}, \
request message {1}'.format(r.status_code, r.content)
raise Exception(msg)
return r
def add_component_to_host(ambari_url, user, password, cluster_name, component_name, component_host):
path = '/api/v1/clusters/{0}/hosts/{1}/host_components/{2}'.format(cluster_name,component_host,component_name)
r = post(ambari_url, user, password, path,'')
if r.status_code not in [202,201,200]:
msg = 'Could not add {0} to host {1}: request code {2}, \
request message {3}'.format(component_name,component_host,r.status_code, r.content)
raise Exception(msg)
return r
def can_add_component(ambari_url, user, password, cluster_name, component_name, component_host):
path = '/api/v1/clusters/{0}/hosts/{1}/host_components/{2}'.format(cluster_name,component_host,component_name)
r = get(ambari_url, user, password, path)
return r.status_code == 404
def get(ambari_url, user, password, path):
r = requests.get(ambari_url + path, auth=(user, password))
return r
def put(ambari_url, user, password, path, data):
headers = {'X-Requested-By': 'ambari'}
r = requests.put(ambari_url + path, data=data, auth=(user, password), headers=headers)
return r
def post(ambari_url, user, password, path, data):
headers = {'X-Requested-By': 'ambari'}
r = requests.post(ambari_url + path, data=data, auth=(user, password), headers=headers)
return r
def delete(ambari_url, user, password, path):
headers = {'X-Requested-By': 'ambari'}
r = requests.delete(ambari_url + path, auth=(user, password), headers=headers)
return r
from ansible.module_utils.basic import *
if __name__ == '__main__':
main()
| apache-2.0 |
kennethgillen/ansible | lib/ansible/modules/web_infrastructure/jenkins_script.py | 13 | 6308 | #!/usr/bin/python
# encoding: utf-8
# (c) 2016, James Hogarth <james.hogarth@gmail.com>
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
ANSIBLE_METADATA = {'metadata_version': '1.0',
'status': ['preview'],
'supported_by': 'community'}
DOCUMENTATION = '''
---
author: James Hogarth
module: jenkins_script
short_description: Executes a groovy script in the jenkins instance
version_added: '2.3'
description:
- The C(jenkins_script) module takes a script plus a dict of values
to use within the script and returns the result of the script being run.
options:
script:
description:
- The groovy script to be executed.
This gets passed as a string Template if args is defined.
required: true
default: null
url:
description:
- The jenkins server to execute the script against. The default is a local
jenkins instance that is not being proxied through a webserver.
required: false
default: http://localhost:8080
validate_certs:
description:
- If set to C(no), the SSL certificates will not be validated.
This should only set to C(no) used on personally controlled sites
using self-signed certificates as it avoids verifying the source site.
required: false
default: True
user:
description:
- The username to connect to the jenkins server with.
required: false
default: null
password:
description:
- The password to connect to the jenkins server with.
required: false
default: null
args:
description:
- A dict of key-value pairs used in formatting the script.
required: false
default: null
notes:
- Since the script can do anything this does not report on changes.
Knowing the script is being run it's important to set changed_when
for the ansible output to be clear on any alterations made.
'''
EXAMPLES = '''
- name: Obtaining a list of plugins
jenkins_script:
script: 'println(Jenkins.instance.pluginManager.plugins)'
user: admin
password: admin
- name: Setting master using a variable to hold a more complicate script
vars:
setmaster_mode: |
import jenkins.model.*
instance = Jenkins.getInstance()
instance.setMode(${jenkins_mode})
instance.save()
- name: use the variable as the script
jenkins_script:
script: "{{ setmaster_mode }}"
args:
jenkins_mode: Node.Mode.EXCLUSIVE
- name: interacting with an untrusted HTTPS connection
jenkins_script:
script: "println(Jenkins.instance.pluginManager.plugins)"
user: admin
password: admin
url: https://localhost
validate_certs: no
'''
RETURN = '''
output:
description: Result of script
returned: success
type: string
sample: 'Result: true'
'''
import json
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.urls import fetch_url
try:
# python2
from urllib import urlencode
except ImportError:
# python3
from urllib.parse import urlencode
def is_csrf_protection_enabled(module):
resp, info = fetch_url(module,
module.params['url'] + '/api/json',
method='GET')
if info["status"] != 200:
module.fail_json(msg="HTTP error " + str(info["status"]) + " " + info["msg"])
content = resp.read()
return json.loads(content).get('useCrumbs', False)
def get_crumb(module):
resp, info = fetch_url(module,
module.params['url'] + '/crumbIssuer/api/json',
method='GET')
if info["status"] != 200:
module.fail_json(msg="HTTP error " + str(info["status"]) + " " + info["msg"])
content = resp.read()
return json.loads(content)
def main():
module = AnsibleModule(
argument_spec = dict(
script = dict(required=True, type="str"),
url = dict(required=False, type="str", default="http://localhost:8080"),
validate_certs = dict(required=False, type="bool", default=True),
user = dict(required=False, no_log=True, type="str",default=None),
password = dict(required=False, no_log=True, type="str",default=None),
args = dict(required=False, type="dict", default=None)
)
)
if module.params['user'] is not None:
if module.params['password'] is None:
module.fail_json(msg="password required when user provided")
module.params['url_username'] = module.params['user']
module.params['url_password'] = module.params['password']
module.params['force_basic_auth'] = True
if module.params['args'] is not None:
from string import Template
script_contents = Template(module.params['script']).substitute(module.params['args'])
else:
script_contents = module.params['script']
headers = {}
if is_csrf_protection_enabled(module):
crumb = get_crumb(module)
headers = {crumb['crumbRequestField']: crumb['crumb']}
resp, info = fetch_url(module,
module.params['url'] + "/scriptText",
data=urlencode({'script': script_contents}),
headers = headers,
method="POST")
if info["status"] != 200:
module.fail_json(msg="HTTP error " + str(info["status"]) + " " + info["msg"])
result = resp.read()
if 'Exception:' in result and 'at java.lang.Thread' in result:
module.fail_json(msg="script failed with stacktrace:\n " + result)
module.exit_json(
output = result,
)
if __name__ == '__main__':
main()
| gpl-3.0 |
buqing2009/MissionPlanner | Lib/code.py | 62 | 10499 | """Utilities needed to emulate Python's interactive interpreter.
"""
# Inspired by similar code by Jeff Epler and Fredrik Lundh.
import sys
import traceback
from codeop import CommandCompiler, compile_command
__all__ = ["InteractiveInterpreter", "InteractiveConsole", "interact",
"compile_command"]
def softspace(file, newvalue):
oldvalue = 0
try:
oldvalue = file.softspace
except AttributeError:
pass
try:
file.softspace = newvalue
except (AttributeError, TypeError):
# "attribute-less object" or "read-only attributes"
pass
return oldvalue
class InteractiveInterpreter:
"""Base class for InteractiveConsole.
This class deals with parsing and interpreter state (the user's
namespace); it doesn't deal with input buffering or prompting or
input file naming (the filename is always passed in explicitly).
"""
def __init__(self, locals=None):
"""Constructor.
The optional 'locals' argument specifies the dictionary in
which code will be executed; it defaults to a newly created
dictionary with key "__name__" set to "__console__" and key
"__doc__" set to None.
"""
if locals is None:
locals = {"__name__": "__console__", "__doc__": None}
self.locals = locals
self.compile = CommandCompiler()
def runsource(self, source, filename="<input>", symbol="single"):
"""Compile and run some source in the interpreter.
Arguments are as for compile_command().
One several things can happen:
1) The input is incorrect; compile_command() raised an
exception (SyntaxError or OverflowError). A syntax traceback
will be printed by calling the showsyntaxerror() method.
2) The input is incomplete, and more input is required;
compile_command() returned None. Nothing happens.
3) The input is complete; compile_command() returned a code
object. The code is executed by calling self.runcode() (which
also handles run-time exceptions, except for SystemExit).
The return value is True in case 2, False in the other cases (unless
an exception is raised). The return value can be used to
decide whether to use sys.ps1 or sys.ps2 to prompt the next
line.
"""
try:
code = self.compile(source, filename, symbol)
except (OverflowError, SyntaxError, ValueError):
# Case 1
self.showsyntaxerror(filename)
return False
if code is None:
# Case 2
return True
# Case 3
self.runcode(code)
return False
def runcode(self, code):
"""Execute a code object.
When an exception occurs, self.showtraceback() is called to
display a traceback. All exceptions are caught except
SystemExit, which is reraised.
A note about KeyboardInterrupt: this exception may occur
elsewhere in this code, and may not always be caught. The
caller should be prepared to deal with it.
"""
try:
exec code in self.locals
except SystemExit:
raise
except:
self.showtraceback()
else:
if softspace(sys.stdout, 0):
print
def showsyntaxerror(self, filename=None):
"""Display the syntax error that just occurred.
This doesn't display a stack trace because there isn't one.
If a filename is given, it is stuffed in the exception instead
of what was there before (because Python's parser always uses
"<string>" when reading from a string).
The output is written by self.write(), below.
"""
type, value, sys.last_traceback = sys.exc_info()
sys.last_type = type
sys.last_value = value
if filename and type is SyntaxError:
# Work hard to stuff the correct filename in the exception
try:
msg, (dummy_filename, lineno, offset, line) = value
except:
# Not the format we expect; leave it alone
pass
else:
# Stuff in the right filename
value = SyntaxError(msg, (filename, lineno, offset, line))
sys.last_value = value
list = traceback.format_exception_only(type, value)
map(self.write, list)
def showtraceback(self):
"""Display the exception that just occurred.
We remove the first stack item because it is our own code.
The output is written by self.write(), below.
"""
try:
type, value, tb = sys.exc_info()
sys.last_type = type
sys.last_value = value
sys.last_traceback = tb
tblist = traceback.extract_tb(tb)
del tblist[:1]
list = traceback.format_list(tblist)
if list:
list.insert(0, "Traceback (most recent call last):\n")
list[len(list):] = traceback.format_exception_only(type, value)
finally:
tblist = tb = None
map(self.write, list)
def write(self, data):
"""Write a string.
The base implementation writes to sys.stderr; a subclass may
replace this with a different implementation.
"""
sys.stderr.write(data)
class InteractiveConsole(InteractiveInterpreter):
"""Closely emulate the behavior of the interactive Python interpreter.
This class builds on InteractiveInterpreter and adds prompting
using the familiar sys.ps1 and sys.ps2, and input buffering.
"""
def __init__(self, locals=None, filename="<console>"):
"""Constructor.
The optional locals argument will be passed to the
InteractiveInterpreter base class.
The optional filename argument should specify the (file)name
of the input stream; it will show up in tracebacks.
"""
InteractiveInterpreter.__init__(self, locals)
self.filename = filename
self.resetbuffer()
def resetbuffer(self):
"""Reset the input buffer."""
self.buffer = []
def interact(self, banner=None):
"""Closely emulate the interactive Python console.
The optional banner argument specify the banner to print
before the first interaction; by default it prints a banner
similar to the one printed by the real Python interpreter,
followed by the current class name in parentheses (so as not
to confuse this with the real interpreter -- since it's so
close!).
"""
try:
sys.ps1
except AttributeError:
sys.ps1 = ">>> "
try:
sys.ps2
except AttributeError:
sys.ps2 = "... "
cprt = 'Type "help", "copyright", "credits" or "license" for more information.'
if banner is None:
self.write("Python %s on %s\n%s\n(%s)\n" %
(sys.version, sys.platform, cprt,
self.__class__.__name__))
else:
self.write("%s\n" % str(banner))
more = 0
while 1:
try:
if more:
prompt = sys.ps2
else:
prompt = sys.ps1
try:
line = self.raw_input(prompt)
# Can be None if sys.stdin was redefined
encoding = getattr(sys.stdin, "encoding", None)
if encoding and not isinstance(line, unicode):
line = line.decode(encoding)
except EOFError:
self.write("\n")
break
else:
more = self.push(line)
except KeyboardInterrupt:
self.write("\nKeyboardInterrupt\n")
self.resetbuffer()
more = 0
def push(self, line):
"""Push a line to the interpreter.
The line should not have a trailing newline; it may have
internal newlines. The line is appended to a buffer and the
interpreter's runsource() method is called with the
concatenated contents of the buffer as source. If this
indicates that the command was executed or invalid, the buffer
is reset; otherwise, the command is incomplete, and the buffer
is left as it was after the line was appended. The return
value is 1 if more input is required, 0 if the line was dealt
with in some way (this is the same as runsource()).
"""
self.buffer.append(line)
source = "\n".join(self.buffer)
more = self.runsource(source, self.filename)
if not more:
self.resetbuffer()
return more
def raw_input(self, prompt=""):
"""Write a prompt and read a line.
The returned line does not include the trailing newline.
When the user enters the EOF key sequence, EOFError is raised.
The base implementation uses the built-in function
raw_input(); a subclass may replace this with a different
implementation.
"""
return raw_input(prompt)
def interact(banner=None, readfunc=None, local=None):
"""Closely emulate the interactive Python interpreter.
This is a backwards compatible interface to the InteractiveConsole
class. When readfunc is not specified, it attempts to import the
readline module to enable GNU readline if it is available.
Arguments (all optional, all default to None):
banner -- passed to InteractiveConsole.interact()
readfunc -- if not None, replaces InteractiveConsole.raw_input()
local -- passed to InteractiveInterpreter.__init__()
"""
console = InteractiveConsole(local)
if readfunc is not None:
console.raw_input = readfunc
else:
try:
import readline
except ImportError:
pass
console.interact(banner)
if __name__ == "__main__":
interact()
| gpl-3.0 |
jrversteegh/softsailor | deps/numpy-1.6.1/numpy/distutils/command/scons.py | 93 | 24248 | import os
import sys
import os.path
from os.path import join as pjoin, dirname as pdirname
from distutils.errors import DistutilsPlatformError
from distutils.errors import DistutilsExecError, DistutilsSetupError
from numpy.distutils.command.build_ext import build_ext as old_build_ext
from numpy.distutils.ccompiler import CCompiler, new_compiler
from numpy.distutils.fcompiler import FCompiler, new_fcompiler
from numpy.distutils.exec_command import find_executable
from numpy.distutils import log
from numpy.distutils.misc_util import is_bootstrapping, get_cmd
from numpy.distutils.misc_util import get_numpy_include_dirs as _incdir
from numpy.distutils.compat import get_exception
# A few notes:
# - numscons is not mandatory to build numpy, so we cannot import it here.
# Any numscons import has to happen once we check numscons is available and
# is required for the build (call through setupscons.py or native numscons
# build).
def get_scons_build_dir():
"""Return the top path where everything produced by scons will be put.
The path is relative to the top setup.py"""
from numscons import get_scons_build_dir
return get_scons_build_dir()
def get_scons_pkg_build_dir(pkg):
"""Return the build directory for the given package (foo.bar).
The path is relative to the top setup.py"""
from numscons.core.utils import pkg_to_path
return pjoin(get_scons_build_dir(), pkg_to_path(pkg))
def get_scons_configres_dir():
"""Return the top path where everything produced by scons will be put.
The path is relative to the top setup.py"""
from numscons import get_scons_configres_dir
return get_scons_configres_dir()
def get_scons_configres_filename():
"""Return the top path where everything produced by scons will be put.
The path is relative to the top setup.py"""
from numscons import get_scons_configres_filename
return get_scons_configres_filename()
def get_scons_local_path():
"""This returns the full path where scons.py for scons-local is located."""
from numscons import get_scons_path
return get_scons_path()
def _get_top_dir(pkg):
# XXX: this mess is necessary because scons is launched per package, and
# has no knowledge outside its build dir, which is package dependent. If
# one day numscons does not launch one process/package, this will be
# unnecessary.
from numscons import get_scons_build_dir
from numscons.core.utils import pkg_to_path
scdir = pjoin(get_scons_build_dir(), pkg_to_path(pkg))
n = scdir.count(os.sep)
return os.sep.join([os.pardir for i in range(n+1)])
def get_distutils_libdir(cmd, pkg):
"""Returns the path where distutils install libraries, relatively to the
scons build directory."""
return pjoin(_get_top_dir(pkg), cmd.build_lib)
def get_distutils_clibdir(cmd, pkg):
"""Returns the path where distutils put pure C libraries."""
return pjoin(_get_top_dir(pkg), cmd.build_clib)
def get_distutils_install_prefix(pkg, inplace):
"""Returns the installation path for the current package."""
from numscons.core.utils import pkg_to_path
if inplace == 1:
return pkg_to_path(pkg)
else:
install_cmd = get_cmd('install').get_finalized_command('install')
return pjoin(install_cmd.install_libbase, pkg_to_path(pkg))
def get_python_exec_invoc():
"""This returns the python executable from which this file is invocated."""
# Do we need to take into account the PYTHONPATH, in a cross platform way,
# that is the string returned can be executed directly on supported
# platforms, and the sys.path of the executed python should be the same
# than the caller ? This may not be necessary, since os.system is said to
# take into accound os.environ. This actually also works for my way of
# using "local python", using the alias facility of bash.
return sys.executable
def get_numpy_include_dirs(sconscript_path):
"""Return include dirs for numpy.
The paths are relatively to the setup.py script path."""
from numscons import get_scons_build_dir
scdir = pjoin(get_scons_build_dir(), pdirname(sconscript_path))
n = scdir.count(os.sep)
dirs = _incdir()
rdirs = []
for d in dirs:
rdirs.append(pjoin(os.sep.join([os.pardir for i in range(n+1)]), d))
return rdirs
def dirl_to_str(dirlist):
"""Given a list of directories, returns a string where the paths are
concatenated by the path separator.
example: ['foo/bar', 'bar/foo'] will return 'foo/bar:bar/foo'."""
return os.pathsep.join(dirlist)
def dist2sconscc(compiler):
"""This converts the name passed to distutils to scons name convention (C
compiler). compiler should be a CCompiler instance.
Example:
--compiler=intel -> intelc"""
compiler_type = compiler.compiler_type
if compiler_type == 'msvc':
return 'msvc'
elif compiler_type == 'intel':
return 'intelc'
else:
return compiler.compiler[0]
def dist2sconsfc(compiler):
"""This converts the name passed to distutils to scons name convention
(Fortran compiler). The argument should be a FCompiler instance.
Example:
--fcompiler=intel -> ifort on linux, ifl on windows"""
if compiler.compiler_type == 'intel':
#raise NotImplementedError('FIXME: intel fortran compiler name ?')
return 'ifort'
elif compiler.compiler_type == 'gnu':
return 'g77'
elif compiler.compiler_type == 'gnu95':
return 'gfortran'
elif compiler.compiler_type == 'sun':
return 'sunf77'
else:
# XXX: Just give up for now, and use generic fortran compiler
return 'fortran'
def dist2sconscxx(compiler):
"""This converts the name passed to distutils to scons name convention
(C++ compiler). The argument should be a Compiler instance."""
if compiler.compiler_type == 'msvc':
return compiler.compiler_type
return compiler.compiler_cxx[0]
def get_compiler_executable(compiler):
"""For any give CCompiler instance, this gives us the name of C compiler
(the actual executable).
NOTE: does NOT work with FCompiler instances."""
# Geez, why does distutils has no common way to get the compiler name...
if compiler.compiler_type == 'msvc':
# this is harcoded in distutils... A bit cleaner way would be to
# initialize the compiler instance and then get compiler.cc, but this
# may be costly: we really just want a string.
# XXX: we need to initialize the compiler anyway, so do not use
# hardcoded string
#compiler.initialize()
#print compiler.cc
return 'cl.exe'
else:
return compiler.compiler[0]
def get_f77_compiler_executable(compiler):
"""For any give FCompiler instance, this gives us the name of F77 compiler
(the actual executable)."""
return compiler.compiler_f77[0]
def get_cxxcompiler_executable(compiler):
"""For any give CCompiler instance, this gives us the name of CXX compiler
(the actual executable).
NOTE: does NOT work with FCompiler instances."""
# Geez, why does distutils has no common way to get the compiler name...
if compiler.compiler_type == 'msvc':
# this is harcoded in distutils... A bit cleaner way would be to
# initialize the compiler instance and then get compiler.cc, but this
# may be costly: we really just want a string.
# XXX: we need to initialize the compiler anyway, so do not use
# hardcoded string
#compiler.initialize()
#print compiler.cc
return 'cl.exe'
else:
return compiler.compiler_cxx[0]
def get_tool_path(compiler):
"""Given a distutils.ccompiler.CCompiler class, returns the path of the
toolset related to C compilation."""
fullpath_exec = find_executable(get_compiler_executable(compiler))
if fullpath_exec:
fullpath = pdirname(fullpath_exec)
else:
raise DistutilsSetupError("Could not find compiler executable info for scons")
return fullpath
def get_f77_tool_path(compiler):
"""Given a distutils.ccompiler.FCompiler class, returns the path of the
toolset related to F77 compilation."""
fullpath_exec = find_executable(get_f77_compiler_executable(compiler))
if fullpath_exec:
fullpath = pdirname(fullpath_exec)
else:
raise DistutilsSetupError("Could not find F77 compiler executable "\
"info for scons")
return fullpath
def get_cxx_tool_path(compiler):
"""Given a distutils.ccompiler.CCompiler class, returns the path of the
toolset related to C compilation."""
fullpath_exec = find_executable(get_cxxcompiler_executable(compiler))
if fullpath_exec:
fullpath = pdirname(fullpath_exec)
else:
raise DistutilsSetupError("Could not find compiler executable info for scons")
return fullpath
def protect_path(path):
"""Convert path (given as a string) to something the shell will have no
problem to understand (space, etc... problems)."""
if path:
# XXX: to this correctly, this is totally bogus for now (does not check for
# already quoted path, for example).
return '"' + path + '"'
else:
return '""'
def parse_package_list(pkglist):
return pkglist.split(",")
def find_common(seq1, seq2):
"""Given two list, return the index of the common items.
The index are relative to seq1.
Note: do not handle duplicate items."""
dict2 = dict([(i, None) for i in seq2])
return [i for i in range(len(seq1)) if dict2.has_key(seq1[i])]
def select_packages(sconspkg, pkglist):
"""Given a list of packages in pkglist, return the list of packages which
match this list."""
common = find_common(sconspkg, pkglist)
if not len(common) == len(pkglist):
msg = "the package list contains a package not found in "\
"the current list. The current list is %s" % sconspkg
raise ValueError(msg)
return common
def check_numscons(minver):
"""Check that we can use numscons.
minver is a 3 integers tuple which defines the min version."""
try:
import numscons
except ImportError:
e = get_exception()
raise RuntimeError("importing numscons failed (error was %s), using " \
"scons within distutils is not possible without "
"this package " % str(e))
try:
# version_info was added in 0.10.0
from numscons import version_info
# Stupid me used string instead of numbers in version_info in
# dev versions of 0.10.0
if isinstance(version_info[0], str):
raise ValueError("Numscons %s or above expected " \
"(detected 0.10.0)" % str(minver))
# Stupid me used list instead of tuple in numscons
version_info = tuple(version_info)
if version_info[:3] < minver:
raise ValueError("Numscons %s or above expected (got %s) "
% (str(minver), str(version_info[:3])))
except ImportError:
raise RuntimeError("You need numscons >= %s to build numpy "\
"with numscons (imported numscons path " \
"is %s)." % (minver, numscons.__file__))
# XXX: this is a giantic mess. Refactor this at some point.
class scons(old_build_ext):
# XXX: add an option to the scons command for configuration (auto/force/cache).
description = "Scons builder"
library_options = [
('with-perflib=', None,
'Specify which performance library to use for BLAS/LAPACK/etc...' \
'Examples: mkl/atlas/sunper/accelerate'),
('with-mkl-lib=', None, 'TODO'),
('with-mkl-include=', None, 'TODO'),
('with-mkl-libraries=', None, 'TODO'),
('with-atlas-lib=', None, 'TODO'),
('with-atlas-include=', None, 'TODO'),
('with-atlas-libraries=', None, 'TODO')
]
user_options = [
('jobs=', 'j', "specify number of worker threads when executing" \
"scons"),
('inplace', 'i', 'If specified, build in place.'),
('import-env', 'e', 'If specified, import user environment into scons env["ENV"].'),
('bypass', 'b', 'Bypass distutils compiler detection (experimental).'),
('scons-tool-path=', None, 'specify additional path '\
'(absolute) to look for scons tools'),
('silent=', None, 'specify whether scons output should less verbose'\
'(1), silent (2), super silent (3) or not (0, default)'),
('log-level=', None, 'specify log level for numscons. Any value ' \
'valid for the logging python module is valid'),
('package-list=', None,
'If specified, only run scons on the given '\
'packages (example: --package-list=scipy.cluster). If empty, '\
'no package is built'),
('fcompiler=', None, "specify the Fortran compiler type"),
('compiler=', None, "specify the C compiler type"),
('cxxcompiler=', None,
"specify the C++ compiler type (same as C by default)"),
('debug', 'g',
"compile/link with debugging information"),
] + library_options
def initialize_options(self):
old_build_ext.initialize_options(self)
self.build_clib = None
self.debug = 0
self.compiler = None
self.cxxcompiler = None
self.fcompiler = None
self.jobs = None
self.silent = 0
self.import_env = 0
self.scons_tool_path = ''
# If true, we bypass distutils to find the c compiler altogether. This
# is to be used in desperate cases (like incompatible visual studio
# version).
self._bypass_distutils_cc = False
# scons compilers
self.scons_compiler = None
self.scons_compiler_path = None
self.scons_fcompiler = None
self.scons_fcompiler_path = None
self.scons_cxxcompiler = None
self.scons_cxxcompiler_path = None
self.package_list = None
self.inplace = 0
self.bypass = 0
# Only critical things
self.log_level = 50
# library options
self.with_perflib = []
self.with_mkl_lib = []
self.with_mkl_include = []
self.with_mkl_libraries = []
self.with_atlas_lib = []
self.with_atlas_include = []
self.with_atlas_libraries = []
def _init_ccompiler(self, compiler_type):
# XXX: The logic to bypass distutils is ... not so logic.
if compiler_type == 'msvc':
self._bypass_distutils_cc = True
try:
distutils_compiler = new_compiler(compiler=compiler_type,
verbose=self.verbose,
dry_run=self.dry_run,
force=self.force)
distutils_compiler.customize(self.distribution)
# This initialization seems necessary, sometimes, for find_executable to work...
if hasattr(distutils_compiler, 'initialize'):
distutils_compiler.initialize()
self.scons_compiler = dist2sconscc(distutils_compiler)
self.scons_compiler_path = protect_path(get_tool_path(distutils_compiler))
except DistutilsPlatformError:
e = get_exception()
if not self._bypass_distutils_cc:
raise e
else:
self.scons_compiler = compiler_type
def _init_fcompiler(self, compiler_type):
self.fcompiler = new_fcompiler(compiler = compiler_type,
verbose = self.verbose,
dry_run = self.dry_run,
force = self.force)
if self.fcompiler is not None:
self.fcompiler.customize(self.distribution)
self.scons_fcompiler = dist2sconsfc(self.fcompiler)
self.scons_fcompiler_path = protect_path(get_f77_tool_path(self.fcompiler))
def _init_cxxcompiler(self, compiler_type):
cxxcompiler = new_compiler(compiler = compiler_type,
verbose = self.verbose,
dry_run = self.dry_run,
force = self.force)
if cxxcompiler is not None:
cxxcompiler.customize(self.distribution, need_cxx = 1)
cxxcompiler.customize_cmd(self)
self.cxxcompiler = cxxcompiler.cxx_compiler()
try:
get_cxx_tool_path(self.cxxcompiler)
except DistutilsSetupError:
self.cxxcompiler = None
if self.cxxcompiler:
self.scons_cxxcompiler = dist2sconscxx(self.cxxcompiler)
self.scons_cxxcompiler_path = protect_path(get_cxx_tool_path(self.cxxcompiler))
def finalize_options(self):
old_build_ext.finalize_options(self)
self.sconscripts = []
self.pre_hooks = []
self.post_hooks = []
self.pkg_names = []
self.pkg_paths = []
if self.distribution.has_scons_scripts():
for i in self.distribution.scons_data:
self.sconscripts.append(i.scons_path)
self.pre_hooks.append(i.pre_hook)
self.post_hooks.append(i.post_hook)
self.pkg_names.append(i.parent_name)
self.pkg_paths.append(i.pkg_path)
# This crap is needed to get the build_clib
# directory
build_clib_cmd = get_cmd("build_clib").get_finalized_command("build_clib")
self.build_clib = build_clib_cmd.build_clib
if not self.cxxcompiler:
self.cxxcompiler = self.compiler
# To avoid trouble, just don't do anything if no sconscripts are used.
# This is useful when for example f2py uses numpy.distutils, because
# f2py does not pass compiler information to scons command, and the
# compilation setup below can crash in some situation.
if len(self.sconscripts) > 0:
if self.bypass:
self.scons_compiler = self.compiler
self.scons_fcompiler = self.fcompiler
self.scons_cxxcompiler = self.cxxcompiler
else:
# Try to get the same compiler than the ones used by distutils: this is
# non trivial because distutils and scons have totally different
# conventions on this one (distutils uses PATH from user's environment,
# whereas scons uses standard locations). The way we do it is once we
# got the c compiler used, we use numpy.distutils function to get the
# full path, and add the path to the env['PATH'] variable in env
# instance (this is done in numpy.distutils.scons module).
self._init_ccompiler(self.compiler)
self._init_fcompiler(self.fcompiler)
self._init_cxxcompiler(self.cxxcompiler)
if self.package_list:
self.package_list = parse_package_list(self.package_list)
def _call_scons(self, scons_exec, sconscript, pkg_name, pkg_path, bootstrapping):
# XXX: when a scons script is missing, scons only prints warnings, and
# does not return a failure (status is 0). We have to detect this from
# distutils (this cannot work for recursive scons builds...)
# XXX: passing everything at command line may cause some trouble where
# there is a size limitation ? What is the standard solution in thise
# case ?
cmd = [scons_exec, "-f", sconscript, '-I.']
if self.jobs:
cmd.append(" --jobs=%d" % int(self.jobs))
if self.inplace:
cmd.append("inplace=1")
cmd.append('scons_tool_path="%s"' % self.scons_tool_path)
cmd.append('src_dir="%s"' % pdirname(sconscript))
cmd.append('pkg_path="%s"' % pkg_path)
cmd.append('pkg_name="%s"' % pkg_name)
cmd.append('log_level=%s' % self.log_level)
#cmd.append('distutils_libdir=%s' % protect_path(pjoin(self.build_lib,
# pdirname(sconscript))))
cmd.append('distutils_libdir=%s' %
protect_path(get_distutils_libdir(self, pkg_name)))
cmd.append('distutils_clibdir=%s' %
protect_path(get_distutils_clibdir(self, pkg_name)))
prefix = get_distutils_install_prefix(pkg_name, self.inplace)
cmd.append('distutils_install_prefix=%s' % protect_path(prefix))
if not self._bypass_distutils_cc:
cmd.append('cc_opt=%s' % self.scons_compiler)
if self.scons_compiler_path:
cmd.append('cc_opt_path=%s' % self.scons_compiler_path)
else:
cmd.append('cc_opt=%s' % self.scons_compiler)
cmd.append('debug=%s' % self.debug)
if self.scons_fcompiler:
cmd.append('f77_opt=%s' % self.scons_fcompiler)
if self.scons_fcompiler_path:
cmd.append('f77_opt_path=%s' % self.scons_fcompiler_path)
if self.scons_cxxcompiler:
cmd.append('cxx_opt=%s' % self.scons_cxxcompiler)
if self.scons_cxxcompiler_path:
cmd.append('cxx_opt_path=%s' % self.scons_cxxcompiler_path)
cmd.append('include_bootstrap=%s' % dirl_to_str(get_numpy_include_dirs(sconscript)))
cmd.append('bypass=%s' % self.bypass)
cmd.append('import_env=%s' % self.import_env)
if self.silent:
if int(self.silent) == 2:
cmd.append('-Q')
elif int(self.silent) == 3:
cmd.append('-s')
cmd.append('silent=%d' % int(self.silent))
cmd.append('bootstrapping=%d' % bootstrapping)
cmdstr = ' '.join(cmd)
if int(self.silent) < 1:
log.info("Executing scons command (pkg is %s): %s ", pkg_name, cmdstr)
else:
log.info("======== Executing scons command for pkg %s =========", pkg_name)
st = os.system(cmdstr)
if st:
#print "status is %d" % st
msg = "Error while executing scons command."
msg += " See above for more information.\n"
msg += """\
If you think it is a problem in numscons, you can also try executing the scons
command with --log-level option for more detailed output of what numscons is
doing, for example --log-level=0; the lowest the level is, the more detailed
the output it."""
raise DistutilsExecError(msg)
def run(self):
if len(self.sconscripts) < 1:
# nothing to do, just leave it here.
return
check_numscons(minver=(0, 11, 0))
if self.package_list is not None:
id = select_packages(self.pkg_names, self.package_list)
sconscripts = [self.sconscripts[i] for i in id]
pre_hooks = [self.pre_hooks[i] for i in id]
post_hooks = [self.post_hooks[i] for i in id]
pkg_names = [self.pkg_names[i] for i in id]
pkg_paths = [self.pkg_paths[i] for i in id]
else:
sconscripts = self.sconscripts
pre_hooks = self.pre_hooks
post_hooks = self.post_hooks
pkg_names = self.pkg_names
pkg_paths = self.pkg_paths
if is_bootstrapping():
bootstrapping = 1
else:
bootstrapping = 0
scons_exec = get_python_exec_invoc()
scons_exec += ' ' + protect_path(pjoin(get_scons_local_path(), 'scons.py'))
for sconscript, pre_hook, post_hook, pkg_name, pkg_path in zip(sconscripts,
pre_hooks, post_hooks,
pkg_names, pkg_paths):
if pre_hook:
pre_hook()
if sconscript:
self._call_scons(scons_exec, sconscript, pkg_name, pkg_path, bootstrapping)
if post_hook:
post_hook(**{'pkg_name': pkg_name, 'scons_cmd' : self})
| gpl-3.0 |
ywcui1990/htmresearch | projects/sequence_prediction/mackey_glass/generate_line.py | 13 | 2270 | #!/usr/bin/env python
# ----------------------------------------------------------------------
# Numenta Platform for Intelligent Computing (NuPIC)
# Copyright (C) 2015, Numenta, Inc. Unless you have an agreement
# with Numenta, Inc., for a separate license for this software code, the
# following terms and conditions apply:
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero Public License version 3 as
# published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
# See the GNU Affero Public License for more details.
#
# You should have received a copy of the GNU Affero Public License
# along with this program. If not, see http://www.gnu.org/licenses.
#
# http://numenta.org/licenses/
# ----------------------------------------------------------------------
import csv
import math
from matplotlib import pyplot
FILE_PREFIX = "data"
m = 1
def run():
T = []
Y = []
a = 0.05
b = 2.0
def fn(t):
global m
v = ((a * t) % b) - 1
if abs(v) < 1e-5:
m *= -1
return m * v
t = 0.
y = fn(t)
dt = .1
with open(FILE_PREFIX + "_all.csv", 'wb') as allFile:
with open(FILE_PREFIX + "_train.csv", 'wb') as trainFile:
with open(FILE_PREFIX + "_test.csv", 'wb') as testFile:
allWriter = csv.writer(allFile)
trainWriter = csv.writer(trainFile)
testWriter = csv.writer(testFile)
for writer in (allWriter, trainWriter, testWriter):
writer.writerow(["y"])
writer.writerow(["float"])
writer.writerow([])
while True:
T.append(t)
Y.append(y)
if abs(round(t) - t) < 1e-5:
print("y(%2.1f)\t= %4.6f \t" % ( t, y ))
allWriter.writerow([y])
if t >= 200 and t < 3200:
trainWriter.writerow([y])
elif t >= 5000 and t < 5500:
testWriter.writerow([y])
t, y = t + dt, fn(t)
if t > 5500:
break
pyplot.plot(T, Y)
pyplot.xlim(5000, 5250)
pyplot.show()
if __name__ == "__main__":
run()
| agpl-3.0 |
MicroPyramid/Django-CRM | accounts/migrations/0002_auto_20190128_1237.py | 1 | 1873 | # Generated by Django 2.1.2 on 2019-01-28 07:07
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
("accounts", "0001_initial"),
("common", "0001_initial"),
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.AddField(
model_name="account",
name="assigned_to",
field=models.ManyToManyField(
related_name="account_assigned_to", to=settings.AUTH_USER_MODEL
),
),
migrations.AddField(
model_name="account",
name="billing_address",
field=models.ForeignKey(
blank=True,
null=True,
on_delete=django.db.models.deletion.CASCADE,
related_name="account_billing_address",
to="common.Address",
),
),
migrations.AddField(
model_name="account",
name="created_by",
field=models.ForeignKey(
on_delete=django.db.models.deletion.CASCADE,
related_name="account_created_by",
to=settings.AUTH_USER_MODEL,
),
),
migrations.AddField(
model_name="account",
name="shipping_address",
field=models.ForeignKey(
blank=True,
null=True,
on_delete=django.db.models.deletion.CASCADE,
related_name="account_shipping_address",
to="common.Address",
),
),
migrations.AddField(
model_name="account",
name="teams",
field=models.ManyToManyField(to="common.Team"),
),
]
| mit |
frodo4fingers/appfs | josefluispelz/EX2/ex2.py | 3 | 1321 | import sys
try:
import cElementTree as ET
except ImportError:
try: #Python 2.5 need to import a different module
import xml.etree.cElementTree as ET
except ImportError:
sys.stderr = "Failed to import cElementTree from any known place\n)"
print(sys.stderr)
filename = sys.argv[-1]
try:
dom = ET.parse(open(filename, "r"))
root = dom.getroot()
except:
sys.stderr = "Unable to open and parse input definition file: {}".format(filename)
print(sys.stderr)
def find_in_tree(tree, node):
found = tree.find(node)
if found == None:
print("No {} in file".format(node))
found = []
return found
csv = ""
for gasDay in root:
if str(gasDay.tag).split("}")[-1] == "gasDay":
date = gasDay.get("date")
starthour = int(gasDay.get("gasDayStartHourInUTC"))
for boundaryNode in gasDay:
if str(boundaryNode.tag).split("}")[-1] == "boundaryNode":
for time in boundaryNode:
if str(time.tag).split("}")[-1] == "time":
HH = int(time.get("hour"))
value = int(time.find("{http://gaslab.zib.de/kwpt/measured}amountOfPower").get("value"))
csv += "{}; {}; {}\n".format(date,HH+starthour,value)
print(csv[:-1]) | mit |
Pennebaker/wagtail | wagtail/wagtaildocs/models.py | 16 | 2696 | from __future__ import unicode_literals
import os.path
from taggit.managers import TaggableManager
from django.db import models
from django.db.models.signals import pre_delete
from django.dispatch.dispatcher import receiver
from django.dispatch import Signal
from django.core.urlresolvers import reverse
from django.conf import settings
from django.utils.translation import ugettext_lazy as _
from django.utils.encoding import python_2_unicode_compatible
from wagtail.wagtailadmin.taggable import TagSearchable
from wagtail.wagtailadmin.utils import get_object_usage
from wagtail.wagtailsearch import index
@python_2_unicode_compatible
class Document(models.Model, TagSearchable):
title = models.CharField(max_length=255, verbose_name=_('Title'))
file = models.FileField(upload_to='documents', verbose_name=_('File'))
created_at = models.DateTimeField(verbose_name=_('Created at'), auto_now_add=True)
uploaded_by_user = models.ForeignKey(settings.AUTH_USER_MODEL, verbose_name=_('Uploaded by user'), null=True, blank=True, editable=False)
tags = TaggableManager(help_text=None, blank=True, verbose_name=_('Tags'))
search_fields = TagSearchable.search_fields + (
index.FilterField('uploaded_by_user'),
)
def __str__(self):
return self.title
@property
def filename(self):
return os.path.basename(self.file.name)
@property
def file_extension(self):
parts = self.filename.split('.')
if len(parts) > 1:
return parts[-1]
else:
return ''
@property
def url(self):
return reverse('wagtaildocs_serve', args=[self.id, self.filename])
def get_usage(self):
return get_object_usage(self)
@property
def usage_url(self):
return reverse('wagtaildocs:document_usage',
args=(self.id,))
def is_editable_by_user(self, user):
if user.has_perm('wagtaildocs.change_document'):
# user has global permission to change documents
return True
elif user.has_perm('wagtaildocs.add_document') and self.uploaded_by_user == user:
# user has document add permission, which also implicitly provides permission to edit their own documents
return True
else:
return False
class Meta:
verbose_name = _('Document')
# Receive the pre_delete signal and delete the file associated with the model instance.
@receiver(pre_delete, sender=Document)
def document_delete(sender, instance, **kwargs):
# Pass false so FileField doesn't save the model.
instance.file.delete(False)
document_served = Signal(providing_args=['request'])
| bsd-3-clause |
andersroos/rankedftw | main/fetch_new.py | 1 | 4939 | from datetime import timedelta
from logging import getLogger, INFO, WARNING
from django.db import transaction
from common.logging import log_context
from common.utils import utcnow
from main.fetch import fetch_new_in_region
from main.models import Version, Season, Ranking, Cache, Region
logger = getLogger('django')
def create_new_season(current_season, end_date):
# New season.
logger.info("detected season change")
# New season date is not super important, ladders around break will end up in correct season, so
# set it to today + 1 day.
season = current_season
season.end_date = end_date
season.save()
logger.info("set end date %s on season %d" % (season.end_date, season.id))
next_season = season.get_next()
next_season.start_date = end_date + timedelta(days=1)
next_season.year = next_season.start_date.year
next_season.number = 1 if next_season.year != season.year else season.number + 1
next_season.name = "%d Season %d" % (next_season.year, next_season.number)
next_season.save()
logger.info("set start data %s, year, name and number on season %d" %
(next_season.start_date, next_season.id))
next_next_season = Season(id=next_season.id + 1,
start_date=None,
end_date=None,
year=0,
number=0,
name='',
version=Version.LOTV)
next_next_season.save()
logger.info("created empty season %d" % next_next_season.id)
# Fixing rankings if they ended up with data time after season end.
rankings = Ranking.objects.filter(season=season,
status__in=(Ranking.COMPLETE_WITH_DATA, Ranking.COMPLETE_WITOUT_DATA),
data_time__gte=season.end_time()).order_by('-id')
for i, ranking in enumerate(rankings):
ranking.data_time = season.end_time() - timedelta(seconds=i)
ranking.save()
logger.info("changed data_time to %s for ranking %d since it was after season break" %
(ranking.data_time, ranking.id))
# Warn about the event to make monitoring send eamil.
logger.warning("season break detected, current is now season %d, start_date %s" %
(next_season.id, next_season.start_date))
def update_season_cache(api_season, region, api_response):
# Update or create the season cache, just for bookkeeping.
try:
cache = Cache.objects.get(region=region, type=Cache.SEASON, bid=1)
cache.updated = api_response.fetch_time
cache.data = api_season.to_text()
cache.save()
except Cache.DoesNotExist:
Cache.objects.create(url=api_season.url, bid=1, type=Cache.SEASON, region=region,
status=api_response.status, created=api_response.fetch_time,
updated=api_response.fetch_time, data=api_season.to_text())
@log_context(feature='new')
def fetch_new(region=None, check_stop=lambda: None, bnet_client=None):
with transaction.atomic():
current_season = Season.get_current_season()
for count in range(1, 3):
check_stop()
res = bnet_client.fetch_current_season(region)
api_season = res.api_season
if res.status == 200:
update_season_cache(api_season, region, res)
# Check season.
if current_season.id == api_season.season_id():
# We already have latest season, continue with fetch.
break
elif current_season.id + 1 == api_season.season_id():
# New season detected, create new season and wait for next fetch new.
create_new_season(current_season, api_season.start_date())
return
elif current_season.near_start(utcnow(), days=2):
logger.info("current season %d near start, blizzard says %d, probably cached or other region"
", bailing" % (current_season.id, api_season.season_id()))
return
else:
raise Exception("season mismatch blizzard says %d, current in db is %d" %
(api_season.season_id(), current_season.id))
else:
# Is should be safe to continue after this since season id is in call to blizzard api. This is info logging
# because it happens all the time due to some blizzard bug.
logger.log(INFO, "could not get season info from %s after %d tries, status %s, skipping season check" %
(api_season.url, count, res.status))
fetch_new_in_region(check_stop, bnet_client, current_season, region)
| agpl-3.0 |
kchodorow/tensorflow | tensorflow/python/util/future_api_test.py | 173 | 1177 | # 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 future_api."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import tensorflow as tf
# pylint: disable=unused-import
from tensorflow.python.util import future_api
# pylint: enable=unused-import
class ExampleParserConfigurationTest(tf.test.TestCase):
def testBasic(self):
self.assertFalse(hasattr(tf, 'arg_max'))
self.assertTrue(hasattr(tf, 'argmax'))
if __name__ == '__main__':
tf.test.main()
| apache-2.0 |
titom1986/CouchPotatoServer | libs/pyutil/zlibutil.py | 106 | 15919 | # Copyright (c) 2002-2010 Zooko Wilcox-O'Hearn
# This file is part of pyutil; see README.rst for licensing terms.
"""
Making your zlib experience that much nicer!
Most importantly, this offers protection from "zlib bomb" attacks, where the
original data was maximally compressable, and a naive use of zlib would
consume all of your RAM while trying to decompress it.
"""
import exceptions, string, zlib
from humanreadable import hr
from pyutil.assertutil import precondition
class DecompressError(exceptions.StandardError, zlib.error): pass
class UnsafeDecompressError(DecompressError): pass # This means it would take more memory to decompress than we can spare.
class TooBigError(DecompressError): pass # This means the resulting uncompressed text would exceed the maximum allowed length.
class ZlibError(DecompressError): pass # internal error, probably due to the input not being zlib compressed text
# The smallest limit that you can impose on zlib decompression and still have
# a chance of succeeding at decompression.
# constant memory overhead of zlib (76 KB), plus minbite (128 bytes) times
# maxexpansion (1032) times buffer-copying duplication (2), plus 2063 so as
# to reach the ceiling of div (2*1032)
MINMAXMEM=76*2**10 + 128 * 1032 * 2 + 2063 - 1
# You should really specify a maxmem which is much higher than MINMAXMEM. If
# maxmem=MINMAXMEM, we will be reduced to decompressing the input in
# 128-byte bites, and furthermore unless the decompressed text is quite small,
# we will be forced to give up and spuriously raise UnsafeDecompressError!
# You really ought to pass a maxmem argument equal to the maximum possible
# memory that your app should ever allocate (for a short-term use).
# I typically set it to 65 MB.
def decompress(zbuf, maxlen=(65 * (2**20)), maxmem=(65 * (2**20))):
"""
Decompress zbuf so that it decompresses to <= maxlen bytes, while using
<= maxmem memory, or else raise an exception. If zbuf contains
uncompressed data an exception will be raised.
This function guards against memory allocation attacks.
@param maxlen the resulting text must not be greater than this
@param maxmem the execution of this function must not use more than this
amount of memory in bytes; The higher this number is (optimally
1032 * maxlen, or even greater), the faster this function can
complete. (Actually I don't fully understand the workings of zlib, so
this function might use a *little* more than this memory, but not a
lot more.) (Also, this function will raise an exception if the amount
of memory required even *approaches* maxmem. Another reason to make
it large.) (Hence the default value which would seem to be
exceedingly large until you realize that it means you can decompress
64 KB chunks of compressiontext at a bite.)
"""
assert isinstance(maxlen, (int, long,)) and maxlen > 0, "maxlen is required to be a real maxlen, geez!"
assert isinstance(maxmem, (int, long,)) and maxmem > 0, "maxmem is required to be a real maxmem, geez!"
assert maxlen <= maxmem, "maxlen is required to be <= maxmem. All data that is included in the return value is counted against maxmem as well as against maxlen, so it is impossible to return a result bigger than maxmem, even if maxlen is bigger than maxmem. See decompress_to_spool() if you want to spool a large text out while limiting the amount of memory used during the process."
lenzbuf = len(zbuf)
offset = 0
decomplen = 0
availmem = maxmem - (76 * 2**10) # zlib can take around 76 KB RAM to do decompression
availmem = availmem / 2 # generating the result string from the intermediate strings will require using the same amount of memory again, briefly. If you care about this kind of thing, then let's rewrite this module in C.
decompstrlist = []
decomp = zlib.decompressobj()
while offset < lenzbuf:
# How much compressedtext can we safely attempt to decompress now without going over `maxmem'? zlib docs say that theoretical maximum for the zlib format would be 1032:1.
lencompbite = availmem / 1032 # XXX TODO: The biggest compression ratio zlib can have for whole files is 1032:1. Unfortunately I don't know if small chunks of compressiontext *within* a file can expand to more than that. I'll assume not... --Zooko 2001-05-12
if lencompbite < 128:
# If we can't safely attempt even a few bytes of compression text, let us give up. Either `maxmem' was too small or this compressiontext is actually a decompression bomb.
raise UnsafeDecompressError, "used up roughly maxmem memory. maxmem: %s, len(zbuf): %s, offset: %s, decomplen: %s, lencompbite: %s" % tuple(map(hr, [maxmem, len(zbuf), offset, decomplen, lencompbite,]))
# I wish the following were a local function like this:
# def proc_decomp_bite(tmpstr, lencompbite=0, decomplen=decomplen, maxlen=maxlen, availmem=availmem, decompstrlist=decompstrlist, offset=offset, zbuf=zbuf):
# ...but we can't conveniently and efficiently update the integer variables like offset in the outer scope. Oh well. --Zooko 2003-06-26
try:
if (offset == 0) and (lencompbite >= lenzbuf):
tmpstr = decomp.decompress(zbuf)
else:
tmpstr = decomp.decompress(zbuf[offset:offset+lencompbite])
except zlib.error, le:
raise ZlibError, (offset, lencompbite, decomplen, hr(le), )
lentmpstr = len(tmpstr)
decomplen = decomplen + lentmpstr
if decomplen > maxlen:
raise TooBigError, "length of resulting data > maxlen. maxlen: %s, len(zbuf): %s, offset: %s, decomplen: %s" % tuple(map(hr, [maxlen, len(zbuf), offset, decomplen,]))
availmem = availmem - lentmpstr
offset = offset + lencompbite
decompstrlist.append(tmpstr)
tmpstr = ''
try:
tmpstr = decomp.flush()
except zlib.error, le:
raise ZlibError, (offset, lencompbite, decomplen, le, )
lentmpstr = len(tmpstr)
decomplen = decomplen + lentmpstr
if decomplen > maxlen:
raise TooBigError, "length of resulting data > maxlen. maxlen: %s, len(zbuf): %s, offset: %s, decomplen: %s" % tuple(map(hr, [maxlen, len(zbuf), offset, decomplen,]))
availmem = availmem - lentmpstr
offset = offset + lencompbite
if lentmpstr > 0:
decompstrlist.append(tmpstr)
tmpstr = ''
if len(decompstrlist) > 0:
return string.join(decompstrlist, '')
else:
return decompstrlist[0]
def decompress_to_fileobj(zbuf, fileobj, maxlen=(65 * (2**20)), maxmem=(65 * (2**20))):
"""
Decompress zbuf so that it decompresses to <= maxlen bytes, while using
<= maxmem memory, or else raise an exception. If zbuf contains
uncompressed data an exception will be raised.
This function guards against memory allocation attacks.
Note that this assumes that data written to fileobj still occupies memory,
so such data counts against maxmem as well as against maxlen.
@param maxlen the resulting text must not be greater than this
@param maxmem the execution of this function must not use more than this
amount of memory in bytes; The higher this number is (optimally
1032 * maxlen, or even greater), the faster this function can
complete. (Actually I don't fully understand the workings of zlib, so
this function might use a *little* more than this memory, but not a
lot more.) (Also, this function will raise an exception if the amount
of memory required even *approaches* maxmem. Another reason to make
it large.) (Hence the default value which would seem to be
exceedingly large until you realize that it means you can decompress
64 KB chunks of compressiontext at a bite.)
@param fileobj a file object to which the decompressed text will be written
"""
precondition(hasattr(fileobj, 'write') and callable(fileobj.write), "fileobj is required to have a write() method.", fileobj=fileobj)
precondition(isinstance(maxlen, (int, long,)) and maxlen > 0, "maxlen is required to be a real maxlen, geez!", maxlen=maxlen)
precondition(isinstance(maxmem, (int, long,)) and maxmem > 0, "maxmem is required to be a real maxmem, geez!", maxmem=maxmem)
precondition(maxlen <= maxmem, "maxlen is required to be <= maxmem. All data that is written out to fileobj is counted against maxmem as well as against maxlen, so it is impossible to return a result bigger than maxmem, even if maxlen is bigger than maxmem. See decompress_to_spool() if you want to spool a large text out while limiting the amount of memory used during the process.", maxlen=maxlen, maxmem=maxmem)
lenzbuf = len(zbuf)
offset = 0
decomplen = 0
availmem = maxmem - (76 * 2**10) # zlib can take around 76 KB RAM to do decompression
decomp = zlib.decompressobj()
while offset < lenzbuf:
# How much compressedtext can we safely attempt to decompress now without going over maxmem? zlib docs say that theoretical maximum for the zlib format would be 1032:1.
lencompbite = availmem / 1032 # XXX TODO: The biggest compression ratio zlib can have for whole files is 1032:1. Unfortunately I don't know if small chunks of compressiontext *within* a file can expand to more than that. I'll assume not... --Zooko 2001-05-12
if lencompbite < 128:
# If we can't safely attempt even a few bytes of compression text, let us give up. Either maxmem was too small or this compressiontext is actually a decompression bomb.
raise UnsafeDecompressError, "used up roughly maxmem memory. maxmem: %s, len(zbuf): %s, offset: %s, decomplen: %s" % tuple(map(hr, [maxmem, len(zbuf), offset, decomplen,]))
# I wish the following were a local function like this:
# def proc_decomp_bite(tmpstr, lencompbite=0, decomplen=decomplen, maxlen=maxlen, availmem=availmem, decompstrlist=decompstrlist, offset=offset, zbuf=zbuf):
# ...but we can't conveniently and efficiently update the integer variables like offset in the outer scope. Oh well. --Zooko 2003-06-26
try:
if (offset == 0) and (lencompbite >= lenzbuf):
tmpstr = decomp.decompress(zbuf)
else:
tmpstr = decomp.decompress(zbuf[offset:offset+lencompbite])
except zlib.error, le:
raise ZlibError, (offset, lencompbite, decomplen, le, )
lentmpstr = len(tmpstr)
decomplen = decomplen + lentmpstr
if decomplen > maxlen:
raise TooBigError, "length of resulting data > maxlen. maxlen: %s, len(zbuf): %s, offset: %s, decomplen: %s" % tuple(map(hr, [maxlen, len(zbuf), offset, decomplen,]))
availmem = availmem - lentmpstr
offset = offset + lencompbite
fileobj.write(tmpstr)
tmpstr = ''
try:
tmpstr = decomp.flush()
except zlib.error, le:
raise ZlibError, (offset, lencompbite, decomplen, le, )
lentmpstr = len(tmpstr)
decomplen = decomplen + lentmpstr
if decomplen > maxlen:
raise TooBigError, "length of resulting data > maxlen. maxlen: %s, len(zbuf): %s, offset: %s, decomplen: %s" % tuple(map(hr, [maxlen, len(zbuf), offset, decomplen,]))
availmem = availmem - lentmpstr
offset = offset + lencompbite
fileobj.write(tmpstr)
tmpstr = ''
def decompress_to_spool(zbuf, fileobj, maxlen=(65 * (2**20)), maxmem=(65 * (2**20))):
"""
Decompress zbuf so that it decompresses to <= maxlen bytes, while using
<= maxmem memory, or else raise an exception. If zbuf contains
uncompressed data an exception will be raised.
This function guards against memory allocation attacks.
Note that this assumes that data written to fileobj does *not* continue to
occupy memory, so such data doesn't count against maxmem, although of
course it still counts against maxlen.
@param maxlen the resulting text must not be greater than this
@param maxmem the execution of this function must not use more than this
amount of memory in bytes; The higher this number is (optimally
1032 * maxlen, or even greater), the faster this function can
complete. (Actually I don't fully understand the workings of zlib, so
this function might use a *little* more than this memory, but not a
lot more.) (Also, this function will raise an exception if the amount
of memory required even *approaches* maxmem. Another reason to make
it large.) (Hence the default value which would seem to be
exceedingly large until you realize that it means you can decompress
64 KB chunks of compressiontext at a bite.)
@param fileobj the decompressed text will be written to it
"""
precondition(hasattr(fileobj, 'write') and callable(fileobj.write), "fileobj is required to have a write() method.", fileobj=fileobj)
precondition(isinstance(maxlen, (int, long,)) and maxlen > 0, "maxlen is required to be a real maxlen, geez!", maxlen=maxlen)
precondition(isinstance(maxmem, (int, long,)) and maxmem > 0, "maxmem is required to be a real maxmem, geez!", maxmem=maxmem)
tmpstr = ''
lenzbuf = len(zbuf)
offset = 0
decomplen = 0
availmem = maxmem - (76 * 2**10) # zlib can take around 76 KB RAM to do decompression
decomp = zlib.decompressobj()
while offset < lenzbuf:
# How much compressedtext can we safely attempt to decompress now without going over `maxmem'? zlib docs say that theoretical maximum for the zlib format would be 1032:1.
lencompbite = availmem / 1032 # XXX TODO: The biggest compression ratio zlib can have for whole files is 1032:1. Unfortunately I don't know if small chunks of compressiontext *within* a file can expand to more than that. I'll assume not... --Zooko 2001-05-12
if lencompbite < 128:
# If we can't safely attempt even a few bytes of compression text, let us give up. Either `maxmem' was too small or this compressiontext is actually a decompression bomb.
raise UnsafeDecompressError, "used up roughly `maxmem' memory. maxmem: %s, len(zbuf): %s, offset: %s, decomplen: %s" % tuple(map(hr, [maxmem, len(zbuf), offset, decomplen,]))
# I wish the following were a local function like this:
# def proc_decomp_bite(tmpstr, lencompbite=0, decomplen=decomplen, maxlen=maxlen, availmem=availmem, decompstrlist=decompstrlist, offset=offset, zbuf=zbuf):
# ...but we can't conveniently and efficiently update the integer variables like offset in the outer scope. Oh well. --Zooko 2003-06-26
try:
if (offset == 0) and (lencompbite >= lenzbuf):
tmpstr = decomp.decompress(zbuf)
else:
tmpstr = decomp.decompress(zbuf[offset:offset+lencompbite])
except zlib.error, le:
raise ZlibError, (offset, lencompbite, decomplen, le, )
lentmpstr = len(tmpstr)
decomplen = decomplen + lentmpstr
if decomplen > maxlen:
raise TooBigError, "length of resulting data > `maxlen'. maxlen: %s, len(zbuf): %s, offset: %s, decomplen: %s" % tuple(map(hr, [maxlen, len(zbuf), offset, decomplen,]))
offset = offset + lencompbite
fileobj.write(tmpstr)
tmpstr = ''
try:
tmpstr = decomp.flush()
except zlib.error, le:
raise ZlibError, (offset, lencompbite, decomplen, le, )
lentmpstr = len(tmpstr)
decomplen = decomplen + lentmpstr
if decomplen > maxlen:
raise TooBigError, "length of resulting data > `maxlen'. maxlen: %s, len(zbuf): %s, offset: %s, decomplen: %s" % tuple(map(hr, [maxlen, len(zbuf), offset, decomplen,]))
offset = offset + lencompbite
fileobj.write(tmpstr)
tmpstr = ''
| gpl-3.0 |
caasiu/xbmc-addons-chinese | plugin.video.dnvodPlayer/js2py/translators/friendly_nodes.py | 20 | 8484 | import binascii
from pyjsparser import PyJsParser
import six
if six.PY3:
basestring = str
long = int
xrange = range
unicode = str
REGEXP_CONVERTER = PyJsParser()
def to_hex(s):
return binascii.hexlify(s.encode('utf8')).decode('utf8') # fucking python 3, I hate it so much
# wtf was wrong with s.encode('hex') ???
def indent(lines, ind=4):
return ind*' '+lines.replace('\n', '\n'+ind*' ').rstrip(' ')
def inject_before_lval(source, lval, code):
if source.count(lval)>1:
print()
print(lval)
raise RuntimeError('To many lvals (%s)' % lval)
elif not source.count(lval):
print()
print(lval)
assert lval not in source
raise RuntimeError('No lval found "%s"' % lval)
end = source.index(lval)
inj = source.rfind('\n', 0, end)
ind = inj
while source[ind+1]==' ':
ind+=1
ind -= inj
return source[:inj+1]+ indent(code, ind) + source[inj+1:]
def get_continue_label(label):
return CONTINUE_LABEL%to_hex(label)
def get_break_label(label):
return BREAK_LABEL%to_hex(label)
def is_valid_py_name(name):
try:
compile(name+' = 11', 'a','exec')
except:
return False
return True
def indent(lines, ind=4):
return ind*' '+lines.replace('\n', '\n'+ind*' ').rstrip(' ')
def compose_regex(val):
reg, flags = val
#reg = REGEXP_CONVERTER._unescape_string(reg)
return u'/%s/%s' % (reg, flags)
def float_repr(f):
if int(f)==f:
return repr(int(f))
return repr(f)
def argsplit(args, sep=','):
"""used to split JS args (it is not that simple as it seems because
sep can be inside brackets).
pass args *without* brackets!
Used also to parse array and object elements, and more"""
parsed_len = 0
last = 0
splits = []
for e in bracket_split(args, brackets=['()', '[]', '{}']):
if e[0] not in ('(', '[', '{'):
for i, char in enumerate(e):
if char==sep:
splits.append(args[last:parsed_len+i])
last = parsed_len + i + 1
parsed_len += len(e)
splits.append(args[last:])
return splits
def bracket_split(source, brackets=('()','{}','[]'), strip=False):
"""DOES NOT RETURN EMPTY STRINGS (can only return empty bracket content if strip=True)"""
starts = [e[0] for e in brackets]
in_bracket = 0
n = 0
last = 0
while n<len(source):
e = source[n]
if not in_bracket and e in starts:
in_bracket = 1
start = n
b_start, b_end = brackets[starts.index(e)]
elif in_bracket:
if e==b_start:
in_bracket += 1
elif e==b_end:
in_bracket -= 1
if not in_bracket:
if source[last:start]:
yield source[last:start]
last = n+1
yield source[start+strip:n+1-strip]
n+=1
if source[last:]:
yield source[last:]
def js_comma(a, b):
return 'PyJsComma('+a+','+b+')'
def js_or(a, b):
return '('+a+' or '+b+')'
def js_bor(a, b):
return '('+a+'|'+b+')'
def js_bxor(a, b):
return '('+a+'^'+b+')'
def js_band(a, b):
return '('+a+'&'+b+')'
def js_and(a, b):
return '('+a+' and '+b+')'
def js_strict_eq(a, b):
return 'PyJsStrictEq('+a+','+b+')'
def js_strict_neq(a, b):
return 'PyJsStrictNeq('+a+','+b+')'
#Not handled by python in the same way like JS. For example 2==2==True returns false.
# In JS above would return true so we need brackets.
def js_abstract_eq(a, b):
return '('+a+'=='+b+')'
#just like ==
def js_abstract_neq(a, b):
return '('+a+'!='+b+')'
def js_lt(a, b):
return '('+a+'<'+b+')'
def js_le(a, b):
return '('+a+'<='+b+')'
def js_ge(a, b):
return '('+a+'>='+b+')'
def js_gt(a, b):
return '('+a+'>'+b+')'
def js_in(a, b):
return b+'.contains('+a+')'
def js_instanceof(a, b):
return a+'.instanceof('+b+')'
def js_lshift(a, b):
return '('+a+'<<'+b+')'
def js_rshift(a, b):
return '('+a+'>>'+b+')'
def js_shit(a, b):
return 'PyJsBshift('+a+','+b+')'
def js_add(a, b): # To simplify later process of converting unary operators + and ++
return '(%s+%s)'%(a, b)
def js_sub(a, b): # To simplify
return '(%s-%s)'%(a, b)
def js_mul(a, b):
return '('+a+'*'+b+')'
def js_div(a, b):
return '('+a+'/'+b+')'
def js_mod(a, b):
return '('+a+'%'+b+')'
def js_typeof(a):
cand = list(bracket_split(a, ('()',)))
if len(cand)==2 and cand[0]=='var.get':
return cand[0]+cand[1][:-1]+',throw=False).typeof()'
return a+'.typeof()'
def js_void(a):
# eval and return undefined
return 'PyJsComma(%s, Js(None))' % a
def js_new(a):
cands = list(bracket_split(a, ('()',)))
lim = len(cands)
if lim < 2:
return a + '.create()'
n = 0
while n < lim:
c = cands[n]
if c[0]=='(':
if cands[n-1].endswith('.get') and n+1>=lim: # last get operation.
return a + '.create()'
elif cands[n-1][0]=='(':
return ''.join(cands[:n])+'.create' + c + ''.join(cands[n+1:])
elif cands[n-1]=='.callprop':
beg = ''.join(cands[:n-1])
args = argsplit(c[1:-1],',')
prop = args[0]
new_args = ','.join(args[1:])
create = '.get(%s).create(%s)' % (prop, new_args)
return beg + create + ''.join(cands[n+1:])
n+=1
return a + '.create()'
def js_delete(a):
#replace last get with delete.
c = list(bracket_split(a, ['()']))
beg, arglist = ''.join(c[:-1]).strip(), c[-1].strip() #strips just to make sure... I will remove it later
if beg[-4:]!='.get':
print(a)
raise SyntaxError('Invalid delete operation')
return beg[:-3]+'delete'+arglist
def js_neg(a):
return '(-'+a+')'
def js_pos(a):
return '(+'+a+')'
def js_inv(a):
return '(~'+a+')'
def js_not(a):
return a+'.neg()'
def js_postfix(a, inc, post):
bra = list(bracket_split(a, ('()',)))
meth = bra[-2]
if not meth.endswith('get'):
raise SyntaxError('Invalid ++ or -- operation.')
bra[-2] = bra[-2][:-3] + 'put'
bra[-1] = '(%s,Js(%s.to_number())%sJs(1))' % (bra[-1][1:-1], a, '+' if inc else '-')
res = ''.join(bra)
return res if not post else '(%s%sJs(1))' % (res, '-' if inc else '+')
def js_pre_inc(a):
return js_postfix(a, True, False)
def js_post_inc(a):
return js_postfix(a, True, True)
def js_pre_dec(a):
return js_postfix(a, False, False)
def js_post_dec(a):
return js_postfix(a, False, True)
CONTINUE_LABEL = 'JS_CONTINUE_LABEL_%s'
BREAK_LABEL = 'JS_BREAK_LABEL_%s'
PREPARE = '''HOLDER = var.own.get(NAME)\nvar.force_own_put(NAME, PyExceptionToJs(PyJsTempException))\n'''
RESTORE = '''if HOLDER is not None:\n var.own[NAME] = HOLDER\nelse:\n del var.own[NAME]\ndel HOLDER\n'''
TRY_CATCH = '''%stry:\nBLOCKfinally:\n%s''' % (PREPARE, indent(RESTORE))
OR = {'||': js_or}
AND = {'&&': js_and}
BOR = {'|': js_bor}
BXOR = {'^': js_bxor}
BAND = {'&': js_band}
EQS = {'===': js_strict_eq,
'!==': js_strict_neq,
'==': js_abstract_eq, # we need == and != too. Read a note above method
'!=': js_abstract_neq}
#Since JS does not have chained comparisons we need to implement all cmp methods.
COMPS = {'<': js_lt,
'<=': js_le,
'>=': js_ge,
'>': js_gt,
'instanceof': js_instanceof, #todo change to validitate
'in': js_in}
BSHIFTS = {'<<': js_lshift,
'>>': js_rshift,
'>>>': js_shit}
ADDS = {'+': js_add,
'-': js_sub}
MULTS = {'*': js_mul,
'/': js_div,
'%': js_mod}
BINARY = {}
BINARY.update(ADDS)
BINARY.update(MULTS)
BINARY.update(BSHIFTS)
BINARY.update(COMPS)
BINARY.update(EQS)
BINARY.update(BAND)
BINARY.update(BXOR)
BINARY.update(BOR)
BINARY.update(AND)
BINARY.update(OR)
#Note they dont contain ++ and -- methods because they both have 2 different methods
# correct method will be found automatically in translate function
UNARY = {'typeof': js_typeof,
'void': js_void,
'new': js_new,
'delete': js_delete,
'!': js_not,
'-': js_neg,
'+': js_pos,
'~': js_inv,
'++': None,
'--': None
} | gpl-2.0 |
benoitsteiner/tensorflow-opencl | tensorflow/contrib/training/python/training/feeding_queue_runner.py | 143 | 1046 | # 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.
# ==============================================================================
"""A `QueueRunner` that takes a feed function as an argument."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
# pylint: disable=unused-import
from tensorflow.python.estimator.inputs.queues.feeding_queue_runner import _FeedingQueueRunner as FeedingQueueRunner
# pylint: enable=unused-import
| apache-2.0 |
gitaarik/django | django/contrib/gis/geos/prototypes/predicates.py | 171 | 1587 | """
This module houses the GEOS ctypes prototype functions for the
unary and binary predicate operations on geometries.
"""
from ctypes import c_char, c_char_p, c_double
from django.contrib.gis.geos.libgeos import GEOM_PTR, GEOSFuncFactory
from django.contrib.gis.geos.prototypes.errcheck import check_predicate
# ## Binary & unary predicate factories ##
class UnaryPredicate(GEOSFuncFactory):
"For GEOS unary predicate functions."
argtypes = [GEOM_PTR]
restype = c_char
errcheck = staticmethod(check_predicate)
class BinaryPredicate(UnaryPredicate):
"For GEOS binary predicate functions."
argtypes = [GEOM_PTR, GEOM_PTR]
# ## Unary Predicates ##
geos_hasz = UnaryPredicate('GEOSHasZ')
geos_isclosed = UnaryPredicate('GEOSisClosed')
geos_isempty = UnaryPredicate('GEOSisEmpty')
geos_isring = UnaryPredicate('GEOSisRing')
geos_issimple = UnaryPredicate('GEOSisSimple')
geos_isvalid = UnaryPredicate('GEOSisValid')
# ## Binary Predicates ##
geos_contains = BinaryPredicate('GEOSContains')
geos_covers = BinaryPredicate('GEOSCovers')
geos_crosses = BinaryPredicate('GEOSCrosses')
geos_disjoint = BinaryPredicate('GEOSDisjoint')
geos_equals = BinaryPredicate('GEOSEquals')
geos_equalsexact = BinaryPredicate('GEOSEqualsExact', argtypes=[GEOM_PTR, GEOM_PTR, c_double])
geos_intersects = BinaryPredicate('GEOSIntersects')
geos_overlaps = BinaryPredicate('GEOSOverlaps')
geos_relatepattern = BinaryPredicate('GEOSRelatePattern', argtypes=[GEOM_PTR, GEOM_PTR, c_char_p])
geos_touches = BinaryPredicate('GEOSTouches')
geos_within = BinaryPredicate('GEOSWithin')
| bsd-3-clause |
supergis/QGIS | python/plugins/processing/gui/utils.py | 4 | 1983 | from qgis.utils import iface
from PyQt4 import QtGui
from processing.core.Processing import Processing
from processing.gui.MessageDialog import MessageDialog
from processing.gui.AlgorithmDialog import AlgorithmDialog
algorithmsToolbar = None
def addAlgorithmEntry(algname, menuName, submenuName, actionText=None, icon=None, addButton=False):
alg = Processing.getAlgorithm(algname)
if alg is None:
return
if menuName:
menu = getMenu(menuName, iface.mainWindow().menuBar())
submenu = getMenu(submenuName, menu)
action = QtGui.QAction(icon or alg.getIcon(), actionText or alg.name, iface.mainWindow())
action.triggered.connect(lambda: _executeAlgorithm(alg))
submenu.addAction(action)
if addButton:
global algorithmsToolbar
if algorithmsToolbar is None:
algorithmsToolbar = iface.addToolBar("ProcessingAlgorithms")
algorithmsToolbar.addAction(action)
def _executeAlgorithm(alg):
message = alg.checkBeforeOpeningParametersDialog()
if message:
dlg = MessageDialog()
dlg.setTitle(tr('Missing dependency'))
dlg.setMessage(
tr('<h3>Missing dependency. This algorithm cannot '
'be run :-( </h3>\n%s') % message)
dlg.exec_()
return
alg = alg.getCopy()
dlg = alg.getCustomParametersDialog()
if not dlg:
dlg = AlgorithmDialog(alg)
canvas = iface.mapCanvas()
prevMapTool = canvas.mapTool()
dlg.show()
dlg.exec_()
if canvas.mapTool() != prevMapTool:
try:
canvas.mapTool().reset()
except:
pass
canvas.setMapTool(prevMapTool)
def getMenu(name, parent):
menus = [c for c in parent.children() if isinstance(c, QtGui.QMenu)]
menusDict = {m.title(): m for m in menus}
if name in menusDict:
return menusDict[name]
else:
menu = QtGui.QMenu(name, parent)
parent.addMenu(menu)
return menu
| gpl-2.0 |
Elite-Kernels/elite_bullhead | tools/perf/scripts/python/netdev-times.py | 11271 | 15048 | # Display a process of packets and processed time.
# It helps us to investigate networking or network device.
#
# options
# tx: show only tx chart
# rx: show only rx chart
# dev=: show only thing related to specified device
# debug: work with debug mode. It shows buffer status.
import os
import sys
sys.path.append(os.environ['PERF_EXEC_PATH'] + \
'/scripts/python/Perf-Trace-Util/lib/Perf/Trace')
from perf_trace_context import *
from Core import *
from Util import *
all_event_list = []; # insert all tracepoint event related with this script
irq_dic = {}; # key is cpu and value is a list which stacks irqs
# which raise NET_RX softirq
net_rx_dic = {}; # key is cpu and value include time of NET_RX softirq-entry
# and a list which stacks receive
receive_hunk_list = []; # a list which include a sequence of receive events
rx_skb_list = []; # received packet list for matching
# skb_copy_datagram_iovec
buffer_budget = 65536; # the budget of rx_skb_list, tx_queue_list and
# tx_xmit_list
of_count_rx_skb_list = 0; # overflow count
tx_queue_list = []; # list of packets which pass through dev_queue_xmit
of_count_tx_queue_list = 0; # overflow count
tx_xmit_list = []; # list of packets which pass through dev_hard_start_xmit
of_count_tx_xmit_list = 0; # overflow count
tx_free_list = []; # list of packets which is freed
# options
show_tx = 0;
show_rx = 0;
dev = 0; # store a name of device specified by option "dev="
debug = 0;
# indices of event_info tuple
EINFO_IDX_NAME= 0
EINFO_IDX_CONTEXT=1
EINFO_IDX_CPU= 2
EINFO_IDX_TIME= 3
EINFO_IDX_PID= 4
EINFO_IDX_COMM= 5
# Calculate a time interval(msec) from src(nsec) to dst(nsec)
def diff_msec(src, dst):
return (dst - src) / 1000000.0
# Display a process of transmitting a packet
def print_transmit(hunk):
if dev != 0 and hunk['dev'].find(dev) < 0:
return
print "%7s %5d %6d.%06dsec %12.3fmsec %12.3fmsec" % \
(hunk['dev'], hunk['len'],
nsecs_secs(hunk['queue_t']),
nsecs_nsecs(hunk['queue_t'])/1000,
diff_msec(hunk['queue_t'], hunk['xmit_t']),
diff_msec(hunk['xmit_t'], hunk['free_t']))
# Format for displaying rx packet processing
PF_IRQ_ENTRY= " irq_entry(+%.3fmsec irq=%d:%s)"
PF_SOFT_ENTRY=" softirq_entry(+%.3fmsec)"
PF_NAPI_POLL= " napi_poll_exit(+%.3fmsec %s)"
PF_JOINT= " |"
PF_WJOINT= " | |"
PF_NET_RECV= " |---netif_receive_skb(+%.3fmsec skb=%x len=%d)"
PF_NET_RX= " |---netif_rx(+%.3fmsec skb=%x)"
PF_CPY_DGRAM= " | skb_copy_datagram_iovec(+%.3fmsec %d:%s)"
PF_KFREE_SKB= " | kfree_skb(+%.3fmsec location=%x)"
PF_CONS_SKB= " | consume_skb(+%.3fmsec)"
# Display a process of received packets and interrputs associated with
# a NET_RX softirq
def print_receive(hunk):
show_hunk = 0
irq_list = hunk['irq_list']
cpu = irq_list[0]['cpu']
base_t = irq_list[0]['irq_ent_t']
# check if this hunk should be showed
if dev != 0:
for i in range(len(irq_list)):
if irq_list[i]['name'].find(dev) >= 0:
show_hunk = 1
break
else:
show_hunk = 1
if show_hunk == 0:
return
print "%d.%06dsec cpu=%d" % \
(nsecs_secs(base_t), nsecs_nsecs(base_t)/1000, cpu)
for i in range(len(irq_list)):
print PF_IRQ_ENTRY % \
(diff_msec(base_t, irq_list[i]['irq_ent_t']),
irq_list[i]['irq'], irq_list[i]['name'])
print PF_JOINT
irq_event_list = irq_list[i]['event_list']
for j in range(len(irq_event_list)):
irq_event = irq_event_list[j]
if irq_event['event'] == 'netif_rx':
print PF_NET_RX % \
(diff_msec(base_t, irq_event['time']),
irq_event['skbaddr'])
print PF_JOINT
print PF_SOFT_ENTRY % \
diff_msec(base_t, hunk['sirq_ent_t'])
print PF_JOINT
event_list = hunk['event_list']
for i in range(len(event_list)):
event = event_list[i]
if event['event_name'] == 'napi_poll':
print PF_NAPI_POLL % \
(diff_msec(base_t, event['event_t']), event['dev'])
if i == len(event_list) - 1:
print ""
else:
print PF_JOINT
else:
print PF_NET_RECV % \
(diff_msec(base_t, event['event_t']), event['skbaddr'],
event['len'])
if 'comm' in event.keys():
print PF_WJOINT
print PF_CPY_DGRAM % \
(diff_msec(base_t, event['comm_t']),
event['pid'], event['comm'])
elif 'handle' in event.keys():
print PF_WJOINT
if event['handle'] == "kfree_skb":
print PF_KFREE_SKB % \
(diff_msec(base_t,
event['comm_t']),
event['location'])
elif event['handle'] == "consume_skb":
print PF_CONS_SKB % \
diff_msec(base_t,
event['comm_t'])
print PF_JOINT
def trace_begin():
global show_tx
global show_rx
global dev
global debug
for i in range(len(sys.argv)):
if i == 0:
continue
arg = sys.argv[i]
if arg == 'tx':
show_tx = 1
elif arg =='rx':
show_rx = 1
elif arg.find('dev=',0, 4) >= 0:
dev = arg[4:]
elif arg == 'debug':
debug = 1
if show_tx == 0 and show_rx == 0:
show_tx = 1
show_rx = 1
def trace_end():
# order all events in time
all_event_list.sort(lambda a,b :cmp(a[EINFO_IDX_TIME],
b[EINFO_IDX_TIME]))
# process all events
for i in range(len(all_event_list)):
event_info = all_event_list[i]
name = event_info[EINFO_IDX_NAME]
if name == 'irq__softirq_exit':
handle_irq_softirq_exit(event_info)
elif name == 'irq__softirq_entry':
handle_irq_softirq_entry(event_info)
elif name == 'irq__softirq_raise':
handle_irq_softirq_raise(event_info)
elif name == 'irq__irq_handler_entry':
handle_irq_handler_entry(event_info)
elif name == 'irq__irq_handler_exit':
handle_irq_handler_exit(event_info)
elif name == 'napi__napi_poll':
handle_napi_poll(event_info)
elif name == 'net__netif_receive_skb':
handle_netif_receive_skb(event_info)
elif name == 'net__netif_rx':
handle_netif_rx(event_info)
elif name == 'skb__skb_copy_datagram_iovec':
handle_skb_copy_datagram_iovec(event_info)
elif name == 'net__net_dev_queue':
handle_net_dev_queue(event_info)
elif name == 'net__net_dev_xmit':
handle_net_dev_xmit(event_info)
elif name == 'skb__kfree_skb':
handle_kfree_skb(event_info)
elif name == 'skb__consume_skb':
handle_consume_skb(event_info)
# display receive hunks
if show_rx:
for i in range(len(receive_hunk_list)):
print_receive(receive_hunk_list[i])
# display transmit hunks
if show_tx:
print " dev len Qdisc " \
" netdevice free"
for i in range(len(tx_free_list)):
print_transmit(tx_free_list[i])
if debug:
print "debug buffer status"
print "----------------------------"
print "xmit Qdisc:remain:%d overflow:%d" % \
(len(tx_queue_list), of_count_tx_queue_list)
print "xmit netdevice:remain:%d overflow:%d" % \
(len(tx_xmit_list), of_count_tx_xmit_list)
print "receive:remain:%d overflow:%d" % \
(len(rx_skb_list), of_count_rx_skb_list)
# called from perf, when it finds a correspoinding event
def irq__softirq_entry(name, context, cpu, sec, nsec, pid, comm, vec):
if symbol_str("irq__softirq_entry", "vec", vec) != "NET_RX":
return
event_info = (name, context, cpu, nsecs(sec, nsec), pid, comm, vec)
all_event_list.append(event_info)
def irq__softirq_exit(name, context, cpu, sec, nsec, pid, comm, vec):
if symbol_str("irq__softirq_entry", "vec", vec) != "NET_RX":
return
event_info = (name, context, cpu, nsecs(sec, nsec), pid, comm, vec)
all_event_list.append(event_info)
def irq__softirq_raise(name, context, cpu, sec, nsec, pid, comm, vec):
if symbol_str("irq__softirq_entry", "vec", vec) != "NET_RX":
return
event_info = (name, context, cpu, nsecs(sec, nsec), pid, comm, vec)
all_event_list.append(event_info)
def irq__irq_handler_entry(name, context, cpu, sec, nsec, pid, comm,
irq, irq_name):
event_info = (name, context, cpu, nsecs(sec, nsec), pid, comm,
irq, irq_name)
all_event_list.append(event_info)
def irq__irq_handler_exit(name, context, cpu, sec, nsec, pid, comm, irq, ret):
event_info = (name, context, cpu, nsecs(sec, nsec), pid, comm, irq, ret)
all_event_list.append(event_info)
def napi__napi_poll(name, context, cpu, sec, nsec, pid, comm, napi, dev_name):
event_info = (name, context, cpu, nsecs(sec, nsec), pid, comm,
napi, dev_name)
all_event_list.append(event_info)
def net__netif_receive_skb(name, context, cpu, sec, nsec, pid, comm, skbaddr,
skblen, dev_name):
event_info = (name, context, cpu, nsecs(sec, nsec), pid, comm,
skbaddr, skblen, dev_name)
all_event_list.append(event_info)
def net__netif_rx(name, context, cpu, sec, nsec, pid, comm, skbaddr,
skblen, dev_name):
event_info = (name, context, cpu, nsecs(sec, nsec), pid, comm,
skbaddr, skblen, dev_name)
all_event_list.append(event_info)
def net__net_dev_queue(name, context, cpu, sec, nsec, pid, comm,
skbaddr, skblen, dev_name):
event_info = (name, context, cpu, nsecs(sec, nsec), pid, comm,
skbaddr, skblen, dev_name)
all_event_list.append(event_info)
def net__net_dev_xmit(name, context, cpu, sec, nsec, pid, comm,
skbaddr, skblen, rc, dev_name):
event_info = (name, context, cpu, nsecs(sec, nsec), pid, comm,
skbaddr, skblen, rc ,dev_name)
all_event_list.append(event_info)
def skb__kfree_skb(name, context, cpu, sec, nsec, pid, comm,
skbaddr, protocol, location):
event_info = (name, context, cpu, nsecs(sec, nsec), pid, comm,
skbaddr, protocol, location)
all_event_list.append(event_info)
def skb__consume_skb(name, context, cpu, sec, nsec, pid, comm, skbaddr):
event_info = (name, context, cpu, nsecs(sec, nsec), pid, comm,
skbaddr)
all_event_list.append(event_info)
def skb__skb_copy_datagram_iovec(name, context, cpu, sec, nsec, pid, comm,
skbaddr, skblen):
event_info = (name, context, cpu, nsecs(sec, nsec), pid, comm,
skbaddr, skblen)
all_event_list.append(event_info)
def handle_irq_handler_entry(event_info):
(name, context, cpu, time, pid, comm, irq, irq_name) = event_info
if cpu not in irq_dic.keys():
irq_dic[cpu] = []
irq_record = {'irq':irq, 'name':irq_name, 'cpu':cpu, 'irq_ent_t':time}
irq_dic[cpu].append(irq_record)
def handle_irq_handler_exit(event_info):
(name, context, cpu, time, pid, comm, irq, ret) = event_info
if cpu not in irq_dic.keys():
return
irq_record = irq_dic[cpu].pop()
if irq != irq_record['irq']:
return
irq_record.update({'irq_ext_t':time})
# if an irq doesn't include NET_RX softirq, drop.
if 'event_list' in irq_record.keys():
irq_dic[cpu].append(irq_record)
def handle_irq_softirq_raise(event_info):
(name, context, cpu, time, pid, comm, vec) = event_info
if cpu not in irq_dic.keys() \
or len(irq_dic[cpu]) == 0:
return
irq_record = irq_dic[cpu].pop()
if 'event_list' in irq_record.keys():
irq_event_list = irq_record['event_list']
else:
irq_event_list = []
irq_event_list.append({'time':time, 'event':'sirq_raise'})
irq_record.update({'event_list':irq_event_list})
irq_dic[cpu].append(irq_record)
def handle_irq_softirq_entry(event_info):
(name, context, cpu, time, pid, comm, vec) = event_info
net_rx_dic[cpu] = {'sirq_ent_t':time, 'event_list':[]}
def handle_irq_softirq_exit(event_info):
(name, context, cpu, time, pid, comm, vec) = event_info
irq_list = []
event_list = 0
if cpu in irq_dic.keys():
irq_list = irq_dic[cpu]
del irq_dic[cpu]
if cpu in net_rx_dic.keys():
sirq_ent_t = net_rx_dic[cpu]['sirq_ent_t']
event_list = net_rx_dic[cpu]['event_list']
del net_rx_dic[cpu]
if irq_list == [] or event_list == 0:
return
rec_data = {'sirq_ent_t':sirq_ent_t, 'sirq_ext_t':time,
'irq_list':irq_list, 'event_list':event_list}
# merge information realted to a NET_RX softirq
receive_hunk_list.append(rec_data)
def handle_napi_poll(event_info):
(name, context, cpu, time, pid, comm, napi, dev_name) = event_info
if cpu in net_rx_dic.keys():
event_list = net_rx_dic[cpu]['event_list']
rec_data = {'event_name':'napi_poll',
'dev':dev_name, 'event_t':time}
event_list.append(rec_data)
def handle_netif_rx(event_info):
(name, context, cpu, time, pid, comm,
skbaddr, skblen, dev_name) = event_info
if cpu not in irq_dic.keys() \
or len(irq_dic[cpu]) == 0:
return
irq_record = irq_dic[cpu].pop()
if 'event_list' in irq_record.keys():
irq_event_list = irq_record['event_list']
else:
irq_event_list = []
irq_event_list.append({'time':time, 'event':'netif_rx',
'skbaddr':skbaddr, 'skblen':skblen, 'dev_name':dev_name})
irq_record.update({'event_list':irq_event_list})
irq_dic[cpu].append(irq_record)
def handle_netif_receive_skb(event_info):
global of_count_rx_skb_list
(name, context, cpu, time, pid, comm,
skbaddr, skblen, dev_name) = event_info
if cpu in net_rx_dic.keys():
rec_data = {'event_name':'netif_receive_skb',
'event_t':time, 'skbaddr':skbaddr, 'len':skblen}
event_list = net_rx_dic[cpu]['event_list']
event_list.append(rec_data)
rx_skb_list.insert(0, rec_data)
if len(rx_skb_list) > buffer_budget:
rx_skb_list.pop()
of_count_rx_skb_list += 1
def handle_net_dev_queue(event_info):
global of_count_tx_queue_list
(name, context, cpu, time, pid, comm,
skbaddr, skblen, dev_name) = event_info
skb = {'dev':dev_name, 'skbaddr':skbaddr, 'len':skblen, 'queue_t':time}
tx_queue_list.insert(0, skb)
if len(tx_queue_list) > buffer_budget:
tx_queue_list.pop()
of_count_tx_queue_list += 1
def handle_net_dev_xmit(event_info):
global of_count_tx_xmit_list
(name, context, cpu, time, pid, comm,
skbaddr, skblen, rc, dev_name) = event_info
if rc == 0: # NETDEV_TX_OK
for i in range(len(tx_queue_list)):
skb = tx_queue_list[i]
if skb['skbaddr'] == skbaddr:
skb['xmit_t'] = time
tx_xmit_list.insert(0, skb)
del tx_queue_list[i]
if len(tx_xmit_list) > buffer_budget:
tx_xmit_list.pop()
of_count_tx_xmit_list += 1
return
def handle_kfree_skb(event_info):
(name, context, cpu, time, pid, comm,
skbaddr, protocol, location) = event_info
for i in range(len(tx_queue_list)):
skb = tx_queue_list[i]
if skb['skbaddr'] == skbaddr:
del tx_queue_list[i]
return
for i in range(len(tx_xmit_list)):
skb = tx_xmit_list[i]
if skb['skbaddr'] == skbaddr:
skb['free_t'] = time
tx_free_list.append(skb)
del tx_xmit_list[i]
return
for i in range(len(rx_skb_list)):
rec_data = rx_skb_list[i]
if rec_data['skbaddr'] == skbaddr:
rec_data.update({'handle':"kfree_skb",
'comm':comm, 'pid':pid, 'comm_t':time})
del rx_skb_list[i]
return
def handle_consume_skb(event_info):
(name, context, cpu, time, pid, comm, skbaddr) = event_info
for i in range(len(tx_xmit_list)):
skb = tx_xmit_list[i]
if skb['skbaddr'] == skbaddr:
skb['free_t'] = time
tx_free_list.append(skb)
del tx_xmit_list[i]
return
def handle_skb_copy_datagram_iovec(event_info):
(name, context, cpu, time, pid, comm, skbaddr, skblen) = event_info
for i in range(len(rx_skb_list)):
rec_data = rx_skb_list[i]
if skbaddr == rec_data['skbaddr']:
rec_data.update({'handle':"skb_copy_datagram_iovec",
'comm':comm, 'pid':pid, 'comm_t':time})
del rx_skb_list[i]
return
| gpl-2.0 |
jeremiahyan/odoo | addons/l10n_ae/__manifest__.py | 4 | 1025 | # -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
# Copyright (C) 2014 Tech Receptives (<http://techreceptives.com>)
{
'name': 'U.A.E. - Accounting',
'author': 'Tech Receptives',
'category': 'Accounting/Localizations/Account Charts',
'description': """
United Arab Emirates accounting chart and localization.
=======================================================
""",
'depends': ['base', 'account'],
'data': [
'data/l10n_ae_data.xml',
'data/account_data.xml',
'data/l10n_ae_chart_data.xml',
'data/account.account.template.csv',
'data/l10n_ae_chart_post_data.xml',
'data/account_tax_report_data.xml',
'data/account_tax_template_data.xml',
'data/fiscal_templates_data.xml',
'data/account_chart_template_data.xml',
'views/report_invoice_templates.xml',
],
'demo': [
'demo/demo_company.xml',
],
}
| gpl-3.0 |
alfa-jor/addon | plugin.video.alfa/lib/python_libtorrent/python_libtorrent/__init__.py | 1 | 11562 | #-*- coding: utf-8 -*-
'''
python-libtorrent for Kodi (script.module.libtorrent)
Copyright (C) 2015-2016 DiMartino, srg70, RussakHH, aisman
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.
'''
from functions import *
import xbmc, xbmcaddon
import sys
import os
import traceback ### Alfa
#__settings__ = xbmcaddon.Addon(id='script.module.libtorrent') ### Alfa
#__version__ = __settings__.getAddonInfo('version') ### Alfa
#__plugin__ = __settings__.getAddonInfo('name') + " v." + __version__ ### Alfa
#__settings__ = xbmcaddon.Addon(id='plugin.video.alfa') ### Alfa
__version__ = '1.1.17' ### Alfa
__plugin__ = "python-libtorrent v.1.1.7" ### Alfa
#__language__ = __settings__.getLocalizedString ### Alfa
__root__ = os.path.dirname(os.path.dirname(__file__))
libtorrent=None
platform = get_platform()
#set_dirname=__settings__.getSetting('dirname') ### Alfa
#set_dirname=os.path.join(__settings__.getAddonInfo('Path'),'lib', 'python_libtorrent') ### Alfa
set_dirname=__root__ ### Alfa
if getSettingAsBool('custom_dirname') and set_dirname:
log('set_dirname:' +str(set_dirname))
dirname=set_dirname
else:
#dirname = os.path.join(xbmc.translatePath('special://temp'), 'xbmcup', 'script.module.libtorrent',
# 'python_libtorrent')
dirname=set_dirname ### Alfa
log('dirname: ' +str(dirname))
versions = ['0.16.19', '1.0.6', '1.0.7', '1.0.8', '1.0.9', '1.0.11', '1.1.0', '1.1.1', '1.1.6', '1.1.7', '1.2.1', '1.2.2'] ### Alfa
default_path = versions[-1]
#set_version = int(__settings__.getSetting('set_version')) ### Alfa
set_version = 0 ### Alfa
if getSettingAsBool('custom_version'):
log('set_version:' +str(set_version)+' '+versions[set_version])
platform['version'] = versions[set_version]
else:
platform['version'] = default_path
sizefile_path = os.path.join(__root__, platform['system'], platform['version'])
if not os.path.exists(sizefile_path):
log('set_version: no sizefile at %s back to default %s' % (sizefile_path, default_path))
platform['version'] = default_path
sizefile_path = os.path.join(__root__, platform['system'], platform['version'])
if not os.path.exists(sizefile_path):
log('set_version: no default at %s searching for any version' % sizefile_path)
try:
versions = sorted(os.listdir(os.path.join(__root__, platform['system'])))
except:
versions = []
for ver in versions:
if not os.path.isdir(os.path.join(__root__, platform['system'], ver)):
versions.remove(ver)
if len(versions)>0:
platform['version'] = versions[-1]
log('set_version: chose %s out of %s' % (platform['version'], str(versions)))
else:
e = 'die because the folder is empty'
log(e)
raise Exception(e)
dest_path = os.path.join(dirname, platform['system'], platform['version'])
sys.path.insert(0, dest_path)
lm=LibraryManager(dest_path, platform)
if not lm.check_exist():
ok=lm.download()
xbmc.sleep(2000)
#if __settings__.getSetting('plugin_name')!=__plugin__: ### Alfa
# __settings__.setSetting('plugin_name', __plugin__) ### Alfa
# lm.update() ### Alfa
log('platform: ' + str(platform))
if platform['system'] not in ['windows', 'windows_x64']: ### Alfa
log('os: '+str(os.uname()))
log_text = 'ucs4' if sys.maxunicode > 65536 else 'ucs2'
log_text += ' x64' if sys.maxint > 2147483647 else ' x86'
log(log_text)
try:
fp = ''
pathname = ''
description = ''
libtorrent = ''
from platformcode import config
if platform['system'] in ['linux_x86', 'windows', 'windows_x64', 'linux_armv6', 'linux_armv7',
'linux_x86_64', 'linux_mipsel_ucs2', 'linux_mipsel_ucs4',
'linux_aarch64_ucs2', 'linux_aarch64_ucs4']: ### Alfa
import libtorrent
elif platform['system'] in ['darwin', 'ios_arm']:
import imp
path_list = [dest_path]
log('path_list = ' + str(path_list))
fp, pathname, description = imp.find_module('libtorrent', path_list)
log('fp = ' + str(fp))
log('pathname = ' + str(pathname))
log('description = ' + str(description))
try:
libtorrent = imp.load_module('libtorrent', fp, pathname, description)
finally:
if fp: fp.close()
elif platform['system'] in ['android_armv7', 'android_x86']:
import imp
from ctypes import CDLL
try:
dest_path=lm.android_workaround(os.path.join(xbmc.translatePath('special://xbmc/'), 'files').replace('/cache/apk/assets', ''))
dll_path=os.path.join(dest_path, 'liblibtorrent.so')
log('CDLL path = ' + dll_path)
liblibtorrent=CDLL(dll_path)
log('CDLL = ' + str(liblibtorrent))
path_list = [dest_path]
log('path_list = ' + str(path_list))
fp, pathname, description = imp.find_module('libtorrent', path_list)
log('fp = ' + str(fp))
log('pathname = ' + str(pathname))
log('description = ' + str(description))
try:
libtorrent = imp.load_module('libtorrent', fp, pathname, description)
finally:
if fp: fp.close()
except Exception, e:
e = unicode(str(e), "utf8", errors="replace").encode("utf8")
config.set_setting("libtorrent_path", "", server="torrent") ### Alfa
config.set_setting("libtorrent_error", str(e), server="torrent") ### Alfa
log(traceback.format_exc(1))
log('fp = ' + str(fp))
log('pathname = ' + str(pathname))
log('description = ' + str(description))
log('Error importing libtorrent from "' + dest_path + '". Exception: ' + str(e))
if fp: fp.close()
# If no permission in dest_path we need to go deeper on root!
try: ### Alfa START
sys_path = '/data/app/'
fp = ''
pathname = sys_path
dest_path = sys_path
description = ''
libtorrent = ''
LIBTORRENT_MSG = config.get_setting("libtorrent_msg", server="torrent", default='')
if not LIBTORRENT_MSG:
dialog = xbmcgui.Dialog()
dialog.notification('ALFA: Instalando Cliente Torrent interno', \
'Puede solicitarle permisos de Superusuario', time=15000)
log('### ALFA: Notificación enviada: Instalando Cliente Torrent interno')
config.set_setting("libtorrent_msg", 'OK', server="torrent")
from core import scrapertools
kodi_app = xbmc.translatePath('special://xbmc')
kodi_app = scrapertools.find_single_match(kodi_app, '\/\w+\/\w+\/.*?\/(.*?)\/')
kodi_dir = '%s-1' % kodi_app
dir_list = ''
try:
dir_list = os.listdir(sys_path).split()
except:
import subprocess
command = ['su', '-c', 'ls', sys_path]
p = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
output_cmd, error_cmd = p.communicate()
log('Comando ROOT: %s' % str(command))
dir_list = output_cmd.split()
if not dir_list:
raise
for file in dir_list:
if kodi_app in file:
kodi_dir = file
break
bits = sys.maxsize > 2 ** 32 and "64" or ""
dest_path = os.path.join(sys_path, kodi_dir, 'lib', platform['arch'] + bits)
dest_path=lm.android_workaround(new_dest_path=dest_path)
dll_path=os.path.join(dest_path, 'liblibtorrent.so')
log('NEW CDLL path = ' + dll_path)
liblibtorrent=CDLL(dll_path)
log('CDLL = ' + str(liblibtorrent))
path_list = [dest_path]
log('path_list = ' + str(path_list))
fp, pathname, description = imp.find_module('libtorrent', path_list)
try:
libtorrent = imp.load_module('libtorrent', fp, pathname, description)
finally:
if fp: fp.close()
except Exception, e:
log('ERROR Comando ROOT: %s, %s' % (str(command), str(dest_path)))
e = unicode(str(e), "utf8", errors="replace").encode("utf8")
log(traceback.format_exc(1)) ### Alfa
log('fp = ' + str(fp))
log('pathname = ' + str(pathname))
log('description = ' + str(description))
log('Error importing libtorrent from "' + dest_path + '". Exception: ' + str(e))
if fp: fp.close()
if libtorrent:
config.set_setting("libtorrent_path", dest_path, server="torrent") ### Alfa
config.set_setting("libtorrent_error", "", server="torrent") ### Alfa
log('Imported libtorrent v' + libtorrent.version + ' from "' + dest_path + '"')
except Exception, e:
e = unicode(str(e), "utf8", errors="replace").encode("utf8")
config.set_setting("libtorrent_path", "", server="torrent") ### Alfa
config.set_setting("libtorrent_error", str(e), server="torrent") ### Alfa
log('Error importing libtorrent from "' + dest_path + '". Exception: ' + str(e))
if fp: fp.close()
def get_libtorrent():
return libtorrent
| gpl-3.0 |
yhoshino11/GuestBook | .venv/lib/python2.7/site-packages/pip/utils/appdirs.py | 311 | 9173 | """
This code was taken from https://github.com/ActiveState/appdirs and modified
to suite our purposes.
"""
from __future__ import absolute_import
import os
import sys
from pip.compat import WINDOWS
def user_cache_dir(appname):
r"""
Return full path to the user-specific cache dir for this application.
"appname" is the name of application.
Typical user cache directories are:
Mac OS X: ~/Library/Caches/<AppName>
Unix: ~/.cache/<AppName> (XDG default)
Windows: C:\Users\<username>\AppData\Local\<AppName>\Cache
On Windows the only suggestion in the MSDN docs is that local settings go
in the `CSIDL_LOCAL_APPDATA` directory. This is identical to the
non-roaming app data dir (the default returned by `user_data_dir`). Apps
typically put cache data somewhere *under* the given dir here. Some
examples:
...\Mozilla\Firefox\Profiles\<ProfileName>\Cache
...\Acme\SuperApp\Cache\1.0
OPINION: This function appends "Cache" to the `CSIDL_LOCAL_APPDATA` value.
"""
if WINDOWS:
# Get the base path
path = os.path.normpath(_get_win_folder("CSIDL_LOCAL_APPDATA"))
# Add our app name and Cache directory to it
path = os.path.join(path, appname, "Cache")
elif sys.platform == "darwin":
# Get the base path
path = os.path.expanduser("~/Library/Caches")
# Add our app name to it
path = os.path.join(path, appname)
else:
# Get the base path
path = os.getenv("XDG_CACHE_HOME", os.path.expanduser("~/.cache"))
# Add our app name to it
path = os.path.join(path, appname)
return path
def user_data_dir(appname, roaming=False):
"""
Return full path to the user-specific data dir for this application.
"appname" is the name of application.
If None, just the system directory is returned.
"roaming" (boolean, default False) can be set True to use the Windows
roaming appdata directory. That means that for users on a Windows
network setup for roaming profiles, this user data will be
sync'd on login. See
<http://technet.microsoft.com/en-us/library/cc766489(WS.10).aspx>
for a discussion of issues.
Typical user data directories are:
Mac OS X: ~/Library/Application Support/<AppName>
Unix: ~/.local/share/<AppName> # or in
$XDG_DATA_HOME, if defined
Win XP (not roaming): C:\Documents and Settings\<username>\ ...
...Application Data\<AppName>
Win XP (roaming): C:\Documents and Settings\<username>\Local ...
...Settings\Application Data\<AppName>
Win 7 (not roaming): C:\\Users\<username>\AppData\Local\<AppName>
Win 7 (roaming): C:\\Users\<username>\AppData\Roaming\<AppName>
For Unix, we follow the XDG spec and support $XDG_DATA_HOME.
That means, by default "~/.local/share/<AppName>".
"""
if WINDOWS:
const = roaming and "CSIDL_APPDATA" or "CSIDL_LOCAL_APPDATA"
path = os.path.join(os.path.normpath(_get_win_folder(const)), appname)
elif sys.platform == "darwin":
path = os.path.join(
os.path.expanduser('~/Library/Application Support/'),
appname,
)
else:
path = os.path.join(
os.getenv('XDG_DATA_HOME', os.path.expanduser("~/.local/share")),
appname,
)
return path
def user_log_dir(appname):
"""
Return full path to the user-specific log dir for this application.
"appname" is the name of application.
If None, just the system directory is returned.
Typical user cache directories are:
Mac OS X: ~/Library/Logs/<AppName>
Unix: ~/.cache/<AppName>/log # or under $XDG_CACHE_HOME if
defined
Win XP: C:\Documents and Settings\<username>\Local Settings\ ...
...Application Data\<AppName>\Logs
Vista: C:\\Users\<username>\AppData\Local\<AppName>\Logs
On Windows the only suggestion in the MSDN docs is that local settings
go in the `CSIDL_LOCAL_APPDATA` directory. (Note: I'm interested in
examples of what some windows apps use for a logs dir.)
OPINION: This function appends "Logs" to the `CSIDL_LOCAL_APPDATA`
value for Windows and appends "log" to the user cache dir for Unix.
"""
if WINDOWS:
path = os.path.join(user_data_dir(appname), "Logs")
elif sys.platform == "darwin":
path = os.path.join(os.path.expanduser('~/Library/Logs'), appname)
else:
path = os.path.join(user_cache_dir(appname), "log")
return path
def user_config_dir(appname, roaming=True):
"""Return full path to the user-specific config dir for this application.
"appname" is the name of application.
If None, just the system directory is returned.
"roaming" (boolean, default True) can be set False to not use the
Windows roaming appdata directory. That means that for users on a
Windows network setup for roaming profiles, this user data will be
sync'd on login. See
<http://technet.microsoft.com/en-us/library/cc766489(WS.10).aspx>
for a discussion of issues.
Typical user data directories are:
Mac OS X: same as user_data_dir
Unix: ~/.config/<AppName>
Win *: same as user_data_dir
For Unix, we follow the XDG spec and support $XDG_CONFIG_HOME.
That means, by deafult "~/.config/<AppName>".
"""
if WINDOWS:
path = user_data_dir(appname, roaming=roaming)
elif sys.platform == "darwin":
path = user_data_dir(appname)
else:
path = os.getenv('XDG_CONFIG_HOME', os.path.expanduser("~/.config"))
path = os.path.join(path, appname)
return path
# for the discussion regarding site_config_dirs locations
# see <https://github.com/pypa/pip/issues/1733>
def site_config_dirs(appname):
"""Return a list of potential user-shared config dirs for this application.
"appname" is the name of application.
Typical user config directories are:
Mac OS X: /Library/Application Support/<AppName>/
Unix: /etc or $XDG_CONFIG_DIRS[i]/<AppName>/ for each value in
$XDG_CONFIG_DIRS
Win XP: C:\Documents and Settings\All Users\Application ...
...Data\<AppName>\
Vista: (Fail! "C:\ProgramData" is a hidden *system* directory
on Vista.)
Win 7: Hidden, but writeable on Win 7:
C:\ProgramData\<AppName>\
"""
if WINDOWS:
path = os.path.normpath(_get_win_folder("CSIDL_COMMON_APPDATA"))
pathlist = [os.path.join(path, appname)]
elif sys.platform == 'darwin':
pathlist = [os.path.join('/Library/Application Support', appname)]
else:
# try looking in $XDG_CONFIG_DIRS
xdg_config_dirs = os.getenv('XDG_CONFIG_DIRS', '/etc/xdg')
if xdg_config_dirs:
pathlist = [
os.sep.join([os.path.expanduser(x), appname])
for x in xdg_config_dirs.split(os.pathsep)
]
else:
pathlist = []
# always look in /etc directly as well
pathlist.append('/etc')
return pathlist
# -- Windows support functions --
def _get_win_folder_from_registry(csidl_name):
"""
This is a fallback technique at best. I'm not sure if using the
registry for this guarantees us the correct answer for all CSIDL_*
names.
"""
import _winreg
shell_folder_name = {
"CSIDL_APPDATA": "AppData",
"CSIDL_COMMON_APPDATA": "Common AppData",
"CSIDL_LOCAL_APPDATA": "Local AppData",
}[csidl_name]
key = _winreg.OpenKey(
_winreg.HKEY_CURRENT_USER,
r"Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders"
)
directory, _type = _winreg.QueryValueEx(key, shell_folder_name)
return directory
def _get_win_folder_with_ctypes(csidl_name):
csidl_const = {
"CSIDL_APPDATA": 26,
"CSIDL_COMMON_APPDATA": 35,
"CSIDL_LOCAL_APPDATA": 28,
}[csidl_name]
buf = ctypes.create_unicode_buffer(1024)
ctypes.windll.shell32.SHGetFolderPathW(None, csidl_const, None, 0, buf)
# Downgrade to short path name if have highbit chars. See
# <http://bugs.activestate.com/show_bug.cgi?id=85099>.
has_high_char = False
for c in buf:
if ord(c) > 255:
has_high_char = True
break
if has_high_char:
buf2 = ctypes.create_unicode_buffer(1024)
if ctypes.windll.kernel32.GetShortPathNameW(buf.value, buf2, 1024):
buf = buf2
return buf.value
if WINDOWS:
try:
import ctypes
_get_win_folder = _get_win_folder_with_ctypes
except ImportError:
_get_win_folder = _get_win_folder_from_registry
| mit |
morrna/flailing-with-flask | lib/flask/_compat.py | 783 | 2164 | # -*- coding: utf-8 -*-
"""
flask._compat
~~~~~~~~~~~~~
Some py2/py3 compatibility support based on a stripped down
version of six so we don't have to depend on a specific version
of it.
:copyright: (c) 2013 by Armin Ronacher.
:license: BSD, see LICENSE for more details.
"""
import sys
PY2 = sys.version_info[0] == 2
_identity = lambda x: x
if not PY2:
text_type = str
string_types = (str,)
integer_types = (int, )
iterkeys = lambda d: iter(d.keys())
itervalues = lambda d: iter(d.values())
iteritems = lambda d: iter(d.items())
from io import StringIO
def reraise(tp, value, tb=None):
if value.__traceback__ is not tb:
raise value.with_traceback(tb)
raise value
implements_to_string = _identity
else:
text_type = unicode
string_types = (str, unicode)
integer_types = (int, long)
iterkeys = lambda d: d.iterkeys()
itervalues = lambda d: d.itervalues()
iteritems = lambda d: d.iteritems()
from cStringIO import StringIO
exec('def reraise(tp, value, tb=None):\n raise tp, value, tb')
def implements_to_string(cls):
cls.__unicode__ = cls.__str__
cls.__str__ = lambda x: x.__unicode__().encode('utf-8')
return cls
def with_metaclass(meta, *bases):
# This requires a bit of explanation: the basic idea is to make a
# dummy metaclass for one level of class instantiation that replaces
# itself with the actual metaclass. Because of internal type checks
# we also need to make sure that we downgrade the custom metaclass
# for one level to something closer to type (that's why __call__ and
# __init__ comes back from type etc.).
#
# This has the advantage over six.with_metaclass in that it does not
# introduce dummy classes into the final MRO.
class metaclass(meta):
__call__ = type.__call__
__init__ = type.__init__
def __new__(cls, name, this_bases, d):
if this_bases is None:
return type.__new__(cls, name, (), d)
return meta(name, bases, d)
return metaclass('temporary_class', None, {})
| apache-2.0 |
OpenSourcePolicyCenter/PolicyBrain | copy_static.py | 2 | 1962 | from __future__ import print_function
# python manage.py dumpdata flatblocks --output flatblocks_heroku.json
from boto.s3.connection import S3Connection
from boto.s3.key import Key
import os
AWS_KEY_ID = os.environ['AWS_KEY_ID']
AWS_SECRET_ID = os.environ['AWS_SECRET_ID']
AWS_STORAGE_BUCKET_NAME = os.environ['AWS_STORAGE_BUCKET_NAME']
aws_connection = S3Connection(AWS_KEY_ID, AWS_SECRET_ID)
bucket = aws_connection.get_bucket(AWS_STORAGE_BUCKET_NAME)
k = Key(bucket)
content_type = {"css": "text/css",
"js": "application/javascript",
"gif": "image/gif",
"png": "image/png",
"jpg": "image/jpeg",
"svg": "image/svg+xml",
"txt": "text/plain",
"ttf": "application/x-font-ttf",
"woff": "application/x-font-woff",
"woff2": "application/octet-stream",
"scss": "application/octet-stream",
"eot": "application/vnd.ms-fontobject",
"swf": "application/application/x-shockwave-flash",
"less": "application/octet-stream"}
for root, dirs, files in os.walk("."):
for f in files:
if f.endswith("py"):
continue
if (f.endswith(".css") or f.endswith(".js") or
f.endswith("png") or f.endswith("jpg")):
full_path = os.path.join(root, f)[2:]
bucket_path = full_path
print(bucket_path)
ext = f[f.rfind('.') + 1:]
print(content_type[ext])
print(os.path.join(root, f))
k = Key(bucket)
k.key = bucket_path
if f.endswith("png") or f.endswith("jpg"):
headers = {'Content-Type': content_type[ext]}
else:
headers = {'Content-Type': content_type[ext],
'Content-Encoding': 'gzip'}
k.set_contents_from_filename(full_path, headers=headers)
| mit |
fin/froide | froide/foirequest/south_migrations/0031_auto__del_field_foirequest_resolution.py | 6 | 22299 | # -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
from froide.helper.auth_migration_util import USER_DB_NAME
APP_MODEL, APP_MODEL_NAME = 'account.User', 'account.user'
class Migration(SchemaMigration):
def forwards(self, orm):
# Deleting field 'FoiRequest.resolution'
db.delete_column(u'foirequest_foirequest', 'resolution')
def backwards(self, orm):
# Adding field 'FoiRequest.resolution'
db.add_column(u'foirequest_foirequest', 'resolution',
self.gf('django.db.models.fields.TextField')(null=True, blank=True),
keep_default=False)
models = {
u'auth.group': {
'Meta': {'object_name': 'Group'},
u'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': u"orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'})
},
u'auth.permission': {
'Meta': {'ordering': "(u'content_type__app_label', u'content_type__model', u'codename')", 'unique_together': "((u'content_type', u'codename'),)", 'object_name': 'Permission'},
'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['contenttypes.ContentType']"}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '50'})
},
APP_MODEL_NAME: {
'Meta': {'object_name': 'User', 'db_table': "'%s'" % USER_DB_NAME},
'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': u"orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}),
u'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': u"orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}),
'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'})
},
u'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'}),
u'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'})
},
u'foirequest.deferredmessage': {
'Meta': {'ordering': "('timestamp',)", 'object_name': 'DeferredMessage'},
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'mail': ('django.db.models.fields.TextField', [], {'blank': 'True'}),
'recipient': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}),
'request': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['foirequest.FoiRequest']", 'null': 'True', 'blank': 'True'}),
'timestamp': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'})
},
u'foirequest.foiattachment': {
'Meta': {'ordering': "('name',)", 'object_name': 'FoiAttachment'},
'approved': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'belongs_to': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['foirequest.FoiMessage']", 'null': 'True'}),
'can_approve': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'converted': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'original_set'", 'null': 'True', 'on_delete': 'models.SET_NULL', 'to': u"orm['foirequest.FoiAttachment']"}),
'file': ('django.db.models.fields.files.FileField', [], {'max_length': '255'}),
'filetype': ('django.db.models.fields.CharField', [], {'max_length': '100', 'blank': 'True'}),
'format': ('django.db.models.fields.CharField', [], {'max_length': '100', 'blank': 'True'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'is_converted': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'is_redacted': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'redacted': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'unredacted_set'", 'null': 'True', 'on_delete': 'models.SET_NULL', 'to': u"orm['foirequest.FoiAttachment']"}),
'size': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'})
},
u'foirequest.foievent': {
'Meta': {'ordering': "('-timestamp',)", 'object_name': 'FoiEvent'},
'context_json': ('django.db.models.fields.TextField', [], {}),
'event_name': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'public': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'public_body': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['publicbody.PublicBody']", 'null': 'True', 'on_delete': 'models.SET_NULL', 'blank': 'True'}),
'request': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['foirequest.FoiRequest']"}),
'timestamp': ('django.db.models.fields.DateTimeField', [], {}),
'user': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['%s']" % APP_MODEL, 'null': 'True', 'on_delete': 'models.SET_NULL', 'blank': 'True'})
},
u'foirequest.foimessage': {
'Meta': {'ordering': "('timestamp',)", 'object_name': 'FoiMessage'},
'content_hidden': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'html': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'is_escalation': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'is_postal': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'is_response': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'not_publishable': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'original': ('django.db.models.fields.TextField', [], {'blank': 'True'}),
'plaintext': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),
'plaintext_redacted': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),
'recipient': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}),
'recipient_email': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}),
'recipient_public_body': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'received_messages'", 'null': 'True', 'on_delete': 'models.SET_NULL', 'to': u"orm['publicbody.PublicBody']"}),
'redacted': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'request': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['foirequest.FoiRequest']"}),
'sender_email': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}),
'sender_name': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}),
'sender_public_body': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'send_messages'", 'null': 'True', 'on_delete': 'models.SET_NULL', 'to': u"orm['publicbody.PublicBody']"}),
'sender_user': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['%s']" % APP_MODEL, 'null': 'True', 'on_delete': 'models.SET_NULL', 'blank': 'True'}),
'sent': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'status': ('django.db.models.fields.CharField', [], {'default': 'None', 'max_length': '50', 'null': 'True', 'blank': 'True'}),
'subject': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}),
'subject_redacted': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}),
'timestamp': ('django.db.models.fields.DateTimeField', [], {'blank': 'True'})
},
u'foirequest.foirequest': {
'Meta': {'ordering': "('last_message',)", 'object_name': 'FoiRequest'},
'checked': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'costs': ('django.db.models.fields.FloatField', [], {'default': '0.0'}),
'description': ('django.db.models.fields.TextField', [], {'blank': 'True'}),
'due_date': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}),
'first_message': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'is_foi': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'jurisdiction': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['publicbody.Jurisdiction']", 'null': 'True', 'on_delete': 'models.SET_NULL'}),
'last_message': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}),
'law': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['publicbody.FoiLaw']", 'null': 'True', 'on_delete': 'models.SET_NULL', 'blank': 'True'}),
'public': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'public_body': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['publicbody.PublicBody']", 'null': 'True', 'on_delete': 'models.SET_NULL', 'blank': 'True'}),
'refusal_reason': ('django.db.models.fields.CharField', [], {'max_length': '1024', 'blank': 'True'}),
'resolved_on': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}),
'same_as': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['foirequest.FoiRequest']", 'null': 'True', 'on_delete': 'models.SET_NULL', 'blank': 'True'}),
'same_as_count': ('django.db.models.fields.IntegerField', [], {'default': '0'}),
'secret': ('django.db.models.fields.CharField', [], {'max_length': '100', 'blank': 'True'}),
'secret_address': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '255', 'db_index': 'True'}),
'site': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['sites.Site']", 'null': 'True', 'on_delete': 'models.SET_NULL'}),
'slug': ('django.db.models.fields.SlugField', [], {'unique': 'True', 'max_length': '255'}),
'status': ('django.db.models.fields.CharField', [], {'max_length': '50'}),
'summary': ('django.db.models.fields.TextField', [], {'blank': 'True'}),
'title': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'user': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['%s']" % APP_MODEL, 'null': 'True', 'on_delete': 'models.SET_NULL'}),
'visibility': ('django.db.models.fields.SmallIntegerField', [], {'default': '0'})
},
u'foirequest.publicbodysuggestion': {
'Meta': {'ordering': "('timestamp',)", 'object_name': 'PublicBodySuggestion'},
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'public_body': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['publicbody.PublicBody']"}),
'reason': ('django.db.models.fields.TextField', [], {'default': "''", 'blank': 'True'}),
'request': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['foirequest.FoiRequest']"}),
'timestamp': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
'user': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['%s']" % APP_MODEL, 'null': 'True', 'on_delete': 'models.SET_NULL'})
},
u'foirequest.taggedfoirequest': {
'Meta': {'object_name': 'TaggedFoiRequest'},
'content_object': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['foirequest.FoiRequest']"}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'tag': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'foirequest_taggedfoirequest_items'", 'to': u"orm['taggit.Tag']"})
},
u'publicbody.foilaw': {
'Meta': {'object_name': 'FoiLaw'},
'combined': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['publicbody.FoiLaw']", 'symmetrical': 'False', 'blank': 'True'}),
'created': ('django.db.models.fields.DateField', [], {'null': 'True', 'blank': 'True'}),
'description': ('django.db.models.fields.TextField', [], {'blank': 'True'}),
'email_only': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'jurisdiction': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['publicbody.Jurisdiction']", 'null': 'True', 'on_delete': 'models.SET_NULL', 'blank': 'True'}),
'letter_end': ('django.db.models.fields.TextField', [], {'blank': 'True'}),
'letter_start': ('django.db.models.fields.TextField', [], {'blank': 'True'}),
'long_description': ('django.db.models.fields.TextField', [], {'blank': 'True'}),
'max_response_time': ('django.db.models.fields.IntegerField', [], {'default': '30', 'null': 'True', 'blank': 'True'}),
'max_response_time_unit': ('django.db.models.fields.CharField', [], {'default': "'day'", 'max_length': '32', 'blank': 'True'}),
'mediator': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'mediating_laws'", 'on_delete': 'models.SET_NULL', 'default': 'None', 'to': u"orm['publicbody.PublicBody']", 'blank': 'True', 'null': 'True'}),
'meta': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'priority': ('django.db.models.fields.SmallIntegerField', [], {'default': '3'}),
'refusal_reasons': ('django.db.models.fields.TextField', [], {'blank': 'True'}),
'request_note': ('django.db.models.fields.TextField', [], {'blank': 'True'}),
'site': ('django.db.models.fields.related.ForeignKey', [], {'default': '1', 'to': u"orm['sites.Site']", 'null': 'True', 'on_delete': 'models.SET_NULL'}),
'slug': ('django.db.models.fields.SlugField', [], {'max_length': '255'}),
'updated': ('django.db.models.fields.DateField', [], {'null': 'True', 'blank': 'True'}),
'url': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'})
},
u'publicbody.jurisdiction': {
'Meta': {'object_name': 'Jurisdiction'},
'description': ('django.db.models.fields.TextField', [], {'blank': 'True'}),
'hidden': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'rank': ('django.db.models.fields.SmallIntegerField', [], {'default': '1'}),
'slug': ('django.db.models.fields.SlugField', [], {'max_length': '255'})
},
u'publicbody.publicbody': {
'Meta': {'ordering': "('name',)", 'object_name': 'PublicBody'},
'_created_by': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'public_body_creators'", 'on_delete': 'models.SET_NULL', 'default': '1', 'to': u"orm['%s']" % APP_MODEL, 'blank': 'True', 'null': 'True'}),
'_updated_by': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'public_body_updaters'", 'on_delete': 'models.SET_NULL', 'default': '1', 'to': u"orm['%s']" % APP_MODEL, 'blank': 'True', 'null': 'True'}),
'address': ('django.db.models.fields.TextField', [], {'blank': 'True'}),
'classification': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}),
'classification_slug': ('django.db.models.fields.SlugField', [], {'max_length': '255'}),
'confirmed': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'contact': ('django.db.models.fields.TextField', [], {'blank': 'True'}),
'depth': ('django.db.models.fields.SmallIntegerField', [], {'default': '0'}),
'description': ('django.db.models.fields.TextField', [], {'blank': 'True'}),
'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'null': 'True', 'blank': 'True'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'jurisdiction': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['publicbody.Jurisdiction']", 'null': 'True', 'on_delete': 'models.SET_NULL', 'blank': 'True'}),
'laws': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['publicbody.FoiLaw']", 'symmetrical': 'False'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'number_of_requests': ('django.db.models.fields.IntegerField', [], {'default': '0'}),
'other_names': ('django.db.models.fields.TextField', [], {'default': "''", 'blank': 'True'}),
'parent': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'children'", 'on_delete': 'models.SET_NULL', 'default': 'None', 'to': u"orm['publicbody.PublicBody']", 'blank': 'True', 'null': 'True'}),
'request_note': ('django.db.models.fields.TextField', [], {'blank': 'True'}),
'root': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'descendants'", 'on_delete': 'models.SET_NULL', 'default': 'None', 'to': u"orm['publicbody.PublicBody']", 'blank': 'True', 'null': 'True'}),
'site': ('django.db.models.fields.related.ForeignKey', [], {'default': '1', 'to': u"orm['sites.Site']", 'null': 'True', 'on_delete': 'models.SET_NULL'}),
'slug': ('django.db.models.fields.SlugField', [], {'max_length': '255'}),
'topic': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['publicbody.PublicBodyTopic']", 'null': 'True', 'on_delete': 'models.SET_NULL'}),
'url': ('django.db.models.fields.URLField', [], {'max_length': '500', 'null': 'True', 'blank': 'True'}),
'website_dump': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'})
},
u'publicbody.publicbodytopic': {
'Meta': {'object_name': 'PublicBodyTopic'},
'count': ('django.db.models.fields.IntegerField', [], {'default': '0'}),
'description': ('django.db.models.fields.TextField', [], {'blank': 'True'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'rank': ('django.db.models.fields.IntegerField', [], {'default': '0'}),
'slug': ('django.db.models.fields.SlugField', [], {'max_length': '255'})
},
u'sites.site': {
'Meta': {'ordering': "('domain',)", 'object_name': 'Site', 'db_table': "'django_site'"},
'domain': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '50'})
},
u'taggit.tag': {
'Meta': {'object_name': 'Tag'},
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'slug': ('django.db.models.fields.SlugField', [], {'unique': 'True', 'max_length': '100'})
}
}
complete_apps = ['foirequest'] | mit |
seem-sky/kbengine | kbe/res/scripts/common/Lib/lib2to3/fixes/fix_idioms.py | 203 | 4876 | """Adjust some old Python 2 idioms to their modern counterparts.
* Change some type comparisons to isinstance() calls:
type(x) == T -> isinstance(x, T)
type(x) is T -> isinstance(x, T)
type(x) != T -> not isinstance(x, T)
type(x) is not T -> not isinstance(x, T)
* Change "while 1:" into "while True:".
* Change both
v = list(EXPR)
v.sort()
foo(v)
and the more general
v = EXPR
v.sort()
foo(v)
into
v = sorted(EXPR)
foo(v)
"""
# Author: Jacques Frechet, Collin Winter
# Local imports
from .. import fixer_base
from ..fixer_util import Call, Comma, Name, Node, BlankLine, syms
CMP = "(n='!=' | '==' | 'is' | n=comp_op< 'is' 'not' >)"
TYPE = "power< 'type' trailer< '(' x=any ')' > >"
class FixIdioms(fixer_base.BaseFix):
explicit = True # The user must ask for this fixer
PATTERN = r"""
isinstance=comparison< %s %s T=any >
|
isinstance=comparison< T=any %s %s >
|
while_stmt< 'while' while='1' ':' any+ >
|
sorted=any<
any*
simple_stmt<
expr_stmt< id1=any '='
power< list='list' trailer< '(' (not arglist<any+>) any ')' > >
>
'\n'
>
sort=
simple_stmt<
power< id2=any
trailer< '.' 'sort' > trailer< '(' ')' >
>
'\n'
>
next=any*
>
|
sorted=any<
any*
simple_stmt< expr_stmt< id1=any '=' expr=any > '\n' >
sort=
simple_stmt<
power< id2=any
trailer< '.' 'sort' > trailer< '(' ')' >
>
'\n'
>
next=any*
>
""" % (TYPE, CMP, CMP, TYPE)
def match(self, node):
r = super(FixIdioms, self).match(node)
# If we've matched one of the sort/sorted subpatterns above, we
# want to reject matches where the initial assignment and the
# subsequent .sort() call involve different identifiers.
if r and "sorted" in r:
if r["id1"] == r["id2"]:
return r
return None
return r
def transform(self, node, results):
if "isinstance" in results:
return self.transform_isinstance(node, results)
elif "while" in results:
return self.transform_while(node, results)
elif "sorted" in results:
return self.transform_sort(node, results)
else:
raise RuntimeError("Invalid match")
def transform_isinstance(self, node, results):
x = results["x"].clone() # The thing inside of type()
T = results["T"].clone() # The type being compared against
x.prefix = ""
T.prefix = " "
test = Call(Name("isinstance"), [x, Comma(), T])
if "n" in results:
test.prefix = " "
test = Node(syms.not_test, [Name("not"), test])
test.prefix = node.prefix
return test
def transform_while(self, node, results):
one = results["while"]
one.replace(Name("True", prefix=one.prefix))
def transform_sort(self, node, results):
sort_stmt = results["sort"]
next_stmt = results["next"]
list_call = results.get("list")
simple_expr = results.get("expr")
if list_call:
list_call.replace(Name("sorted", prefix=list_call.prefix))
elif simple_expr:
new = simple_expr.clone()
new.prefix = ""
simple_expr.replace(Call(Name("sorted"), [new],
prefix=simple_expr.prefix))
else:
raise RuntimeError("should not have reached here")
sort_stmt.remove()
btwn = sort_stmt.prefix
# Keep any prefix lines between the sort_stmt and the list_call and
# shove them right after the sorted() call.
if "\n" in btwn:
if next_stmt:
# The new prefix should be everything from the sort_stmt's
# prefix up to the last newline, then the old prefix after a new
# line.
prefix_lines = (btwn.rpartition("\n")[0], next_stmt[0].prefix)
next_stmt[0].prefix = "\n".join(prefix_lines)
else:
assert list_call.parent
assert list_call.next_sibling is None
# Put a blank line after list_call and set its prefix.
end_line = BlankLine()
list_call.parent.append_child(end_line)
assert list_call.next_sibling is end_line
# The new prefix should be everything up to the first new line
# of sort_stmt's prefix.
end_line.prefix = btwn.rpartition("\n")[0]
| lgpl-3.0 |
kiwicopple/MyMDb | venv/Lib/encodings/cp874.py | 593 | 12851 | """ Python Character Mapping Codec cp874 generated from 'MAPPINGS/VENDORS/MICSFT/WINDOWS/CP874.TXT' with gencodec.py.
"""#"
import codecs
### Codec APIs
class Codec(codecs.Codec):
def encode(self,input,errors='strict'):
return codecs.charmap_encode(input,errors,encoding_table)
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_table)[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='cp874',
encode=Codec().encode,
decode=Codec().decode,
incrementalencoder=IncrementalEncoder,
incrementaldecoder=IncrementalDecoder,
streamreader=StreamReader,
streamwriter=StreamWriter,
)
### Decoding Table
decoding_table = (
u'\x00' # 0x00 -> NULL
u'\x01' # 0x01 -> START OF HEADING
u'\x02' # 0x02 -> START OF TEXT
u'\x03' # 0x03 -> END OF TEXT
u'\x04' # 0x04 -> END OF TRANSMISSION
u'\x05' # 0x05 -> ENQUIRY
u'\x06' # 0x06 -> ACKNOWLEDGE
u'\x07' # 0x07 -> BELL
u'\x08' # 0x08 -> BACKSPACE
u'\t' # 0x09 -> HORIZONTAL TABULATION
u'\n' # 0x0A -> LINE FEED
u'\x0b' # 0x0B -> VERTICAL TABULATION
u'\x0c' # 0x0C -> FORM FEED
u'\r' # 0x0D -> CARRIAGE RETURN
u'\x0e' # 0x0E -> SHIFT OUT
u'\x0f' # 0x0F -> SHIFT IN
u'\x10' # 0x10 -> DATA LINK ESCAPE
u'\x11' # 0x11 -> DEVICE CONTROL ONE
u'\x12' # 0x12 -> DEVICE CONTROL TWO
u'\x13' # 0x13 -> DEVICE CONTROL THREE
u'\x14' # 0x14 -> DEVICE CONTROL FOUR
u'\x15' # 0x15 -> NEGATIVE ACKNOWLEDGE
u'\x16' # 0x16 -> SYNCHRONOUS IDLE
u'\x17' # 0x17 -> END OF TRANSMISSION BLOCK
u'\x18' # 0x18 -> CANCEL
u'\x19' # 0x19 -> END OF MEDIUM
u'\x1a' # 0x1A -> SUBSTITUTE
u'\x1b' # 0x1B -> ESCAPE
u'\x1c' # 0x1C -> FILE SEPARATOR
u'\x1d' # 0x1D -> GROUP SEPARATOR
u'\x1e' # 0x1E -> RECORD SEPARATOR
u'\x1f' # 0x1F -> UNIT SEPARATOR
u' ' # 0x20 -> SPACE
u'!' # 0x21 -> EXCLAMATION MARK
u'"' # 0x22 -> QUOTATION MARK
u'#' # 0x23 -> NUMBER SIGN
u'$' # 0x24 -> DOLLAR SIGN
u'%' # 0x25 -> PERCENT SIGN
u'&' # 0x26 -> AMPERSAND
u"'" # 0x27 -> APOSTROPHE
u'(' # 0x28 -> LEFT PARENTHESIS
u')' # 0x29 -> RIGHT PARENTHESIS
u'*' # 0x2A -> ASTERISK
u'+' # 0x2B -> PLUS SIGN
u',' # 0x2C -> COMMA
u'-' # 0x2D -> HYPHEN-MINUS
u'.' # 0x2E -> FULL STOP
u'/' # 0x2F -> SOLIDUS
u'0' # 0x30 -> DIGIT ZERO
u'1' # 0x31 -> DIGIT ONE
u'2' # 0x32 -> DIGIT TWO
u'3' # 0x33 -> DIGIT THREE
u'4' # 0x34 -> DIGIT FOUR
u'5' # 0x35 -> DIGIT FIVE
u'6' # 0x36 -> DIGIT SIX
u'7' # 0x37 -> DIGIT SEVEN
u'8' # 0x38 -> DIGIT EIGHT
u'9' # 0x39 -> DIGIT NINE
u':' # 0x3A -> COLON
u';' # 0x3B -> SEMICOLON
u'<' # 0x3C -> LESS-THAN SIGN
u'=' # 0x3D -> EQUALS SIGN
u'>' # 0x3E -> GREATER-THAN SIGN
u'?' # 0x3F -> QUESTION MARK
u'@' # 0x40 -> COMMERCIAL AT
u'A' # 0x41 -> LATIN CAPITAL LETTER A
u'B' # 0x42 -> LATIN CAPITAL LETTER B
u'C' # 0x43 -> LATIN CAPITAL LETTER C
u'D' # 0x44 -> LATIN CAPITAL LETTER D
u'E' # 0x45 -> LATIN CAPITAL LETTER E
u'F' # 0x46 -> LATIN CAPITAL LETTER F
u'G' # 0x47 -> LATIN CAPITAL LETTER G
u'H' # 0x48 -> LATIN CAPITAL LETTER H
u'I' # 0x49 -> LATIN CAPITAL LETTER I
u'J' # 0x4A -> LATIN CAPITAL LETTER J
u'K' # 0x4B -> LATIN CAPITAL LETTER K
u'L' # 0x4C -> LATIN CAPITAL LETTER L
u'M' # 0x4D -> LATIN CAPITAL LETTER M
u'N' # 0x4E -> LATIN CAPITAL LETTER N
u'O' # 0x4F -> LATIN CAPITAL LETTER O
u'P' # 0x50 -> LATIN CAPITAL LETTER P
u'Q' # 0x51 -> LATIN CAPITAL LETTER Q
u'R' # 0x52 -> LATIN CAPITAL LETTER R
u'S' # 0x53 -> LATIN CAPITAL LETTER S
u'T' # 0x54 -> LATIN CAPITAL LETTER T
u'U' # 0x55 -> LATIN CAPITAL LETTER U
u'V' # 0x56 -> LATIN CAPITAL LETTER V
u'W' # 0x57 -> LATIN CAPITAL LETTER W
u'X' # 0x58 -> LATIN CAPITAL LETTER X
u'Y' # 0x59 -> LATIN CAPITAL LETTER Y
u'Z' # 0x5A -> LATIN CAPITAL LETTER Z
u'[' # 0x5B -> LEFT SQUARE BRACKET
u'\\' # 0x5C -> REVERSE SOLIDUS
u']' # 0x5D -> RIGHT SQUARE BRACKET
u'^' # 0x5E -> CIRCUMFLEX ACCENT
u'_' # 0x5F -> LOW LINE
u'`' # 0x60 -> GRAVE ACCENT
u'a' # 0x61 -> LATIN SMALL LETTER A
u'b' # 0x62 -> LATIN SMALL LETTER B
u'c' # 0x63 -> LATIN SMALL LETTER C
u'd' # 0x64 -> LATIN SMALL LETTER D
u'e' # 0x65 -> LATIN SMALL LETTER E
u'f' # 0x66 -> LATIN SMALL LETTER F
u'g' # 0x67 -> LATIN SMALL LETTER G
u'h' # 0x68 -> LATIN SMALL LETTER H
u'i' # 0x69 -> LATIN SMALL LETTER I
u'j' # 0x6A -> LATIN SMALL LETTER J
u'k' # 0x6B -> LATIN SMALL LETTER K
u'l' # 0x6C -> LATIN SMALL LETTER L
u'm' # 0x6D -> LATIN SMALL LETTER M
u'n' # 0x6E -> LATIN SMALL LETTER N
u'o' # 0x6F -> LATIN SMALL LETTER O
u'p' # 0x70 -> LATIN SMALL LETTER P
u'q' # 0x71 -> LATIN SMALL LETTER Q
u'r' # 0x72 -> LATIN SMALL LETTER R
u's' # 0x73 -> LATIN SMALL LETTER S
u't' # 0x74 -> LATIN SMALL LETTER T
u'u' # 0x75 -> LATIN SMALL LETTER U
u'v' # 0x76 -> LATIN SMALL LETTER V
u'w' # 0x77 -> LATIN SMALL LETTER W
u'x' # 0x78 -> LATIN SMALL LETTER X
u'y' # 0x79 -> LATIN SMALL LETTER Y
u'z' # 0x7A -> LATIN SMALL LETTER Z
u'{' # 0x7B -> LEFT CURLY BRACKET
u'|' # 0x7C -> VERTICAL LINE
u'}' # 0x7D -> RIGHT CURLY BRACKET
u'~' # 0x7E -> TILDE
u'\x7f' # 0x7F -> DELETE
u'\u20ac' # 0x80 -> EURO SIGN
u'\ufffe' # 0x81 -> UNDEFINED
u'\ufffe' # 0x82 -> UNDEFINED
u'\ufffe' # 0x83 -> UNDEFINED
u'\ufffe' # 0x84 -> UNDEFINED
u'\u2026' # 0x85 -> HORIZONTAL ELLIPSIS
u'\ufffe' # 0x86 -> UNDEFINED
u'\ufffe' # 0x87 -> UNDEFINED
u'\ufffe' # 0x88 -> UNDEFINED
u'\ufffe' # 0x89 -> UNDEFINED
u'\ufffe' # 0x8A -> UNDEFINED
u'\ufffe' # 0x8B -> UNDEFINED
u'\ufffe' # 0x8C -> UNDEFINED
u'\ufffe' # 0x8D -> UNDEFINED
u'\ufffe' # 0x8E -> UNDEFINED
u'\ufffe' # 0x8F -> UNDEFINED
u'\ufffe' # 0x90 -> UNDEFINED
u'\u2018' # 0x91 -> LEFT SINGLE QUOTATION MARK
u'\u2019' # 0x92 -> RIGHT SINGLE QUOTATION MARK
u'\u201c' # 0x93 -> LEFT DOUBLE QUOTATION MARK
u'\u201d' # 0x94 -> RIGHT DOUBLE QUOTATION MARK
u'\u2022' # 0x95 -> BULLET
u'\u2013' # 0x96 -> EN DASH
u'\u2014' # 0x97 -> EM DASH
u'\ufffe' # 0x98 -> UNDEFINED
u'\ufffe' # 0x99 -> UNDEFINED
u'\ufffe' # 0x9A -> UNDEFINED
u'\ufffe' # 0x9B -> UNDEFINED
u'\ufffe' # 0x9C -> UNDEFINED
u'\ufffe' # 0x9D -> UNDEFINED
u'\ufffe' # 0x9E -> UNDEFINED
u'\ufffe' # 0x9F -> UNDEFINED
u'\xa0' # 0xA0 -> NO-BREAK SPACE
u'\u0e01' # 0xA1 -> THAI CHARACTER KO KAI
u'\u0e02' # 0xA2 -> THAI CHARACTER KHO KHAI
u'\u0e03' # 0xA3 -> THAI CHARACTER KHO KHUAT
u'\u0e04' # 0xA4 -> THAI CHARACTER KHO KHWAI
u'\u0e05' # 0xA5 -> THAI CHARACTER KHO KHON
u'\u0e06' # 0xA6 -> THAI CHARACTER KHO RAKHANG
u'\u0e07' # 0xA7 -> THAI CHARACTER NGO NGU
u'\u0e08' # 0xA8 -> THAI CHARACTER CHO CHAN
u'\u0e09' # 0xA9 -> THAI CHARACTER CHO CHING
u'\u0e0a' # 0xAA -> THAI CHARACTER CHO CHANG
u'\u0e0b' # 0xAB -> THAI CHARACTER SO SO
u'\u0e0c' # 0xAC -> THAI CHARACTER CHO CHOE
u'\u0e0d' # 0xAD -> THAI CHARACTER YO YING
u'\u0e0e' # 0xAE -> THAI CHARACTER DO CHADA
u'\u0e0f' # 0xAF -> THAI CHARACTER TO PATAK
u'\u0e10' # 0xB0 -> THAI CHARACTER THO THAN
u'\u0e11' # 0xB1 -> THAI CHARACTER THO NANGMONTHO
u'\u0e12' # 0xB2 -> THAI CHARACTER THO PHUTHAO
u'\u0e13' # 0xB3 -> THAI CHARACTER NO NEN
u'\u0e14' # 0xB4 -> THAI CHARACTER DO DEK
u'\u0e15' # 0xB5 -> THAI CHARACTER TO TAO
u'\u0e16' # 0xB6 -> THAI CHARACTER THO THUNG
u'\u0e17' # 0xB7 -> THAI CHARACTER THO THAHAN
u'\u0e18' # 0xB8 -> THAI CHARACTER THO THONG
u'\u0e19' # 0xB9 -> THAI CHARACTER NO NU
u'\u0e1a' # 0xBA -> THAI CHARACTER BO BAIMAI
u'\u0e1b' # 0xBB -> THAI CHARACTER PO PLA
u'\u0e1c' # 0xBC -> THAI CHARACTER PHO PHUNG
u'\u0e1d' # 0xBD -> THAI CHARACTER FO FA
u'\u0e1e' # 0xBE -> THAI CHARACTER PHO PHAN
u'\u0e1f' # 0xBF -> THAI CHARACTER FO FAN
u'\u0e20' # 0xC0 -> THAI CHARACTER PHO SAMPHAO
u'\u0e21' # 0xC1 -> THAI CHARACTER MO MA
u'\u0e22' # 0xC2 -> THAI CHARACTER YO YAK
u'\u0e23' # 0xC3 -> THAI CHARACTER RO RUA
u'\u0e24' # 0xC4 -> THAI CHARACTER RU
u'\u0e25' # 0xC5 -> THAI CHARACTER LO LING
u'\u0e26' # 0xC6 -> THAI CHARACTER LU
u'\u0e27' # 0xC7 -> THAI CHARACTER WO WAEN
u'\u0e28' # 0xC8 -> THAI CHARACTER SO SALA
u'\u0e29' # 0xC9 -> THAI CHARACTER SO RUSI
u'\u0e2a' # 0xCA -> THAI CHARACTER SO SUA
u'\u0e2b' # 0xCB -> THAI CHARACTER HO HIP
u'\u0e2c' # 0xCC -> THAI CHARACTER LO CHULA
u'\u0e2d' # 0xCD -> THAI CHARACTER O ANG
u'\u0e2e' # 0xCE -> THAI CHARACTER HO NOKHUK
u'\u0e2f' # 0xCF -> THAI CHARACTER PAIYANNOI
u'\u0e30' # 0xD0 -> THAI CHARACTER SARA A
u'\u0e31' # 0xD1 -> THAI CHARACTER MAI HAN-AKAT
u'\u0e32' # 0xD2 -> THAI CHARACTER SARA AA
u'\u0e33' # 0xD3 -> THAI CHARACTER SARA AM
u'\u0e34' # 0xD4 -> THAI CHARACTER SARA I
u'\u0e35' # 0xD5 -> THAI CHARACTER SARA II
u'\u0e36' # 0xD6 -> THAI CHARACTER SARA UE
u'\u0e37' # 0xD7 -> THAI CHARACTER SARA UEE
u'\u0e38' # 0xD8 -> THAI CHARACTER SARA U
u'\u0e39' # 0xD9 -> THAI CHARACTER SARA UU
u'\u0e3a' # 0xDA -> THAI CHARACTER PHINTHU
u'\ufffe' # 0xDB -> UNDEFINED
u'\ufffe' # 0xDC -> UNDEFINED
u'\ufffe' # 0xDD -> UNDEFINED
u'\ufffe' # 0xDE -> UNDEFINED
u'\u0e3f' # 0xDF -> THAI CURRENCY SYMBOL BAHT
u'\u0e40' # 0xE0 -> THAI CHARACTER SARA E
u'\u0e41' # 0xE1 -> THAI CHARACTER SARA AE
u'\u0e42' # 0xE2 -> THAI CHARACTER SARA O
u'\u0e43' # 0xE3 -> THAI CHARACTER SARA AI MAIMUAN
u'\u0e44' # 0xE4 -> THAI CHARACTER SARA AI MAIMALAI
u'\u0e45' # 0xE5 -> THAI CHARACTER LAKKHANGYAO
u'\u0e46' # 0xE6 -> THAI CHARACTER MAIYAMOK
u'\u0e47' # 0xE7 -> THAI CHARACTER MAITAIKHU
u'\u0e48' # 0xE8 -> THAI CHARACTER MAI EK
u'\u0e49' # 0xE9 -> THAI CHARACTER MAI THO
u'\u0e4a' # 0xEA -> THAI CHARACTER MAI TRI
u'\u0e4b' # 0xEB -> THAI CHARACTER MAI CHATTAWA
u'\u0e4c' # 0xEC -> THAI CHARACTER THANTHAKHAT
u'\u0e4d' # 0xED -> THAI CHARACTER NIKHAHIT
u'\u0e4e' # 0xEE -> THAI CHARACTER YAMAKKAN
u'\u0e4f' # 0xEF -> THAI CHARACTER FONGMAN
u'\u0e50' # 0xF0 -> THAI DIGIT ZERO
u'\u0e51' # 0xF1 -> THAI DIGIT ONE
u'\u0e52' # 0xF2 -> THAI DIGIT TWO
u'\u0e53' # 0xF3 -> THAI DIGIT THREE
u'\u0e54' # 0xF4 -> THAI DIGIT FOUR
u'\u0e55' # 0xF5 -> THAI DIGIT FIVE
u'\u0e56' # 0xF6 -> THAI DIGIT SIX
u'\u0e57' # 0xF7 -> THAI DIGIT SEVEN
u'\u0e58' # 0xF8 -> THAI DIGIT EIGHT
u'\u0e59' # 0xF9 -> THAI DIGIT NINE
u'\u0e5a' # 0xFA -> THAI CHARACTER ANGKHANKHU
u'\u0e5b' # 0xFB -> THAI CHARACTER KHOMUT
u'\ufffe' # 0xFC -> UNDEFINED
u'\ufffe' # 0xFD -> UNDEFINED
u'\ufffe' # 0xFE -> UNDEFINED
u'\ufffe' # 0xFF -> UNDEFINED
)
### Encoding table
encoding_table=codecs.charmap_build(decoding_table)
| mit |
Tridify/IfcOpenShell-New | test/run.py | 8 | 14052 | ###############################################################################
# #
# This file is part of IfcOpenShell. #
# #
# IfcOpenShell is free software: you can redistribute it and/or modify #
# it under the terms of the Lesser GNU General Public License as published by #
# the Free Software Foundation, either version 3.0 of the License, or #
# (at your option) any later version. #
# #
# IfcOpenShell 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 #
# Lesser GNU General Public License for more details. #
# #
# You should have received a copy of the Lesser GNU General Public License #
# along with this program. If not, see <http://www.gnu.org/licenses/>. #
# #
###############################################################################
###############################################################################
# #
# The IfcOpenShell test suite downloads IFC files that are publicely #
# available on the internet and uses Blender and IfcOpenShell to generate a #
# render of the parsed file. For the script to run, Blender needs to be #
# installed and added to PATH. #
# #
###############################################################################
import os
import sys
import shutil
import inspect
import subprocess
from zipfile import ZipFile
from urllib.request import urlretrieve
# Test whether Blender and IfcOpenShell are installed
if subprocess.call(['blender','-b','-P','bpy.py','TEST']) != 0:
print("[Error] Failed to launch Blender")
sys.exit(1)
else:
print("[Notice] Found Blender and IfcOpenShell on system")
# Global variables for keeping track of test cases
test_cases = []
failed = []
# Create the ouput directory
cwd = os.path.abspath(os.path.dirname(inspect.getfile(inspect.currentframe())))
os.chdir(cwd)
if not os.path.exists("output"): os.mkdir("output")
if not os.path.exists("input"): os.mkdir("input")
def extension(fn):
return os.path.splitext(fn)[-1].lower()
# Class to download extract and convert IFC files
class TestFile:
def __init__(self,fn,store_as=None):
global test_cases
self.fn = fn
self.store_as = store_as
self.failed = []
test_cases.append(self)
def __call__(self):
if self.fn.startswith("http://") or self.fn.startswith("ftp://"):
fn = self.store_as if self.store_as else self.fn.split("/")[-1]
if os.path.exists(os.path.join("input",fn)):
print ("[Notice] Already downloaded:",fn)
else:
print ("[Notice] Downloading:",fn)
urlretrieve(self.fn,os.path.join("input",fn))
self.fn = fn
if extension(self.fn) == '.zip':
print ("[Notice] Extracting:",self.fn)
zf = ZipFile(os.path.join("input",self.fn))
self.fn = [n for n in zf.namelist() if extension(n) == '.ifc' and not n.startswith('__') and not n.startswith('.')]
for fn in self.fn:
if not os.path.exists(os.path.join("input",fn)): zf.extract(fn,"input")
zf.close()
else: self.fn = [self.fn]
for fn in self.fn:
print ("[Notice] Rendering:",fn)
succes = subprocess.call(['blender','-b','-P','bpy.py','render',os.path.join("input",fn)]) == 0
if not succes: self.failed.append(fn)
return len(self.failed) == 0
def __str__(self): return "\n".join(self.failed) if len(self.failed) else ""
# Karlsruher Institut fuer Technologie
TestFile("http://iai-typo3.iai.fzk.de/www-extern-kit/fileadmin/download/download-vrsys/ADT-FZK-Haus-2005-2006.zip")
TestFile("http://iai-typo3.iai.fzk.de/www-extern-kit/fileadmin/download/download-vrsys/Nem-FZK-Haus-2x3.zip")
TestFile("http://iai-typo3.iai.fzk.de/www-extern-kit/fileadmin/download/download-vrsys/AC14-FZK-Haus.zip")
TestFile("http://iai-typo3.iai.fzk.de/www-extern-kit/fileadmin/download/download-vrsys/FZK-Haus-EliteCAD.zip")
TestFile("http://iai-typo3.iai.fzk.de/www-extern-kit/fileadmin/download/download-vrsys/FJK-Project-Final.zip")
TestFile("http://www.iai.fzk.de/www-extern-kit/fileadmin/download/download-vrsys/Bien-Zenker_Jasmin-Sun-AC14-V2-IFC.zip")
TestFile("http://www.iai.fzk.de/www-extern-kit/fileadmin/download/download-vrsys/ADT-Smiley-West-Project-14-10-2005.zip")
TestFile("http://www.iai.fzk.de/www-extern-kit/fileadmin/download/download-vrsys/Allplan-Smiley-West.zip")
TestFile("http://www.iai.fzk.de/www-extern-kit/fileadmin/download/download-vrsys/AC-11-Smiley-West-04-07-2007-IFC.zip")
TestFile("http://www.iai.fzk.de/www-extern-kit/fileadmin/download/download-vrsys/Allplan-2008-Institute-Var-2-IFC.zip")
TestFile("http://www.iai.fzk.de/www-extern-kit/fileadmin/download/download-vrsys/AC11-Institute-Var-2-IFC.zip")
TestFile("http://iai-typo3.iai.fzk.de/www-extern-kit/fileadmin/download/download-vrsys/PART02_Wilfer_200302_20070209_IFC.zip")
TestFile("http://iai-typo3.iai.fzk.de/www-extern-kit/fileadmin/download/download-vrsys/PART06_Kermi_200405_20070401_IFC.zip")
TestFile("http://iai-typo3.iai.fzk.de/www-extern-kit/fileadmin/download/download-vrsys/Ettenheim-GIS-05-11-2006_optimized.zip")
# Selvaag Gruppen
TestFile("ftp://ftp.dds.no/pub/ifc/Munkerud/Munkerud_hus6_BE.zip")
# Statsbygg
TestFile("ftp://ftp.dds.no/pub/ifc/HiTOS/2x3_HiTOS_EL_new.zip")
TestFile("ftp://ftp.dds.no/pub/ifc/HiTOS/2x3_HiTOS_HVAC_new.zip")
TestFile("ftp://ftp.dds.no/pub/ifc/HiTOS/HITOS_Architectural_2006-10-25.zip")
# Nemetschek Vectorworks
TestFile("http://download2cf.nemetschek.net/www_misc/bim/DCR-LOD_100.zip")
TestFile("http://download2cf.nemetschek.net/www_misc/bim/DCR-LOD_200.zip")
# Rather large:
# TestFile("http://download2cf.nemetschek.net/www_misc/bim/DCR-LOD_300.zip")
# Data Design Systems
TestFile("ftp://ftp.dds.no/pub/ifc/BardNa/Dds_BardNa.zip")
# Common Building Information Model Files
TestFile("http://projects.buildingsmartalliance.org/files/?artifact_id=4278","2011-09-14-Duplex-IFC.zip")
TestFile("http://projects.buildingsmartalliance.org/files/?artifact_id=4284","2011-09-14-Office-IFC.zip")
# Rather large:
# TestFile("http://projects.buildingsmartalliance.org/files/?artifact_id=4289","2011-09-14-Clinic-IFC.zip")
# http://openifcmodel.cs.auckland.ac.nz IAI
TestFile("http://openifcmodel.cs.auckland.ac.nz/_models/0912101-01wall_layers_number_1.ifc")
TestFile("http://openifcmodel.cs.auckland.ac.nz/_models/0912101-02wall_opening_straight_ac_1.ifc")
TestFile("http://openifcmodel.cs.auckland.ac.nz/_models/0912101-03wall_recess_ben_1.ifc")
TestFile("http://openifcmodel.cs.auckland.ac.nz/_models/0912101-04wall_L-shape_all_1.ifc")
TestFile("http://openifcmodel.cs.auckland.ac.nz/_models/0912102-01beam_profile_basic_rev_1.ifc")
TestFile("http://openifcmodel.cs.auckland.ac.nz/_models/0912102-01beam_profile_para_ac_1.ifc")
TestFile("http://openifcmodel.cs.auckland.ac.nz/_models/0912102-02brep_beams_opening_ben_1.ifc")
TestFile("http://openifcmodel.cs.auckland.ac.nz/_models/0912102-02extruded_beam_open_tek_1.ifc")
TestFile("http://openifcmodel.cs.auckland.ac.nz/_models/0912103-01col_profile_clip_ben_1.ifc")
TestFile("http://openifcmodel.cs.auckland.ac.nz/_models/0912103-01columns_basic_all_1.ifc")
TestFile("http://openifcmodel.cs.auckland.ac.nz/_models/0912103-02col_brep_opening_ben_1.ifc")
TestFile("http://openifcmodel.cs.auckland.ac.nz/_models/0912103-02OpeningsInExtrudedColumns_rev_1.ifc")
TestFile("http://openifcmodel.cs.auckland.ac.nz/_models/0912104-01slab_profile_basic_ac_1.ifc")
TestFile("http://openifcmodel.cs.auckland.ac.nz/_models/0912104-03extruded_slab_openings_all_1.ifc")
TestFile("http://openifcmodel.cs.auckland.ac.nz/_models/0912104-04slab_recess_tek_1.ifc")
TestFile("http://openifcmodel.cs.auckland.ac.nz/_models/0912105-01doors_explicit_geom_all_1.ifc")
TestFile("http://openifcmodel.cs.auckland.ac.nz/_models/0912105-02DoorOperationsPlacementInsideWall_rev_1.ifc")
TestFile("http://openifcmodel.cs.auckland.ac.nz/_models/0912106-01window_brep_ac_1.ifc")
TestFile("http://openifcmodel.cs.auckland.ac.nz/_models/0912106-02windows_placement_inside_wall_all_1.ifc")
TestFile("http://openifcmodel.cs.auckland.ac.nz/_models/0912107-01stair_geometry_ben_1.ifc")
TestFile("http://openifcmodel.cs.auckland.ac.nz/_models/0912108-01ramp_geometry_ben_2.ifc")
TestFile("http://openifcmodel.cs.auckland.ac.nz/_models/0912108-01RampAsContainer_rev_1.ifc")
TestFile("http://openifcmodel.cs.auckland.ac.nz/_models/0912109-01railing_brep_ac_1.ifc")
TestFile("http://openifcmodel.cs.auckland.ac.nz/_models/0912109-01railing_extrusion_tek_1.ifc")
TestFile("http://openifcmodel.cs.auckland.ac.nz/_models/09121010-01RoofWithGeometry_rev_1.ifc")
TestFile("http://openifcmodel.cs.auckland.ac.nz/_models/09121010-02roof_with_openings_ben_1.ifc")
TestFile("http://openifcmodel.cs.auckland.ac.nz/_models/09121011curtain_wall_basic_rev_1.ifc")
TestFile("http://openifcmodel.cs.auckland.ac.nz/_models/09121012mem_profile_basic_tek_1.ifc")
TestFile("http://openifcmodel.cs.auckland.ac.nz/_models/09121013plate_steel_exam_tek_1.ifc")
TestFile("http://openifcmodel.cs.auckland.ac.nz/_models/09121014pile_basic_tek_1.ifc")
TestFile("http://openifcmodel.cs.auckland.ac.nz/_models/09121015footing_ac_1.ifc")
# http://openifcmodel.cs.auckland.ac.nz NIST
TestFile("http://openifcmodel.cs.auckland.ac.nz/_models/171210AISC_Sculpture_brep.ifc")
TestFile("http://openifcmodel.cs.auckland.ac.nz/_models/171210AISC_Sculpture_param.ifc")
TestFile("http://openifcmodel.cs.auckland.ac.nz/_models/171210analysis_brep.ifc")
TestFile("http://openifcmodel.cs.auckland.ac.nz/_models/171210analysis_param.ifc")
TestFile("http://openifcmodel.cs.auckland.ac.nz/_models/171210Bentley1_brep.ifc")
TestFile("http://openifcmodel.cs.auckland.ac.nz/_models/171210Bentley1_param.ifc")
TestFile("http://openifcmodel.cs.auckland.ac.nz/_models/171210CADstudio_brep.ifc")
TestFile("http://openifcmodel.cs.auckland.ac.nz/_models/171210cutouts_brep.ifc")
TestFile("http://openifcmodel.cs.auckland.ac.nz/_models/171210DesignData1_brep.ifc")
TestFile("http://openifcmodel.cs.auckland.ac.nz/_models/171210DesignData3_brep.ifc")
TestFile("http://openifcmodel.cs.auckland.ac.nz/_models/171210PlayersTheater_param.ifc")
TestFile("http://openifcmodel.cs.auckland.ac.nz/_models/171210profiles_brep.ifc")
TestFile("http://openifcmodel.cs.auckland.ac.nz/_models/171210profilescp1_brep.ifc")
TestFile("http://openifcmodel.cs.auckland.ac.nz/_models/171210sections_brep.ifc")
TestFile("http://openifcmodel.cs.auckland.ac.nz/_models/171210threebeams_brep.ifc")
TestFile("http://openifcmodel.cs.auckland.ac.nz/_models/171210TrainingStructure_brep.ifc")
TestFile("http://openifcmodel.cs.auckland.ac.nz/_models/171210eccentricity_physical.ifc")
# BIMserver
TestFile("http://bimserver.googlecode.com/svn/trunk/TestData/data/06-03-01_windows_in_curved_wall_vw.ifc")
TestFile("http://bimserver.googlecode.com/svn/trunk/TestData/data/4351.ifc")
TestFile("http://bimserver.googlecode.com/svn/trunk/TestData/data/AC9R1-Haus-G-H-Ver2-2x3.ifc")
TestFile("http://bimserver.googlecode.com/svn/trunk/TestData/data/AC90R1-niedriha-V2-2x3.ifc")
# File courtesey of Jon Mirtschin / Geometry Gym
TestFile("geometrygym_great_court_roof.ifc")
# File courtesey of Ryan Schultz / Opening Design / Studio Wikitecture
TestFile("revit2012_janesville_restaurant.zip")
# Walls cut by IfcPolygonalBoundedHalfSpaces from Revit 2011
TestFile("revit2011_wall1.ifc")
TestFile("revit2011_wall2.ifc")
# Objects from Autocad Architecture 2010
TestFile("acad2010_walls.ifc")
TestFile("acad2010_objects.ifc")
# Various half space configuration to test cutting tolerances
TestFile("ifcopenshell_halfspaces.ifc")
# Several IfcPolygonalBoundedHalfSpaces cutting a single solid
TestFile("revit2014_multiple_bounded_halfspaces.ifc")
# Several parameterized profile extrusions generated by one
# of the examples from the IfcOpenShell repository
TestFile("IfcCShapeProfileDef.ifc")
TestFile("IfcCircleProfileDef.ifc")
TestFile("IfcEllipseProfileDef.ifc")
TestFile("IfcIShapeProfileDef.ifc")
TestFile("IfcLShapeProfileDef.ifc")
TestFile("IfcRectangleProfileDef.ifc")
TestFile("IfcTShapeProfileDef.ifc")
TestFile("IfcTrapeziumProfileDef.ifc")
TestFile("IfcUShapeProfileDef.ifc")
TestFile("IfcZShapeProfileDef.ifc")
TestFile("IfcReinforcingBar.ifc")
TestFile("advanced_brep.ifc")
TestFile("basic_shape_Brep.ifc")
TestFile("basic_shape_CSG.ifc")
TestFile("basic_shape_SurfaceModel.ifc")
TestFile("basic_shape_SweptSolid.ifc")
TestFile("basic_shape_Tessellation.ifc")
TestFile("building_element_configuration_wall.ifc")
TestFile("building_service_element_air-terminal-type.ifc")
TestFile("building_service_element_air-terminal.ifc")
TestFile("construction_scheduling_task.ifc")
TestFile("mapped_shape_multiple.ifc")
TestFile("mapped_shape_representation.ifc")
TestFile("mapped_shape_transformation.ifc")
TestFile("standard_case_element_beam.ifc")
TestFile("structural_analysis_curve.ifc")
for test in test_cases:
succes = test()
if not succes:
failed.append(test)
if len(failed):
print("[Notice] Conversion failed for the following cases:")
for test in failed:
print (test)
else:
print("[Notice] All cases succeeded")
| gpl-3.0 |
lerrua/vim-bootstrap | lib/markupsafe/_native.py | 1243 | 1187 | # -*- coding: utf-8 -*-
"""
markupsafe._native
~~~~~~~~~~~~~~~~~~
Native Python implementation the C module is not compiled.
:copyright: (c) 2010 by Armin Ronacher.
:license: BSD, see LICENSE for more details.
"""
from markupsafe import Markup
from markupsafe._compat import text_type
def escape(s):
"""Convert the characters &, <, >, ' and " in string s to HTML-safe
sequences. Use this if you need to display text that might contain
such characters in HTML. Marks return value as markup string.
"""
if hasattr(s, '__html__'):
return s.__html__()
return Markup(text_type(s)
.replace('&', '&')
.replace('>', '>')
.replace('<', '<')
.replace("'", ''')
.replace('"', '"')
)
def escape_silent(s):
"""Like :func:`escape` but converts `None` into an empty
markup string.
"""
if s is None:
return Markup()
return escape(s)
def soft_unicode(s):
"""Make a string unicode if it isn't already. That way a markup
string is not converted back to unicode.
"""
if not isinstance(s, text_type):
s = text_type(s)
return s
| mit |
jojoanne/ex | basic/solution/wordcount.py | 211 | 3529 | #!/usr/bin/python -tt
# Copyright 2010 Google Inc.
# Licensed under the Apache License, Version 2.0
# http://www.apache.org/licenses/LICENSE-2.0
# Google's Python Class
# http://code.google.com/edu/languages/google-python-class/
"""Wordcount exercise
Google's Python class
The main() below is already defined and complete. It calls print_words()
and print_top() functions which you write.
1. For the --count flag, implement a print_words(filename) function that counts
how often each word appears in the text and prints:
word1 count1
word2 count2
...
Print the above list in order sorted by word (python will sort punctuation to
come before letters -- that's fine). Store all the words as lowercase,
so 'The' and 'the' count as the same word.
2. For the --topcount flag, implement a print_top(filename) which is similar
to print_words() but which prints just the top 20 most common words sorted
so the most common word is first, then the next most common, and so on.
Use str.split() (no arguments) to split on all whitespace.
Workflow: don't build the whole program at once. Get it to an intermediate
milestone and print your data structure and sys.exit(0).
When that's working, try for the next milestone.
Optional: define a helper function to avoid code duplication inside
print_words() and print_top().
"""
import sys
# +++your code here+++
# Define print_words(filename) and print_top(filename) functions.
# You could write a helper utility function that reads a file
# and builds and returns a word/count dict for it.
# Then print_words() and print_top() can just call the utility function.
#### LAB(begin solution)
def word_count_dict(filename):
"""Returns a word/count dict for this filename."""
# Utility used by count() and Topcount().
word_count = {} # Map each word to its count
input_file = open(filename, 'r')
for line in input_file:
words = line.split()
for word in words:
word = word.lower()
# Special case if we're seeing this word for the first time.
if not word in word_count:
word_count[word] = 1
else:
word_count[word] = word_count[word] + 1
input_file.close() # Not strictly required, but good form.
return word_count
def print_words(filename):
"""Prints one per line '<word> <count>' sorted by word for the given file."""
word_count = word_count_dict(filename)
words = sorted(word_count.keys())
for word in words:
print word, word_count[word]
def get_count(word_count_tuple):
"""Returns the count from a dict word/count tuple -- used for custom sort."""
return word_count_tuple[1]
def print_top(filename):
"""Prints the top count listing for the given file."""
word_count = word_count_dict(filename)
# Each item is a (word, count) tuple.
# Sort them so the big counts are first using key=get_count() to extract count.
items = sorted(word_count.items(), key=get_count, reverse=True)
# Print the first 20
for item in items[:20]:
print item[0], item[1]
##### LAB(end solution)
# This basic command line argument parsing code is provided and
# calls the print_words() and print_top() functions which you must define.
def main():
if len(sys.argv) != 3:
print 'usage: ./wordcount.py {--count | --topcount} file'
sys.exit(1)
option = sys.argv[1]
filename = sys.argv[2]
if option == '--count':
print_words(filename)
elif option == '--topcount':
print_top(filename)
else:
print 'unknown option: ' + option
sys.exit(1)
if __name__ == '__main__':
main()
| apache-2.0 |
ceci/pygments-hack | pygments/cmdline.py | 75 | 13055 | # -*- coding: utf-8 -*-
"""
pygments.cmdline
~~~~~~~~~~~~~~~~
Command line interface.
:copyright: Copyright 2006-2010 by the Pygments team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
import sys
import getopt
from textwrap import dedent
from pygments import __version__, highlight
from pygments.util import ClassNotFound, OptionError, docstring_headline
from pygments.lexers import get_all_lexers, get_lexer_by_name, get_lexer_for_filename, \
find_lexer_class, guess_lexer, TextLexer
from pygments.formatters import get_all_formatters, get_formatter_by_name, \
get_formatter_for_filename, find_formatter_class, \
TerminalFormatter # pylint:disable-msg=E0611
from pygments.filters import get_all_filters, find_filter_class
from pygments.styles import get_all_styles, get_style_by_name
USAGE = """\
Usage: %s [-l <lexer> | -g] [-F <filter>[:<options>]] [-f <formatter>]
[-O <options>] [-P <option=value>] [-o <outfile>] [<infile>]
%s -S <style> -f <formatter> [-a <arg>] [-O <options>] [-P <option=value>]
%s -L [<which> ...]
%s -N <filename>
%s -H <type> <name>
%s -h | -V
Highlight the input file and write the result to <outfile>.
If no input file is given, use stdin, if -o is not given, use stdout.
<lexer> is a lexer name (query all lexer names with -L). If -l is not
given, the lexer is guessed from the extension of the input file name
(this obviously doesn't work if the input is stdin). If -g is passed,
attempt to guess the lexer from the file contents, or pass through as
plain text if this fails (this can work for stdin).
Likewise, <formatter> is a formatter name, and will be guessed from
the extension of the output file name. If no output file is given,
the terminal formatter will be used by default.
With the -O option, you can give the lexer and formatter a comma-
separated list of options, e.g. ``-O bg=light,python=cool``.
The -P option adds lexer and formatter options like the -O option, but
you can only give one option per -P. That way, the option value may
contain commas and equals signs, which it can't with -O, e.g.
``-P "heading=Pygments, the Python highlighter".
With the -F option, you can add filters to the token stream, you can
give options in the same way as for -O after a colon (note: there must
not be spaces around the colon).
The -O, -P and -F options can be given multiple times.
With the -S option, print out style definitions for style <style>
for formatter <formatter>. The argument given by -a is formatter
dependent.
The -L option lists lexers, formatters, styles or filters -- set
`which` to the thing you want to list (e.g. "styles"), or omit it to
list everything.
The -N option guesses and prints out a lexer name based solely on
the given filename. It does not take input or highlight anything.
If no specific lexer can be determined "text" is returned.
The -H option prints detailed help for the object <name> of type <type>,
where <type> is one of "lexer", "formatter" or "filter".
The -h option prints this help.
The -V option prints the package version.
"""
def _parse_options(o_strs):
opts = {}
if not o_strs:
return opts
for o_str in o_strs:
if not o_str:
continue
o_args = o_str.split(',')
for o_arg in o_args:
o_arg = o_arg.strip()
try:
o_key, o_val = o_arg.split('=')
o_key = o_key.strip()
o_val = o_val.strip()
except ValueError:
opts[o_arg] = True
else:
opts[o_key] = o_val
return opts
def _parse_filters(f_strs):
filters = []
if not f_strs:
return filters
for f_str in f_strs:
if ':' in f_str:
fname, fopts = f_str.split(':', 1)
filters.append((fname, _parse_options([fopts])))
else:
filters.append((f_str, {}))
return filters
def _print_help(what, name):
try:
if what == 'lexer':
cls = find_lexer_class(name)
print "Help on the %s lexer:" % cls.name
print dedent(cls.__doc__)
elif what == 'formatter':
cls = find_formatter_class(name)
print "Help on the %s formatter:" % cls.name
print dedent(cls.__doc__)
elif what == 'filter':
cls = find_filter_class(name)
print "Help on the %s filter:" % name
print dedent(cls.__doc__)
except AttributeError:
print >>sys.stderr, "%s not found!" % what
def _print_list(what):
if what == 'lexer':
print
print "Lexers:"
print "~~~~~~~"
info = []
for fullname, names, exts, _ in get_all_lexers():
tup = (', '.join(names)+':', fullname,
exts and '(filenames ' + ', '.join(exts) + ')' or '')
info.append(tup)
info.sort()
for i in info:
print ('* %s\n %s %s') % i
elif what == 'formatter':
print
print "Formatters:"
print "~~~~~~~~~~~"
info = []
for cls in get_all_formatters():
doc = docstring_headline(cls)
tup = (', '.join(cls.aliases) + ':', doc, cls.filenames and
'(filenames ' + ', '.join(cls.filenames) + ')' or '')
info.append(tup)
info.sort()
for i in info:
print ('* %s\n %s %s') % i
elif what == 'filter':
print
print "Filters:"
print "~~~~~~~~"
for name in get_all_filters():
cls = find_filter_class(name)
print "* " + name + ':'
print " %s" % docstring_headline(cls)
elif what == 'style':
print
print "Styles:"
print "~~~~~~~"
for name in get_all_styles():
cls = get_style_by_name(name)
print "* " + name + ':'
print " %s" % docstring_headline(cls)
def main(args=sys.argv):
"""
Main command line entry point.
"""
# pylint: disable-msg=R0911,R0912,R0915
usage = USAGE % ((args[0],) * 6)
try:
popts, args = getopt.getopt(args[1:], "l:f:F:o:O:P:LS:a:N:hVHg")
except getopt.GetoptError, err:
print >>sys.stderr, usage
return 2
opts = {}
O_opts = []
P_opts = []
F_opts = []
for opt, arg in popts:
if opt == '-O':
O_opts.append(arg)
elif opt == '-P':
P_opts.append(arg)
elif opt == '-F':
F_opts.append(arg)
opts[opt] = arg
if not opts and not args:
print usage
return 0
if opts.pop('-h', None) is not None:
print usage
return 0
if opts.pop('-V', None) is not None:
print 'Pygments version %s, (c) 2006-2008 by Georg Brandl.' % __version__
return 0
# handle ``pygmentize -L``
L_opt = opts.pop('-L', None)
if L_opt is not None:
if opts:
print >>sys.stderr, usage
return 2
# print version
main(['', '-V'])
if not args:
args = ['lexer', 'formatter', 'filter', 'style']
for arg in args:
_print_list(arg.rstrip('s'))
return 0
# handle ``pygmentize -H``
H_opt = opts.pop('-H', None)
if H_opt is not None:
if opts or len(args) != 2:
print >>sys.stderr, usage
return 2
what, name = args
if what not in ('lexer', 'formatter', 'filter'):
print >>sys.stderr, usage
return 2
_print_help(what, name)
return 0
# parse -O options
parsed_opts = _parse_options(O_opts)
opts.pop('-O', None)
# parse -P options
for p_opt in P_opts:
try:
name, value = p_opt.split('=', 1)
except ValueError:
parsed_opts[p_opt] = True
else:
parsed_opts[name] = value
opts.pop('-P', None)
# handle ``pygmentize -N``
infn = opts.pop('-N', None)
if infn is not None:
try:
lexer = get_lexer_for_filename(infn, **parsed_opts)
except ClassNotFound, err:
lexer = TextLexer()
except OptionError, err:
print >>sys.stderr, 'Error:', err
return 1
print lexer.aliases[0]
return 0
# handle ``pygmentize -S``
S_opt = opts.pop('-S', None)
a_opt = opts.pop('-a', None)
if S_opt is not None:
f_opt = opts.pop('-f', None)
if not f_opt:
print >>sys.stderr, usage
return 2
if opts or args:
print >>sys.stderr, usage
return 2
try:
parsed_opts['style'] = S_opt
fmter = get_formatter_by_name(f_opt, **parsed_opts)
except ClassNotFound, err:
print >>sys.stderr, err
return 1
arg = a_opt or ''
try:
print fmter.get_style_defs(arg)
except Exception, err:
print >>sys.stderr, 'Error:', err
return 1
return 0
# if no -S is given, -a is not allowed
if a_opt is not None:
print >>sys.stderr, usage
return 2
# parse -F options
F_opts = _parse_filters(F_opts)
opts.pop('-F', None)
# select formatter
outfn = opts.pop('-o', None)
fmter = opts.pop('-f', None)
if fmter:
try:
fmter = get_formatter_by_name(fmter, **parsed_opts)
except (OptionError, ClassNotFound), err:
print >>sys.stderr, 'Error:', err
return 1
if outfn:
if not fmter:
try:
fmter = get_formatter_for_filename(outfn, **parsed_opts)
except (OptionError, ClassNotFound), err:
print >>sys.stderr, 'Error:', err
return 1
try:
outfile = open(outfn, 'wb')
except Exception, err:
print >>sys.stderr, 'Error: cannot open outfile:', err
return 1
else:
if not fmter:
fmter = TerminalFormatter(**parsed_opts)
outfile = sys.stdout
# select lexer
lexer = opts.pop('-l', None)
if lexer:
try:
lexer = get_lexer_by_name(lexer, **parsed_opts)
except (OptionError, ClassNotFound), err:
print >>sys.stderr, 'Error:', err
return 1
if args:
if len(args) > 1:
print >>sys.stderr, usage
return 2
infn = args[0]
try:
code = open(infn, 'rb').read()
except Exception, err:
print >>sys.stderr, 'Error: cannot read infile:', err
return 1
if not lexer:
try:
lexer = get_lexer_for_filename(infn, code, **parsed_opts)
except ClassNotFound, err:
if '-g' in opts:
try:
lexer = guess_lexer(code)
except ClassNotFound:
lexer = TextLexer()
else:
print >>sys.stderr, 'Error:', err
return 1
except OptionError, err:
print >>sys.stderr, 'Error:', err
return 1
else:
if '-g' in opts:
code = sys.stdin.read()
try:
lexer = guess_lexer(code)
except ClassNotFound:
lexer = TextLexer()
elif not lexer:
print >>sys.stderr, 'Error: no lexer name given and reading ' + \
'from stdin (try using -g or -l <lexer>)'
return 2
else:
code = sys.stdin.read()
# No encoding given? Use latin1 if output file given,
# stdin/stdout encoding otherwise.
# (This is a compromise, I'm not too happy with it...)
if 'encoding' not in parsed_opts and 'outencoding' not in parsed_opts:
if outfn:
# encoding pass-through
fmter.encoding = 'latin1'
else:
if sys.version_info < (3,):
# use terminal encoding; Python 3's terminals already do that
lexer.encoding = getattr(sys.stdin, 'encoding',
None) or 'ascii'
fmter.encoding = getattr(sys.stdout, 'encoding',
None) or 'ascii'
# ... and do it!
try:
# process filters
for fname, fopts in F_opts:
lexer.add_filter(fname, **fopts)
highlight(code, lexer, fmter, outfile)
except Exception, err:
import traceback
info = traceback.format_exception(*sys.exc_info())
msg = info[-1].strip()
if len(info) >= 3:
# extract relevant file and position info
msg += '\n (f%s)' % info[-2].split('\n')[0].strip()[1:]
print >>sys.stderr
print >>sys.stderr, '*** Error while highlighting:'
print >>sys.stderr, msg
return 1
return 0
| bsd-2-clause |
TheChymera/LabbookDB | labbookdb/introspection/schema.py | 1 | 2296 | import codecs
import pydotplus
import sadisplay
from os import path
from labbookdb.db.query import ALLOWED_CLASSES
from labbookdb.db.common_classes import *
def generate(
extent="all",
save_dotfile="",
save_plot="",
label="",
linker_tables=False
):
"""Retreive the LabbookDB schema and save either a DOT file, or a PNG or PDF plot.
"""
if extent == "all":
nodes = ALLOWED_CLASSES.values()
elif type(extent) is list:
nodes = [ALLOWED_CLASSES[key] for key in extent]
if linker_tables:
nodes.extend(linker_tables)
desc = sadisplay.describe(nodes)
if save_dotfile:
save_dotfile = path.abspath(path.expanduser(save_dotfile))
with codecs.open(save_dotfile, 'w', encoding='utf-8') as f:
f.write(sadisplay.dot(desc))
if save_plot:
save_plot = path.abspath(path.expanduser(save_plot))
dot = sadisplay.dot(desc)
dot = dot.replace('label = "generated by sadisplay v0.4.8"', 'label = "{}"'.format(label))
graph = pydotplus.graph_from_dot_data(dot)
filename, extension = path.splitext(save_plot)
if extension in [".png",".PNG"]:
graph.write_png(save_plot)
elif extension in [".pdf",".PDF"]:
graph.write_pdf(save_plot)
if __name__ == '__main__':
# generate(extent="all", save_plot="~/full_schema.png")
# generate(extent=["Animal","CageStay","Cage","OpticFiberImplantProtocol","Operation","OrthogonalStereotacticTarget","Protocol"], save_plot="~/cagestay_schema.pdf", linker_tables=[operation_association])
# generate(extent=["Animal","CageStay","Cage",], save_plot="~/cagestay_schema.pdf", linker_tables=[cage_stay_association])
# generate(
# extent=[
# "Animal",
# "ForcedSwimTestMeasurement",
# "Evaluation",
# "CageStay",
# "Cage",
# "Measurement",
# "Treatment",
# "Protocol",
# ],
# save_plot="~/fst_schema.pdf",
# linker_tables=[
# cage_stay_association,
# treatment_cage_association,
# ],
# )
# generate(extent=["Animal","CageStay","Cage","SucrosePreferenceMeasurement"], save_plot="~/measurements_schema.pdf")
generate(extent=["Animal","Operation","Protocol","Operator"], save_plot="~/basic_schema.pdf", linker_tables=[authors_association,operation_association])
# generate(extent=["Animal","FMRIMeasurement","OpenFieldTestMeasurement","WeightMeasurement"], save_plot="~/measurements_schema.pdf")
| bsd-3-clause |
MakahikiKTUH/makahiki-ktuh | makahiki/scripts/data-analysis/competition_summary.py | 9 | 1517 | #!/usr/bin/env python
import sys
from os.path import abspath, dirname, join
from django.conf import settings
from django.core.management import setup_environ
try:
import settings as settings_mod # Assumed to be in the same directory.
except ImportError:
sys.stderr.write(
"Error: Can't find the file 'settings.py' in the directory containing"\
" %r. It appears you've customized things.\nYou'll have to run "\
"django-admin.py, passing it your settings module.\n(If the file "\
"settings.py does indeed exist, it's causing an ImportError somehow.)"\
"\n" % __file__)
sys.exit(1)
# setup the environment before we start accessing things in the settings.
setup_environ(settings_mod)
sys.path.insert(0, join(settings.PROJECT_ROOT, "apps"))
from apps.managers.team_mgr.models import Team
def competition_summary():
"""
Writes summary of competition to a file. The following things are on
each line:
* Building
* Lounge
* Total points to date
* User wall posts
* Number of canopy members in the lounge.
"""
if len(sys.argv) != 2:
print "Usage: python competition_summary.py <filename to write to>"
exit()
with open(sys.argv[1], "w") as out:
for team in Team.objects.all():
posts = team.post_set.filter(style_class="user_post").count()
out.write("%s,%d,%d\n" % (
team.name, team.points(), posts))
if __name__ == "__main__":
competition_summary()
| mit |
tamland/xbmc-addon-watchdog | core/emitters.py | 1 | 3300 | # -*- coding: utf-8 -*-
#
# Copyright (C) 2014 Thomas Amland
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from __future__ import unicode_literals
import os
from watchdog.observers.api import BaseObserver
from watchdog.observers.api import ObservedWatch
from polling_local import LocalPoller
from polling_xbmc import VFSPoller
from utils import encode_path, is_url
try:
from watchdog.observers.inotify import InotifyEmitter as NativeEmitter
except:
try:
from watchdog.observers.kqueue import KqueueEmitter as NativeEmitter
except:
try:
from watchdog.observers.read_directory_changes import WindowsApiEmitter as NativeEmitter
except:
NativeEmitter = LocalPoller
class MultiEmitterObserver(BaseObserver):
def __init__(self):
BaseObserver.__init__(self, None)
@property
def paths(self):
return [w.path for w in self._watches]
def schedule(self, event_handler, path, emitter_cls=None):
with self._lock:
watch = ObservedWatch(path, True)
emitter = emitter_cls(self.event_queue, watch, self.timeout)
if self.is_alive():
emitter.start()
self._add_handler_for_watch(event_handler, watch)
self._add_emitter(emitter)
self._watches.add(watch)
return watch
def select_emitter(path):
import xbmcvfs
import settings
from utils import log
if is_url(path) and xbmcvfs.exists(path):
return VFSPoller
if os.path.exists(encode_path(path)):
if settings.POLLING:
return LocalPoller
if _is_remote_filesystem(path):
log("select_observer: path <%s> identified as remote filesystem" % path)
return LocalPoller
return NativeEmitter
raise IOError("No such directory: '%s'" % path)
def _is_remote_filesystem(path):
from utils import log
from watchdog.utils import platform
if not platform.is_linux():
return False
remote_fs_types = ['cifs', 'smbfs', 'nfs', 'nfs4']
escaped_path = encode_path(path.rstrip('/').replace(' ', '\\040'))
try:
with open('/proc/mounts', 'r') as f:
for line in f:
_, mount_point, fstype = line.split()[:3]
if mount_point == escaped_path:
log("[fstype] type is \"%s\" '%s' " % (fstype, path.decode('utf-8')))
return fstype in remote_fs_types
log("[fstype] path not in /proc/mounts '%s' " % escaped_path.decode('utf-8'))
return False
except (IOError, ValueError) as e:
log("[fstype] failed to read /proc/mounts. %s, %s" % (type(e), e))
return False | gpl-3.0 |
omni5cience/django-inlineformfield | .tox/py27/lib/python2.7/site-packages/IPython/core/tests/test_application.py | 20 | 1647 | # coding: utf-8
"""Tests for IPython.core.application"""
import os
import tempfile
from IPython.core.application import BaseIPythonApplication
from IPython.testing import decorators as dec
from IPython.utils import py3compat
@dec.onlyif_unicode_paths
def test_unicode_cwd():
"""Check that IPython starts with non-ascii characters in the path."""
wd = tempfile.mkdtemp(suffix=u"€")
old_wd = py3compat.getcwd()
os.chdir(wd)
#raise Exception(repr(py3compat.getcwd()))
try:
app = BaseIPythonApplication()
# The lines below are copied from Application.initialize()
app.init_profile_dir()
app.init_config_files()
app.load_config_file(suppress_errors=False)
finally:
os.chdir(old_wd)
@dec.onlyif_unicode_paths
def test_unicode_ipdir():
"""Check that IPython starts with non-ascii characters in the IP dir."""
ipdir = tempfile.mkdtemp(suffix=u"€")
# Create the config file, so it tries to load it.
with open(os.path.join(ipdir, 'ipython_config.py'), "w") as f:
pass
old_ipdir1 = os.environ.pop("IPYTHONDIR", None)
old_ipdir2 = os.environ.pop("IPYTHON_DIR", None)
os.environ["IPYTHONDIR"] = py3compat.unicode_to_str(ipdir, "utf-8")
try:
app = BaseIPythonApplication()
# The lines below are copied from Application.initialize()
app.init_profile_dir()
app.init_config_files()
app.load_config_file(suppress_errors=False)
finally:
if old_ipdir1:
os.environ["IPYTHONDIR"] = old_ipdir1
if old_ipdir2:
os.environ["IPYTHONDIR"] = old_ipdir2
| mit |
jendap/tensorflow | tensorflow/python/keras/layers/pooling_test.py | 10 | 7660 | # 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 pooling layers."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
from tensorflow.python import keras
from tensorflow.python.eager import context
from tensorflow.python.framework import test_util as tf_test_util
from tensorflow.python.keras import testing_utils
from tensorflow.python.platform import test
class GlobalPoolingTest(test.TestCase):
@tf_test_util.run_in_graph_and_eager_modes
def test_globalpooling_1d(self):
testing_utils.layer_test(keras.layers.pooling.GlobalMaxPooling1D,
input_shape=(3, 4, 5))
testing_utils.layer_test(keras.layers.pooling.GlobalMaxPooling1D,
kwargs={'data_format': 'channels_first'},
input_shape=(3, 4, 5))
testing_utils.layer_test(
keras.layers.pooling.GlobalAveragePooling1D, input_shape=(3, 4, 5))
testing_utils.layer_test(keras.layers.pooling.GlobalAveragePooling1D,
kwargs={'data_format': 'channels_first'},
input_shape=(3, 4, 5))
@tf_test_util.run_in_graph_and_eager_modes
def test_globalpooling_1d_masking_support(self):
model = keras.Sequential()
model.add(keras.layers.Masking(mask_value=0., input_shape=(3, 4)))
model.add(keras.layers.GlobalAveragePooling1D())
model.compile(loss='mae', optimizer='rmsprop')
model_input = np.random.random((2, 3, 4))
model_input[0, 1:, :] = 0
output = model.predict(model_input)
self.assertAllClose(output[0], model_input[0, 0, :])
@tf_test_util.run_in_graph_and_eager_modes
def test_globalpooling_2d(self):
testing_utils.layer_test(
keras.layers.pooling.GlobalMaxPooling2D,
kwargs={'data_format': 'channels_first'},
input_shape=(3, 4, 5, 6))
testing_utils.layer_test(
keras.layers.pooling.GlobalMaxPooling2D,
kwargs={'data_format': 'channels_last'},
input_shape=(3, 5, 6, 4))
testing_utils.layer_test(
keras.layers.pooling.GlobalAveragePooling2D,
kwargs={'data_format': 'channels_first'},
input_shape=(3, 4, 5, 6))
testing_utils.layer_test(
keras.layers.pooling.GlobalAveragePooling2D,
kwargs={'data_format': 'channels_last'},
input_shape=(3, 5, 6, 4))
@tf_test_util.run_in_graph_and_eager_modes
def test_globalpooling_3d(self):
testing_utils.layer_test(
keras.layers.pooling.GlobalMaxPooling3D,
kwargs={'data_format': 'channels_first'},
input_shape=(3, 4, 3, 4, 3))
testing_utils.layer_test(
keras.layers.pooling.GlobalMaxPooling3D,
kwargs={'data_format': 'channels_last'},
input_shape=(3, 4, 3, 4, 3))
testing_utils.layer_test(
keras.layers.pooling.GlobalAveragePooling3D,
kwargs={'data_format': 'channels_first'},
input_shape=(3, 4, 3, 4, 3))
testing_utils.layer_test(
keras.layers.pooling.GlobalAveragePooling3D,
kwargs={'data_format': 'channels_last'},
input_shape=(3, 4, 3, 4, 3))
class Pooling2DTest(test.TestCase):
@tf_test_util.run_in_graph_and_eager_modes
def test_maxpooling_2d(self):
pool_size = (3, 3)
for strides in [(1, 1), (2, 2)]:
testing_utils.layer_test(
keras.layers.MaxPooling2D,
kwargs={
'strides': strides,
'padding': 'valid',
'pool_size': pool_size
},
input_shape=(3, 5, 6, 4))
@tf_test_util.run_in_graph_and_eager_modes
def test_averagepooling_2d(self):
testing_utils.layer_test(
keras.layers.AveragePooling2D,
kwargs={'strides': (2, 2),
'padding': 'same',
'pool_size': (2, 2)},
input_shape=(3, 5, 6, 4))
testing_utils.layer_test(
keras.layers.AveragePooling2D,
kwargs={'strides': (2, 2),
'padding': 'valid',
'pool_size': (3, 3)},
input_shape=(3, 5, 6, 4))
# This part of the test can only run on GPU but doesn't appear
# to be properly assigned to a GPU when running in eager mode.
if not context.executing_eagerly():
# Only runs on GPU with CUDA, channels_first is not supported on CPU.
# TODO(b/62340061): Support channels_first on CPU.
if test.is_gpu_available(cuda_only=True):
testing_utils.layer_test(
keras.layers.AveragePooling2D,
kwargs={
'strides': (1, 1),
'padding': 'valid',
'pool_size': (2, 2),
'data_format': 'channels_first'
},
input_shape=(3, 4, 5, 6))
class Pooling3DTest(test.TestCase):
@tf_test_util.run_in_graph_and_eager_modes
def test_maxpooling_3d(self):
pool_size = (3, 3, 3)
testing_utils.layer_test(
keras.layers.MaxPooling3D,
kwargs={'strides': 2,
'padding': 'valid',
'pool_size': pool_size},
input_shape=(3, 11, 12, 10, 4))
testing_utils.layer_test(
keras.layers.MaxPooling3D,
kwargs={
'strides': 3,
'padding': 'valid',
'data_format': 'channels_first',
'pool_size': pool_size
},
input_shape=(3, 4, 11, 12, 10))
@tf_test_util.run_in_graph_and_eager_modes
def test_averagepooling_3d(self):
pool_size = (3, 3, 3)
testing_utils.layer_test(
keras.layers.AveragePooling3D,
kwargs={'strides': 2,
'padding': 'valid',
'pool_size': pool_size},
input_shape=(3, 11, 12, 10, 4))
testing_utils.layer_test(
keras.layers.AveragePooling3D,
kwargs={
'strides': 3,
'padding': 'valid',
'data_format': 'channels_first',
'pool_size': pool_size
},
input_shape=(3, 4, 11, 12, 10))
class Pooling1DTest(test.TestCase):
@tf_test_util.run_in_graph_and_eager_modes
def test_maxpooling_1d(self):
for padding in ['valid', 'same']:
for stride in [1, 2]:
testing_utils.layer_test(
keras.layers.MaxPooling1D,
kwargs={'strides': stride,
'padding': padding},
input_shape=(3, 5, 4))
testing_utils.layer_test(
keras.layers.MaxPooling1D,
kwargs={'data_format': 'channels_first'},
input_shape=(3, 2, 6))
@tf_test_util.run_in_graph_and_eager_modes
def test_averagepooling_1d(self):
for padding in ['valid', 'same']:
for stride in [1, 2]:
testing_utils.layer_test(
keras.layers.AveragePooling1D,
kwargs={'strides': stride,
'padding': padding},
input_shape=(3, 5, 4))
testing_utils.layer_test(
keras.layers.AveragePooling1D,
kwargs={'data_format': 'channels_first'},
input_shape=(3, 2, 6))
if __name__ == '__main__':
test.main()
| apache-2.0 |
moijes12/oh-mainline | vendor/packages/Pygments/pygments/lexers/agile.py | 69 | 78670 | # -*- coding: utf-8 -*-
"""
pygments.lexers.agile
~~~~~~~~~~~~~~~~~~~~~
Lexers for agile languages.
:copyright: Copyright 2006-2013 by the Pygments team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
import re
from pygments.lexer import Lexer, RegexLexer, ExtendedRegexLexer, \
LexerContext, include, combined, do_insertions, bygroups, using
from pygments.token import Error, Text, Other, \
Comment, Operator, Keyword, Name, String, Number, Generic, Punctuation
from pygments.util import get_bool_opt, get_list_opt, shebang_matches
from pygments import unistring as uni
__all__ = ['PythonLexer', 'PythonConsoleLexer', 'PythonTracebackLexer',
'Python3Lexer', 'Python3TracebackLexer', 'RubyLexer',
'RubyConsoleLexer', 'PerlLexer', 'LuaLexer', 'MoonScriptLexer',
'CrocLexer', 'MiniDLexer', 'IoLexer', 'TclLexer', 'FactorLexer',
'FancyLexer', 'DgLexer']
# b/w compatibility
from pygments.lexers.functional import SchemeLexer
from pygments.lexers.jvm import IokeLexer, ClojureLexer
line_re = re.compile('.*?\n')
class PythonLexer(RegexLexer):
"""
For `Python <http://www.python.org>`_ source code.
"""
name = 'Python'
aliases = ['python', 'py', 'sage']
filenames = ['*.py', '*.pyw', '*.sc', 'SConstruct', 'SConscript', '*.tac', '*.sage']
mimetypes = ['text/x-python', 'application/x-python']
tokens = {
'root': [
(r'\n', Text),
(r'^(\s*)([rRuU]{,2}"""(?:.|\n)*?""")', bygroups(Text, String.Doc)),
(r"^(\s*)([rRuU]{,2}'''(?:.|\n)*?''')", bygroups(Text, String.Doc)),
(r'[^\S\n]+', Text),
(r'#.*$', Comment),
(r'[]{}:(),;[]', Punctuation),
(r'\\\n', Text),
(r'\\', Text),
(r'(in|is|and|or|not)\b', Operator.Word),
(r'!=|==|<<|>>|[-~+/*%=<>&^|.]', Operator),
include('keywords'),
(r'(def)((?:\s|\\\s)+)', bygroups(Keyword, Text), 'funcname'),
(r'(class)((?:\s|\\\s)+)', bygroups(Keyword, Text), 'classname'),
(r'(from)((?:\s|\\\s)+)', bygroups(Keyword.Namespace, Text),
'fromimport'),
(r'(import)((?:\s|\\\s)+)', bygroups(Keyword.Namespace, Text),
'import'),
include('builtins'),
include('backtick'),
('(?:[rR]|[uU][rR]|[rR][uU])"""', String, 'tdqs'),
("(?:[rR]|[uU][rR]|[rR][uU])'''", String, 'tsqs'),
('(?:[rR]|[uU][rR]|[rR][uU])"', String, 'dqs'),
("(?:[rR]|[uU][rR]|[rR][uU])'", String, 'sqs'),
('[uU]?"""', String, combined('stringescape', 'tdqs')),
("[uU]?'''", String, combined('stringescape', 'tsqs')),
('[uU]?"', String, combined('stringescape', 'dqs')),
("[uU]?'", String, combined('stringescape', 'sqs')),
include('name'),
include('numbers'),
],
'keywords': [
(r'(assert|break|continue|del|elif|else|except|exec|'
r'finally|for|global|if|lambda|pass|print|raise|'
r'return|try|while|yield(\s+from)?|as|with)\b', Keyword),
],
'builtins': [
(r'(?<!\.)(__import__|abs|all|any|apply|basestring|bin|bool|buffer|'
r'bytearray|bytes|callable|chr|classmethod|cmp|coerce|compile|'
r'complex|delattr|dict|dir|divmod|enumerate|eval|execfile|exit|'
r'file|filter|float|frozenset|getattr|globals|hasattr|hash|hex|id|'
r'input|int|intern|isinstance|issubclass|iter|len|list|locals|'
r'long|map|max|min|next|object|oct|open|ord|pow|property|range|'
r'raw_input|reduce|reload|repr|reversed|round|set|setattr|slice|'
r'sorted|staticmethod|str|sum|super|tuple|type|unichr|unicode|'
r'vars|xrange|zip)\b', Name.Builtin),
(r'(?<!\.)(self|None|Ellipsis|NotImplemented|False|True'
r')\b', Name.Builtin.Pseudo),
(r'(?<!\.)(ArithmeticError|AssertionError|AttributeError|'
r'BaseException|DeprecationWarning|EOFError|EnvironmentError|'
r'Exception|FloatingPointError|FutureWarning|GeneratorExit|IOError|'
r'ImportError|ImportWarning|IndentationError|IndexError|KeyError|'
r'KeyboardInterrupt|LookupError|MemoryError|NameError|'
r'NotImplemented|NotImplementedError|OSError|OverflowError|'
r'OverflowWarning|PendingDeprecationWarning|ReferenceError|'
r'RuntimeError|RuntimeWarning|StandardError|StopIteration|'
r'SyntaxError|SyntaxWarning|SystemError|SystemExit|TabError|'
r'TypeError|UnboundLocalError|UnicodeDecodeError|'
r'UnicodeEncodeError|UnicodeError|UnicodeTranslateError|'
r'UnicodeWarning|UserWarning|ValueError|VMSError|Warning|'
r'WindowsError|ZeroDivisionError)\b', Name.Exception),
],
'numbers': [
(r'(\d+\.\d*|\d*\.\d+)([eE][+-]?[0-9]+)?j?', Number.Float),
(r'\d+[eE][+-]?[0-9]+j?', Number.Float),
(r'0[0-7]+j?', Number.Oct),
(r'0[xX][a-fA-F0-9]+', Number.Hex),
(r'\d+L', Number.Integer.Long),
(r'\d+j?', Number.Integer)
],
'backtick': [
('`.*?`', String.Backtick),
],
'name': [
(r'@[a-zA-Z0-9_.]+', Name.Decorator),
('[a-zA-Z_][a-zA-Z0-9_]*', Name),
],
'funcname': [
('[a-zA-Z_][a-zA-Z0-9_]*', Name.Function, '#pop')
],
'classname': [
('[a-zA-Z_][a-zA-Z0-9_]*', Name.Class, '#pop')
],
'import': [
(r'(?:[ \t]|\\\n)+', Text),
(r'as\b', Keyword.Namespace),
(r',', Operator),
(r'[a-zA-Z_][a-zA-Z0-9_.]*', Name.Namespace),
(r'', Text, '#pop') # all else: go back
],
'fromimport': [
(r'(?:[ \t]|\\\n)+', Text),
(r'import\b', Keyword.Namespace, '#pop'),
# if None occurs here, it's "raise x from None", since None can
# never be a module name
(r'None\b', Name.Builtin.Pseudo, '#pop'),
# sadly, in "raise x from y" y will be highlighted as namespace too
(r'[a-zA-Z_.][a-zA-Z0-9_.]*', Name.Namespace),
# anything else here also means "raise x from y" and is therefore
# not an error
(r'', Text, '#pop'),
],
'stringescape': [
(r'\\([\\abfnrtv"\']|\n|N{.*?}|u[a-fA-F0-9]{4}|'
r'U[a-fA-F0-9]{8}|x[a-fA-F0-9]{2}|[0-7]{1,3})', String.Escape)
],
'strings': [
(r'%(\([a-zA-Z0-9_]+\))?[-#0 +]*([0-9]+|[*])?(\.([0-9]+|[*]))?'
'[hlL]?[diouxXeEfFgGcrs%]', String.Interpol),
(r'[^\\\'"%\n]+', String),
# quotes, percents and backslashes must be parsed one at a time
(r'[\'"\\]', String),
# unhandled string formatting sign
(r'%', String)
# newlines are an error (use "nl" state)
],
'nl': [
(r'\n', String)
],
'dqs': [
(r'"', String, '#pop'),
(r'\\\\|\\"|\\\n', String.Escape), # included here for raw strings
include('strings')
],
'sqs': [
(r"'", String, '#pop'),
(r"\\\\|\\'|\\\n", String.Escape), # included here for raw strings
include('strings')
],
'tdqs': [
(r'"""', String, '#pop'),
include('strings'),
include('nl')
],
'tsqs': [
(r"'''", String, '#pop'),
include('strings'),
include('nl')
],
}
def analyse_text(text):
return shebang_matches(text, r'pythonw?(2(\.\d)?)?')
class Python3Lexer(RegexLexer):
"""
For `Python <http://www.python.org>`_ source code (version 3.0).
*New in Pygments 0.10.*
"""
name = 'Python 3'
aliases = ['python3', 'py3']
filenames = [] # Nothing until Python 3 gets widespread
mimetypes = ['text/x-python3', 'application/x-python3']
flags = re.MULTILINE | re.UNICODE
uni_name = "[%s][%s]*" % (uni.xid_start, uni.xid_continue)
tokens = PythonLexer.tokens.copy()
tokens['keywords'] = [
(r'(assert|break|continue|del|elif|else|except|'
r'finally|for|global|if|lambda|pass|raise|nonlocal|'
r'return|try|while|yield(\s+from)?|as|with|True|False|None)\b',
Keyword),
]
tokens['builtins'] = [
(r'(?<!\.)(__import__|abs|all|any|bin|bool|bytearray|bytes|'
r'chr|classmethod|cmp|compile|complex|delattr|dict|dir|'
r'divmod|enumerate|eval|filter|float|format|frozenset|getattr|'
r'globals|hasattr|hash|hex|id|input|int|isinstance|issubclass|'
r'iter|len|list|locals|map|max|memoryview|min|next|object|oct|'
r'open|ord|pow|print|property|range|repr|reversed|round|'
r'set|setattr|slice|sorted|staticmethod|str|sum|super|tuple|type|'
r'vars|zip)\b', Name.Builtin),
(r'(?<!\.)(self|Ellipsis|NotImplemented)\b', Name.Builtin.Pseudo),
(r'(?<!\.)(ArithmeticError|AssertionError|AttributeError|'
r'BaseException|BufferError|BytesWarning|DeprecationWarning|'
r'EOFError|EnvironmentError|Exception|FloatingPointError|'
r'FutureWarning|GeneratorExit|IOError|ImportError|'
r'ImportWarning|IndentationError|IndexError|KeyError|'
r'KeyboardInterrupt|LookupError|MemoryError|NameError|'
r'NotImplementedError|OSError|OverflowError|'
r'PendingDeprecationWarning|ReferenceError|'
r'RuntimeError|RuntimeWarning|StopIteration|'
r'SyntaxError|SyntaxWarning|SystemError|SystemExit|TabError|'
r'TypeError|UnboundLocalError|UnicodeDecodeError|'
r'UnicodeEncodeError|UnicodeError|UnicodeTranslateError|'
r'UnicodeWarning|UserWarning|ValueError|VMSError|Warning|'
r'WindowsError|ZeroDivisionError)\b', Name.Exception),
]
tokens['numbers'] = [
(r'(\d+\.\d*|\d*\.\d+)([eE][+-]?[0-9]+)?', Number.Float),
(r'0[oO][0-7]+', Number.Oct),
(r'0[bB][01]+', Number.Bin),
(r'0[xX][a-fA-F0-9]+', Number.Hex),
(r'\d+', Number.Integer)
]
tokens['backtick'] = []
tokens['name'] = [
(r'@[a-zA-Z0-9_]+', Name.Decorator),
(uni_name, Name),
]
tokens['funcname'] = [
(uni_name, Name.Function, '#pop')
]
tokens['classname'] = [
(uni_name, Name.Class, '#pop')
]
tokens['import'] = [
(r'(\s+)(as)(\s+)', bygroups(Text, Keyword, Text)),
(r'\.', Name.Namespace),
(uni_name, Name.Namespace),
(r'(\s*)(,)(\s*)', bygroups(Text, Operator, Text)),
(r'', Text, '#pop') # all else: go back
]
tokens['fromimport'] = [
(r'(\s+)(import)\b', bygroups(Text, Keyword), '#pop'),
(r'\.', Name.Namespace),
(uni_name, Name.Namespace),
(r'', Text, '#pop'),
]
# don't highlight "%s" substitutions
tokens['strings'] = [
(r'[^\\\'"%\n]+', String),
# quotes, percents and backslashes must be parsed one at a time
(r'[\'"\\]', String),
# unhandled string formatting sign
(r'%', String)
# newlines are an error (use "nl" state)
]
def analyse_text(text):
return shebang_matches(text, r'pythonw?3(\.\d)?')
class PythonConsoleLexer(Lexer):
"""
For Python console output or doctests, such as:
.. sourcecode:: pycon
>>> a = 'foo'
>>> print a
foo
>>> 1 / 0
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ZeroDivisionError: integer division or modulo by zero
Additional options:
`python3`
Use Python 3 lexer for code. Default is ``False``.
*New in Pygments 1.0.*
"""
name = 'Python console session'
aliases = ['pycon']
mimetypes = ['text/x-python-doctest']
def __init__(self, **options):
self.python3 = get_bool_opt(options, 'python3', False)
Lexer.__init__(self, **options)
def get_tokens_unprocessed(self, text):
if self.python3:
pylexer = Python3Lexer(**self.options)
tblexer = Python3TracebackLexer(**self.options)
else:
pylexer = PythonLexer(**self.options)
tblexer = PythonTracebackLexer(**self.options)
curcode = ''
insertions = []
curtb = ''
tbindex = 0
tb = 0
for match in line_re.finditer(text):
line = match.group()
if line.startswith(u'>>> ') or line.startswith(u'... '):
tb = 0
insertions.append((len(curcode),
[(0, Generic.Prompt, line[:4])]))
curcode += line[4:]
elif line.rstrip() == u'...' and not tb:
# only a new >>> prompt can end an exception block
# otherwise an ellipsis in place of the traceback frames
# will be mishandled
insertions.append((len(curcode),
[(0, Generic.Prompt, u'...')]))
curcode += line[3:]
else:
if curcode:
for item in do_insertions(insertions,
pylexer.get_tokens_unprocessed(curcode)):
yield item
curcode = ''
insertions = []
if (line.startswith(u'Traceback (most recent call last):') or
re.match(ur' File "[^"]+", line \d+\n$', line)):
tb = 1
curtb = line
tbindex = match.start()
elif line == 'KeyboardInterrupt\n':
yield match.start(), Name.Class, line
elif tb:
curtb += line
if not (line.startswith(' ') or line.strip() == u'...'):
tb = 0
for i, t, v in tblexer.get_tokens_unprocessed(curtb):
yield tbindex+i, t, v
else:
yield match.start(), Generic.Output, line
if curcode:
for item in do_insertions(insertions,
pylexer.get_tokens_unprocessed(curcode)):
yield item
class PythonTracebackLexer(RegexLexer):
"""
For Python tracebacks.
*New in Pygments 0.7.*
"""
name = 'Python Traceback'
aliases = ['pytb']
filenames = ['*.pytb']
mimetypes = ['text/x-python-traceback']
tokens = {
'root': [
(r'^Traceback \(most recent call last\):\n',
Generic.Traceback, 'intb'),
# SyntaxError starts with this.
(r'^(?= File "[^"]+", line \d+)', Generic.Traceback, 'intb'),
(r'^.*\n', Other),
],
'intb': [
(r'^( File )("[^"]+")(, line )(\d+)(, in )(.+)(\n)',
bygroups(Text, Name.Builtin, Text, Number, Text, Name, Text)),
(r'^( File )("[^"]+")(, line )(\d+)(\n)',
bygroups(Text, Name.Builtin, Text, Number, Text)),
(r'^( )(.+)(\n)',
bygroups(Text, using(PythonLexer), Text)),
(r'^([ \t]*)(\.\.\.)(\n)',
bygroups(Text, Comment, Text)), # for doctests...
(r'^([^:]+)(: )(.+)(\n)',
bygroups(Generic.Error, Text, Name, Text), '#pop'),
(r'^([a-zA-Z_][a-zA-Z0-9_]*)(:?\n)',
bygroups(Generic.Error, Text), '#pop')
],
}
class Python3TracebackLexer(RegexLexer):
"""
For Python 3.0 tracebacks, with support for chained exceptions.
*New in Pygments 1.0.*
"""
name = 'Python 3.0 Traceback'
aliases = ['py3tb']
filenames = ['*.py3tb']
mimetypes = ['text/x-python3-traceback']
tokens = {
'root': [
(r'\n', Text),
(r'^Traceback \(most recent call last\):\n', Generic.Traceback, 'intb'),
(r'^During handling of the above exception, another '
r'exception occurred:\n\n', Generic.Traceback),
(r'^The above exception was the direct cause of the '
r'following exception:\n\n', Generic.Traceback),
],
'intb': [
(r'^( File )("[^"]+")(, line )(\d+)(, in )(.+)(\n)',
bygroups(Text, Name.Builtin, Text, Number, Text, Name, Text)),
(r'^( )(.+)(\n)',
bygroups(Text, using(Python3Lexer), Text)),
(r'^([ \t]*)(\.\.\.)(\n)',
bygroups(Text, Comment, Text)), # for doctests...
(r'^([^:]+)(: )(.+)(\n)',
bygroups(Generic.Error, Text, Name, Text), '#pop'),
(r'^([a-zA-Z_][a-zA-Z0-9_]*)(:?\n)',
bygroups(Generic.Error, Text), '#pop')
],
}
class RubyLexer(ExtendedRegexLexer):
"""
For `Ruby <http://www.ruby-lang.org>`_ source code.
"""
name = 'Ruby'
aliases = ['rb', 'ruby', 'duby']
filenames = ['*.rb', '*.rbw', 'Rakefile', '*.rake', '*.gemspec',
'*.rbx', '*.duby']
mimetypes = ['text/x-ruby', 'application/x-ruby']
flags = re.DOTALL | re.MULTILINE
def heredoc_callback(self, match, ctx):
# okay, this is the hardest part of parsing Ruby...
# match: 1 = <<-?, 2 = quote? 3 = name 4 = quote? 5 = rest of line
start = match.start(1)
yield start, Operator, match.group(1) # <<-?
yield match.start(2), String.Heredoc, match.group(2) # quote ", ', `
yield match.start(3), Name.Constant, match.group(3) # heredoc name
yield match.start(4), String.Heredoc, match.group(4) # quote again
heredocstack = ctx.__dict__.setdefault('heredocstack', [])
outermost = not bool(heredocstack)
heredocstack.append((match.group(1) == '<<-', match.group(3)))
ctx.pos = match.start(5)
ctx.end = match.end(5)
# this may find other heredocs
for i, t, v in self.get_tokens_unprocessed(context=ctx):
yield i, t, v
ctx.pos = match.end()
if outermost:
# this is the outer heredoc again, now we can process them all
for tolerant, hdname in heredocstack:
lines = []
for match in line_re.finditer(ctx.text, ctx.pos):
if tolerant:
check = match.group().strip()
else:
check = match.group().rstrip()
if check == hdname:
for amatch in lines:
yield amatch.start(), String.Heredoc, amatch.group()
yield match.start(), Name.Constant, match.group()
ctx.pos = match.end()
break
else:
lines.append(match)
else:
# end of heredoc not found -- error!
for amatch in lines:
yield amatch.start(), Error, amatch.group()
ctx.end = len(ctx.text)
del heredocstack[:]
def gen_rubystrings_rules():
def intp_regex_callback(self, match, ctx):
yield match.start(1), String.Regex, match.group(1) # begin
nctx = LexerContext(match.group(3), 0, ['interpolated-regex'])
for i, t, v in self.get_tokens_unprocessed(context=nctx):
yield match.start(3)+i, t, v
yield match.start(4), String.Regex, match.group(4) # end[mixounse]*
ctx.pos = match.end()
def intp_string_callback(self, match, ctx):
yield match.start(1), String.Other, match.group(1)
nctx = LexerContext(match.group(3), 0, ['interpolated-string'])
for i, t, v in self.get_tokens_unprocessed(context=nctx):
yield match.start(3)+i, t, v
yield match.start(4), String.Other, match.group(4) # end
ctx.pos = match.end()
states = {}
states['strings'] = [
# easy ones
(r'\:@{0,2}([a-zA-Z_]\w*[\!\?]?|\*\*?|[-+]@?|'
r'[/%&|^`~]|\[\]=?|<<|>>|<=?>|>=?|===?)', String.Symbol),
(r":'(\\\\|\\'|[^'])*'", String.Symbol),
(r"'(\\\\|\\'|[^'])*'", String.Single),
(r':"', String.Symbol, 'simple-sym'),
(r'([a-zA-Z_][a-zA-Z0-9]*)(:)',
bygroups(String.Symbol, Punctuation)), # Since Ruby 1.9
(r'"', String.Double, 'simple-string'),
(r'(?<!\.)`', String.Backtick, 'simple-backtick'),
]
# double-quoted string and symbol
for name, ttype, end in ('string', String.Double, '"'), \
('sym', String.Symbol, '"'), \
('backtick', String.Backtick, '`'):
states['simple-'+name] = [
include('string-intp-escaped'),
(r'[^\\%s#]+' % end, ttype),
(r'[\\#]', ttype),
(end, ttype, '#pop'),
]
# braced quoted strings
for lbrace, rbrace, name in ('\\{', '\\}', 'cb'), \
('\\[', '\\]', 'sb'), \
('\\(', '\\)', 'pa'), \
('<', '>', 'ab'):
states[name+'-intp-string'] = [
(r'\\[\\' + lbrace + rbrace + ']', String.Other),
(r'(?<!\\)' + lbrace, String.Other, '#push'),
(r'(?<!\\)' + rbrace, String.Other, '#pop'),
include('string-intp-escaped'),
(r'[\\#' + lbrace + rbrace + ']', String.Other),
(r'[^\\#' + lbrace + rbrace + ']+', String.Other),
]
states['strings'].append((r'%[QWx]?' + lbrace, String.Other,
name+'-intp-string'))
states[name+'-string'] = [
(r'\\[\\' + lbrace + rbrace + ']', String.Other),
(r'(?<!\\)' + lbrace, String.Other, '#push'),
(r'(?<!\\)' + rbrace, String.Other, '#pop'),
(r'[\\#' + lbrace + rbrace + ']', String.Other),
(r'[^\\#' + lbrace + rbrace + ']+', String.Other),
]
states['strings'].append((r'%[qsw]' + lbrace, String.Other,
name+'-string'))
states[name+'-regex'] = [
(r'\\[\\' + lbrace + rbrace + ']', String.Regex),
(r'(?<!\\)' + lbrace, String.Regex, '#push'),
(r'(?<!\\)' + rbrace + '[mixounse]*', String.Regex, '#pop'),
include('string-intp'),
(r'[\\#' + lbrace + rbrace + ']', String.Regex),
(r'[^\\#' + lbrace + rbrace + ']+', String.Regex),
]
states['strings'].append((r'%r' + lbrace, String.Regex,
name+'-regex'))
# these must come after %<brace>!
states['strings'] += [
# %r regex
(r'(%r([^a-zA-Z0-9]))((?:\\\2|(?!\2).)*)(\2[mixounse]*)',
intp_regex_callback),
# regular fancy strings with qsw
(r'%[qsw]([^a-zA-Z0-9])((?:\\\1|(?!\1).)*)\1', String.Other),
(r'(%[QWx]([^a-zA-Z0-9]))((?:\\\2|(?!\2).)*)(\2)',
intp_string_callback),
# special forms of fancy strings after operators or
# in method calls with braces
(r'(?<=[-+/*%=<>&!^|~,(])(\s*)(%([\t ])(?:(?:\\\3|(?!\3).)*)\3)',
bygroups(Text, String.Other, None)),
# and because of fixed width lookbehinds the whole thing a
# second time for line startings...
(r'^(\s*)(%([\t ])(?:(?:\\\3|(?!\3).)*)\3)',
bygroups(Text, String.Other, None)),
# all regular fancy strings without qsw
(r'(%([^a-zA-Z0-9\s]))((?:\\\2|(?!\2).)*)(\2)',
intp_string_callback),
]
return states
tokens = {
'root': [
(r'#.*?$', Comment.Single),
(r'=begin\s.*?\n=end.*?$', Comment.Multiline),
# keywords
(r'(BEGIN|END|alias|begin|break|case|defined\?|'
r'do|else|elsif|end|ensure|for|if|in|next|redo|'
r'rescue|raise|retry|return|super|then|undef|unless|until|when|'
r'while|yield)\b', Keyword),
# start of function, class and module names
(r'(module)(\s+)([a-zA-Z_][a-zA-Z0-9_]*'
r'(?:::[a-zA-Z_][a-zA-Z0-9_]*)*)',
bygroups(Keyword, Text, Name.Namespace)),
(r'(def)(\s+)', bygroups(Keyword, Text), 'funcname'),
(r'def(?=[*%&^`~+-/\[<>=])', Keyword, 'funcname'),
(r'(class)(\s+)', bygroups(Keyword, Text), 'classname'),
# special methods
(r'(initialize|new|loop|include|extend|raise|attr_reader|'
r'attr_writer|attr_accessor|attr|catch|throw|private|'
r'module_function|public|protected|true|false|nil)\b',
Keyword.Pseudo),
(r'(not|and|or)\b', Operator.Word),
(r'(autoload|block_given|const_defined|eql|equal|frozen|include|'
r'instance_of|is_a|iterator|kind_of|method_defined|nil|'
r'private_method_defined|protected_method_defined|'
r'public_method_defined|respond_to|tainted)\?', Name.Builtin),
(r'(chomp|chop|exit|gsub|sub)!', Name.Builtin),
(r'(?<!\.)(Array|Float|Integer|String|__id__|__send__|abort|'
r'ancestors|at_exit|autoload|binding|callcc|caller|'
r'catch|chomp|chop|class_eval|class_variables|'
r'clone|const_defined\?|const_get|const_missing|const_set|'
r'constants|display|dup|eval|exec|exit|extend|fail|fork|'
r'format|freeze|getc|gets|global_variables|gsub|'
r'hash|id|included_modules|inspect|instance_eval|'
r'instance_method|instance_methods|'
r'instance_variable_get|instance_variable_set|instance_variables|'
r'lambda|load|local_variables|loop|'
r'method|method_missing|methods|module_eval|name|'
r'object_id|open|p|print|printf|private_class_method|'
r'private_instance_methods|'
r'private_methods|proc|protected_instance_methods|'
r'protected_methods|public_class_method|'
r'public_instance_methods|public_methods|'
r'putc|puts|raise|rand|readline|readlines|require|'
r'scan|select|self|send|set_trace_func|singleton_methods|sleep|'
r'split|sprintf|srand|sub|syscall|system|taint|'
r'test|throw|to_a|to_s|trace_var|trap|untaint|untrace_var|'
r'warn)\b', Name.Builtin),
(r'__(FILE|LINE)__\b', Name.Builtin.Pseudo),
# normal heredocs
(r'(?<!\w)(<<-?)(["`\']?)([a-zA-Z_]\w*)(\2)(.*?\n)',
heredoc_callback),
# empty string heredocs
(r'(<<-?)("|\')()(\2)(.*?\n)', heredoc_callback),
(r'__END__', Comment.Preproc, 'end-part'),
# multiline regex (after keywords or assignments)
(r'(?:^|(?<=[=<>~!:])|'
r'(?<=(?:\s|;)when\s)|'
r'(?<=(?:\s|;)or\s)|'
r'(?<=(?:\s|;)and\s)|'
r'(?<=(?:\s|;|\.)index\s)|'
r'(?<=(?:\s|;|\.)scan\s)|'
r'(?<=(?:\s|;|\.)sub\s)|'
r'(?<=(?:\s|;|\.)sub!\s)|'
r'(?<=(?:\s|;|\.)gsub\s)|'
r'(?<=(?:\s|;|\.)gsub!\s)|'
r'(?<=(?:\s|;|\.)match\s)|'
r'(?<=(?:\s|;)if\s)|'
r'(?<=(?:\s|;)elsif\s)|'
r'(?<=^when\s)|'
r'(?<=^index\s)|'
r'(?<=^scan\s)|'
r'(?<=^sub\s)|'
r'(?<=^gsub\s)|'
r'(?<=^sub!\s)|'
r'(?<=^gsub!\s)|'
r'(?<=^match\s)|'
r'(?<=^if\s)|'
r'(?<=^elsif\s)'
r')(\s*)(/)', bygroups(Text, String.Regex), 'multiline-regex'),
# multiline regex (in method calls or subscripts)
(r'(?<=\(|,|\[)/', String.Regex, 'multiline-regex'),
# multiline regex (this time the funny no whitespace rule)
(r'(\s+)(/)(?![\s=])', bygroups(Text, String.Regex),
'multiline-regex'),
# lex numbers and ignore following regular expressions which
# are division operators in fact (grrrr. i hate that. any
# better ideas?)
# since pygments 0.7 we also eat a "?" operator after numbers
# so that the char operator does not work. Chars are not allowed
# there so that you can use the ternary operator.
# stupid example:
# x>=0?n[x]:""
(r'(0_?[0-7]+(?:_[0-7]+)*)(\s*)([/?])?',
bygroups(Number.Oct, Text, Operator)),
(r'(0x[0-9A-Fa-f]+(?:_[0-9A-Fa-f]+)*)(\s*)([/?])?',
bygroups(Number.Hex, Text, Operator)),
(r'(0b[01]+(?:_[01]+)*)(\s*)([/?])?',
bygroups(Number.Bin, Text, Operator)),
(r'([\d]+(?:_\d+)*)(\s*)([/?])?',
bygroups(Number.Integer, Text, Operator)),
# Names
(r'@@[a-zA-Z_][a-zA-Z0-9_]*', Name.Variable.Class),
(r'@[a-zA-Z_][a-zA-Z0-9_]*', Name.Variable.Instance),
(r'\$[a-zA-Z0-9_]+', Name.Variable.Global),
(r'\$[!@&`\'+~=/\\,;.<>_*$?:"]', Name.Variable.Global),
(r'\$-[0adFiIlpvw]', Name.Variable.Global),
(r'::', Operator),
include('strings'),
# chars
(r'\?(\\[MC]-)*' # modifiers
r'(\\([\\abefnrstv#"\']|x[a-fA-F0-9]{1,2}|[0-7]{1,3})|\S)'
r'(?!\w)',
String.Char),
(r'[A-Z][a-zA-Z0-9_]+', Name.Constant),
# this is needed because ruby attributes can look
# like keywords (class) or like this: ` ?!?
(r'(\.|::)([a-zA-Z_]\w*[\!\?]?|[*%&^`~+-/\[<>=])',
bygroups(Operator, Name)),
(r'[a-zA-Z_]\w*[\!\?]?', Name),
(r'(\[|\]|\*\*|<<?|>>?|>=|<=|<=>|=~|={3}|'
r'!~|&&?|\|\||\.{1,3})', Operator),
(r'[-+/*%=<>&!^|~]=?', Operator),
(r'[(){};,/?:\\]', Punctuation),
(r'\s+', Text)
],
'funcname': [
(r'\(', Punctuation, 'defexpr'),
(r'(?:([a-zA-Z_][a-zA-Z0-9_]*)(\.))?'
r'([a-zA-Z_]\w*[\!\?]?|\*\*?|[-+]@?|'
r'[/%&|^`~]|\[\]=?|<<|>>|<=?>|>=?|===?)',
bygroups(Name.Class, Operator, Name.Function), '#pop'),
(r'', Text, '#pop')
],
'classname': [
(r'\(', Punctuation, 'defexpr'),
(r'<<', Operator, '#pop'),
(r'[A-Z_]\w*', Name.Class, '#pop'),
(r'', Text, '#pop')
],
'defexpr': [
(r'(\))(\.|::)?', bygroups(Punctuation, Operator), '#pop'),
(r'\(', Operator, '#push'),
include('root')
],
'in-intp': [
('}', String.Interpol, '#pop'),
include('root'),
],
'string-intp': [
(r'#{', String.Interpol, 'in-intp'),
(r'#@@?[a-zA-Z_][a-zA-Z0-9_]*', String.Interpol),
(r'#\$[a-zA-Z_][a-zA-Z0-9_]*', String.Interpol)
],
'string-intp-escaped': [
include('string-intp'),
(r'\\([\\abefnrstv#"\']|x[a-fA-F0-9]{1,2}|[0-7]{1,3})',
String.Escape)
],
'interpolated-regex': [
include('string-intp'),
(r'[\\#]', String.Regex),
(r'[^\\#]+', String.Regex),
],
'interpolated-string': [
include('string-intp'),
(r'[\\#]', String.Other),
(r'[^\\#]+', String.Other),
],
'multiline-regex': [
include('string-intp'),
(r'\\\\', String.Regex),
(r'\\/', String.Regex),
(r'[\\#]', String.Regex),
(r'[^\\/#]+', String.Regex),
(r'/[mixounse]*', String.Regex, '#pop'),
],
'end-part': [
(r'.+', Comment.Preproc, '#pop')
]
}
tokens.update(gen_rubystrings_rules())
def analyse_text(text):
return shebang_matches(text, r'ruby(1\.\d)?')
class RubyConsoleLexer(Lexer):
"""
For Ruby interactive console (**irb**) output like:
.. sourcecode:: rbcon
irb(main):001:0> a = 1
=> 1
irb(main):002:0> puts a
1
=> nil
"""
name = 'Ruby irb session'
aliases = ['rbcon', 'irb']
mimetypes = ['text/x-ruby-shellsession']
_prompt_re = re.compile('irb\([a-zA-Z_][a-zA-Z0-9_]*\):\d{3}:\d+[>*"\'] '
'|>> |\?> ')
def get_tokens_unprocessed(self, text):
rblexer = RubyLexer(**self.options)
curcode = ''
insertions = []
for match in line_re.finditer(text):
line = match.group()
m = self._prompt_re.match(line)
if m is not None:
end = m.end()
insertions.append((len(curcode),
[(0, Generic.Prompt, line[:end])]))
curcode += line[end:]
else:
if curcode:
for item in do_insertions(insertions,
rblexer.get_tokens_unprocessed(curcode)):
yield item
curcode = ''
insertions = []
yield match.start(), Generic.Output, line
if curcode:
for item in do_insertions(insertions,
rblexer.get_tokens_unprocessed(curcode)):
yield item
class PerlLexer(RegexLexer):
"""
For `Perl <http://www.perl.org>`_ source code.
"""
name = 'Perl'
aliases = ['perl', 'pl']
filenames = ['*.pl', '*.pm']
mimetypes = ['text/x-perl', 'application/x-perl']
flags = re.DOTALL | re.MULTILINE
# TODO: give this to a perl guy who knows how to parse perl...
tokens = {
'balanced-regex': [
(r'/(\\\\|\\[^\\]|[^\\/])*/[egimosx]*', String.Regex, '#pop'),
(r'!(\\\\|\\[^\\]|[^\\!])*![egimosx]*', String.Regex, '#pop'),
(r'\\(\\\\|[^\\])*\\[egimosx]*', String.Regex, '#pop'),
(r'{(\\\\|\\[^\\]|[^\\}])*}[egimosx]*', String.Regex, '#pop'),
(r'<(\\\\|\\[^\\]|[^\\>])*>[egimosx]*', String.Regex, '#pop'),
(r'\[(\\\\|\\[^\\]|[^\\\]])*\][egimosx]*', String.Regex, '#pop'),
(r'\((\\\\|\\[^\\]|[^\\\)])*\)[egimosx]*', String.Regex, '#pop'),
(r'@(\\\\|\\[^\\]|[^\\\@])*@[egimosx]*', String.Regex, '#pop'),
(r'%(\\\\|\\[^\\]|[^\\\%])*%[egimosx]*', String.Regex, '#pop'),
(r'\$(\\\\|\\[^\\]|[^\\\$])*\$[egimosx]*', String.Regex, '#pop'),
],
'root': [
(r'\#.*?$', Comment.Single),
(r'^=[a-zA-Z0-9]+\s+.*?\n=cut', Comment.Multiline),
(r'(case|continue|do|else|elsif|for|foreach|if|last|my|'
r'next|our|redo|reset|then|unless|until|while|use|'
r'print|new|BEGIN|CHECK|INIT|END|return)\b', Keyword),
(r'(format)(\s+)([a-zA-Z0-9_]+)(\s*)(=)(\s*\n)',
bygroups(Keyword, Text, Name, Text, Punctuation, Text), 'format'),
(r'(eq|lt|gt|le|ge|ne|not|and|or|cmp)\b', Operator.Word),
# common delimiters
(r's/(\\\\|\\[^\\]|[^\\/])*/(\\\\|\\[^\\]|[^\\/])*/[egimosx]*',
String.Regex),
(r's!(\\\\|\\!|[^!])*!(\\\\|\\!|[^!])*![egimosx]*', String.Regex),
(r's\\(\\\\|[^\\])*\\(\\\\|[^\\])*\\[egimosx]*', String.Regex),
(r's@(\\\\|\\[^\\]|[^\\@])*@(\\\\|\\[^\\]|[^\\@])*@[egimosx]*',
String.Regex),
(r's%(\\\\|\\[^\\]|[^\\%])*%(\\\\|\\[^\\]|[^\\%])*%[egimosx]*',
String.Regex),
# balanced delimiters
(r's{(\\\\|\\[^\\]|[^\\}])*}\s*', String.Regex, 'balanced-regex'),
(r's<(\\\\|\\[^\\]|[^\\>])*>\s*', String.Regex, 'balanced-regex'),
(r's\[(\\\\|\\[^\\]|[^\\\]])*\]\s*', String.Regex,
'balanced-regex'),
(r's\((\\\\|\\[^\\]|[^\\\)])*\)\s*', String.Regex,
'balanced-regex'),
(r'm?/(\\\\|\\[^\\]|[^\\/\n])*/[gcimosx]*', String.Regex),
(r'm(?=[/!\\{<\[\(@%\$])', String.Regex, 'balanced-regex'),
(r'((?<==~)|(?<=\())\s*/(\\\\|\\[^\\]|[^\\/])*/[gcimosx]*',
String.Regex),
(r'\s+', Text),
(r'(abs|accept|alarm|atan2|bind|binmode|bless|caller|chdir|'
r'chmod|chomp|chop|chown|chr|chroot|close|closedir|connect|'
r'continue|cos|crypt|dbmclose|dbmopen|defined|delete|die|'
r'dump|each|endgrent|endhostent|endnetent|endprotoent|'
r'endpwent|endservent|eof|eval|exec|exists|exit|exp|fcntl|'
r'fileno|flock|fork|format|formline|getc|getgrent|getgrgid|'
r'getgrnam|gethostbyaddr|gethostbyname|gethostent|getlogin|'
r'getnetbyaddr|getnetbyname|getnetent|getpeername|getpgrp|'
r'getppid|getpriority|getprotobyname|getprotobynumber|'
r'getprotoent|getpwent|getpwnam|getpwuid|getservbyname|'
r'getservbyport|getservent|getsockname|getsockopt|glob|gmtime|'
r'goto|grep|hex|import|index|int|ioctl|join|keys|kill|last|'
r'lc|lcfirst|length|link|listen|local|localtime|log|lstat|'
r'map|mkdir|msgctl|msgget|msgrcv|msgsnd|my|next|no|oct|open|'
r'opendir|ord|our|pack|package|pipe|pop|pos|printf|'
r'prototype|push|quotemeta|rand|read|readdir|'
r'readline|readlink|readpipe|recv|redo|ref|rename|require|'
r'reverse|rewinddir|rindex|rmdir|scalar|seek|seekdir|'
r'select|semctl|semget|semop|send|setgrent|sethostent|setnetent|'
r'setpgrp|setpriority|setprotoent|setpwent|setservent|'
r'setsockopt|shift|shmctl|shmget|shmread|shmwrite|shutdown|'
r'sin|sleep|socket|socketpair|sort|splice|split|sprintf|sqrt|'
r'srand|stat|study|substr|symlink|syscall|sysopen|sysread|'
r'sysseek|system|syswrite|tell|telldir|tie|tied|time|times|tr|'
r'truncate|uc|ucfirst|umask|undef|unlink|unpack|unshift|untie|'
r'utime|values|vec|wait|waitpid|wantarray|warn|write'
r')\b', Name.Builtin),
(r'((__(DATA|DIE|WARN)__)|(STD(IN|OUT|ERR)))\b', Name.Builtin.Pseudo),
(r'<<([\'"]?)([a-zA-Z_][a-zA-Z0-9_]*)\1;?\n.*?\n\2\n', String),
(r'__END__', Comment.Preproc, 'end-part'),
(r'\$\^[ADEFHILMOPSTWX]', Name.Variable.Global),
(r"\$[\\\"\[\]'&`+*.,;=%~?@$!<>(^|/-](?!\w)", Name.Variable.Global),
(r'[$@%#]+', Name.Variable, 'varname'),
(r'0_?[0-7]+(_[0-7]+)*', Number.Oct),
(r'0x[0-9A-Fa-f]+(_[0-9A-Fa-f]+)*', Number.Hex),
(r'0b[01]+(_[01]+)*', Number.Bin),
(r'(?i)(\d*(_\d*)*\.\d+(_\d*)*|\d+(_\d*)*\.\d+(_\d*)*)(e[+-]?\d+)?',
Number.Float),
(r'(?i)\d+(_\d*)*e[+-]?\d+(_\d*)*', Number.Float),
(r'\d+(_\d+)*', Number.Integer),
(r"'(\\\\|\\[^\\]|[^'\\])*'", String),
(r'"(\\\\|\\[^\\]|[^"\\])*"', String),
(r'`(\\\\|\\[^\\]|[^`\\])*`', String.Backtick),
(r'<([^\s>]+)>', String.Regex),
(r'(q|qq|qw|qr|qx)\{', String.Other, 'cb-string'),
(r'(q|qq|qw|qr|qx)\(', String.Other, 'rb-string'),
(r'(q|qq|qw|qr|qx)\[', String.Other, 'sb-string'),
(r'(q|qq|qw|qr|qx)\<', String.Other, 'lt-string'),
(r'(q|qq|qw|qr|qx)([^a-zA-Z0-9])(.|\n)*?\2', String.Other),
(r'package\s+', Keyword, 'modulename'),
(r'sub\s+', Keyword, 'funcname'),
(r'(\[\]|\*\*|::|<<|>>|>=|<=>|<=|={3}|!=|=~|'
r'!~|&&?|\|\||\.{1,3})', Operator),
(r'[-+/*%=<>&^|!\\~]=?', Operator),
(r'[\(\)\[\]:;,<>/\?\{\}]', Punctuation), # yes, there's no shortage
# of punctuation in Perl!
(r'(?=\w)', Name, 'name'),
],
'format': [
(r'\.\n', String.Interpol, '#pop'),
(r'[^\n]*\n', String.Interpol),
],
'varname': [
(r'\s+', Text),
(r'\{', Punctuation, '#pop'), # hash syntax?
(r'\)|,', Punctuation, '#pop'), # argument specifier
(r'[a-zA-Z0-9_]+::', Name.Namespace),
(r'[a-zA-Z0-9_:]+', Name.Variable, '#pop'),
],
'name': [
(r'[a-zA-Z0-9_]+::', Name.Namespace),
(r'[a-zA-Z0-9_:]+', Name, '#pop'),
(r'[A-Z_]+(?=[^a-zA-Z0-9_])', Name.Constant, '#pop'),
(r'(?=[^a-zA-Z0-9_])', Text, '#pop'),
],
'modulename': [
(r'[a-zA-Z_]\w*', Name.Namespace, '#pop')
],
'funcname': [
(r'[a-zA-Z_]\w*[\!\?]?', Name.Function),
(r'\s+', Text),
# argument declaration
(r'(\([$@%]*\))(\s*)', bygroups(Punctuation, Text)),
(r'.*?{', Punctuation, '#pop'),
(r';', Punctuation, '#pop'),
],
'cb-string': [
(r'\\[\{\}\\]', String.Other),
(r'\\', String.Other),
(r'\{', String.Other, 'cb-string'),
(r'\}', String.Other, '#pop'),
(r'[^\{\}\\]+', String.Other)
],
'rb-string': [
(r'\\[\(\)\\]', String.Other),
(r'\\', String.Other),
(r'\(', String.Other, 'rb-string'),
(r'\)', String.Other, '#pop'),
(r'[^\(\)]+', String.Other)
],
'sb-string': [
(r'\\[\[\]\\]', String.Other),
(r'\\', String.Other),
(r'\[', String.Other, 'sb-string'),
(r'\]', String.Other, '#pop'),
(r'[^\[\]]+', String.Other)
],
'lt-string': [
(r'\\[\<\>\\]', String.Other),
(r'\\', String.Other),
(r'\<', String.Other, 'lt-string'),
(r'\>', String.Other, '#pop'),
(r'[^\<\>]+', String.Other)
],
'end-part': [
(r'.+', Comment.Preproc, '#pop')
]
}
def analyse_text(text):
if shebang_matches(text, r'perl'):
return True
if 'my $' in text:
return 0.9
return 0.1 # who knows, might still be perl!
class LuaLexer(RegexLexer):
"""
For `Lua <http://www.lua.org>`_ source code.
Additional options accepted:
`func_name_highlighting`
If given and ``True``, highlight builtin function names
(default: ``True``).
`disabled_modules`
If given, must be a list of module names whose function names
should not be highlighted. By default all modules are highlighted.
To get a list of allowed modules have a look into the
`_luabuiltins` module:
.. sourcecode:: pycon
>>> from pygments.lexers._luabuiltins import MODULES
>>> MODULES.keys()
['string', 'coroutine', 'modules', 'io', 'basic', ...]
"""
name = 'Lua'
aliases = ['lua']
filenames = ['*.lua', '*.wlua']
mimetypes = ['text/x-lua', 'application/x-lua']
tokens = {
'root': [
# lua allows a file to start with a shebang
(r'#!(.*?)$', Comment.Preproc),
(r'', Text, 'base'),
],
'base': [
(r'(?s)--\[(=*)\[.*?\]\1\]', Comment.Multiline),
('--.*$', Comment.Single),
(r'(?i)(\d*\.\d+|\d+\.\d*)(e[+-]?\d+)?', Number.Float),
(r'(?i)\d+e[+-]?\d+', Number.Float),
('(?i)0x[0-9a-f]*', Number.Hex),
(r'\d+', Number.Integer),
(r'\n', Text),
(r'[^\S\n]', Text),
# multiline strings
(r'(?s)\[(=*)\[.*?\]\1\]', String),
(r'(==|~=|<=|>=|\.\.\.|\.\.|[=+\-*/%^<>#])', Operator),
(r'[\[\]\{\}\(\)\.,:;]', Punctuation),
(r'(and|or|not)\b', Operator.Word),
('(break|do|else|elseif|end|for|if|in|repeat|return|then|until|'
r'while)\b', Keyword),
(r'(local)\b', Keyword.Declaration),
(r'(true|false|nil)\b', Keyword.Constant),
(r'(function)\b', Keyword, 'funcname'),
(r'[A-Za-z_][A-Za-z0-9_]*(\.[A-Za-z_][A-Za-z0-9_]*)?', Name),
("'", String.Single, combined('stringescape', 'sqs')),
('"', String.Double, combined('stringescape', 'dqs'))
],
'funcname': [
(r'\s+', Text),
('(?:([A-Za-z_][A-Za-z0-9_]*)(\.))?([A-Za-z_][A-Za-z0-9_]*)',
bygroups(Name.Class, Punctuation, Name.Function), '#pop'),
# inline function
('\(', Punctuation, '#pop'),
],
# if I understand correctly, every character is valid in a lua string,
# so this state is only for later corrections
'string': [
('.', String)
],
'stringescape': [
(r'''\\([abfnrtv\\"']|\d{1,3})''', String.Escape)
],
'sqs': [
("'", String, '#pop'),
include('string')
],
'dqs': [
('"', String, '#pop'),
include('string')
]
}
def __init__(self, **options):
self.func_name_highlighting = get_bool_opt(
options, 'func_name_highlighting', True)
self.disabled_modules = get_list_opt(options, 'disabled_modules', [])
self._functions = set()
if self.func_name_highlighting:
from pygments.lexers._luabuiltins import MODULES
for mod, func in MODULES.iteritems():
if mod not in self.disabled_modules:
self._functions.update(func)
RegexLexer.__init__(self, **options)
def get_tokens_unprocessed(self, text):
for index, token, value in \
RegexLexer.get_tokens_unprocessed(self, text):
if token is Name:
if value in self._functions:
yield index, Name.Builtin, value
continue
elif '.' in value:
a, b = value.split('.')
yield index, Name, a
yield index + len(a), Punctuation, u'.'
yield index + len(a) + 1, Name, b
continue
yield index, token, value
class MoonScriptLexer(LuaLexer):
"""
For `MoonScript <http://moonscript.org.org>`_ source code.
*New in Pygments 1.5.*
"""
name = "MoonScript"
aliases = ["moon", "moonscript"]
filenames = ["*.moon"]
mimetypes = ['text/x-moonscript', 'application/x-moonscript']
tokens = {
'root': [
(r'#!(.*?)$', Comment.Preproc),
(r'', Text, 'base'),
],
'base': [
('--.*$', Comment.Single),
(r'(?i)(\d*\.\d+|\d+\.\d*)(e[+-]?\d+)?', Number.Float),
(r'(?i)\d+e[+-]?\d+', Number.Float),
(r'(?i)0x[0-9a-f]*', Number.Hex),
(r'\d+', Number.Integer),
(r'\n', Text),
(r'[^\S\n]+', Text),
(r'(?s)\[(=*)\[.*?\]\1\]', String),
(r'(->|=>)', Name.Function),
(r':[a-zA-Z_][a-zA-Z0-9_]*', Name.Variable),
(r'(==|!=|~=|<=|>=|\.\.\.|\.\.|[=+\-*/%^<>#!.\\:])', Operator),
(r'[;,]', Punctuation),
(r'[\[\]\{\}\(\)]', Keyword.Type),
(r'[a-zA-Z_][a-zA-Z0-9_]*:', Name.Variable),
(r"(class|extends|if|then|super|do|with|import|export|"
r"while|elseif|return|for|in|from|when|using|else|"
r"and|or|not|switch|break)\b", Keyword),
(r'(true|false|nil)\b', Keyword.Constant),
(r'(and|or|not)\b', Operator.Word),
(r'(self)\b', Name.Builtin.Pseudo),
(r'@@?([a-zA-Z_][a-zA-Z0-9_]*)?', Name.Variable.Class),
(r'[A-Z]\w*', Name.Class), # proper name
(r'[A-Za-z_][A-Za-z0-9_]*(\.[A-Za-z_][A-Za-z0-9_]*)?', Name),
("'", String.Single, combined('stringescape', 'sqs')),
('"', String.Double, combined('stringescape', 'dqs'))
],
'stringescape': [
(r'''\\([abfnrtv\\"']|\d{1,3})''', String.Escape)
],
'sqs': [
("'", String.Single, '#pop'),
(".", String)
],
'dqs': [
('"', String.Double, '#pop'),
(".", String)
]
}
def get_tokens_unprocessed(self, text):
# set . as Operator instead of Punctuation
for index, token, value in \
LuaLexer.get_tokens_unprocessed(self, text):
if token == Punctuation and value == ".":
token = Operator
yield index, token, value
class CrocLexer(RegexLexer):
"""
For `Croc <http://jfbillingsley.com/croc>`_ source.
"""
name = 'Croc'
filenames = ['*.croc']
aliases = ['croc']
mimetypes = ['text/x-crocsrc']
tokens = {
'root': [
(r'\n', Text),
(r'\s+', Text),
# Comments
(r'//(.*?)\n', Comment.Single),
(r'/\*', Comment.Multiline, 'nestedcomment'),
# Keywords
(r'(as|assert|break|case|catch|class|continue|default'
r'|do|else|finally|for|foreach|function|global|namespace'
r'|if|import|in|is|local|module|return|scope|super|switch'
r'|this|throw|try|vararg|while|with|yield)\b', Keyword),
(r'(false|true|null)\b', Keyword.Constant),
# FloatLiteral
(r'([0-9][0-9_]*)(?=[.eE])(\.[0-9][0-9_]*)?([eE][+\-]?[0-9_]+)?',
Number.Float),
# IntegerLiteral
# -- Binary
(r'0[bB][01][01_]*', Number),
# -- Hexadecimal
(r'0[xX][0-9a-fA-F][0-9a-fA-F_]*', Number.Hex),
# -- Decimal
(r'([0-9][0-9_]*)(?![.eE])', Number.Integer),
# CharacterLiteral
(r"""'(\\['"\\nrt]|\\x[0-9a-fA-F]{2}|\\[0-9]{1,3}"""
r"""|\\u[0-9a-fA-F]{4}|\\U[0-9a-fA-F]{8}|.)'""",
String.Char
),
# StringLiteral
# -- WysiwygString
(r'@"(""|[^"])*"', String),
(r'@`(``|[^`])*`', String),
(r"@'(''|[^'])*'", String),
# -- DoubleQuotedString
(r'"(\\\\|\\"|[^"])*"', String),
# Tokens
(
r'(~=|\^=|%=|\*=|==|!=|>>>=|>>>|>>=|>>|>=|<=>|\?=|-\>'
r'|<<=|<<|<=|\+\+|\+=|--|-=|\|\||\|=|&&|&=|\.\.|/=)'
r'|[-/.&$@|\+<>!()\[\]{}?,;:=*%^~#\\]', Punctuation
),
# Identifier
(r'[a-zA-Z_]\w*', Name),
],
'nestedcomment': [
(r'[^*/]+', Comment.Multiline),
(r'/\*', Comment.Multiline, '#push'),
(r'\*/', Comment.Multiline, '#pop'),
(r'[*/]', Comment.Multiline),
],
}
class MiniDLexer(CrocLexer):
"""
For MiniD source. MiniD is now known as Croc.
"""
name = 'MiniD'
filenames = ['*.md']
aliases = ['minid']
mimetypes = ['text/x-minidsrc']
class IoLexer(RegexLexer):
"""
For `Io <http://iolanguage.com/>`_ (a small, prototype-based
programming language) source.
*New in Pygments 0.10.*
"""
name = 'Io'
filenames = ['*.io']
aliases = ['io']
mimetypes = ['text/x-iosrc']
tokens = {
'root': [
(r'\n', Text),
(r'\s+', Text),
# Comments
(r'//(.*?)\n', Comment.Single),
(r'#(.*?)\n', Comment.Single),
(r'/(\\\n)?[*](.|\n)*?[*](\\\n)?/', Comment.Multiline),
(r'/\+', Comment.Multiline, 'nestedcomment'),
# DoubleQuotedString
(r'"(\\\\|\\"|[^"])*"', String),
# Operators
(r'::=|:=|=|\(|\)|;|,|\*|-|\+|>|<|@|!|/|\||\^|\.|%|&|\[|\]|\{|\}',
Operator),
# keywords
(r'(clone|do|doFile|doString|method|for|if|else|elseif|then)\b',
Keyword),
# constants
(r'(nil|false|true)\b', Name.Constant),
# names
(r'(Object|list|List|Map|args|Sequence|Coroutine|File)\b',
Name.Builtin),
('[a-zA-Z_][a-zA-Z0-9_]*', Name),
# numbers
(r'(\d+\.?\d*|\d*\.\d+)([eE][+-]?[0-9]+)?', Number.Float),
(r'\d+', Number.Integer)
],
'nestedcomment': [
(r'[^+/]+', Comment.Multiline),
(r'/\+', Comment.Multiline, '#push'),
(r'\+/', Comment.Multiline, '#pop'),
(r'[+/]', Comment.Multiline),
]
}
class TclLexer(RegexLexer):
"""
For Tcl source code.
*New in Pygments 0.10.*
"""
keyword_cmds_re = (
r'\b(after|apply|array|break|catch|continue|elseif|else|error|'
r'eval|expr|for|foreach|global|if|namespace|proc|rename|return|'
r'set|switch|then|trace|unset|update|uplevel|upvar|variable|'
r'vwait|while)\b'
)
builtin_cmds_re = (
r'\b(append|bgerror|binary|cd|chan|clock|close|concat|dde|dict|'
r'encoding|eof|exec|exit|fblocked|fconfigure|fcopy|file|'
r'fileevent|flush|format|gets|glob|history|http|incr|info|interp|'
r'join|lappend|lassign|lindex|linsert|list|llength|load|loadTk|'
r'lrange|lrepeat|lreplace|lreverse|lsearch|lset|lsort|mathfunc|'
r'mathop|memory|msgcat|open|package|pid|pkg::create|pkg_mkIndex|'
r'platform|platform::shell|puts|pwd|re_syntax|read|refchan|'
r'regexp|registry|regsub|scan|seek|socket|source|split|string|'
r'subst|tell|time|tm|unknown|unload)\b'
)
name = 'Tcl'
aliases = ['tcl']
filenames = ['*.tcl']
mimetypes = ['text/x-tcl', 'text/x-script.tcl', 'application/x-tcl']
def _gen_command_rules(keyword_cmds_re, builtin_cmds_re, context=""):
return [
(keyword_cmds_re, Keyword, 'params' + context),
(builtin_cmds_re, Name.Builtin, 'params' + context),
(r'([\w\.\-]+)', Name.Variable, 'params' + context),
(r'#', Comment, 'comment'),
]
tokens = {
'root': [
include('command'),
include('basic'),
include('data'),
(r'}', Keyword), # HACK: somehow we miscounted our braces
],
'command': _gen_command_rules(keyword_cmds_re, builtin_cmds_re),
'command-in-brace': _gen_command_rules(keyword_cmds_re,
builtin_cmds_re,
"-in-brace"),
'command-in-bracket': _gen_command_rules(keyword_cmds_re,
builtin_cmds_re,
"-in-bracket"),
'command-in-paren': _gen_command_rules(keyword_cmds_re,
builtin_cmds_re,
"-in-paren"),
'basic': [
(r'\(', Keyword, 'paren'),
(r'\[', Keyword, 'bracket'),
(r'\{', Keyword, 'brace'),
(r'"', String.Double, 'string'),
(r'(eq|ne|in|ni)\b', Operator.Word),
(r'!=|==|<<|>>|<=|>=|&&|\|\||\*\*|[-+~!*/%<>&^|?:]', Operator),
],
'data': [
(r'\s+', Text),
(r'0x[a-fA-F0-9]+', Number.Hex),
(r'0[0-7]+', Number.Oct),
(r'\d+\.\d+', Number.Float),
(r'\d+', Number.Integer),
(r'\$([\w\.\-\:]+)', Name.Variable),
(r'([\w\.\-\:]+)', Text),
],
'params': [
(r';', Keyword, '#pop'),
(r'\n', Text, '#pop'),
(r'(else|elseif|then)\b', Keyword),
include('basic'),
include('data'),
],
'params-in-brace': [
(r'}', Keyword, ('#pop', '#pop')),
include('params')
],
'params-in-paren': [
(r'\)', Keyword, ('#pop', '#pop')),
include('params')
],
'params-in-bracket': [
(r'\]', Keyword, ('#pop', '#pop')),
include('params')
],
'string': [
(r'\[', String.Double, 'string-square'),
(r'(?s)(\\\\|\\[0-7]+|\\.|[^"\\])', String.Double),
(r'"', String.Double, '#pop')
],
'string-square': [
(r'\[', String.Double, 'string-square'),
(r'(?s)(\\\\|\\[0-7]+|\\.|\\\n|[^\]\\])', String.Double),
(r'\]', String.Double, '#pop')
],
'brace': [
(r'}', Keyword, '#pop'),
include('command-in-brace'),
include('basic'),
include('data'),
],
'paren': [
(r'\)', Keyword, '#pop'),
include('command-in-paren'),
include('basic'),
include('data'),
],
'bracket': [
(r'\]', Keyword, '#pop'),
include('command-in-bracket'),
include('basic'),
include('data'),
],
'comment': [
(r'.*[^\\]\n', Comment, '#pop'),
(r'.*\\\n', Comment),
],
}
def analyse_text(text):
return shebang_matches(text, r'(tcl)')
class FactorLexer(RegexLexer):
"""
Lexer for the `Factor <http://factorcode.org>`_ language.
*New in Pygments 1.4.*
"""
name = 'Factor'
aliases = ['factor']
filenames = ['*.factor']
mimetypes = ['text/x-factor']
flags = re.MULTILINE | re.UNICODE
builtin_kernel = (
r'(?:or|2bi|2tri|while|wrapper|nip|4dip|wrapper\\?|bi\\*|'
r'callstack>array|both\\?|hashcode|die|dupd|callstack|'
r'callstack\\?|3dup|tri@|pick|curry|build|\\?execute|3bi|'
r'prepose|>boolean|\\?if|clone|eq\\?|tri\\*|\\?|=|swapd|'
r'2over|2keep|3keep|clear|2dup|when|not|tuple\\?|dup|2bi\\*|'
r'2tri\\*|call|tri-curry|object|bi@|do|unless\\*|if\\*|loop|'
r'bi-curry\\*|drop|when\\*|assert=|retainstack|assert\\?|-rot|'
r'execute|2bi@|2tri@|boa|with|either\\?|3drop|bi|curry\\?|'
r'datastack|until|3dip|over|3curry|tri-curry\\*|tri-curry@|swap|'
r'and|2nip|throw|bi-curry|\\(clone\\)|hashcode\\*|compose|2dip|if|3tri|'
r'unless|compose\\?|tuple|keep|2curry|equal\\?|assert|tri|2drop|'
r'most|<wrapper>|boolean\\?|identity-hashcode|identity-tuple\\?|'
r'null|new|dip|bi-curry@|rot|xor|identity-tuple|boolean)\s'
)
builtin_assocs = (
r'(?:\\?at|assoc\\?|assoc-clone-like|assoc=|delete-at\\*|'
r'assoc-partition|extract-keys|new-assoc|value\\?|assoc-size|'
r'map>assoc|push-at|assoc-like|key\\?|assoc-intersect|'
r'assoc-refine|update|assoc-union|assoc-combine|at\\*|'
r'assoc-empty\\?|at\\+|set-at|assoc-all\\?|assoc-subset\\?|'
r'assoc-hashcode|change-at|assoc-each|assoc-diff|zip|values|'
r'value-at|rename-at|inc-at|enum\\?|at|cache|assoc>map|<enum>|'
r'assoc|assoc-map|enum|value-at\\*|assoc-map-as|>alist|'
r'assoc-filter-as|clear-assoc|assoc-stack|maybe-set-at|'
r'substitute|assoc-filter|2cache|delete-at|assoc-find|keys|'
r'assoc-any\\?|unzip)\s'
)
builtin_combinators = (
r'(?:case|execute-effect|no-cond|no-case\\?|3cleave>quot|2cleave|'
r'cond>quot|wrong-values\\?|no-cond\\?|cleave>quot|no-case|'
r'case>quot|3cleave|wrong-values|to-fixed-point|alist>quot|'
r'case-find|cond|cleave|call-effect|2cleave>quot|recursive-hashcode|'
r'linear-case-quot|spread|spread>quot)\s'
)
builtin_math = (
r'(?:number=|if-zero|next-power-of-2|each-integer|\\?1\\+|'
r'fp-special\\?|imaginary-part|unless-zero|float>bits|number\\?|'
r'fp-infinity\\?|bignum\\?|fp-snan\\?|denominator|fp-bitwise=|\\*|'
r'\\+|power-of-2\\?|-|u>=|/|>=|bitand|log2-expects-positive|<|'
r'log2|>|integer\\?|number|bits>double|2/|zero\\?|(find-integer)|'
r'bits>float|float\\?|shift|ratio\\?|even\\?|ratio|fp-sign|bitnot|'
r'>fixnum|complex\\?|/i|/f|byte-array>bignum|when-zero|sgn|>bignum|'
r'next-float|u<|u>|mod|recip|rational|find-last-integer|>float|'
r'(all-integers\\?)|2^|times|integer|fixnum\\?|neg|fixnum|sq|'
r'bignum|(each-integer)|bit\\?|fp-qnan\\?|find-integer|complex|'
r'<fp-nan>|real|double>bits|bitor|rem|fp-nan-payload|all-integers\\?|'
r'real-part|log2-expects-positive\\?|prev-float|align|unordered\\?|'
r'float|fp-nan\\?|abs|bitxor|u<=|odd\\?|<=|/mod|rational\\?|>integer|'
r'real\\?|numerator)\s'
)
builtin_sequences = (
r'(?:member-eq\\?|append|assert-sequence=|find-last-from|trim-head-slice|'
r'clone-like|3sequence|assert-sequence\\?|map-as|last-index-from|'
r'reversed|index-from|cut\\*|pad-tail|remove-eq!|concat-as|'
r'but-last|snip|trim-tail|nths|nth|2selector|sequence|slice\\?|'
r'<slice>|partition|remove-nth|tail-slice|empty\\?|tail\\*|'
r'if-empty|find-from|virtual-sequence\\?|member\\?|set-length|'
r'drop-prefix|unclip|unclip-last-slice|iota|map-sum|'
r'bounds-error\\?|sequence-hashcode-step|selector-for|'
r'accumulate-as|map|start|midpoint@|\\(accumulate\\)|rest-slice|'
r'prepend|fourth|sift|accumulate!|new-sequence|follow|map!|'
r'like|first4|1sequence|reverse|slice|unless-empty|padding|'
r'virtual@|repetition\\?|set-last|index|4sequence|max-length|'
r'set-second|immutable-sequence|first2|first3|replicate-as|'
r'reduce-index|unclip-slice|supremum|suffix!|insert-nth|'
r'trim-tail-slice|tail|3append|short|count|suffix|concat|'
r'flip|filter|sum|immutable\\?|reverse!|2sequence|map-integers|'
r'delete-all|start\\*|indices|snip-slice|check-slice|sequence\\?|'
r'head|map-find|filter!|append-as|reduce|sequence=|halves|'
r'collapse-slice|interleave|2map|filter-as|binary-reduce|'
r'slice-error\\?|product|bounds-check\\?|bounds-check|harvest|'
r'immutable|virtual-exemplar|find|produce|remove|pad-head|last|'
r'replicate|set-fourth|remove-eq|shorten|reversed\\?|'
r'map-find-last|3map-as|2unclip-slice|shorter\\?|3map|find-last|'
r'head-slice|pop\\*|2map-as|tail-slice\\*|but-last-slice|'
r'2map-reduce|iota\\?|collector-for|accumulate|each|selector|'
r'append!|new-resizable|cut-slice|each-index|head-slice\\*|'
r'2reverse-each|sequence-hashcode|pop|set-nth|\\?nth|'
r'<flat-slice>|second|join|when-empty|collector|'
r'immutable-sequence\\?|<reversed>|all\\?|3append-as|'
r'virtual-sequence|subseq\\?|remove-nth!|push-either|new-like|'
r'length|last-index|push-if|2all\\?|lengthen|assert-sequence|'
r'copy|map-reduce|move|third|first|3each|tail\\?|set-first|'
r'prefix|bounds-error|any\\?|<repetition>|trim-slice|exchange|'
r'surround|2reduce|cut|change-nth|min-length|set-third|produce-as|'
r'push-all|head\\?|delete-slice|rest|sum-lengths|2each|head\\*|'
r'infimum|remove!|glue|slice-error|subseq|trim|replace-slice|'
r'push|repetition|map-index|trim-head|unclip-last|mismatch)\s'
)
builtin_namespaces = (
r'(?:global|\\+@|change|set-namestack|change-global|init-namespaces|'
r'on|off|set-global|namespace|set|with-scope|bind|with-variable|'
r'inc|dec|counter|initialize|namestack|get|get-global|make-assoc)\s'
)
builtin_arrays = (
r'(?:<array>|2array|3array|pair|>array|1array|4array|pair\\?|'
r'array|resize-array|array\\?)\s'
)
builtin_io = (
r'(?:\\+character\\+|bad-seek-type\\?|readln|each-morsel|stream-seek|'
r'read|print|with-output-stream|contents|write1|stream-write1|'
r'stream-copy|stream-element-type|with-input-stream|'
r'stream-print|stream-read|stream-contents|stream-tell|'
r'tell-output|bl|seek-output|bad-seek-type|nl|stream-nl|write|'
r'flush|stream-lines|\\+byte\\+|stream-flush|read1|'
r'seek-absolute\\?|stream-read1|lines|stream-readln|'
r'stream-read-until|each-line|seek-end|with-output-stream\\*|'
r'seek-absolute|with-streams|seek-input|seek-relative\\?|'
r'input-stream|stream-write|read-partial|seek-end\\?|'
r'seek-relative|error-stream|read-until|with-input-stream\\*|'
r'with-streams\\*|tell-input|each-block|output-stream|'
r'stream-read-partial|each-stream-block|each-stream-line)\s'
)
builtin_strings = (
r'(?:resize-string|>string|<string>|1string|string|string\\?)\s'
)
builtin_vectors = (
r'(?:vector\\?|<vector>|\\?push|vector|>vector|1vector)\s'
)
builtin_continuations = (
r'(?:with-return|restarts|return-continuation|with-datastack|'
r'recover|rethrow-restarts|<restart>|ifcc|set-catchstack|'
r'>continuation<|cleanup|ignore-errors|restart\\?|'
r'compute-restarts|attempt-all-error|error-thread|continue|'
r'<continuation>|attempt-all-error\\?|condition\\?|'
r'<condition>|throw-restarts|error|catchstack|continue-with|'
r'thread-error-hook|continuation|rethrow|callcc1|'
r'error-continuation|callcc0|attempt-all|condition|'
r'continuation\\?|restart|return)\s'
)
tokens = {
'root': [
# TODO: (( inputs -- outputs ))
# TODO: << ... >>
# defining words
(r'(\s*)(:|::|MACRO:|MEMO:)(\s+)(\S+)',
bygroups(Text, Keyword, Text, Name.Function)),
(r'(\s*)(M:)(\s+)(\S+)(\s+)(\S+)',
bygroups(Text, Keyword, Text, Name.Class, Text, Name.Function)),
(r'(\s*)(GENERIC:)(\s+)(\S+)',
bygroups(Text, Keyword, Text, Name.Function)),
(r'(\s*)(HOOK:|GENERIC#)(\s+)(\S+)(\s+)(\S+)',
bygroups(Text, Keyword, Text, Name.Function, Text, Name.Function)),
(r'(\()(\s+)', bygroups(Name.Function, Text), 'stackeffect'),
(r'\;\s', Keyword),
# imports and namespaces
(r'(USING:)((?:\s|\\\s)+)',
bygroups(Keyword.Namespace, Text), 'import'),
(r'(USE:)(\s+)(\S+)',
bygroups(Keyword.Namespace, Text, Name.Namespace)),
(r'(UNUSE:)(\s+)(\S+)',
bygroups(Keyword.Namespace, Text, Name.Namespace)),
(r'(QUALIFIED:)(\s+)(\S+)',
bygroups(Keyword.Namespace, Text, Name.Namespace)),
(r'(QUALIFIED-WITH:)(\s+)(\S+)',
bygroups(Keyword.Namespace, Text, Name.Namespace)),
(r'(FROM:|EXCLUDE:)(\s+)(\S+)(\s+)(=>)',
bygroups(Keyword.Namespace, Text, Name.Namespace, Text, Text)),
(r'(IN:)(\s+)(\S+)',
bygroups(Keyword.Namespace, Text, Name.Namespace)),
(r'(?:ALIAS|DEFER|FORGET|POSTPONE):', Keyword.Namespace),
# tuples and classes
(r'(TUPLE:)(\s+)(\S+)(\s+<\s+)(\S+)',
bygroups(Keyword, Text, Name.Class, Text, Name.Class), 'slots'),
(r'(TUPLE:)(\s+)(\S+)',
bygroups(Keyword, Text, Name.Class), 'slots'),
(r'(UNION:)(\s+)(\S+)', bygroups(Keyword, Text, Name.Class)),
(r'(INTERSECTION:)(\s+)(\S+)', bygroups(Keyword, Text, Name.Class)),
(r'(PREDICATE:)(\s+)(\S+)(\s+<\s+)(\S+)',
bygroups(Keyword, Text, Name.Class, Text, Name.Class)),
(r'(C:)(\s+)(\S+)(\s+)(\S+)',
bygroups(Keyword, Text, Name.Function, Text, Name.Class)),
(r'INSTANCE:', Keyword),
(r'SLOT:', Keyword),
(r'MIXIN:', Keyword),
(r'(?:SINGLETON|SINGLETONS):', Keyword),
# other syntax
(r'CONSTANT:', Keyword),
(r'(?:SYMBOL|SYMBOLS):', Keyword),
(r'ERROR:', Keyword),
(r'SYNTAX:', Keyword),
(r'(HELP:)(\s+)(\S+)', bygroups(Keyword, Text, Name.Function)),
(r'(MAIN:)(\s+)(\S+)',
bygroups(Keyword.Namespace, Text, Name.Function)),
(r'(?:ALIEN|TYPEDEF|FUNCTION|STRUCT):', Keyword),
# vocab.private
# TODO: words inside vocab.private should have red names?
(r'(?:<PRIVATE|PRIVATE>)', Keyword.Namespace),
# strings
(r'"""\s+(?:.|\n)*?\s+"""', String),
(r'"(?:\\\\|\\"|[^"])*"', String),
(r'CHAR:\s+(\\[\\abfnrstv]*|\S)\s', String.Char),
# comments
(r'\!\s+.*$', Comment),
(r'#\!\s+.*$', Comment),
# boolean constants
(r'(t|f)\s', Name.Constant),
# numbers
(r'-?\d+\.\d+\s', Number.Float),
(r'-?\d+\s', Number.Integer),
(r'HEX:\s+[a-fA-F\d]+\s', Number.Hex),
(r'BIN:\s+[01]+\s', Number.Integer),
(r'OCT:\s+[0-7]+\s', Number.Oct),
# operators
(r'[-+/*=<>^]\s', Operator),
# keywords
(r'(?:deprecated|final|foldable|flushable|inline|recursive)\s',
Keyword),
# builtins
(builtin_kernel, Name.Builtin),
(builtin_assocs, Name.Builtin),
(builtin_combinators, Name.Builtin),
(builtin_math, Name.Builtin),
(builtin_sequences, Name.Builtin),
(builtin_namespaces, Name.Builtin),
(builtin_arrays, Name.Builtin),
(builtin_io, Name.Builtin),
(builtin_strings, Name.Builtin),
(builtin_vectors, Name.Builtin),
(builtin_continuations, Name.Builtin),
# whitespaces - usually not relevant
(r'\s+', Text),
# everything else is text
(r'\S+', Text),
],
'stackeffect': [
(r'\s*\(', Name.Function, 'stackeffect'),
(r'\)', Name.Function, '#pop'),
(r'\-\-', Name.Function),
(r'\s+', Text),
(r'\S+', Name.Variable),
],
'slots': [
(r'\s+', Text),
(r';\s', Keyword, '#pop'),
(r'\S+', Name.Variable),
],
'import': [
(r';', Keyword, '#pop'),
(r'\S+', Name.Namespace),
(r'\s+', Text),
],
}
class FancyLexer(RegexLexer):
"""
Pygments Lexer For `Fancy <http://www.fancy-lang.org/>`_.
Fancy is a self-hosted, pure object-oriented, dynamic,
class-based, concurrent general-purpose programming language
running on Rubinius, the Ruby VM.
*New in Pygments 1.5.*
"""
name = 'Fancy'
filenames = ['*.fy', '*.fancypack']
aliases = ['fancy', 'fy']
mimetypes = ['text/x-fancysrc']
tokens = {
# copied from PerlLexer:
'balanced-regex': [
(r'/(\\\\|\\/|[^/])*/[egimosx]*', String.Regex, '#pop'),
(r'!(\\\\|\\!|[^!])*![egimosx]*', String.Regex, '#pop'),
(r'\\(\\\\|[^\\])*\\[egimosx]*', String.Regex, '#pop'),
(r'{(\\\\|\\}|[^}])*}[egimosx]*', String.Regex, '#pop'),
(r'<(\\\\|\\>|[^>])*>[egimosx]*', String.Regex, '#pop'),
(r'\[(\\\\|\\\]|[^\]])*\][egimosx]*', String.Regex, '#pop'),
(r'\((\\\\|\\\)|[^\)])*\)[egimosx]*', String.Regex, '#pop'),
(r'@(\\\\|\\\@|[^\@])*@[egimosx]*', String.Regex, '#pop'),
(r'%(\\\\|\\\%|[^\%])*%[egimosx]*', String.Regex, '#pop'),
(r'\$(\\\\|\\\$|[^\$])*\$[egimosx]*', String.Regex, '#pop'),
],
'root': [
(r'\s+', Text),
# balanced delimiters (copied from PerlLexer):
(r's{(\\\\|\\}|[^}])*}\s*', String.Regex, 'balanced-regex'),
(r's<(\\\\|\\>|[^>])*>\s*', String.Regex, 'balanced-regex'),
(r's\[(\\\\|\\\]|[^\]])*\]\s*', String.Regex, 'balanced-regex'),
(r's\((\\\\|\\\)|[^\)])*\)\s*', String.Regex, 'balanced-regex'),
(r'm?/(\\\\|\\/|[^/\n])*/[gcimosx]*', String.Regex),
(r'm(?=[/!\\{<\[\(@%\$])', String.Regex, 'balanced-regex'),
# Comments
(r'#(.*?)\n', Comment.Single),
# Symbols
(r'\'([^\'\s\[\]\(\)\{\}]+|\[\])', String.Symbol),
# Multi-line DoubleQuotedString
(r'"""(\\\\|\\"|[^"])*"""', String),
# DoubleQuotedString
(r'"(\\\\|\\"|[^"])*"', String),
# keywords
(r'(def|class|try|catch|finally|retry|return|return_local|match|'
r'case|->|=>)\b', Keyword),
# constants
(r'(self|super|nil|false|true)\b', Name.Constant),
(r'[(){};,/?\|:\\]', Punctuation),
# names
(r'(Object|Array|Hash|Directory|File|Class|String|Number|'
r'Enumerable|FancyEnumerable|Block|TrueClass|NilClass|'
r'FalseClass|Tuple|Symbol|Stack|Set|FancySpec|Method|Package|'
r'Range)\b', Name.Builtin),
# functions
(r'[a-zA-Z]([a-zA-Z0-9_]|[-+?!=*/^><%])*:', Name.Function),
# operators, must be below functions
(r'[-+*/~,<>=&!?%^\[\]\.$]+', Operator),
('[A-Z][a-zA-Z0-9_]*', Name.Constant),
('@[a-zA-Z_][a-zA-Z0-9_]*', Name.Variable.Instance),
('@@[a-zA-Z_][a-zA-Z0-9_]*', Name.Variable.Class),
('@@?', Operator),
('[a-zA-Z_][a-zA-Z0-9_]*', Name),
# numbers - / checks are necessary to avoid mismarking regexes,
# see comment in RubyLexer
(r'(0[oO]?[0-7]+(?:_[0-7]+)*)(\s*)([/?])?',
bygroups(Number.Oct, Text, Operator)),
(r'(0[xX][0-9A-Fa-f]+(?:_[0-9A-Fa-f]+)*)(\s*)([/?])?',
bygroups(Number.Hex, Text, Operator)),
(r'(0[bB][01]+(?:_[01]+)*)(\s*)([/?])?',
bygroups(Number.Bin, Text, Operator)),
(r'([\d]+(?:_\d+)*)(\s*)([/?])?',
bygroups(Number.Integer, Text, Operator)),
(r'\d+([eE][+-]?[0-9]+)|\d+\.\d+([eE][+-]?[0-9]+)?', Number.Float),
(r'\d+', Number.Integer)
]
}
class DgLexer(RegexLexer):
"""
Lexer for `dg <http://pyos.github.com/dg>`_,
a functional and object-oriented programming language
running on the CPython 3 VM.
*New in Pygments 1.6.*
"""
name = 'dg'
aliases = ['dg']
filenames = ['*.dg']
mimetypes = ['text/x-dg']
tokens = {
'root': [
# Whitespace:
(r'\s+', Text),
(r'#.*?$', Comment.Single),
# Lexemes:
# Numbers
(r'0[bB][01]+', Number.Bin),
(r'0[oO][0-7]+', Number.Oct),
(r'0[xX][\da-fA-F]+', Number.Hex),
(r'[+-]?\d+\.\d+([eE][+-]?\d+)?[jJ]?', Number.Float),
(r'[+-]?\d+[eE][+-]?\d+[jJ]?', Number.Float),
(r'[+-]?\d+[jJ]?', Number.Integer),
# Character/String Literals
(r"[br]*'''", String, combined('stringescape', 'tsqs', 'string')),
(r'[br]*"""', String, combined('stringescape', 'tdqs', 'string')),
(r"[br]*'", String, combined('stringescape', 'sqs', 'string')),
(r'[br]*"', String, combined('stringescape', 'dqs', 'string')),
# Operators
(r"`\w+'*`", Operator), # Infix links
# Reserved infix links
(r'\b(or|and|if|else|where|is|in)\b', Operator.Word),
(r'[!$%&*+\-./:<-@\\^|~;,]+', Operator),
# Identifiers
# Python 3 types
(r"(?<!\.)(bool|bytearray|bytes|classmethod|complex|dict'?|"
r"float|frozenset|int|list'?|memoryview|object|property|range|"
r"set'?|slice|staticmethod|str|super|tuple'?|type)"
r"(?!['\w])", Name.Builtin),
# Python 3 builtins + some more
(r'(?<!\.)(__import__|abs|all|any|bin|bind|chr|cmp|compile|complex|'
r'delattr|dir|divmod|drop|dropwhile|enumerate|eval|filter|flip|'
r'foldl1?|format|fst|getattr|globals|hasattr|hash|head|hex|id|'
r'init|input|isinstance|issubclass|iter|iterate|last|len|locals|'
r'map|max|min|next|oct|open|ord|pow|print|repr|reversed|round|'
r'setattr|scanl1?|snd|sorted|sum|tail|take|takewhile|vars|zip)'
r"(?!['\w])", Name.Builtin),
(r"(?<!\.)(self|Ellipsis|NotImplemented|None|True|False)(?!['\w])",
Name.Builtin.Pseudo),
(r"(?<!\.)[A-Z]\w*(Error|Exception|Warning)'*(?!['\w])",
Name.Exception),
(r"(?<!\.)(KeyboardInterrupt|SystemExit|StopIteration|"
r"GeneratorExit)(?!['\w])", Name.Exception),
# Compiler-defined identifiers
(r"(?<![\.\w])(import|inherit|for|while|switch|not|raise|unsafe|"
r"yield|with)(?!['\w])", Keyword.Reserved),
# Other links
(r"[A-Z_']+\b", Name),
(r"[A-Z][\w']*\b", Keyword.Type),
(r"\w+'*", Name),
# Blocks
(r'[()]', Punctuation),
],
'stringescape': [
(r'\\([\\abfnrtv"\']|\n|N{.*?}|u[a-fA-F0-9]{4}|'
r'U[a-fA-F0-9]{8}|x[a-fA-F0-9]{2}|[0-7]{1,3})', String.Escape)
],
'string': [
(r'%(\([a-zA-Z0-9_]+\))?[-#0 +]*([0-9]+|[*])?(\.([0-9]+|[*]))?'
'[hlL]?[diouxXeEfFgGcrs%]', String.Interpol),
(r'[^\\\'"%\n]+', String),
# quotes, percents and backslashes must be parsed one at a time
(r'[\'"\\]', String),
# unhandled string formatting sign
(r'%', String),
(r'\n', String)
],
'dqs': [
(r'"', String, '#pop')
],
'sqs': [
(r"'", String, '#pop')
],
'tdqs': [
(r'"""', String, '#pop')
],
'tsqs': [
(r"'''", String, '#pop')
],
}
| agpl-3.0 |
ging/fi-ware-chef_validator | chef_validator/tests/unit/common/test_wsgi.py | 2 | 5616 | #
# Copyright 2010-2011 OpenStack Foundation
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import stubout
from chef_validator.common import exception
from chef_validator.common import wsgi
from chef_validator.tests.unit.base import ValidatorTestCase
class RequestTest(ValidatorTestCase):
def setUp(self):
self.stubs = stubout.StubOutForTesting()
super(RequestTest, self).setUp()
def test_content_type_unsupported(self):
request = wsgi.Request.blank('/tests/123')
request.headers["Content-Type"] = "text/html"
self.assertRaises(exception.InvalidContentType,
request.get_content_type, ('application/xml'))
def test_content_type_with_charset(self):
request = wsgi.Request.blank('/tests/123')
request.headers["Content-Type"] = "application/json; charset=UTF-8"
result = request.get_content_type(('application/json'))
self.assertEqual("application/json", result)
def test_content_type_from_accept_xml(self):
request = wsgi.Request.blank('/tests/123')
request.headers["Accept"] = "application/xml"
result = request.best_match_content_type()
self.assertEqual("application/json", result)
def test_content_type_from_accept_json(self):
request = wsgi.Request.blank('/tests/123')
request.headers["Accept"] = "application/json"
result = request.best_match_content_type()
self.assertEqual("application/json", result)
def test_content_type_from_accept_xml_json(self):
request = wsgi.Request.blank('/tests/123')
request.headers["Accept"] = "application/xml, application/json"
result = request.best_match_content_type()
self.assertEqual("application/json", result)
def test_content_type_from_accept_json_xml_quality(self):
request = wsgi.Request.blank('/tests/123')
request.headers["Accept"] = ("application/json; q=0.3, "
"application/xml; q=0.9")
result = request.best_match_content_type()
self.assertEqual("application/json", result)
def test_content_type_accept_default(self):
request = wsgi.Request.blank('/tests/123.unsupported')
request.headers["Accept"] = "application/unsupported1"
result = request.best_match_content_type()
self.assertEqual("application/json", result)
class ResourceTest(ValidatorTestCase):
def setUp(self):
self.stubs = stubout.StubOutForTesting()
super(ResourceTest, self).setUp()
def test_get_action_args(self):
env = {
'wsgiorg.routing_args': [
None,
{
'controller': None,
'format': None,
'action': 'update',
'id': 12,
},
],
}
expected = {'action': 'update', 'format': None, 'id': 12}
actual = wsgi.Resource(None, None, None).get_action_args(env)
self.assertEqual(expected, actual)
def test_get_action_args_invalid_index(self):
env = {'wsgiorg.routing_args': []}
expected = {}
actual = wsgi.Resource(None, None, None).get_action_args(env)
self.assertEqual(expected, actual)
def test_get_action_args_del_controller_error(self):
actions = {'format': None,
'action': 'update',
'id': 12}
env = {'wsgiorg.routing_args': [None, actions]}
expected = {'action': 'update', 'format': None, 'id': 12}
actual = wsgi.Resource(None, None, None).get_action_args(env)
self.assertEqual(expected, actual)
def test_get_action_args_del_format_error(self):
actions = {'action': 'update', 'id': 12}
env = {'wsgiorg.routing_args': [None, actions]}
expected = {'action': 'update', 'id': 12}
actual = wsgi.Resource(None, None, None).get_action_args(env)
self.assertEqual(expected, actual)
def test_dispatch(self):
class Controller(object):
def index(self, shirt, pants=None):
return (shirt, pants)
resource = wsgi.Resource(None, None, None)
actual = resource.dispatch(Controller(), 'index', 'on', pants='off')
expected = ('on', 'off')
self.assertEqual(expected, actual)
def test_dispatch_default(self):
class Controller(object):
def default(self, shirt, pants=None):
return (shirt, pants)
resource = wsgi.Resource(None, None, None)
actual = resource.dispatch(Controller(), 'index', 'on', pants='off')
expected = ('on', 'off')
self.assertEqual(expected, actual)
def test_dispatch_no_default(self):
class Controller(object):
def show(self, shirt, pants=None):
return (shirt, pants)
resource = wsgi.Resource(None, None, None)
self.assertRaises(AttributeError, resource.dispatch, Controller(),
'index', 'on', pants='off')
| apache-2.0 |
lwiecek/django | tests/forms_tests/field_tests/test_charfield.py | 3 | 4321 | from __future__ import unicode_literals
from django.forms import (
CharField, PasswordInput, Textarea, TextInput, ValidationError,
)
from django.test import SimpleTestCase
from . import FormFieldAssertionsMixin
class CharFieldTest(FormFieldAssertionsMixin, SimpleTestCase):
def test_charfield_1(self):
f = CharField()
self.assertEqual('1', f.clean(1))
self.assertEqual('hello', f.clean('hello'))
with self.assertRaisesMessage(ValidationError, "'This field is required.'"):
f.clean(None)
with self.assertRaisesMessage(ValidationError, "'This field is required.'"):
f.clean('')
self.assertEqual('[1, 2, 3]', f.clean([1, 2, 3]))
self.assertIsNone(f.max_length)
self.assertIsNone(f.min_length)
def test_charfield_2(self):
f = CharField(required=False)
self.assertEqual('1', f.clean(1))
self.assertEqual('hello', f.clean('hello'))
self.assertEqual('', f.clean(None))
self.assertEqual('', f.clean(''))
self.assertEqual('[1, 2, 3]', f.clean([1, 2, 3]))
self.assertIsNone(f.max_length)
self.assertIsNone(f.min_length)
def test_charfield_3(self):
f = CharField(max_length=10, required=False)
self.assertEqual('12345', f.clean('12345'))
self.assertEqual('1234567890', f.clean('1234567890'))
msg = "'Ensure this value has at most 10 characters (it has 11).'"
with self.assertRaisesMessage(ValidationError, msg):
f.clean('1234567890a')
self.assertEqual(f.max_length, 10)
self.assertIsNone(f.min_length)
def test_charfield_4(self):
f = CharField(min_length=10, required=False)
self.assertEqual('', f.clean(''))
msg = "'Ensure this value has at least 10 characters (it has 5).'"
with self.assertRaisesMessage(ValidationError, msg):
f.clean('12345')
self.assertEqual('1234567890', f.clean('1234567890'))
self.assertEqual('1234567890a', f.clean('1234567890a'))
self.assertIsNone(f.max_length)
self.assertEqual(f.min_length, 10)
def test_charfield_5(self):
f = CharField(min_length=10, required=True)
with self.assertRaisesMessage(ValidationError, "'This field is required.'"):
f.clean('')
msg = "'Ensure this value has at least 10 characters (it has 5).'"
with self.assertRaisesMessage(ValidationError, msg):
f.clean('12345')
self.assertEqual('1234567890', f.clean('1234567890'))
self.assertEqual('1234567890a', f.clean('1234567890a'))
self.assertIsNone(f.max_length)
self.assertEqual(f.min_length, 10)
def test_charfield_length_not_int(self):
"""
Setting min_length or max_length to something that is not a number
raises an exception.
"""
with self.assertRaises(ValueError):
CharField(min_length='a')
with self.assertRaises(ValueError):
CharField(max_length='a')
with self.assertRaises(ValueError):
CharField('a')
def test_charfield_widget_attrs(self):
"""
CharField.widget_attrs() always returns a dictionary (#15912).
"""
# Return an empty dictionary if max_length is None
f = CharField()
self.assertEqual(f.widget_attrs(TextInput()), {})
self.assertEqual(f.widget_attrs(Textarea()), {})
# Otherwise, return a maxlength attribute equal to max_length
f = CharField(max_length=10)
self.assertEqual(f.widget_attrs(TextInput()), {'maxlength': '10'})
self.assertEqual(f.widget_attrs(PasswordInput()), {'maxlength': '10'})
self.assertEqual(f.widget_attrs(Textarea()), {'maxlength': '10'})
def test_charfield_strip(self):
"""
Values have whitespace stripped but not if strip=False.
"""
f = CharField()
self.assertEqual(f.clean(' 1'), '1')
self.assertEqual(f.clean('1 '), '1')
f = CharField(strip=False)
self.assertEqual(f.clean(' 1'), ' 1')
self.assertEqual(f.clean('1 '), '1 ')
def test_charfield_disabled(self):
f = CharField(disabled=True)
self.assertWidgetRendersTo(f, '<input type="text" name="f" id="id_f" disabled />')
| bsd-3-clause |
runt18/mojo | mojo/devtools/common/devtoolslib/shell_arguments.py | 1 | 8783 | # Copyright 2015 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.
"""Produces configured shell abstractions.
This module knows how to produce a configured shell abstraction based on
shell_config.ShellConfig.
"""
import os.path
import urlparse
from devtoolslib.android_shell import AndroidShell
from devtoolslib.linux_shell import LinuxShell
from devtoolslib.shell_config import ShellConfigurationException
# When spinning up servers for local origins, we want to use predictable ports
# so that caching works between subsequent runs with the same command line.
_LOCAL_ORIGIN_PORT = 31840
_MAPPINGS_BASE_PORT = 31841
def _is_web_url(dest):
return True if urlparse.urlparse(dest).scheme else False
def _host_local_url_destination(shell, dest_file, port, reuse_servers):
"""Starts a local server to host |dest_file|.
Returns:
Url of the hosted file.
"""
directory = os.path.dirname(dest_file)
if not os.path.exists(directory):
raise ValueError('local path passed as --map-url destination '
'does not exist')
mappings = [('', [directory])]
server_url = shell.serve_local_directories(mappings, port, reuse_servers)
return server_url + os.path.relpath(dest_file, directory)
def _host_local_origin_destination(shell, dest_dir, port, reuse_servers):
"""Starts a local server to host |dest_dir|.
Returns:
Url of the hosted directory.
"""
mappings = [('', [dest_dir])]
return shell.serve_local_directories(mappings, port, reuse_servers)
def _rewrite(mapping, host_destination_functon, shell, port, reuse_servers):
"""Takes a mapping given as <src>=<dest> and rewrites the <dest> part to be
hosted locally using the given function if <dest> is not a web url.
"""
parts = mapping.split('=')
if len(parts) != 2:
raise ValueError('each mapping value should be in format '
'"<url>=<url-or-local-path>"')
if _is_web_url(parts[1]):
# The destination is a web url, do nothing.
return mapping
src = parts[0]
dest = host_destination_functon(shell, parts[1], port, reuse_servers)
return src + '=' + dest
def _apply_mappings(shell, original_arguments, map_urls, map_origins,
reuse_servers):
"""Applies mappings for specified urls and origins. For each local path
specified as destination a local server will be spawned and the mapping will
be rewritten accordingly.
Args:
shell: The shell that is being configured.
original_arguments: Current list of shell arguments.
map_urls: List of url mappings, each in the form of
<url>=<url-or-local-path>.
map_origins: List of origin mappings, each in the form of
<origin>=<url-or-local-path>.
reuse_servers: Assume that the development servers are already running and
do not spawn any.
Returns:
The updated argument list.
"""
next_port = _MAPPINGS_BASE_PORT
args = original_arguments
if map_urls:
# Sort the mappings to preserve caching regardless of argument order.
for map_url in sorted(map_urls):
mapping = _rewrite(map_url, _host_local_url_destination, shell, next_port,
reuse_servers)
next_port += 1
# All url mappings need to be coalesced into one shell argument.
args = append_to_argument(args, '--url-mappings=', mapping)
if map_origins:
for map_origin in sorted(map_origins):
mapping = _rewrite(map_origin, _host_local_origin_destination, shell,
next_port, reuse_servers)
next_port += 1
# Origin mappings are specified as separate, repeated shell arguments.
args.append('--map-origin=' + mapping)
return args
def configure_local_origin(shell, local_dir, port, reuse_servers):
"""Sets up a local http server to serve files in |local_dir| along with
device port forwarding if needed.
Returns:
The list of arguments to be appended to the shell argument list.
"""
mappings = [('', [local_dir])]
origin_url = shell.serve_local_directories(mappings, port, reuse_servers)
return ["--origin=" + origin_url]
def append_to_argument(arguments, key, value, delimiter=","):
"""Looks for an argument of the form "key=val1,val2" within |arguments| and
appends |value| to it.
If the argument is not present in |arguments| it is added.
Args:
arguments: List of arguments for the shell.
key: Identifier of the argument, including the equal sign, eg.
"--content-handlers=".
value: The value to be appended, after |delimeter|, to the argument.
delimiter: The string used to separate values within the argument.
Returns:
The updated argument list.
"""
assert key and key.endswith('=')
assert value
for i, argument in enumerate(arguments):
if not argument.startswith(key):
continue
arguments[i] = argument + delimiter + value
break
else:
arguments.append(key + value)
return arguments
def _configure_dev_server(shell, shell_args, dev_server_config, reuse_servers,
verbose):
"""Sets up a dev server on the host according to |dev_server_config|.
Args:
shell: The shell that is being configured.
shell_arguments: Current list of shell arguments.
dev_server_config: Instance of shell_config.DevServerConfig describing the
dev server to be set up.
Returns:
The updated argument list.
"""
port = dev_server_config.port if dev_server_config.port else 0
server_url = shell.serve_local_directories(
dev_server_config.mappings, port, reuse_servers)
shell_args.append('--map-origin=%s=%s' % (dev_server_config.host, server_url))
if verbose:
print "Configured %s locally at %s to serve:" % (dev_server_config.host,
server_url)
for mapping_prefix, mapping_path in dev_server_config.mappings:
print " /%s -> %s" % (mapping_prefix, mapping_path)
return shell_args
def get_shell(shell_config, shell_args):
"""
Produces a shell abstraction configured according to |shell_config|.
Args:
shell_config: Instance of shell_config.ShellConfig.
shell_args: Additional raw shell arguments to be passed to the shell. We
need to take these into account as some parameters need to appear only
once on the argument list (e.g. url-mappings) so we need to coalesce any
overrides and the existing value into just one argument.
Returns:
A tuple of (shell, shell_args). |shell| is the configured shell abstraction,
|shell_args| is updated list of shell arguments.
Throws:
ShellConfigurationException if shell abstraction could not be configured.
"""
if shell_config.android:
shell = AndroidShell(shell_config.adb_path, shell_config.target_device,
logcat_tags=shell_config.logcat_tags,
verbose=shell_config.verbose)
device_status, error = shell.check_device()
if not device_status:
raise ShellConfigurationException('Device check failed: ' + error)
if shell_config.shell_path:
shell.install_apk(shell_config.shell_path)
else:
if not shell_config.shell_path:
raise ShellConfigurationException('Can not run without a shell binary. '
'Please pass --shell-path.')
shell = LinuxShell(shell_config.shell_path)
if shell_config.use_osmesa:
shell_args.append('--args-for=mojo:native_viewport_service --use-osmesa')
shell_args = _apply_mappings(shell, shell_args, shell_config.map_url_list,
shell_config.map_origin_list,
shell_config.reuse_servers)
if shell_config.origin:
if _is_web_url(shell_config.origin):
shell_args.append('--origin=' + shell_config.origin)
else:
local_origin_port = _LOCAL_ORIGIN_PORT
shell_args.extend(configure_local_origin(shell, shell_config.origin,
local_origin_port,
shell_config.reuse_servers))
if shell_config.content_handlers:
for (mime_type,
content_handler_url) in shell_config.content_handlers.iteritems():
shell_args = append_to_argument(shell_args, '--content-handlers=',
'%s,%s' % (mime_type,
content_handler_url))
for dev_server_config in shell_config.dev_servers:
shell_args = _configure_dev_server(shell, shell_args, dev_server_config,
shell_config.reuse_servers,
shell_config.verbose)
return shell, shell_args
| bsd-3-clause |
mattip/numpy | numpy/core/tests/test_deprecations.py | 1 | 28555 | """
Tests related to deprecation warnings. Also a convenient place
to document how deprecations should eventually be turned into errors.
"""
import datetime
import operator
import warnings
import pytest
import tempfile
import re
import sys
import numpy as np
from numpy.testing import (
assert_raises, assert_warns, assert_, assert_array_equal
)
from numpy.core._multiarray_tests import fromstring_null_term_c_api
try:
import pytz
_has_pytz = True
except ImportError:
_has_pytz = False
class _DeprecationTestCase:
# Just as warning: warnings uses re.match, so the start of this message
# must match.
message = ''
warning_cls = DeprecationWarning
def setup(self):
self.warn_ctx = warnings.catch_warnings(record=True)
self.log = self.warn_ctx.__enter__()
# Do *not* ignore other DeprecationWarnings. Ignoring warnings
# can give very confusing results because of
# https://bugs.python.org/issue4180 and it is probably simplest to
# try to keep the tests cleanly giving only the right warning type.
# (While checking them set to "error" those are ignored anyway)
# We still have them show up, because otherwise they would be raised
warnings.filterwarnings("always", category=self.warning_cls)
warnings.filterwarnings("always", message=self.message,
category=self.warning_cls)
def teardown(self):
self.warn_ctx.__exit__()
def assert_deprecated(self, function, num=1, ignore_others=False,
function_fails=False,
exceptions=np._NoValue,
args=(), kwargs={}):
"""Test if DeprecationWarnings are given and raised.
This first checks if the function when called gives `num`
DeprecationWarnings, after that it tries to raise these
DeprecationWarnings and compares them with `exceptions`.
The exceptions can be different for cases where this code path
is simply not anticipated and the exception is replaced.
Parameters
----------
function : callable
The function to test
num : int
Number of DeprecationWarnings to expect. This should normally be 1.
ignore_others : bool
Whether warnings of the wrong type should be ignored (note that
the message is not checked)
function_fails : bool
If the function would normally fail, setting this will check for
warnings inside a try/except block.
exceptions : Exception or tuple of Exceptions
Exception to expect when turning the warnings into an error.
The default checks for DeprecationWarnings. If exceptions is
empty the function is expected to run successfully.
args : tuple
Arguments for `function`
kwargs : dict
Keyword arguments for `function`
"""
# reset the log
self.log[:] = []
if exceptions is np._NoValue:
exceptions = (self.warning_cls,)
try:
function(*args, **kwargs)
except (Exception if function_fails else tuple()):
pass
# just in case, clear the registry
num_found = 0
for warning in self.log:
if warning.category is self.warning_cls:
num_found += 1
elif not ignore_others:
raise AssertionError(
"expected %s but got: %s" %
(self.warning_cls.__name__, warning.category))
if num is not None and num_found != num:
msg = "%i warnings found but %i expected." % (len(self.log), num)
lst = [str(w) for w in self.log]
raise AssertionError("\n".join([msg] + lst))
with warnings.catch_warnings():
warnings.filterwarnings("error", message=self.message,
category=self.warning_cls)
try:
function(*args, **kwargs)
if exceptions != tuple():
raise AssertionError(
"No error raised during function call")
except exceptions:
if exceptions == tuple():
raise AssertionError(
"Error raised during function call")
def assert_not_deprecated(self, function, args=(), kwargs={}):
"""Test that warnings are not raised.
This is just a shorthand for:
self.assert_deprecated(function, num=0, ignore_others=True,
exceptions=tuple(), args=args, kwargs=kwargs)
"""
self.assert_deprecated(function, num=0, ignore_others=True,
exceptions=tuple(), args=args, kwargs=kwargs)
class _VisibleDeprecationTestCase(_DeprecationTestCase):
warning_cls = np.VisibleDeprecationWarning
class TestNonTupleNDIndexDeprecation:
def test_basic(self):
a = np.zeros((5, 5))
with warnings.catch_warnings():
warnings.filterwarnings('always')
assert_warns(FutureWarning, a.__getitem__, [[0, 1], [0, 1]])
assert_warns(FutureWarning, a.__getitem__, [slice(None)])
warnings.filterwarnings('error')
assert_raises(FutureWarning, a.__getitem__, [[0, 1], [0, 1]])
assert_raises(FutureWarning, a.__getitem__, [slice(None)])
# a a[[0, 1]] always was advanced indexing, so no error/warning
a[[0, 1]]
class TestComparisonDeprecations(_DeprecationTestCase):
"""This tests the deprecation, for non-element-wise comparison logic.
This used to mean that when an error occurred during element-wise comparison
(i.e. broadcasting) NotImplemented was returned, but also in the comparison
itself, False was given instead of the error.
Also test FutureWarning for the None comparison.
"""
message = "elementwise.* comparison failed; .*"
def test_normal_types(self):
for op in (operator.eq, operator.ne):
# Broadcasting errors:
self.assert_deprecated(op, args=(np.zeros(3), []))
a = np.zeros(3, dtype='i,i')
# (warning is issued a couple of times here)
self.assert_deprecated(op, args=(a, a[:-1]), num=None)
# ragged array comparison returns True/False
a = np.array([1, np.array([1,2,3])], dtype=object)
b = np.array([1, np.array([1,2,3])], dtype=object)
self.assert_deprecated(op, args=(a, b), num=None)
def test_string(self):
# For two string arrays, strings always raised the broadcasting error:
a = np.array(['a', 'b'])
b = np.array(['a', 'b', 'c'])
assert_raises(ValueError, lambda x, y: x == y, a, b)
# The empty list is not cast to string, and this used to pass due
# to dtype mismatch; now (2018-06-21) it correctly leads to a
# FutureWarning.
assert_warns(FutureWarning, lambda: a == [])
def test_void_dtype_equality_failures(self):
class NotArray:
def __array__(self):
raise TypeError
# Needed so Python 3 does not raise DeprecationWarning twice.
def __ne__(self, other):
return NotImplemented
self.assert_deprecated(lambda: np.arange(2) == NotArray())
self.assert_deprecated(lambda: np.arange(2) != NotArray())
struct1 = np.zeros(2, dtype="i4,i4")
struct2 = np.zeros(2, dtype="i4,i4,i4")
assert_warns(FutureWarning, lambda: struct1 == 1)
assert_warns(FutureWarning, lambda: struct1 == struct2)
assert_warns(FutureWarning, lambda: struct1 != 1)
assert_warns(FutureWarning, lambda: struct1 != struct2)
def test_array_richcompare_legacy_weirdness(self):
# It doesn't really work to use assert_deprecated here, b/c part of
# the point of assert_deprecated is to check that when warnings are
# set to "error" mode then the error is propagated -- which is good!
# But here we are testing a bunch of code that is deprecated *because*
# it has the habit of swallowing up errors and converting them into
# different warnings. So assert_warns will have to be sufficient.
assert_warns(FutureWarning, lambda: np.arange(2) == "a")
assert_warns(FutureWarning, lambda: np.arange(2) != "a")
# No warning for scalar comparisons
with warnings.catch_warnings():
warnings.filterwarnings("error")
assert_(not (np.array(0) == "a"))
assert_(np.array(0) != "a")
assert_(not (np.int16(0) == "a"))
assert_(np.int16(0) != "a")
for arg1 in [np.asarray(0), np.int16(0)]:
struct = np.zeros(2, dtype="i4,i4")
for arg2 in [struct, "a"]:
for f in [operator.lt, operator.le, operator.gt, operator.ge]:
with warnings.catch_warnings() as l:
warnings.filterwarnings("always")
assert_raises(TypeError, f, arg1, arg2)
assert_(not l)
class TestDatetime64Timezone(_DeprecationTestCase):
"""Parsing of datetime64 with timezones deprecated in 1.11.0, because
datetime64 is now timezone naive rather than UTC only.
It will be quite a while before we can remove this, because, at the very
least, a lot of existing code uses the 'Z' modifier to avoid conversion
from local time to UTC, even if otherwise it handles time in a timezone
naive fashion.
"""
def test_string(self):
self.assert_deprecated(np.datetime64, args=('2000-01-01T00+01',))
self.assert_deprecated(np.datetime64, args=('2000-01-01T00Z',))
@pytest.mark.skipif(not _has_pytz,
reason="The pytz module is not available.")
def test_datetime(self):
tz = pytz.timezone('US/Eastern')
dt = datetime.datetime(2000, 1, 1, 0, 0, tzinfo=tz)
self.assert_deprecated(np.datetime64, args=(dt,))
class TestNonCContiguousViewDeprecation(_DeprecationTestCase):
"""View of non-C-contiguous arrays deprecated in 1.11.0.
The deprecation will not be raised for arrays that are both C and F
contiguous, as C contiguous is dominant. There are more such arrays
with relaxed stride checking than without so the deprecation is not
as visible with relaxed stride checking in force.
"""
def test_fortran_contiguous(self):
self.assert_deprecated(np.ones((2,2)).T.view, args=(complex,))
self.assert_deprecated(np.ones((2,2)).T.view, args=(np.int8,))
class TestArrayDataAttributeAssignmentDeprecation(_DeprecationTestCase):
"""Assigning the 'data' attribute of an ndarray is unsafe as pointed
out in gh-7093. Eventually, such assignment should NOT be allowed, but
in the interests of maintaining backwards compatibility, only a Deprecation-
Warning will be raised instead for the time being to give developers time to
refactor relevant code.
"""
def test_data_attr_assignment(self):
a = np.arange(10)
b = np.linspace(0, 1, 10)
self.message = ("Assigning the 'data' attribute is an "
"inherently unsafe operation and will "
"be removed in the future.")
self.assert_deprecated(a.__setattr__, args=('data', b.data))
class TestBinaryReprInsufficientWidthParameterForRepresentation(_DeprecationTestCase):
"""
If a 'width' parameter is passed into ``binary_repr`` that is insufficient to
represent the number in base 2 (positive) or 2's complement (negative) form,
the function used to silently ignore the parameter and return a representation
using the minimal number of bits needed for the form in question. Such behavior
is now considered unsafe from a user perspective and will raise an error in the future.
"""
def test_insufficient_width_positive(self):
args = (10,)
kwargs = {'width': 2}
self.message = ("Insufficient bit width provided. This behavior "
"will raise an error in the future.")
self.assert_deprecated(np.binary_repr, args=args, kwargs=kwargs)
def test_insufficient_width_negative(self):
args = (-5,)
kwargs = {'width': 2}
self.message = ("Insufficient bit width provided. This behavior "
"will raise an error in the future.")
self.assert_deprecated(np.binary_repr, args=args, kwargs=kwargs)
class TestNumericStyleTypecodes(_DeprecationTestCase):
"""
Most numeric style typecodes were previously deprecated (and removed)
in 1.20. This also deprecates the remaining ones.
"""
# 2020-06-09, NumPy 1.20
def test_all_dtypes(self):
deprecated_types = ['Bytes0', 'Datetime64', 'Str0']
# Depending on intp size, either Uint32 or Uint64 is defined:
deprecated_types.append(f"U{np.dtype(np.intp).name}")
for dt in deprecated_types:
self.assert_deprecated(np.dtype, exceptions=(TypeError,),
args=(dt,))
class TestTestDeprecated:
def test_assert_deprecated(self):
test_case_instance = _DeprecationTestCase()
test_case_instance.setup()
assert_raises(AssertionError,
test_case_instance.assert_deprecated,
lambda: None)
def foo():
warnings.warn("foo", category=DeprecationWarning, stacklevel=2)
test_case_instance.assert_deprecated(foo)
test_case_instance.teardown()
class TestNonNumericConjugate(_DeprecationTestCase):
"""
Deprecate no-op behavior of ndarray.conjugate on non-numeric dtypes,
which conflicts with the error behavior of np.conjugate.
"""
def test_conjugate(self):
for a in np.array(5), np.array(5j):
self.assert_not_deprecated(a.conjugate)
for a in (np.array('s'), np.array('2016', 'M'),
np.array((1, 2), [('a', int), ('b', int)])):
self.assert_deprecated(a.conjugate)
class TestNPY_CHAR(_DeprecationTestCase):
# 2017-05-03, 1.13.0
def test_npy_char_deprecation(self):
from numpy.core._multiarray_tests import npy_char_deprecation
self.assert_deprecated(npy_char_deprecation)
assert_(npy_char_deprecation() == 'S1')
class TestPyArray_AS1D(_DeprecationTestCase):
def test_npy_pyarrayas1d_deprecation(self):
from numpy.core._multiarray_tests import npy_pyarrayas1d_deprecation
assert_raises(NotImplementedError, npy_pyarrayas1d_deprecation)
class TestPyArray_AS2D(_DeprecationTestCase):
def test_npy_pyarrayas2d_deprecation(self):
from numpy.core._multiarray_tests import npy_pyarrayas2d_deprecation
assert_raises(NotImplementedError, npy_pyarrayas2d_deprecation)
class Test_UPDATEIFCOPY(_DeprecationTestCase):
"""
v1.14 deprecates creating an array with the UPDATEIFCOPY flag, use
WRITEBACKIFCOPY instead
"""
def test_npy_updateifcopy_deprecation(self):
from numpy.core._multiarray_tests import npy_updateifcopy_deprecation
arr = np.arange(9).reshape(3, 3)
v = arr.T
self.assert_deprecated(npy_updateifcopy_deprecation, args=(v,))
class TestDatetimeEvent(_DeprecationTestCase):
# 2017-08-11, 1.14.0
def test_3_tuple(self):
for cls in (np.datetime64, np.timedelta64):
# two valid uses - (unit, num) and (unit, num, den, None)
self.assert_not_deprecated(cls, args=(1, ('ms', 2)))
self.assert_not_deprecated(cls, args=(1, ('ms', 2, 1, None)))
# trying to use the event argument, removed in 1.7.0, is deprecated
# it used to be a uint8
self.assert_deprecated(cls, args=(1, ('ms', 2, 'event')))
self.assert_deprecated(cls, args=(1, ('ms', 2, 63)))
self.assert_deprecated(cls, args=(1, ('ms', 2, 1, 'event')))
self.assert_deprecated(cls, args=(1, ('ms', 2, 1, 63)))
class TestTruthTestingEmptyArrays(_DeprecationTestCase):
# 2017-09-25, 1.14.0
message = '.*truth value of an empty array is ambiguous.*'
def test_1d(self):
self.assert_deprecated(bool, args=(np.array([]),))
def test_2d(self):
self.assert_deprecated(bool, args=(np.zeros((1, 0)),))
self.assert_deprecated(bool, args=(np.zeros((0, 1)),))
self.assert_deprecated(bool, args=(np.zeros((0, 0)),))
class TestBincount(_DeprecationTestCase):
# 2017-06-01, 1.14.0
def test_bincount_minlength(self):
self.assert_deprecated(lambda: np.bincount([1, 2, 3], minlength=None))
class TestAlen(_DeprecationTestCase):
# 2019-08-02, 1.18.0
def test_alen(self):
self.assert_deprecated(lambda: np.alen(np.array([1, 2, 3])))
class TestGeneratorSum(_DeprecationTestCase):
# 2018-02-25, 1.15.0
def test_generator_sum(self):
self.assert_deprecated(np.sum, args=((i for i in range(5)),))
class TestPositiveOnNonNumerical(_DeprecationTestCase):
# 2018-06-28, 1.16.0
def test_positive_on_non_number(self):
self.assert_deprecated(operator.pos, args=(np.array('foo'),))
class TestFromstring(_DeprecationTestCase):
# 2017-10-19, 1.14
def test_fromstring(self):
self.assert_deprecated(np.fromstring, args=('\x00'*80,))
class TestFromStringAndFileInvalidData(_DeprecationTestCase):
# 2019-06-08, 1.17.0
# Tests should be moved to real tests when deprecation is done.
message = "string or file could not be read to its end"
@pytest.mark.parametrize("invalid_str", [",invalid_data", "invalid_sep"])
def test_deprecate_unparsable_data_file(self, invalid_str):
x = np.array([1.51, 2, 3.51, 4], dtype=float)
with tempfile.TemporaryFile(mode="w") as f:
x.tofile(f, sep=',', format='%.2f')
f.write(invalid_str)
f.seek(0)
self.assert_deprecated(lambda: np.fromfile(f, sep=","))
f.seek(0)
self.assert_deprecated(lambda: np.fromfile(f, sep=",", count=5))
# Should not raise:
with warnings.catch_warnings():
warnings.simplefilter("error", DeprecationWarning)
f.seek(0)
res = np.fromfile(f, sep=",", count=4)
assert_array_equal(res, x)
@pytest.mark.parametrize("invalid_str", [",invalid_data", "invalid_sep"])
def test_deprecate_unparsable_string(self, invalid_str):
x = np.array([1.51, 2, 3.51, 4], dtype=float)
x_str = "1.51,2,3.51,4{}".format(invalid_str)
self.assert_deprecated(lambda: np.fromstring(x_str, sep=","))
self.assert_deprecated(lambda: np.fromstring(x_str, sep=",", count=5))
# The C-level API can use not fixed size, but 0 terminated strings,
# so test that as well:
bytestr = x_str.encode("ascii")
self.assert_deprecated(lambda: fromstring_null_term_c_api(bytestr))
with assert_warns(DeprecationWarning):
# this is slightly strange, in that fromstring leaves data
# potentially uninitialized (would be good to error when all is
# read, but count is larger then actual data maybe).
res = np.fromstring(x_str, sep=",", count=5)
assert_array_equal(res[:-1], x)
with warnings.catch_warnings():
warnings.simplefilter("error", DeprecationWarning)
# Should not raise:
res = np.fromstring(x_str, sep=",", count=4)
assert_array_equal(res, x)
class Test_GetSet_NumericOps(_DeprecationTestCase):
# 2018-09-20, 1.16.0
def test_get_numeric_ops(self):
from numpy.core._multiarray_tests import getset_numericops
self.assert_deprecated(getset_numericops, num=2)
# empty kwargs prevents any state actually changing which would break
# other tests.
self.assert_deprecated(np.set_numeric_ops, kwargs={})
assert_raises(ValueError, np.set_numeric_ops, add='abc')
class TestShape1Fields(_DeprecationTestCase):
warning_cls = FutureWarning
# 2019-05-20, 1.17.0
def test_shape_1_fields(self):
self.assert_deprecated(np.dtype, args=([('a', int, 1)],))
class TestNonZero(_DeprecationTestCase):
# 2019-05-26, 1.17.0
def test_zerod(self):
self.assert_deprecated(lambda: np.nonzero(np.array(0)))
self.assert_deprecated(lambda: np.nonzero(np.array(1)))
def test_deprecate_ragged_arrays():
# 2019-11-29 1.19.0
#
# NEP 34 deprecated automatic object dtype when creating ragged
# arrays. Also see the "ragged" tests in `test_multiarray`
#
# emits a VisibleDeprecationWarning
arg = [1, [2, 3]]
with assert_warns(np.VisibleDeprecationWarning):
np.array(arg)
class TestTooDeepDeprecation(_VisibleDeprecationTestCase):
# NumPy 1.20, 2020-05-08
# This is a bit similar to the above ragged array deprecation case.
message = re.escape("Creating an ndarray from nested sequences exceeding")
def test_deprecation(self):
nested = [1]
for i in range(np.MAXDIMS - 1):
nested = [nested]
self.assert_not_deprecated(np.array, args=(nested,))
self.assert_not_deprecated(np.array,
args=(nested,), kwargs=dict(dtype=object))
self.assert_deprecated(np.array, args=([nested],))
class TestToString(_DeprecationTestCase):
# 2020-03-06 1.19.0
message = re.escape("tostring() is deprecated. Use tobytes() instead.")
def test_tostring(self):
arr = np.array(list(b"test\xFF"), dtype=np.uint8)
self.assert_deprecated(arr.tostring)
def test_tostring_matches_tobytes(self):
arr = np.array(list(b"test\xFF"), dtype=np.uint8)
b = arr.tobytes()
with assert_warns(DeprecationWarning):
s = arr.tostring()
assert s == b
class TestDTypeCoercion(_DeprecationTestCase):
# 2020-02-06 1.19.0
message = "Converting .* to a dtype .*is deprecated"
deprecated_types = [
# The builtin scalar super types:
np.generic, np.flexible, np.number,
np.inexact, np.floating, np.complexfloating,
np.integer, np.unsignedinteger, np.signedinteger,
# character is a deprecated S1 special case:
np.character,
]
def test_dtype_coercion(self):
for scalar_type in self.deprecated_types:
self.assert_deprecated(np.dtype, args=(scalar_type,))
def test_array_construction(self):
for scalar_type in self.deprecated_types:
self.assert_deprecated(np.array, args=([], scalar_type,))
def test_not_deprecated(self):
# All specific types are not deprecated:
for group in np.sctypes.values():
for scalar_type in group:
self.assert_not_deprecated(np.dtype, args=(scalar_type,))
for scalar_type in [type, dict, list, tuple]:
# Typical python types are coerced to object currently:
self.assert_not_deprecated(np.dtype, args=(scalar_type,))
class BuiltInRoundComplexDType(_DeprecationTestCase):
# 2020-03-31 1.19.0
deprecated_types = [np.csingle, np.cdouble, np.clongdouble]
not_deprecated_types = [
np.int8, np.int16, np.int32, np.int64,
np.uint8, np.uint16, np.uint32, np.uint64,
np.float16, np.float32, np.float64,
]
def test_deprecated(self):
for scalar_type in self.deprecated_types:
scalar = scalar_type(0)
self.assert_deprecated(round, args=(scalar,))
self.assert_deprecated(round, args=(scalar, 0))
self.assert_deprecated(round, args=(scalar,), kwargs={'ndigits': 0})
def test_not_deprecated(self):
for scalar_type in self.not_deprecated_types:
scalar = scalar_type(0)
self.assert_not_deprecated(round, args=(scalar,))
self.assert_not_deprecated(round, args=(scalar, 0))
self.assert_not_deprecated(round, args=(scalar,), kwargs={'ndigits': 0})
class TestIncorrectAdvancedIndexWithEmptyResult(_DeprecationTestCase):
# 2020-05-27, NumPy 1.20.0
message = "Out of bound index found. This was previously ignored.*"
@pytest.mark.parametrize("index", [([3, 0],), ([0, 0], [3, 0])])
def test_empty_subspace(self, index):
# Test for both a single and two/multiple advanced indices. These
# This will raise an IndexError in the future.
arr = np.ones((2, 2, 0))
self.assert_deprecated(arr.__getitem__, args=(index,))
self.assert_deprecated(arr.__setitem__, args=(index, 0.))
# for this array, the subspace is only empty after applying the slice
arr2 = np.ones((2, 2, 1))
index2 = (slice(0, 0),) + index
self.assert_deprecated(arr2.__getitem__, args=(index2,))
self.assert_deprecated(arr2.__setitem__, args=(index2, 0.))
def test_empty_index_broadcast_not_deprecated(self):
arr = np.ones((2, 2, 2))
index = ([[3], [2]], []) # broadcast to an empty result.
self.assert_not_deprecated(arr.__getitem__, args=(index,))
self.assert_not_deprecated(arr.__setitem__,
args=(index, np.empty((2, 0, 2))))
class TestNonExactMatchDeprecation(_DeprecationTestCase):
# 2020-04-22
def test_non_exact_match(self):
arr = np.array([[3, 6, 6], [4, 5, 1]])
# misspelt mode check
self.assert_deprecated(lambda: np.ravel_multi_index(arr, (7, 6), mode='Cilp'))
# using completely different word with first character as R
self.assert_deprecated(lambda: np.searchsorted(arr[0], 4, side='Random'))
class TestDeprecatedGlobals(_DeprecationTestCase):
# 2020-06-06
@pytest.mark.skipif(
sys.version_info < (3, 7),
reason='module-level __getattr__ not supported')
def test_type_aliases(self):
# from builtins
self.assert_deprecated(lambda: np.bool)
self.assert_deprecated(lambda: np.int)
self.assert_deprecated(lambda: np.float)
self.assert_deprecated(lambda: np.complex)
self.assert_deprecated(lambda: np.object)
self.assert_deprecated(lambda: np.str)
# from np.compat
self.assert_deprecated(lambda: np.long)
self.assert_deprecated(lambda: np.unicode)
class TestMatrixInOuter(_DeprecationTestCase):
# 2020-05-13 NumPy 1.20.0
message = (r"add.outer\(\) was passed a numpy matrix as "
r"(first|second) argument.")
def test_deprecated(self):
arr = np.array([1, 2, 3])
m = np.array([1, 2, 3]).view(np.matrix)
self.assert_deprecated(np.add.outer, args=(m, m), num=2)
self.assert_deprecated(np.add.outer, args=(arr, m))
self.assert_deprecated(np.add.outer, args=(m, arr))
self.assert_not_deprecated(np.add.outer, args=(arr, arr))
class TestRaggedArray(_DeprecationTestCase):
# 2020-07-24, NumPy 1.20.0
message = "setting an array element with a sequence"
def test_deprecated(self):
arr = np.ones((1, 1))
# Deprecated if the array is a leave node:
self.assert_deprecated(lambda: np.array([arr, 0], dtype=np.float64))
self.assert_deprecated(lambda: np.array([0, arr], dtype=np.float64))
# And when it is an assignment into a lower dimensional subarray:
self.assert_deprecated(lambda: np.array([arr, [0]], dtype=np.float64))
self.assert_deprecated(lambda: np.array([[0], arr], dtype=np.float64))
class FlatteningConcatenateUnsafeCast(_DeprecationTestCase):
# NumPy 1.20, 2020-09-03
message = "concatenate with `axis=None` will use same-kind casting"
def test_deprecated(self):
self.assert_deprecated(np.concatenate,
args=(([0.], [1.]),),
kwargs=dict(axis=None, out=np.empty(2, dtype=np.int64)))
def test_not_deprecated(self):
self.assert_not_deprecated(np.concatenate,
args=(([0.], [1.]),),
kwargs={'axis': None, 'out': np.empty(2, dtype=np.int64),
'casting': "unsafe"})
with assert_raises(TypeError):
# Tests should notice if the deprecation warning is given first...
np.concatenate(([0.], [1.]), out=np.empty(2, dtype=np.int64),
casting="same_kind")
| bsd-3-clause |
ActiveState/code | recipes/Python/577466_Cronlike_Triggers/recipe-577466.py | 1 | 11517 | #!/usr/bin/env python
"""
This module provides a class for cron-like scheduling systems, and
exposes the function used to convert static cron expressions to Python
sets.
CronExpression objects are instantiated with a cron formatted string
that represents the times when the trigger is active. When using
expressions that contain periodic terms, an extension of cron created
for this module, a starting epoch should be explicitly defined. When the
epoch is not explicitly defined, it defaults to the Unix epoch. Periodic
terms provide a method of recurring triggers based on arbitrary time
periods.
Standard Cron Triggers:
>>> job = CronExpression("0 0 * * 1-5/2 find /var/log -delete")
>>> job.check_trigger((2010, 11, 17, 0, 0))
True
>>> job.check_trigger((2012, 12, 21, 0 , 0))
False
Periodic Trigger:
>>> job = CronExpression("0 %9 * * * Feed 'it'", (2010, 5, 1, 7, 0, -6))
>>> job.comment
"Feed 'it'"
>>> job.check_trigger((2010, 5, 1, 7, 0), utc_offset=-6)
True
>>> job.check_trigger((2010, 5, 1, 16, 0), utc_offset=-6)
True
>>> job.check_trigger((2010, 5, 2, 1, 0), utc_offset=-6)
True
"""
import datetime
import calendar
__all__ = ["CronExpression", "parse_atom", "DEFAULT_EPOCH", "SUBSTITUTIONS"]
__license__ = "Public Domain"
DAY_NAMES = zip(('sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'), xrange(7))
MINUTES = (0, 59)
HOURS = (0, 23)
DAYS_OF_MONTH = (1, 31)
MONTHS = (1, 12)
DAYS_OF_WEEK = (0, 6)
L_FIELDS = (DAYS_OF_WEEK, DAYS_OF_MONTH)
FIELD_RANGES = (MINUTES, HOURS, DAYS_OF_MONTH, MONTHS, DAYS_OF_WEEK)
MONTH_NAMES = zip(('jan', 'feb', 'mar', 'apr', 'may', 'jun',
'jul', 'aug', 'sep', 'oct', 'nov', 'dec'), xrange(1, 13))
DEFAULT_EPOCH = (1970, 1, 1, 0, 0, 0)
SUBSTITUTIONS = {
"@yearly": "0 0 1 1 *",
"@anually": "0 0 1 1 *",
"@monthly": "0 0 1 * *",
"@weekly": "0 0 * * 0",
"@daily": "0 0 * * *",
"@midnight": "0 0 * * *",
"@hourly": "0 * * * *"
}
class CronExpression(object):
def __init__(self, line, epoch=DEFAULT_EPOCH, epoch_utc_offset=0):
"""
Instantiates a CronExpression object with an optionally defined epoch.
If the epoch is defined, the UTC offset can be specified one of two
ways: as the sixth element in 'epoch' or supplied in epoch_utc_offset.
The epoch should be defined down to the minute sorted by
descending significance.
"""
for key, value in SUBSTITUTIONS.items():
if line.startswith(key):
line = line.replace(key, value)
break
fields = line.split(None, 5)
if len(fields) == 5:
fields.append('')
minutes, hours, dom, months, dow, self.comment = fields
dow = dow.replace('7', '0').replace('?', '*')
dom = dom.replace('?', '*')
for monthstr, monthnum in MONTH_NAMES:
months = months.lower().replace(monthstr, str(monthnum))
for dowstr, downum in DAY_NAMES:
dow = dow.lower().replace(dowstr, str(downum))
self.string_tab = [minutes, hours, dom.upper(), months, dow.upper()]
self.compute_numtab()
if len(epoch) == 5:
y, mo, d, h, m = epoch
self.epoch = (y, mo, d, h, m, epoch_utc_offset)
else:
self.epoch = epoch
def __str__(self):
base = self.__class__.__name__ + "(%s)"
cron_line = self.string_tab + [str(self.comment])
if not self.comment:
cron_line.pop()
arguments = '"' + ' '.join(cron_line) + '"'
if self.epoch != DEFAULT_EPOCH:
return base % (arguments + ", epoch=" + repr(self.epoch))
else:
return base % arguments
def __repr__(self):
return str(self)
def compute_numtab(self):
"""
Recomputes the sets for the static ranges of the trigger time.
This method should only be called by the user if the string_tab
member is modified.
"""
self.numerical_tab = []
for field_str, span in zip(self.string_tab, FIELD_RANGES):
split_field_str = field_str.split(',')
if len(split_field_str) > 1 and "*" in split_field_str:
raise ValueError("\"*\" must be alone in a field.")
unified = set()
for cron_atom in split_field_str:
# parse_atom only handles static cases
for special_char in ('%', '#', 'L', 'W'):
if special_char in cron_atom:
break
else:
unified.update(parse_atom(cron_atom, span))
self.numerical_tab.append(unified)
if self.string_tab[2] == "*" and self.string_tab[4] != "*":
self.numerical_tab[2] = set()
def check_trigger(self, date_tuple, utc_offset=0):
"""
Returns boolean indicating if the trigger is active at the given time.
The date tuple should be in the local time. Unless periodicities are
used, utc_offset does not need to be specified. If periodicities are
used, specifically in the hour and minutes fields, it is crucial that
the utc_offset is specified.
"""
year, month, day, hour, mins = date_tuple
given_date = datetime.date(year, month, day)
zeroday = datetime.date(*self.epoch[:3])
last_dom = calendar.monthrange(year, month)[-1]
dom_matched = True
# In calendar and datetime.date.weekday, Monday = 0
given_dow = (datetime.date.weekday(given_date) + 1) % 7
first_dow = (given_dow + 1 - day) % 7
# Figure out how much time has passed from the epoch to the given date
utc_diff = utc_offset - self.epoch[5]
mod_delta_yrs = year - self.epoch[0]
mod_delta_mon = month - self.epoch[1] + mod_delta_yrs * 12
mod_delta_day = (given_date - zeroday).days
mod_delta_hrs = hour - self.epoch[3] + mod_delta_day * 24 + utc_diff
mod_delta_min = mins - self.epoch[4] + mod_delta_hrs * 60
# Makes iterating through like components easier.
quintuple = zip(
(mins, hour, day, month, given_dow),
self.numerical_tab,
self.string_tab,
(mod_delta_min, mod_delta_hrs, mod_delta_day, mod_delta_mon,
mod_delta_day),
FIELD_RANGES)
for value, valid_values, field_str, delta_t, field_type in quintuple:
# All valid, static values for the fields are stored in sets
if value in valid_values:
continue
# The following for loop implements the logic for context
# sensitive and epoch sensitive constraints. break statements,
# which are executed when a match is found, lead to a continue
# in the outer loop. If there are no matches found, the given date
# does not match expression constraints, so the function returns
# False as seen at the end of this for...else... construct.
for cron_atom in field_str.split(','):
if cron_atom[0] == '%':
if not(delta_t % int(cron_atom[1:])):
break
elif field_type == DAYS_OF_WEEK and '#' in cron_atom:
D, N = int(cron_atom[0]), int(cron_atom[2])
# Computes Nth occurence of D day of the week
if (((D - first_dow) % 7) + 1 + 7 * (N - 1)) == day:
break
elif field_type == DAYS_OF_MONTH and cron_atom[-1] == 'W':
target = min(int(cron_atom[:-1]), last_dom)
lands_on = (first_dow + target - 1) % 7
if lands_on == 0:
# Shift from Sun. to Mon. unless Mon. is next month
target += 1 if target < last_dom else -2
elif lands_on == 6:
# Shift from Sat. to Fri. unless Fri. in prior month
target += -1 if target > 1 else 2
# Break if the day is correct, and target is a weekday
if target == day and (first_dow + target - 7) % 7 > 1:
break
elif field_type in L_FIELDS and cron_atom.endswith('L'):
# In dom field, L means the last day of the month
target = last_dom
if field_type == DAYS_OF_WEEK:
# Calculates the last occurence of given day of week
desired_dow = int(cron_atom[:-1])
target = (((desired_dow - first_dow) % 7) + 29)
target -= 7 if target > last_dom else 0
if target == day:
break
else:
# See 2010.11.15 of CHANGELOG
if field_type == DAYS_OF_MONTH and self.string_tab[4] != '*':
dom_matched = False
continue
elif field_type == DAYS_OF_WEEK and self.string_tab[2] != '*':
# If we got here, then days of months validated so it does
# not matter that days of the week failed.
return dom_matched
# None of the expressions matched which means this field fails
return False
# Arriving at this point means the date landed within the constraints
# of all fields; the associated trigger should be fired.
return True
def parse_atom(parse, minmax):
"""
Returns a set containing valid values for a given cron-style range of
numbers. The 'minmax' arguments is a two element iterable containing the
inclusive upper and lower limits of the expression.
Examples:
>>> parse_atom("1-5",(0,6))
set([1, 2, 3, 4, 5])
>>> parse_atom("*/6",(0,23))
set([0, 6, 12, 18])
>>> parse_atom("18-6/4",(0,23))
set([18, 22, 0, 4])
>>> parse_atom("*/9",(0,23))
set([0, 9, 18])
"""
parse = parse.strip()
increment = 1
if parse == '*':
return set(xrange(minmax[0], minmax[1] + 1))
elif parse.isdigit():
# A single number still needs to be returned as a set
value = int(parse)
if value >= minmax[0] and value <= minmax[1]:
return set((value,))
else:
raise ValueError("Invalid bounds: \"%s\"" % parse)
elif '-' in parse or '/' in parse:
divide = parse.split('/')
subrange = divide[0]
if len(divide) == 2:
# Example: 1-3/5 or */7 increment should be 5 and 7 respectively
increment = int(divide[1])
if '-' in subrange:
# Example: a-b
prefix, suffix = [int(n) for n in subrange.split('-')]
if prefix < minmax[0] or suffix > minmax[1]:
raise ValueError("Invalid bounds: \"%s\"" % parse)
elif subrange == '*':
# Include all values with the given range
prefix, suffix = minmax
else:
raise ValueError("Unrecognized symbol: \"%s\"" % subrange)
if prefix < suffix:
# Example: 7-10
return set(xrange(prefix, suffix + 1, increment))
else:
# Example: 12-4/2; (12, 12 + n, ..., 12 + m*n) U (n_0, ..., 4)
noskips = list(xrange(prefix, minmax[1] + 1))
noskips+= list(xrange(minmax[0], suffix + 1))
return set(noskips[::increment])
| mit |
CoinGame/BCEShadow | share/qt/extract_strings_qt.py | 1294 | 1784 | #!/usr/bin/python
'''
Extract _("...") strings for translation and convert to Qt4 stringdefs so that
they can be picked up by Qt linguist.
'''
from subprocess import Popen, PIPE
import glob
OUT_CPP="src/qt/bitcoinstrings.cpp"
EMPTY=['""']
def parse_po(text):
"""
Parse 'po' format produced by xgettext.
Return a list of (msgid,msgstr) tuples.
"""
messages = []
msgid = []
msgstr = []
in_msgid = False
in_msgstr = False
for line in text.split('\n'):
line = line.rstrip('\r')
if line.startswith('msgid '):
if in_msgstr:
messages.append((msgid, msgstr))
in_msgstr = False
# message start
in_msgid = True
msgid = [line[6:]]
elif line.startswith('msgstr '):
in_msgid = False
in_msgstr = True
msgstr = [line[7:]]
elif line.startswith('"'):
if in_msgid:
msgid.append(line)
if in_msgstr:
msgstr.append(line)
if in_msgstr:
messages.append((msgid, msgstr))
return messages
files = glob.glob('src/*.cpp') + glob.glob('src/*.h')
# xgettext -n --keyword=_ $FILES
child = Popen(['xgettext','--output=-','-n','--keyword=_'] + files, stdout=PIPE)
(out, err) = child.communicate()
messages = parse_po(out)
f = open(OUT_CPP, 'w')
f.write("""#include <QtGlobal>
// Automatically generated by extract_strings.py
#ifdef __GNUC__
#define UNUSED __attribute__((unused))
#else
#define UNUSED
#endif
""")
f.write('static const char UNUSED *bitcoin_strings[] = {')
for (msgid, msgstr) in messages:
if msgid != EMPTY:
f.write('QT_TRANSLATE_NOOP("bitcoin-core", %s),\n' % ('\n'.join(msgid)))
f.write('};')
f.close()
| mit |
jskinn/robot-vision-experiment-framework | trials/feature_detection/feature_detector_result.py | 1 | 5505 | # Copyright (c) 2017, John Skinner
import cv2
import logging
import pickle
import bson.objectid as oid
import core.trial_result
import util.transform as tf
class FeatureDetectorResult(core.trial_result.TrialResult):
"""
Trial result for any feature detector.
Contains the list of key points produced by that detector
"""
def __init__(self, system_id, keypoints, timestamps, camera_poses, sequence_type, system_settings,
keypoints_id=None, id_=None, **kwargs):
"""
:param system_id: The identifier of the system producing this result
:param keypoints: A dictionary of image ids to detected keypoints
:param timestamps: A map of image timestamps to image identifiers
:param sequence_type: The type of image sequence used to produce this result
:param system_settings: The settings of the system producing these results
:param id_: The database id of the object, if it exists
:param kwargs: Additional keyword arguments
"""
kwargs['success'] = True
super().__init__(system_id=system_id, sequence_type=sequence_type, system_settings=system_settings,
id_=id_, **kwargs)
self._keypoints = keypoints
self._keypoints_id = keypoints_id
self._timestamps = timestamps
self._camera_poses = camera_poses
@property
def keypoints(self):
"""
The keypoints identified by the detector.
This is a map from image id to lists of key points for that image.
:return: dict
"""
return self._keypoints
@property
def timestamps(self):
"""
A map of processing timestamps or indexes to image ids,
as was provided to the system when it was running.
:return:
"""
return self._timestamps
@property
def camera_poses(self):
"""
The ground-truth camera pose for each image
:return:
"""
return self._camera_poses
def get_keypoints(self):
"""
Get the keypoints identified by the detector. This is the same as the property.
:return: A dictionary of keypoints matched to image timestamp.
"""
return self.keypoints
def get_features_by_timestamp(self):
"""
Get the detected feature points by timestamp rather than image id.
:return: A dict mapping timestamps to detected feature results
"""
return {time: self.keypoints[id_] for time, id_ in self.timestamps.items()}
def save_data(self, db_client):
"""
Save the keypoints, many keypoints for many images are too big to store in a single document
:param db_client:
:return:
"""
if self._keypoints_id is None:
s_keypoints = {identifier: [serialize_keypoint(keypoint) for keypoint in keypoints]
for identifier, keypoints in self.keypoints.items()}
self._keypoints_id = db_client.grid_fs.put(pickle.dumps(s_keypoints, protocol=pickle.HIGHEST_PROTOCOL))
def serialize(self):
serialized = super().serialize()
if self._keypoints_id is None:
logging.getLogger(__name__).warning("Keypoints have not yet been saved,"
" you must call 'save_data' before serialization")
serialized['keypoints_id'] = self._keypoints_id
serialized['timestamps'] = [(stamp, str(identifier)) for stamp, identifier in self.timestamps.items()]
serialized['camera_poses'] = [(stamp, pose.serialize()) for stamp, pose in self.camera_poses.items()]
return serialized
@classmethod
def deserialize(cls, serialized_representation, db_client, **kwargs):
if 'keypoints_id' in serialized_representation:
kwargs['keypoints_id'] = serialized_representation['keypoints_id']
if kwargs['keypoints_id'] is not None:
s_keypoints = pickle.loads(db_client.grid_fs.get(kwargs['keypoints_id']).read())
kwargs['keypoints'] = {image_id: [deserialize_keypoint(s_keypoint) for s_keypoint in inner_list]
for image_id, inner_list in s_keypoints.items()}
if 'timestamps' in serialized_representation:
kwargs['timestamps'] = {stamp: oid.ObjectId(identifier)
for stamp, identifier in serialized_representation['timestamps']}
if 'camera_poses' in serialized_representation:
kwargs['camera_poses'] = {stamp: tf.Transform.deserialize(s_trans) for stamp, s_trans
in serialized_representation['camera_poses']}
return super().deserialize(serialized_representation, db_client, **kwargs)
def serialize_keypoint(keypoint):
point = keypoint.pt
return {
'x': point[0], 'y': point[1],
'angle': keypoint.angle,
'class_id': keypoint.class_id,
'octave': keypoint.octave,
'response': keypoint.response,
'size': keypoint.size
}
def deserialize_keypoint(s_keypoint):
return cv2.KeyPoint(x=s_keypoint['x'],
y=s_keypoint['y'],
_angle=s_keypoint['angle'],
_class_id=s_keypoint['class_id'],
_octave=s_keypoint['octave'],
_response=s_keypoint['response'],
_size=s_keypoint['size'])
| bsd-2-clause |
andhit-r/account-financial-tools | account_asset_management_xls/__init__.py | 34 | 1280 | # -*- encoding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
#
# Copyright (c) 2014 Noviat nv/sa (www.noviat.com). All rights reserved.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
try:
from . import account_asset
from . import wizard
from . import report
except ImportError:
import logging
logging.getLogger(__name__).warn(
"report_xls not available in addons path")
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
| agpl-3.0 |
PierreF/docker-py | docker/api/exec_api.py | 11 | 2234 | import shlex
import six
from .. import errors
from .. import utils
class ExecApiMixin(object):
@utils.minimum_version('1.15')
@utils.check_resource
def exec_create(self, container, cmd, stdout=True, stderr=True, tty=False,
privileged=False, user=''):
if privileged and utils.compare_version('1.19', self._version) < 0:
raise errors.InvalidVersion(
'Privileged exec is not supported in API < 1.19'
)
if user and utils.compare_version('1.19', self._version) < 0:
raise errors.InvalidVersion(
'User-specific exec is not supported in API < 1.19'
)
if isinstance(cmd, six.string_types):
cmd = shlex.split(str(cmd))
data = {
'Container': container,
'User': user,
'Privileged': privileged,
'Tty': tty,
'AttachStdin': False,
'AttachStdout': stdout,
'AttachStderr': stderr,
'Cmd': cmd
}
url = self._url('/containers/{0}/exec', container)
res = self._post_json(url, data=data)
return self._result(res, True)
@utils.minimum_version('1.16')
def exec_inspect(self, exec_id):
if isinstance(exec_id, dict):
exec_id = exec_id.get('Id')
res = self._get(self._url("/exec/{0}/json", exec_id))
return self._result(res, True)
@utils.minimum_version('1.15')
def exec_resize(self, exec_id, height=None, width=None):
if isinstance(exec_id, dict):
exec_id = exec_id.get('Id')
params = {'h': height, 'w': width}
url = self._url("/exec/{0}/resize", exec_id)
res = self._post(url, params=params)
self._raise_for_status(res)
@utils.minimum_version('1.15')
def exec_start(self, exec_id, detach=False, tty=False, stream=False):
if isinstance(exec_id, dict):
exec_id = exec_id.get('Id')
data = {
'Tty': tty,
'Detach': detach
}
res = self._post_json(
self._url('/exec/{0}/start', exec_id), data=data, stream=stream
)
return self._get_result_tty(stream, res, tty)
| apache-2.0 |
paramsingh/listenbrainz-server | listenbrainz/listen_replay/replay_user.py | 1 | 3677 | """ This script should be used to replay user listens to fix bad data.
"""
import abc
import json
import uuid
from datetime import datetime
from flask import current_app
from listenbrainz.utils import get_measurement_name, quote, convert_to_unix_timestamp
from listenbrainz.webserver import create_app
from listenbrainz.webserver.influx_connection import init_influx_connection
from listenbrainz.listenstore.influx_listenstore import DUMP_CHUNK_SIZE
class UserReplayer(abc.ABC):
def __init__(self, user_name):
self.user_name = user_name
self.max_time = datetime.now()
self.app = create_app()
@abc.abstractmethod
def filter(self, row):
""" Modify row as needed by the subclass
Returns:
row (dict): modified row as needed
or None if row needs to be removed
"""
pass
def convert_to_influx_insert_format(self, row, measurement):
data = {
'measurement': measurement,
'time': convert_to_unix_timestamp(row['time']),
}
data['fields'] = row
data['fields'].pop('time')
try:
dedup_tag = data['fields'].pop('dedup_tag')
data['tags'] = {'dedup_tag': dedup_tag}
except KeyError:
pass # no dedup tag, don't need to do anything
return data
def copy_measurement(self, src, dest, apply_filter=False):
done = False
offset = 0
while True:
result = self.ls.get_listens_batch_for_dump(src, self.max_time, offset)
rows = []
count = 0
for row in result.get_points(get_measurement_name(src)):
count += 1
if apply_filter:
row = self.filter_function(row)
if row:
rows.append(self.convert_to_influx_insert_format(row, quote(dest)))
self.ls.write_points_to_db(rows)
offset += DUMP_CHUNK_SIZE
if count == 0:
break
def start(self):
with self.app.app_context():
current_app.logger.info("Connecting to Influx...")
self.ls = init_influx_connection(current_app.logger, {
'REDIS_HOST': current_app.config['REDIS_HOST'],
'REDIS_PORT': current_app.config['REDIS_PORT'],
'REDIS_NAMESPACE': current_app.config['REDIS_NAMESPACE'],
'INFLUX_HOST': current_app.config['INFLUX_HOST'],
'INFLUX_PORT': current_app.config['INFLUX_PORT'],
'INFLUX_DB_NAME': current_app.config['INFLUX_DB_NAME'],
})
current_app.logger.info("Done!")
new_measurement_name = str(uuid.uuid4())
current_app.logger.info("Temporary destination measurement: %s", new_measurement_name)
current_app.logger.info("Copying listens from %s to temporary measurement...", self.user_name)
self.copy_measurement(src=self.user_name, dest=new_measurement_name, apply_filter=True)
current_app.logger.info("Done!")
current_app.logger.info("Removing user measurement...")
self.ls.delete(self.user_name)
current_app.logger.info("Done!")
current_app.logger.info("Copying listens back from temporary measurement to %s...", self.user_name)
self.copy_measurement(src=new_measurement_name, dest=self.user_name, apply_filter=False)
current_app.logger.info("Done!")
current_app.logger.info("Removing temporary measurement...")
self.ls.delete(new_measurement_name)
current_app.logger.info("Done!")
| gpl-2.0 |
pwoodworth/intellij-community | python/lib/Lib/site-packages/django/contrib/markup/templatetags/markup.py | 289 | 3522 | """
Set of "markup" template filters for Django. These filters transform plain text
markup syntaxes to HTML; currently there is support for:
* Textile, which requires the PyTextile library available at
http://loopcore.com/python-textile/
* Markdown, which requires the Python-markdown library from
http://www.freewisdom.org/projects/python-markdown
* reStructuredText, which requires docutils from http://docutils.sf.net/
"""
from django import template
from django.conf import settings
from django.utils.encoding import smart_str, force_unicode
from django.utils.safestring import mark_safe
register = template.Library()
def textile(value):
try:
import textile
except ImportError:
if settings.DEBUG:
raise template.TemplateSyntaxError("Error in {% textile %} filter: The Python textile library isn't installed.")
return force_unicode(value)
else:
return mark_safe(force_unicode(textile.textile(smart_str(value), encoding='utf-8', output='utf-8')))
textile.is_safe = True
def markdown(value, arg=''):
"""
Runs Markdown over a given value, optionally using various
extensions python-markdown supports.
Syntax::
{{ value|markdown:"extension1_name,extension2_name..." }}
To enable safe mode, which strips raw HTML and only returns HTML
generated by actual Markdown syntax, pass "safe" as the first
extension in the list.
If the version of Markdown in use does not support extensions,
they will be silently ignored.
"""
try:
import markdown
except ImportError:
if settings.DEBUG:
raise template.TemplateSyntaxError("Error in {% markdown %} filter: The Python markdown library isn't installed.")
return force_unicode(value)
else:
# markdown.version was first added in 1.6b. The only version of markdown
# to fully support extensions before 1.6b was the shortlived 1.6a.
if hasattr(markdown, 'version'):
extensions = [e for e in arg.split(",") if e]
if len(extensions) > 0 and extensions[0] == "safe":
extensions = extensions[1:]
safe_mode = True
else:
safe_mode = False
# Unicode support only in markdown v1.7 or above. Version_info
# exist only in markdown v1.6.2rc-2 or above.
if getattr(markdown, "version_info", None) < (1,7):
return mark_safe(force_unicode(markdown.markdown(smart_str(value), extensions, safe_mode=safe_mode)))
else:
return mark_safe(markdown.markdown(force_unicode(value), extensions, safe_mode=safe_mode))
else:
return mark_safe(force_unicode(markdown.markdown(smart_str(value))))
markdown.is_safe = True
def restructuredtext(value):
try:
from docutils.core import publish_parts
except ImportError:
if settings.DEBUG:
raise template.TemplateSyntaxError("Error in {% restructuredtext %} filter: The Python docutils library isn't installed.")
return force_unicode(value)
else:
docutils_settings = getattr(settings, "RESTRUCTUREDTEXT_FILTER_SETTINGS", {})
parts = publish_parts(source=smart_str(value), writer_name="html4css1", settings_overrides=docutils_settings)
return mark_safe(force_unicode(parts["fragment"]))
restructuredtext.is_safe = True
register.filter(textile)
register.filter(markdown)
register.filter(restructuredtext)
| apache-2.0 |
MIPS/external-chromium_org | build/android/buildbot/bb_device_steps.py | 23 | 12572 | #!/usr/bin/env python
# Copyright (c) 2013 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 collections
import glob
import multiprocessing
import os
import shutil
import sys
import bb_utils
import bb_annotations
sys.path.append(os.path.join(os.path.dirname(__file__), '..'))
import provision_devices
from pylib import android_commands
from pylib import constants
from pylib.gtest import gtest_config
sys.path.append(os.path.join(
constants.DIR_SOURCE_ROOT, 'third_party', 'android_testrunner'))
import errors
CHROME_SRC = constants.DIR_SOURCE_ROOT
LOGCAT_DIR = os.path.join(CHROME_SRC, 'out', 'logcat')
# Describes an instrumation test suite:
# test: Name of test we're running.
# apk: apk to be installed.
# apk_package: package for the apk to be installed.
# test_apk: apk to run tests on.
# test_data: data folder in format destination:source.
# host_driven_root: The host-driven test root directory.
# annotation: Annotation of the tests to include.
# exclude_annotation: The annotation of the tests to exclude.
I_TEST = collections.namedtuple('InstrumentationTest', [
'name', 'apk', 'apk_package', 'test_apk', 'test_data', 'host_driven_root',
'annotation', 'exclude_annotation', 'extra_flags'])
def I(name, apk, apk_package, test_apk, test_data, host_driven_root=None,
annotation=None, exclude_annotation=None, extra_flags=None):
return I_TEST(name, apk, apk_package, test_apk, test_data, host_driven_root,
annotation, exclude_annotation, extra_flags)
INSTRUMENTATION_TESTS = dict((suite.name, suite) for suite in [
I('ContentShell',
'ContentShell.apk',
'org.chromium.content_shell_apk',
'ContentShellTest',
'content:content/test/data/android/device_files'),
I('ChromiumTestShell',
'ChromiumTestShell.apk',
'org.chromium.chrome.testshell',
'ChromiumTestShellTest',
'chrome:chrome/test/data/android/device_files',
constants.CHROMIUM_TEST_SHELL_HOST_DRIVEN_DIR),
I('AndroidWebView',
'AndroidWebView.apk',
'org.chromium.android_webview.shell',
'AndroidWebViewTest',
'webview:android_webview/test/data/device_files'),
])
VALID_TESTS = set(['chromedriver', 'ui', 'unit', 'webkit', 'webkit_layout',
'webrtc'])
RunCmd = bb_utils.RunCmd
# multiprocessing map_async requires a top-level function for pickle library.
def RebootDeviceSafe(device):
"""Reboot a device, wait for it to start, and squelch timeout exceptions."""
try:
android_commands.AndroidCommands(device).Reboot(True)
except errors.DeviceUnresponsiveError as e:
return e
def RebootDevices():
"""Reboot all attached and online devices."""
# Early return here to avoid presubmit dependence on adb,
# which might not exist in this checkout.
if bb_utils.TESTING:
return
devices = android_commands.GetAttachedDevices(emulator=False)
print 'Rebooting: %s' % devices
if devices:
pool = multiprocessing.Pool(len(devices))
results = pool.map_async(RebootDeviceSafe, devices).get(99999)
for device, result in zip(devices, results):
if result:
print '%s failed to startup.' % device
if any(results):
bb_annotations.PrintWarning()
else:
print 'Reboots complete.'
def RunTestSuites(options, suites):
"""Manages an invocation of test_runner.py for gtests.
Args:
options: options object.
suites: List of suite names to run.
"""
args = ['--verbose']
if options.target == 'Release':
args.append('--release')
if options.asan:
args.append('--tool=asan')
for suite in suites:
bb_annotations.PrintNamedStep(suite)
cmd = ['build/android/test_runner.py', 'gtest', '-s', suite] + args
if suite == 'content_browsertests':
cmd.append('--num_retries=1')
RunCmd(cmd)
def RunChromeDriverTests(_):
"""Run all the steps for running chromedriver tests."""
bb_annotations.PrintNamedStep('chromedriver_annotation')
RunCmd(['chrome/test/chromedriver/run_buildbot_steps.py',
'--android-package=%s' % constants.CHROMIUM_TEST_SHELL_PACKAGE])
def InstallApk(options, test, print_step=False):
"""Install an apk to all phones.
Args:
options: options object
test: An I_TEST namedtuple
print_step: Print a buildbot step
"""
if print_step:
bb_annotations.PrintNamedStep('install_%s' % test.name.lower())
args = ['--apk', test.apk, '--apk_package', test.apk_package]
if options.target == 'Release':
args.append('--release')
RunCmd(['build/android/adb_install_apk.py'] + args, halt_on_failure=True)
def RunInstrumentationSuite(options, test, flunk_on_failure=True,
python_only=False):
"""Manages an invocation of test_runner.py for instrumentation tests.
Args:
options: options object
test: An I_TEST namedtuple
flunk_on_failure: Flunk the step if tests fail.
Python: Run only host driven Python tests.
"""
bb_annotations.PrintNamedStep('%s_instrumentation_tests' % test.name.lower())
InstallApk(options, test)
args = ['--test-apk', test.test_apk, '--test_data', test.test_data,
'--verbose']
if options.target == 'Release':
args.append('--release')
if options.asan:
args.append('--tool=asan')
if options.flakiness_server:
args.append('--flakiness-dashboard-server=%s' %
options.flakiness_server)
if test.host_driven_root:
args.append('--python_test_root=%s' % test.host_driven_root)
if test.annotation:
args.extend(['-A', test.annotation])
if test.exclude_annotation:
args.extend(['-E', test.exclude_annotation])
if test.extra_flags:
args.extend(test.extra_flags)
if python_only:
args.append('-p')
RunCmd(['build/android/test_runner.py', 'instrumentation'] + args,
flunk_on_failure=flunk_on_failure)
def RunWebkitLint(target):
"""Lint WebKit's TestExpectation files."""
bb_annotations.PrintNamedStep('webkit_lint')
RunCmd(['webkit/tools/layout_tests/run_webkit_tests.py',
'--lint-test-files',
'--chromium',
'--target', target])
def RunWebkitLayoutTests(options):
"""Run layout tests on an actual device."""
bb_annotations.PrintNamedStep('webkit_tests')
cmd_args = [
'--no-show-results',
'--no-new-test-results',
'--full-results-html',
'--clobber-old-results',
'--exit-after-n-failures', '5000',
'--exit-after-n-crashes-or-timeouts', '100',
'--debug-rwt-logging',
'--results-directory', '..layout-test-results',
'--target', options.target,
'--builder-name', options.build_properties.get('buildername', ''),
'--build-number', str(options.build_properties.get('buildnumber', '')),
'--master-name', options.build_properties.get('mastername', ''),
'--build-name', options.build_properties.get('buildername', ''),
'--platform=android']
for flag in 'test_results_server', 'driver_name', 'additional_drt_flag':
if flag in options.factory_properties:
cmd_args.extend(['--%s' % flag.replace('_', '-'),
options.factory_properties.get(flag)])
for f in options.factory_properties.get('additional_expectations', []):
cmd_args.extend(
['--additional-expectations=%s' % os.path.join(CHROME_SRC, *f)])
# TODO(dpranke): Remove this block after
# https://codereview.chromium.org/12927002/ lands.
for f in options.factory_properties.get('additional_expectations_files', []):
cmd_args.extend(
['--additional-expectations=%s' % os.path.join(CHROME_SRC, *f)])
RunCmd(['webkit/tools/layout_tests/run_webkit_tests.py'] + cmd_args,
flunk_on_failure=False)
def SpawnLogcatMonitor():
shutil.rmtree(LOGCAT_DIR, ignore_errors=True)
bb_utils.SpawnCmd([
os.path.join(CHROME_SRC, 'build', 'android', 'adb_logcat_monitor.py'),
LOGCAT_DIR])
# Wait for logcat_monitor to pull existing logcat
RunCmd(['sleep', '5'])
def ProvisionDevices(options):
# Restart adb to work around bugs, sleep to wait for usb discovery.
RunCmd(['adb', 'kill-server'])
RunCmd(['adb', 'start-server'])
RunCmd(['sleep', '1'])
bb_annotations.PrintNamedStep('provision_devices')
if options.reboot:
RebootDevices()
provision_cmd = ['build/android/provision_devices.py', '-t', options.target]
if options.auto_reconnect:
provision_cmd.append('--auto-reconnect')
RunCmd(provision_cmd)
def DeviceStatusCheck(_):
bb_annotations.PrintNamedStep('device_status_check')
RunCmd(['build/android/buildbot/bb_device_status_check.py'],
halt_on_failure=True)
def GetDeviceSetupStepCmds():
return [
('provision_devices', ProvisionDevices),
('device_status_check', DeviceStatusCheck)
]
def RunUnitTests(options):
RunTestSuites(options, gtest_config.STABLE_TEST_SUITES)
def RunInstrumentationTests(options):
for test in INSTRUMENTATION_TESTS.itervalues():
RunInstrumentationSuite(options, test)
def RunWebkitTests(options):
RunTestSuites(options, ['webkit_unit_tests'])
RunWebkitLint(options.target)
def RunWebRTCTests(options):
RunTestSuites(options, gtest_config.WEBRTC_TEST_SUITES)
def GetTestStepCmds():
return [
('chromedriver', RunChromeDriverTests),
('unit', RunUnitTests),
('ui', RunInstrumentationTests),
('webkit', RunWebkitTests),
('webkit_layout', RunWebkitLayoutTests),
('webrtc', RunWebRTCTests),
]
def LogcatDump(options):
# Print logcat, kill logcat monitor
bb_annotations.PrintNamedStep('logcat_dump')
logcat_file = os.path.join(CHROME_SRC, 'out', options.target, 'full_log')
with open(logcat_file, 'w') as f:
RunCmd([
os.path.join(CHROME_SRC, 'build', 'android', 'adb_logcat_printer.py'),
LOGCAT_DIR], stdout=f)
RunCmd(['cat', logcat_file])
def GenerateTestReport(options):
bb_annotations.PrintNamedStep('test_report')
for report in glob.glob(
os.path.join(CHROME_SRC, 'out', options.target, 'test_logs', '*.log')):
RunCmd(['cat', report])
os.remove(report)
def MainTestWrapper(options):
try:
# Spawn logcat monitor
SpawnLogcatMonitor()
# Run all device setup steps
for _, cmd in GetDeviceSetupStepCmds():
cmd(options)
if options.install:
test_obj = INSTRUMENTATION_TESTS[options.install]
InstallApk(options, test_obj, print_step=True)
if options.test_filter:
bb_utils.RunSteps(options.test_filter, GetTestStepCmds(), options)
if options.experimental:
RunTestSuites(options, gtest_config.EXPERIMENTAL_TEST_SUITES)
finally:
# Run all post test steps
LogcatDump(options)
GenerateTestReport(options)
# KillHostHeartbeat() has logic to check if heartbeat process is running,
# and kills only if it finds the process is running on the host.
provision_devices.KillHostHeartbeat()
def GetDeviceStepsOptParser():
parser = bb_utils.GetParser()
parser.add_option('--experimental', action='store_true',
help='Run experiemental tests')
parser.add_option('-f', '--test-filter', metavar='<filter>', default=[],
action='append',
help=('Run a test suite. Test suites: "%s"' %
'", "'.join(VALID_TESTS)))
parser.add_option('--asan', action='store_true', help='Run tests with asan.')
parser.add_option('--install', metavar='<apk name>',
help='Install an apk by name')
parser.add_option('--reboot', action='store_true',
help='Reboot devices before running tests')
parser.add_option(
'--flakiness-server',
help='The flakiness dashboard server to which the results should be '
'uploaded.')
parser.add_option(
'--auto-reconnect', action='store_true',
help='Push script to device which restarts adbd on disconnections.')
parser.add_option(
'--logcat-dump-output',
help='The logcat dump output will be "tee"-ed into this file')
return parser
def main(argv):
parser = GetDeviceStepsOptParser()
options, args = parser.parse_args(argv[1:])
if args:
return sys.exit('Unused args %s' % args)
unknown_tests = set(options.test_filter) - VALID_TESTS
if unknown_tests:
return sys.exit('Unknown tests %s' % list(unknown_tests))
setattr(options, 'target', options.factory_properties.get('target', 'Debug'))
MainTestWrapper(options)
if __name__ == '__main__':
sys.exit(main(sys.argv))
| bsd-3-clause |
Wapaul1/ray | python/ray/rllib/models/catalog.py | 1 | 5882 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import gym
from ray.rllib.models.action_dist import (
Categorical, Deterministic, DiagGaussian)
from ray.rllib.models.preprocessors import (
NoPreprocessor, AtariRamPreprocessor, AtariPixelPreprocessor)
from ray.rllib.models.fcnet import FullyConnectedNetwork
from ray.rllib.models.visionnet import VisionNetwork
MODEL_CONFIGS = [
"conv_filters", # Number of filters
"dim", # Dimension for ATARI
"grayscale", # Converts ATARI frame to 1 Channel Grayscale image
"zero_mean", # Changes frame to range from [-1, 1] if true
"extra_frameskip", # (int) for number of frames to skip
"fcnet_activation", # Nonlinearity for fully connected net (tanh, relu)
"fcnet_hiddens", # Number of hidden layers for fully connected net
"free_log_std" # Documented in ray.rllib.models.Model
]
class ModelCatalog(object):
"""Registry of default models and action distributions for envs.
Example:
dist_class, dist_dim = ModelCatalog.get_action_dist(env.action_space)
model = ModelCatalog.get_model(inputs, dist_dim)
dist = dist_class(model.outputs)
action_op = dist.sample()
"""
ATARI_OBS_SHAPE = (210, 160, 3)
ATARI_RAM_OBS_SHAPE = (128,)
_registered_preprocessor = dict()
@staticmethod
def get_action_dist(action_space, dist_type=None):
"""Returns action distribution class and size for the given action space.
Args:
action_space (Space): Action space of the target gym env.
dist_type (Optional[str]): Identifier of the action distribution.
Returns:
dist_class (ActionDistribution): Python class of the distribution.
dist_dim (int): The size of the input vector to the distribution.
"""
if isinstance(action_space, gym.spaces.Box):
if dist_type is None:
return DiagGaussian, action_space.shape[0] * 2
elif dist_type == 'deterministic':
return Deterministic, action_space.shape[0]
elif isinstance(action_space, gym.spaces.Discrete):
return Categorical, action_space.n
raise NotImplementedError(
"Unsupported args: {} {}".format(action_space, dist_type))
@staticmethod
def get_model(inputs, num_outputs, options=dict()):
"""Returns a suitable model conforming to given input and output specs.
Args:
inputs (Tensor): The input tensor to the model.
num_outputs (int): The size of the output vector of the model.
options (dict): Optional args to pass to the model constructor.
Returns:
model (Model): Neural network model.
"""
obs_rank = len(inputs.get_shape()) - 1
if obs_rank > 1:
return VisionNetwork(inputs, num_outputs, options)
return FullyConnectedNetwork(inputs, num_outputs, options)
@classmethod
def get_preprocessor(cls, env_name, obs_shape, options=dict()):
"""Returns a suitable processor for the given environment.
Args:
env_name (str): The name of the environment.
obs_shape (tuple): The shape of the env observation space.
options (dict): Options to pass to the preprocessor.
Returns:
preprocessor (Preprocessor): Preprocessor for the env observations.
"""
for k in options.keys():
if k not in MODEL_CONFIGS:
raise Exception(
"Unknown config key `{}`, all keys: {}".format(
k, MODEL_CONFIGS))
print("Observation shape is {}".format(obs_shape))
if env_name in cls._registered_preprocessor:
return cls._registered_preprocessor[env_name](options)
if obs_shape == cls.ATARI_OBS_SHAPE:
print("Assuming Atari pixel env, using AtariPixelPreprocessor.")
return AtariPixelPreprocessor(options)
elif obs_shape == cls.ATARI_RAM_OBS_SHAPE:
print("Assuming Atari ram env, using AtariRamPreprocessor.")
return AtariRamPreprocessor(options)
print("Non-atari env, not using any observation preprocessor.")
return NoPreprocessor(options)
@classmethod
def get_preprocessor_as_wrapper(cls, env, options=dict()):
"""Returns a preprocessor as a gym observation wrapper.
Args:
env (gym.Env): The gym environment to wrap.
options (dict): Options to pass to the preprocessor.
Returns:
wrapper (gym.ObservationWrapper): Preprocessor in wrapper form.
"""
preprocessor = cls.get_preprocessor(
env.spec.id, env.observation_space.shape, options)
return _RLlibPreprocessorWrapper(env, preprocessor)
@classmethod
def register_preprocessor(cls, env_name, preprocessor_class):
"""Register a preprocessor class for a specific environment.
Args:
env_name (str): Name of the gym env we register the
preprocessor for.
preprocessor_class (type):
Python class of the distribution.
"""
cls._registered_preprocessor[env_name] = preprocessor_class
class _RLlibPreprocessorWrapper(gym.ObservationWrapper):
"""Adapts a RLlib preprocessor for use as an observation wrapper."""
def __init__(self, env, preprocessor):
super(_RLlibPreprocessorWrapper, self).__init__(env)
self.preprocessor = preprocessor
from gym.spaces.box import Box
self.observation_space = Box(
-1.0, 1.0,
preprocessor.transform_shape(env.observation_space.shape))
def _observation(self, observation):
return self.preprocessor.transform(observation)
| apache-2.0 |
fnurl/alot | alot/commands/globals.py | 1 | 35270 | # Copyright (C) 2011-2012 Patrick Totzke <patricktotzke@gmail.com>
# This file is released under the GNU GPL, version 3 or a later revision.
# For further details see the COPYING file
from __future__ import absolute_import
from __future__ import division
import argparse
import code
import email
import email.utils
import glob
import logging
import os
import subprocess
from StringIO import StringIO
import urwid
from twisted.internet.defer import inlineCallbacks
from twisted.internet import threads
from . import Command, registerCommand
from . import CommandCanceled
from .utils import set_encrypt
from .. import commands
from .. import buffers
from .. import helper
from ..helper import split_commandstring
from ..helper import mailto_to_envelope
from ..completion import CommandLineCompleter
from ..completion import ContactsCompleter
from ..completion import AccountCompleter
from ..completion import TagsCompleter
from ..widgets.utils import DialogBox
from ..db.errors import DatabaseLockedError
from ..db.envelope import Envelope
from ..settings import settings
from ..utils import argparse as cargparse
MODE = 'global'
@registerCommand(MODE, 'exit')
class ExitCommand(Command):
"""Shut down cleanly.
The _prompt variable is for internal use only, it's used to control
prompting to close without sending, and is used by the BufferCloseCommand
if settings change after yielding to the UI.
"""
def __init__(self, _prompt=True, **kwargs):
super(ExitCommand, self).__init__(**kwargs)
self.prompt_to_send = _prompt
@inlineCallbacks
def apply(self, ui):
if settings.get('bug_on_exit'):
msg = 'really quit?'
if (yield ui.choice(msg, select='yes', cancel='no',
msg_position='left')) == 'no':
return
# check if there are any unsent messages
if self.prompt_to_send:
for buffer in ui.buffers:
if (isinstance(buffer, buffers.EnvelopeBuffer) and
not buffer.envelope.sent_time):
if (yield ui.choice('quit without sending message?',
select='yes', cancel='no',
msg_position='left')) == 'no':
raise CommandCanceled()
for b in ui.buffers:
b.cleanup()
ui.apply_command(FlushCommand(callback=ui.exit))
ui.cleanup()
if ui.db_was_locked:
msg = 'Database locked. Exit without saving?'
if (yield ui.choice(msg, select='yes', cancel='no',
msg_position='left')) == 'no':
return
ui.exit()
@registerCommand(MODE, 'search', usage='search query', arguments=[
(['--sort'], {'help': 'sort order', 'choices': [
'oldest_first', 'newest_first', 'message_id', 'unsorted']}),
(['query'], {'nargs': argparse.REMAINDER, 'help': 'search string'})])
class SearchCommand(Command):
"""open a new search buffer"""
repeatable = True
def __init__(self, query, sort=None, **kwargs):
"""
:param query: notmuch querystring
:type query: str
:param sort: how to order results. Must be one of
'oldest_first', 'newest_first', 'message_id' or
'unsorted'.
:type sort: str
"""
self.query = ' '.join(query)
self.order = sort
Command.__init__(self, **kwargs)
def apply(self, ui):
if self.query:
open_searches = ui.get_buffers_of_type(buffers.SearchBuffer)
to_be_focused = None
for sb in open_searches:
if sb.querystring == self.query:
to_be_focused = sb
if to_be_focused:
if ui.current_buffer != to_be_focused:
ui.buffer_focus(to_be_focused)
else:
# refresh an already displayed search
ui.current_buffer.rebuild()
ui.update()
else:
ui.buffer_open(buffers.SearchBuffer(ui, self.query,
sort_order=self.order))
else:
ui.notify('empty query string')
@registerCommand(MODE, 'prompt', arguments=[
(['startwith'], {'nargs': '?', 'default': '', 'help': 'initial content'})])
class PromptCommand(Command):
"""prompts for commandline and interprets it upon select"""
def __init__(self, startwith='', **kwargs):
"""
:param startwith: initial content of the prompt widget
:type startwith: str
"""
self.startwith = startwith
Command.__init__(self, **kwargs)
@inlineCallbacks
def apply(self, ui):
logging.info('open command shell')
mode = ui.mode or 'global'
cmpl = CommandLineCompleter(ui.dbman, mode, ui.current_buffer)
cmdline = yield ui.prompt(
'',
text=self.startwith,
completer=cmpl,
history=ui.commandprompthistory)
logging.debug('CMDLINE: %s', cmdline)
# interpret and apply commandline
if cmdline:
# save into prompt history
ui.commandprompthistory.append(cmdline)
ui.apply_commandline(cmdline)
else:
raise CommandCanceled()
@registerCommand(MODE, 'refresh')
class RefreshCommand(Command):
"""refresh the current buffer"""
repeatable = True
def apply(self, ui):
ui.current_buffer.rebuild()
ui.update()
@registerCommand(
MODE, 'shellescape', arguments=[
(['--spawn'], {'action': cargparse.BooleanAction, 'default': None,
'help': 'run in terminal window'}),
(['--thread'], {'action': cargparse.BooleanAction, 'default': None,
'help': 'run in separate thread'}),
(['--refocus'], {'action': cargparse.BooleanAction,
'help': 'refocus current buffer after command '
'has finished'}),
(['cmd'], {'help': 'command line to execute'})],
forced={'shell': True},
)
class ExternalCommand(Command):
"""run external command"""
repeatable = True
def __init__(self, cmd, stdin=None, shell=False, spawn=False,
refocus=True, thread=False, on_success=None, **kwargs):
"""
:param cmd: the command to call
:type cmd: list or str
:param stdin: input to pipe to the process
:type stdin: file or str
:param spawn: run command in a new terminal
:type spawn: bool
:param shell: let shell interpret command string
:type shell: bool
:param thread: run asynchronously, don't block alot
:type thread: bool
:param refocus: refocus calling buffer after cmd termination
:type refocus: bool
:param on_success: code to execute after command successfully exited
:type on_success: callable
"""
logging.debug({'spawn': spawn})
# make sure cmd is a list of str
if isinstance(cmd, unicode):
# convert cmdstring to list: in case shell==True,
# Popen passes only the first item in the list to $SHELL
cmd = [cmd] if shell else split_commandstring(cmd)
# determine complete command list to pass
touchhook = settings.get_hook('touch_external_cmdlist')
# filter cmd, shell and thread through hook if defined
if touchhook is not None:
logging.debug('calling hook: touch_external_cmdlist')
res = touchhook(cmd, shell=shell, spawn=spawn, thread=thread)
logging.debug('got: %s', res)
cmd, shell, self.in_thread = res
# otherwise if spawn requested and X11 is running
elif spawn:
if 'DISPLAY' in os.environ:
term_cmd = settings.get('terminal_cmd', '')
logging.info('spawn in terminal: %s', term_cmd)
termcmdlist = split_commandstring(term_cmd)
cmd = termcmdlist + cmd
else:
thread = False
self.cmdlist = cmd
self.stdin = stdin
self.shell = shell
self.refocus = refocus
self.in_thread = thread
self.on_success = on_success
Command.__init__(self, **kwargs)
def apply(self, ui):
logging.debug('cmdlist: %s', self.cmdlist)
callerbuffer = ui.current_buffer
# set standard input for subcommand
stdin = None
if self.stdin is not None:
# wrap strings in StrinIO so that they behaves like a file
if isinstance(self.stdin, unicode):
stdin = StringIO(self.stdin)
else:
stdin = self.stdin
def afterwards(data):
if data == 'success':
if callable(self.on_success):
self.on_success()
else:
ui.notify(data, priority='error')
if self.refocus and callerbuffer in ui.buffers:
logging.info('refocussing')
ui.buffer_focus(callerbuffer)
logging.info('calling external command: %s', self.cmdlist)
def thread_code(*_):
try:
if stdin is None:
proc = subprocess.Popen(self.cmdlist, shell=self.shell,
stderr=subprocess.PIPE)
ret = proc.wait()
err = proc.stderr.read()
else:
proc = subprocess.Popen(self.cmdlist, shell=self.shell,
stdin=subprocess.PIPE,
stderr=subprocess.PIPE)
_, err = proc.communicate(stdin.read())
ret = proc.wait()
if ret == 0:
return 'success'
else:
return err.strip()
except OSError as e:
return str(e)
if self.in_thread:
d = threads.deferToThread(thread_code)
d.addCallback(afterwards)
else:
ui.mainloop.screen.stop()
ret = thread_code()
ui.mainloop.screen.start()
# make sure urwid renders its canvas at the correct size
ui.mainloop.screen_size = None
ui.mainloop.draw_screen()
afterwards(ret)
class EditCommand(ExternalCommand):
"""edit a file"""
def __init__(self, path, spawn=None, thread=None, **kwargs):
"""
:param path: path to the file to be edited
:type path: str
:param spawn: force running edtor in a new terminal
:type spawn: bool
:param thread: run asynchronously, don't block alot
:type thread: bool
"""
self.spawn = spawn
if spawn is None:
self.spawn = settings.get('editor_spawn')
self.thread = thread
if thread is None:
self.thread = settings.get('editor_in_thread')
editor_cmdstring = None
if os.path.isfile('/usr/bin/editor'):
editor_cmdstring = '/usr/bin/editor'
editor_cmdstring = os.environ.get('EDITOR', editor_cmdstring)
editor_cmdstring = settings.get('editor_cmd') or editor_cmdstring
logging.debug('using editor_cmd: %s', editor_cmdstring)
self.cmdlist = None
if '%s' in editor_cmdstring:
cmdstring = editor_cmdstring.replace('%s',
helper.shell_quote(path))
self.cmdlist = split_commandstring(cmdstring)
else:
self.cmdlist = split_commandstring(editor_cmdstring) + [path]
logging.debug({'spawn: ': self.spawn, 'in_thread': self.thread})
ExternalCommand.__init__(self, self.cmdlist,
spawn=self.spawn, thread=self.thread,
**kwargs)
def apply(self, ui):
if self.cmdlist is None:
ui.notify('no editor set', priority='error')
else:
return ExternalCommand.apply(self, ui)
@registerCommand(MODE, 'pyshell')
class PythonShellCommand(Command):
"""open an interactive python shell for introspection"""
repeatable = True
def apply(self, ui):
ui.mainloop.screen.stop()
code.interact(local=locals())
ui.mainloop.screen.start()
@registerCommand(MODE, 'repeat')
class RepeatCommand(Command):
"""Repeats the command executed last time"""
def __init__(self, **kwargs):
Command.__init__(self, **kwargs)
def apply(self, ui):
if ui.last_commandline is not None:
ui.apply_commandline(ui.last_commandline)
else:
ui.notify('no last command')
@registerCommand(MODE, 'call', arguments=[
(['command'], {'help': 'python command string to call'})])
class CallCommand(Command):
"""Executes python code"""
repeatable = True
def __init__(self, command, **kwargs):
"""
:param command: python command string to call
:type command: str
"""
Command.__init__(self, **kwargs)
self.command = command
def apply(self, ui):
try:
hooks = settings.hooks
if hooks:
env = {'ui': ui, 'settings': settings}
for k, v in env.iteritems():
if k not in hooks.__dict__:
hooks.__dict__[k] = v
exec(self.command)
except Exception as e:
logging.exception(e)
msg = 'an error occurred during execution of "%s":\n%s'
ui.notify(msg % (self.command, e), priority='error')
@registerCommand(MODE, 'bclose', arguments=[
(['--redraw'],
{'action': cargparse.BooleanAction,
'help': 'redraw current buffer after command has finished'}),
(['--force'],
{'action': 'store_true', 'help': 'never ask for confirmation'})])
class BufferCloseCommand(Command):
"""close a buffer"""
repeatable = True
def __init__(self, buffer=None, force=False, redraw=True, **kwargs):
"""
:param buffer: the buffer to close or None for current
:type buffer: `alot.buffers.Buffer`
:param force: force buffer close
:type force: bool
"""
self.buffer = buffer
self.force = force
self.redraw = redraw
Command.__init__(self, **kwargs)
@inlineCallbacks
def apply(self, ui):
def one_buffer(prompt=True):
"""Helper to handle the case on only one buffer being opened.
prompt is a boolean that is passed to ExitCommand() as the _prompt
keyword argument.
"""
# If there is only one buffer and the settings don't allow using
# closebuffer to exit, then just stop.
if not settings.get('quit_on_last_bclose'):
msg = ('not closing last remaining buffer as '
'global.quit_on_last_bclose is set to False')
logging.info(msg)
ui.notify(msg, priority='error')
# Otherwise pass directly to exit command, which also prommpts for
# 'close without sending'
else:
logging.info('closing the last buffer, exiting')
ui.apply_command(ExitCommand(_prompt=prompt))
if self.buffer is None:
self.buffer = ui.current_buffer
if len(ui.buffers) == 1:
one_buffer()
return
if (isinstance(self.buffer, buffers.EnvelopeBuffer) and
not self.buffer.envelope.sent_time):
if (not self.force and (yield ui.choice('close without sending?',
select='yes', cancel='no',
msg_position='left')) ==
'no'):
raise CommandCanceled()
# Because we yield above it is possible that the settings or the number
# of buffers chould change, so retest.
if len(ui.buffers) == 1:
one_buffer(prompt=False)
else:
ui.buffer_close(self.buffer, self.redraw)
@registerCommand(MODE, 'bprevious', forced={'offset': -1},
help='focus previous buffer')
@registerCommand(MODE, 'bnext', forced={'offset': +1},
help='focus next buffer')
@registerCommand(
MODE, 'buffer',
arguments=[(['index'], {'type': int, 'help': 'buffer index to focus'})],
help='focus buffer with given index')
class BufferFocusCommand(Command):
"""focus a :class:`~alot.buffers.Buffer`"""
repeatable = True
def __init__(self, buffer=None, index=None, offset=0, **kwargs):
"""
:param buffer: the buffer to focus or None
:type buffer: `alot.buffers.Buffer`
:param index: index (in bufferlist) of the buffer to focus.
:type index: int
:param offset: position of the buffer to focus relative to the
currently focussed one. This is used only if `buffer`
is set to `None`
:type offset: int
"""
self.buffer = buffer
self.index = index
self.offset = offset
Command.__init__(self, **kwargs)
def apply(self, ui):
if self.buffer is None:
if self.index is not None:
try:
self.buffer = ui.buffers[self.index]
except IndexError:
ui.notify('no buffer exists at index %d' % self.index)
return
else:
self.index = ui.buffers.index(ui.current_buffer)
num = len(ui.buffers)
self.buffer = ui.buffers[(self.index + self.offset) % num]
ui.buffer_focus(self.buffer)
@registerCommand(MODE, 'bufferlist')
class OpenBufferlistCommand(Command):
"""open a list of active buffers"""
def __init__(self, filtfun=lambda x: x, **kwargs):
"""
:param filtfun: filter to apply to displayed list
:type filtfun: callable (str->bool)
"""
self.filtfun = filtfun
Command.__init__(self, **kwargs)
def apply(self, ui):
blists = ui.get_buffers_of_type(buffers.BufferlistBuffer)
if blists:
ui.buffer_focus(blists[0])
else:
bl = buffers.BufferlistBuffer(ui, self.filtfun)
ui.buffer_open(bl)
@registerCommand(MODE, 'taglist', arguments=[
(['--tags'], {'nargs': '+', 'help': 'tags to display'}),
])
class TagListCommand(Command):
"""opens taglist buffer"""
def __init__(self, filtfun=lambda x: x, tags=None, **kwargs):
"""
:param filtfun: filter to apply to displayed list
:type filtfun: callable (str->bool)
"""
self.filtfun = filtfun
self.tags = tags
Command.__init__(self, **kwargs)
def apply(self, ui):
tags = self.tags or ui.dbman.get_all_tags()
blists = ui.get_buffers_of_type(buffers.TagListBuffer)
if blists:
buf = blists[0]
buf.tags = tags
buf.rebuild()
ui.buffer_focus(buf)
else:
ui.buffer_open(buffers.TagListBuffer(ui, tags, self.filtfun))
@registerCommand(MODE, 'flush')
class FlushCommand(Command):
"""flush write operations or retry until committed"""
repeatable = True
def __init__(self, callback=None, silent=False, **kwargs):
"""
:param callback: function to call after successful writeout
:type callback: callable
"""
Command.__init__(self, **kwargs)
self.callback = callback
self.silent = silent
def apply(self, ui):
try:
ui.dbman.flush()
if callable(self.callback):
self.callback()
logging.debug('flush complete')
if ui.db_was_locked:
if not self.silent:
ui.notify('changes flushed')
ui.db_was_locked = False
ui.update()
except DatabaseLockedError:
timeout = settings.get('flush_retry_timeout')
if timeout > 0:
def f(*_):
self.apply(ui)
ui.mainloop.set_alarm_in(timeout, f)
if not ui.db_was_locked:
if not self.silent:
ui.notify('index locked, will try again in %d secs'
% timeout)
ui.db_was_locked = True
ui.update()
return
# TODO: choices
@registerCommand(MODE, 'help', arguments=[
(['commandname'], {'help': 'command or \'bindings\''})])
class HelpCommand(Command):
"""display help for a command. Use \'bindings\' to display all keybings
interpreted in current mode.'"""
def __init__(self, commandname='', **kwargs):
"""
:param commandname: command to document
:type commandname: str
"""
Command.__init__(self, **kwargs)
self.commandname = commandname
def apply(self, ui):
logging.debug('HELP')
if self.commandname == 'bindings':
text_att = settings.get_theming_attribute('help', 'text')
title_att = settings.get_theming_attribute('help', 'title')
section_att = settings.get_theming_attribute('help', 'section')
# get mappings
globalmaps, modemaps = settings.get_keybindings(ui.mode)
# build table
maxkeylength = len(max((modemaps).keys() + globalmaps.keys(),
key=len))
keycolumnwidth = maxkeylength + 2
linewidgets = []
# mode specific maps
if modemaps:
txt = (section_att, '\n%s-mode specific maps' % ui.mode)
linewidgets.append(urwid.Text(txt))
for (k, v) in modemaps.iteritems():
line = urwid.Columns([('fixed', keycolumnwidth,
urwid.Text((text_att, k))),
urwid.Text((text_att, v))])
linewidgets.append(line)
# global maps
linewidgets.append(urwid.Text((section_att, '\nglobal maps')))
for (k, v) in globalmaps.iteritems():
if k not in modemaps:
line = urwid.Columns(
[('fixed', keycolumnwidth, urwid.Text((text_att, k))),
urwid.Text((text_att, v))])
linewidgets.append(line)
body = urwid.ListBox(linewidgets)
titletext = 'Bindings Help (escape cancels)'
box = DialogBox(body, titletext,
bodyattr=text_att,
titleattr=title_att)
# put promptwidget as overlay on main widget
overlay = urwid.Overlay(box, ui.root_widget, 'center',
('relative', 70), 'middle',
('relative', 70))
ui.show_as_root_until_keypress(overlay, 'esc')
else:
logging.debug('HELP %s', self.commandname)
parser = commands.lookup_parser(self.commandname, ui.mode)
if parser:
ui.notify(parser.format_help(), block=True)
else:
ui.notify('command not known: %s' % self.commandname,
priority='error')
@registerCommand(MODE, 'compose', arguments=[
(['--sender'], {'nargs': '?', 'help': 'sender'}),
(['--template'], {'nargs': '?',
'help': 'path to a template message file'}),
(['--subject'], {'nargs': '?', 'help': 'subject line'}),
(['--to'], {'nargs': '+', 'help': 'recipients'}),
(['--cc'], {'nargs': '+', 'help': 'copy to'}),
(['--bcc'], {'nargs': '+', 'help': 'blind copy to'}),
(['--attach'], {'nargs': '+', 'help': 'attach files'}),
(['--omit_signature'], {'action': 'store_true',
'help': 'do not add signature'}),
(['--spawn'], {'action': cargparse.BooleanAction, 'default': None,
'help': 'spawn editor in new terminal'}),
(['rest'], {'nargs': '*'}),
])
class ComposeCommand(Command):
"""compose a new email"""
def __init__(self, envelope=None, headers=None, template=None, sender=u'',
subject=u'', to=None, cc=None, bcc=None, attach=None,
omit_signature=False, spawn=None, rest=None, encrypt=False,
**kwargs):
"""
:param envelope: use existing envelope
:type envelope: :class:`~alot.db.envelope.Envelope`
:param headers: forced header values
:type headers: dict (str->str)
:param template: name of template to parse into the envelope after
creation. This should be the name of a file in your
template_dir
:type template: str
:param sender: From-header value
:type sender: str
:param subject: Subject-header value
:type subject: str
:param to: To-header value
:type to: str
:param cc: Cc-header value
:type cc: str
:param bcc: Bcc-header value
:type bcc: str
:param attach: Path to files to be attached (globable)
:type attach: str
:param omit_signature: do not attach/append signature
:type omit_signature: bool
:param spawn: force spawning of editor in a new terminal
:type spawn: bool
:param rest: remaining parameters. These can start with
'mailto' in which case it is interpreted as mailto string.
Otherwise it will be interpreted as recipients (to) header
:type rest: list(str)
:param encrypt: if the email should be encrypted
:type encrypt: bool
"""
Command.__init__(self, **kwargs)
self.envelope = envelope
self.template = template
self.headers = headers or {}
self.sender = sender
self.subject = subject
self.to = to or []
self.cc = cc or []
self.bcc = bcc or []
self.attach = attach
self.omit_signature = omit_signature
self.force_spawn = spawn
self.rest = ' '.join(rest or [])
self.encrypt = encrypt
@inlineCallbacks
def apply(self, ui):
if self.envelope is None:
if self.rest:
if self.rest.startswith('mailto'):
self.envelope = mailto_to_envelope(self.rest)
else:
self.envelope = Envelope()
self.envelope.add('To', self.rest)
else:
self.envelope = Envelope()
if self.template is not None:
# get location of tempsdir, containing msg templates
tempdir = settings.get('template_dir')
tempdir = os.path.expanduser(tempdir)
if not tempdir:
xdgdir = os.environ.get('XDG_CONFIG_HOME',
os.path.expanduser('~/.config'))
tempdir = os.path.join(xdgdir, 'alot', 'templates')
path = os.path.expanduser(self.template)
if not os.path.dirname(path): # use tempsdir
if not os.path.isdir(tempdir):
ui.notify('no templates directory: %s' % tempdir,
priority='error')
return
path = os.path.join(tempdir, path)
if not os.path.isfile(path):
ui.notify('could not find template: %s' % path,
priority='error')
return
try:
with open(path) as f:
self.envelope.parse_template(f.read())
except Exception as e:
ui.notify(str(e), priority='error')
return
# set forced headers
for key, value in self.headers.iteritems():
self.envelope.add(key, value)
# set forced headers for separate parameters
if self.sender:
self.envelope.add('From', self.sender)
if self.subject:
self.envelope.add('Subject', self.subject)
if self.to:
self.envelope.add('To', ','.join(self.to))
if self.cc:
self.envelope.add('Cc', ','.join(self.cc))
if self.bcc:
self.envelope.add('Bcc', ','.join(self.bcc))
# get missing From header
if 'From' not in self.envelope.headers:
accounts = settings.get_accounts()
if len(accounts) == 1:
a = accounts[0]
fromstring = email.utils.formataddr((a.realname, a.address))
self.envelope.add('From', fromstring)
else:
cmpl = AccountCompleter()
fromaddress = yield ui.prompt('From', completer=cmpl,
tab=1, history=ui.senderhistory)
if fromaddress is None:
raise CommandCanceled()
ui.senderhistory.append(fromaddress)
self.envelope.add('From', fromaddress)
# find out the right account
sender = self.envelope.get('From')
name, addr = email.Utils.parseaddr(sender)
account = settings.get_account_by_address(addr)
if account is None:
accounts = settings.get_accounts()
if not accounts:
ui.notify('no accounts set.', priority='error')
return
account = accounts[0]
# add signature
if not self.omit_signature and account.signature:
logging.debug('has signature')
sig = os.path.expanduser(account.signature)
if os.path.isfile(sig):
logging.debug('is file')
if account.signature_as_attachment:
name = account.signature_filename or None
self.envelope.attach(sig, filename=name)
logging.debug('attached')
else:
with open(sig) as f:
sigcontent = f.read()
enc = helper.guess_encoding(sigcontent)
mimetype = helper.guess_mimetype(sigcontent)
if mimetype.startswith('text'):
sigcontent = helper.string_decode(sigcontent, enc)
self.envelope.body += '\n' + sigcontent
else:
ui.notify('could not locate signature: %s' % sig,
priority='error')
if (yield ui.choice('send without signature?', 'yes',
'no')) == 'no':
return
# Figure out whether we should GPG sign messages by default
# and look up key if so
self.envelope.sign = account.sign_by_default
self.envelope.sign_key = account.gpg_key
# get missing To header
if 'To' not in self.envelope.headers:
allbooks = not settings.get('complete_matching_abook_only')
logging.debug(allbooks)
abooks = settings.get_addressbooks(order=[account],
append_remaining=allbooks)
logging.debug(abooks)
completer = ContactsCompleter(abooks)
to = yield ui.prompt('To', completer=completer,
history=ui.recipienthistory)
if to is None:
raise CommandCanceled()
to = to.strip(' \t\n,')
ui.recipienthistory.append(to)
self.envelope.add('To', to)
if settings.get('ask_subject') and \
'Subject' not in self.envelope.headers:
subject = yield ui.prompt('Subject')
logging.debug('SUBJECT: "%s"', subject)
if subject is None:
raise CommandCanceled()
self.envelope.add('Subject', subject)
if settings.get('compose_ask_tags'):
comp = TagsCompleter(ui.dbman)
tagsstring = yield ui.prompt('Tags', completer=comp)
tags = [t for t in tagsstring.split(',') if t]
if tags is None:
raise CommandCanceled()
self.envelope.tags = tags
if self.attach:
for gpath in self.attach:
for a in glob.glob(gpath):
self.envelope.attach(a)
logging.debug('attaching: %s', a)
# set encryption if needed
if self.encrypt or account.encrypt_by_default == u"all":
logging.debug("Trying to encrypt message because encrypt=%s and "
"encrypt_by_default=%s", self.encrypt,
account.encrypt_by_default)
yield set_encrypt(ui, self.envelope, block_error=self.encrypt)
elif account.encrypt_by_default == u"trusted":
logging.debug("Trying to encrypt message because "
"account.encrypt_by_default=%s",
account.encrypt_by_default)
yield set_encrypt(ui, self.envelope, block_error=self.encrypt, signed_only=True)
else:
logging.debug("No encryption by default, encrypt_by_default=%s",
account.encrypt_by_default)
cmd = commands.envelope.EditCommand(envelope=self.envelope,
spawn=self.force_spawn,
refocus=False)
ui.apply_command(cmd)
@registerCommand(
MODE, 'move', help='move focus in current buffer',
arguments=[
(['movement'],
{'nargs': argparse.REMAINDER,
'help': 'up, down, [half]page up, [half]page down, first'})])
class MoveCommand(Command):
"""move in widget"""
def __init__(self, movement=None, **kwargs):
if movement is None:
self.movement = ''
else:
self.movement = ' '.join(movement)
Command.__init__(self, **kwargs)
def apply(self, ui):
if self.movement in ['up', 'down', 'page up', 'page down']:
ui.mainloop.process_input([self.movement])
elif self.movement in ['halfpage down', 'halfpage up']:
ui.mainloop.process_input(
ui.mainloop.screen_size[1] // 2 * [self.movement.split()[-1]])
elif self.movement == 'first':
if hasattr(ui.current_buffer, "focus_first"):
ui.current_buffer.focus_first()
ui.update()
elif self.movement == 'last':
if hasattr(ui.current_buffer, "focus_last"):
ui.current_buffer.focus_last()
ui.update()
else:
ui.notify('unknown movement: ' + self.movement,
priority='error')
| gpl-3.0 |
bretttegart/treadmill | lib/python/treadmill/runtime/runtime_base.py | 1 | 3014 | """Base runtime interface.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import abc
import logging
import os
import shutil
import six
from treadmill import appcfg
from treadmill import exc
from treadmill import supervisor
from treadmill.appcfg import abort as app_abort
from treadmill.appcfg import manifest as app_manifest
_LOGGER = logging.getLogger(__name__)
@six.add_metaclass(abc.ABCMeta)
class RuntimeBase(object):
"""Base class for a Treadmill runtime.
:param tm_env:
The Treadmill application environment
:type tm_env:
`appenv.AppEnvironment`
:param container_dir:
Full path to the application container directory
:type container_dir:
``str``
"""
__slots__ = (
'_tm_env',
'_service',
'_param',
)
def __init__(self, tm_env, container_dir, param=None):
self._tm_env = tm_env
self._param = {} if param is None else param
self._service = supervisor.open_service(container_dir)
@abc.abstractmethod
def _can_run(self, manifest):
"""Determines if the manifest can run with the runtime.
:returns:
``True`` if can run
:rtype:
``Boolean``
"""
pass
@abc.abstractmethod
def _run(self, manifest):
"""Prepares container environment and exec's container."""
pass
def run(self):
"""Prepares container environment and exec's container
The function is intended to be invoked from 'run' script and never
returns.
:returns:
This function never returns
"""
manifest_file = os.path.join(self._service.data_dir, appcfg.APP_JSON)
manifest = app_manifest.read(manifest_file)
if not self._can_run(manifest):
raise exc.ContainerSetupError('invalid_type',
app_abort.AbortedReason.INVALID_TYPE)
self._run(manifest)
@abc.abstractmethod
def _finish(self):
"""Frees allocated resources and mark then as available."""
pass
def finish(self):
"""Frees allocated resources and mark then as available."""
# Required because on windows log files are archived and deleted
# which cannot happen when the supervisor/log is still running.
supervisor.ensure_not_supervised(self._service.directory)
self._finish()
shutil.rmtree(self._service.directory)
_LOGGER.info('Finished cleanup: %s', self._service.directory)
@abc.abstractmethod
def kill(self):
"""Kills a container."""
pass
# pylint: disable=W0613
# tm_env for method in child class to use
@classmethod
def manifest(cls, tm_env, manifest):
"""Add runtime modification to manifest, default does nothing
"""
app_manifest.add_manifest_features(manifest, cls.name)
| apache-2.0 |
blablacar/exabgp | lib/exabgp/reactor/api/transcoder.py | 6 | 3398 | import sys
import json
from exabgp.bgp.message import Message
from exabgp.bgp.message import Open
from exabgp.bgp.message import Notification
from exabgp.bgp.message.open.capability import Negotiated
from exabgp.version import json as json_version
from exabgp.reactor.api.response import Response
from exabgp.protocol.ip import IPv4
from exabgp.bgp.message.open.asn import ASN
class _FakeNeighbor (object):
def __init__ (self,local,remote,asn,peer):
self.local_address = IPv4(local)
self.peer_address = IPv4(remote)
self.peer_as = ASN(asn)
self.local_as = ASN(peer)
class Transcoder (object):
seen_open = {
'send': None,
'receive': None,
}
negotiated = None
json = Response.JSON(json_version)
def __init__ (self, src='json', dst='json'):
if src != 'json':
raise RuntimeError('left as an exercise to the reader')
if dst != 'json':
raise RuntimeError('left as an exercise to the reader')
self.convert = self._from_json
self.encoder = self.json
def _state (self):
self.seen_open['send'] = None
self.seen_open['receive'] = None
self.negotiated = None
def _open (self,direction,message):
self.seen_open[direction] = message
if all(self.seen_open.values()):
self.negotiated = Negotiated(None)
self.negotiated.sent(self.seen_open['send'])
self.negotiated.received(self.seen_open['receive'])
def _from_json (self, string):
try:
parsed = json.loads(string)
except ValueError:
print >> sys.stderr, 'invalid JSON message'
sys.exit(1)
if parsed.get('exabgp','0.0.0') != json_version:
print >> sys.stderr, 'invalid json version', string
sys.exit(1)
content = parsed.get('type','')
if not content:
print >> sys.stderr, 'invalid json content', string
sys.exit(1)
neighbor = _FakeNeighbor(
parsed['neighbor']['address']['local'],
parsed['neighbor']['address']['peer'],
parsed['neighbor']['asn']['local'],
parsed['neighbor']['asn']['peer'],
)
if content == 'state':
self._state()
return string
direction = parsed['neighbor']['direction']
category = parsed['neighbor']['message']['category']
header = parsed['neighbor']['message']['header']
body = parsed['neighbor']['message']['body']
raw = ''.join(chr(int(body[_:_+2],16)) for _ in range(0,len(body),2))
if content == 'open':
message = Open.unpack_message(raw)
self._open(direction,message)
return self.encoder.open(neighbor,direction,message,header,body)
if content == 'keapalive':
return self.encoder.keepalive(neighbor,direction,header,body)
if content == 'notification':
message = Notification.unpack_message(raw)
return self.encoder.notification(neighbor,direction,message,header,body)
if not self.negotiated:
print >> sys.stderr, 'invalid message sequence, open not exchange not complete', string
sys.exit(1)
message = Message.unpack(category,raw,self.negotiated)
if content == 'update':
return self.encoder.update(neighbor, direction, message, header,body)
if content == 'eor': # XXX: Should not be required
return self.encoder.update(neighbor, direction, message, header,body)
if content == 'refresh':
return self.json.refresh(neighbor, direction, message, header,body)
if content == 'operational':
return self.json.refresh(neighbor, direction, message, header,body)
raise RuntimeError('the programer is a monkey and forgot a JSON message type')
| bsd-3-clause |
mKeRix/home-assistant | homeassistant/components/lock/device_action.py | 19 | 2752 | """Provides device automations for Lock."""
from typing import List, Optional
import voluptuous as vol
from homeassistant.const import (
ATTR_ENTITY_ID,
ATTR_SUPPORTED_FEATURES,
CONF_DEVICE_ID,
CONF_DOMAIN,
CONF_ENTITY_ID,
CONF_TYPE,
SERVICE_LOCK,
SERVICE_OPEN,
SERVICE_UNLOCK,
)
from homeassistant.core import Context, HomeAssistant
from homeassistant.helpers import entity_registry
import homeassistant.helpers.config_validation as cv
from . import DOMAIN, SUPPORT_OPEN
ACTION_TYPES = {"lock", "unlock", "open"}
ACTION_SCHEMA = cv.DEVICE_ACTION_BASE_SCHEMA.extend(
{
vol.Required(CONF_TYPE): vol.In(ACTION_TYPES),
vol.Required(CONF_ENTITY_ID): cv.entity_domain(DOMAIN),
}
)
async def async_get_actions(hass: HomeAssistant, device_id: str) -> List[dict]:
"""List device actions for Lock devices."""
registry = await entity_registry.async_get_registry(hass)
actions = []
# Get all the integrations entities for this device
for entry in entity_registry.async_entries_for_device(registry, device_id):
if entry.domain != DOMAIN:
continue
# Add actions for each entity that belongs to this integration
actions.append(
{
CONF_DEVICE_ID: device_id,
CONF_DOMAIN: DOMAIN,
CONF_ENTITY_ID: entry.entity_id,
CONF_TYPE: "lock",
}
)
actions.append(
{
CONF_DEVICE_ID: device_id,
CONF_DOMAIN: DOMAIN,
CONF_ENTITY_ID: entry.entity_id,
CONF_TYPE: "unlock",
}
)
state = hass.states.get(entry.entity_id)
if state:
features = state.attributes.get(ATTR_SUPPORTED_FEATURES, 0)
if features & (SUPPORT_OPEN):
actions.append(
{
CONF_DEVICE_ID: device_id,
CONF_DOMAIN: DOMAIN,
CONF_ENTITY_ID: entry.entity_id,
CONF_TYPE: "open",
}
)
return actions
async def async_call_action_from_config(
hass: HomeAssistant, config: dict, variables: dict, context: Optional[Context]
) -> None:
"""Execute a device action."""
config = ACTION_SCHEMA(config)
service_data = {ATTR_ENTITY_ID: config[CONF_ENTITY_ID]}
if config[CONF_TYPE] == "lock":
service = SERVICE_LOCK
elif config[CONF_TYPE] == "unlock":
service = SERVICE_UNLOCK
elif config[CONF_TYPE] == "open":
service = SERVICE_OPEN
await hass.services.async_call(
DOMAIN, service, service_data, blocking=True, context=context
)
| mit |
sarvex/tensorflow | tensorflow/python/compiler/tensorrt/test/base_test.py | 6 | 11066 | # Copyright 2018 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Basic tests for TF-TensorRT integration."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
from tensorflow.python.compiler.tensorrt.test import tf_trt_integration_test_base as trt_test
from tensorflow.python.framework import constant_op
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import ops
from tensorflow.python.ops import array_ops
from tensorflow.python.ops import math_ops
from tensorflow.python.ops import nn
from tensorflow.python.ops import nn_ops
from tensorflow.python.platform import test
class SimpleSingleEngineTest(trt_test.TfTrtIntegrationTestBase):
def GraphFn(self, inp):
"""Create a graph containing single segment."""
dtype = inp.dtype
conv_filter = constant_op.constant(
[[[[1., 0.5, 4., 6., 0.5, 1.], [1., 0.5, 1., 1., 0.5, 1.]]]],
name="weights",
dtype=dtype)
conv = nn.conv2d(
input=inp,
filter=conv_filter,
strides=[1, 2, 2, 1],
padding="SAME",
name="conv")
bias = constant_op.constant([4., 1.5, 2., 3., 5., 7.],
name="bias",
dtype=dtype)
added = nn.bias_add(conv, bias, name="bias_add")
relu = nn.relu(added, "relu")
identity = array_ops.identity(relu, "identity")
pool = nn_ops.max_pool(
identity, [1, 2, 2, 1], [1, 2, 2, 1], "VALID", name="max_pool")
return array_ops.squeeze(pool, name="output_0")
def GetParams(self):
# TODO(aaroey): test graph with different dtypes.
return self.BuildParams(self.GraphFn, dtypes.float32, [[100, 24, 24, 2]],
[[100, 6, 6, 6]])
def ExpectedEnginesToBuild(self, run_params):
"""Return the expected engines to build."""
return {
"TRTEngineOp_0": [
"weights", "conv", "bias", "bias_add", "relu", "identity",
"max_pool"
]
}
class SimpleMultiEnginesTest(trt_test.TfTrtIntegrationTestBase):
def GraphFn(self, inp):
"""Create a graph containing multiple segment."""
dtype = inp.dtype
conv_filter = constant_op.constant(
[[[[1., 0.5, 4., 6., 0.5, 1.], [1., 0.5, 1., 1., 0.5, 1.]]]],
name="weights",
dtype=dtype)
conv = nn.conv2d(
input=inp,
filter=conv_filter,
strides=[1, 2, 2, 1],
padding="SAME",
name="conv")
c1 = constant_op.constant(
np.random.randn(12, 12, 6), dtype=dtype, name="c1")
p = math_ops.mul(conv, c1, name="mul")
c2 = constant_op.constant(
np.random.randn(12, 12, 6), dtype=dtype, name="c2")
q = math_ops.div(conv, c2, name="div")
edge = self.trt_incompatible_op(q, name="incompatible")
one = constant_op.constant(1, name="one", dtype=dtype)
edge = math_ops.sub(one, edge, name="one_sub")
edge = math_ops.div(edge, edge, name="div1")
r = math_ops.add(edge, edge, name="add")
p = math_ops.sub(p, edge, name="sub")
q = math_ops.mul(q, edge, name="mul1")
s = math_ops.add(p, q, name="add1")
s = math_ops.sub(s, r, name="sub1")
return array_ops.squeeze(s, name="output_0")
def GetParams(self):
# TODO(aaroey): test graph with different dtypes.
return self.BuildParams(self.GraphFn, dtypes.float32, [[100, 24, 24, 2]],
[[100, 12, 12, 6]])
def ExpectedEnginesToBuild(self, run_params):
"""Return the expected engines to build."""
return {
"TRTEngineOp_0": [
"add", "add1", "c1", "div1", "mul", "mul1", "sub", "sub1", "one",
"one_sub"
],
"TRTEngineOp_1": ["c2", "conv", "div", "weights"]
}
def setUp(self):
super(trt_test.TfTrtIntegrationTestBase, self).setUp() # pylint: disable=bad-super-call
# Disable layout optimizer, since it will convert BiasAdd with NHWC
# format to NCHW format under four dimentional input.
self.DisableNonTrtOptimizers()
class SimpleMultiEnginesTest2(trt_test.TfTrtIntegrationTestBase):
def GraphFn(self, inp):
"""Create a graph containing two segment."""
n = inp
for i in range(2):
c = constant_op.constant(1.0, name="c%d" % i)
n = math_ops.add(n, c, name="add%d" % i)
n = math_ops.mul(n, n, name="mul%d" % i)
edge = self.trt_incompatible_op(n, name="incompatible")
with ops.control_dependencies([edge]):
c = constant_op.constant(1.0, name="c2")
n = math_ops.add(n, c, name="add2")
n = math_ops.mul(n, n, name="mul2")
c = constant_op.constant(1.0, name="c3")
n = math_ops.add(n, c, name="add3")
n = math_ops.mul(n, n, name="mul3")
return array_ops.squeeze(n, name="output_0")
def GetParams(self):
shapes = [[2, 32, 32, 3]]
return self.BuildParams(self.GraphFn, dtypes.float32, input_shapes=shapes,
output_shapes=shapes)
def ExpectedEnginesToBuild(self, run_params):
"""Return the expected engines to build."""
return {
"TRTEngineOp_0": ["c0", "c1", "add0", "add1", "mul0", "mul1"],
"TRTEngineOp_1": ["c2", "c3", "add2", "add3", "mul2", "mul3"]
}
def ShouldRunTest(self, run_params):
"""Whether to run the test."""
# Disable the test in fp16 mode since multiple matmul and add ops together
# can cause overflow.
return (
(run_params.precision_mode != "FP16") and
not (trt_test.IsQuantizationMode(run_params.precision_mode) and
not run_params.use_calibration)), "test FP32 and non-calibration"
class ConstInputTest(trt_test.TfTrtIntegrationTestBase):
def GraphFn(self, inp):
"""Create a graph containing multiple segment."""
n = inp
c = constant_op.constant(1.0, name="c")
# Adds control dependency from the constant op to a trt incompatible op,
# and adds control dependency from the trt incompatible op to all other
# ops, to make sure the constant op cannot be contracted with any trt
# segment that depends on it.
with ops.control_dependencies([c]):
d = self.trt_incompatible_op(n, name="incompatible")
with ops.control_dependencies([d]):
n = math_ops.add(n, c, name="add")
n = math_ops.mul(n, n, name="mul")
n = math_ops.add(n, n, name="add1")
n = self.trt_incompatible_op(n, name="incompatible1")
with ops.control_dependencies([d]):
n = math_ops.add(n, c, name="add2")
n = math_ops.mul(n, n, name="mul1")
n = math_ops.add(n, n, name="add3")
return array_ops.squeeze(n, name="output_0")
def GetParams(self):
shapes = [[2, 32, 32, 3]]
return self.BuildParams(self.GraphFn, dtypes.float32, input_shapes=shapes,
output_shapes=shapes)
def ExpectedEnginesToBuild(self, run_params):
"""Return the expected engines to build."""
return {
"TRTEngineOp_0": ["add", "add1", "mul"],
"TRTEngineOp_1": ["add2", "add3", "mul1"]
}
class ConstDataInputSingleEngineTest(trt_test.TfTrtIntegrationTestBase):
def GraphFn(self, inp):
"""Create a graph containing single segment."""
n = inp
c = constant_op.constant(1.0, name="c")
n = math_ops.add(n, c, name="add")
n = math_ops.mul(n, n, name="mul")
n = math_ops.add(n, n, name="add1")
return array_ops.squeeze(n, name="output_0")
def GetParams(self):
shapes = [[2, 32, 32, 3]]
return self.BuildParams(self.GraphFn, dtypes.float32, input_shapes=shapes,
output_shapes=shapes)
def ExpectedEnginesToBuild(self, run_params):
"""Return the expected engines to build."""
return {"TRTEngineOp_0": ["c", "add", "add1", "mul"]}
class ConstDataInputMultipleEnginesTest(trt_test.TfTrtIntegrationTestBase):
def GraphFn(self, inp):
"""Create a graph containing multiple segment."""
n = inp
c = constant_op.constant(1.0, name="c")
n = math_ops.add(n, c, name="add")
n = math_ops.mul(n, n, name="mul")
n = math_ops.add(n, n, name="add1")
n = self.trt_incompatible_op(n, name="incompatible1")
n = math_ops.add(n, c, name="add2")
n = math_ops.mul(n, n, name="mul1")
n = math_ops.add(n, n, name="add3")
return array_ops.squeeze(n, name="output_0")
def GetParams(self):
shapes = [[2, 32, 32, 3]]
return self.BuildParams(self.GraphFn, dtypes.float32, input_shapes=shapes,
output_shapes=shapes)
def ExpectedEnginesToBuild(self, run_params):
"""Return the expected engines to build."""
return {
"TRTEngineOp_0": ["add2", "add3", "mul1"],
# Why segment ["add", "add1", "mul"] was assigned segment id 1
# instead of 0: the parent node of this segment is actually const
# node 'c', but it's removed later since it's const output of the
# segment which is not allowed.
"TRTEngineOp_1": ["add", "add1", "mul"]
}
class ControlDependencyTest(trt_test.TfTrtIntegrationTestBase):
def GraphFn(self, inp):
"""Create a graph containing multiple segment."""
c1 = constant_op.constant(1.0, name="c1")
c2 = constant_op.constant(1.0, name="c2")
d1 = constant_op.constant(1.0, name="d1")
d2 = self.trt_incompatible_op(inp, name="d2")
with ops.control_dependencies([d1, d2]):
add = math_ops.add(inp, c1, name="add")
with ops.control_dependencies([d1, d2]):
mul = math_ops.mul(add, add, name="mul")
with ops.control_dependencies([d1, d2]):
add1 = math_ops.add(mul, mul, name="add1")
edge = self.trt_incompatible_op(add1, name="incompatible")
with ops.control_dependencies([d1, d2, add, mul]):
add2 = math_ops.add(edge, c2, name="add2")
with ops.control_dependencies([d1, d2, add1, mul]):
mul1 = math_ops.mul(add2, add2, name="mul1")
with ops.control_dependencies([d1, d2, add, add1]):
add3 = math_ops.add(mul1, mul1, name="add3")
return array_ops.squeeze(add3, name="output_0")
def GetParams(self):
shapes = [[2, 32, 32, 3]]
return self.BuildParams(self.GraphFn, dtypes.float32, input_shapes=shapes,
output_shapes=shapes)
def ExpectedEnginesToBuild(self, run_params):
"""Return the expected engines to build."""
return {
"TRTEngineOp_0": ["c1", "add", "add1", "mul"],
"TRTEngineOp_1": ["c2", "add2", "add3", "mul1"]
}
if __name__ == "__main__":
test.main()
| apache-2.0 |
setr/Toolkit | toolkit/TreeGenerator/OSX_Build/dist/treeGUI.app/Contents/Resources/treeGUI.py | 2 | 4269 | #!/usr/bin/env python2.7
import wx
import os
from textParser import TextParser
class MainWindow(wx.Frame):
""" Our GUI menu """
def __init__(self, *args, **kwargs):
super(MainWindow, self).__init__(*args, **kwargs)
self.parser = TextParser()
self.createControls()
self.bindEvents()
self.doLayout()
def createControls(self):
self.inputText = wx.TextCtrl(self, style=wx.TE_MULTILINE|wx.TE_DONTWRAP)
self.outputText = wx.TextCtrl(self, style=wx.TE_MULTILINE|wx.TE_DONTWRAP)
font1 = wx.Font(11, wx.TELETYPE, wx.NORMAL, wx.NORMAL, False, u'Consolas')
self.outputText.SetFont(font1)
self.convertButton = wx.Button(self, label="Convert!")
self.openFileButton = wx.Button(self, label="Open File")
self.headerText = wx.TextCtrl(self)
def bindEvents(self):
# what in the fuck is \
for control, event, handler in \
[(self.convertButton, wx.EVT_BUTTON, self.onConvert),
(self.inputText, wx.EVT_TEXT, self.onInputChange),
(self.outputText, wx.EVT_TEXT, self.onOutputChange),
(self.openFileButton, wx.EVT_BUTTON, self.onOpen),
(self.headerText, wx.EVT_TEXT, self.onHeaderChange)]:
control.Bind(event, handler)
def doLayout(self):
boxSizer = wx.BoxSizer(orient=wx.HORIZONTAL)
gridSizer = wx.FlexGridSizer(cols=2, vgap=10, hgap=10)
gridSizer.AddGrowableCol(0,1)
gridSizer.AddGrowableCol(1,1)
gridSizer.AddGrowableRow(0,4)
gridSizer.AddGrowableRow(1,1)
txtboxOptions=dict(flag=wx.EXPAND, proportion=22)
buttonOptions = dict(flag=wx.ALIGN_CENTER)
emptySpace = ((0, 0), dict())
for control, options in \
[(self.inputText, txtboxOptions),
(self.outputText, txtboxOptions),
(self.openFileButton, buttonOptions),
(self.headerText, buttonOptions)]:
gridSizer.Add(control, **options)
for control, options in \
[(gridSizer, dict(border=5, flag=wx.ALL|wx.EXPAND, proportion=1))]:
boxSizer.Add(control, **options)
self.SetSizerAndFit(boxSizer)
def onOpen(self, event):
""" Open a file, paste content to inputText"""
dirname = ""
OpenFileDialog = wx.FileDialog(self, "Open XYZ file", dirname, "", "*.*", wx.FD_OPEN | wx.FD_FILE_MUST_EXIST)
if OpenFileDialog.ShowModal() == wx.ID_CANCEL:
return # the user changed his mind ...
input_stream = OpenFileDialog.GetPath()
try:
with open(input_stream, 'r') as f:
self.inputText.SetValue(f.read())
except IOError:
errorDLG = wx.MessageDialog(self, "Could not open file. Are you sure the file path was correct?", "I/O ERROR", wx.ICON_ERROR)
errorDLG.ShowModal()
errorDLG.Destroy()
except UnicodeDecodeError:
errorDLG = wx.MessageDialog(self, "Could not understand the file. Are you sure this is a text file?", "READ ERROR", wx.ICON_ERROR)
errorDLG.ShowModal()
errorDLG.Destroy()
def onHeaderChange(self, event):
print "HEPLP"
newHeader = self.headerText.GetValue().strip()
print newHeader
if newHeader is not None and newHeader != "":
self.parser.HEADER = newHeader
else:
self.parser.HEADER = "*"
self.onInputChange(event)
def onConvert(self, event):
raise NotImplementedError
def onInputChange(self, event):
text = self.inputText.GetValue()
root = self.parser.startParse(False, text)
out = root.printAll()
out.encode("UTF-8")
self.outputText.SetValue(out)
# Auto-copys output to clipboard
clipdata = wx.TextDataObject()
clipdata.SetText(out)
wx.TheClipboard.Open()
wx.TheClipboard.SetData(clipdata)
wx.TheClipboard.Close()
def onOutputChange(self, event):
pass
if __name__ == '__main__':
app = wx.App(0)
frame = MainWindow(None, title='Demo with Notebook')
frame.Show()
app.MainLoop()
| gpl-2.0 |
odoo-turkiye/odoo | addons/subscription/__openerp__.py | 261 | 1885 | # -*- 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': 'Recurring Documents',
'version': '1.0',
'category': 'Tools',
'description': """
Create recurring documents.
===========================
This module allows to create new documents and add subscriptions on that document.
e.g. To have an invoice generated automatically periodically:
-------------------------------------------------------------
* Define a document type based on Invoice object
* Define a subscription whose source document is the document defined as
above. Specify the interval information and partner to be invoice.
""",
'author': 'OpenERP SA',
'depends': ['base'],
'data': ['security/subcription_security.xml', 'security/ir.model.access.csv', 'subscription_view.xml'],
'demo': ['subscription_demo.xml',],
'installable': True,
'auto_install': False,
}
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
| agpl-3.0 |
iut-ibk/Calimero | site-packages/pybrain/rl/environments/ode/tasks/johnnie.py | 3 | 8538 | __author__ = 'Frank Sehnke, sehnke@in.tum.de'
from pybrain.rl.environments import EpisodicTask
from pybrain.rl.environments.ode.sensors import * #@UnusedWildImport
from scipy import ones, tanh, clip
#Basic class for all Johnnie tasks
class JohnnieTask(EpisodicTask):
def __init__(self, env):
EpisodicTask.__init__(self, env)
self.maxPower = 100.0 #Overall maximal tourque - is multiplied with relative max tourque for individual joint to get individual max tourque
self.reward_history = []
self.count = 0 #timestep counter
self.epiLen = 500 #suggestet episodic length for normal Johnnie tasks
self.incLearn = 0 #counts the task resets for incrementall learning
self.env.FricMu = 20.0 #We need higher friction for Johnnie
self.env.dt = 0.01 #We also need more timly resolution
# normalize standard sensors to (-1, 1)
self.sensor_limits = []
#Angle sensors
for i in range(self.env.actLen):
self.sensor_limits.append((self.env.cLowList[i], self.env.cHighList[i]))
# Joint velocity sensors
for i in range(self.env.actLen):
self.sensor_limits.append((-20, 20))
#Norm all actor dimensions to (-1, 1)
self.actor_limits = [(-1, 1)] * env.actLen
def performAction(self, action):
#Filtered mapping towards performAction of the underlying environment
#The standard Johnnie task uses a PID controller to controll directly angles instead of forces
#This makes most tasks much simpler to learn
isJoints=self.env.getSensorByName('JointSensor') #The joint angles
isSpeeds=self.env.getSensorByName('JointVelocitySensor') #The joint angular velocitys
act=(action+1.0)/2.0*(self.env.cHighList-self.env.cLowList)+self.env.cLowList #norm output to action intervall
action=tanh((act-isJoints-isSpeeds)*16.0)*self.maxPower*self.env.tourqueList #simple PID
EpisodicTask.performAction(self, action)
#self.env.performAction(action)
def isFinished(self):
#returns true if episode timesteps has reached episode length and resets the task
if self.count > self.epiLen:
self.res()
return True
else:
self.count += 1
return False
def res(self):
#sets counter and history back, increases incremental counter
self.count = 0
self.incLearn += 1
self.reward_history.append(self.getTotalReward())
#The standing tasks, just not falling on its own is the goal
class StandingTask(JohnnieTask):
def __init__(self, env):
JohnnieTask.__init__(self, env)
#add task spezific sensors, TODO build attitude sensors
self.env.addSensor(SpecificBodyPositionSensor(['footLeft'], "footLPos"))
self.env.addSensor(SpecificBodyPositionSensor(['footRight'], "footRPos"))
self.env.addSensor(SpecificBodyPositionSensor(['palm'], "bodyPos"))
self.env.addSensor(SpecificBodyPositionSensor(['head'], "headPos"))
#we changed sensors so we need to update environments sensorLength variable
self.env.obsLen = len(self.env.getSensors())
#normalization for the task spezific sensors
for _ in range(self.env.obsLen - 2 * self.env.actLen):
self.sensor_limits.append((-20, 20))
self.epiLen = 1000 #suggested episode length for this task
def getReward(self):
# calculate reward and return reward
reward = self.env.getSensorByName('headPos')[1] / float(self.epiLen) #reward is hight of head
#to prevent jumping reward can't get bigger than head position while standing absolut upright
reward = clip(reward, -14.0, 4.0)
return reward
#Robust standing task suited for complete learning with already standable controller
class RStandingTask(StandingTask):
def __init__(self, env):
StandingTask.__init__(self, env)
self.epiLen = 4000 #suggested episode length for this task
self.h1 = self.epiLen / 4 #timestep of first perturbation
self.h2 = self.epiLen / 2 #timestep of environment reset
self.h3 = 3 * self.epiLen / 4 #timestep of second perturbation
self.pVect1 = (0, -9.81, -9.81) #gravity vector for first perturbation
self.pVect2 = (0, -9.81, 0) #gravity vector standard
self.pVect3 = (0, -9.81, 9.81) #gravity vector for second perturbation
def isFinished(self):
if self.count > self.epiLen:
self.res()
return True
else:
self.count += 1
self.disturb()
return False
#changes gravity vector for perturbation
def disturb(self):
disturb = self.getDisturb()
if self.count == self.h1: self.env.world.setGravity(self.pVect1)
if self.count == self.h1 + disturb: self.env.world.setGravity(self.pVect2)
if self.count == self.h2: self.env.reset()
if self.count == self.h3: self.env.world.setGravity(self.pVect3)
if self.count == self.h3 + disturb: self.env.world.setGravity(self.pVect2)
def getDisturb(self):
return 50
#Robust standing task suited for incremental learning with already standable controller
class RobStandingTask(RStandingTask):
#increases the amount of perturbation with the number of episodes
def getDisturb(self):
return clip((10 + self.incLearn / 50), 0.0, 50)
#Robust standing task suited for complete learning with an empty controller
class RobustStandingTask(RobStandingTask):
#increases the amount of perturbation with the number of episodes
def getDisturb(self):
return clip((self.incLearn / 200), 0.0, 50)
#The jumping tasks, goal is to maximize the highest point the head reaches during episode
class JumpingTask(JohnnieTask):
def __init__(self, env):
JohnnieTask.__init__(self, env)
#add task spezific sensors, TODO build attitude sensors
self.env.addSensor(SpecificBodyPositionSensor(['footLeft']))
self.env.addSensor(SpecificBodyPositionSensor(['footRight']))
self.env.addSensor(SpecificBodyPositionSensor(['palm']))
self.env.addSensor(SpecificBodyPositionSensor(['head']))
#we changed sensors so we need to update environments sensorLength variable
self.env.obsLen = len(self.env.getSensors())
#normalization for the task spezific sensors
for _ in range(self.env.obsLen - 2 * self.env.actLen):
self.sensor_limits.append((-20, 20))
self.epiLen = 400 #suggested episode length for this task
self.maxHight = 4.0 #maximum hight reached during episode
self.maxPower = 400.0 #jumping needs more power
def getReward(self):
# calculate reward and return reward
reward = self.env.getSensorByName('SpecificBodyPositionSensor8')[1] #reward is hight of head
if reward > self.maxHight:
self.maxHight = reward
if self.count == self.epiLen:
reward = self.maxHight
else:
reward = 0.0
return reward
def res(self):
self.count = 0
self.reward_history.append(self.getTotalReward())
self.maxHight = 4.0
#The standing up from prone task, goal is to stand up from prone in an upright position.
#Nearly unsolveable task - most learners achive to bring Johnnie in some kind of kneeling position
class StandingUpTask(StandingTask):
def __init__(self, env):
StandingTask.__init__(self, env)
self.epiLen = 2000 #suggested episode length for this task
self.env.tourqueList[0] = 2.5
self.env.tourqueList[1] = 2.5
def getReward(self):
# calculate reward and return reward
if self.count < 800:
return 0.0
else:
reward = self.env.getSensorByName('SpecificBodyPositionSensor8')[1] / float(self.epiLen - 800) #reward is hight of head
#to prevent jumping reward can't get bigger than head position while standing absolut upright
reward = clip(reward, -14.0, 4.0)
return reward
def performAction(self, action):
if self.count < 800:
#provoke falling
a = ones(self.env.actLen, int) * self.maxPower * self.env.tourqueList * -1
StandingTask.performAction(self, a)
else:
StandingTask.performAction(self, action)
| gpl-2.0 |
tivek/conan | conans/test/functional/compile_helpers_test.py | 3 | 4261 | import os
import unittest
from conans.model.env_info import DepsEnvInfo
from conans.model.profile import Profile
from conans.model.settings import Settings
from conans.paths import CONANFILE
from conans.test.utils.tools import TestBufferConanOutput, TestClient
from conans.util.files import save
class MockSetting(str):
@property
def value(self):
return self
class MockCompiler(object):
def __init__(self, name, libcxx, version):
self.name = name
self.libcxx = libcxx
self.version = MockSetting(version)
def __repr__(self, *args, **kwargs): # @UnusedVariable
return self.name
class MockSettings(Settings):
def __init__(self, build_type="Release", os=None, arch=None,
compiler_name=None, libcxx=None, version=None):
self._build_type = build_type
self._libcxx = libcxx or "libstdc++"
self._os = os or "Linux"
self._arch = arch or "x86"
self._compiler = MockCompiler(compiler_name or "gcc", self._libcxx, version or "4.8")
@property
def build_type(self):
return self._build_type
@property
def libcxx(self):
return self._libcxx
@property
def os(self):
return MockSetting(self._os)
@property
def arch(self):
return MockSetting(self._arch)
@property
def compiler(self):
return self._compiler
class MockAndroidSettings(Settings):
@property
def os(self):
return "Android"
class BuildInfoMock(object):
@property
def lib_paths(self):
return ["path/to/lib1", "path/to/lib2"]
@property
def exelinkflags(self):
return ["-framework thing"]
@property
def sharedlinkflags(self):
return ["-framework thing2"]
@property
def include_paths(self):
return ["path/to/includes/lib1", "path/to/includes/lib2"]
@property
def defines(self):
return ["MYDEF1", "MYDEF2"]
@property
def libs(self):
return ["lib1", "lib2"]
@property
def cflags(self):
return ["cflag1"]
@property
def cppflags(self):
return ["cppflag1"]
class MockConanfile(object):
def __init__(self, settings):
self.settings = settings
self.output = TestBufferConanOutput()
@property
def deps_cpp_info(self):
return BuildInfoMock()
@property
def deps_env_info(self):
return DepsEnvInfo()
@property
def env_values_dicts(self):
return {}, {}
conanfile_scope_env = """
from conans import ConanFile
class AConan(ConanFile):
settings = "os"
requires = "Hello/0.1@lasote/testing"
def build(self):
self.run("SET" if self.settings.os=="Windows" else "env")
"""
conanfile_dep = """
from conans import ConanFile
class AConan(ConanFile):
name = "Hello"
version = "0.1"
def package_info(self):
self.env_info.PATH=["/path/to/my/folder"]
"""
class ProfilesEnvironmentTest(unittest.TestCase):
def setUp(self):
self.client = TestClient()
def build_with_profile_test(self):
self._create_profile("scopes_env", {},
{"CXX": "/path/tomy/g++_build", "CC": "/path/tomy/gcc_build"})
self.client.save({CONANFILE: conanfile_dep})
self.client.run("export . lasote/testing")
self.client.save({CONANFILE: conanfile_scope_env}, clean_first=True)
self.client.run("install . --build=missing --pr scopes_env")
self.client.run("build .")
self.assertRegexpMatches(str(self.client.user_io.out), "PATH=['\"]*/path/to/my/folder")
self._assert_env_variable_printed("CC", "/path/tomy/gcc_build")
self._assert_env_variable_printed("CXX", "/path/tomy/g++_build")
def _assert_env_variable_printed(self, name, value):
self.assertIn("%s=%s" % (name, value), self.client.user_io.out)
def _create_profile(self, name, settings, env=None):
env = env or {}
profile = Profile()
profile._settings = settings or {}
for varname, value in env.items():
profile.env_values.add(varname, value)
save(os.path.join(self.client.client_cache.profiles_path, name), "include(default)\n" + profile.dumps())
| mit |
vitorio/bite-project | deps/gdata-python-client/tests/atom_tests/token_store_test.py | 128 | 2896 | #!/usr/bin/python
#
# Copyright (C) 2008 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
__author__ = 'j.s@google.com (Jeff Scudder)'
import unittest
import atom.token_store
import atom.http_interface
import atom.service
import atom.url
class TokenStoreTest(unittest.TestCase):
def setUp(self):
self.token = atom.service.BasicAuthToken('aaa1', scopes=[
'http://example.com/', 'http://example.org'])
self.tokens = atom.token_store.TokenStore()
self.tokens.add_token(self.token)
def testAddAndFindTokens(self):
self.assert_(self.tokens.find_token('http://example.com/') == self.token)
self.assert_(self.tokens.find_token('http://example.org/') == self.token)
self.assert_(self.tokens.find_token('http://example.org/foo?ok=1') == (
self.token))
self.assert_(isinstance(self.tokens.find_token('http://example.net/'),
atom.http_interface.GenericToken))
self.assert_(isinstance(self.tokens.find_token('example.com/'),
atom.http_interface.GenericToken))
def testFindTokenUsingMultipleUrls(self):
self.assert_(self.tokens.find_token(
'http://example.com/') == self.token)
self.assert_(self.tokens.find_token(
'http://example.org/bar') == self.token)
self.assert_(isinstance(self.tokens.find_token(''),
atom.http_interface.GenericToken))
self.assert_(isinstance(self.tokens.find_token(
'http://example.net/'),
atom.http_interface.GenericToken))
def testFindTokenWithPartialScopes(self):
token = atom.service.BasicAuthToken('aaa1',
scopes=[atom.url.Url(host='www.example.com', path='/foo'),
atom.url.Url(host='www.example.net')])
token_store = atom.token_store.TokenStore()
token_store.add_token(token)
self.assert_(token_store.find_token(
'http://www.example.com/foobar') == token)
self.assert_(token_store.find_token(
'https://www.example.com:443/foobar') == token)
self.assert_(token_store.find_token(
'http://www.example.net/xyz') == token)
self.assert_(token_store.find_token('http://www.example.org/') != token)
self.assert_(isinstance(token_store.find_token('http://example.org/'),
atom.http_interface.GenericToken))
def suite():
return unittest.TestSuite((unittest.makeSuite(TokenStoreTest,'test'),))
if __name__ == '__main__':
unittest.main()
| apache-2.0 |
gdgellatly/OCB1 | addons/email_template/res_partner.py | 432 | 1688 | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Business Applications
# Copyright (c) 2011 OpenERP S.A. <http://openerp.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
from openerp.osv import fields, osv
class res_partner(osv.osv):
"""Inherit res.partner to add a generic opt-out field that can be used
to restrict usage of automatic email templates.
This field is unused by default. """
_inherit = 'res.partner'
_columns = {
'opt_out': fields.boolean('Opt-Out',
help="If opt-out is checked, this contact has refused to receive emails for mass mailing and marketing campaign. "
"Filter 'Available for Mass Mailing' allows users to filter the partners when performing mass mailing."),
}
_defaults = {
'opt_out': False,
}
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
| agpl-3.0 |
hulu/uwsgi | plugins/rack/uwsgiplugin.py | 13 | 3183 | import os
NAME = 'rack'
try:
RUBYPATH = os.environ['UWSGICONFIG_RUBYPATH']
except:
RUBYPATH = 'ruby'
rbconfig = 'Config'
version = os.popen(RUBYPATH + " -e \"print RUBY_VERSION\"").read().rstrip()
v = version.split('.')
GCC_LIST = ['rack_plugin', 'rack_api']
if (v[0] == '1' and v[1] == '9') or v[0] >= '2':
CFLAGS = os.popen(RUBYPATH + " -e \"require 'rbconfig';print RbConfig::CONFIG['CFLAGS']\"").read().rstrip().split()
CFLAGS.append('-DRUBY19')
CFLAGS.append('-Wno-unused-parameter')
rbconfig = 'RbConfig'
else:
CFLAGS = os.popen(RUBYPATH + " -e \"require 'rbconfig';print %s::CONFIG['CFLAGS']\"" % rbconfig).read().rstrip().split()
includedir = os.popen(RUBYPATH + " -e \"require 'rbconfig';print %s::CONFIG['rubyhdrdir']\"" % rbconfig).read().rstrip()
if includedir == 'nil':
includedir = os.popen(RUBYPATH + " -e \"require 'rbconfig';print %s::CONFIG['archdir']\"" % rbconfig).read().rstrip()
CFLAGS.append('-I' + includedir)
else:
CFLAGS.append('-I' + includedir)
archdir = os.popen(RUBYPATH + " -e \"require 'rbconfig';print %s::CONFIG['archdir']\"" % rbconfig).read().rstrip()
arch = os.popen(RUBYPATH + " -e \"require 'rbconfig';print %s::CONFIG['arch']\"" % rbconfig).read().rstrip()
archdir2 = os.popen(RUBYPATH + " -e \"require 'rbconfig';print %s::CONFIG['rubyarchhdrdir']\"" % rbconfig).read().rstrip()
CFLAGS.append('-I' + archdir)
CFLAGS.append('-I' + archdir + '/' + arch)
CFLAGS.append('-I' + includedir + '/' + arch)
if archdir2:
CFLAGS.append('-I' + archdir2)
LDFLAGS = os.popen(RUBYPATH + " -e \"require 'rbconfig';print %s::CONFIG['LDFLAGS']\"" % rbconfig).read().rstrip().split()
libpath = os.popen(RUBYPATH + " -e \"require 'rbconfig';print %s::CONFIG['libdir']\"" % rbconfig).read().rstrip()
has_shared = os.popen(RUBYPATH + " -e \"require 'rbconfig';print %s::CONFIG['ENABLE_SHARED']\"" % rbconfig).read().rstrip()
LIBS = os.popen(RUBYPATH + " -e \"require 'rbconfig';print %s::CONFIG['LIBS']\"" % rbconfig).read().rstrip().split()
if has_shared == 'yes':
LDFLAGS.append('-L' + libpath)
os.environ['LD_RUN_PATH'] = libpath
LIBS.append(os.popen(RUBYPATH + " -e \"require 'rbconfig';print '-l' + %s::CONFIG['RUBY_SO_NAME']\"" % rbconfig).read().rstrip())
else:
rubylibdir = os.popen(RUBYPATH + " -e \"require 'rbconfig';print RbConfig::CONFIG['rubylibdir']\"").read().rstrip()
rubyarchdir = os.popen(RUBYPATH + " -e \"require 'rbconfig';print RbConfig::CONFIG['archdir']\"").read().rstrip()
# detect Heroku system
heroku = False
if rubylibdir.startswith('/tmp/build_'):
heroku = True
rubylibdir = '/app/' + '/'.join(rubylibdir.split('/')[3:])
if rubyarchdir.startswith('/tmp/build_'):
heroku = True
rubyarchdir = '/app/' + '/'.join(rubyarchdir.split('/')[3:])
if heroku:
CFLAGS.append('-DUWSGI_RUBY_HEROKU')
CFLAGS.append('-DUWSGI_RUBY_LIBDIR="\\"%s\\""' % rubylibdir)
CFLAGS.append('-DUWSGI_RUBY_ARCHDIR="\\"%s\\""' % rubyarchdir)
GCC_LIST.append("%s/%s" % (libpath, os.popen(RUBYPATH + " -e \"require 'rbconfig';print %s::CONFIG['LIBRUBY_A']\"" % rbconfig).read().rstrip()))
| gpl-2.0 |
sajuptpm/manila | manila/tests/api/contrib/test_share_type_access.py | 3 | 14105 | #
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import datetime
import mock
import six
import webob
from manila.api.contrib import share_type_access as type_access
from manila.api.v1 import share_types
from manila import context
from manila import db
from manila import exception
from manila.share import share_types as share_types_api
from manila import test
from manila.tests.api import fakes
def generate_type(type_id, is_public):
return {
'id': type_id,
'name': u'test',
'deleted': False,
'created_at': datetime.datetime(2012, 1, 1, 1, 1, 1, 1),
'updated_at': None,
'deleted_at': None,
'is_public': bool(is_public),
'extra_specs': {}
}
SHARE_TYPES = {
'0': generate_type('0', True),
'1': generate_type('1', True),
'2': generate_type('2', False),
'3': generate_type('3', False)}
PROJ1_UUID = '11111111-1111-1111-1111-111111111111'
PROJ2_UUID = '22222222-2222-2222-2222-222222222222'
PROJ3_UUID = '33333333-3333-3333-3333-333333333333'
ACCESS_LIST = [{'share_type_id': '2', 'project_id': PROJ2_UUID},
{'share_type_id': '2', 'project_id': PROJ3_UUID},
{'share_type_id': '3', 'project_id': PROJ3_UUID}]
def fake_share_type_get(context, id, inactive=False, expected_fields=None):
vol = SHARE_TYPES[id]
if expected_fields and 'projects' in expected_fields:
vol['projects'] = [a['project_id']
for a in ACCESS_LIST if a['share_type_id'] == id]
return vol
def _has_type_access(type_id, project_id):
for access in ACCESS_LIST:
if (access['share_type_id'] == type_id
and access['project_id'] == project_id):
return True
return False
def fake_share_type_get_all(context, inactive=False, filters=None):
if filters is None or filters.get('is_public', None) is None:
return SHARE_TYPES
res = {}
for k, v in six.iteritems(SHARE_TYPES):
if filters['is_public'] and _has_type_access(k, context.project_id):
res.update({k: v})
continue
if v['is_public'] == filters['is_public']:
res.update({k: v})
return res
class FakeResponse(object):
obj = {'share_type': {'id': '0'},
'share_types': [
{'id': '0'},
{'id': '2'}]}
def attach(self, **kwargs):
pass
class FakeRequest(object):
environ = {"manila.context": context.get_admin_context()}
def get_db_share_type(self, resource_id):
return SHARE_TYPES[resource_id]
class ShareTypeAccessTest(test.TestCase):
def setUp(self):
super(ShareTypeAccessTest, self).setUp()
self.type_access_controller = type_access.ShareTypeAccessController()
self.type_action_controller = type_access.ShareTypeActionController()
self.type_controller = share_types.ShareTypesController()
self.req = FakeRequest()
self.context = self.req.environ['manila.context']
self.mock_object(db, 'share_type_get',
fake_share_type_get)
self.mock_object(db, 'share_type_get_all',
fake_share_type_get_all)
def assertShareTypeListEqual(self, expected, observed):
self.assertEqual(len(expected), len(observed))
expected = sorted(expected, key=lambda item: item['id'])
observed = sorted(observed, key=lambda item: item['id'])
for d1, d2 in zip(expected, observed):
self.assertEqual(d1['id'], d2['id'])
def test_list_type_access_public(self):
"""Querying os-share-type-access on public type should return 404."""
req = fakes.HTTPRequest.blank('/v1/fake/types/os-share-type-access',
use_admin_context=True)
self.assertRaises(webob.exc.HTTPNotFound,
self.type_access_controller.index,
req, '1')
def test_list_type_access_private(self):
expected = {'share_type_access': [
{'share_type_id': '2', 'project_id': PROJ2_UUID},
{'share_type_id': '2', 'project_id': PROJ3_UUID}]}
result = self.type_access_controller.index(self.req, '2')
self.assertEqual(expected, result)
def test_list_with_no_context(self):
req = fakes.HTTPRequest.blank('/v1/types/fake/types')
def fake_authorize(context, target=None, action=None):
raise exception.PolicyNotAuthorized(action='index')
self.mock_object(type_access, 'authorize', fake_authorize)
self.assertRaises(exception.PolicyNotAuthorized,
self.type_access_controller.index,
req, 'fake')
def test_list_type_with_admin_default_proj1(self):
expected = {'share_types': [{'id': '0'}, {'id': '1'}]}
req = fakes.HTTPRequest.blank('/v1/fake/types',
use_admin_context=True)
req.environ['manila.context'].project_id = PROJ1_UUID
result = self.type_controller.index(req)
self.assertShareTypeListEqual(expected['share_types'],
result['share_types'])
def test_list_type_with_admin_default_proj2(self):
expected = {'share_types': [{'id': '0'}, {'id': '1'}, {'id': '2'}]}
req = fakes.HTTPRequest.blank('/v2/fake/types',
use_admin_context=True)
req.environ['manila.context'].project_id = PROJ2_UUID
result = self.type_controller.index(req)
self.assertShareTypeListEqual(expected['share_types'],
result['share_types'])
def test_list_type_with_admin_ispublic_true(self):
expected = {'share_types': [{'id': '0'}, {'id': '1'}]}
req = fakes.HTTPRequest.blank('/v2/fake/types?is_public=true',
use_admin_context=True)
result = self.type_controller.index(req)
self.assertShareTypeListEqual(expected['share_types'],
result['share_types'])
def test_list_type_with_admin_ispublic_false(self):
expected = {'share_types': [{'id': '2'}, {'id': '3'}]}
req = fakes.HTTPRequest.blank('/v2/fake/types?is_public=false',
use_admin_context=True)
result = self.type_controller.index(req)
self.assertShareTypeListEqual(expected['share_types'],
result['share_types'])
def test_list_type_with_admin_ispublic_false_proj2(self):
expected = {'share_types': [{'id': '2'}, {'id': '3'}]}
req = fakes.HTTPRequest.blank('/v2/fake/types?is_public=false',
use_admin_context=True)
req.environ['manila.context'].project_id = PROJ2_UUID
result = self.type_controller.index(req)
self.assertShareTypeListEqual(expected['share_types'],
result['share_types'])
def test_list_type_with_admin_ispublic_none(self):
expected = {'share_types': [{'id': '0'}, {'id': '1'}, {'id': '2'},
{'id': '3'}]}
req = fakes.HTTPRequest.blank('/v2/fake/types?is_public=all',
use_admin_context=True)
result = self.type_controller.index(req)
self.assertShareTypeListEqual(expected['share_types'],
result['share_types'])
def test_list_type_with_no_admin_default(self):
expected = {'share_types': [{'id': '0'}, {'id': '1'}]}
req = fakes.HTTPRequest.blank('/v2/fake/types',
use_admin_context=False)
result = self.type_controller.index(req)
self.assertShareTypeListEqual(expected['share_types'],
result['share_types'])
def test_list_type_with_no_admin_ispublic_true(self):
expected = {'share_types': [{'id': '0'}, {'id': '1'}]}
req = fakes.HTTPRequest.blank('/v2/fake/types?is_public=true',
use_admin_context=False)
result = self.type_controller.index(req)
self.assertShareTypeListEqual(expected['share_types'],
result['share_types'])
def test_list_type_with_no_admin_ispublic_false(self):
expected = {'share_types': [{'id': '0'}, {'id': '1'}]}
req = fakes.HTTPRequest.blank('/v2/fake/types?is_public=false',
use_admin_context=False)
result = self.type_controller.index(req)
self.assertShareTypeListEqual(expected['share_types'],
result['share_types'])
def test_list_type_with_no_admin_ispublic_none(self):
expected = {'share_types': [{'id': '0'}, {'id': '1'}]}
req = fakes.HTTPRequest.blank('/v2/fake/types?is_public=all',
use_admin_context=False)
result = self.type_controller.index(req)
self.assertShareTypeListEqual(expected['share_types'],
result['share_types'])
def test_show(self):
resp = FakeResponse()
self.type_action_controller.show(self.req, resp, '0')
self.assertEqual({'id': '0', 'os-share-type-access:is_public': True},
resp.obj['share_type'])
self.type_action_controller.show(self.req, resp, '2')
self.assertEqual({'id': '0', 'os-share-type-access:is_public': False},
resp.obj['share_type'])
def test_create(self):
resp = FakeResponse()
self.type_action_controller.create(self.req, {}, resp)
self.assertEqual({'id': '0', 'os-share-type-access:is_public': True},
resp.obj['share_type'])
def test_add_project_access(self):
def stub_add_share_type_access(context, type_id, project_id):
self.assertEqual('3', type_id, "type_id")
self.assertEqual(PROJ2_UUID, project_id, "project_id")
self.mock_object(db, 'share_type_access_add',
stub_add_share_type_access)
body = {'addProjectAccess': {'project': PROJ2_UUID}}
req = fakes.HTTPRequest.blank('/v2/fake/types/2/action',
use_admin_context=True)
result = self.type_action_controller._addProjectAccess(req, '3', body)
self.assertEqual(202, result.status_code)
def test_add_project_access_with_no_admin_user(self):
req = fakes.HTTPRequest.blank('/v2/fake/types/2/action',
use_admin_context=False)
body = {'addProjectAccess': {'project': PROJ2_UUID}}
self.assertRaises(exception.PolicyNotAuthorized,
self.type_action_controller._addProjectAccess,
req, '2', body)
def test_add_project_access_with_already_added_access(self):
def stub_add_share_type_access(context, type_id, project_id):
raise exception.ShareTypeAccessExists(share_type_id=type_id,
project_id=project_id)
self.mock_object(db, 'share_type_access_add',
stub_add_share_type_access)
body = {'addProjectAccess': {'project': PROJ2_UUID}}
req = fakes.HTTPRequest.blank('/v2/fake/types/2/action',
use_admin_context=True)
self.assertRaises(webob.exc.HTTPConflict,
self.type_action_controller._addProjectAccess,
req, '3', body)
def test_add_project_access_to_public_share_type(self):
share_type_id = '3'
body = {'addProjectAccess': {'project': PROJ2_UUID}}
self.mock_object(share_types_api, 'get_share_type',
mock.Mock(return_value={"is_public": True}))
req = fakes.HTTPRequest.blank('/v2/fake/types/2/action',
use_admin_context=True)
self.assertRaises(webob.exc.HTTPForbidden,
self.type_action_controller._addProjectAccess,
req, share_type_id, body)
share_types_api.get_share_type.assert_called_once_with(
mock.ANY, share_type_id)
def test_remove_project_access_with_bad_access(self):
def stub_remove_share_type_access(context, type_id, project_id):
raise exception.ShareTypeAccessNotFound(share_type_id=type_id,
project_id=project_id)
self.mock_object(db, 'share_type_access_remove',
stub_remove_share_type_access)
body = {'removeProjectAccess': {'project': PROJ2_UUID}}
req = fakes.HTTPRequest.blank('/v2/fake/types/2/action',
use_admin_context=True)
self.assertRaises(webob.exc.HTTPNotFound,
self.type_action_controller._removeProjectAccess,
req, '3', body)
def test_remove_project_access_with_no_admin_user(self):
req = fakes.HTTPRequest.blank('/v2/fake/types/2/action',
use_admin_context=False)
body = {'removeProjectAccess': {'project': PROJ2_UUID}}
self.assertRaises(exception.PolicyNotAuthorized,
self.type_action_controller._removeProjectAccess,
req, '2', body)
| apache-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.