repo_name
stringlengths 5
100
| path
stringlengths 4
254
| copies
stringlengths 1
5
| size
stringlengths 4
7
| content
stringlengths 681
1M
| license
stringclasses 15
values | hash
int64 -9,223,351,895,964,839,000
9,223,298,349B
| line_mean
float64 3.5
100
| line_max
int64 15
1k
| alpha_frac
float64 0.25
0.97
| autogenerated
bool 1
class | ratio
float64 1.5
8.15
| config_test
bool 2
classes | has_no_keywords
bool 2
classes | few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
ahmedbodi/AutobahnPython | examples/asyncio/websocket/echo/client_coroutines.py | 13 | 2044 | ###############################################################################
##
## Copyright (C) 2013-2014 Tavendo GmbH
##
## 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 autobahn.asyncio.websocket import WebSocketClientProtocol, \
WebSocketClientFactory
import asyncio
class MyClientProtocol(WebSocketClientProtocol):
def onConnect(self, response):
print("Server connected: {0}".format(response.peer))
@asyncio.coroutine
def onOpen(self):
print("WebSocket connection open.")
## start sending messages every second ..
while True:
self.sendMessage(u"Hello, world!".encode('utf8'))
self.sendMessage(b"\x00\x01\x03\x04", isBinary = True)
yield from asyncio.sleep(1)
def onMessage(self, payload, isBinary):
if isBinary:
print("Binary message received: {0} bytes".format(len(payload)))
else:
print("Text message received: {0}".format(payload.decode('utf8')))
def onClose(self, wasClean, code, reason):
print("WebSocket connection closed: {0}".format(reason))
if __name__ == '__main__':
import asyncio
factory = WebSocketClientFactory("ws://localhost:9000", debug = False)
factory.protocol = MyClientProtocol
loop = asyncio.get_event_loop()
coro = loop.create_connection(factory, '127.0.0.1', 9000)
loop.run_until_complete(coro)
loop.run_forever()
loop.close()
| apache-2.0 | 7,822,061,744,094,950,000 | 31.444444 | 79 | 0.623288 | false | 4.214433 | false | false | false |
ifduyue/django | django/core/checks/registry.py | 13 | 3108 | from itertools import chain
from django.utils.itercompat import is_iterable
class Tags:
"""
Built-in tags for internal checks.
"""
admin = 'admin'
caches = 'caches'
compatibility = 'compatibility'
database = 'database'
models = 'models'
security = 'security'
signals = 'signals'
templates = 'templates'
urls = 'urls'
class CheckRegistry:
def __init__(self):
self.registered_checks = set()
self.deployment_checks = set()
def register(self, check=None, *tags, **kwargs):
"""
Can be used as a function or a decorator. Register given function
`f` labeled with given `tags`. The function should receive **kwargs
and return list of Errors and Warnings.
Example::
registry = CheckRegistry()
@registry.register('mytag', 'anothertag')
def my_check(apps, **kwargs):
# ... perform checks and collect `errors` ...
return errors
# or
registry.register(my_check, 'mytag', 'anothertag')
"""
kwargs.setdefault('deploy', False)
def inner(check):
check.tags = tags
checks = self.deployment_checks if kwargs['deploy'] else self.registered_checks
checks.add(check)
return check
if callable(check):
return inner(check)
else:
if check:
tags += (check, )
return inner
def run_checks(self, app_configs=None, tags=None, include_deployment_checks=False):
"""
Run all registered checks and return list of Errors and Warnings.
"""
errors = []
checks = self.get_checks(include_deployment_checks)
if tags is not None:
checks = [check for check in checks if not set(check.tags).isdisjoint(tags)]
else:
# By default, 'database'-tagged checks are not run as they do more
# than mere static code analysis.
checks = [check for check in checks if Tags.database not in check.tags]
for check in checks:
new_errors = check(app_configs=app_configs)
assert is_iterable(new_errors), (
"The function %r did not return a list. All functions registered "
"with the checks registry must return a list." % check)
errors.extend(new_errors)
return errors
def tag_exists(self, tag, include_deployment_checks=False):
return tag in self.tags_available(include_deployment_checks)
def tags_available(self, deployment_checks=False):
return set(chain.from_iterable(
check.tags for check in self.get_checks(deployment_checks)
))
def get_checks(self, include_deployment_checks=False):
checks = list(self.registered_checks)
if include_deployment_checks:
checks.extend(self.deployment_checks)
return checks
registry = CheckRegistry()
register = registry.register
run_checks = registry.run_checks
tag_exists = registry.tag_exists
| bsd-3-clause | -2,035,686,896,372,967,700 | 30.714286 | 91 | 0.602317 | false | 4.433666 | false | false | false |
kmike/scikit-learn | sklearn/utils/__init__.py | 3 | 10094 | """
The :mod:`sklearn.utils` module includes various utilites.
"""
from collections import Sequence
import numpy as np
from scipy.sparse import issparse
import warnings
from .murmurhash import murmurhash3_32
from .validation import (as_float_array, check_arrays, safe_asarray,
assert_all_finite, array2d, atleast2d_or_csc,
atleast2d_or_csr, warn_if_not_float,
check_random_state)
from .class_weight import compute_class_weight
__all__ = ["murmurhash3_32", "as_float_array", "check_arrays", "safe_asarray",
"assert_all_finite", "array2d", "atleast2d_or_csc",
"atleast2d_or_csr", "warn_if_not_float", "check_random_state",
"compute_class_weight"]
# Make sure that DeprecationWarning get printed
warnings.simplefilter("always", DeprecationWarning)
class deprecated(object):
"""Decorator to mark a function or class as deprecated.
Issue a warning when the function is called/the class is instantiated and
adds a warning to the docstring.
The optional extra argument will be appended to the deprecation message
and the docstring. Note: to use this with the default value for extra, put
in an empty of parentheses:
>>> from sklearn.utils import deprecated
>>> deprecated() # doctest: +ELLIPSIS
<sklearn.utils.deprecated object at ...>
>>> @deprecated()
... def some_function(): pass
"""
# Adapted from http://wiki.python.org/moin/PythonDecoratorLibrary,
# but with many changes.
def __init__(self, extra=''):
"""
Parameters
----------
extra: string
to be added to the deprecation messages
"""
self.extra = extra
def __call__(self, obj):
if isinstance(obj, type):
return self._decorate_class(obj)
else:
return self._decorate_fun(obj)
def _decorate_class(self, cls):
msg = "Class %s is deprecated" % cls.__name__
if self.extra:
msg += "; %s" % self.extra
# FIXME: we should probably reset __new__ for full generality
init = cls.__init__
def wrapped(*args, **kwargs):
warnings.warn(msg, category=DeprecationWarning)
return init(*args, **kwargs)
cls.__init__ = wrapped
wrapped.__name__ = '__init__'
wrapped.__doc__ = self._update_doc(init.__doc__)
wrapped.deprecated_original = init
return cls
def _decorate_fun(self, fun):
"""Decorate function fun"""
msg = "Function %s is deprecated" % fun.__name__
if self.extra:
msg += "; %s" % self.extra
def wrapped(*args, **kwargs):
warnings.warn(msg, category=DeprecationWarning)
return fun(*args, **kwargs)
wrapped.__name__ = fun.__name__
wrapped.__dict__ = fun.__dict__
wrapped.__doc__ = self._update_doc(fun.__doc__)
return wrapped
def _update_doc(self, olddoc):
newdoc = "DEPRECATED"
if self.extra:
newdoc = "%s: %s" % (newdoc, self.extra)
if olddoc:
newdoc = "%s\n\n%s" % (newdoc, olddoc)
return newdoc
def safe_mask(X, mask):
"""Return a mask which is safe to use on X.
Parameters
----------
X : {array-like, sparse matrix}
Data on which to apply mask.
mask: array
Mask to be used on X.
Returns
-------
mask
"""
mask = np.asanyarray(mask)
if np.issubdtype(mask.dtype, np.int):
return mask
if hasattr(X, "toarray"):
ind = np.arange(mask.shape[0])
mask = ind[mask]
return mask
def resample(*arrays, **options):
"""Resample arrays or sparse matrices in a consistent way
The default strategy implements one step of the bootstrapping
procedure.
Parameters
----------
`*arrays` : sequence of arrays or scipy.sparse matrices with same shape[0]
replace : boolean, True by default
Implements resampling with replacement. If False, this will implement
(sliced) random permutations.
n_samples : int, None by default
Number of samples to generate. If left to None this is
automatically set to the first dimension of the arrays.
random_state : int or RandomState instance
Control the shuffling for reproducible behavior.
Returns
-------
Sequence of resampled views of the collections. The original arrays are
not impacted.
Examples
--------
It is possible to mix sparse and dense arrays in the same run::
>>> X = [[1., 0.], [2., 1.], [0., 0.]]
>>> y = np.array([0, 1, 2])
>>> from scipy.sparse import coo_matrix
>>> X_sparse = coo_matrix(X)
>>> from sklearn.utils import resample
>>> X, X_sparse, y = resample(X, X_sparse, y, random_state=0)
>>> X
array([[ 1., 0.],
[ 2., 1.],
[ 1., 0.]])
>>> X_sparse # doctest: +ELLIPSIS +NORMALIZE_WHITESPACE
<3x2 sparse matrix of type '<... 'numpy.float64'>'
with 4 stored elements in Compressed Sparse Row format>
>>> X_sparse.toarray()
array([[ 1., 0.],
[ 2., 1.],
[ 1., 0.]])
>>> y
array([0, 1, 0])
>>> resample(y, n_samples=2, random_state=0)
array([0, 1])
See also
--------
:class:`sklearn.cross_validation.Bootstrap`
:func:`sklearn.utils.shuffle`
"""
random_state = check_random_state(options.pop('random_state', None))
replace = options.pop('replace', True)
max_n_samples = options.pop('n_samples', None)
if options:
raise ValueError("Unexpected kw arguments: %r" % options.keys())
if len(arrays) == 0:
return None
first = arrays[0]
n_samples = first.shape[0] if hasattr(first, 'shape') else len(first)
if max_n_samples is None:
max_n_samples = n_samples
if max_n_samples > n_samples:
raise ValueError("Cannot sample %d out of arrays with dim %d" % (
max_n_samples, n_samples))
arrays = check_arrays(*arrays, sparse_format='csr')
if replace:
indices = random_state.randint(0, n_samples, size=(max_n_samples,))
else:
indices = np.arange(n_samples)
random_state.shuffle(indices)
indices = indices[:max_n_samples]
resampled_arrays = []
for array in arrays:
array = array[indices]
resampled_arrays.append(array)
if len(resampled_arrays) == 1:
# syntactic sugar for the unit argument case
return resampled_arrays[0]
else:
return resampled_arrays
def shuffle(*arrays, **options):
"""Shuffle arrays or sparse matrices in a consistent way
This is a convenience alias to ``resample(*arrays, replace=False)`` to do
random permutations of the collections.
Parameters
----------
`*arrays` : sequence of arrays or scipy.sparse matrices with same shape[0]
random_state : int or RandomState instance
Control the shuffling for reproducible behavior.
n_samples : int, None by default
Number of samples to generate. If left to None this is
automatically set to the first dimension of the arrays.
Returns
-------
Sequence of shuffled views of the collections. The original arrays are
not impacted.
Examples
--------
It is possible to mix sparse and dense arrays in the same run::
>>> X = [[1., 0.], [2., 1.], [0., 0.]]
>>> y = np.array([0, 1, 2])
>>> from scipy.sparse import coo_matrix
>>> X_sparse = coo_matrix(X)
>>> from sklearn.utils import shuffle
>>> X, X_sparse, y = shuffle(X, X_sparse, y, random_state=0)
>>> X
array([[ 0., 0.],
[ 2., 1.],
[ 1., 0.]])
>>> X_sparse # doctest: +ELLIPSIS +NORMALIZE_WHITESPACE
<3x2 sparse matrix of type '<... 'numpy.float64'>'
with 3 stored elements in Compressed Sparse Row format>
>>> X_sparse.toarray()
array([[ 0., 0.],
[ 2., 1.],
[ 1., 0.]])
>>> y
array([2, 1, 0])
>>> shuffle(y, n_samples=2, random_state=0)
array([0, 1])
See also
--------
:func:`sklearn.utils.resample`
"""
options['replace'] = False
return resample(*arrays, **options)
def safe_sqr(X, copy=True):
"""Element wise squaring of array-likes and sparse matrices.
Parameters
----------
X : array like, matrix, sparse matrix
Returns
-------
X ** 2 : element wise square
"""
X = safe_asarray(X)
if issparse(X):
if copy:
X = X.copy()
X.data **= 2
else:
if copy:
X = X ** 2
else:
X **= 2
return X
def gen_even_slices(n, n_packs):
"""Generator to create n_packs slices going up to n.
Examples
--------
>>> from sklearn.utils import gen_even_slices
>>> list(gen_even_slices(10, 1))
[slice(0, 10, None)]
>>> list(gen_even_slices(10, 10)) #doctest: +ELLIPSIS
[slice(0, 1, None), slice(1, 2, None), ..., slice(9, 10, None)]
>>> list(gen_even_slices(10, 5)) #doctest: +ELLIPSIS
[slice(0, 2, None), slice(2, 4, None), ..., slice(8, 10, None)]
>>> list(gen_even_slices(10, 3))
[slice(0, 4, None), slice(4, 7, None), slice(7, 10, None)]
"""
start = 0
for pack_num in range(n_packs):
this_n = n // n_packs
if pack_num < n % n_packs:
this_n += 1
if this_n > 0:
end = start + this_n
yield slice(start, end, None)
start = end
def tosequence(x):
"""Cast iterable x to a Sequence, avoiding a copy if possible."""
if isinstance(x, np.ndarray):
return np.asarray(x)
elif isinstance(x, Sequence):
return x
else:
return list(x)
class ConvergenceWarning(Warning):
"Custom warning to capture convergence problems"
| bsd-3-clause | 2,334,709,577,611,160,600 | 26.883978 | 79 | 0.56806 | false | 3.874856 | false | false | false |
houlixin/BBB-TISDK | linux-devkit/sysroots/i686-arago-linux/usr/lib/python2.7/encodings/cp1250.py | 593 | 13942 | """ Python Character Mapping Codec cp1250 generated from 'MAPPINGS/VENDORS/MICSFT/WINDOWS/CP1250.TXT' with gencodec.py.
"""#"
import codecs
### Codec APIs
class Codec(codecs.Codec):
def encode(self,input,errors='strict'):
return codecs.charmap_encode(input,errors,encoding_table)
def decode(self,input,errors='strict'):
return codecs.charmap_decode(input,errors,decoding_table)
class IncrementalEncoder(codecs.IncrementalEncoder):
def encode(self, input, final=False):
return codecs.charmap_encode(input,self.errors,encoding_table)[0]
class IncrementalDecoder(codecs.IncrementalDecoder):
def decode(self, input, final=False):
return codecs.charmap_decode(input,self.errors,decoding_table)[0]
class StreamWriter(Codec,codecs.StreamWriter):
pass
class StreamReader(Codec,codecs.StreamReader):
pass
### encodings module API
def getregentry():
return codecs.CodecInfo(
name='cp1250',
encode=Codec().encode,
decode=Codec().decode,
incrementalencoder=IncrementalEncoder,
incrementaldecoder=IncrementalDecoder,
streamreader=StreamReader,
streamwriter=StreamWriter,
)
### Decoding Table
decoding_table = (
u'\x00' # 0x00 -> NULL
u'\x01' # 0x01 -> START OF HEADING
u'\x02' # 0x02 -> START OF TEXT
u'\x03' # 0x03 -> END OF TEXT
u'\x04' # 0x04 -> END OF TRANSMISSION
u'\x05' # 0x05 -> ENQUIRY
u'\x06' # 0x06 -> ACKNOWLEDGE
u'\x07' # 0x07 -> BELL
u'\x08' # 0x08 -> BACKSPACE
u'\t' # 0x09 -> HORIZONTAL TABULATION
u'\n' # 0x0A -> LINE FEED
u'\x0b' # 0x0B -> VERTICAL TABULATION
u'\x0c' # 0x0C -> FORM FEED
u'\r' # 0x0D -> CARRIAGE RETURN
u'\x0e' # 0x0E -> SHIFT OUT
u'\x0f' # 0x0F -> SHIFT IN
u'\x10' # 0x10 -> DATA LINK ESCAPE
u'\x11' # 0x11 -> DEVICE CONTROL ONE
u'\x12' # 0x12 -> DEVICE CONTROL TWO
u'\x13' # 0x13 -> DEVICE CONTROL THREE
u'\x14' # 0x14 -> DEVICE CONTROL FOUR
u'\x15' # 0x15 -> NEGATIVE ACKNOWLEDGE
u'\x16' # 0x16 -> SYNCHRONOUS IDLE
u'\x17' # 0x17 -> END OF TRANSMISSION BLOCK
u'\x18' # 0x18 -> CANCEL
u'\x19' # 0x19 -> END OF MEDIUM
u'\x1a' # 0x1A -> SUBSTITUTE
u'\x1b' # 0x1B -> ESCAPE
u'\x1c' # 0x1C -> FILE SEPARATOR
u'\x1d' # 0x1D -> GROUP SEPARATOR
u'\x1e' # 0x1E -> RECORD SEPARATOR
u'\x1f' # 0x1F -> UNIT SEPARATOR
u' ' # 0x20 -> SPACE
u'!' # 0x21 -> EXCLAMATION MARK
u'"' # 0x22 -> QUOTATION MARK
u'#' # 0x23 -> NUMBER SIGN
u'$' # 0x24 -> DOLLAR SIGN
u'%' # 0x25 -> PERCENT SIGN
u'&' # 0x26 -> AMPERSAND
u"'" # 0x27 -> APOSTROPHE
u'(' # 0x28 -> LEFT PARENTHESIS
u')' # 0x29 -> RIGHT PARENTHESIS
u'*' # 0x2A -> ASTERISK
u'+' # 0x2B -> PLUS SIGN
u',' # 0x2C -> COMMA
u'-' # 0x2D -> HYPHEN-MINUS
u'.' # 0x2E -> FULL STOP
u'/' # 0x2F -> SOLIDUS
u'0' # 0x30 -> DIGIT ZERO
u'1' # 0x31 -> DIGIT ONE
u'2' # 0x32 -> DIGIT TWO
u'3' # 0x33 -> DIGIT THREE
u'4' # 0x34 -> DIGIT FOUR
u'5' # 0x35 -> DIGIT FIVE
u'6' # 0x36 -> DIGIT SIX
u'7' # 0x37 -> DIGIT SEVEN
u'8' # 0x38 -> DIGIT EIGHT
u'9' # 0x39 -> DIGIT NINE
u':' # 0x3A -> COLON
u';' # 0x3B -> SEMICOLON
u'<' # 0x3C -> LESS-THAN SIGN
u'=' # 0x3D -> EQUALS SIGN
u'>' # 0x3E -> GREATER-THAN SIGN
u'?' # 0x3F -> QUESTION MARK
u'@' # 0x40 -> COMMERCIAL AT
u'A' # 0x41 -> LATIN CAPITAL LETTER A
u'B' # 0x42 -> LATIN CAPITAL LETTER B
u'C' # 0x43 -> LATIN CAPITAL LETTER C
u'D' # 0x44 -> LATIN CAPITAL LETTER D
u'E' # 0x45 -> LATIN CAPITAL LETTER E
u'F' # 0x46 -> LATIN CAPITAL LETTER F
u'G' # 0x47 -> LATIN CAPITAL LETTER G
u'H' # 0x48 -> LATIN CAPITAL LETTER H
u'I' # 0x49 -> LATIN CAPITAL LETTER I
u'J' # 0x4A -> LATIN CAPITAL LETTER J
u'K' # 0x4B -> LATIN CAPITAL LETTER K
u'L' # 0x4C -> LATIN CAPITAL LETTER L
u'M' # 0x4D -> LATIN CAPITAL LETTER M
u'N' # 0x4E -> LATIN CAPITAL LETTER N
u'O' # 0x4F -> LATIN CAPITAL LETTER O
u'P' # 0x50 -> LATIN CAPITAL LETTER P
u'Q' # 0x51 -> LATIN CAPITAL LETTER Q
u'R' # 0x52 -> LATIN CAPITAL LETTER R
u'S' # 0x53 -> LATIN CAPITAL LETTER S
u'T' # 0x54 -> LATIN CAPITAL LETTER T
u'U' # 0x55 -> LATIN CAPITAL LETTER U
u'V' # 0x56 -> LATIN CAPITAL LETTER V
u'W' # 0x57 -> LATIN CAPITAL LETTER W
u'X' # 0x58 -> LATIN CAPITAL LETTER X
u'Y' # 0x59 -> LATIN CAPITAL LETTER Y
u'Z' # 0x5A -> LATIN CAPITAL LETTER Z
u'[' # 0x5B -> LEFT SQUARE BRACKET
u'\\' # 0x5C -> REVERSE SOLIDUS
u']' # 0x5D -> RIGHT SQUARE BRACKET
u'^' # 0x5E -> CIRCUMFLEX ACCENT
u'_' # 0x5F -> LOW LINE
u'`' # 0x60 -> GRAVE ACCENT
u'a' # 0x61 -> LATIN SMALL LETTER A
u'b' # 0x62 -> LATIN SMALL LETTER B
u'c' # 0x63 -> LATIN SMALL LETTER C
u'd' # 0x64 -> LATIN SMALL LETTER D
u'e' # 0x65 -> LATIN SMALL LETTER E
u'f' # 0x66 -> LATIN SMALL LETTER F
u'g' # 0x67 -> LATIN SMALL LETTER G
u'h' # 0x68 -> LATIN SMALL LETTER H
u'i' # 0x69 -> LATIN SMALL LETTER I
u'j' # 0x6A -> LATIN SMALL LETTER J
u'k' # 0x6B -> LATIN SMALL LETTER K
u'l' # 0x6C -> LATIN SMALL LETTER L
u'm' # 0x6D -> LATIN SMALL LETTER M
u'n' # 0x6E -> LATIN SMALL LETTER N
u'o' # 0x6F -> LATIN SMALL LETTER O
u'p' # 0x70 -> LATIN SMALL LETTER P
u'q' # 0x71 -> LATIN SMALL LETTER Q
u'r' # 0x72 -> LATIN SMALL LETTER R
u's' # 0x73 -> LATIN SMALL LETTER S
u't' # 0x74 -> LATIN SMALL LETTER T
u'u' # 0x75 -> LATIN SMALL LETTER U
u'v' # 0x76 -> LATIN SMALL LETTER V
u'w' # 0x77 -> LATIN SMALL LETTER W
u'x' # 0x78 -> LATIN SMALL LETTER X
u'y' # 0x79 -> LATIN SMALL LETTER Y
u'z' # 0x7A -> LATIN SMALL LETTER Z
u'{' # 0x7B -> LEFT CURLY BRACKET
u'|' # 0x7C -> VERTICAL LINE
u'}' # 0x7D -> RIGHT CURLY BRACKET
u'~' # 0x7E -> TILDE
u'\x7f' # 0x7F -> DELETE
u'\u20ac' # 0x80 -> EURO SIGN
u'\ufffe' # 0x81 -> UNDEFINED
u'\u201a' # 0x82 -> SINGLE LOW-9 QUOTATION MARK
u'\ufffe' # 0x83 -> UNDEFINED
u'\u201e' # 0x84 -> DOUBLE LOW-9 QUOTATION MARK
u'\u2026' # 0x85 -> HORIZONTAL ELLIPSIS
u'\u2020' # 0x86 -> DAGGER
u'\u2021' # 0x87 -> DOUBLE DAGGER
u'\ufffe' # 0x88 -> UNDEFINED
u'\u2030' # 0x89 -> PER MILLE SIGN
u'\u0160' # 0x8A -> LATIN CAPITAL LETTER S WITH CARON
u'\u2039' # 0x8B -> SINGLE LEFT-POINTING ANGLE QUOTATION MARK
u'\u015a' # 0x8C -> LATIN CAPITAL LETTER S WITH ACUTE
u'\u0164' # 0x8D -> LATIN CAPITAL LETTER T WITH CARON
u'\u017d' # 0x8E -> LATIN CAPITAL LETTER Z WITH CARON
u'\u0179' # 0x8F -> LATIN CAPITAL LETTER Z WITH ACUTE
u'\ufffe' # 0x90 -> UNDEFINED
u'\u2018' # 0x91 -> LEFT SINGLE QUOTATION MARK
u'\u2019' # 0x92 -> RIGHT SINGLE QUOTATION MARK
u'\u201c' # 0x93 -> LEFT DOUBLE QUOTATION MARK
u'\u201d' # 0x94 -> RIGHT DOUBLE QUOTATION MARK
u'\u2022' # 0x95 -> BULLET
u'\u2013' # 0x96 -> EN DASH
u'\u2014' # 0x97 -> EM DASH
u'\ufffe' # 0x98 -> UNDEFINED
u'\u2122' # 0x99 -> TRADE MARK SIGN
u'\u0161' # 0x9A -> LATIN SMALL LETTER S WITH CARON
u'\u203a' # 0x9B -> SINGLE RIGHT-POINTING ANGLE QUOTATION MARK
u'\u015b' # 0x9C -> LATIN SMALL LETTER S WITH ACUTE
u'\u0165' # 0x9D -> LATIN SMALL LETTER T WITH CARON
u'\u017e' # 0x9E -> LATIN SMALL LETTER Z WITH CARON
u'\u017a' # 0x9F -> LATIN SMALL LETTER Z WITH ACUTE
u'\xa0' # 0xA0 -> NO-BREAK SPACE
u'\u02c7' # 0xA1 -> CARON
u'\u02d8' # 0xA2 -> BREVE
u'\u0141' # 0xA3 -> LATIN CAPITAL LETTER L WITH STROKE
u'\xa4' # 0xA4 -> CURRENCY SIGN
u'\u0104' # 0xA5 -> LATIN CAPITAL LETTER A WITH OGONEK
u'\xa6' # 0xA6 -> BROKEN BAR
u'\xa7' # 0xA7 -> SECTION SIGN
u'\xa8' # 0xA8 -> DIAERESIS
u'\xa9' # 0xA9 -> COPYRIGHT SIGN
u'\u015e' # 0xAA -> LATIN CAPITAL LETTER S WITH CEDILLA
u'\xab' # 0xAB -> LEFT-POINTING DOUBLE ANGLE QUOTATION MARK
u'\xac' # 0xAC -> NOT SIGN
u'\xad' # 0xAD -> SOFT HYPHEN
u'\xae' # 0xAE -> REGISTERED SIGN
u'\u017b' # 0xAF -> LATIN CAPITAL LETTER Z WITH DOT ABOVE
u'\xb0' # 0xB0 -> DEGREE SIGN
u'\xb1' # 0xB1 -> PLUS-MINUS SIGN
u'\u02db' # 0xB2 -> OGONEK
u'\u0142' # 0xB3 -> LATIN SMALL LETTER L WITH STROKE
u'\xb4' # 0xB4 -> ACUTE ACCENT
u'\xb5' # 0xB5 -> MICRO SIGN
u'\xb6' # 0xB6 -> PILCROW SIGN
u'\xb7' # 0xB7 -> MIDDLE DOT
u'\xb8' # 0xB8 -> CEDILLA
u'\u0105' # 0xB9 -> LATIN SMALL LETTER A WITH OGONEK
u'\u015f' # 0xBA -> LATIN SMALL LETTER S WITH CEDILLA
u'\xbb' # 0xBB -> RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK
u'\u013d' # 0xBC -> LATIN CAPITAL LETTER L WITH CARON
u'\u02dd' # 0xBD -> DOUBLE ACUTE ACCENT
u'\u013e' # 0xBE -> LATIN SMALL LETTER L WITH CARON
u'\u017c' # 0xBF -> LATIN SMALL LETTER Z WITH DOT ABOVE
u'\u0154' # 0xC0 -> LATIN CAPITAL LETTER R WITH ACUTE
u'\xc1' # 0xC1 -> LATIN CAPITAL LETTER A WITH ACUTE
u'\xc2' # 0xC2 -> LATIN CAPITAL LETTER A WITH CIRCUMFLEX
u'\u0102' # 0xC3 -> LATIN CAPITAL LETTER A WITH BREVE
u'\xc4' # 0xC4 -> LATIN CAPITAL LETTER A WITH DIAERESIS
u'\u0139' # 0xC5 -> LATIN CAPITAL LETTER L WITH ACUTE
u'\u0106' # 0xC6 -> LATIN CAPITAL LETTER C WITH ACUTE
u'\xc7' # 0xC7 -> LATIN CAPITAL LETTER C WITH CEDILLA
u'\u010c' # 0xC8 -> LATIN CAPITAL LETTER C WITH CARON
u'\xc9' # 0xC9 -> LATIN CAPITAL LETTER E WITH ACUTE
u'\u0118' # 0xCA -> LATIN CAPITAL LETTER E WITH OGONEK
u'\xcb' # 0xCB -> LATIN CAPITAL LETTER E WITH DIAERESIS
u'\u011a' # 0xCC -> LATIN CAPITAL LETTER E WITH CARON
u'\xcd' # 0xCD -> LATIN CAPITAL LETTER I WITH ACUTE
u'\xce' # 0xCE -> LATIN CAPITAL LETTER I WITH CIRCUMFLEX
u'\u010e' # 0xCF -> LATIN CAPITAL LETTER D WITH CARON
u'\u0110' # 0xD0 -> LATIN CAPITAL LETTER D WITH STROKE
u'\u0143' # 0xD1 -> LATIN CAPITAL LETTER N WITH ACUTE
u'\u0147' # 0xD2 -> LATIN CAPITAL LETTER N WITH CARON
u'\xd3' # 0xD3 -> LATIN CAPITAL LETTER O WITH ACUTE
u'\xd4' # 0xD4 -> LATIN CAPITAL LETTER O WITH CIRCUMFLEX
u'\u0150' # 0xD5 -> LATIN CAPITAL LETTER O WITH DOUBLE ACUTE
u'\xd6' # 0xD6 -> LATIN CAPITAL LETTER O WITH DIAERESIS
u'\xd7' # 0xD7 -> MULTIPLICATION SIGN
u'\u0158' # 0xD8 -> LATIN CAPITAL LETTER R WITH CARON
u'\u016e' # 0xD9 -> LATIN CAPITAL LETTER U WITH RING ABOVE
u'\xda' # 0xDA -> LATIN CAPITAL LETTER U WITH ACUTE
u'\u0170' # 0xDB -> LATIN CAPITAL LETTER U WITH DOUBLE ACUTE
u'\xdc' # 0xDC -> LATIN CAPITAL LETTER U WITH DIAERESIS
u'\xdd' # 0xDD -> LATIN CAPITAL LETTER Y WITH ACUTE
u'\u0162' # 0xDE -> LATIN CAPITAL LETTER T WITH CEDILLA
u'\xdf' # 0xDF -> LATIN SMALL LETTER SHARP S
u'\u0155' # 0xE0 -> LATIN SMALL LETTER R WITH ACUTE
u'\xe1' # 0xE1 -> LATIN SMALL LETTER A WITH ACUTE
u'\xe2' # 0xE2 -> LATIN SMALL LETTER A WITH CIRCUMFLEX
u'\u0103' # 0xE3 -> LATIN SMALL LETTER A WITH BREVE
u'\xe4' # 0xE4 -> LATIN SMALL LETTER A WITH DIAERESIS
u'\u013a' # 0xE5 -> LATIN SMALL LETTER L WITH ACUTE
u'\u0107' # 0xE6 -> LATIN SMALL LETTER C WITH ACUTE
u'\xe7' # 0xE7 -> LATIN SMALL LETTER C WITH CEDILLA
u'\u010d' # 0xE8 -> LATIN SMALL LETTER C WITH CARON
u'\xe9' # 0xE9 -> LATIN SMALL LETTER E WITH ACUTE
u'\u0119' # 0xEA -> LATIN SMALL LETTER E WITH OGONEK
u'\xeb' # 0xEB -> LATIN SMALL LETTER E WITH DIAERESIS
u'\u011b' # 0xEC -> LATIN SMALL LETTER E WITH CARON
u'\xed' # 0xED -> LATIN SMALL LETTER I WITH ACUTE
u'\xee' # 0xEE -> LATIN SMALL LETTER I WITH CIRCUMFLEX
u'\u010f' # 0xEF -> LATIN SMALL LETTER D WITH CARON
u'\u0111' # 0xF0 -> LATIN SMALL LETTER D WITH STROKE
u'\u0144' # 0xF1 -> LATIN SMALL LETTER N WITH ACUTE
u'\u0148' # 0xF2 -> LATIN SMALL LETTER N WITH CARON
u'\xf3' # 0xF3 -> LATIN SMALL LETTER O WITH ACUTE
u'\xf4' # 0xF4 -> LATIN SMALL LETTER O WITH CIRCUMFLEX
u'\u0151' # 0xF5 -> LATIN SMALL LETTER O WITH DOUBLE ACUTE
u'\xf6' # 0xF6 -> LATIN SMALL LETTER O WITH DIAERESIS
u'\xf7' # 0xF7 -> DIVISION SIGN
u'\u0159' # 0xF8 -> LATIN SMALL LETTER R WITH CARON
u'\u016f' # 0xF9 -> LATIN SMALL LETTER U WITH RING ABOVE
u'\xfa' # 0xFA -> LATIN SMALL LETTER U WITH ACUTE
u'\u0171' # 0xFB -> LATIN SMALL LETTER U WITH DOUBLE ACUTE
u'\xfc' # 0xFC -> LATIN SMALL LETTER U WITH DIAERESIS
u'\xfd' # 0xFD -> LATIN SMALL LETTER Y WITH ACUTE
u'\u0163' # 0xFE -> LATIN SMALL LETTER T WITH CEDILLA
u'\u02d9' # 0xFF -> DOT ABOVE
)
### Encoding table
encoding_table=codecs.charmap_build(decoding_table)
| gpl-2.0 | -6,356,832,018,515,183,000 | 44.413681 | 119 | 0.550351 | false | 3.023639 | false | false | false |
dataxu/ansible | lib/ansible/modules/system/kernel_blacklist.py | 125 | 4009 | #!/usr/bin/python
# encoding: utf-8 -*-
# Copyright: (c) 2013, Matthias Vogelgesang <matthias.vogelgesang@gmail.com>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
DOCUMENTATION = '''
---
module: kernel_blacklist
author:
- Matthias Vogelgesang (@matze)
version_added: '1.4'
short_description: Blacklist kernel modules
description:
- Add or remove kernel modules from blacklist.
options:
name:
description:
- Name of kernel module to black- or whitelist.
required: true
state:
description:
- Whether the module should be present in the blacklist or absent.
choices: [ absent, present ]
default: present
blacklist_file:
description:
- If specified, use this blacklist file instead of
C(/etc/modprobe.d/blacklist-ansible.conf).
'''
EXAMPLES = '''
- name: Blacklist the nouveau driver module
kernel_blacklist:
name: nouveau
state: present
'''
import os
import re
from ansible.module_utils.basic import AnsibleModule
class Blacklist(object):
def __init__(self, module, filename, checkmode):
self.filename = filename
self.module = module
self.checkmode = checkmode
def create_file(self):
if not self.checkmode and not os.path.exists(self.filename):
open(self.filename, 'a').close()
return True
elif self.checkmode and not os.path.exists(self.filename):
self.filename = os.devnull
return True
else:
return False
def get_pattern(self):
return r'^blacklist\s*' + self.module + '$'
def readlines(self):
f = open(self.filename, 'r')
lines = f.readlines()
f.close()
return lines
def module_listed(self):
lines = self.readlines()
pattern = self.get_pattern()
for line in lines:
stripped = line.strip()
if stripped.startswith('#'):
continue
if re.match(pattern, stripped):
return True
return False
def remove_module(self):
lines = self.readlines()
pattern = self.get_pattern()
if self.checkmode:
f = open(os.devnull, 'w')
else:
f = open(self.filename, 'w')
for line in lines:
if not re.match(pattern, line.strip()):
f.write(line)
f.close()
def add_module(self):
if self.checkmode:
f = open(os.devnull, 'a')
else:
f = open(self.filename, 'a')
f.write('blacklist %s\n' % self.module)
f.close()
def main():
module = AnsibleModule(
argument_spec=dict(
name=dict(type='str', required=True),
state=dict(type='str', default='present', choices=['absent', 'present']),
blacklist_file=dict(type='str')
),
supports_check_mode=True,
)
args = dict(changed=False, failed=False,
name=module.params['name'], state=module.params['state'])
filename = '/etc/modprobe.d/blacklist-ansible.conf'
if module.params['blacklist_file']:
filename = module.params['blacklist_file']
blacklist = Blacklist(args['name'], filename, module.check_mode)
if blacklist.create_file():
args['changed'] = True
else:
args['changed'] = False
if blacklist.module_listed():
if args['state'] == 'absent':
blacklist.remove_module()
args['changed'] = True
else:
if args['state'] == 'present':
blacklist.add_module()
args['changed'] = True
module.exit_json(**args)
if __name__ == '__main__':
main()
| gpl-3.0 | 8,498,771,084,445,727,000 | 24.864516 | 92 | 0.575206 | false | 4.017034 | false | false | false |
163gal/Time-Line | libs_arm/wx/_controls.py | 2 | 332374 | # This file was created automatically by SWIG 1.3.29.
# Don't modify this file, modify the SWIG interface instead.
import _controls_
import new
new_instancemethod = new.instancemethod
def _swig_setattr_nondynamic(self,class_type,name,value,static=1):
if (name == "thisown"): return self.this.own(value)
if (name == "this"):
if type(value).__name__ == 'PySwigObject':
self.__dict__[name] = value
return
method = class_type.__swig_setmethods__.get(name,None)
if method: return method(self,value)
if (not static) or hasattr(self,name):
self.__dict__[name] = value
else:
raise AttributeError("You cannot add attributes to %s" % self)
def _swig_setattr(self,class_type,name,value):
return _swig_setattr_nondynamic(self,class_type,name,value,0)
def _swig_getattr(self,class_type,name):
if (name == "thisown"): return self.this.own()
method = class_type.__swig_getmethods__.get(name,None)
if method: return method(self)
raise AttributeError,name
def _swig_repr(self):
try: strthis = "proxy of " + self.this.__repr__()
except: strthis = ""
return "<%s.%s; %s >" % (self.__class__.__module__, self.__class__.__name__, strthis,)
import types
try:
_object = types.ObjectType
_newclass = 1
except AttributeError:
class _object : pass
_newclass = 0
del types
def _swig_setattr_nondynamic_method(set):
def set_attr(self,name,value):
if (name == "thisown"): return self.this.own(value)
if hasattr(self,name) or (name == "this"):
set(self,name,value)
else:
raise AttributeError("You cannot add attributes to %s" % self)
return set_attr
import _core
wx = _core
#---------------------------------------------------------------------------
BU_LEFT = _controls_.BU_LEFT
BU_TOP = _controls_.BU_TOP
BU_RIGHT = _controls_.BU_RIGHT
BU_BOTTOM = _controls_.BU_BOTTOM
BU_ALIGN_MASK = _controls_.BU_ALIGN_MASK
BU_EXACTFIT = _controls_.BU_EXACTFIT
BU_AUTODRAW = _controls_.BU_AUTODRAW
BU_NOTEXT = _controls_.BU_NOTEXT
class AnyButton(_core.Control):
"""Proxy of C++ AnyButton class"""
thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
def __init__(self): raise AttributeError, "No constructor defined"
__repr__ = _swig_repr
def SetBitmap(*args, **kwargs):
"""SetBitmap(self, Bitmap bitmap, int dir=LEFT)"""
return _controls_.AnyButton_SetBitmap(*args, **kwargs)
def GetBitmap(*args, **kwargs):
"""GetBitmap(self) -> Bitmap"""
return _controls_.AnyButton_GetBitmap(*args, **kwargs)
Bitmap = property(GetBitmap,SetBitmap)
def SetBitmapLabel(*args, **kwargs):
"""SetBitmapLabel(self, Bitmap bitmap)"""
return _controls_.AnyButton_SetBitmapLabel(*args, **kwargs)
def SetBitmapPressed(*args, **kwargs):
"""SetBitmapPressed(self, Bitmap bitmap)"""
return _controls_.AnyButton_SetBitmapPressed(*args, **kwargs)
def SetBitmapDisabled(*args, **kwargs):
"""SetBitmapDisabled(self, Bitmap bitmap)"""
return _controls_.AnyButton_SetBitmapDisabled(*args, **kwargs)
def SetBitmapCurrent(*args, **kwargs):
"""SetBitmapCurrent(self, Bitmap bitmap)"""
return _controls_.AnyButton_SetBitmapCurrent(*args, **kwargs)
def SetBitmapFocus(*args, **kwargs):
"""SetBitmapFocus(self, Bitmap bitmap)"""
return _controls_.AnyButton_SetBitmapFocus(*args, **kwargs)
def GetBitmapLabel(*args, **kwargs):
"""GetBitmapLabel(self) -> Bitmap"""
return _controls_.AnyButton_GetBitmapLabel(*args, **kwargs)
def GetBitmapPressed(*args, **kwargs):
"""GetBitmapPressed(self) -> Bitmap"""
return _controls_.AnyButton_GetBitmapPressed(*args, **kwargs)
def GetBitmapDisabled(*args, **kwargs):
"""GetBitmapDisabled(self) -> Bitmap"""
return _controls_.AnyButton_GetBitmapDisabled(*args, **kwargs)
def GetBitmapCurrent(*args, **kwargs):
"""GetBitmapCurrent(self) -> Bitmap"""
return _controls_.AnyButton_GetBitmapCurrent(*args, **kwargs)
def GetBitmapFocus(*args, **kwargs):
"""GetBitmapFocus(self) -> Bitmap"""
return _controls_.AnyButton_GetBitmapFocus(*args, **kwargs)
BitmapLabel = property(GetBitmapLabel,SetBitmapLabel)
BitmapPressed = property(GetBitmapPressed,SetBitmapPressed)
BitmapDisabled = property(GetBitmapDisabled,SetBitmapDisabled)
BitmapCurrent = property(GetBitmapCurrent,SetBitmapCurrent)
BitmapFocus = property(GetBitmapFocus,SetBitmapFocus)
def GetBitmapSelected(*args, **kwargs):
"""GetBitmapSelected(self) -> Bitmap"""
return _controls_.AnyButton_GetBitmapSelected(*args, **kwargs)
def GetBitmapHover(*args, **kwargs):
"""GetBitmapHover(self) -> Bitmap"""
return _controls_.AnyButton_GetBitmapHover(*args, **kwargs)
def SetBitmapSelected(*args, **kwargs):
"""SetBitmapSelected(self, Bitmap bitmap)"""
return _controls_.AnyButton_SetBitmapSelected(*args, **kwargs)
def SetBitmapHover(*args, **kwargs):
"""SetBitmapHover(self, Bitmap bitmap)"""
return _controls_.AnyButton_SetBitmapHover(*args, **kwargs)
BitmapSelected = property(GetBitmapSelected,SetBitmapSelected)
BitmapHover = property(GetBitmapHover,SetBitmapHover)
def SetBitmapMargins(*args):
"""
SetBitmapMargins(self, int x, int y)
SetBitmapMargins(self, Size sz)
"""
return _controls_.AnyButton_SetBitmapMargins(*args)
def GetBitmapMargins(*args, **kwargs):
"""GetBitmapMargins(self) -> Size"""
return _controls_.AnyButton_GetBitmapMargins(*args, **kwargs)
BitmapMargins = property(GetBitmapMargins,SetBitmapMargins)
def SetBitmapPosition(*args, **kwargs):
"""SetBitmapPosition(self, int dir)"""
return _controls_.AnyButton_SetBitmapPosition(*args, **kwargs)
def DontShowLabel(*args, **kwargs):
"""DontShowLabel(self) -> bool"""
return _controls_.AnyButton_DontShowLabel(*args, **kwargs)
def ShowsLabel(*args, **kwargs):
"""ShowsLabel(self) -> bool"""
return _controls_.AnyButton_ShowsLabel(*args, **kwargs)
_controls_.AnyButton_swigregister(AnyButton)
cvar = _controls_.cvar
ButtonNameStr = cvar.ButtonNameStr
class Button(AnyButton):
"""
A button is a control that contains a text string, and is one of the most
common elements of a GUI. It may be placed on a dialog box or panel, or
indeed almost any other window.
"""
thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
def __init__(self, *args, **kwargs):
"""
__init__(self, Window parent, int id=-1, String label=EmptyString,
Point pos=DefaultPosition, Size size=DefaultSize,
long style=0, Validator validator=DefaultValidator,
String name=ButtonNameStr) -> Button
Create and show a button. The preferred way to create standard
buttons is to use a standard ID and an empty label. In this case
wxWigets will automatically use a stock label that corresponds to the
ID given. These labels may vary across platforms as the platform
itself will provide the label if possible. In addition, the button
will be decorated with stock icons under GTK+ 2.
"""
_controls_.Button_swiginit(self,_controls_.new_Button(*args, **kwargs))
self._setOORInfo(self)
def Create(*args, **kwargs):
"""
Create(self, Window parent, int id=-1, String label=EmptyString,
Point pos=DefaultPosition, Size size=DefaultSize,
long style=0, Validator validator=DefaultValidator,
String name=ButtonNameStr) -> bool
Acutally create the GUI Button for 2-phase creation.
"""
return _controls_.Button_Create(*args, **kwargs)
def SetAuthNeeded(*args, **kwargs):
"""SetAuthNeeded(self, bool show=True)"""
return _controls_.Button_SetAuthNeeded(*args, **kwargs)
def GetAuthNeeded(*args, **kwargs):
"""GetAuthNeeded(self) -> bool"""
return _controls_.Button_GetAuthNeeded(*args, **kwargs)
def SetDefault(*args, **kwargs):
"""
SetDefault(self) -> Window
This sets the button to be the default item for the panel or dialog box.
"""
return _controls_.Button_SetDefault(*args, **kwargs)
def GetDefaultSize(*args, **kwargs):
"""
GetDefaultSize() -> Size
Returns the default button size for this platform.
"""
return _controls_.Button_GetDefaultSize(*args, **kwargs)
GetDefaultSize = staticmethod(GetDefaultSize)
def GetClassDefaultAttributes(*args, **kwargs):
"""
GetClassDefaultAttributes(int variant=WINDOW_VARIANT_NORMAL) -> VisualAttributes
Get the default attributes for this class. This is useful if you want
to use the same font or colour in your own control as in a standard
control -- which is a much better idea than hard coding specific
colours or fonts which might look completely out of place on the
user's system, especially if it uses themes.
The variant parameter is only relevant under Mac currently and is
ignore under other platforms. Under Mac, it will change the size of
the returned font. See `wx.Window.SetWindowVariant` for more about
this.
"""
return _controls_.Button_GetClassDefaultAttributes(*args, **kwargs)
GetClassDefaultAttributes = staticmethod(GetClassDefaultAttributes)
_controls_.Button_swigregister(Button)
def PreButton(*args, **kwargs):
"""
PreButton() -> Button
Precreate a Button for 2-phase creation.
"""
val = _controls_.new_PreButton(*args, **kwargs)
return val
def Button_GetDefaultSize(*args):
"""
Button_GetDefaultSize() -> Size
Returns the default button size for this platform.
"""
return _controls_.Button_GetDefaultSize(*args)
def Button_GetClassDefaultAttributes(*args, **kwargs):
"""
Button_GetClassDefaultAttributes(int variant=WINDOW_VARIANT_NORMAL) -> VisualAttributes
Get the default attributes for this class. This is useful if you want
to use the same font or colour in your own control as in a standard
control -- which is a much better idea than hard coding specific
colours or fonts which might look completely out of place on the
user's system, especially if it uses themes.
The variant parameter is only relevant under Mac currently and is
ignore under other platforms. Under Mac, it will change the size of
the returned font. See `wx.Window.SetWindowVariant` for more about
this.
"""
return _controls_.Button_GetClassDefaultAttributes(*args, **kwargs)
class BitmapButton(Button):
"""
A Button that contains a bitmap. A bitmap button can be supplied with a
single bitmap, and wxWidgets will draw all button states using this bitmap. If
the application needs more control, additional bitmaps for the selected state,
unpressed focused state, and greyed-out state may be supplied.
"""
thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
def __init__(self, *args, **kwargs):
"""
__init__(self, Window parent, int id=-1, Bitmap bitmap=wxNullBitmap,
Point pos=DefaultPosition, Size size=DefaultSize,
long style=BU_AUTODRAW, Validator validator=DefaultValidator,
String name=ButtonNameStr) -> BitmapButton
Create and show a button with a bitmap for the label.
"""
_controls_.BitmapButton_swiginit(self,_controls_.new_BitmapButton(*args, **kwargs))
self._setOORInfo(self)
def Create(*args, **kwargs):
"""
Create(self, Window parent, int id=-1, Bitmap bitmap=wxNullBitmap,
Point pos=DefaultPosition, Size size=DefaultSize,
long style=BU_AUTODRAW, Validator validator=DefaultValidator,
String name=ButtonNameStr) -> bool
Acutally create the GUI BitmapButton for 2-phase creation.
"""
return _controls_.BitmapButton_Create(*args, **kwargs)
_controls_.BitmapButton_swigregister(BitmapButton)
def PreBitmapButton(*args, **kwargs):
"""
PreBitmapButton() -> BitmapButton
Precreate a BitmapButton for 2-phase creation.
"""
val = _controls_.new_PreBitmapButton(*args, **kwargs)
return val
#---------------------------------------------------------------------------
CHK_2STATE = _controls_.CHK_2STATE
CHK_3STATE = _controls_.CHK_3STATE
CHK_ALLOW_3RD_STATE_FOR_USER = _controls_.CHK_ALLOW_3RD_STATE_FOR_USER
class CheckBox(_core.Control):
"""
A checkbox is a labelled box which by default is either on (the
checkmark is visible) or off (no checkmark). Optionally (When the
wx.CHK_3STATE style flag is set) it can have a third state, called the
mixed or undetermined state. Often this is used as a "Does Not
Apply" state.
"""
thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
def __init__(self, *args, **kwargs):
"""
__init__(self, Window parent, int id=-1, String label=EmptyString,
Point pos=DefaultPosition, Size size=DefaultSize,
long style=0, Validator validator=DefaultValidator,
String name=CheckBoxNameStr) -> CheckBox
Creates and shows a CheckBox control
"""
_controls_.CheckBox_swiginit(self,_controls_.new_CheckBox(*args, **kwargs))
self._setOORInfo(self)
def Create(*args, **kwargs):
"""
Create(self, Window parent, int id=-1, String label=EmptyString,
Point pos=DefaultPosition, Size size=DefaultSize,
long style=0, Validator validator=DefaultValidator,
String name=CheckBoxNameStr) -> bool
Actually create the GUI CheckBox for 2-phase creation.
"""
return _controls_.CheckBox_Create(*args, **kwargs)
def GetValue(*args, **kwargs):
"""
GetValue(self) -> bool
Gets the state of a 2-state CheckBox. Returns True if it is checked,
False otherwise.
"""
return _controls_.CheckBox_GetValue(*args, **kwargs)
def IsChecked(*args, **kwargs):
"""
IsChecked(self) -> bool
Similar to GetValue, but raises an exception if it is not a 2-state
CheckBox.
"""
return _controls_.CheckBox_IsChecked(*args, **kwargs)
def SetValue(*args, **kwargs):
"""
SetValue(self, bool state)
Set the state of a 2-state CheckBox. Pass True for checked, False for
unchecked.
"""
return _controls_.CheckBox_SetValue(*args, **kwargs)
def Get3StateValue(*args, **kwargs):
"""
Get3StateValue(self) -> int
Returns wx.CHK_UNCHECKED when the CheckBox is unchecked,
wx.CHK_CHECKED when it is checked and wx.CHK_UNDETERMINED when it's in
the undetermined state. Raises an exceptiion when the function is
used with a 2-state CheckBox.
"""
return _controls_.CheckBox_Get3StateValue(*args, **kwargs)
def Set3StateValue(*args, **kwargs):
"""
Set3StateValue(self, int state)
Sets the CheckBox to the given state. The state parameter can be one
of the following: wx.CHK_UNCHECKED (Check is off), wx.CHK_CHECKED (the
Check is on) or wx.CHK_UNDETERMINED (Check is mixed). Raises an
exception when the CheckBox is a 2-state checkbox and setting the
state to wx.CHK_UNDETERMINED.
"""
return _controls_.CheckBox_Set3StateValue(*args, **kwargs)
def Is3State(*args, **kwargs):
"""
Is3State(self) -> bool
Returns whether or not the CheckBox is a 3-state CheckBox.
"""
return _controls_.CheckBox_Is3State(*args, **kwargs)
def Is3rdStateAllowedForUser(*args, **kwargs):
"""
Is3rdStateAllowedForUser(self) -> bool
Returns whether or not the user can set the CheckBox to the third
state.
"""
return _controls_.CheckBox_Is3rdStateAllowedForUser(*args, **kwargs)
def GetClassDefaultAttributes(*args, **kwargs):
"""
GetClassDefaultAttributes(int variant=WINDOW_VARIANT_NORMAL) -> VisualAttributes
Get the default attributes for this class. This is useful if you want
to use the same font or colour in your own control as in a standard
control -- which is a much better idea than hard coding specific
colours or fonts which might look completely out of place on the
user's system, especially if it uses themes.
The variant parameter is only relevant under Mac currently and is
ignore under other platforms. Under Mac, it will change the size of
the returned font. See `wx.Window.SetWindowVariant` for more about
this.
"""
return _controls_.CheckBox_GetClassDefaultAttributes(*args, **kwargs)
GetClassDefaultAttributes = staticmethod(GetClassDefaultAttributes)
ThreeStateValue = property(Get3StateValue,Set3StateValue,doc="See `Get3StateValue` and `Set3StateValue`")
Value = property(GetValue,SetValue,doc="See `GetValue` and `SetValue`")
_controls_.CheckBox_swigregister(CheckBox)
CheckBoxNameStr = cvar.CheckBoxNameStr
def PreCheckBox(*args, **kwargs):
"""
PreCheckBox() -> CheckBox
Precreate a CheckBox for 2-phase creation.
"""
val = _controls_.new_PreCheckBox(*args, **kwargs)
return val
def CheckBox_GetClassDefaultAttributes(*args, **kwargs):
"""
CheckBox_GetClassDefaultAttributes(int variant=WINDOW_VARIANT_NORMAL) -> VisualAttributes
Get the default attributes for this class. This is useful if you want
to use the same font or colour in your own control as in a standard
control -- which is a much better idea than hard coding specific
colours or fonts which might look completely out of place on the
user's system, especially if it uses themes.
The variant parameter is only relevant under Mac currently and is
ignore under other platforms. Under Mac, it will change the size of
the returned font. See `wx.Window.SetWindowVariant` for more about
this.
"""
return _controls_.CheckBox_GetClassDefaultAttributes(*args, **kwargs)
#---------------------------------------------------------------------------
class Choice(_core.ControlWithItems):
"""
A Choice control is used to select one of a list of strings.
Unlike a `wx.ListBox`, only the selection is visible until the
user pulls down the menu of choices.
"""
thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
def __init__(self, *args, **kwargs):
"""
__init__(Window parent, int id, Point pos=DefaultPosition, Size size=DefaultSize,
List choices=EmptyList, long style=0, Validator validator=DefaultValidator,
String name=ChoiceNameStr) -> Choice
Create and show a Choice control
"""
_controls_.Choice_swiginit(self,_controls_.new_Choice(*args, **kwargs))
self._setOORInfo(self)
def Create(*args, **kwargs):
"""
Create(Window parent, int id, Point pos=DefaultPosition, Size size=DefaultSize,
List choices=EmptyList, long style=0, Validator validator=DefaultValidator,
String name=ChoiceNameStr) -> bool
Actually create the GUI Choice control for 2-phase creation
"""
return _controls_.Choice_Create(*args, **kwargs)
def GetCurrentSelection(*args, **kwargs):
"""
GetCurrentSelection(self) -> int
Unlike `GetSelection` which only returns the accepted selection value,
i.e. the selection in the control once the user closes the dropdown
list, this function returns the current selection. That is, while the
dropdown list is shown, it returns the currently selected item in
it. When it is not shown, its result is the same as for the other
function.
"""
return _controls_.Choice_GetCurrentSelection(*args, **kwargs)
def GetClassDefaultAttributes(*args, **kwargs):
"""
GetClassDefaultAttributes(int variant=WINDOW_VARIANT_NORMAL) -> VisualAttributes
Get the default attributes for this class. This is useful if you want
to use the same font or colour in your own control as in a standard
control -- which is a much better idea than hard coding specific
colours or fonts which might look completely out of place on the
user's system, especially if it uses themes.
The variant parameter is only relevant under Mac currently and is
ignore under other platforms. Under Mac, it will change the size of
the returned font. See `wx.Window.SetWindowVariant` for more about
this.
"""
return _controls_.Choice_GetClassDefaultAttributes(*args, **kwargs)
GetClassDefaultAttributes = staticmethod(GetClassDefaultAttributes)
CurrentSelection = property(GetCurrentSelection,doc="See `GetCurrentSelection`")
_controls_.Choice_swigregister(Choice)
ChoiceNameStr = cvar.ChoiceNameStr
def PreChoice(*args, **kwargs):
"""
PreChoice() -> Choice
Precreate a Choice control for 2-phase creation.
"""
val = _controls_.new_PreChoice(*args, **kwargs)
return val
def Choice_GetClassDefaultAttributes(*args, **kwargs):
"""
Choice_GetClassDefaultAttributes(int variant=WINDOW_VARIANT_NORMAL) -> VisualAttributes
Get the default attributes for this class. This is useful if you want
to use the same font or colour in your own control as in a standard
control -- which is a much better idea than hard coding specific
colours or fonts which might look completely out of place on the
user's system, especially if it uses themes.
The variant parameter is only relevant under Mac currently and is
ignore under other platforms. Under Mac, it will change the size of
the returned font. See `wx.Window.SetWindowVariant` for more about
this.
"""
return _controls_.Choice_GetClassDefaultAttributes(*args, **kwargs)
#---------------------------------------------------------------------------
class ComboBox(_core.Control,_core.ItemContainer,_core.TextEntry):
"""
A combobox is like a combination of an edit control and a
listbox. It can be displayed as static list with editable or
read-only text field; or a drop-down list with text field.
A combobox permits a single selection only. Combobox items are
numbered from zero.
"""
thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
def __init__(self, *args, **kwargs):
"""
__init__(Window parent, int id=-1, String value=EmptyString,
Point pos=DefaultPosition, Size size=DefaultSize,
List choices=EmptyList, long style=0, Validator validator=DefaultValidator,
String name=ComboBoxNameStr) -> ComboBox
Constructor, creates and shows a ComboBox control.
"""
_controls_.ComboBox_swiginit(self,_controls_.new_ComboBox(*args, **kwargs))
self._setOORInfo(self)
def Create(*args, **kwargs):
"""
Create(Window parent, int id=-1, String value=EmptyString,
Point pos=DefaultPosition, Size size=DefaultSize,
List choices=EmptyList, long style=0, Validator validator=DefaultValidator,
String name=ChoiceNameStr) -> bool
Actually create the GUI wxComboBox control for 2-phase creation
"""
return _controls_.ComboBox_Create(*args, **kwargs)
def SetMark(*args, **kwargs):
"""
SetMark(self, long from, long to)
Selects the text between the two positions in the combobox text field.
"""
return _controls_.ComboBox_SetMark(*args, **kwargs)
def GetMark(*args, **kwargs):
"""
GetMark(self) -> (from, to)
Gets the positions of the begining and ending of the selection mark in
the combobox text field.
"""
return _controls_.ComboBox_GetMark(*args, **kwargs)
def IsEmpty(*args, **kwargs):
"""IsEmpty(self) -> bool"""
return _controls_.ComboBox_IsEmpty(*args, **kwargs)
def IsListEmpty(*args, **kwargs):
"""IsListEmpty(self) -> bool"""
return _controls_.ComboBox_IsListEmpty(*args, **kwargs)
def IsTextEmpty(*args, **kwargs):
"""IsTextEmpty(self) -> bool"""
return _controls_.ComboBox_IsTextEmpty(*args, **kwargs)
def Popup(*args, **kwargs):
"""Popup(self)"""
return _controls_.ComboBox_Popup(*args, **kwargs)
def Dismiss(*args, **kwargs):
"""Dismiss(self)"""
return _controls_.ComboBox_Dismiss(*args, **kwargs)
def GetCurrentSelection(*args, **kwargs):
"""
GetCurrentSelection(self) -> int
Unlike `GetSelection` which only returns the accepted selection value,
i.e. the selection in the control once the user closes the dropdown
list, this function returns the current selection. That is, while the
dropdown list is shown, it returns the currently selected item in
it. When it is not shown, its result is the same as for the other
function.
"""
return _controls_.ComboBox_GetCurrentSelection(*args, **kwargs)
def SetStringSelection(*args, **kwargs):
"""
SetStringSelection(self, String string) -> bool
Select the item with the specifed string
"""
return _controls_.ComboBox_SetStringSelection(*args, **kwargs)
def GetClassDefaultAttributes(*args, **kwargs):
"""
GetClassDefaultAttributes(int variant=WINDOW_VARIANT_NORMAL) -> VisualAttributes
Get the default attributes for this class. This is useful if you want
to use the same font or colour in your own control as in a standard
control -- which is a much better idea than hard coding specific
colours or fonts which might look completely out of place on the
user's system, especially if it uses themes.
The variant parameter is only relevant under Mac currently and is
ignore under other platforms. Under Mac, it will change the size of
the returned font. See `wx.Window.SetWindowVariant` for more about
this.
"""
return _controls_.ComboBox_GetClassDefaultAttributes(*args, **kwargs)
GetClassDefaultAttributes = staticmethod(GetClassDefaultAttributes)
CurrentSelection = property(GetCurrentSelection)
Mark = property(GetMark,SetMark)
_controls_.ComboBox_swigregister(ComboBox)
ComboBoxNameStr = cvar.ComboBoxNameStr
def PreComboBox(*args, **kwargs):
"""
PreComboBox() -> ComboBox
Precreate a ComboBox control for 2-phase creation.
"""
val = _controls_.new_PreComboBox(*args, **kwargs)
return val
def ComboBox_GetClassDefaultAttributes(*args, **kwargs):
"""
ComboBox_GetClassDefaultAttributes(int variant=WINDOW_VARIANT_NORMAL) -> VisualAttributes
Get the default attributes for this class. This is useful if you want
to use the same font or colour in your own control as in a standard
control -- which is a much better idea than hard coding specific
colours or fonts which might look completely out of place on the
user's system, especially if it uses themes.
The variant parameter is only relevant under Mac currently and is
ignore under other platforms. Under Mac, it will change the size of
the returned font. See `wx.Window.SetWindowVariant` for more about
this.
"""
return _controls_.ComboBox_GetClassDefaultAttributes(*args, **kwargs)
#---------------------------------------------------------------------------
GA_HORIZONTAL = _controls_.GA_HORIZONTAL
GA_VERTICAL = _controls_.GA_VERTICAL
GA_SMOOTH = _controls_.GA_SMOOTH
GA_PROGRESSBAR = 0 # obsolete
class Gauge(_core.Control):
"""Proxy of C++ Gauge class"""
thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
def __init__(self, *args, **kwargs):
"""
__init__(self, Window parent, int id=-1, int range=100, Point pos=DefaultPosition,
Size size=DefaultSize, long style=GA_HORIZONTAL,
Validator validator=DefaultValidator,
String name=GaugeNameStr) -> Gauge
"""
_controls_.Gauge_swiginit(self,_controls_.new_Gauge(*args, **kwargs))
self._setOORInfo(self)
def Create(*args, **kwargs):
"""
Create(self, Window parent, int id=-1, int range=100, Point pos=DefaultPosition,
Size size=DefaultSize, long style=GA_HORIZONTAL,
Validator validator=DefaultValidator,
String name=GaugeNameStr) -> bool
"""
return _controls_.Gauge_Create(*args, **kwargs)
def SetRange(*args, **kwargs):
"""SetRange(self, int range)"""
return _controls_.Gauge_SetRange(*args, **kwargs)
def GetRange(*args, **kwargs):
"""GetRange(self) -> int"""
return _controls_.Gauge_GetRange(*args, **kwargs)
def SetValue(*args, **kwargs):
"""SetValue(self, int pos)"""
return _controls_.Gauge_SetValue(*args, **kwargs)
def GetValue(*args, **kwargs):
"""GetValue(self) -> int"""
return _controls_.Gauge_GetValue(*args, **kwargs)
def Pulse(*args, **kwargs):
"""Pulse(self)"""
return _controls_.Gauge_Pulse(*args, **kwargs)
def IsVertical(*args, **kwargs):
"""IsVertical(self) -> bool"""
return _controls_.Gauge_IsVertical(*args, **kwargs)
def SetShadowWidth(*args, **kwargs):
"""SetShadowWidth(self, int w)"""
return _controls_.Gauge_SetShadowWidth(*args, **kwargs)
def GetShadowWidth(*args, **kwargs):
"""GetShadowWidth(self) -> int"""
return _controls_.Gauge_GetShadowWidth(*args, **kwargs)
def SetBezelFace(*args, **kwargs):
"""SetBezelFace(self, int w)"""
return _controls_.Gauge_SetBezelFace(*args, **kwargs)
def GetBezelFace(*args, **kwargs):
"""GetBezelFace(self) -> int"""
return _controls_.Gauge_GetBezelFace(*args, **kwargs)
def GetClassDefaultAttributes(*args, **kwargs):
"""
GetClassDefaultAttributes(int variant=WINDOW_VARIANT_NORMAL) -> VisualAttributes
Get the default attributes for this class. This is useful if you want
to use the same font or colour in your own control as in a standard
control -- which is a much better idea than hard coding specific
colours or fonts which might look completely out of place on the
user's system, especially if it uses themes.
The variant parameter is only relevant under Mac currently and is
ignore under other platforms. Under Mac, it will change the size of
the returned font. See `wx.Window.SetWindowVariant` for more about
this.
"""
return _controls_.Gauge_GetClassDefaultAttributes(*args, **kwargs)
GetClassDefaultAttributes = staticmethod(GetClassDefaultAttributes)
BezelFace = property(GetBezelFace,SetBezelFace,doc="See `GetBezelFace` and `SetBezelFace`")
Range = property(GetRange,SetRange,doc="See `GetRange` and `SetRange`")
ShadowWidth = property(GetShadowWidth,SetShadowWidth,doc="See `GetShadowWidth` and `SetShadowWidth`")
Value = property(GetValue,SetValue,doc="See `GetValue` and `SetValue`")
_controls_.Gauge_swigregister(Gauge)
GaugeNameStr = cvar.GaugeNameStr
def PreGauge(*args, **kwargs):
"""PreGauge() -> Gauge"""
val = _controls_.new_PreGauge(*args, **kwargs)
return val
def Gauge_GetClassDefaultAttributes(*args, **kwargs):
"""
Gauge_GetClassDefaultAttributes(int variant=WINDOW_VARIANT_NORMAL) -> VisualAttributes
Get the default attributes for this class. This is useful if you want
to use the same font or colour in your own control as in a standard
control -- which is a much better idea than hard coding specific
colours or fonts which might look completely out of place on the
user's system, especially if it uses themes.
The variant parameter is only relevant under Mac currently and is
ignore under other platforms. Under Mac, it will change the size of
the returned font. See `wx.Window.SetWindowVariant` for more about
this.
"""
return _controls_.Gauge_GetClassDefaultAttributes(*args, **kwargs)
#---------------------------------------------------------------------------
class StaticBox(_core.Control):
"""Proxy of C++ StaticBox class"""
thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
def __init__(self, *args, **kwargs):
"""
__init__(self, Window parent, int id=-1, String label=EmptyString,
Point pos=DefaultPosition, Size size=DefaultSize,
long style=0, String name=StaticBoxNameStr) -> StaticBox
"""
_controls_.StaticBox_swiginit(self,_controls_.new_StaticBox(*args, **kwargs))
self._setOORInfo(self)
def Create(*args, **kwargs):
"""
Create(self, Window parent, int id=-1, String label=EmptyString,
Point pos=DefaultPosition, Size size=DefaultSize,
long style=0, String name=StaticBoxNameStr) -> bool
"""
return _controls_.StaticBox_Create(*args, **kwargs)
def GetClassDefaultAttributes(*args, **kwargs):
"""
GetClassDefaultAttributes(int variant=WINDOW_VARIANT_NORMAL) -> VisualAttributes
Get the default attributes for this class. This is useful if you want
to use the same font or colour in your own control as in a standard
control -- which is a much better idea than hard coding specific
colours or fonts which might look completely out of place on the
user's system, especially if it uses themes.
The variant parameter is only relevant under Mac currently and is
ignore under other platforms. Under Mac, it will change the size of
the returned font. See `wx.Window.SetWindowVariant` for more about
this.
"""
return _controls_.StaticBox_GetClassDefaultAttributes(*args, **kwargs)
GetClassDefaultAttributes = staticmethod(GetClassDefaultAttributes)
_controls_.StaticBox_swigregister(StaticBox)
StaticBitmapNameStr = cvar.StaticBitmapNameStr
StaticBoxNameStr = cvar.StaticBoxNameStr
StaticTextNameStr = cvar.StaticTextNameStr
StaticLineNameStr = cvar.StaticLineNameStr
def PreStaticBox(*args, **kwargs):
"""PreStaticBox() -> StaticBox"""
val = _controls_.new_PreStaticBox(*args, **kwargs)
return val
def StaticBox_GetClassDefaultAttributes(*args, **kwargs):
"""
StaticBox_GetClassDefaultAttributes(int variant=WINDOW_VARIANT_NORMAL) -> VisualAttributes
Get the default attributes for this class. This is useful if you want
to use the same font or colour in your own control as in a standard
control -- which is a much better idea than hard coding specific
colours or fonts which might look completely out of place on the
user's system, especially if it uses themes.
The variant parameter is only relevant under Mac currently and is
ignore under other platforms. Under Mac, it will change the size of
the returned font. See `wx.Window.SetWindowVariant` for more about
this.
"""
return _controls_.StaticBox_GetClassDefaultAttributes(*args, **kwargs)
#---------------------------------------------------------------------------
class StaticLine(_core.Control):
"""Proxy of C++ StaticLine class"""
thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
def __init__(self, *args, **kwargs):
"""
__init__(self, Window parent, int id=-1, Point pos=DefaultPosition,
Size size=DefaultSize, long style=LI_HORIZONTAL,
String name=StaticLineNameStr) -> StaticLine
"""
_controls_.StaticLine_swiginit(self,_controls_.new_StaticLine(*args, **kwargs))
self._setOORInfo(self)
def Create(*args, **kwargs):
"""
Create(self, Window parent, int id=-1, Point pos=DefaultPosition,
Size size=DefaultSize, long style=LI_HORIZONTAL,
String name=StaticLineNameStr) -> bool
"""
return _controls_.StaticLine_Create(*args, **kwargs)
def IsVertical(*args, **kwargs):
"""IsVertical(self) -> bool"""
return _controls_.StaticLine_IsVertical(*args, **kwargs)
def GetDefaultSize(*args, **kwargs):
"""GetDefaultSize() -> int"""
return _controls_.StaticLine_GetDefaultSize(*args, **kwargs)
GetDefaultSize = staticmethod(GetDefaultSize)
def GetClassDefaultAttributes(*args, **kwargs):
"""
GetClassDefaultAttributes(int variant=WINDOW_VARIANT_NORMAL) -> VisualAttributes
Get the default attributes for this class. This is useful if you want
to use the same font or colour in your own control as in a standard
control -- which is a much better idea than hard coding specific
colours or fonts which might look completely out of place on the
user's system, especially if it uses themes.
The variant parameter is only relevant under Mac currently and is
ignore under other platforms. Under Mac, it will change the size of
the returned font. See `wx.Window.SetWindowVariant` for more about
this.
"""
return _controls_.StaticLine_GetClassDefaultAttributes(*args, **kwargs)
GetClassDefaultAttributes = staticmethod(GetClassDefaultAttributes)
_controls_.StaticLine_swigregister(StaticLine)
def PreStaticLine(*args, **kwargs):
"""PreStaticLine() -> StaticLine"""
val = _controls_.new_PreStaticLine(*args, **kwargs)
return val
def StaticLine_GetDefaultSize(*args):
"""StaticLine_GetDefaultSize() -> int"""
return _controls_.StaticLine_GetDefaultSize(*args)
def StaticLine_GetClassDefaultAttributes(*args, **kwargs):
"""
StaticLine_GetClassDefaultAttributes(int variant=WINDOW_VARIANT_NORMAL) -> VisualAttributes
Get the default attributes for this class. This is useful if you want
to use the same font or colour in your own control as in a standard
control -- which is a much better idea than hard coding specific
colours or fonts which might look completely out of place on the
user's system, especially if it uses themes.
The variant parameter is only relevant under Mac currently and is
ignore under other platforms. Under Mac, it will change the size of
the returned font. See `wx.Window.SetWindowVariant` for more about
this.
"""
return _controls_.StaticLine_GetClassDefaultAttributes(*args, **kwargs)
#---------------------------------------------------------------------------
ST_NO_AUTORESIZE = _controls_.ST_NO_AUTORESIZE
ST_ELLIPSIZE_START = _controls_.ST_ELLIPSIZE_START
ST_ELLIPSIZE_MIDDLE = _controls_.ST_ELLIPSIZE_MIDDLE
ST_ELLIPSIZE_END = _controls_.ST_ELLIPSIZE_END
class StaticText(_core.Control):
"""Proxy of C++ StaticText class"""
thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
def __init__(self, *args, **kwargs):
"""
__init__(self, Window parent, int id=-1, String label=EmptyString,
Point pos=DefaultPosition, Size size=DefaultSize,
long style=0, String name=StaticTextNameStr) -> StaticText
"""
_controls_.StaticText_swiginit(self,_controls_.new_StaticText(*args, **kwargs))
self._setOORInfo(self)
def Create(*args, **kwargs):
"""
Create(self, Window parent, int id=-1, String label=EmptyString,
Point pos=DefaultPosition, Size size=DefaultSize,
long style=0, String name=StaticTextNameStr) -> bool
"""
return _controls_.StaticText_Create(*args, **kwargs)
def Wrap(*args, **kwargs):
"""
Wrap(self, int width)
This functions wraps the control's label so that each of its lines
becomes at most ``width`` pixels wide if possible (the lines are
broken at words boundaries so it might not be the case if words are
too long). If ``width`` is negative, no wrapping is done.
"""
return _controls_.StaticText_Wrap(*args, **kwargs)
def IsEllipsized(*args, **kwargs):
"""IsEllipsized(self) -> bool"""
return _controls_.StaticText_IsEllipsized(*args, **kwargs)
def GetClassDefaultAttributes(*args, **kwargs):
"""
GetClassDefaultAttributes(int variant=WINDOW_VARIANT_NORMAL) -> VisualAttributes
Get the default attributes for this class. This is useful if you want
to use the same font or colour in your own control as in a standard
control -- which is a much better idea than hard coding specific
colours or fonts which might look completely out of place on the
user's system, especially if it uses themes.
The variant parameter is only relevant under Mac currently and is
ignore under other platforms. Under Mac, it will change the size of
the returned font. See `wx.Window.SetWindowVariant` for more about
this.
"""
return _controls_.StaticText_GetClassDefaultAttributes(*args, **kwargs)
GetClassDefaultAttributes = staticmethod(GetClassDefaultAttributes)
_controls_.StaticText_swigregister(StaticText)
def PreStaticText(*args, **kwargs):
"""PreStaticText() -> StaticText"""
val = _controls_.new_PreStaticText(*args, **kwargs)
return val
def StaticText_GetClassDefaultAttributes(*args, **kwargs):
"""
StaticText_GetClassDefaultAttributes(int variant=WINDOW_VARIANT_NORMAL) -> VisualAttributes
Get the default attributes for this class. This is useful if you want
to use the same font or colour in your own control as in a standard
control -- which is a much better idea than hard coding specific
colours or fonts which might look completely out of place on the
user's system, especially if it uses themes.
The variant parameter is only relevant under Mac currently and is
ignore under other platforms. Under Mac, it will change the size of
the returned font. See `wx.Window.SetWindowVariant` for more about
this.
"""
return _controls_.StaticText_GetClassDefaultAttributes(*args, **kwargs)
#---------------------------------------------------------------------------
class StaticBitmap(_core.Control):
"""Proxy of C++ StaticBitmap class"""
thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
def __init__(self, *args, **kwargs):
"""
__init__(self, Window parent, int id=-1, Bitmap bitmap=wxNullBitmap,
Point pos=DefaultPosition, Size size=DefaultSize,
long style=0, String name=StaticBitmapNameStr) -> StaticBitmap
"""
_controls_.StaticBitmap_swiginit(self,_controls_.new_StaticBitmap(*args, **kwargs))
self._setOORInfo(self)
def Create(*args, **kwargs):
"""
Create(self, Window parent, int id=-1, Bitmap bitmap=wxNullBitmap,
Point pos=DefaultPosition, Size size=DefaultSize,
long style=0, String name=StaticBitmapNameStr) -> bool
"""
return _controls_.StaticBitmap_Create(*args, **kwargs)
def GetBitmap(*args, **kwargs):
"""GetBitmap(self) -> Bitmap"""
return _controls_.StaticBitmap_GetBitmap(*args, **kwargs)
def SetBitmap(*args, **kwargs):
"""SetBitmap(self, Bitmap bitmap)"""
return _controls_.StaticBitmap_SetBitmap(*args, **kwargs)
def SetIcon(*args, **kwargs):
"""SetIcon(self, Icon icon)"""
return _controls_.StaticBitmap_SetIcon(*args, **kwargs)
def GetClassDefaultAttributes(*args, **kwargs):
"""
GetClassDefaultAttributes(int variant=WINDOW_VARIANT_NORMAL) -> VisualAttributes
Get the default attributes for this class. This is useful if you want
to use the same font or colour in your own control as in a standard
control -- which is a much better idea than hard coding specific
colours or fonts which might look completely out of place on the
user's system, especially if it uses themes.
The variant parameter is only relevant under Mac currently and is
ignore under other platforms. Under Mac, it will change the size of
the returned font. See `wx.Window.SetWindowVariant` for more about
this.
"""
return _controls_.StaticBitmap_GetClassDefaultAttributes(*args, **kwargs)
GetClassDefaultAttributes = staticmethod(GetClassDefaultAttributes)
_controls_.StaticBitmap_swigregister(StaticBitmap)
def PreStaticBitmap(*args, **kwargs):
"""PreStaticBitmap() -> StaticBitmap"""
val = _controls_.new_PreStaticBitmap(*args, **kwargs)
return val
def StaticBitmap_GetClassDefaultAttributes(*args, **kwargs):
"""
StaticBitmap_GetClassDefaultAttributes(int variant=WINDOW_VARIANT_NORMAL) -> VisualAttributes
Get the default attributes for this class. This is useful if you want
to use the same font or colour in your own control as in a standard
control -- which is a much better idea than hard coding specific
colours or fonts which might look completely out of place on the
user's system, especially if it uses themes.
The variant parameter is only relevant under Mac currently and is
ignore under other platforms. Under Mac, it will change the size of
the returned font. See `wx.Window.SetWindowVariant` for more about
this.
"""
return _controls_.StaticBitmap_GetClassDefaultAttributes(*args, **kwargs)
#---------------------------------------------------------------------------
class ListBox(_core.ControlWithItems):
"""Proxy of C++ ListBox class"""
thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
def __init__(self, *args, **kwargs):
"""
__init__(self, Window parent, int id=-1, Point pos=DefaultPosition,
Size size=DefaultSize, wxArrayString choices=wxPyEmptyStringArray,
long style=0, Validator validator=DefaultValidator,
String name=ListBoxNameStr) -> ListBox
"""
_controls_.ListBox_swiginit(self,_controls_.new_ListBox(*args, **kwargs))
self._setOORInfo(self)
def Create(*args, **kwargs):
"""
Create(self, Window parent, int id=-1, Point pos=DefaultPosition,
Size size=DefaultSize, wxArrayString choices=wxPyEmptyStringArray,
long style=0, Validator validator=DefaultValidator,
String name=ListBoxNameStr) -> bool
"""
return _controls_.ListBox_Create(*args, **kwargs)
def Insert(*args, **kwargs):
"""
Insert(self, String item, int pos, PyObject clientData=None)
Insert an item into the control before the item at the ``pos`` index,
optionally associating some data object with the item.
"""
return _controls_.ListBox_Insert(*args, **kwargs)
def InsertItems(*args, **kwargs):
"""InsertItems(self, wxArrayString items, unsigned int pos)"""
return _controls_.ListBox_InsertItems(*args, **kwargs)
def Set(*args, **kwargs):
"""
Set(self, List strings)
Replace all the items in the control
"""
return _controls_.ListBox_Set(*args, **kwargs)
def IsSelected(*args, **kwargs):
"""IsSelected(self, int n) -> bool"""
return _controls_.ListBox_IsSelected(*args, **kwargs)
def SetSelection(*args, **kwargs):
"""SetSelection(self, int n, bool select=True)"""
return _controls_.ListBox_SetSelection(*args, **kwargs)
def Select(*args, **kwargs):
"""
Select(self, int n)
This is the same as `SetSelection` and exists only because it is
slightly more natural for controls which support multiple selection.
"""
return _controls_.ListBox_Select(*args, **kwargs)
def Deselect(*args, **kwargs):
"""Deselect(self, int n)"""
return _controls_.ListBox_Deselect(*args, **kwargs)
def DeselectAll(*args, **kwargs):
"""DeselectAll(self, int itemToLeaveSelected=-1)"""
return _controls_.ListBox_DeselectAll(*args, **kwargs)
def SetStringSelection(*args, **kwargs):
"""SetStringSelection(self, String s, bool select=True) -> bool"""
return _controls_.ListBox_SetStringSelection(*args, **kwargs)
def GetSelections(*args, **kwargs):
"""GetSelections(self) -> PyObject"""
return _controls_.ListBox_GetSelections(*args, **kwargs)
def SetFirstItem(*args, **kwargs):
"""SetFirstItem(self, int n)"""
return _controls_.ListBox_SetFirstItem(*args, **kwargs)
def SetFirstItemStr(*args, **kwargs):
"""SetFirstItemStr(self, String s)"""
return _controls_.ListBox_SetFirstItemStr(*args, **kwargs)
def EnsureVisible(*args, **kwargs):
"""EnsureVisible(self, int n)"""
return _controls_.ListBox_EnsureVisible(*args, **kwargs)
def AppendAndEnsureVisible(*args, **kwargs):
"""AppendAndEnsureVisible(self, String s)"""
return _controls_.ListBox_AppendAndEnsureVisible(*args, **kwargs)
def HitTest(*args, **kwargs):
"""
HitTest(self, Point pt) -> int
Test where the given (in client coords) point lies
"""
return _controls_.ListBox_HitTest(*args, **kwargs)
def SetItemForegroundColour(*args, **kwargs):
"""SetItemForegroundColour(self, int item, Colour c)"""
return _controls_.ListBox_SetItemForegroundColour(*args, **kwargs)
def SetItemBackgroundColour(*args, **kwargs):
"""SetItemBackgroundColour(self, int item, Colour c)"""
return _controls_.ListBox_SetItemBackgroundColour(*args, **kwargs)
def SetItemFont(*args, **kwargs):
"""SetItemFont(self, int item, Font f)"""
return _controls_.ListBox_SetItemFont(*args, **kwargs)
def GetClassDefaultAttributes(*args, **kwargs):
"""
GetClassDefaultAttributes(int variant=WINDOW_VARIANT_NORMAL) -> VisualAttributes
Get the default attributes for this class. This is useful if you want
to use the same font or colour in your own control as in a standard
control -- which is a much better idea than hard coding specific
colours or fonts which might look completely out of place on the
user's system, especially if it uses themes.
The variant parameter is only relevant under Mac currently and is
ignore under other platforms. Under Mac, it will change the size of
the returned font. See `wx.Window.SetWindowVariant` for more about
this.
"""
return _controls_.ListBox_GetClassDefaultAttributes(*args, **kwargs)
GetClassDefaultAttributes = staticmethod(GetClassDefaultAttributes)
Selections = property(GetSelections,doc="See `GetSelections`")
_controls_.ListBox_swigregister(ListBox)
ListBoxNameStr = cvar.ListBoxNameStr
def PreListBox(*args, **kwargs):
"""PreListBox() -> ListBox"""
val = _controls_.new_PreListBox(*args, **kwargs)
return val
def ListBox_GetClassDefaultAttributes(*args, **kwargs):
"""
ListBox_GetClassDefaultAttributes(int variant=WINDOW_VARIANT_NORMAL) -> VisualAttributes
Get the default attributes for this class. This is useful if you want
to use the same font or colour in your own control as in a standard
control -- which is a much better idea than hard coding specific
colours or fonts which might look completely out of place on the
user's system, especially if it uses themes.
The variant parameter is only relevant under Mac currently and is
ignore under other platforms. Under Mac, it will change the size of
the returned font. See `wx.Window.SetWindowVariant` for more about
this.
"""
return _controls_.ListBox_GetClassDefaultAttributes(*args, **kwargs)
#---------------------------------------------------------------------------
class CheckListBox(ListBox):
"""Proxy of C++ CheckListBox class"""
thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
def __init__(self, *args, **kwargs):
"""
__init__(self, Window parent, int id=-1, Point pos=DefaultPosition,
Size size=DefaultSize, wxArrayString choices=wxPyEmptyStringArray,
long style=0, Validator validator=DefaultValidator,
String name=ListBoxNameStr) -> CheckListBox
"""
_controls_.CheckListBox_swiginit(self,_controls_.new_CheckListBox(*args, **kwargs))
self._setOORInfo(self)
def Create(*args, **kwargs):
"""
Create(self, Window parent, int id=-1, Point pos=DefaultPosition,
Size size=DefaultSize, wxArrayString choices=wxPyEmptyStringArray,
long style=0, Validator validator=DefaultValidator,
String name=ListBoxNameStr) -> bool
"""
return _controls_.CheckListBox_Create(*args, **kwargs)
def IsChecked(*args, **kwargs):
"""IsChecked(self, unsigned int index) -> bool"""
return _controls_.CheckListBox_IsChecked(*args, **kwargs)
def Check(*args, **kwargs):
"""Check(self, unsigned int index, int check=True)"""
return _controls_.CheckListBox_Check(*args, **kwargs)
def GetChecked(self):
"""
GetChecked(self)
Return a tuple of integers corresponding to the checked items in
the control, based on `IsChecked`.
"""
return tuple([i for i in range(self.Count) if self.IsChecked(i)])
def GetCheckedStrings(self):
"""
GetCheckedStrings(self)
Return a tuple of strings corresponding to the checked
items of the control, based on `GetChecked`.
"""
return tuple([self.GetString(i) for i in self.GetChecked()])
def SetChecked(self, indexes):
"""
SetChecked(self, indexes)
Sets the checked state of items if the index of the item is
found in the indexes sequence.
"""
for i in indexes:
assert 0 <= i < self.Count, "Index (%s) out of range" % i
for i in range(self.Count):
self.Check(i, i in indexes)
def SetCheckedStrings(self, strings):
"""
SetCheckedStrings(self, indexes)
Sets the checked state of items if the item's string is found
in the strings sequence.
"""
for s in strings:
assert s in self.GetStrings(), "String ('%s') not found" % s
for i in range(self.Count):
self.Check(i, self.GetString(i) in strings)
Checked = property(GetChecked,SetChecked)
CheckedStrings = property(GetCheckedStrings,SetCheckedStrings)
_controls_.CheckListBox_swigregister(CheckListBox)
def PreCheckListBox(*args, **kwargs):
"""PreCheckListBox() -> CheckListBox"""
val = _controls_.new_PreCheckListBox(*args, **kwargs)
return val
#---------------------------------------------------------------------------
TE_NO_VSCROLL = _controls_.TE_NO_VSCROLL
TE_AUTO_SCROLL = _controls_.TE_AUTO_SCROLL
TE_READONLY = _controls_.TE_READONLY
TE_MULTILINE = _controls_.TE_MULTILINE
TE_PROCESS_TAB = _controls_.TE_PROCESS_TAB
TE_LEFT = _controls_.TE_LEFT
TE_CENTER = _controls_.TE_CENTER
TE_RIGHT = _controls_.TE_RIGHT
TE_CENTRE = _controls_.TE_CENTRE
TE_RICH = _controls_.TE_RICH
TE_PROCESS_ENTER = _controls_.TE_PROCESS_ENTER
TE_PASSWORD = _controls_.TE_PASSWORD
TE_AUTO_URL = _controls_.TE_AUTO_URL
TE_NOHIDESEL = _controls_.TE_NOHIDESEL
TE_DONTWRAP = _controls_.TE_DONTWRAP
TE_CHARWRAP = _controls_.TE_CHARWRAP
TE_WORDWRAP = _controls_.TE_WORDWRAP
TE_BESTWRAP = _controls_.TE_BESTWRAP
TE_RICH2 = _controls_.TE_RICH2
TE_CAPITALIZE = _controls_.TE_CAPITALIZE
TE_LINEWRAP = TE_CHARWRAP
PROCESS_ENTER = TE_PROCESS_ENTER
PASSWORD = TE_PASSWORD
TEXT_ALIGNMENT_DEFAULT = _controls_.TEXT_ALIGNMENT_DEFAULT
TEXT_ALIGNMENT_LEFT = _controls_.TEXT_ALIGNMENT_LEFT
TEXT_ALIGNMENT_CENTRE = _controls_.TEXT_ALIGNMENT_CENTRE
TEXT_ALIGNMENT_CENTER = _controls_.TEXT_ALIGNMENT_CENTER
TEXT_ALIGNMENT_RIGHT = _controls_.TEXT_ALIGNMENT_RIGHT
TEXT_ALIGNMENT_JUSTIFIED = _controls_.TEXT_ALIGNMENT_JUSTIFIED
TEXT_ATTR_TEXT_COLOUR = _controls_.TEXT_ATTR_TEXT_COLOUR
TEXT_ATTR_BACKGROUND_COLOUR = _controls_.TEXT_ATTR_BACKGROUND_COLOUR
TEXT_ATTR_FONT_FACE = _controls_.TEXT_ATTR_FONT_FACE
TEXT_ATTR_FONT_SIZE = _controls_.TEXT_ATTR_FONT_SIZE
TEXT_ATTR_FONT_WEIGHT = _controls_.TEXT_ATTR_FONT_WEIGHT
TEXT_ATTR_FONT_ITALIC = _controls_.TEXT_ATTR_FONT_ITALIC
TEXT_ATTR_FONT_UNDERLINE = _controls_.TEXT_ATTR_FONT_UNDERLINE
TEXT_ATTR_FONT_STRIKETHROUGH = _controls_.TEXT_ATTR_FONT_STRIKETHROUGH
TEXT_ATTR_FONT_ENCODING = _controls_.TEXT_ATTR_FONT_ENCODING
TEXT_ATTR_FONT_FAMILY = _controls_.TEXT_ATTR_FONT_FAMILY
TEXT_ATTR_FONT = _controls_.TEXT_ATTR_FONT
TEXT_ATTR_ALIGNMENT = _controls_.TEXT_ATTR_ALIGNMENT
TEXT_ATTR_LEFT_INDENT = _controls_.TEXT_ATTR_LEFT_INDENT
TEXT_ATTR_RIGHT_INDENT = _controls_.TEXT_ATTR_RIGHT_INDENT
TEXT_ATTR_TABS = _controls_.TEXT_ATTR_TABS
TEXT_ATTR_PARA_SPACING_AFTER = _controls_.TEXT_ATTR_PARA_SPACING_AFTER
TEXT_ATTR_LINE_SPACING = _controls_.TEXT_ATTR_LINE_SPACING
TEXT_ATTR_CHARACTER_STYLE_NAME = _controls_.TEXT_ATTR_CHARACTER_STYLE_NAME
TEXT_ATTR_PARAGRAPH_STYLE_NAME = _controls_.TEXT_ATTR_PARAGRAPH_STYLE_NAME
TEXT_ATTR_LIST_STYLE_NAME = _controls_.TEXT_ATTR_LIST_STYLE_NAME
TEXT_ATTR_BULLET_STYLE = _controls_.TEXT_ATTR_BULLET_STYLE
TEXT_ATTR_BULLET_NUMBER = _controls_.TEXT_ATTR_BULLET_NUMBER
TEXT_ATTR_BULLET_TEXT = _controls_.TEXT_ATTR_BULLET_TEXT
TEXT_ATTR_BULLET_NAME = _controls_.TEXT_ATTR_BULLET_NAME
TEXT_ATTR_BULLET = _controls_.TEXT_ATTR_BULLET
TEXT_ATTR_URL = _controls_.TEXT_ATTR_URL
TEXT_ATTR_PAGE_BREAK = _controls_.TEXT_ATTR_PAGE_BREAK
TEXT_ATTR_EFFECTS = _controls_.TEXT_ATTR_EFFECTS
TEXT_ATTR_OUTLINE_LEVEL = _controls_.TEXT_ATTR_OUTLINE_LEVEL
TEXT_ATTR_CHARACTER = _controls_.TEXT_ATTR_CHARACTER
TEXT_ATTR_PARAGRAPH = _controls_.TEXT_ATTR_PARAGRAPH
TEXT_ATTR_ALL = _controls_.TEXT_ATTR_ALL
TEXT_ATTR_BULLET_STYLE_NONE = _controls_.TEXT_ATTR_BULLET_STYLE_NONE
TEXT_ATTR_BULLET_STYLE_ARABIC = _controls_.TEXT_ATTR_BULLET_STYLE_ARABIC
TEXT_ATTR_BULLET_STYLE_LETTERS_UPPER = _controls_.TEXT_ATTR_BULLET_STYLE_LETTERS_UPPER
TEXT_ATTR_BULLET_STYLE_LETTERS_LOWER = _controls_.TEXT_ATTR_BULLET_STYLE_LETTERS_LOWER
TEXT_ATTR_BULLET_STYLE_ROMAN_UPPER = _controls_.TEXT_ATTR_BULLET_STYLE_ROMAN_UPPER
TEXT_ATTR_BULLET_STYLE_ROMAN_LOWER = _controls_.TEXT_ATTR_BULLET_STYLE_ROMAN_LOWER
TEXT_ATTR_BULLET_STYLE_SYMBOL = _controls_.TEXT_ATTR_BULLET_STYLE_SYMBOL
TEXT_ATTR_BULLET_STYLE_BITMAP = _controls_.TEXT_ATTR_BULLET_STYLE_BITMAP
TEXT_ATTR_BULLET_STYLE_PARENTHESES = _controls_.TEXT_ATTR_BULLET_STYLE_PARENTHESES
TEXT_ATTR_BULLET_STYLE_PERIOD = _controls_.TEXT_ATTR_BULLET_STYLE_PERIOD
TEXT_ATTR_BULLET_STYLE_STANDARD = _controls_.TEXT_ATTR_BULLET_STYLE_STANDARD
TEXT_ATTR_BULLET_STYLE_RIGHT_PARENTHESIS = _controls_.TEXT_ATTR_BULLET_STYLE_RIGHT_PARENTHESIS
TEXT_ATTR_BULLET_STYLE_OUTLINE = _controls_.TEXT_ATTR_BULLET_STYLE_OUTLINE
TEXT_ATTR_BULLET_STYLE_ALIGN_LEFT = _controls_.TEXT_ATTR_BULLET_STYLE_ALIGN_LEFT
TEXT_ATTR_BULLET_STYLE_ALIGN_RIGHT = _controls_.TEXT_ATTR_BULLET_STYLE_ALIGN_RIGHT
TEXT_ATTR_BULLET_STYLE_ALIGN_CENTRE = _controls_.TEXT_ATTR_BULLET_STYLE_ALIGN_CENTRE
TEXT_ATTR_EFFECT_NONE = _controls_.TEXT_ATTR_EFFECT_NONE
TEXT_ATTR_EFFECT_CAPITALS = _controls_.TEXT_ATTR_EFFECT_CAPITALS
TEXT_ATTR_EFFECT_SMALL_CAPITALS = _controls_.TEXT_ATTR_EFFECT_SMALL_CAPITALS
TEXT_ATTR_EFFECT_STRIKETHROUGH = _controls_.TEXT_ATTR_EFFECT_STRIKETHROUGH
TEXT_ATTR_EFFECT_DOUBLE_STRIKETHROUGH = _controls_.TEXT_ATTR_EFFECT_DOUBLE_STRIKETHROUGH
TEXT_ATTR_EFFECT_SHADOW = _controls_.TEXT_ATTR_EFFECT_SHADOW
TEXT_ATTR_EFFECT_EMBOSS = _controls_.TEXT_ATTR_EFFECT_EMBOSS
TEXT_ATTR_EFFECT_OUTLINE = _controls_.TEXT_ATTR_EFFECT_OUTLINE
TEXT_ATTR_EFFECT_ENGRAVE = _controls_.TEXT_ATTR_EFFECT_ENGRAVE
TEXT_ATTR_EFFECT_SUPERSCRIPT = _controls_.TEXT_ATTR_EFFECT_SUPERSCRIPT
TEXT_ATTR_EFFECT_SUBSCRIPT = _controls_.TEXT_ATTR_EFFECT_SUBSCRIPT
TEXT_ATTR_LINE_SPACING_NORMAL = _controls_.TEXT_ATTR_LINE_SPACING_NORMAL
TEXT_ATTR_LINE_SPACING_HALF = _controls_.TEXT_ATTR_LINE_SPACING_HALF
TEXT_ATTR_LINE_SPACING_TWICE = _controls_.TEXT_ATTR_LINE_SPACING_TWICE
OutOfRangeTextCoord = _controls_.OutOfRangeTextCoord
InvalidTextCoord = _controls_.InvalidTextCoord
TEXT_TYPE_ANY = _controls_.TEXT_TYPE_ANY
class TextAttr(object):
"""Proxy of C++ TextAttr class"""
thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
def __init__(self, *args, **kwargs):
"""
__init__(self, Colour colText=wxNullColour, Colour colBack=wxNullColour,
Font font=wxNullFont, int alignment=TEXT_ALIGNMENT_DEFAULT) -> TextAttr
"""
_controls_.TextAttr_swiginit(self,_controls_.new_TextAttr(*args, **kwargs))
__swig_destroy__ = _controls_.delete_TextAttr
__del__ = lambda self : None;
def Init(*args, **kwargs):
"""Init(self)"""
return _controls_.TextAttr_Init(*args, **kwargs)
def Copy(*args, **kwargs):
"""Copy(self, TextAttr attr)"""
return _controls_.TextAttr_Copy(*args, **kwargs)
def EqPartial(*args, **kwargs):
"""EqPartial(self, TextAttr attr) -> bool"""
return _controls_.TextAttr_EqPartial(*args, **kwargs)
def GetFontAttributes(*args, **kwargs):
"""GetFontAttributes(self, Font font, int flags=TEXT_ATTR_FONT) -> bool"""
return _controls_.TextAttr_GetFontAttributes(*args, **kwargs)
def SetTextColour(*args, **kwargs):
"""SetTextColour(self, Colour colText)"""
return _controls_.TextAttr_SetTextColour(*args, **kwargs)
def SetBackgroundColour(*args, **kwargs):
"""SetBackgroundColour(self, Colour colBack)"""
return _controls_.TextAttr_SetBackgroundColour(*args, **kwargs)
def SetAlignment(*args, **kwargs):
"""SetAlignment(self, int alignment)"""
return _controls_.TextAttr_SetAlignment(*args, **kwargs)
def SetTabs(*args, **kwargs):
"""SetTabs(self, wxArrayInt tabs)"""
return _controls_.TextAttr_SetTabs(*args, **kwargs)
def SetLeftIndent(*args, **kwargs):
"""SetLeftIndent(self, int indent, int subIndent=0)"""
return _controls_.TextAttr_SetLeftIndent(*args, **kwargs)
def SetRightIndent(*args, **kwargs):
"""SetRightIndent(self, int indent)"""
return _controls_.TextAttr_SetRightIndent(*args, **kwargs)
def SetFontSize(*args, **kwargs):
"""SetFontSize(self, int pointSize)"""
return _controls_.TextAttr_SetFontSize(*args, **kwargs)
def SetFontStyle(*args, **kwargs):
"""SetFontStyle(self, int fontStyle)"""
return _controls_.TextAttr_SetFontStyle(*args, **kwargs)
def SetFontWeight(*args, **kwargs):
"""SetFontWeight(self, int fontWeight)"""
return _controls_.TextAttr_SetFontWeight(*args, **kwargs)
def SetFontFaceName(*args, **kwargs):
"""SetFontFaceName(self, String faceName)"""
return _controls_.TextAttr_SetFontFaceName(*args, **kwargs)
def SetFontUnderlined(*args, **kwargs):
"""SetFontUnderlined(self, bool underlined)"""
return _controls_.TextAttr_SetFontUnderlined(*args, **kwargs)
def SetFontStrikethrough(*args, **kwargs):
"""SetFontStrikethrough(self, bool strikethrough)"""
return _controls_.TextAttr_SetFontStrikethrough(*args, **kwargs)
def SetFontEncoding(*args, **kwargs):
"""SetFontEncoding(self, int encoding)"""
return _controls_.TextAttr_SetFontEncoding(*args, **kwargs)
def SetFontFamily(*args, **kwargs):
"""SetFontFamily(self, int family)"""
return _controls_.TextAttr_SetFontFamily(*args, **kwargs)
def SetFont(*args, **kwargs):
"""SetFont(self, Font font, int flags=TEXT_ATTR_FONT)"""
return _controls_.TextAttr_SetFont(*args, **kwargs)
def SetFlags(*args, **kwargs):
"""SetFlags(self, long flags)"""
return _controls_.TextAttr_SetFlags(*args, **kwargs)
def SetCharacterStyleName(*args, **kwargs):
"""SetCharacterStyleName(self, String name)"""
return _controls_.TextAttr_SetCharacterStyleName(*args, **kwargs)
def SetParagraphStyleName(*args, **kwargs):
"""SetParagraphStyleName(self, String name)"""
return _controls_.TextAttr_SetParagraphStyleName(*args, **kwargs)
def SetListStyleName(*args, **kwargs):
"""SetListStyleName(self, String name)"""
return _controls_.TextAttr_SetListStyleName(*args, **kwargs)
def SetParagraphSpacingAfter(*args, **kwargs):
"""SetParagraphSpacingAfter(self, int spacing)"""
return _controls_.TextAttr_SetParagraphSpacingAfter(*args, **kwargs)
def SetParagraphSpacingBefore(*args, **kwargs):
"""SetParagraphSpacingBefore(self, int spacing)"""
return _controls_.TextAttr_SetParagraphSpacingBefore(*args, **kwargs)
def SetLineSpacing(*args, **kwargs):
"""SetLineSpacing(self, int spacing)"""
return _controls_.TextAttr_SetLineSpacing(*args, **kwargs)
def SetBulletStyle(*args, **kwargs):
"""SetBulletStyle(self, int style)"""
return _controls_.TextAttr_SetBulletStyle(*args, **kwargs)
def SetBulletNumber(*args, **kwargs):
"""SetBulletNumber(self, int n)"""
return _controls_.TextAttr_SetBulletNumber(*args, **kwargs)
def SetBulletText(*args, **kwargs):
"""SetBulletText(self, String text)"""
return _controls_.TextAttr_SetBulletText(*args, **kwargs)
def SetBulletFont(*args, **kwargs):
"""SetBulletFont(self, String bulletFont)"""
return _controls_.TextAttr_SetBulletFont(*args, **kwargs)
def SetBulletName(*args, **kwargs):
"""SetBulletName(self, String name)"""
return _controls_.TextAttr_SetBulletName(*args, **kwargs)
def SetURL(*args, **kwargs):
"""SetURL(self, String url)"""
return _controls_.TextAttr_SetURL(*args, **kwargs)
def SetPageBreak(*args, **kwargs):
"""SetPageBreak(self, bool pageBreak=True)"""
return _controls_.TextAttr_SetPageBreak(*args, **kwargs)
def SetTextEffects(*args, **kwargs):
"""SetTextEffects(self, int effects)"""
return _controls_.TextAttr_SetTextEffects(*args, **kwargs)
def SetTextEffectFlags(*args, **kwargs):
"""SetTextEffectFlags(self, int effects)"""
return _controls_.TextAttr_SetTextEffectFlags(*args, **kwargs)
def SetOutlineLevel(*args, **kwargs):
"""SetOutlineLevel(self, int level)"""
return _controls_.TextAttr_SetOutlineLevel(*args, **kwargs)
def GetTextColour(*args, **kwargs):
"""GetTextColour(self) -> Colour"""
return _controls_.TextAttr_GetTextColour(*args, **kwargs)
def GetBackgroundColour(*args, **kwargs):
"""GetBackgroundColour(self) -> Colour"""
return _controls_.TextAttr_GetBackgroundColour(*args, **kwargs)
def GetAlignment(*args, **kwargs):
"""GetAlignment(self) -> int"""
return _controls_.TextAttr_GetAlignment(*args, **kwargs)
def GetTabs(*args, **kwargs):
"""GetTabs(self) -> wxArrayInt"""
return _controls_.TextAttr_GetTabs(*args, **kwargs)
def GetLeftIndent(*args, **kwargs):
"""GetLeftIndent(self) -> long"""
return _controls_.TextAttr_GetLeftIndent(*args, **kwargs)
def GetLeftSubIndent(*args, **kwargs):
"""GetLeftSubIndent(self) -> long"""
return _controls_.TextAttr_GetLeftSubIndent(*args, **kwargs)
def GetRightIndent(*args, **kwargs):
"""GetRightIndent(self) -> long"""
return _controls_.TextAttr_GetRightIndent(*args, **kwargs)
def GetFlags(*args, **kwargs):
"""GetFlags(self) -> long"""
return _controls_.TextAttr_GetFlags(*args, **kwargs)
def GetFontSize(*args, **kwargs):
"""GetFontSize(self) -> int"""
return _controls_.TextAttr_GetFontSize(*args, **kwargs)
def GetFontStyle(*args, **kwargs):
"""GetFontStyle(self) -> int"""
return _controls_.TextAttr_GetFontStyle(*args, **kwargs)
def GetFontWeight(*args, **kwargs):
"""GetFontWeight(self) -> int"""
return _controls_.TextAttr_GetFontWeight(*args, **kwargs)
def GetFontUnderlined(*args, **kwargs):
"""GetFontUnderlined(self) -> bool"""
return _controls_.TextAttr_GetFontUnderlined(*args, **kwargs)
def GetFontStrikethrough(*args, **kwargs):
"""GetFontStrikethrough(self) -> bool"""
return _controls_.TextAttr_GetFontStrikethrough(*args, **kwargs)
def GetFontFaceName(*args, **kwargs):
"""GetFontFaceName(self) -> String"""
return _controls_.TextAttr_GetFontFaceName(*args, **kwargs)
def GetFontEncoding(*args, **kwargs):
"""GetFontEncoding(self) -> int"""
return _controls_.TextAttr_GetFontEncoding(*args, **kwargs)
def GetFontFamily(*args, **kwargs):
"""GetFontFamily(self) -> int"""
return _controls_.TextAttr_GetFontFamily(*args, **kwargs)
def GetFont(*args, **kwargs):
"""GetFont(self) -> Font"""
return _controls_.TextAttr_GetFont(*args, **kwargs)
CreateFont = GetFont
def GetCharacterStyleName(*args, **kwargs):
"""GetCharacterStyleName(self) -> String"""
return _controls_.TextAttr_GetCharacterStyleName(*args, **kwargs)
def GetParagraphStyleName(*args, **kwargs):
"""GetParagraphStyleName(self) -> String"""
return _controls_.TextAttr_GetParagraphStyleName(*args, **kwargs)
def GetListStyleName(*args, **kwargs):
"""GetListStyleName(self) -> String"""
return _controls_.TextAttr_GetListStyleName(*args, **kwargs)
def GetParagraphSpacingAfter(*args, **kwargs):
"""GetParagraphSpacingAfter(self) -> int"""
return _controls_.TextAttr_GetParagraphSpacingAfter(*args, **kwargs)
def GetParagraphSpacingBefore(*args, **kwargs):
"""GetParagraphSpacingBefore(self) -> int"""
return _controls_.TextAttr_GetParagraphSpacingBefore(*args, **kwargs)
def GetLineSpacing(*args, **kwargs):
"""GetLineSpacing(self) -> int"""
return _controls_.TextAttr_GetLineSpacing(*args, **kwargs)
def GetBulletStyle(*args, **kwargs):
"""GetBulletStyle(self) -> int"""
return _controls_.TextAttr_GetBulletStyle(*args, **kwargs)
def GetBulletNumber(*args, **kwargs):
"""GetBulletNumber(self) -> int"""
return _controls_.TextAttr_GetBulletNumber(*args, **kwargs)
def GetBulletText(*args, **kwargs):
"""GetBulletText(self) -> String"""
return _controls_.TextAttr_GetBulletText(*args, **kwargs)
def GetBulletFont(*args, **kwargs):
"""GetBulletFont(self) -> String"""
return _controls_.TextAttr_GetBulletFont(*args, **kwargs)
def GetBulletName(*args, **kwargs):
"""GetBulletName(self) -> String"""
return _controls_.TextAttr_GetBulletName(*args, **kwargs)
def GetURL(*args, **kwargs):
"""GetURL(self) -> String"""
return _controls_.TextAttr_GetURL(*args, **kwargs)
def GetTextEffects(*args, **kwargs):
"""GetTextEffects(self) -> int"""
return _controls_.TextAttr_GetTextEffects(*args, **kwargs)
def GetTextEffectFlags(*args, **kwargs):
"""GetTextEffectFlags(self) -> int"""
return _controls_.TextAttr_GetTextEffectFlags(*args, **kwargs)
def GetOutlineLevel(*args, **kwargs):
"""GetOutlineLevel(self) -> int"""
return _controls_.TextAttr_GetOutlineLevel(*args, **kwargs)
def HasTextColour(*args, **kwargs):
"""HasTextColour(self) -> bool"""
return _controls_.TextAttr_HasTextColour(*args, **kwargs)
def HasBackgroundColour(*args, **kwargs):
"""HasBackgroundColour(self) -> bool"""
return _controls_.TextAttr_HasBackgroundColour(*args, **kwargs)
def HasAlignment(*args, **kwargs):
"""HasAlignment(self) -> bool"""
return _controls_.TextAttr_HasAlignment(*args, **kwargs)
def HasTabs(*args, **kwargs):
"""HasTabs(self) -> bool"""
return _controls_.TextAttr_HasTabs(*args, **kwargs)
def HasLeftIndent(*args, **kwargs):
"""HasLeftIndent(self) -> bool"""
return _controls_.TextAttr_HasLeftIndent(*args, **kwargs)
def HasRightIndent(*args, **kwargs):
"""HasRightIndent(self) -> bool"""
return _controls_.TextAttr_HasRightIndent(*args, **kwargs)
def HasFontWeight(*args, **kwargs):
"""HasFontWeight(self) -> bool"""
return _controls_.TextAttr_HasFontWeight(*args, **kwargs)
def HasFontSize(*args, **kwargs):
"""HasFontSize(self) -> bool"""
return _controls_.TextAttr_HasFontSize(*args, **kwargs)
def HasFontItalic(*args, **kwargs):
"""HasFontItalic(self) -> bool"""
return _controls_.TextAttr_HasFontItalic(*args, **kwargs)
def HasFontUnderlined(*args, **kwargs):
"""HasFontUnderlined(self) -> bool"""
return _controls_.TextAttr_HasFontUnderlined(*args, **kwargs)
def HasFontStrikethrough(*args, **kwargs):
"""HasFontStrikethrough(self) -> bool"""
return _controls_.TextAttr_HasFontStrikethrough(*args, **kwargs)
def HasFontFaceName(*args, **kwargs):
"""HasFontFaceName(self) -> bool"""
return _controls_.TextAttr_HasFontFaceName(*args, **kwargs)
def HasFontEncoding(*args, **kwargs):
"""HasFontEncoding(self) -> bool"""
return _controls_.TextAttr_HasFontEncoding(*args, **kwargs)
def HasFontFamily(*args, **kwargs):
"""HasFontFamily(self) -> bool"""
return _controls_.TextAttr_HasFontFamily(*args, **kwargs)
def HasFont(*args, **kwargs):
"""HasFont(self) -> bool"""
return _controls_.TextAttr_HasFont(*args, **kwargs)
def HasParagraphSpacingAfter(*args, **kwargs):
"""HasParagraphSpacingAfter(self) -> bool"""
return _controls_.TextAttr_HasParagraphSpacingAfter(*args, **kwargs)
def HasParagraphSpacingBefore(*args, **kwargs):
"""HasParagraphSpacingBefore(self) -> bool"""
return _controls_.TextAttr_HasParagraphSpacingBefore(*args, **kwargs)
def HasLineSpacing(*args, **kwargs):
"""HasLineSpacing(self) -> bool"""
return _controls_.TextAttr_HasLineSpacing(*args, **kwargs)
def HasCharacterStyleName(*args, **kwargs):
"""HasCharacterStyleName(self) -> bool"""
return _controls_.TextAttr_HasCharacterStyleName(*args, **kwargs)
def HasParagraphStyleName(*args, **kwargs):
"""HasParagraphStyleName(self) -> bool"""
return _controls_.TextAttr_HasParagraphStyleName(*args, **kwargs)
def HasListStyleName(*args, **kwargs):
"""HasListStyleName(self) -> bool"""
return _controls_.TextAttr_HasListStyleName(*args, **kwargs)
def HasBulletStyle(*args, **kwargs):
"""HasBulletStyle(self) -> bool"""
return _controls_.TextAttr_HasBulletStyle(*args, **kwargs)
def HasBulletNumber(*args, **kwargs):
"""HasBulletNumber(self) -> bool"""
return _controls_.TextAttr_HasBulletNumber(*args, **kwargs)
def HasBulletText(*args, **kwargs):
"""HasBulletText(self) -> bool"""
return _controls_.TextAttr_HasBulletText(*args, **kwargs)
def HasBulletName(*args, **kwargs):
"""HasBulletName(self) -> bool"""
return _controls_.TextAttr_HasBulletName(*args, **kwargs)
def HasURL(*args, **kwargs):
"""HasURL(self) -> bool"""
return _controls_.TextAttr_HasURL(*args, **kwargs)
def HasPageBreak(*args, **kwargs):
"""HasPageBreak(self) -> bool"""
return _controls_.TextAttr_HasPageBreak(*args, **kwargs)
def HasTextEffects(*args, **kwargs):
"""HasTextEffects(self) -> bool"""
return _controls_.TextAttr_HasTextEffects(*args, **kwargs)
def HasTextEffect(*args, **kwargs):
"""HasTextEffect(self, int effect) -> bool"""
return _controls_.TextAttr_HasTextEffect(*args, **kwargs)
def HasOutlineLevel(*args, **kwargs):
"""HasOutlineLevel(self) -> bool"""
return _controls_.TextAttr_HasOutlineLevel(*args, **kwargs)
def HasFlag(*args, **kwargs):
"""HasFlag(self, long flag) -> bool"""
return _controls_.TextAttr_HasFlag(*args, **kwargs)
def RemoveFlag(*args, **kwargs):
"""RemoveFlag(self, long flag)"""
return _controls_.TextAttr_RemoveFlag(*args, **kwargs)
def AddFlag(*args, **kwargs):
"""AddFlag(self, long flag)"""
return _controls_.TextAttr_AddFlag(*args, **kwargs)
def IsCharacterStyle(*args, **kwargs):
"""IsCharacterStyle(self) -> bool"""
return _controls_.TextAttr_IsCharacterStyle(*args, **kwargs)
def IsParagraphStyle(*args, **kwargs):
"""IsParagraphStyle(self) -> bool"""
return _controls_.TextAttr_IsParagraphStyle(*args, **kwargs)
def IsDefault(*args, **kwargs):
"""IsDefault(self) -> bool"""
return _controls_.TextAttr_IsDefault(*args, **kwargs)
def Apply(*args, **kwargs):
"""Apply(self, TextAttr style, TextAttr compareWith=None) -> bool"""
return _controls_.TextAttr_Apply(*args, **kwargs)
def Merge(*args, **kwargs):
"""Merge(self, TextAttr overlay)"""
return _controls_.TextAttr_Merge(*args, **kwargs)
def Combine(*args, **kwargs):
"""Combine(TextAttr attr, TextAttr attrDef, TextCtrl text) -> TextAttr"""
return _controls_.TextAttr_Combine(*args, **kwargs)
Combine = staticmethod(Combine)
def TabsEq(*args, **kwargs):
"""TabsEq(wxArrayInt tabs1, wxArrayInt tabs2) -> bool"""
return _controls_.TextAttr_TabsEq(*args, **kwargs)
TabsEq = staticmethod(TabsEq)
def RemoveStyle(*args, **kwargs):
"""RemoveStyle(TextAttr destStyle, TextAttr style) -> bool"""
return _controls_.TextAttr_RemoveStyle(*args, **kwargs)
RemoveStyle = staticmethod(RemoveStyle)
def CombineBitlists(*args, **kwargs):
"""CombineBitlists(int valueA, int valueB, int flagsA, int flagsB) -> bool"""
return _controls_.TextAttr_CombineBitlists(*args, **kwargs)
CombineBitlists = staticmethod(CombineBitlists)
def BitlistsEqPartial(*args, **kwargs):
"""BitlistsEqPartial(int valueA, int valueB, int flags) -> bool"""
return _controls_.TextAttr_BitlistsEqPartial(*args, **kwargs)
BitlistsEqPartial = staticmethod(BitlistsEqPartial)
def SplitParaCharStyles(*args, **kwargs):
"""SplitParaCharStyles(TextAttr style, TextAttr parStyle, TextAttr charStyle) -> bool"""
return _controls_.TextAttr_SplitParaCharStyles(*args, **kwargs)
SplitParaCharStyles = staticmethod(SplitParaCharStyles)
Alignment = property(GetAlignment,SetAlignment)
BackgroundColour = property(GetBackgroundColour,SetBackgroundColour)
Flags = property(GetFlags,SetFlags)
Font = property(GetFont,SetFont)
LeftIndent = property(GetLeftIndent,SetLeftIndent)
LeftSubIndent = property(GetLeftSubIndent)
RightIndent = property(GetRightIndent,SetRightIndent)
Tabs = property(GetTabs,SetTabs)
TextColour = property(GetTextColour,SetTextColour)
FontSize = property(GetFontSize,SetFontSize)
FontStyle = property(GetFontStyle,SetFontStyle)
FontWeight = property(GetFontWeight,SetFontWeight)
FontUnderlined = property(GetFontUnderlined,SetFontUnderlined)
FontFaceName = property(GetFontFaceName,SetFontFaceName)
FontEncoding = property(GetFontEncoding,SetFontEncoding)
FontFamily = property(GetFontFamily,SetFontFamily)
CharacterStyleName = property(GetCharacterStyleName,SetCharacterStyleName)
ParagraphStyleName = property(GetParagraphStyleName,SetParagraphStyleName)
ListStyleName = property(GetListStyleName,SetListStyleName)
ParagraphSpacingAfter = property(GetParagraphSpacingAfter,SetParagraphSpacingAfter)
ParagraphSpacingBefore = property(GetParagraphSpacingBefore,SetParagraphSpacingBefore)
LineSpacing = property(GetLineSpacing,SetLineSpacing)
BulletStyle = property(GetBulletStyle,SetBulletStyle)
BulletNumber = property(GetBulletNumber,SetBulletNumber)
BulletText = property(GetBulletText,SetBulletText)
BulletFont = property(GetBulletFont,SetBulletFont)
BulletName = property(GetBulletName,SetBulletName)
URL = property(GetURL,SetURL)
TextEffects = property(GetTextEffects,SetTextEffects)
TextEffectFlags = property(GetTextEffectFlags,SetTextEffectFlags)
OutlineLevel = property(GetOutlineLevel,SetOutlineLevel)
_controls_.TextAttr_swigregister(TextAttr)
TextCtrlNameStr = cvar.TextCtrlNameStr
def TextAttr_Combine(*args, **kwargs):
"""TextAttr_Combine(TextAttr attr, TextAttr attrDef, TextCtrl text) -> TextAttr"""
return _controls_.TextAttr_Combine(*args, **kwargs)
def TextAttr_TabsEq(*args, **kwargs):
"""TextAttr_TabsEq(wxArrayInt tabs1, wxArrayInt tabs2) -> bool"""
return _controls_.TextAttr_TabsEq(*args, **kwargs)
def TextAttr_RemoveStyle(*args, **kwargs):
"""TextAttr_RemoveStyle(TextAttr destStyle, TextAttr style) -> bool"""
return _controls_.TextAttr_RemoveStyle(*args, **kwargs)
def TextAttr_CombineBitlists(*args, **kwargs):
"""TextAttr_CombineBitlists(int valueA, int valueB, int flagsA, int flagsB) -> bool"""
return _controls_.TextAttr_CombineBitlists(*args, **kwargs)
def TextAttr_BitlistsEqPartial(*args, **kwargs):
"""TextAttr_BitlistsEqPartial(int valueA, int valueB, int flags) -> bool"""
return _controls_.TextAttr_BitlistsEqPartial(*args, **kwargs)
def TextAttr_SplitParaCharStyles(*args, **kwargs):
"""TextAttr_SplitParaCharStyles(TextAttr style, TextAttr parStyle, TextAttr charStyle) -> bool"""
return _controls_.TextAttr_SplitParaCharStyles(*args, **kwargs)
class TextCtrl(_core.TextCtrlBase):
"""Proxy of C++ TextCtrl class"""
thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
def __init__(self, *args, **kwargs):
"""
__init__(self, Window parent, int id=-1, String value=EmptyString,
Point pos=DefaultPosition, Size size=DefaultSize,
long style=0, Validator validator=DefaultValidator,
String name=TextCtrlNameStr) -> TextCtrl
"""
_controls_.TextCtrl_swiginit(self,_controls_.new_TextCtrl(*args, **kwargs))
self._setOORInfo(self)
def Create(*args, **kwargs):
"""
Create(self, Window parent, int id=-1, String value=EmptyString,
Point pos=DefaultPosition, Size size=DefaultSize,
long style=0, Validator validator=DefaultValidator,
String name=TextCtrlNameStr) -> bool
"""
return _controls_.TextCtrl_Create(*args, **kwargs)
def IsSingleLine(*args, **kwargs):
"""IsSingleLine(self) -> bool"""
return _controls_.TextCtrl_IsSingleLine(*args, **kwargs)
def IsMultiLine(*args, **kwargs):
"""IsMultiLine(self) -> bool"""
return _controls_.TextCtrl_IsMultiLine(*args, **kwargs)
def EmulateKeyPress(*args, **kwargs):
"""EmulateKeyPress(self, KeyEvent event) -> bool"""
return _controls_.TextCtrl_EmulateKeyPress(*args, **kwargs)
def MacCheckSpelling(*args, **kwargs):
"""MacCheckSpelling(self, bool check)"""
return _controls_.TextCtrl_MacCheckSpelling(*args, **kwargs)
def SendTextUpdatedEvent(*args, **kwargs):
"""SendTextUpdatedEvent(self)"""
return _controls_.TextCtrl_SendTextUpdatedEvent(*args, **kwargs)
def write(*args, **kwargs):
"""write(self, String text)"""
return _controls_.TextCtrl_write(*args, **kwargs)
def GetClassDefaultAttributes(*args, **kwargs):
"""
GetClassDefaultAttributes(int variant=WINDOW_VARIANT_NORMAL) -> VisualAttributes
Get the default attributes for this class. This is useful if you want
to use the same font or colour in your own control as in a standard
control -- which is a much better idea than hard coding specific
colours or fonts which might look completely out of place on the
user's system, especially if it uses themes.
The variant parameter is only relevant under Mac currently and is
ignore under other platforms. Under Mac, it will change the size of
the returned font. See `wx.Window.SetWindowVariant` for more about
this.
"""
return _controls_.TextCtrl_GetClassDefaultAttributes(*args, **kwargs)
GetClassDefaultAttributes = staticmethod(GetClassDefaultAttributes)
_controls_.TextCtrl_swigregister(TextCtrl)
def PreTextCtrl(*args, **kwargs):
"""PreTextCtrl() -> TextCtrl"""
val = _controls_.new_PreTextCtrl(*args, **kwargs)
return val
def TextCtrl_GetClassDefaultAttributes(*args, **kwargs):
"""
TextCtrl_GetClassDefaultAttributes(int variant=WINDOW_VARIANT_NORMAL) -> VisualAttributes
Get the default attributes for this class. This is useful if you want
to use the same font or colour in your own control as in a standard
control -- which is a much better idea than hard coding specific
colours or fonts which might look completely out of place on the
user's system, especially if it uses themes.
The variant parameter is only relevant under Mac currently and is
ignore under other platforms. Under Mac, it will change the size of
the returned font. See `wx.Window.SetWindowVariant` for more about
this.
"""
return _controls_.TextCtrl_GetClassDefaultAttributes(*args, **kwargs)
wxEVT_COMMAND_TEXT_UPDATED = _controls_.wxEVT_COMMAND_TEXT_UPDATED
wxEVT_COMMAND_TEXT_ENTER = _controls_.wxEVT_COMMAND_TEXT_ENTER
wxEVT_COMMAND_TEXT_URL = _controls_.wxEVT_COMMAND_TEXT_URL
wxEVT_COMMAND_TEXT_MAXLEN = _controls_.wxEVT_COMMAND_TEXT_MAXLEN
class TextUrlEvent(_core.CommandEvent):
"""Proxy of C++ TextUrlEvent class"""
thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
def __init__(self, *args, **kwargs):
"""__init__(self, int winid, MouseEvent evtMouse, long start, long end) -> TextUrlEvent"""
_controls_.TextUrlEvent_swiginit(self,_controls_.new_TextUrlEvent(*args, **kwargs))
def GetMouseEvent(*args, **kwargs):
"""GetMouseEvent(self) -> MouseEvent"""
return _controls_.TextUrlEvent_GetMouseEvent(*args, **kwargs)
def GetURLStart(*args, **kwargs):
"""GetURLStart(self) -> long"""
return _controls_.TextUrlEvent_GetURLStart(*args, **kwargs)
def GetURLEnd(*args, **kwargs):
"""GetURLEnd(self) -> long"""
return _controls_.TextUrlEvent_GetURLEnd(*args, **kwargs)
MouseEvent = property(GetMouseEvent,doc="See `GetMouseEvent`")
URLEnd = property(GetURLEnd,doc="See `GetURLEnd`")
URLStart = property(GetURLStart,doc="See `GetURLStart`")
_controls_.TextUrlEvent_swigregister(TextUrlEvent)
EVT_TEXT = wx.PyEventBinder( wxEVT_COMMAND_TEXT_UPDATED, 1)
EVT_TEXT_ENTER = wx.PyEventBinder( wxEVT_COMMAND_TEXT_ENTER, 1)
EVT_TEXT_URL = wx.PyEventBinder( wxEVT_COMMAND_TEXT_URL, 1)
EVT_TEXT_MAXLEN = wx.PyEventBinder( wxEVT_COMMAND_TEXT_MAXLEN, 1)
#---------------------------------------------------------------------------
class ScrollBar(_core.Control):
"""Proxy of C++ ScrollBar class"""
thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
def __init__(self, *args, **kwargs):
"""
__init__(self, Window parent, int id=-1, Point pos=DefaultPosition,
Size size=DefaultSize, long style=SB_HORIZONTAL,
Validator validator=DefaultValidator, String name=ScrollBarNameStr) -> ScrollBar
"""
_controls_.ScrollBar_swiginit(self,_controls_.new_ScrollBar(*args, **kwargs))
self._setOORInfo(self)
def Create(*args, **kwargs):
"""
Create(self, Window parent, int id=-1, Point pos=DefaultPosition,
Size size=DefaultSize, long style=SB_HORIZONTAL,
Validator validator=DefaultValidator, String name=ScrollBarNameStr) -> bool
Do the 2nd phase and create the GUI control.
"""
return _controls_.ScrollBar_Create(*args, **kwargs)
def GetThumbPosition(*args, **kwargs):
"""GetThumbPosition(self) -> int"""
return _controls_.ScrollBar_GetThumbPosition(*args, **kwargs)
def GetThumbSize(*args, **kwargs):
"""GetThumbSize(self) -> int"""
return _controls_.ScrollBar_GetThumbSize(*args, **kwargs)
GetThumbLength = GetThumbSize
def GetPageSize(*args, **kwargs):
"""GetPageSize(self) -> int"""
return _controls_.ScrollBar_GetPageSize(*args, **kwargs)
def GetRange(*args, **kwargs):
"""GetRange(self) -> int"""
return _controls_.ScrollBar_GetRange(*args, **kwargs)
def IsVertical(*args, **kwargs):
"""IsVertical(self) -> bool"""
return _controls_.ScrollBar_IsVertical(*args, **kwargs)
def SetThumbPosition(*args, **kwargs):
"""SetThumbPosition(self, int viewStart)"""
return _controls_.ScrollBar_SetThumbPosition(*args, **kwargs)
def GetClassDefaultAttributes(*args, **kwargs):
"""
GetClassDefaultAttributes(int variant=WINDOW_VARIANT_NORMAL) -> VisualAttributes
Get the default attributes for this class. This is useful if you want
to use the same font or colour in your own control as in a standard
control -- which is a much better idea than hard coding specific
colours or fonts which might look completely out of place on the
user's system, especially if it uses themes.
The variant parameter is only relevant under Mac currently and is
ignore under other platforms. Under Mac, it will change the size of
the returned font. See `wx.Window.SetWindowVariant` for more about
this.
"""
return _controls_.ScrollBar_GetClassDefaultAttributes(*args, **kwargs)
GetClassDefaultAttributes = staticmethod(GetClassDefaultAttributes)
PageSize = property(GetPageSize,doc="See `GetPageSize`")
Range = property(GetRange,doc="See `GetRange`")
ThumbPosition = property(GetThumbPosition,SetThumbPosition,doc="See `GetThumbPosition` and `SetThumbPosition`")
ThumbSize = property(GetThumbSize,doc="See `GetThumbSize`")
_controls_.ScrollBar_swigregister(ScrollBar)
ScrollBarNameStr = cvar.ScrollBarNameStr
def PreScrollBar(*args, **kwargs):
"""PreScrollBar() -> ScrollBar"""
val = _controls_.new_PreScrollBar(*args, **kwargs)
return val
def ScrollBar_GetClassDefaultAttributes(*args, **kwargs):
"""
ScrollBar_GetClassDefaultAttributes(int variant=WINDOW_VARIANT_NORMAL) -> VisualAttributes
Get the default attributes for this class. This is useful if you want
to use the same font or colour in your own control as in a standard
control -- which is a much better idea than hard coding specific
colours or fonts which might look completely out of place on the
user's system, especially if it uses themes.
The variant parameter is only relevant under Mac currently and is
ignore under other platforms. Under Mac, it will change the size of
the returned font. See `wx.Window.SetWindowVariant` for more about
this.
"""
return _controls_.ScrollBar_GetClassDefaultAttributes(*args, **kwargs)
#---------------------------------------------------------------------------
SP_HORIZONTAL = _controls_.SP_HORIZONTAL
SP_VERTICAL = _controls_.SP_VERTICAL
SP_ARROW_KEYS = _controls_.SP_ARROW_KEYS
SP_WRAP = _controls_.SP_WRAP
class SpinButton(_core.Control):
"""Proxy of C++ SpinButton class"""
thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
def __init__(self, *args, **kwargs):
"""
__init__(self, Window parent, int id=-1, Point pos=DefaultPosition,
Size size=DefaultSize, long style=SP_HORIZONTAL,
String name=SPIN_BUTTON_NAME) -> SpinButton
"""
_controls_.SpinButton_swiginit(self,_controls_.new_SpinButton(*args, **kwargs))
self._setOORInfo(self)
def Create(*args, **kwargs):
"""
Create(self, Window parent, int id=-1, Point pos=DefaultPosition,
Size size=DefaultSize, long style=SP_HORIZONTAL,
String name=SPIN_BUTTON_NAME) -> bool
"""
return _controls_.SpinButton_Create(*args, **kwargs)
def GetValue(*args, **kwargs):
"""GetValue(self) -> int"""
return _controls_.SpinButton_GetValue(*args, **kwargs)
def GetMin(*args, **kwargs):
"""GetMin(self) -> int"""
return _controls_.SpinButton_GetMin(*args, **kwargs)
def GetMax(*args, **kwargs):
"""GetMax(self) -> int"""
return _controls_.SpinButton_GetMax(*args, **kwargs)
def SetValue(*args, **kwargs):
"""SetValue(self, int val)"""
return _controls_.SpinButton_SetValue(*args, **kwargs)
def SetMin(*args, **kwargs):
"""SetMin(self, int minVal)"""
return _controls_.SpinButton_SetMin(*args, **kwargs)
def SetMax(*args, **kwargs):
"""SetMax(self, int maxVal)"""
return _controls_.SpinButton_SetMax(*args, **kwargs)
def SetRange(*args, **kwargs):
"""SetRange(self, int minVal, int maxVal)"""
return _controls_.SpinButton_SetRange(*args, **kwargs)
def IsVertical(*args, **kwargs):
"""IsVertical(self) -> bool"""
return _controls_.SpinButton_IsVertical(*args, **kwargs)
def GetClassDefaultAttributes(*args, **kwargs):
"""
GetClassDefaultAttributes(int variant=WINDOW_VARIANT_NORMAL) -> VisualAttributes
Get the default attributes for this class. This is useful if you want
to use the same font or colour in your own control as in a standard
control -- which is a much better idea than hard coding specific
colours or fonts which might look completely out of place on the
user's system, especially if it uses themes.
The variant parameter is only relevant under Mac currently and is
ignore under other platforms. Under Mac, it will change the size of
the returned font. See `wx.Window.SetWindowVariant` for more about
this.
"""
return _controls_.SpinButton_GetClassDefaultAttributes(*args, **kwargs)
GetClassDefaultAttributes = staticmethod(GetClassDefaultAttributes)
Max = property(GetMax,SetMax,doc="See `GetMax` and `SetMax`")
Min = property(GetMin,SetMin,doc="See `GetMin` and `SetMin`")
Value = property(GetValue,SetValue,doc="See `GetValue` and `SetValue`")
_controls_.SpinButton_swigregister(SpinButton)
SPIN_BUTTON_NAME = cvar.SPIN_BUTTON_NAME
SpinCtrlNameStr = cvar.SpinCtrlNameStr
def PreSpinButton(*args, **kwargs):
"""PreSpinButton() -> SpinButton"""
val = _controls_.new_PreSpinButton(*args, **kwargs)
return val
def SpinButton_GetClassDefaultAttributes(*args, **kwargs):
"""
SpinButton_GetClassDefaultAttributes(int variant=WINDOW_VARIANT_NORMAL) -> VisualAttributes
Get the default attributes for this class. This is useful if you want
to use the same font or colour in your own control as in a standard
control -- which is a much better idea than hard coding specific
colours or fonts which might look completely out of place on the
user's system, especially if it uses themes.
The variant parameter is only relevant under Mac currently and is
ignore under other platforms. Under Mac, it will change the size of
the returned font. See `wx.Window.SetWindowVariant` for more about
this.
"""
return _controls_.SpinButton_GetClassDefaultAttributes(*args, **kwargs)
class SpinCtrl(_core.Control):
"""Proxy of C++ SpinCtrl class"""
thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
def __init__(self, *args, **kwargs):
"""
__init__(self, Window parent, int id=-1, String value=EmptyString,
Point pos=DefaultPosition, Size size=DefaultSize,
long style=wxSP_ARROW_KEYS|wxALIGN_RIGHT,
int min=0, int max=100, int initial=0, String name=SpinCtrlNameStr) -> SpinCtrl
"""
_controls_.SpinCtrl_swiginit(self,_controls_.new_SpinCtrl(*args, **kwargs))
self._setOORInfo(self)
def Create(*args, **kwargs):
"""
Create(self, Window parent, int id=-1, String value=EmptyString,
Point pos=DefaultPosition, Size size=DefaultSize,
long style=SP_ARROW_KEYS, int min=0, int max=100,
int initial=0, String name=SpinCtrlNameStr) -> bool
"""
return _controls_.SpinCtrl_Create(*args, **kwargs)
def GetValue(*args, **kwargs):
"""GetValue(self) -> int"""
return _controls_.SpinCtrl_GetValue(*args, **kwargs)
def SetValue(*args, **kwargs):
"""SetValue(self, int value)"""
return _controls_.SpinCtrl_SetValue(*args, **kwargs)
def SetValueString(*args, **kwargs):
"""SetValueString(self, String text)"""
return _controls_.SpinCtrl_SetValueString(*args, **kwargs)
def SetRange(*args, **kwargs):
"""SetRange(self, int minVal, int maxVal)"""
return _controls_.SpinCtrl_SetRange(*args, **kwargs)
def GetMin(*args, **kwargs):
"""GetMin(self) -> int"""
return _controls_.SpinCtrl_GetMin(*args, **kwargs)
def GetMax(*args, **kwargs):
"""GetMax(self) -> int"""
return _controls_.SpinCtrl_GetMax(*args, **kwargs)
def SetSelection(*args, **kwargs):
"""SetSelection(self, long from, long to)"""
return _controls_.SpinCtrl_SetSelection(*args, **kwargs)
def GetClassDefaultAttributes(*args, **kwargs):
"""
GetClassDefaultAttributes(int variant=WINDOW_VARIANT_NORMAL) -> VisualAttributes
Get the default attributes for this class. This is useful if you want
to use the same font or colour in your own control as in a standard
control -- which is a much better idea than hard coding specific
colours or fonts which might look completely out of place on the
user's system, especially if it uses themes.
The variant parameter is only relevant under Mac currently and is
ignore under other platforms. Under Mac, it will change the size of
the returned font. See `wx.Window.SetWindowVariant` for more about
this.
"""
return _controls_.SpinCtrl_GetClassDefaultAttributes(*args, **kwargs)
GetClassDefaultAttributes = staticmethod(GetClassDefaultAttributes)
Max = property(GetMax,doc="See `GetMax`")
Min = property(GetMin,doc="See `GetMin`")
Value = property(GetValue,SetValue,doc="See `GetValue` and `SetValue`")
_controls_.SpinCtrl_swigregister(SpinCtrl)
def PreSpinCtrl(*args, **kwargs):
"""PreSpinCtrl() -> SpinCtrl"""
val = _controls_.new_PreSpinCtrl(*args, **kwargs)
return val
def SpinCtrl_GetClassDefaultAttributes(*args, **kwargs):
"""
SpinCtrl_GetClassDefaultAttributes(int variant=WINDOW_VARIANT_NORMAL) -> VisualAttributes
Get the default attributes for this class. This is useful if you want
to use the same font or colour in your own control as in a standard
control -- which is a much better idea than hard coding specific
colours or fonts which might look completely out of place on the
user's system, especially if it uses themes.
The variant parameter is only relevant under Mac currently and is
ignore under other platforms. Under Mac, it will change the size of
the returned font. See `wx.Window.SetWindowVariant` for more about
this.
"""
return _controls_.SpinCtrl_GetClassDefaultAttributes(*args, **kwargs)
class SpinEvent(_core.NotifyEvent):
"""Proxy of C++ SpinEvent class"""
thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
def __init__(self, *args, **kwargs):
"""__init__(self, EventType commandType=wxEVT_NULL, int winid=0) -> SpinEvent"""
_controls_.SpinEvent_swiginit(self,_controls_.new_SpinEvent(*args, **kwargs))
def GetPosition(*args, **kwargs):
"""GetPosition(self) -> int"""
return _controls_.SpinEvent_GetPosition(*args, **kwargs)
def SetPosition(*args, **kwargs):
"""SetPosition(self, int pos)"""
return _controls_.SpinEvent_SetPosition(*args, **kwargs)
def GetValue(*args, **kwargs):
"""GetValue(self) -> int"""
return _controls_.SpinEvent_GetValue(*args, **kwargs)
def SetValue(*args, **kwargs):
"""SetValue(self, int value)"""
return _controls_.SpinEvent_SetValue(*args, **kwargs)
Position = property(GetPosition,SetPosition)
Value = property(GetValue,SetValue)
_controls_.SpinEvent_swigregister(SpinEvent)
wxEVT_SPIN_UP = _controls_.wxEVT_SPIN_UP
wxEVT_SPIN_DOWN = _controls_.wxEVT_SPIN_DOWN
wxEVT_SPIN = _controls_.wxEVT_SPIN
wxEVT_COMMAND_SPINCTRL_UPDATED = _controls_.wxEVT_COMMAND_SPINCTRL_UPDATED
wxEVT_COMMAND_SPINCTRLDOUBLE_UPDATED = _controls_.wxEVT_COMMAND_SPINCTRLDOUBLE_UPDATED
EVT_SPIN_UP = wx.PyEventBinder( wxEVT_SPIN_UP, 1)
EVT_SPIN_DOWN = wx.PyEventBinder( wxEVT_SPIN_DOWN, 1)
EVT_SPIN = wx.PyEventBinder( wxEVT_SPIN, 1)
EVT_SPINCTRL = wx.PyEventBinder( wxEVT_COMMAND_SPINCTRL_UPDATED, 1)
EVT_SPINCTRLDOUBLE = wx.PyEventBinder( wxEVT_COMMAND_SPINCTRLDOUBLE_UPDATED, 1)
class SpinCtrlDouble(_core.Control):
"""Proxy of C++ SpinCtrlDouble class"""
thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
def __init__(self, *args, **kwargs):
"""
__init__(self, Window parent, int id=ID_ANY, String value=wxEmptyString,
Point pos=DefaultPosition, Size size=DefaultSize,
long style=wxSP_ARROW_KEYS|wxALIGN_RIGHT,
double min=0, double max=100, double initial=0,
double inc=1, String name="wxSpinCtrlDouble") -> SpinCtrlDouble
"""
_controls_.SpinCtrlDouble_swiginit(self,_controls_.new_SpinCtrlDouble(*args, **kwargs))
self._setOORInfo(self)
def Create(*args, **kwargs):
"""
Create(self, Window parent, int id=ID_ANY, String value=wxEmptyString,
Point pos=DefaultPosition, Size size=DefaultSize,
long style=SP_ARROW_KEYS, double min=0,
double max=100, double initial=0, double inc=1,
String name="wxSpinCtrlDouble") -> bool
"""
return _controls_.SpinCtrlDouble_Create(*args, **kwargs)
def GetValue(*args, **kwargs):
"""GetValue(self) -> double"""
return _controls_.SpinCtrlDouble_GetValue(*args, **kwargs)
def GetMin(*args, **kwargs):
"""GetMin(self) -> double"""
return _controls_.SpinCtrlDouble_GetMin(*args, **kwargs)
def GetMax(*args, **kwargs):
"""GetMax(self) -> double"""
return _controls_.SpinCtrlDouble_GetMax(*args, **kwargs)
def GetIncrement(*args, **kwargs):
"""GetIncrement(self) -> double"""
return _controls_.SpinCtrlDouble_GetIncrement(*args, **kwargs)
def GetDigits(*args, **kwargs):
"""GetDigits(self) -> unsigned int"""
return _controls_.SpinCtrlDouble_GetDigits(*args, **kwargs)
def SetValue(*args, **kwargs):
"""SetValue(self, double value)"""
return _controls_.SpinCtrlDouble_SetValue(*args, **kwargs)
def SetRange(*args, **kwargs):
"""SetRange(self, double minVal, double maxVal)"""
return _controls_.SpinCtrlDouble_SetRange(*args, **kwargs)
def SetMin(self, minVal):
self.SetRange(minVal, self.GetMax())
def SetMax(self, maxVal):
self.SetRange(self.GetMin(), maxVal)
def SetIncrement(*args, **kwargs):
"""SetIncrement(self, double inc)"""
return _controls_.SpinCtrlDouble_SetIncrement(*args, **kwargs)
def SetDigits(*args, **kwargs):
"""SetDigits(self, unsigned int digits)"""
return _controls_.SpinCtrlDouble_SetDigits(*args, **kwargs)
Value = property(GetValue,SetValue)
Min = property(GetMin,SetMin)
Max = property(GetMax,SetMax)
Increment = property(GetIncrement,SetIncrement)
Digits = property(GetDigits,SetDigits)
_controls_.SpinCtrlDouble_swigregister(SpinCtrlDouble)
def PreSpinCtrlDouble(*args, **kwargs):
"""PreSpinCtrlDouble() -> SpinCtrlDouble"""
val = _controls_.new_PreSpinCtrlDouble(*args, **kwargs)
return val
class SpinDoubleEvent(_core.NotifyEvent):
"""Proxy of C++ SpinDoubleEvent class"""
thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
def __init__(self, *args, **kwargs):
"""__init__(self, EventType commandType=wxEVT_NULL, int winid=0, double value=0) -> SpinDoubleEvent"""
_controls_.SpinDoubleEvent_swiginit(self,_controls_.new_SpinDoubleEvent(*args, **kwargs))
def GetValue(*args, **kwargs):
"""GetValue(self) -> double"""
return _controls_.SpinDoubleEvent_GetValue(*args, **kwargs)
def SetValue(*args, **kwargs):
"""SetValue(self, double value)"""
return _controls_.SpinDoubleEvent_SetValue(*args, **kwargs)
Value = property(GetValue,SetValue)
_controls_.SpinDoubleEvent_swigregister(SpinDoubleEvent)
EVT_SPINCTRLDOUBLE = wx.PyEventBinder( wxEVT_COMMAND_SPINCTRLDOUBLE_UPDATED, 1 )
#---------------------------------------------------------------------------
class RadioBox(_core.Control):
"""Proxy of C++ RadioBox class"""
thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
def __init__(self, *args, **kwargs):
"""
__init__(self, Window parent, int id=-1, String label=EmptyString,
Point pos=DefaultPosition, Size size=DefaultSize,
wxArrayString choices=wxPyEmptyStringArray,
int majorDimension=0, long style=RA_HORIZONTAL,
Validator validator=DefaultValidator,
String name=RadioBoxNameStr) -> RadioBox
"""
if kwargs.has_key('point'): kwargs['pos'] = kwargs['point'];del kwargs['point']
_controls_.RadioBox_swiginit(self,_controls_.new_RadioBox(*args, **kwargs))
self._setOORInfo(self)
def Create(*args, **kwargs):
"""
Create(self, Window parent, int id=-1, String label=EmptyString,
Point pos=DefaultPosition, Size size=DefaultSize,
wxArrayString choices=wxPyEmptyStringArray,
int majorDimension=0, long style=RA_HORIZONTAL,
Validator validator=DefaultValidator,
String name=RadioBoxNameStr) -> bool
"""
return _controls_.RadioBox_Create(*args, **kwargs)
def SetSelection(*args, **kwargs):
"""SetSelection(self, int n)"""
return _controls_.RadioBox_SetSelection(*args, **kwargs)
def GetSelection(*args, **kwargs):
"""GetSelection(self) -> int"""
return _controls_.RadioBox_GetSelection(*args, **kwargs)
def GetStringSelection(*args, **kwargs):
"""GetStringSelection(self) -> String"""
return _controls_.RadioBox_GetStringSelection(*args, **kwargs)
def SetStringSelection(*args, **kwargs):
"""SetStringSelection(self, String s) -> bool"""
return _controls_.RadioBox_SetStringSelection(*args, **kwargs)
def GetCount(*args, **kwargs):
"""GetCount(self) -> size_t"""
return _controls_.RadioBox_GetCount(*args, **kwargs)
def FindString(*args, **kwargs):
"""FindString(self, String s) -> int"""
return _controls_.RadioBox_FindString(*args, **kwargs)
def GetString(*args, **kwargs):
"""GetString(self, int n) -> String"""
return _controls_.RadioBox_GetString(*args, **kwargs)
def SetString(*args, **kwargs):
"""SetString(self, int n, String label)"""
return _controls_.RadioBox_SetString(*args, **kwargs)
GetItemLabel = GetString
SetItemLabel = SetString
def EnableItem(*args, **kwargs):
"""EnableItem(self, unsigned int n, bool enable=True)"""
return _controls_.RadioBox_EnableItem(*args, **kwargs)
def ShowItem(*args, **kwargs):
"""ShowItem(self, unsigned int n, bool show=True)"""
return _controls_.RadioBox_ShowItem(*args, **kwargs)
def IsItemEnabled(*args, **kwargs):
"""IsItemEnabled(self, unsigned int n) -> bool"""
return _controls_.RadioBox_IsItemEnabled(*args, **kwargs)
def IsItemShown(*args, **kwargs):
"""IsItemShown(self, unsigned int n) -> bool"""
return _controls_.RadioBox_IsItemShown(*args, **kwargs)
def GetColumnCount(*args, **kwargs):
"""GetColumnCount(self) -> unsigned int"""
return _controls_.RadioBox_GetColumnCount(*args, **kwargs)
def GetRowCount(*args, **kwargs):
"""GetRowCount(self) -> unsigned int"""
return _controls_.RadioBox_GetRowCount(*args, **kwargs)
def GetNextItem(*args, **kwargs):
"""GetNextItem(self, int item, int dir, long style) -> int"""
return _controls_.RadioBox_GetNextItem(*args, **kwargs)
def SetItemToolTip(*args, **kwargs):
"""SetItemToolTip(self, unsigned int item, String text)"""
return _controls_.RadioBox_SetItemToolTip(*args, **kwargs)
def GetItemToolTip(*args, **kwargs):
"""GetItemToolTip(self, unsigned int item) -> ToolTip"""
return _controls_.RadioBox_GetItemToolTip(*args, **kwargs)
def SetItemHelpText(*args, **kwargs):
"""SetItemHelpText(self, unsigned int n, String helpText)"""
return _controls_.RadioBox_SetItemHelpText(*args, **kwargs)
def GetItemHelpText(*args, **kwargs):
"""GetItemHelpText(self, unsigned int n) -> String"""
return _controls_.RadioBox_GetItemHelpText(*args, **kwargs)
def GetClassDefaultAttributes(*args, **kwargs):
"""
GetClassDefaultAttributes(int variant=WINDOW_VARIANT_NORMAL) -> VisualAttributes
Get the default attributes for this class. This is useful if you want
to use the same font or colour in your own control as in a standard
control -- which is a much better idea than hard coding specific
colours or fonts which might look completely out of place on the
user's system, especially if it uses themes.
The variant parameter is only relevant under Mac currently and is
ignore under other platforms. Under Mac, it will change the size of
the returned font. See `wx.Window.SetWindowVariant` for more about
this.
"""
return _controls_.RadioBox_GetClassDefaultAttributes(*args, **kwargs)
GetClassDefaultAttributes = staticmethod(GetClassDefaultAttributes)
ColumnCount = property(GetColumnCount,doc="See `GetColumnCount`")
Count = property(GetCount,doc="See `GetCount`")
RowCount = property(GetRowCount,doc="See `GetRowCount`")
Selection = property(GetSelection,SetSelection,doc="See `GetSelection` and `SetSelection`")
StringSelection = property(GetStringSelection,SetStringSelection,doc="See `GetStringSelection` and `SetStringSelection`")
_controls_.RadioBox_swigregister(RadioBox)
RadioBoxNameStr = cvar.RadioBoxNameStr
RadioButtonNameStr = cvar.RadioButtonNameStr
def PreRadioBox(*args, **kwargs):
"""PreRadioBox() -> RadioBox"""
val = _controls_.new_PreRadioBox(*args, **kwargs)
return val
def RadioBox_GetClassDefaultAttributes(*args, **kwargs):
"""
RadioBox_GetClassDefaultAttributes(int variant=WINDOW_VARIANT_NORMAL) -> VisualAttributes
Get the default attributes for this class. This is useful if you want
to use the same font or colour in your own control as in a standard
control -- which is a much better idea than hard coding specific
colours or fonts which might look completely out of place on the
user's system, especially if it uses themes.
The variant parameter is only relevant under Mac currently and is
ignore under other platforms. Under Mac, it will change the size of
the returned font. See `wx.Window.SetWindowVariant` for more about
this.
"""
return _controls_.RadioBox_GetClassDefaultAttributes(*args, **kwargs)
#---------------------------------------------------------------------------
class RadioButton(_core.Control):
"""Proxy of C++ RadioButton class"""
thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
def __init__(self, *args, **kwargs):
"""
__init__(self, Window parent, int id=-1, String label=EmptyString,
Point pos=DefaultPosition, Size size=DefaultSize,
long style=0, Validator validator=DefaultValidator,
String name=RadioButtonNameStr) -> RadioButton
"""
_controls_.RadioButton_swiginit(self,_controls_.new_RadioButton(*args, **kwargs))
self._setOORInfo(self)
def Create(*args, **kwargs):
"""
Create(self, Window parent, int id=-1, String label=EmptyString,
Point pos=DefaultPosition, Size size=DefaultSize,
long style=0, Validator validator=DefaultValidator,
String name=RadioButtonNameStr) -> bool
"""
return _controls_.RadioButton_Create(*args, **kwargs)
def GetValue(*args, **kwargs):
"""GetValue(self) -> bool"""
return _controls_.RadioButton_GetValue(*args, **kwargs)
def SetValue(*args, **kwargs):
"""SetValue(self, bool value)"""
return _controls_.RadioButton_SetValue(*args, **kwargs)
def GetClassDefaultAttributes(*args, **kwargs):
"""
GetClassDefaultAttributes(int variant=WINDOW_VARIANT_NORMAL) -> VisualAttributes
Get the default attributes for this class. This is useful if you want
to use the same font or colour in your own control as in a standard
control -- which is a much better idea than hard coding specific
colours or fonts which might look completely out of place on the
user's system, especially if it uses themes.
The variant parameter is only relevant under Mac currently and is
ignore under other platforms. Under Mac, it will change the size of
the returned font. See `wx.Window.SetWindowVariant` for more about
this.
"""
return _controls_.RadioButton_GetClassDefaultAttributes(*args, **kwargs)
GetClassDefaultAttributes = staticmethod(GetClassDefaultAttributes)
Value = property(GetValue,SetValue,doc="See `GetValue` and `SetValue`")
_controls_.RadioButton_swigregister(RadioButton)
def PreRadioButton(*args, **kwargs):
"""PreRadioButton() -> RadioButton"""
val = _controls_.new_PreRadioButton(*args, **kwargs)
return val
def RadioButton_GetClassDefaultAttributes(*args, **kwargs):
"""
RadioButton_GetClassDefaultAttributes(int variant=WINDOW_VARIANT_NORMAL) -> VisualAttributes
Get the default attributes for this class. This is useful if you want
to use the same font or colour in your own control as in a standard
control -- which is a much better idea than hard coding specific
colours or fonts which might look completely out of place on the
user's system, especially if it uses themes.
The variant parameter is only relevant under Mac currently and is
ignore under other platforms. Under Mac, it will change the size of
the returned font. See `wx.Window.SetWindowVariant` for more about
this.
"""
return _controls_.RadioButton_GetClassDefaultAttributes(*args, **kwargs)
#---------------------------------------------------------------------------
SL_HORIZONTAL = _controls_.SL_HORIZONTAL
SL_VERTICAL = _controls_.SL_VERTICAL
SL_TICKS = _controls_.SL_TICKS
SL_AUTOTICKS = _controls_.SL_AUTOTICKS
SL_LEFT = _controls_.SL_LEFT
SL_TOP = _controls_.SL_TOP
SL_RIGHT = _controls_.SL_RIGHT
SL_BOTTOM = _controls_.SL_BOTTOM
SL_BOTH = _controls_.SL_BOTH
SL_SELRANGE = _controls_.SL_SELRANGE
SL_INVERSE = _controls_.SL_INVERSE
SL_MIN_MAX_LABELS = _controls_.SL_MIN_MAX_LABELS
SL_VALUE_LABEL = _controls_.SL_VALUE_LABEL
SL_LABELS = _controls_.SL_LABELS
class Slider(_core.Control):
"""Proxy of C++ Slider class"""
thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
def __init__(self, *args, **kwargs):
"""
__init__(self, Window parent, int id=-1, int value=0, int minValue=0,
int maxValue=100, Point pos=DefaultPosition,
Size size=DefaultSize, long style=SL_HORIZONTAL,
Validator validator=DefaultValidator,
String name=SliderNameStr) -> Slider
"""
if kwargs.has_key('point'): kwargs['pos'] = kwargs['point'];del kwargs['point']
_controls_.Slider_swiginit(self,_controls_.new_Slider(*args, **kwargs))
self._setOORInfo(self)
def Create(*args, **kwargs):
"""
Create(self, Window parent, int id=-1, int value=0, int minValue=0,
int maxValue=100, Point pos=DefaultPosition,
Size size=DefaultSize, long style=SL_HORIZONTAL,
Validator validator=DefaultValidator,
String name=SliderNameStr) -> bool
"""
return _controls_.Slider_Create(*args, **kwargs)
def GetValue(*args, **kwargs):
"""GetValue(self) -> int"""
return _controls_.Slider_GetValue(*args, **kwargs)
def SetValue(*args, **kwargs):
"""SetValue(self, int value)"""
return _controls_.Slider_SetValue(*args, **kwargs)
def GetMin(*args, **kwargs):
"""GetMin(self) -> int"""
return _controls_.Slider_GetMin(*args, **kwargs)
def GetMax(*args, **kwargs):
"""GetMax(self) -> int"""
return _controls_.Slider_GetMax(*args, **kwargs)
def SetMin(*args, **kwargs):
"""SetMin(self, int minValue)"""
return _controls_.Slider_SetMin(*args, **kwargs)
def SetMax(*args, **kwargs):
"""SetMax(self, int maxValue)"""
return _controls_.Slider_SetMax(*args, **kwargs)
def SetRange(*args, **kwargs):
"""SetRange(self, int minValue, int maxValue)"""
return _controls_.Slider_SetRange(*args, **kwargs)
def GetRange(self):
return self.GetMin(), self.GetMax()
def SetLineSize(*args, **kwargs):
"""SetLineSize(self, int lineSize)"""
return _controls_.Slider_SetLineSize(*args, **kwargs)
def SetPageSize(*args, **kwargs):
"""SetPageSize(self, int pageSize)"""
return _controls_.Slider_SetPageSize(*args, **kwargs)
def GetLineSize(*args, **kwargs):
"""GetLineSize(self) -> int"""
return _controls_.Slider_GetLineSize(*args, **kwargs)
def GetPageSize(*args, **kwargs):
"""GetPageSize(self) -> int"""
return _controls_.Slider_GetPageSize(*args, **kwargs)
def SetThumbLength(*args, **kwargs):
"""SetThumbLength(self, int lenPixels)"""
return _controls_.Slider_SetThumbLength(*args, **kwargs)
def GetThumbLength(*args, **kwargs):
"""GetThumbLength(self) -> int"""
return _controls_.Slider_GetThumbLength(*args, **kwargs)
def SetTickFreq(*args, **kwargs):
"""SetTickFreq(self, int n, int pos=1)"""
return _controls_.Slider_SetTickFreq(*args, **kwargs)
def GetTickFreq(*args, **kwargs):
"""GetTickFreq(self) -> int"""
return _controls_.Slider_GetTickFreq(*args, **kwargs)
def ClearTicks(*args, **kwargs):
"""ClearTicks(self)"""
return _controls_.Slider_ClearTicks(*args, **kwargs)
def SetTick(*args, **kwargs):
"""SetTick(self, int tickPos)"""
return _controls_.Slider_SetTick(*args, **kwargs)
def ClearSel(*args, **kwargs):
"""ClearSel(self)"""
return _controls_.Slider_ClearSel(*args, **kwargs)
def GetSelEnd(*args, **kwargs):
"""GetSelEnd(self) -> int"""
return _controls_.Slider_GetSelEnd(*args, **kwargs)
def GetSelStart(*args, **kwargs):
"""GetSelStart(self) -> int"""
return _controls_.Slider_GetSelStart(*args, **kwargs)
def SetSelection(*args, **kwargs):
"""SetSelection(self, int min, int max)"""
return _controls_.Slider_SetSelection(*args, **kwargs)
def GetClassDefaultAttributes(*args, **kwargs):
"""
GetClassDefaultAttributes(int variant=WINDOW_VARIANT_NORMAL) -> VisualAttributes
Get the default attributes for this class. This is useful if you want
to use the same font or colour in your own control as in a standard
control -- which is a much better idea than hard coding specific
colours or fonts which might look completely out of place on the
user's system, especially if it uses themes.
The variant parameter is only relevant under Mac currently and is
ignore under other platforms. Under Mac, it will change the size of
the returned font. See `wx.Window.SetWindowVariant` for more about
this.
"""
return _controls_.Slider_GetClassDefaultAttributes(*args, **kwargs)
GetClassDefaultAttributes = staticmethod(GetClassDefaultAttributes)
LineSize = property(GetLineSize,SetLineSize,doc="See `GetLineSize` and `SetLineSize`")
Max = property(GetMax,SetMax,doc="See `GetMax` and `SetMax`")
Min = property(GetMin,SetMin,doc="See `GetMin` and `SetMin`")
PageSize = property(GetPageSize,SetPageSize,doc="See `GetPageSize` and `SetPageSize`")
SelEnd = property(GetSelEnd,doc="See `GetSelEnd`")
SelStart = property(GetSelStart,doc="See `GetSelStart`")
ThumbLength = property(GetThumbLength,SetThumbLength,doc="See `GetThumbLength` and `SetThumbLength`")
TickFreq = property(GetTickFreq,SetTickFreq,doc="See `GetTickFreq` and `SetTickFreq`")
Value = property(GetValue,SetValue,doc="See `GetValue` and `SetValue`")
_controls_.Slider_swigregister(Slider)
SliderNameStr = cvar.SliderNameStr
def PreSlider(*args, **kwargs):
"""PreSlider() -> Slider"""
val = _controls_.new_PreSlider(*args, **kwargs)
return val
def Slider_GetClassDefaultAttributes(*args, **kwargs):
"""
Slider_GetClassDefaultAttributes(int variant=WINDOW_VARIANT_NORMAL) -> VisualAttributes
Get the default attributes for this class. This is useful if you want
to use the same font or colour in your own control as in a standard
control -- which is a much better idea than hard coding specific
colours or fonts which might look completely out of place on the
user's system, especially if it uses themes.
The variant parameter is only relevant under Mac currently and is
ignore under other platforms. Under Mac, it will change the size of
the returned font. See `wx.Window.SetWindowVariant` for more about
this.
"""
return _controls_.Slider_GetClassDefaultAttributes(*args, **kwargs)
#---------------------------------------------------------------------------
wxEVT_COMMAND_TOGGLEBUTTON_CLICKED = _controls_.wxEVT_COMMAND_TOGGLEBUTTON_CLICKED
EVT_TOGGLEBUTTON = wx.PyEventBinder( wxEVT_COMMAND_TOGGLEBUTTON_CLICKED, 1)
class ToggleButton(AnyButton):
"""Proxy of C++ ToggleButton class"""
thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
def __init__(self, *args, **kwargs):
"""
__init__(self, Window parent, int id=-1, String label=EmptyString,
Point pos=DefaultPosition, Size size=DefaultSize,
long style=0, Validator validator=DefaultValidator,
String name=ToggleButtonNameStr) -> ToggleButton
"""
_controls_.ToggleButton_swiginit(self,_controls_.new_ToggleButton(*args, **kwargs))
self._setOORInfo(self)
def Create(*args, **kwargs):
"""
Create(self, Window parent, int id=-1, String label=EmptyString,
Point pos=DefaultPosition, Size size=DefaultSize,
long style=0, Validator validator=DefaultValidator,
String name=ToggleButtonNameStr) -> bool
"""
return _controls_.ToggleButton_Create(*args, **kwargs)
def SetValue(*args, **kwargs):
"""SetValue(self, bool value)"""
return _controls_.ToggleButton_SetValue(*args, **kwargs)
def GetValue(*args, **kwargs):
"""GetValue(self) -> bool"""
return _controls_.ToggleButton_GetValue(*args, **kwargs)
def GetClassDefaultAttributes(*args, **kwargs):
"""
GetClassDefaultAttributes(int variant=WINDOW_VARIANT_NORMAL) -> VisualAttributes
Get the default attributes for this class. This is useful if you want
to use the same font or colour in your own control as in a standard
control -- which is a much better idea than hard coding specific
colours or fonts which might look completely out of place on the
user's system, especially if it uses themes.
The variant parameter is only relevant under Mac currently and is
ignore under other platforms. Under Mac, it will change the size of
the returned font. See `wx.Window.SetWindowVariant` for more about
this.
"""
return _controls_.ToggleButton_GetClassDefaultAttributes(*args, **kwargs)
GetClassDefaultAttributes = staticmethod(GetClassDefaultAttributes)
Value = property(GetValue,SetValue,doc="See `GetValue` and `SetValue`")
_controls_.ToggleButton_swigregister(ToggleButton)
ToggleButtonNameStr = cvar.ToggleButtonNameStr
def PreToggleButton(*args, **kwargs):
"""PreToggleButton() -> ToggleButton"""
val = _controls_.new_PreToggleButton(*args, **kwargs)
return val
def ToggleButton_GetClassDefaultAttributes(*args, **kwargs):
"""
ToggleButton_GetClassDefaultAttributes(int variant=WINDOW_VARIANT_NORMAL) -> VisualAttributes
Get the default attributes for this class. This is useful if you want
to use the same font or colour in your own control as in a standard
control -- which is a much better idea than hard coding specific
colours or fonts which might look completely out of place on the
user's system, especially if it uses themes.
The variant parameter is only relevant under Mac currently and is
ignore under other platforms. Under Mac, it will change the size of
the returned font. See `wx.Window.SetWindowVariant` for more about
this.
"""
return _controls_.ToggleButton_GetClassDefaultAttributes(*args, **kwargs)
#---------------------------------------------------------------------------
NB_FIXEDWIDTH = _controls_.NB_FIXEDWIDTH
NB_TOP = _controls_.NB_TOP
NB_LEFT = _controls_.NB_LEFT
NB_RIGHT = _controls_.NB_RIGHT
NB_BOTTOM = _controls_.NB_BOTTOM
NB_MULTILINE = _controls_.NB_MULTILINE
NB_NOPAGETHEME = _controls_.NB_NOPAGETHEME
NB_HITTEST_NOWHERE = _controls_.NB_HITTEST_NOWHERE
NB_HITTEST_ONICON = _controls_.NB_HITTEST_ONICON
NB_HITTEST_ONLABEL = _controls_.NB_HITTEST_ONLABEL
NB_HITTEST_ONITEM = _controls_.NB_HITTEST_ONITEM
NB_HITTEST_ONPAGE = _controls_.NB_HITTEST_ONPAGE
class Notebook(_core.BookCtrlBase):
"""Proxy of C++ Notebook class"""
thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
def __init__(self, *args, **kwargs):
"""
__init__(self, Window parent, int id=-1, Point pos=DefaultPosition,
Size size=DefaultSize, long style=0, String name=NotebookNameStr) -> Notebook
"""
_controls_.Notebook_swiginit(self,_controls_.new_Notebook(*args, **kwargs))
self._setOORInfo(self)
def Create(*args, **kwargs):
"""
Create(self, Window parent, int id=-1, Point pos=DefaultPosition,
Size size=DefaultSize, long style=0, String name=NotebookNameStr) -> bool
"""
return _controls_.Notebook_Create(*args, **kwargs)
def GetRowCount(*args, **kwargs):
"""GetRowCount(self) -> int"""
return _controls_.Notebook_GetRowCount(*args, **kwargs)
def SetPadding(*args, **kwargs):
"""SetPadding(self, Size padding)"""
return _controls_.Notebook_SetPadding(*args, **kwargs)
def SetTabSize(*args, **kwargs):
"""SetTabSize(self, Size sz)"""
return _controls_.Notebook_SetTabSize(*args, **kwargs)
def GetThemeBackgroundColour(*args, **kwargs):
"""GetThemeBackgroundColour(self) -> Colour"""
return _controls_.Notebook_GetThemeBackgroundColour(*args, **kwargs)
def GetClassDefaultAttributes(*args, **kwargs):
"""
GetClassDefaultAttributes(int variant=WINDOW_VARIANT_NORMAL) -> VisualAttributes
Get the default attributes for this class. This is useful if you want
to use the same font or colour in your own control as in a standard
control -- which is a much better idea than hard coding specific
colours or fonts which might look completely out of place on the
user's system, especially if it uses themes.
The variant parameter is only relevant under Mac currently and is
ignore under other platforms. Under Mac, it will change the size of
the returned font. See `wx.Window.SetWindowVariant` for more about
this.
"""
return _controls_.Notebook_GetClassDefaultAttributes(*args, **kwargs)
GetClassDefaultAttributes = staticmethod(GetClassDefaultAttributes)
def SendPageChangingEvent(*args, **kwargs):
"""SendPageChangingEvent(self, int nPage) -> bool"""
return _controls_.Notebook_SendPageChangingEvent(*args, **kwargs)
def SendPageChangedEvent(*args, **kwargs):
"""SendPageChangedEvent(self, int nPageOld, int nPageNew=-1)"""
return _controls_.Notebook_SendPageChangedEvent(*args, **kwargs)
RowCount = property(GetRowCount,doc="See `GetRowCount`")
ThemeBackgroundColour = property(GetThemeBackgroundColour,doc="See `GetThemeBackgroundColour`")
_controls_.Notebook_swigregister(Notebook)
NotebookNameStr = cvar.NotebookNameStr
def PreNotebook(*args, **kwargs):
"""PreNotebook() -> Notebook"""
val = _controls_.new_PreNotebook(*args, **kwargs)
return val
def Notebook_GetClassDefaultAttributes(*args, **kwargs):
"""
Notebook_GetClassDefaultAttributes(int variant=WINDOW_VARIANT_NORMAL) -> VisualAttributes
Get the default attributes for this class. This is useful if you want
to use the same font or colour in your own control as in a standard
control -- which is a much better idea than hard coding specific
colours or fonts which might look completely out of place on the
user's system, especially if it uses themes.
The variant parameter is only relevant under Mac currently and is
ignore under other platforms. Under Mac, it will change the size of
the returned font. See `wx.Window.SetWindowVariant` for more about
this.
"""
return _controls_.Notebook_GetClassDefaultAttributes(*args, **kwargs)
NotebookEvent = wx.BookCtrlEvent
wxEVT_COMMAND_NOTEBOOK_PAGE_CHANGED = _controls_.wxEVT_COMMAND_NOTEBOOK_PAGE_CHANGED
wxEVT_COMMAND_NOTEBOOK_PAGE_CHANGING = _controls_.wxEVT_COMMAND_NOTEBOOK_PAGE_CHANGING
# wxNotebook events
EVT_NOTEBOOK_PAGE_CHANGED = wx.PyEventBinder( wxEVT_COMMAND_NOTEBOOK_PAGE_CHANGED, 1 )
EVT_NOTEBOOK_PAGE_CHANGING = wx.PyEventBinder( wxEVT_COMMAND_NOTEBOOK_PAGE_CHANGING, 1 )
#----------------------------------------------------------------------------
class NotebookPage(wx.Panel):
"""
There is an old (and apparently unsolvable) bug when placing a
window with a nonstandard background colour in a wx.Notebook on
wxGTK1, as the notbooks's background colour would always be used
when the window is refreshed. The solution is to place a panel in
the notbook and the coloured window on the panel, sized to cover
the panel. This simple class does that for you, just put an
instance of this in the notebook and make your regular window a
child of this one and it will handle the resize for you.
"""
def __init__(self, parent, id=-1,
pos=wx.DefaultPosition, size=wx.DefaultSize,
style=wx.TAB_TRAVERSAL, name="panel"):
wx.Panel.__init__(self, parent, id, pos, size, style, name)
self.child = None
self.Bind(wx.EVT_SIZE, self.OnSize)
def OnSize(self, evt):
if self.child is None:
children = self.GetChildren()
if len(children):
self.child = children[0]
if self.child:
self.child.SetPosition((0,0))
self.child.SetSize(self.GetSize())
#---------------------------------------------------------------------------
LB_DEFAULT = _controls_.LB_DEFAULT
LB_TOP = _controls_.LB_TOP
LB_BOTTOM = _controls_.LB_BOTTOM
LB_LEFT = _controls_.LB_LEFT
LB_RIGHT = _controls_.LB_RIGHT
LB_ALIGN_MASK = _controls_.LB_ALIGN_MASK
class Listbook(_core.BookCtrlBase):
"""Proxy of C++ Listbook class"""
thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
def __init__(self, *args, **kwargs):
"""
__init__(self, Window parent, int id=-1, Point pos=DefaultPosition,
Size size=DefaultSize, long style=0, String name=EmptyString) -> Listbook
"""
_controls_.Listbook_swiginit(self,_controls_.new_Listbook(*args, **kwargs))
self._setOORInfo(self)
def Create(*args, **kwargs):
"""
Create(self, Window parent, int id=-1, Point pos=DefaultPosition,
Size size=DefaultSize, long style=0, String name=EmptyString) -> bool
"""
return _controls_.Listbook_Create(*args, **kwargs)
def GetListView(*args, **kwargs):
"""GetListView(self) -> ListView"""
return _controls_.Listbook_GetListView(*args, **kwargs)
ListView = property(GetListView,doc="See `GetListView`")
_controls_.Listbook_swigregister(Listbook)
def PreListbook(*args, **kwargs):
"""PreListbook() -> Listbook"""
val = _controls_.new_PreListbook(*args, **kwargs)
return val
ListbookEvent = wx.BookCtrlEvent
wxEVT_COMMAND_LISTBOOK_PAGE_CHANGED = _controls_.wxEVT_COMMAND_LISTBOOK_PAGE_CHANGED
wxEVT_COMMAND_LISTBOOK_PAGE_CHANGING = _controls_.wxEVT_COMMAND_LISTBOOK_PAGE_CHANGING
EVT_LISTBOOK_PAGE_CHANGED = wx.PyEventBinder( wxEVT_COMMAND_LISTBOOK_PAGE_CHANGED, 1 )
EVT_LISTBOOK_PAGE_CHANGING = wx.PyEventBinder( wxEVT_COMMAND_LISTBOOK_PAGE_CHANGING, 1 )
CHB_DEFAULT = _controls_.CHB_DEFAULT
CHB_TOP = _controls_.CHB_TOP
CHB_BOTTOM = _controls_.CHB_BOTTOM
CHB_LEFT = _controls_.CHB_LEFT
CHB_RIGHT = _controls_.CHB_RIGHT
CHB_ALIGN_MASK = _controls_.CHB_ALIGN_MASK
class Choicebook(_core.BookCtrlBase):
"""Proxy of C++ Choicebook class"""
thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
def __init__(self, *args, **kwargs):
"""
__init__(self, Window parent, int id, Point pos=DefaultPosition, Size size=DefaultSize,
long style=0, String name=EmptyString) -> Choicebook
"""
_controls_.Choicebook_swiginit(self,_controls_.new_Choicebook(*args, **kwargs))
self._setOORInfo(self)
def Create(*args, **kwargs):
"""
Create(self, Window parent, int id, Point pos=DefaultPosition, Size size=DefaultSize,
long style=0, String name=EmptyString) -> bool
"""
return _controls_.Choicebook_Create(*args, **kwargs)
def GetChoiceCtrl(*args, **kwargs):
"""GetChoiceCtrl(self) -> Choice"""
return _controls_.Choicebook_GetChoiceCtrl(*args, **kwargs)
ChoiceCtrl = property(GetChoiceCtrl,doc="See `GetChoiceCtrl`")
_controls_.Choicebook_swigregister(Choicebook)
def PreChoicebook(*args, **kwargs):
"""PreChoicebook() -> Choicebook"""
val = _controls_.new_PreChoicebook(*args, **kwargs)
return val
ChoicebookEvent = wx.BookCtrlEvent
wxEVT_COMMAND_CHOICEBOOK_PAGE_CHANGED = _controls_.wxEVT_COMMAND_CHOICEBOOK_PAGE_CHANGED
wxEVT_COMMAND_CHOICEBOOK_PAGE_CHANGING = _controls_.wxEVT_COMMAND_CHOICEBOOK_PAGE_CHANGING
EVT_CHOICEBOOK_PAGE_CHANGED = wx.PyEventBinder( wxEVT_COMMAND_CHOICEBOOK_PAGE_CHANGED, 1 )
EVT_CHOICEBOOK_PAGE_CHANGING = wx.PyEventBinder( wxEVT_COMMAND_CHOICEBOOK_PAGE_CHANGING, 1 )
#---------------------------------------------------------------------------
class Treebook(_core.BookCtrlBase):
"""Proxy of C++ Treebook class"""
thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
def __init__(self, *args, **kwargs):
"""
__init__(self, Window parent, int id, Point pos=DefaultPosition, Size size=DefaultSize,
long style=BK_DEFAULT,
String name=EmptyString) -> Treebook
"""
_controls_.Treebook_swiginit(self,_controls_.new_Treebook(*args, **kwargs))
self._setOORInfo(self)
def Create(*args, **kwargs):
"""
Create(self, Window parent, int id, Point pos=DefaultPosition, Size size=DefaultSize,
long style=BK_DEFAULT,
String name=EmptyString) -> bool
"""
return _controls_.Treebook_Create(*args, **kwargs)
def InsertSubPage(*args, **kwargs):
"""
InsertSubPage(self, size_t pos, Window page, String text, bool select=False,
int imageId=NOT_FOUND) -> bool
"""
return _controls_.Treebook_InsertSubPage(*args, **kwargs)
def AddSubPage(*args, **kwargs):
"""AddSubPage(self, Window page, String text, bool select=False, int imageId=NOT_FOUND) -> bool"""
return _controls_.Treebook_AddSubPage(*args, **kwargs)
def IsNodeExpanded(*args, **kwargs):
"""IsNodeExpanded(self, size_t pos) -> bool"""
return _controls_.Treebook_IsNodeExpanded(*args, **kwargs)
def ExpandNode(*args, **kwargs):
"""ExpandNode(self, size_t pos, bool expand=True) -> bool"""
return _controls_.Treebook_ExpandNode(*args, **kwargs)
def CollapseNode(*args, **kwargs):
"""CollapseNode(self, size_t pos) -> bool"""
return _controls_.Treebook_CollapseNode(*args, **kwargs)
def GetPageParent(*args, **kwargs):
"""GetPageParent(self, size_t pos) -> int"""
return _controls_.Treebook_GetPageParent(*args, **kwargs)
def GetTreeCtrl(*args, **kwargs):
"""GetTreeCtrl(self) -> TreeCtrl"""
return _controls_.Treebook_GetTreeCtrl(*args, **kwargs)
TreeCtrl = property(GetTreeCtrl,doc="See `GetTreeCtrl`")
_controls_.Treebook_swigregister(Treebook)
def PreTreebook(*args, **kwargs):
"""PreTreebook() -> Treebook"""
val = _controls_.new_PreTreebook(*args, **kwargs)
return val
TreebookEvent = wx.BookCtrlEvent
wxEVT_COMMAND_TREEBOOK_PAGE_CHANGED = _controls_.wxEVT_COMMAND_TREEBOOK_PAGE_CHANGED
wxEVT_COMMAND_TREEBOOK_PAGE_CHANGING = _controls_.wxEVT_COMMAND_TREEBOOK_PAGE_CHANGING
wxEVT_COMMAND_TREEBOOK_NODE_COLLAPSED = _controls_.wxEVT_COMMAND_TREEBOOK_NODE_COLLAPSED
wxEVT_COMMAND_TREEBOOK_NODE_EXPANDED = _controls_.wxEVT_COMMAND_TREEBOOK_NODE_EXPANDED
EVT_TREEBOOK_PAGE_CHANGED = wx.PyEventBinder( wxEVT_COMMAND_TREEBOOK_PAGE_CHANGED, 1 )
EVT_TREEBOOK_PAGE_CHANGING = wx.PyEventBinder( wxEVT_COMMAND_TREEBOOK_PAGE_CHANGING, 1)
EVT_TREEBOOK_NODE_COLLAPSED = wx.PyEventBinder( wxEVT_COMMAND_TREEBOOK_NODE_COLLAPSED, 1 )
EVT_TREEBOOK_NODE_EXPANDED = wx.PyEventBinder( wxEVT_COMMAND_TREEBOOK_NODE_EXPANDED, 1 )
#---------------------------------------------------------------------------
class Toolbook(_core.BookCtrlBase):
"""Proxy of C++ Toolbook class"""
thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
def __init__(self, *args, **kwargs):
"""
__init__(self, Window parent, int id, Point pos=DefaultPosition, Size size=DefaultSize,
long style=BK_DEFAULT,
String name=EmptyString) -> Toolbook
"""
_controls_.Toolbook_swiginit(self,_controls_.new_Toolbook(*args, **kwargs))
self._setOORInfo(self)
def Create(*args, **kwargs):
"""
Create(self, Window parent, int id, Point pos=DefaultPosition, Size size=DefaultSize,
long style=0, String name=wxEmptyString) -> bool
"""
return _controls_.Toolbook_Create(*args, **kwargs)
def GetToolBar(*args, **kwargs):
"""GetToolBar(self) -> ToolBarBase"""
return _controls_.Toolbook_GetToolBar(*args, **kwargs)
def Realize(*args, **kwargs):
"""Realize(self)"""
return _controls_.Toolbook_Realize(*args, **kwargs)
ToolBar = property(GetToolBar,doc="See `GetToolBar`")
_controls_.Toolbook_swigregister(Toolbook)
def PreToolbook(*args, **kwargs):
"""PreToolbook() -> Toolbook"""
val = _controls_.new_PreToolbook(*args, **kwargs)
return val
ToolbookEvent = wx.BookCtrlEvent
wxEVT_COMMAND_TOOLBOOK_PAGE_CHANGED = _controls_.wxEVT_COMMAND_TOOLBOOK_PAGE_CHANGED
wxEVT_COMMAND_TOOLBOOK_PAGE_CHANGING = _controls_.wxEVT_COMMAND_TOOLBOOK_PAGE_CHANGING
EVT_TOOLBOOK_PAGE_CHANGED = wx.PyEventBinder( wxEVT_COMMAND_TOOLBOOK_PAGE_CHANGED, 1)
EVT_TOOLBOOK_PAGE_CHANGING = wx.PyEventBinder( wxEVT_COMMAND_TOOLBOOK_PAGE_CHANGING, 1)
#---------------------------------------------------------------------------
TOOL_STYLE_BUTTON = _controls_.TOOL_STYLE_BUTTON
TOOL_STYLE_SEPARATOR = _controls_.TOOL_STYLE_SEPARATOR
TOOL_STYLE_CONTROL = _controls_.TOOL_STYLE_CONTROL
TB_HORIZONTAL = _controls_.TB_HORIZONTAL
TB_VERTICAL = _controls_.TB_VERTICAL
TB_TOP = _controls_.TB_TOP
TB_LEFT = _controls_.TB_LEFT
TB_BOTTOM = _controls_.TB_BOTTOM
TB_RIGHT = _controls_.TB_RIGHT
TB_3DBUTTONS = _controls_.TB_3DBUTTONS
TB_FLAT = _controls_.TB_FLAT
TB_DOCKABLE = _controls_.TB_DOCKABLE
TB_NOICONS = _controls_.TB_NOICONS
TB_TEXT = _controls_.TB_TEXT
TB_NODIVIDER = _controls_.TB_NODIVIDER
TB_NOALIGN = _controls_.TB_NOALIGN
TB_HORZ_LAYOUT = _controls_.TB_HORZ_LAYOUT
TB_HORZ_TEXT = _controls_.TB_HORZ_TEXT
TB_NO_TOOLTIPS = _controls_.TB_NO_TOOLTIPS
class ToolBarToolBase(_core.Object):
"""Proxy of C++ ToolBarToolBase class"""
thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
def __init__(self): raise AttributeError, "No constructor defined"
__repr__ = _swig_repr
def GetId(*args, **kwargs):
"""GetId(self) -> int"""
return _controls_.ToolBarToolBase_GetId(*args, **kwargs)
def GetControl(*args, **kwargs):
"""GetControl(self) -> Control"""
return _controls_.ToolBarToolBase_GetControl(*args, **kwargs)
def GetToolBar(*args, **kwargs):
"""GetToolBar(self) -> ToolBarBase"""
return _controls_.ToolBarToolBase_GetToolBar(*args, **kwargs)
def IsStretchable(*args, **kwargs):
"""IsStretchable(self) -> bool"""
return _controls_.ToolBarToolBase_IsStretchable(*args, **kwargs)
def IsButton(*args, **kwargs):
"""IsButton(self) -> int"""
return _controls_.ToolBarToolBase_IsButton(*args, **kwargs)
def IsControl(*args, **kwargs):
"""IsControl(self) -> int"""
return _controls_.ToolBarToolBase_IsControl(*args, **kwargs)
def IsSeparator(*args, **kwargs):
"""IsSeparator(self) -> int"""
return _controls_.ToolBarToolBase_IsSeparator(*args, **kwargs)
def IsStretchableSpace(*args, **kwargs):
"""IsStretchableSpace(self) -> bool"""
return _controls_.ToolBarToolBase_IsStretchableSpace(*args, **kwargs)
def GetStyle(*args, **kwargs):
"""GetStyle(self) -> int"""
return _controls_.ToolBarToolBase_GetStyle(*args, **kwargs)
def GetKind(*args, **kwargs):
"""GetKind(self) -> int"""
return _controls_.ToolBarToolBase_GetKind(*args, **kwargs)
def MakeStretchable(*args, **kwargs):
"""MakeStretchable(self)"""
return _controls_.ToolBarToolBase_MakeStretchable(*args, **kwargs)
def IsEnabled(*args, **kwargs):
"""IsEnabled(self) -> bool"""
return _controls_.ToolBarToolBase_IsEnabled(*args, **kwargs)
def IsToggled(*args, **kwargs):
"""IsToggled(self) -> bool"""
return _controls_.ToolBarToolBase_IsToggled(*args, **kwargs)
def CanBeToggled(*args, **kwargs):
"""CanBeToggled(self) -> bool"""
return _controls_.ToolBarToolBase_CanBeToggled(*args, **kwargs)
def GetNormalBitmap(*args, **kwargs):
"""GetNormalBitmap(self) -> Bitmap"""
return _controls_.ToolBarToolBase_GetNormalBitmap(*args, **kwargs)
def GetDisabledBitmap(*args, **kwargs):
"""GetDisabledBitmap(self) -> Bitmap"""
return _controls_.ToolBarToolBase_GetDisabledBitmap(*args, **kwargs)
def GetBitmap(*args, **kwargs):
"""GetBitmap(self) -> Bitmap"""
return _controls_.ToolBarToolBase_GetBitmap(*args, **kwargs)
def GetLabel(*args, **kwargs):
"""GetLabel(self) -> String"""
return _controls_.ToolBarToolBase_GetLabel(*args, **kwargs)
def GetShortHelp(*args, **kwargs):
"""GetShortHelp(self) -> String"""
return _controls_.ToolBarToolBase_GetShortHelp(*args, **kwargs)
def GetLongHelp(*args, **kwargs):
"""GetLongHelp(self) -> String"""
return _controls_.ToolBarToolBase_GetLongHelp(*args, **kwargs)
def Enable(*args, **kwargs):
"""Enable(self, bool enable) -> bool"""
return _controls_.ToolBarToolBase_Enable(*args, **kwargs)
def Toggle(*args, **kwargs):
"""Toggle(self)"""
return _controls_.ToolBarToolBase_Toggle(*args, **kwargs)
def SetToggle(*args, **kwargs):
"""SetToggle(self, bool toggle) -> bool"""
return _controls_.ToolBarToolBase_SetToggle(*args, **kwargs)
def SetShortHelp(*args, **kwargs):
"""SetShortHelp(self, String help) -> bool"""
return _controls_.ToolBarToolBase_SetShortHelp(*args, **kwargs)
def SetLongHelp(*args, **kwargs):
"""SetLongHelp(self, String help) -> bool"""
return _controls_.ToolBarToolBase_SetLongHelp(*args, **kwargs)
def SetNormalBitmap(*args, **kwargs):
"""SetNormalBitmap(self, Bitmap bmp)"""
return _controls_.ToolBarToolBase_SetNormalBitmap(*args, **kwargs)
def SetDisabledBitmap(*args, **kwargs):
"""SetDisabledBitmap(self, Bitmap bmp)"""
return _controls_.ToolBarToolBase_SetDisabledBitmap(*args, **kwargs)
def SetLabel(*args, **kwargs):
"""SetLabel(self, String label)"""
return _controls_.ToolBarToolBase_SetLabel(*args, **kwargs)
def Detach(*args, **kwargs):
"""Detach(self)"""
return _controls_.ToolBarToolBase_Detach(*args, **kwargs)
def Attach(*args, **kwargs):
"""Attach(self, ToolBarBase tbar)"""
return _controls_.ToolBarToolBase_Attach(*args, **kwargs)
def SetDropdownMenu(*args, **kwargs):
"""SetDropdownMenu(self, Menu menu)"""
return _controls_.ToolBarToolBase_SetDropdownMenu(*args, **kwargs)
def GetDropdownMenu(*args, **kwargs):
"""GetDropdownMenu(self) -> Menu"""
return _controls_.ToolBarToolBase_GetDropdownMenu(*args, **kwargs)
def GetClientData(*args, **kwargs):
"""GetClientData(self) -> PyObject"""
return _controls_.ToolBarToolBase_GetClientData(*args, **kwargs)
def SetClientData(*args, **kwargs):
"""SetClientData(self, PyObject clientData)"""
return _controls_.ToolBarToolBase_SetClientData(*args, **kwargs)
GetBitmap1 = GetNormalBitmap
GetBitmap2 = GetDisabledBitmap
SetBitmap1 = SetNormalBitmap
SetBitmap2 = SetDisabledBitmap
Bitmap = property(GetBitmap,doc="See `GetBitmap`")
ClientData = property(GetClientData,SetClientData,doc="See `GetClientData` and `SetClientData`")
Control = property(GetControl,doc="See `GetControl`")
DisabledBitmap = property(GetDisabledBitmap,SetDisabledBitmap,doc="See `GetDisabledBitmap` and `SetDisabledBitmap`")
Id = property(GetId,doc="See `GetId`")
Kind = property(GetKind,doc="See `GetKind`")
Label = property(GetLabel,SetLabel,doc="See `GetLabel` and `SetLabel`")
LongHelp = property(GetLongHelp,SetLongHelp,doc="See `GetLongHelp` and `SetLongHelp`")
NormalBitmap = property(GetNormalBitmap,SetNormalBitmap,doc="See `GetNormalBitmap` and `SetNormalBitmap`")
ShortHelp = property(GetShortHelp,SetShortHelp,doc="See `GetShortHelp` and `SetShortHelp`")
Style = property(GetStyle,doc="See `GetStyle`")
ToolBar = property(GetToolBar,doc="See `GetToolBar`")
_controls_.ToolBarToolBase_swigregister(ToolBarToolBase)
class ToolBarBase(_core.Control):
"""Proxy of C++ ToolBarBase class"""
thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
def __init__(self): raise AttributeError, "No constructor defined"
__repr__ = _swig_repr
def DoAddTool(*args, **kwargs):
"""
DoAddTool(self, int id, String label, Bitmap bitmap, Bitmap bmpDisabled=wxNullBitmap,
int kind=ITEM_NORMAL, String shortHelp=EmptyString,
String longHelp=EmptyString,
PyObject clientData=None) -> ToolBarToolBase
"""
return _controls_.ToolBarBase_DoAddTool(*args, **kwargs)
def DoInsertTool(*args, **kwargs):
"""
DoInsertTool(self, size_t pos, int id, String label, Bitmap bitmap, Bitmap bmpDisabled=wxNullBitmap,
int kind=ITEM_NORMAL,
String shortHelp=EmptyString, String longHelp=EmptyString,
PyObject clientData=None) -> ToolBarToolBase
"""
return _controls_.ToolBarBase_DoInsertTool(*args, **kwargs)
# These match the original Add methods for this class, kept for
# backwards compatibility with versions < 2.3.3.
def AddTool(self, id, bitmap,
pushedBitmap = wx.NullBitmap,
isToggle = 0,
clientData = None,
shortHelpString = '',
longHelpString = '') :
'''Old style method to add a tool to the toolbar.'''
kind = wx.ITEM_NORMAL
if isToggle: kind = wx.ITEM_CHECK
return self.DoAddTool(id, '', bitmap, pushedBitmap, kind,
shortHelpString, longHelpString, clientData)
def AddSimpleTool(self, id, bitmap,
shortHelpString = '',
longHelpString = '',
isToggle = 0):
'''Old style method to add a tool to the toolbar.'''
kind = wx.ITEM_NORMAL
if isToggle: kind = wx.ITEM_CHECK
return self.DoAddTool(id, '', bitmap, wx.NullBitmap, kind,
shortHelpString, longHelpString, None)
def InsertTool(self, pos, id, bitmap,
pushedBitmap = wx.NullBitmap,
isToggle = 0,
clientData = None,
shortHelpString = '',
longHelpString = ''):
'''Old style method to insert a tool in the toolbar.'''
kind = wx.ITEM_NORMAL
if isToggle: kind = wx.ITEM_CHECK
return self.DoInsertTool(pos, id, '', bitmap, pushedBitmap, kind,
shortHelpString, longHelpString, clientData)
def InsertSimpleTool(self, pos, id, bitmap,
shortHelpString = '',
longHelpString = '',
isToggle = 0):
'''Old style method to insert a tool in the toolbar.'''
kind = wx.ITEM_NORMAL
if isToggle: kind = wx.ITEM_CHECK
return self.DoInsertTool(pos, id, '', bitmap, wx.NullBitmap, kind,
shortHelpString, longHelpString, None)
# The following are the new toolbar Add methods starting with
# 2.3.3. They are renamed to have 'Label' in the name so as to be
# able to keep backwards compatibility with using the above
# methods. Eventually these should migrate to be the methods used
# primarily and lose the 'Label' in the name...
def AddLabelTool(self, id, label, bitmap,
bmpDisabled = wx.NullBitmap,
kind = wx.ITEM_NORMAL,
shortHelp = '', longHelp = '',
clientData = None):
'''
The full AddTool() function.
If bmpDisabled is wx.NullBitmap, a shadowed version of the normal bitmap
is created and used as the disabled image.
'''
return self.DoAddTool(id, label, bitmap, bmpDisabled, kind,
shortHelp, longHelp, clientData)
def InsertLabelTool(self, pos, id, label, bitmap,
bmpDisabled = wx.NullBitmap,
kind = wx.ITEM_NORMAL,
shortHelp = '', longHelp = '',
clientData = None):
'''
Insert the new tool at the given position, if pos == GetToolsCount(), it
is equivalent to AddTool()
'''
return self.DoInsertTool(pos, id, label, bitmap, bmpDisabled, kind,
shortHelp, longHelp, clientData)
def AddCheckLabelTool(self, id, label, bitmap,
bmpDisabled = wx.NullBitmap,
shortHelp = '', longHelp = '',
clientData = None):
'''Add a check tool, i.e. a tool which can be toggled'''
return self.DoAddTool(id, label, bitmap, bmpDisabled, wx.ITEM_CHECK,
shortHelp, longHelp, clientData)
def AddRadioLabelTool(self, id, label, bitmap,
bmpDisabled = wx.NullBitmap,
shortHelp = '', longHelp = '',
clientData = None):
'''
Add a radio tool, i.e. a tool which can be toggled and releases any
other toggled radio tools in the same group when it happens
'''
return self.DoAddTool(id, label, bitmap, bmpDisabled, wx.ITEM_RADIO,
shortHelp, longHelp, clientData)
# For consistency with the backwards compatible methods above, here are
# some non-'Label' versions of the Check and Radio methods
def AddCheckTool(self, id, bitmap,
bmpDisabled = wx.NullBitmap,
shortHelp = '', longHelp = '',
clientData = None):
'''Add a check tool, i.e. a tool which can be toggled'''
return self.DoAddTool(id, '', bitmap, bmpDisabled, wx.ITEM_CHECK,
shortHelp, longHelp, clientData)
def AddRadioTool(self, id, bitmap,
bmpDisabled = wx.NullBitmap,
shortHelp = '', longHelp = '',
clientData = None):
'''
Add a radio tool, i.e. a tool which can be toggled and releases any
other toggled radio tools in the same group when it happens
'''
return self.DoAddTool(id, '', bitmap, bmpDisabled, wx.ITEM_RADIO,
shortHelp, longHelp, clientData)
def AddToolItem(*args, **kwargs):
"""AddToolItem(self, ToolBarToolBase tool) -> ToolBarToolBase"""
return _controls_.ToolBarBase_AddToolItem(*args, **kwargs)
def InsertToolItem(*args, **kwargs):
"""InsertToolItem(self, size_t pos, ToolBarToolBase tool) -> ToolBarToolBase"""
return _controls_.ToolBarBase_InsertToolItem(*args, **kwargs)
def AddControl(*args, **kwargs):
"""AddControl(self, Control control, String label=wxEmptyString) -> ToolBarToolBase"""
return _controls_.ToolBarBase_AddControl(*args, **kwargs)
def InsertControl(*args, **kwargs):
"""InsertControl(self, size_t pos, Control control, String label=wxEmptyString) -> ToolBarToolBase"""
return _controls_.ToolBarBase_InsertControl(*args, **kwargs)
def FindControl(*args, **kwargs):
"""FindControl(self, int id) -> Control"""
return _controls_.ToolBarBase_FindControl(*args, **kwargs)
def AddSeparator(*args, **kwargs):
"""AddSeparator(self) -> ToolBarToolBase"""
return _controls_.ToolBarBase_AddSeparator(*args, **kwargs)
def InsertSeparator(*args, **kwargs):
"""InsertSeparator(self, size_t pos) -> ToolBarToolBase"""
return _controls_.ToolBarBase_InsertSeparator(*args, **kwargs)
def AddStretchableSpace(*args, **kwargs):
"""AddStretchableSpace(self) -> ToolBarToolBase"""
return _controls_.ToolBarBase_AddStretchableSpace(*args, **kwargs)
def InsertStretchableSpace(*args, **kwargs):
"""InsertStretchableSpace(self, size_t pos) -> ToolBarToolBase"""
return _controls_.ToolBarBase_InsertStretchableSpace(*args, **kwargs)
def RemoveTool(*args, **kwargs):
"""RemoveTool(self, int id) -> ToolBarToolBase"""
return _controls_.ToolBarBase_RemoveTool(*args, **kwargs)
def DeleteToolByPos(*args, **kwargs):
"""DeleteToolByPos(self, size_t pos) -> bool"""
return _controls_.ToolBarBase_DeleteToolByPos(*args, **kwargs)
def DeleteTool(*args, **kwargs):
"""DeleteTool(self, int id) -> bool"""
return _controls_.ToolBarBase_DeleteTool(*args, **kwargs)
def ClearTools(*args, **kwargs):
"""ClearTools(self)"""
return _controls_.ToolBarBase_ClearTools(*args, **kwargs)
def Realize(*args, **kwargs):
"""Realize(self) -> bool"""
return _controls_.ToolBarBase_Realize(*args, **kwargs)
def EnableTool(*args, **kwargs):
"""EnableTool(self, int id, bool enable)"""
return _controls_.ToolBarBase_EnableTool(*args, **kwargs)
def ToggleTool(*args, **kwargs):
"""ToggleTool(self, int id, bool toggle)"""
return _controls_.ToolBarBase_ToggleTool(*args, **kwargs)
def SetToggle(*args, **kwargs):
"""SetToggle(self, int id, bool toggle)"""
return _controls_.ToolBarBase_SetToggle(*args, **kwargs)
def GetToolClientData(*args, **kwargs):
"""GetToolClientData(self, int id) -> PyObject"""
return _controls_.ToolBarBase_GetToolClientData(*args, **kwargs)
def SetToolClientData(*args, **kwargs):
"""SetToolClientData(self, int id, PyObject clientData)"""
return _controls_.ToolBarBase_SetToolClientData(*args, **kwargs)
def GetToolPos(*args, **kwargs):
"""GetToolPos(self, int id) -> int"""
return _controls_.ToolBarBase_GetToolPos(*args, **kwargs)
def GetToolState(*args, **kwargs):
"""GetToolState(self, int id) -> bool"""
return _controls_.ToolBarBase_GetToolState(*args, **kwargs)
def GetToolEnabled(*args, **kwargs):
"""GetToolEnabled(self, int id) -> bool"""
return _controls_.ToolBarBase_GetToolEnabled(*args, **kwargs)
def SetToolShortHelp(*args, **kwargs):
"""SetToolShortHelp(self, int id, String helpString)"""
return _controls_.ToolBarBase_SetToolShortHelp(*args, **kwargs)
def GetToolShortHelp(*args, **kwargs):
"""GetToolShortHelp(self, int id) -> String"""
return _controls_.ToolBarBase_GetToolShortHelp(*args, **kwargs)
def SetToolLongHelp(*args, **kwargs):
"""SetToolLongHelp(self, int id, String helpString)"""
return _controls_.ToolBarBase_SetToolLongHelp(*args, **kwargs)
def GetToolLongHelp(*args, **kwargs):
"""GetToolLongHelp(self, int id) -> String"""
return _controls_.ToolBarBase_GetToolLongHelp(*args, **kwargs)
def SetMarginsXY(*args, **kwargs):
"""SetMarginsXY(self, int x, int y)"""
return _controls_.ToolBarBase_SetMarginsXY(*args, **kwargs)
def SetMargins(*args, **kwargs):
"""SetMargins(self, Size size)"""
return _controls_.ToolBarBase_SetMargins(*args, **kwargs)
def SetToolPacking(*args, **kwargs):
"""SetToolPacking(self, int packing)"""
return _controls_.ToolBarBase_SetToolPacking(*args, **kwargs)
def SetToolSeparation(*args, **kwargs):
"""SetToolSeparation(self, int separation)"""
return _controls_.ToolBarBase_SetToolSeparation(*args, **kwargs)
def GetToolMargins(*args, **kwargs):
"""GetToolMargins(self) -> Size"""
return _controls_.ToolBarBase_GetToolMargins(*args, **kwargs)
def GetMargins(*args, **kwargs):
"""GetMargins(self) -> Size"""
return _controls_.ToolBarBase_GetMargins(*args, **kwargs)
def GetToolPacking(*args, **kwargs):
"""GetToolPacking(self) -> int"""
return _controls_.ToolBarBase_GetToolPacking(*args, **kwargs)
def GetToolSeparation(*args, **kwargs):
"""GetToolSeparation(self) -> int"""
return _controls_.ToolBarBase_GetToolSeparation(*args, **kwargs)
def SetRows(*args, **kwargs):
"""SetRows(self, int nRows)"""
return _controls_.ToolBarBase_SetRows(*args, **kwargs)
def SetMaxRowsCols(*args, **kwargs):
"""SetMaxRowsCols(self, int rows, int cols)"""
return _controls_.ToolBarBase_SetMaxRowsCols(*args, **kwargs)
def GetMaxRows(*args, **kwargs):
"""GetMaxRows(self) -> int"""
return _controls_.ToolBarBase_GetMaxRows(*args, **kwargs)
def GetMaxCols(*args, **kwargs):
"""GetMaxCols(self) -> int"""
return _controls_.ToolBarBase_GetMaxCols(*args, **kwargs)
def SetToolBitmapSize(*args, **kwargs):
"""SetToolBitmapSize(self, Size size)"""
return _controls_.ToolBarBase_SetToolBitmapSize(*args, **kwargs)
def GetToolBitmapSize(*args, **kwargs):
"""GetToolBitmapSize(self) -> Size"""
return _controls_.ToolBarBase_GetToolBitmapSize(*args, **kwargs)
def GetToolSize(*args, **kwargs):
"""GetToolSize(self) -> Size"""
return _controls_.ToolBarBase_GetToolSize(*args, **kwargs)
def FindToolForPosition(*args, **kwargs):
"""FindToolForPosition(self, int x, int y) -> ToolBarToolBase"""
return _controls_.ToolBarBase_FindToolForPosition(*args, **kwargs)
def FindById(*args, **kwargs):
"""FindById(self, int toolid) -> ToolBarToolBase"""
return _controls_.ToolBarBase_FindById(*args, **kwargs)
def IsVertical(*args, **kwargs):
"""IsVertical(self) -> bool"""
return _controls_.ToolBarBase_IsVertical(*args, **kwargs)
def GetToolsCount(*args, **kwargs):
"""GetToolsCount(self) -> size_t"""
return _controls_.ToolBarBase_GetToolsCount(*args, **kwargs)
def GetToolByPos(*args, **kwargs):
"""GetToolByPos(self, int pos) -> ToolBarToolBase"""
return _controls_.ToolBarBase_GetToolByPos(*args, **kwargs)
def SetDropdownMenu(*args, **kwargs):
"""SetDropdownMenu(self, int toolid, Menu menu) -> bool"""
return _controls_.ToolBarBase_SetDropdownMenu(*args, **kwargs)
Margins = property(GetMargins,SetMargins,doc="See `GetMargins` and `SetMargins`")
MaxCols = property(GetMaxCols,doc="See `GetMaxCols`")
MaxRows = property(GetMaxRows,doc="See `GetMaxRows`")
ToolBitmapSize = property(GetToolBitmapSize,SetToolBitmapSize,doc="See `GetToolBitmapSize` and `SetToolBitmapSize`")
ToolMargins = property(GetToolMargins,doc="See `GetToolMargins`")
ToolPacking = property(GetToolPacking,SetToolPacking,doc="See `GetToolPacking` and `SetToolPacking`")
ToolSeparation = property(GetToolSeparation,SetToolSeparation,doc="See `GetToolSeparation` and `SetToolSeparation`")
ToolSize = property(GetToolSize,doc="See `GetToolSize`")
ToolsCount = property(GetToolsCount,doc="See `GetToolsCount`")
_controls_.ToolBarBase_swigregister(ToolBarBase)
class ToolBar(ToolBarBase):
"""Proxy of C++ ToolBar class"""
thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
def __init__(self, *args, **kwargs):
"""
__init__(self, Window parent, int id=-1, Point pos=DefaultPosition,
Size size=DefaultSize, long style=wxNO_BORDER|wxTB_HORIZONTAL,
String name=wxPyToolBarNameStr) -> ToolBar
"""
_controls_.ToolBar_swiginit(self,_controls_.new_ToolBar(*args, **kwargs))
self._setOORInfo(self)
def Create(*args, **kwargs):
"""
Create(self, Window parent, int id=-1, Point pos=DefaultPosition,
Size size=DefaultSize, long style=wxNO_BORDER|wxTB_HORIZONTAL,
String name=wxPyToolBarNameStr) -> bool
"""
return _controls_.ToolBar_Create(*args, **kwargs)
def SetToolNormalBitmap(*args, **kwargs):
"""SetToolNormalBitmap(self, int id, Bitmap bitmap)"""
return _controls_.ToolBar_SetToolNormalBitmap(*args, **kwargs)
def SetToolDisabledBitmap(*args, **kwargs):
"""SetToolDisabledBitmap(self, int id, Bitmap bitmap)"""
return _controls_.ToolBar_SetToolDisabledBitmap(*args, **kwargs)
def GetClassDefaultAttributes(*args, **kwargs):
"""
GetClassDefaultAttributes(int variant=WINDOW_VARIANT_NORMAL) -> VisualAttributes
Get the default attributes for this class. This is useful if you want
to use the same font or colour in your own control as in a standard
control -- which is a much better idea than hard coding specific
colours or fonts which might look completely out of place on the
user's system, especially if it uses themes.
The variant parameter is only relevant under Mac currently and is
ignore under other platforms. Under Mac, it will change the size of
the returned font. See `wx.Window.SetWindowVariant` for more about
this.
"""
return _controls_.ToolBar_GetClassDefaultAttributes(*args, **kwargs)
GetClassDefaultAttributes = staticmethod(GetClassDefaultAttributes)
_controls_.ToolBar_swigregister(ToolBar)
def PreToolBar(*args, **kwargs):
"""PreToolBar() -> ToolBar"""
val = _controls_.new_PreToolBar(*args, **kwargs)
return val
def ToolBar_GetClassDefaultAttributes(*args, **kwargs):
"""
ToolBar_GetClassDefaultAttributes(int variant=WINDOW_VARIANT_NORMAL) -> VisualAttributes
Get the default attributes for this class. This is useful if you want
to use the same font or colour in your own control as in a standard
control -- which is a much better idea than hard coding specific
colours or fonts which might look completely out of place on the
user's system, especially if it uses themes.
The variant parameter is only relevant under Mac currently and is
ignore under other platforms. Under Mac, it will change the size of
the returned font. See `wx.Window.SetWindowVariant` for more about
this.
"""
return _controls_.ToolBar_GetClassDefaultAttributes(*args, **kwargs)
#---------------------------------------------------------------------------
LC_VRULES = _controls_.LC_VRULES
LC_HRULES = _controls_.LC_HRULES
LC_ICON = _controls_.LC_ICON
LC_SMALL_ICON = _controls_.LC_SMALL_ICON
LC_LIST = _controls_.LC_LIST
LC_REPORT = _controls_.LC_REPORT
LC_ALIGN_TOP = _controls_.LC_ALIGN_TOP
LC_ALIGN_LEFT = _controls_.LC_ALIGN_LEFT
LC_AUTOARRANGE = _controls_.LC_AUTOARRANGE
LC_VIRTUAL = _controls_.LC_VIRTUAL
LC_EDIT_LABELS = _controls_.LC_EDIT_LABELS
LC_NO_HEADER = _controls_.LC_NO_HEADER
LC_NO_SORT_HEADER = _controls_.LC_NO_SORT_HEADER
LC_SINGLE_SEL = _controls_.LC_SINGLE_SEL
LC_SORT_ASCENDING = _controls_.LC_SORT_ASCENDING
LC_SORT_DESCENDING = _controls_.LC_SORT_DESCENDING
LC_MASK_TYPE = _controls_.LC_MASK_TYPE
LC_MASK_ALIGN = _controls_.LC_MASK_ALIGN
LC_MASK_SORT = _controls_.LC_MASK_SORT
LIST_MASK_STATE = _controls_.LIST_MASK_STATE
LIST_MASK_TEXT = _controls_.LIST_MASK_TEXT
LIST_MASK_IMAGE = _controls_.LIST_MASK_IMAGE
LIST_MASK_DATA = _controls_.LIST_MASK_DATA
LIST_SET_ITEM = _controls_.LIST_SET_ITEM
LIST_MASK_WIDTH = _controls_.LIST_MASK_WIDTH
LIST_MASK_FORMAT = _controls_.LIST_MASK_FORMAT
LIST_STATE_DONTCARE = _controls_.LIST_STATE_DONTCARE
LIST_STATE_DROPHILITED = _controls_.LIST_STATE_DROPHILITED
LIST_STATE_FOCUSED = _controls_.LIST_STATE_FOCUSED
LIST_STATE_SELECTED = _controls_.LIST_STATE_SELECTED
LIST_STATE_CUT = _controls_.LIST_STATE_CUT
LIST_STATE_DISABLED = _controls_.LIST_STATE_DISABLED
LIST_STATE_FILTERED = _controls_.LIST_STATE_FILTERED
LIST_STATE_INUSE = _controls_.LIST_STATE_INUSE
LIST_STATE_PICKED = _controls_.LIST_STATE_PICKED
LIST_STATE_SOURCE = _controls_.LIST_STATE_SOURCE
LIST_HITTEST_ABOVE = _controls_.LIST_HITTEST_ABOVE
LIST_HITTEST_BELOW = _controls_.LIST_HITTEST_BELOW
LIST_HITTEST_NOWHERE = _controls_.LIST_HITTEST_NOWHERE
LIST_HITTEST_ONITEMICON = _controls_.LIST_HITTEST_ONITEMICON
LIST_HITTEST_ONITEMLABEL = _controls_.LIST_HITTEST_ONITEMLABEL
LIST_HITTEST_ONITEMRIGHT = _controls_.LIST_HITTEST_ONITEMRIGHT
LIST_HITTEST_ONITEMSTATEICON = _controls_.LIST_HITTEST_ONITEMSTATEICON
LIST_HITTEST_TOLEFT = _controls_.LIST_HITTEST_TOLEFT
LIST_HITTEST_TORIGHT = _controls_.LIST_HITTEST_TORIGHT
LIST_HITTEST_ONITEM = _controls_.LIST_HITTEST_ONITEM
LIST_GETSUBITEMRECT_WHOLEITEM = _controls_.LIST_GETSUBITEMRECT_WHOLEITEM
LIST_NEXT_ABOVE = _controls_.LIST_NEXT_ABOVE
LIST_NEXT_ALL = _controls_.LIST_NEXT_ALL
LIST_NEXT_BELOW = _controls_.LIST_NEXT_BELOW
LIST_NEXT_LEFT = _controls_.LIST_NEXT_LEFT
LIST_NEXT_RIGHT = _controls_.LIST_NEXT_RIGHT
LIST_ALIGN_DEFAULT = _controls_.LIST_ALIGN_DEFAULT
LIST_ALIGN_LEFT = _controls_.LIST_ALIGN_LEFT
LIST_ALIGN_TOP = _controls_.LIST_ALIGN_TOP
LIST_ALIGN_SNAP_TO_GRID = _controls_.LIST_ALIGN_SNAP_TO_GRID
LIST_FORMAT_LEFT = _controls_.LIST_FORMAT_LEFT
LIST_FORMAT_RIGHT = _controls_.LIST_FORMAT_RIGHT
LIST_FORMAT_CENTRE = _controls_.LIST_FORMAT_CENTRE
LIST_FORMAT_CENTER = _controls_.LIST_FORMAT_CENTER
LIST_AUTOSIZE = _controls_.LIST_AUTOSIZE
LIST_AUTOSIZE_USEHEADER = _controls_.LIST_AUTOSIZE_USEHEADER
LIST_RECT_BOUNDS = _controls_.LIST_RECT_BOUNDS
LIST_RECT_ICON = _controls_.LIST_RECT_ICON
LIST_RECT_LABEL = _controls_.LIST_RECT_LABEL
LIST_FIND_UP = _controls_.LIST_FIND_UP
LIST_FIND_DOWN = _controls_.LIST_FIND_DOWN
LIST_FIND_LEFT = _controls_.LIST_FIND_LEFT
LIST_FIND_RIGHT = _controls_.LIST_FIND_RIGHT
#---------------------------------------------------------------------------
class ListItemAttr(object):
"""Proxy of C++ ListItemAttr class"""
thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
def __init__(self, *args, **kwargs):
"""
__init__(self, Colour colText=wxNullColour, Colour colBack=wxNullColour,
Font font=wxNullFont) -> ListItemAttr
"""
_controls_.ListItemAttr_swiginit(self,_controls_.new_ListItemAttr(*args, **kwargs))
__swig_destroy__ = _controls_.delete_ListItemAttr
__del__ = lambda self : None;
def SetTextColour(*args, **kwargs):
"""SetTextColour(self, Colour colText)"""
return _controls_.ListItemAttr_SetTextColour(*args, **kwargs)
def SetBackgroundColour(*args, **kwargs):
"""SetBackgroundColour(self, Colour colBack)"""
return _controls_.ListItemAttr_SetBackgroundColour(*args, **kwargs)
def SetFont(*args, **kwargs):
"""SetFont(self, Font font)"""
return _controls_.ListItemAttr_SetFont(*args, **kwargs)
def HasTextColour(*args, **kwargs):
"""HasTextColour(self) -> bool"""
return _controls_.ListItemAttr_HasTextColour(*args, **kwargs)
def HasBackgroundColour(*args, **kwargs):
"""HasBackgroundColour(self) -> bool"""
return _controls_.ListItemAttr_HasBackgroundColour(*args, **kwargs)
def HasFont(*args, **kwargs):
"""HasFont(self) -> bool"""
return _controls_.ListItemAttr_HasFont(*args, **kwargs)
def GetTextColour(*args, **kwargs):
"""GetTextColour(self) -> Colour"""
return _controls_.ListItemAttr_GetTextColour(*args, **kwargs)
def GetBackgroundColour(*args, **kwargs):
"""GetBackgroundColour(self) -> Colour"""
return _controls_.ListItemAttr_GetBackgroundColour(*args, **kwargs)
def GetFont(*args, **kwargs):
"""GetFont(self) -> Font"""
return _controls_.ListItemAttr_GetFont(*args, **kwargs)
def AssignFrom(*args, **kwargs):
"""AssignFrom(self, ListItemAttr source)"""
return _controls_.ListItemAttr_AssignFrom(*args, **kwargs)
def Destroy(*args, **kwargs):
"""Destroy(self)"""
args[0].this.own(False)
return _controls_.ListItemAttr_Destroy(*args, **kwargs)
BackgroundColour = property(GetBackgroundColour,SetBackgroundColour,doc="See `GetBackgroundColour` and `SetBackgroundColour`")
Font = property(GetFont,SetFont,doc="See `GetFont` and `SetFont`")
TextColour = property(GetTextColour,SetTextColour,doc="See `GetTextColour` and `SetTextColour`")
_controls_.ListItemAttr_swigregister(ListItemAttr)
ListCtrlNameStr = cvar.ListCtrlNameStr
#---------------------------------------------------------------------------
class ListItem(_core.Object):
"""Proxy of C++ ListItem class"""
thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
def __init__(self, *args, **kwargs):
"""__init__(self) -> ListItem"""
_controls_.ListItem_swiginit(self,_controls_.new_ListItem(*args, **kwargs))
__swig_destroy__ = _controls_.delete_ListItem
__del__ = lambda self : None;
def Clear(*args, **kwargs):
"""Clear(self)"""
return _controls_.ListItem_Clear(*args, **kwargs)
def ClearAttributes(*args, **kwargs):
"""ClearAttributes(self)"""
return _controls_.ListItem_ClearAttributes(*args, **kwargs)
def SetMask(*args, **kwargs):
"""SetMask(self, long mask)"""
return _controls_.ListItem_SetMask(*args, **kwargs)
def SetId(*args, **kwargs):
"""SetId(self, long id)"""
return _controls_.ListItem_SetId(*args, **kwargs)
def SetColumn(*args, **kwargs):
"""SetColumn(self, int col)"""
return _controls_.ListItem_SetColumn(*args, **kwargs)
def SetState(*args, **kwargs):
"""SetState(self, long state)"""
return _controls_.ListItem_SetState(*args, **kwargs)
def SetStateMask(*args, **kwargs):
"""SetStateMask(self, long stateMask)"""
return _controls_.ListItem_SetStateMask(*args, **kwargs)
def SetText(*args, **kwargs):
"""SetText(self, String text)"""
return _controls_.ListItem_SetText(*args, **kwargs)
def SetImage(*args, **kwargs):
"""SetImage(self, int image)"""
return _controls_.ListItem_SetImage(*args, **kwargs)
def SetData(*args, **kwargs):
"""SetData(self, long data)"""
return _controls_.ListItem_SetData(*args, **kwargs)
def SetWidth(*args, **kwargs):
"""SetWidth(self, int width)"""
return _controls_.ListItem_SetWidth(*args, **kwargs)
def SetAlign(*args, **kwargs):
"""SetAlign(self, int align)"""
return _controls_.ListItem_SetAlign(*args, **kwargs)
def SetTextColour(*args, **kwargs):
"""SetTextColour(self, Colour colText)"""
return _controls_.ListItem_SetTextColour(*args, **kwargs)
def SetBackgroundColour(*args, **kwargs):
"""SetBackgroundColour(self, Colour colBack)"""
return _controls_.ListItem_SetBackgroundColour(*args, **kwargs)
def SetFont(*args, **kwargs):
"""SetFont(self, Font font)"""
return _controls_.ListItem_SetFont(*args, **kwargs)
def GetMask(*args, **kwargs):
"""GetMask(self) -> long"""
return _controls_.ListItem_GetMask(*args, **kwargs)
def GetId(*args, **kwargs):
"""GetId(self) -> long"""
return _controls_.ListItem_GetId(*args, **kwargs)
def GetColumn(*args, **kwargs):
"""GetColumn(self) -> int"""
return _controls_.ListItem_GetColumn(*args, **kwargs)
def GetState(*args, **kwargs):
"""GetState(self) -> long"""
return _controls_.ListItem_GetState(*args, **kwargs)
def GetText(*args, **kwargs):
"""GetText(self) -> String"""
return _controls_.ListItem_GetText(*args, **kwargs)
def GetImage(*args, **kwargs):
"""GetImage(self) -> int"""
return _controls_.ListItem_GetImage(*args, **kwargs)
def GetData(*args, **kwargs):
"""GetData(self) -> long"""
return _controls_.ListItem_GetData(*args, **kwargs)
def GetWidth(*args, **kwargs):
"""GetWidth(self) -> int"""
return _controls_.ListItem_GetWidth(*args, **kwargs)
def GetAlign(*args, **kwargs):
"""GetAlign(self) -> int"""
return _controls_.ListItem_GetAlign(*args, **kwargs)
def GetAttributes(*args, **kwargs):
"""GetAttributes(self) -> ListItemAttr"""
return _controls_.ListItem_GetAttributes(*args, **kwargs)
def HasAttributes(*args, **kwargs):
"""HasAttributes(self) -> bool"""
return _controls_.ListItem_HasAttributes(*args, **kwargs)
def GetTextColour(*args, **kwargs):
"""GetTextColour(self) -> Colour"""
return _controls_.ListItem_GetTextColour(*args, **kwargs)
def GetBackgroundColour(*args, **kwargs):
"""GetBackgroundColour(self) -> Colour"""
return _controls_.ListItem_GetBackgroundColour(*args, **kwargs)
def GetFont(*args, **kwargs):
"""GetFont(self) -> Font"""
return _controls_.ListItem_GetFont(*args, **kwargs)
m_mask = property(_controls_.ListItem_m_mask_get, _controls_.ListItem_m_mask_set)
m_itemId = property(_controls_.ListItem_m_itemId_get, _controls_.ListItem_m_itemId_set)
m_col = property(_controls_.ListItem_m_col_get, _controls_.ListItem_m_col_set)
m_state = property(_controls_.ListItem_m_state_get, _controls_.ListItem_m_state_set)
m_stateMask = property(_controls_.ListItem_m_stateMask_get, _controls_.ListItem_m_stateMask_set)
m_text = property(_controls_.ListItem_m_text_get, _controls_.ListItem_m_text_set)
m_image = property(_controls_.ListItem_m_image_get, _controls_.ListItem_m_image_set)
m_data = property(_controls_.ListItem_m_data_get, _controls_.ListItem_m_data_set)
m_format = property(_controls_.ListItem_m_format_get, _controls_.ListItem_m_format_set)
m_width = property(_controls_.ListItem_m_width_get, _controls_.ListItem_m_width_set)
Align = property(GetAlign,SetAlign,doc="See `GetAlign` and `SetAlign`")
Attributes = property(GetAttributes,doc="See `GetAttributes`")
BackgroundColour = property(GetBackgroundColour,SetBackgroundColour,doc="See `GetBackgroundColour` and `SetBackgroundColour`")
Column = property(GetColumn,SetColumn,doc="See `GetColumn` and `SetColumn`")
Data = property(GetData,SetData,doc="See `GetData` and `SetData`")
Font = property(GetFont,SetFont,doc="See `GetFont` and `SetFont`")
Id = property(GetId,SetId,doc="See `GetId` and `SetId`")
Image = property(GetImage,SetImage,doc="See `GetImage` and `SetImage`")
Mask = property(GetMask,SetMask,doc="See `GetMask` and `SetMask`")
State = property(GetState,SetState,doc="See `GetState` and `SetState`")
Text = property(GetText,SetText,doc="See `GetText` and `SetText`")
TextColour = property(GetTextColour,SetTextColour,doc="See `GetTextColour` and `SetTextColour`")
Width = property(GetWidth,SetWidth,doc="See `GetWidth` and `SetWidth`")
_controls_.ListItem_swigregister(ListItem)
#---------------------------------------------------------------------------
class ListEvent(_core.NotifyEvent):
"""Proxy of C++ ListEvent class"""
thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
def __init__(self, *args, **kwargs):
"""__init__(self, EventType commandType=wxEVT_NULL, int id=0) -> ListEvent"""
_controls_.ListEvent_swiginit(self,_controls_.new_ListEvent(*args, **kwargs))
m_code = property(_controls_.ListEvent_m_code_get, _controls_.ListEvent_m_code_set)
m_oldItemIndex = property(_controls_.ListEvent_m_oldItemIndex_get, _controls_.ListEvent_m_oldItemIndex_set)
m_itemIndex = property(_controls_.ListEvent_m_itemIndex_get, _controls_.ListEvent_m_itemIndex_set)
m_col = property(_controls_.ListEvent_m_col_get, _controls_.ListEvent_m_col_set)
m_pointDrag = property(_controls_.ListEvent_m_pointDrag_get, _controls_.ListEvent_m_pointDrag_set)
m_item = property(_controls_.ListEvent_m_item_get)
def GetKeyCode(*args, **kwargs):
"""GetKeyCode(self) -> int"""
return _controls_.ListEvent_GetKeyCode(*args, **kwargs)
GetCode = GetKeyCode
def GetIndex(*args, **kwargs):
"""GetIndex(self) -> long"""
return _controls_.ListEvent_GetIndex(*args, **kwargs)
def GetColumn(*args, **kwargs):
"""GetColumn(self) -> int"""
return _controls_.ListEvent_GetColumn(*args, **kwargs)
def GetPoint(*args, **kwargs):
"""GetPoint(self) -> Point"""
return _controls_.ListEvent_GetPoint(*args, **kwargs)
GetPosition = GetPoint
def GetLabel(*args, **kwargs):
"""GetLabel(self) -> String"""
return _controls_.ListEvent_GetLabel(*args, **kwargs)
def GetText(*args, **kwargs):
"""GetText(self) -> String"""
return _controls_.ListEvent_GetText(*args, **kwargs)
def GetImage(*args, **kwargs):
"""GetImage(self) -> int"""
return _controls_.ListEvent_GetImage(*args, **kwargs)
def GetData(*args, **kwargs):
"""GetData(self) -> long"""
return _controls_.ListEvent_GetData(*args, **kwargs)
def GetMask(*args, **kwargs):
"""GetMask(self) -> long"""
return _controls_.ListEvent_GetMask(*args, **kwargs)
def GetItem(*args, **kwargs):
"""GetItem(self) -> ListItem"""
return _controls_.ListEvent_GetItem(*args, **kwargs)
def GetCacheFrom(*args, **kwargs):
"""GetCacheFrom(self) -> long"""
return _controls_.ListEvent_GetCacheFrom(*args, **kwargs)
def GetCacheTo(*args, **kwargs):
"""GetCacheTo(self) -> long"""
return _controls_.ListEvent_GetCacheTo(*args, **kwargs)
def IsEditCancelled(*args, **kwargs):
"""IsEditCancelled(self) -> bool"""
return _controls_.ListEvent_IsEditCancelled(*args, **kwargs)
def SetEditCanceled(*args, **kwargs):
"""SetEditCanceled(self, bool editCancelled)"""
return _controls_.ListEvent_SetEditCanceled(*args, **kwargs)
CacheFrom = property(GetCacheFrom,doc="See `GetCacheFrom`")
CacheTo = property(GetCacheTo,doc="See `GetCacheTo`")
Column = property(GetColumn,doc="See `GetColumn`")
Data = property(GetData,doc="See `GetData`")
Image = property(GetImage,doc="See `GetImage`")
Index = property(GetIndex,doc="See `GetIndex`")
Item = property(GetItem,doc="See `GetItem`")
KeyCode = property(GetKeyCode,doc="See `GetKeyCode`")
Label = property(GetLabel,doc="See `GetLabel`")
Mask = property(GetMask,doc="See `GetMask`")
Point = property(GetPoint,doc="See `GetPoint`")
Text = property(GetText,doc="See `GetText`")
_controls_.ListEvent_swigregister(ListEvent)
wxEVT_COMMAND_LIST_BEGIN_DRAG = _controls_.wxEVT_COMMAND_LIST_BEGIN_DRAG
wxEVT_COMMAND_LIST_BEGIN_RDRAG = _controls_.wxEVT_COMMAND_LIST_BEGIN_RDRAG
wxEVT_COMMAND_LIST_BEGIN_LABEL_EDIT = _controls_.wxEVT_COMMAND_LIST_BEGIN_LABEL_EDIT
wxEVT_COMMAND_LIST_END_LABEL_EDIT = _controls_.wxEVT_COMMAND_LIST_END_LABEL_EDIT
wxEVT_COMMAND_LIST_DELETE_ITEM = _controls_.wxEVT_COMMAND_LIST_DELETE_ITEM
wxEVT_COMMAND_LIST_DELETE_ALL_ITEMS = _controls_.wxEVT_COMMAND_LIST_DELETE_ALL_ITEMS
wxEVT_COMMAND_LIST_ITEM_SELECTED = _controls_.wxEVT_COMMAND_LIST_ITEM_SELECTED
wxEVT_COMMAND_LIST_ITEM_DESELECTED = _controls_.wxEVT_COMMAND_LIST_ITEM_DESELECTED
wxEVT_COMMAND_LIST_KEY_DOWN = _controls_.wxEVT_COMMAND_LIST_KEY_DOWN
wxEVT_COMMAND_LIST_INSERT_ITEM = _controls_.wxEVT_COMMAND_LIST_INSERT_ITEM
wxEVT_COMMAND_LIST_COL_CLICK = _controls_.wxEVT_COMMAND_LIST_COL_CLICK
wxEVT_COMMAND_LIST_ITEM_RIGHT_CLICK = _controls_.wxEVT_COMMAND_LIST_ITEM_RIGHT_CLICK
wxEVT_COMMAND_LIST_ITEM_MIDDLE_CLICK = _controls_.wxEVT_COMMAND_LIST_ITEM_MIDDLE_CLICK
wxEVT_COMMAND_LIST_ITEM_ACTIVATED = _controls_.wxEVT_COMMAND_LIST_ITEM_ACTIVATED
wxEVT_COMMAND_LIST_CACHE_HINT = _controls_.wxEVT_COMMAND_LIST_CACHE_HINT
wxEVT_COMMAND_LIST_COL_RIGHT_CLICK = _controls_.wxEVT_COMMAND_LIST_COL_RIGHT_CLICK
wxEVT_COMMAND_LIST_COL_BEGIN_DRAG = _controls_.wxEVT_COMMAND_LIST_COL_BEGIN_DRAG
wxEVT_COMMAND_LIST_COL_DRAGGING = _controls_.wxEVT_COMMAND_LIST_COL_DRAGGING
wxEVT_COMMAND_LIST_COL_END_DRAG = _controls_.wxEVT_COMMAND_LIST_COL_END_DRAG
wxEVT_COMMAND_LIST_ITEM_FOCUSED = _controls_.wxEVT_COMMAND_LIST_ITEM_FOCUSED
EVT_LIST_BEGIN_DRAG = wx.PyEventBinder(wxEVT_COMMAND_LIST_BEGIN_DRAG , 1)
EVT_LIST_BEGIN_RDRAG = wx.PyEventBinder(wxEVT_COMMAND_LIST_BEGIN_RDRAG , 1)
EVT_LIST_BEGIN_LABEL_EDIT = wx.PyEventBinder(wxEVT_COMMAND_LIST_BEGIN_LABEL_EDIT , 1)
EVT_LIST_END_LABEL_EDIT = wx.PyEventBinder(wxEVT_COMMAND_LIST_END_LABEL_EDIT , 1)
EVT_LIST_DELETE_ITEM = wx.PyEventBinder(wxEVT_COMMAND_LIST_DELETE_ITEM , 1)
EVT_LIST_DELETE_ALL_ITEMS = wx.PyEventBinder(wxEVT_COMMAND_LIST_DELETE_ALL_ITEMS , 1)
EVT_LIST_ITEM_SELECTED = wx.PyEventBinder(wxEVT_COMMAND_LIST_ITEM_SELECTED , 1)
EVT_LIST_ITEM_DESELECTED = wx.PyEventBinder(wxEVT_COMMAND_LIST_ITEM_DESELECTED , 1)
EVT_LIST_KEY_DOWN = wx.PyEventBinder(wxEVT_COMMAND_LIST_KEY_DOWN , 1)
EVT_LIST_INSERT_ITEM = wx.PyEventBinder(wxEVT_COMMAND_LIST_INSERT_ITEM , 1)
EVT_LIST_COL_CLICK = wx.PyEventBinder(wxEVT_COMMAND_LIST_COL_CLICK , 1)
EVT_LIST_ITEM_RIGHT_CLICK = wx.PyEventBinder(wxEVT_COMMAND_LIST_ITEM_RIGHT_CLICK , 1)
EVT_LIST_ITEM_MIDDLE_CLICK = wx.PyEventBinder(wxEVT_COMMAND_LIST_ITEM_MIDDLE_CLICK, 1)
EVT_LIST_ITEM_ACTIVATED = wx.PyEventBinder(wxEVT_COMMAND_LIST_ITEM_ACTIVATED , 1)
EVT_LIST_CACHE_HINT = wx.PyEventBinder(wxEVT_COMMAND_LIST_CACHE_HINT , 1)
EVT_LIST_COL_RIGHT_CLICK = wx.PyEventBinder(wxEVT_COMMAND_LIST_COL_RIGHT_CLICK , 1)
EVT_LIST_COL_BEGIN_DRAG = wx.PyEventBinder(wxEVT_COMMAND_LIST_COL_BEGIN_DRAG , 1)
EVT_LIST_COL_DRAGGING = wx.PyEventBinder(wxEVT_COMMAND_LIST_COL_DRAGGING , 1)
EVT_LIST_COL_END_DRAG = wx.PyEventBinder(wxEVT_COMMAND_LIST_COL_END_DRAG , 1)
EVT_LIST_ITEM_FOCUSED = wx.PyEventBinder(wxEVT_COMMAND_LIST_ITEM_FOCUSED , 1)
#---------------------------------------------------------------------------
class ListCtrl(_core.Control):
"""Proxy of C++ ListCtrl class"""
thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
def __init__(self, *args, **kwargs):
"""
__init__(self, Window parent, int id=-1, Point pos=DefaultPosition,
Size size=DefaultSize, long style=LC_ICON,
Validator validator=DefaultValidator, String name=ListCtrlNameStr) -> ListCtrl
"""
_controls_.ListCtrl_swiginit(self,_controls_.new_ListCtrl(*args, **kwargs))
self._setOORInfo(self);ListCtrl._setCallbackInfo(self, self, ListCtrl)
def Create(*args, **kwargs):
"""
Create(self, Window parent, int id=-1, Point pos=DefaultPosition,
Size size=DefaultSize, long style=LC_ICON,
Validator validator=DefaultValidator, String name=ListCtrlNameStr) -> bool
Do the 2nd phase and create the GUI control.
"""
return _controls_.ListCtrl_Create(*args, **kwargs)
def _setCallbackInfo(*args, **kwargs):
"""_setCallbackInfo(self, PyObject self, PyObject _class)"""
return _controls_.ListCtrl__setCallbackInfo(*args, **kwargs)
def GetColumn(*args, **kwargs):
"""GetColumn(self, int col) -> ListItem"""
val = _controls_.ListCtrl_GetColumn(*args, **kwargs)
if val is not None: val.thisown = 1
return val
def SetColumn(*args, **kwargs):
"""SetColumn(self, int col, ListItem item) -> bool"""
return _controls_.ListCtrl_SetColumn(*args, **kwargs)
def GetColumnWidth(*args, **kwargs):
"""GetColumnWidth(self, int col) -> int"""
return _controls_.ListCtrl_GetColumnWidth(*args, **kwargs)
def SetColumnWidth(*args, **kwargs):
"""SetColumnWidth(self, int col, int width) -> bool"""
return _controls_.ListCtrl_SetColumnWidth(*args, **kwargs)
def HasColumnOrderSupport(*args, **kwargs):
"""HasColumnOrderSupport() -> bool"""
return _controls_.ListCtrl_HasColumnOrderSupport(*args, **kwargs)
HasColumnOrderSupport = staticmethod(HasColumnOrderSupport)
def GetColumnOrder(*args, **kwargs):
"""GetColumnOrder(self, int col) -> int"""
return _controls_.ListCtrl_GetColumnOrder(*args, **kwargs)
def GetColumnIndexFromOrder(*args, **kwargs):
"""GetColumnIndexFromOrder(self, int order) -> int"""
return _controls_.ListCtrl_GetColumnIndexFromOrder(*args, **kwargs)
def GetColumnsOrder(*args, **kwargs):
"""GetColumnsOrder(self) -> wxArrayInt"""
return _controls_.ListCtrl_GetColumnsOrder(*args, **kwargs)
def SetColumnsOrder(*args, **kwargs):
"""SetColumnsOrder(self, wxArrayInt orders) -> bool"""
return _controls_.ListCtrl_SetColumnsOrder(*args, **kwargs)
def GetCountPerPage(*args, **kwargs):
"""GetCountPerPage(self) -> int"""
return _controls_.ListCtrl_GetCountPerPage(*args, **kwargs)
def GetViewRect(*args, **kwargs):
"""GetViewRect(self) -> Rect"""
return _controls_.ListCtrl_GetViewRect(*args, **kwargs)
def GetEditControl(*args, **kwargs):
"""GetEditControl(self) -> TextCtrl"""
return _controls_.ListCtrl_GetEditControl(*args, **kwargs)
def GetItem(*args, **kwargs):
"""GetItem(self, long itemId, int col=0) -> ListItem"""
val = _controls_.ListCtrl_GetItem(*args, **kwargs)
if val is not None: val.thisown = 1
return val
def SetItem(*args, **kwargs):
"""SetItem(self, ListItem info) -> bool"""
return _controls_.ListCtrl_SetItem(*args, **kwargs)
def SetStringItem(*args, **kwargs):
"""SetStringItem(self, long index, int col, String label, int imageId=-1) -> long"""
return _controls_.ListCtrl_SetStringItem(*args, **kwargs)
def GetItemState(*args, **kwargs):
"""GetItemState(self, long item, long stateMask) -> int"""
return _controls_.ListCtrl_GetItemState(*args, **kwargs)
def SetItemState(*args, **kwargs):
"""SetItemState(self, long item, long state, long stateMask) -> bool"""
return _controls_.ListCtrl_SetItemState(*args, **kwargs)
def SetItemImage(*args, **kwargs):
"""SetItemImage(self, long item, int image, int selImage=-1) -> bool"""
return _controls_.ListCtrl_SetItemImage(*args, **kwargs)
def SetItemColumnImage(*args, **kwargs):
"""SetItemColumnImage(self, long item, long column, int image) -> bool"""
return _controls_.ListCtrl_SetItemColumnImage(*args, **kwargs)
def GetItemText(*args, **kwargs):
"""GetItemText(self, long item, int col=0) -> String"""
return _controls_.ListCtrl_GetItemText(*args, **kwargs)
def SetItemText(*args, **kwargs):
"""SetItemText(self, long item, String str)"""
return _controls_.ListCtrl_SetItemText(*args, **kwargs)
def GetItemData(*args, **kwargs):
"""GetItemData(self, long item) -> long"""
return _controls_.ListCtrl_GetItemData(*args, **kwargs)
def SetItemData(*args, **kwargs):
"""SetItemData(self, long item, long data) -> bool"""
return _controls_.ListCtrl_SetItemData(*args, **kwargs)
def GetItemPosition(*args, **kwargs):
"""GetItemPosition(self, long item) -> Point"""
return _controls_.ListCtrl_GetItemPosition(*args, **kwargs)
def GetItemRect(*args, **kwargs):
"""GetItemRect(self, long item, int code=LIST_RECT_BOUNDS) -> Rect"""
return _controls_.ListCtrl_GetItemRect(*args, **kwargs)
def SetItemPosition(*args, **kwargs):
"""SetItemPosition(self, long item, Point pos) -> bool"""
return _controls_.ListCtrl_SetItemPosition(*args, **kwargs)
def GetItemCount(*args, **kwargs):
"""GetItemCount(self) -> int"""
return _controls_.ListCtrl_GetItemCount(*args, **kwargs)
def GetColumnCount(*args, **kwargs):
"""GetColumnCount(self) -> int"""
return _controls_.ListCtrl_GetColumnCount(*args, **kwargs)
def GetItemSpacing(*args, **kwargs):
"""GetItemSpacing(self) -> Size"""
return _controls_.ListCtrl_GetItemSpacing(*args, **kwargs)
GetItemSpacing = wx.deprecated(GetItemSpacing)
def SetItemSpacing(*args, **kwargs):
"""SetItemSpacing(self, int spacing, bool isSmall=False)"""
return _controls_.ListCtrl_SetItemSpacing(*args, **kwargs)
SetItemSpacing = wx.deprecated(SetItemSpacing)
def GetSelectedItemCount(*args, **kwargs):
"""GetSelectedItemCount(self) -> int"""
return _controls_.ListCtrl_GetSelectedItemCount(*args, **kwargs)
def GetTextColour(*args, **kwargs):
"""GetTextColour(self) -> Colour"""
return _controls_.ListCtrl_GetTextColour(*args, **kwargs)
def SetTextColour(*args, **kwargs):
"""SetTextColour(self, Colour col)"""
return _controls_.ListCtrl_SetTextColour(*args, **kwargs)
def GetTopItem(*args, **kwargs):
"""GetTopItem(self) -> long"""
return _controls_.ListCtrl_GetTopItem(*args, **kwargs)
def SetSingleStyle(*args, **kwargs):
"""SetSingleStyle(self, long style, bool add=True)"""
return _controls_.ListCtrl_SetSingleStyle(*args, **kwargs)
def GetNextItem(*args, **kwargs):
"""GetNextItem(self, long item, int geometry=LIST_NEXT_ALL, int state=LIST_STATE_DONTCARE) -> long"""
return _controls_.ListCtrl_GetNextItem(*args, **kwargs)
def GetImageList(*args, **kwargs):
"""GetImageList(self, int which) -> ImageList"""
return _controls_.ListCtrl_GetImageList(*args, **kwargs)
def SetImageList(*args, **kwargs):
"""SetImageList(self, ImageList imageList, int which)"""
return _controls_.ListCtrl_SetImageList(*args, **kwargs)
def AssignImageList(*args, **kwargs):
"""AssignImageList(self, ImageList imageList, int which)"""
return _controls_.ListCtrl_AssignImageList(*args, **kwargs)
def InReportView(*args, **kwargs):
"""InReportView(self) -> bool"""
return _controls_.ListCtrl_InReportView(*args, **kwargs)
def IsVirtual(*args, **kwargs):
"""IsVirtual(self) -> bool"""
return _controls_.ListCtrl_IsVirtual(*args, **kwargs)
def RefreshItem(*args, **kwargs):
"""RefreshItem(self, long item)"""
return _controls_.ListCtrl_RefreshItem(*args, **kwargs)
def RefreshItems(*args, **kwargs):
"""RefreshItems(self, long itemFrom, long itemTo)"""
return _controls_.ListCtrl_RefreshItems(*args, **kwargs)
def Arrange(*args, **kwargs):
"""Arrange(self, int flag=LIST_ALIGN_DEFAULT) -> bool"""
return _controls_.ListCtrl_Arrange(*args, **kwargs)
def DeleteItem(*args, **kwargs):
"""DeleteItem(self, long item) -> bool"""
return _controls_.ListCtrl_DeleteItem(*args, **kwargs)
def DeleteAllItems(*args, **kwargs):
"""DeleteAllItems(self) -> bool"""
return _controls_.ListCtrl_DeleteAllItems(*args, **kwargs)
def DeleteColumn(*args, **kwargs):
"""DeleteColumn(self, int col) -> bool"""
return _controls_.ListCtrl_DeleteColumn(*args, **kwargs)
def DeleteAllColumns(*args, **kwargs):
"""DeleteAllColumns(self) -> bool"""
return _controls_.ListCtrl_DeleteAllColumns(*args, **kwargs)
def ClearAll(*args, **kwargs):
"""ClearAll(self)"""
return _controls_.ListCtrl_ClearAll(*args, **kwargs)
def EditLabel(*args, **kwargs):
"""EditLabel(self, long item)"""
return _controls_.ListCtrl_EditLabel(*args, **kwargs)
def EnsureVisible(*args, **kwargs):
"""EnsureVisible(self, long item) -> bool"""
return _controls_.ListCtrl_EnsureVisible(*args, **kwargs)
def FindItem(*args, **kwargs):
"""FindItem(self, long start, String str, bool partial=False) -> long"""
return _controls_.ListCtrl_FindItem(*args, **kwargs)
def FindItemData(*args, **kwargs):
"""FindItemData(self, long start, long data) -> long"""
return _controls_.ListCtrl_FindItemData(*args, **kwargs)
def FindItemAtPos(*args, **kwargs):
"""FindItemAtPos(self, long start, Point pt, int direction) -> long"""
return _controls_.ListCtrl_FindItemAtPos(*args, **kwargs)
def HitTest(*args, **kwargs):
"""
HitTest(Point point) -> (item, where)
Determines which item (if any) is at the specified point, giving
in the second return value (see wx.LIST_HITTEST flags.)
"""
return _controls_.ListCtrl_HitTest(*args, **kwargs)
def HitTestSubItem(*args, **kwargs):
"""
HitTestSubItem(Point point) -> (item, where, subItem)
Determines which item (if any) is at the specified point, giving in
the second return value (see wx.LIST_HITTEST flags) and also the subItem, if
any.
"""
return _controls_.ListCtrl_HitTestSubItem(*args, **kwargs)
def InsertItem(*args, **kwargs):
"""InsertItem(self, ListItem info) -> long"""
return _controls_.ListCtrl_InsertItem(*args, **kwargs)
def InsertStringItem(*args, **kwargs):
"""InsertStringItem(self, long index, String label, int imageIndex=-1) -> long"""
return _controls_.ListCtrl_InsertStringItem(*args, **kwargs)
def InsertImageItem(*args, **kwargs):
"""InsertImageItem(self, long index, int imageIndex) -> long"""
return _controls_.ListCtrl_InsertImageItem(*args, **kwargs)
def InsertImageStringItem(*args, **kwargs):
"""InsertImageStringItem(self, long index, String label, int imageIndex) -> long"""
return _controls_.ListCtrl_InsertImageStringItem(*args, **kwargs)
def InsertColumnItem(*args, **kwargs):
"""InsertColumnItem(self, long col, ListItem info) -> long"""
return _controls_.ListCtrl_InsertColumnItem(*args, **kwargs)
InsertColumnInfo = InsertColumnItem
def InsertColumn(*args, **kwargs):
"""
InsertColumn(self, long col, String heading, int format=LIST_FORMAT_LEFT,
int width=-1) -> long
"""
return _controls_.ListCtrl_InsertColumn(*args, **kwargs)
def SetItemCount(*args, **kwargs):
"""SetItemCount(self, long count)"""
return _controls_.ListCtrl_SetItemCount(*args, **kwargs)
def ScrollList(*args, **kwargs):
"""ScrollList(self, int dx, int dy) -> bool"""
return _controls_.ListCtrl_ScrollList(*args, **kwargs)
def SetItemTextColour(*args, **kwargs):
"""SetItemTextColour(self, long item, Colour col)"""
return _controls_.ListCtrl_SetItemTextColour(*args, **kwargs)
def GetItemTextColour(*args, **kwargs):
"""GetItemTextColour(self, long item) -> Colour"""
return _controls_.ListCtrl_GetItemTextColour(*args, **kwargs)
def SetItemBackgroundColour(*args, **kwargs):
"""SetItemBackgroundColour(self, long item, Colour col)"""
return _controls_.ListCtrl_SetItemBackgroundColour(*args, **kwargs)
def GetItemBackgroundColour(*args, **kwargs):
"""GetItemBackgroundColour(self, long item) -> Colour"""
return _controls_.ListCtrl_GetItemBackgroundColour(*args, **kwargs)
def SetItemFont(*args, **kwargs):
"""SetItemFont(self, long item, Font f)"""
return _controls_.ListCtrl_SetItemFont(*args, **kwargs)
def GetItemFont(*args, **kwargs):
"""GetItemFont(self, long item) -> Font"""
return _controls_.ListCtrl_GetItemFont(*args, **kwargs)
#
# Some helpers...
def Select(self, idx, on=1):
'''[de]select an item'''
if on: state = wx.LIST_STATE_SELECTED
else: state = 0
self.SetItemState(idx, state, wx.LIST_STATE_SELECTED)
def Focus(self, idx):
'''Focus and show the given item'''
self.SetItemState(idx, wx.LIST_STATE_FOCUSED, wx.LIST_STATE_FOCUSED)
self.EnsureVisible(idx)
def GetFocusedItem(self):
'''get the currently focused item or -1 if none'''
return self.GetNextItem(-1, wx.LIST_NEXT_ALL, wx.LIST_STATE_FOCUSED)
def GetFirstSelected(self, *args):
'''return first selected item, or -1 when none'''
return self.GetNextSelected(-1)
def GetNextSelected(self, item):
'''return subsequent selected items, or -1 when no more'''
return self.GetNextItem(item, wx.LIST_NEXT_ALL, wx.LIST_STATE_SELECTED)
def IsSelected(self, idx):
'''return True if the item is selected'''
return (self.GetItemState(idx, wx.LIST_STATE_SELECTED) & wx.LIST_STATE_SELECTED) != 0
def SetColumnImage(self, col, image):
item = self.GetColumn(col)
# preserve all other attributes too
item.SetMask( wx.LIST_MASK_STATE |
wx.LIST_MASK_TEXT |
wx.LIST_MASK_IMAGE |
wx.LIST_MASK_DATA |
wx.LIST_SET_ITEM |
wx.LIST_MASK_WIDTH |
wx.LIST_MASK_FORMAT )
item.SetImage(image)
self.SetColumn(col, item)
def ClearColumnImage(self, col):
self.SetColumnImage(col, -1)
def Append(self, entry):
'''Append an item to the list control. The entry parameter should be a
sequence with an item for each column'''
if len(entry):
if wx.USE_UNICODE:
cvtfunc = unicode
else:
cvtfunc = str
pos = self.GetItemCount()
self.InsertStringItem(pos, cvtfunc(entry[0]))
for i in range(1, len(entry)):
self.SetStringItem(pos, i, cvtfunc(entry[i]))
return pos
def SortItems(*args, **kwargs):
"""SortItems(self, PyObject func) -> bool"""
return _controls_.ListCtrl_SortItems(*args, **kwargs)
def GetMainWindow(*args, **kwargs):
"""GetMainWindow(self) -> Window"""
return _controls_.ListCtrl_GetMainWindow(*args, **kwargs)
def GetClassDefaultAttributes(*args, **kwargs):
"""
GetClassDefaultAttributes(int variant=WINDOW_VARIANT_NORMAL) -> VisualAttributes
Get the default attributes for this class. This is useful if you want
to use the same font or colour in your own control as in a standard
control -- which is a much better idea than hard coding specific
colours or fonts which might look completely out of place on the
user's system, especially if it uses themes.
The variant parameter is only relevant under Mac currently and is
ignore under other platforms. Under Mac, it will change the size of
the returned font. See `wx.Window.SetWindowVariant` for more about
this.
"""
return _controls_.ListCtrl_GetClassDefaultAttributes(*args, **kwargs)
GetClassDefaultAttributes = staticmethod(GetClassDefaultAttributes)
ColumnCount = property(GetColumnCount,doc="See `GetColumnCount`")
CountPerPage = property(GetCountPerPage,doc="See `GetCountPerPage`")
EditControl = property(GetEditControl,doc="See `GetEditControl`")
FocusedItem = property(GetFocusedItem,doc="See `GetFocusedItem`")
ItemCount = property(GetItemCount,SetItemCount,doc="See `GetItemCount` and `SetItemCount`")
MainWindow = property(GetMainWindow,doc="See `GetMainWindow`")
SelectedItemCount = property(GetSelectedItemCount,doc="See `GetSelectedItemCount`")
TextColour = property(GetTextColour,SetTextColour,doc="See `GetTextColour` and `SetTextColour`")
TopItem = property(GetTopItem,doc="See `GetTopItem`")
ViewRect = property(GetViewRect,doc="See `GetViewRect`")
_controls_.ListCtrl_swigregister(ListCtrl)
def PreListCtrl(*args, **kwargs):
"""PreListCtrl() -> ListCtrl"""
val = _controls_.new_PreListCtrl(*args, **kwargs)
return val
def ListCtrl_HasColumnOrderSupport(*args):
"""ListCtrl_HasColumnOrderSupport() -> bool"""
return _controls_.ListCtrl_HasColumnOrderSupport(*args)
def ListCtrl_GetClassDefaultAttributes(*args, **kwargs):
"""
ListCtrl_GetClassDefaultAttributes(int variant=WINDOW_VARIANT_NORMAL) -> VisualAttributes
Get the default attributes for this class. This is useful if you want
to use the same font or colour in your own control as in a standard
control -- which is a much better idea than hard coding specific
colours or fonts which might look completely out of place on the
user's system, especially if it uses themes.
The variant parameter is only relevant under Mac currently and is
ignore under other platforms. Under Mac, it will change the size of
the returned font. See `wx.Window.SetWindowVariant` for more about
this.
"""
return _controls_.ListCtrl_GetClassDefaultAttributes(*args, **kwargs)
#---------------------------------------------------------------------------
class ListView(ListCtrl):
"""Proxy of C++ ListView class"""
thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
def __init__(self, *args, **kwargs):
"""
__init__(self, Window parent, int id=-1, Point pos=DefaultPosition,
Size size=DefaultSize, long style=LC_REPORT,
Validator validator=DefaultValidator, String name=ListCtrlNameStr) -> ListView
"""
_controls_.ListView_swiginit(self,_controls_.new_ListView(*args, **kwargs))
self._setOORInfo(self)
def Create(*args, **kwargs):
"""
Create(self, Window parent, int id=-1, Point pos=DefaultPosition,
Size size=DefaultSize, long style=LC_REPORT,
Validator validator=DefaultValidator, String name=ListCtrlNameStr) -> bool
Do the 2nd phase and create the GUI control.
"""
return _controls_.ListView_Create(*args, **kwargs)
def Select(*args, **kwargs):
"""Select(self, long n, bool on=True)"""
return _controls_.ListView_Select(*args, **kwargs)
def Focus(*args, **kwargs):
"""Focus(self, long index)"""
return _controls_.ListView_Focus(*args, **kwargs)
def GetFocusedItem(*args, **kwargs):
"""GetFocusedItem(self) -> long"""
return _controls_.ListView_GetFocusedItem(*args, **kwargs)
def GetNextSelected(*args, **kwargs):
"""GetNextSelected(self, long item) -> long"""
return _controls_.ListView_GetNextSelected(*args, **kwargs)
def GetFirstSelected(*args, **kwargs):
"""GetFirstSelected(self) -> long"""
return _controls_.ListView_GetFirstSelected(*args, **kwargs)
def IsSelected(*args, **kwargs):
"""IsSelected(self, long index) -> bool"""
return _controls_.ListView_IsSelected(*args, **kwargs)
def SetColumnImage(*args, **kwargs):
"""SetColumnImage(self, int col, int image)"""
return _controls_.ListView_SetColumnImage(*args, **kwargs)
def ClearColumnImage(*args, **kwargs):
"""ClearColumnImage(self, int col)"""
return _controls_.ListView_ClearColumnImage(*args, **kwargs)
FocusedItem = property(GetFocusedItem,doc="See `GetFocusedItem`")
_controls_.ListView_swigregister(ListView)
def PreListView(*args, **kwargs):
"""PreListView() -> ListView"""
val = _controls_.new_PreListView(*args, **kwargs)
return val
#---------------------------------------------------------------------------
TR_NO_BUTTONS = _controls_.TR_NO_BUTTONS
TR_HAS_BUTTONS = _controls_.TR_HAS_BUTTONS
TR_NO_LINES = _controls_.TR_NO_LINES
TR_LINES_AT_ROOT = _controls_.TR_LINES_AT_ROOT
TR_SINGLE = _controls_.TR_SINGLE
TR_MULTIPLE = _controls_.TR_MULTIPLE
TR_EXTENDED = _controls_.TR_EXTENDED
TR_HAS_VARIABLE_ROW_HEIGHT = _controls_.TR_HAS_VARIABLE_ROW_HEIGHT
TR_EDIT_LABELS = _controls_.TR_EDIT_LABELS
TR_HIDE_ROOT = _controls_.TR_HIDE_ROOT
TR_ROW_LINES = _controls_.TR_ROW_LINES
TR_FULL_ROW_HIGHLIGHT = _controls_.TR_FULL_ROW_HIGHLIGHT
TR_DEFAULT_STYLE = _controls_.TR_DEFAULT_STYLE
TR_TWIST_BUTTONS = _controls_.TR_TWIST_BUTTONS
# obsolete
TR_MAC_BUTTONS = 0
wxTR_AQUA_BUTTONS = 0
TreeItemIcon_Normal = _controls_.TreeItemIcon_Normal
TreeItemIcon_Selected = _controls_.TreeItemIcon_Selected
TreeItemIcon_Expanded = _controls_.TreeItemIcon_Expanded
TreeItemIcon_SelectedExpanded = _controls_.TreeItemIcon_SelectedExpanded
TreeItemIcon_Max = _controls_.TreeItemIcon_Max
TREE_ITEMSTATE_NONE = _controls_.TREE_ITEMSTATE_NONE
TREE_ITEMSTATE_NEXT = _controls_.TREE_ITEMSTATE_NEXT
TREE_ITEMSTATE_PREV = _controls_.TREE_ITEMSTATE_PREV
TREE_HITTEST_ABOVE = _controls_.TREE_HITTEST_ABOVE
TREE_HITTEST_BELOW = _controls_.TREE_HITTEST_BELOW
TREE_HITTEST_NOWHERE = _controls_.TREE_HITTEST_NOWHERE
TREE_HITTEST_ONITEMBUTTON = _controls_.TREE_HITTEST_ONITEMBUTTON
TREE_HITTEST_ONITEMICON = _controls_.TREE_HITTEST_ONITEMICON
TREE_HITTEST_ONITEMINDENT = _controls_.TREE_HITTEST_ONITEMINDENT
TREE_HITTEST_ONITEMLABEL = _controls_.TREE_HITTEST_ONITEMLABEL
TREE_HITTEST_ONITEMRIGHT = _controls_.TREE_HITTEST_ONITEMRIGHT
TREE_HITTEST_ONITEMSTATEICON = _controls_.TREE_HITTEST_ONITEMSTATEICON
TREE_HITTEST_TOLEFT = _controls_.TREE_HITTEST_TOLEFT
TREE_HITTEST_TORIGHT = _controls_.TREE_HITTEST_TORIGHT
TREE_HITTEST_ONITEMUPPERPART = _controls_.TREE_HITTEST_ONITEMUPPERPART
TREE_HITTEST_ONITEMLOWERPART = _controls_.TREE_HITTEST_ONITEMLOWERPART
TREE_HITTEST_ONITEM = _controls_.TREE_HITTEST_ONITEM
#---------------------------------------------------------------------------
class TreeItemId(object):
"""Proxy of C++ TreeItemId class"""
thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
def __init__(self, *args, **kwargs):
"""__init__(self) -> TreeItemId"""
_controls_.TreeItemId_swiginit(self,_controls_.new_TreeItemId(*args, **kwargs))
__swig_destroy__ = _controls_.delete_TreeItemId
__del__ = lambda self : None;
def IsOk(*args, **kwargs):
"""IsOk(self) -> bool"""
return _controls_.TreeItemId_IsOk(*args, **kwargs)
def __eq__(*args, **kwargs):
"""__eq__(self, TreeItemId other) -> bool"""
return _controls_.TreeItemId___eq__(*args, **kwargs)
def __ne__(*args, **kwargs):
"""__ne__(self, TreeItemId other) -> bool"""
return _controls_.TreeItemId___ne__(*args, **kwargs)
m_pItem = property(_controls_.TreeItemId_m_pItem_get, _controls_.TreeItemId_m_pItem_set)
Ok = IsOk
def __nonzero__(self): return self.IsOk()
_controls_.TreeItemId_swigregister(TreeItemId)
TreeCtrlNameStr = cvar.TreeCtrlNameStr
class TreeItemData(object):
"""Proxy of C++ TreeItemData class"""
thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
def __init__(self, *args, **kwargs):
"""__init__(self, PyObject obj=None) -> TreeItemData"""
_controls_.TreeItemData_swiginit(self,_controls_.new_TreeItemData(*args, **kwargs))
__swig_destroy__ = _controls_.delete_TreeItemData
__del__ = lambda self : None;
def GetData(*args, **kwargs):
"""GetData(self) -> PyObject"""
return _controls_.TreeItemData_GetData(*args, **kwargs)
def SetData(*args, **kwargs):
"""SetData(self, PyObject obj)"""
return _controls_.TreeItemData_SetData(*args, **kwargs)
def GetId(*args, **kwargs):
"""GetId(self) -> TreeItemId"""
return _controls_.TreeItemData_GetId(*args, **kwargs)
def SetId(*args, **kwargs):
"""SetId(self, TreeItemId id)"""
return _controls_.TreeItemData_SetId(*args, **kwargs)
def Destroy(*args, **kwargs):
"""Destroy(self)"""
args[0].this.own(False)
return _controls_.TreeItemData_Destroy(*args, **kwargs)
Data = property(GetData,SetData,doc="See `GetData` and `SetData`")
Id = property(GetId,SetId,doc="See `GetId` and `SetId`")
_controls_.TreeItemData_swigregister(TreeItemData)
#---------------------------------------------------------------------------
wxEVT_COMMAND_TREE_BEGIN_DRAG = _controls_.wxEVT_COMMAND_TREE_BEGIN_DRAG
wxEVT_COMMAND_TREE_BEGIN_RDRAG = _controls_.wxEVT_COMMAND_TREE_BEGIN_RDRAG
wxEVT_COMMAND_TREE_BEGIN_LABEL_EDIT = _controls_.wxEVT_COMMAND_TREE_BEGIN_LABEL_EDIT
wxEVT_COMMAND_TREE_END_LABEL_EDIT = _controls_.wxEVT_COMMAND_TREE_END_LABEL_EDIT
wxEVT_COMMAND_TREE_DELETE_ITEM = _controls_.wxEVT_COMMAND_TREE_DELETE_ITEM
wxEVT_COMMAND_TREE_GET_INFO = _controls_.wxEVT_COMMAND_TREE_GET_INFO
wxEVT_COMMAND_TREE_SET_INFO = _controls_.wxEVT_COMMAND_TREE_SET_INFO
wxEVT_COMMAND_TREE_ITEM_EXPANDED = _controls_.wxEVT_COMMAND_TREE_ITEM_EXPANDED
wxEVT_COMMAND_TREE_ITEM_EXPANDING = _controls_.wxEVT_COMMAND_TREE_ITEM_EXPANDING
wxEVT_COMMAND_TREE_ITEM_COLLAPSED = _controls_.wxEVT_COMMAND_TREE_ITEM_COLLAPSED
wxEVT_COMMAND_TREE_ITEM_COLLAPSING = _controls_.wxEVT_COMMAND_TREE_ITEM_COLLAPSING
wxEVT_COMMAND_TREE_SEL_CHANGED = _controls_.wxEVT_COMMAND_TREE_SEL_CHANGED
wxEVT_COMMAND_TREE_SEL_CHANGING = _controls_.wxEVT_COMMAND_TREE_SEL_CHANGING
wxEVT_COMMAND_TREE_KEY_DOWN = _controls_.wxEVT_COMMAND_TREE_KEY_DOWN
wxEVT_COMMAND_TREE_ITEM_ACTIVATED = _controls_.wxEVT_COMMAND_TREE_ITEM_ACTIVATED
wxEVT_COMMAND_TREE_ITEM_RIGHT_CLICK = _controls_.wxEVT_COMMAND_TREE_ITEM_RIGHT_CLICK
wxEVT_COMMAND_TREE_ITEM_MIDDLE_CLICK = _controls_.wxEVT_COMMAND_TREE_ITEM_MIDDLE_CLICK
wxEVT_COMMAND_TREE_END_DRAG = _controls_.wxEVT_COMMAND_TREE_END_DRAG
wxEVT_COMMAND_TREE_STATE_IMAGE_CLICK = _controls_.wxEVT_COMMAND_TREE_STATE_IMAGE_CLICK
wxEVT_COMMAND_TREE_ITEM_GETTOOLTIP = _controls_.wxEVT_COMMAND_TREE_ITEM_GETTOOLTIP
wxEVT_COMMAND_TREE_ITEM_MENU = _controls_.wxEVT_COMMAND_TREE_ITEM_MENU
EVT_TREE_BEGIN_DRAG = wx.PyEventBinder(wxEVT_COMMAND_TREE_BEGIN_DRAG , 1)
EVT_TREE_BEGIN_RDRAG = wx.PyEventBinder(wxEVT_COMMAND_TREE_BEGIN_RDRAG , 1)
EVT_TREE_BEGIN_LABEL_EDIT = wx.PyEventBinder(wxEVT_COMMAND_TREE_BEGIN_LABEL_EDIT , 1)
EVT_TREE_END_LABEL_EDIT = wx.PyEventBinder(wxEVT_COMMAND_TREE_END_LABEL_EDIT , 1)
EVT_TREE_DELETE_ITEM = wx.PyEventBinder(wxEVT_COMMAND_TREE_DELETE_ITEM , 1)
EVT_TREE_GET_INFO = wx.PyEventBinder(wxEVT_COMMAND_TREE_GET_INFO , 1)
EVT_TREE_SET_INFO = wx.PyEventBinder(wxEVT_COMMAND_TREE_SET_INFO , 1)
EVT_TREE_ITEM_EXPANDED = wx.PyEventBinder(wxEVT_COMMAND_TREE_ITEM_EXPANDED , 1)
EVT_TREE_ITEM_EXPANDING = wx.PyEventBinder(wxEVT_COMMAND_TREE_ITEM_EXPANDING , 1)
EVT_TREE_ITEM_COLLAPSED = wx.PyEventBinder(wxEVT_COMMAND_TREE_ITEM_COLLAPSED , 1)
EVT_TREE_ITEM_COLLAPSING = wx.PyEventBinder(wxEVT_COMMAND_TREE_ITEM_COLLAPSING , 1)
EVT_TREE_SEL_CHANGED = wx.PyEventBinder(wxEVT_COMMAND_TREE_SEL_CHANGED , 1)
EVT_TREE_SEL_CHANGING = wx.PyEventBinder(wxEVT_COMMAND_TREE_SEL_CHANGING , 1)
EVT_TREE_KEY_DOWN = wx.PyEventBinder(wxEVT_COMMAND_TREE_KEY_DOWN , 1)
EVT_TREE_ITEM_ACTIVATED = wx.PyEventBinder(wxEVT_COMMAND_TREE_ITEM_ACTIVATED , 1)
EVT_TREE_ITEM_RIGHT_CLICK = wx.PyEventBinder(wxEVT_COMMAND_TREE_ITEM_RIGHT_CLICK , 1)
EVT_TREE_ITEM_MIDDLE_CLICK = wx.PyEventBinder(wxEVT_COMMAND_TREE_ITEM_MIDDLE_CLICK, 1)
EVT_TREE_END_DRAG = wx.PyEventBinder(wxEVT_COMMAND_TREE_END_DRAG , 1)
EVT_TREE_STATE_IMAGE_CLICK = wx.PyEventBinder(wxEVT_COMMAND_TREE_STATE_IMAGE_CLICK, 1)
EVT_TREE_ITEM_GETTOOLTIP = wx.PyEventBinder(wxEVT_COMMAND_TREE_ITEM_GETTOOLTIP, 1)
EVT_TREE_ITEM_MENU = wx.PyEventBinder(wxEVT_COMMAND_TREE_ITEM_MENU, 1)
class TreeEvent(_core.NotifyEvent):
"""Proxy of C++ TreeEvent class"""
thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
def __init__(self, *args):
"""
__init__(self, EventType commandType=wxEVT_NULL, int id=0) -> TreeEvent
__init__(self, EventType commandType, TreeCtrl tree, TreeItemId item=NullTreeItemId) -> TreeEvent
"""
_controls_.TreeEvent_swiginit(self,_controls_.new_TreeEvent(*args))
def GetItem(*args, **kwargs):
"""GetItem(self) -> TreeItemId"""
return _controls_.TreeEvent_GetItem(*args, **kwargs)
def SetItem(*args, **kwargs):
"""SetItem(self, TreeItemId item)"""
return _controls_.TreeEvent_SetItem(*args, **kwargs)
def GetOldItem(*args, **kwargs):
"""GetOldItem(self) -> TreeItemId"""
return _controls_.TreeEvent_GetOldItem(*args, **kwargs)
def SetOldItem(*args, **kwargs):
"""SetOldItem(self, TreeItemId item)"""
return _controls_.TreeEvent_SetOldItem(*args, **kwargs)
def GetPoint(*args, **kwargs):
"""GetPoint(self) -> Point"""
return _controls_.TreeEvent_GetPoint(*args, **kwargs)
def SetPoint(*args, **kwargs):
"""SetPoint(self, Point pt)"""
return _controls_.TreeEvent_SetPoint(*args, **kwargs)
def GetKeyEvent(*args, **kwargs):
"""GetKeyEvent(self) -> KeyEvent"""
return _controls_.TreeEvent_GetKeyEvent(*args, **kwargs)
def GetKeyCode(*args, **kwargs):
"""GetKeyCode(self) -> int"""
return _controls_.TreeEvent_GetKeyCode(*args, **kwargs)
def SetKeyEvent(*args, **kwargs):
"""SetKeyEvent(self, KeyEvent evt)"""
return _controls_.TreeEvent_SetKeyEvent(*args, **kwargs)
def GetLabel(*args, **kwargs):
"""GetLabel(self) -> String"""
return _controls_.TreeEvent_GetLabel(*args, **kwargs)
def SetLabel(*args, **kwargs):
"""SetLabel(self, String label)"""
return _controls_.TreeEvent_SetLabel(*args, **kwargs)
def IsEditCancelled(*args, **kwargs):
"""IsEditCancelled(self) -> bool"""
return _controls_.TreeEvent_IsEditCancelled(*args, **kwargs)
def SetEditCanceled(*args, **kwargs):
"""SetEditCanceled(self, bool editCancelled)"""
return _controls_.TreeEvent_SetEditCanceled(*args, **kwargs)
def SetToolTip(*args, **kwargs):
"""SetToolTip(self, String toolTip)"""
return _controls_.TreeEvent_SetToolTip(*args, **kwargs)
def GetToolTip(*args, **kwargs):
"""GetToolTip(self) -> String"""
return _controls_.TreeEvent_GetToolTip(*args, **kwargs)
Item = property(GetItem,SetItem,doc="See `GetItem` and `SetItem`")
KeyCode = property(GetKeyCode,doc="See `GetKeyCode`")
KeyEvent = property(GetKeyEvent,SetKeyEvent,doc="See `GetKeyEvent` and `SetKeyEvent`")
Label = property(GetLabel,SetLabel,doc="See `GetLabel` and `SetLabel`")
OldItem = property(GetOldItem,SetOldItem,doc="See `GetOldItem` and `SetOldItem`")
Point = property(GetPoint,SetPoint,doc="See `GetPoint` and `SetPoint`")
ToolTip = property(GetToolTip,SetToolTip,doc="See `GetToolTip` and `SetToolTip`")
EditCancelled = property(IsEditCancelled,SetEditCanceled,doc="See `IsEditCancelled` and `SetEditCanceled`")
_controls_.TreeEvent_swigregister(TreeEvent)
#---------------------------------------------------------------------------
class TreeCtrl(_core.Control):
"""Proxy of C++ TreeCtrl class"""
thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
def __init__(self, *args, **kwargs):
"""
__init__(self, Window parent, int id=-1, Point pos=DefaultPosition,
Size size=DefaultSize, long style=TR_DEFAULT_STYLE,
Validator validator=DefaultValidator,
String name=TreeCtrlNameStr) -> TreeCtrl
"""
_controls_.TreeCtrl_swiginit(self,_controls_.new_TreeCtrl(*args, **kwargs))
self._setOORInfo(self);TreeCtrl._setCallbackInfo(self, self, TreeCtrl)
def Create(*args, **kwargs):
"""
Create(self, Window parent, int id=-1, Point pos=DefaultPosition,
Size size=DefaultSize, long style=TR_DEFAULT_STYLE,
Validator validator=DefaultValidator,
String name=TreeCtrlNameStr) -> bool
Do the 2nd phase and create the GUI control.
"""
return _controls_.TreeCtrl_Create(*args, **kwargs)
def _setCallbackInfo(*args, **kwargs):
"""_setCallbackInfo(self, PyObject self, PyObject _class)"""
return _controls_.TreeCtrl__setCallbackInfo(*args, **kwargs)
def GetCount(*args, **kwargs):
"""GetCount(self) -> unsigned int"""
return _controls_.TreeCtrl_GetCount(*args, **kwargs)
def GetIndent(*args, **kwargs):
"""GetIndent(self) -> unsigned int"""
return _controls_.TreeCtrl_GetIndent(*args, **kwargs)
def SetIndent(*args, **kwargs):
"""SetIndent(self, unsigned int indent)"""
return _controls_.TreeCtrl_SetIndent(*args, **kwargs)
def GetSpacing(*args, **kwargs):
"""GetSpacing(self) -> unsigned int"""
return _controls_.TreeCtrl_GetSpacing(*args, **kwargs)
def SetSpacing(*args, **kwargs):
"""SetSpacing(self, unsigned int spacing)"""
return _controls_.TreeCtrl_SetSpacing(*args, **kwargs)
def GetImageList(*args, **kwargs):
"""GetImageList(self) -> ImageList"""
return _controls_.TreeCtrl_GetImageList(*args, **kwargs)
def GetStateImageList(*args, **kwargs):
"""GetStateImageList(self) -> ImageList"""
return _controls_.TreeCtrl_GetStateImageList(*args, **kwargs)
def SetImageList(*args, **kwargs):
"""SetImageList(self, ImageList imageList)"""
return _controls_.TreeCtrl_SetImageList(*args, **kwargs)
def SetStateImageList(*args, **kwargs):
"""SetStateImageList(self, ImageList imageList)"""
return _controls_.TreeCtrl_SetStateImageList(*args, **kwargs)
def AssignImageList(*args, **kwargs):
"""AssignImageList(self, ImageList imageList)"""
return _controls_.TreeCtrl_AssignImageList(*args, **kwargs)
def AssignStateImageList(*args, **kwargs):
"""AssignStateImageList(self, ImageList imageList)"""
return _controls_.TreeCtrl_AssignStateImageList(*args, **kwargs)
def GetItemText(*args, **kwargs):
"""GetItemText(self, TreeItemId item) -> String"""
return _controls_.TreeCtrl_GetItemText(*args, **kwargs)
def GetItemImage(*args, **kwargs):
"""GetItemImage(self, TreeItemId item, int which=TreeItemIcon_Normal) -> int"""
return _controls_.TreeCtrl_GetItemImage(*args, **kwargs)
def GetItemData(*args, **kwargs):
"""GetItemData(self, TreeItemId item) -> TreeItemData"""
return _controls_.TreeCtrl_GetItemData(*args, **kwargs)
def GetItemPyData(*args, **kwargs):
"""GetItemPyData(self, TreeItemId item) -> PyObject"""
return _controls_.TreeCtrl_GetItemPyData(*args, **kwargs)
GetPyData = GetItemPyData
def GetItemTextColour(*args, **kwargs):
"""GetItemTextColour(self, TreeItemId item) -> Colour"""
return _controls_.TreeCtrl_GetItemTextColour(*args, **kwargs)
def GetItemBackgroundColour(*args, **kwargs):
"""GetItemBackgroundColour(self, TreeItemId item) -> Colour"""
return _controls_.TreeCtrl_GetItemBackgroundColour(*args, **kwargs)
def GetItemFont(*args, **kwargs):
"""GetItemFont(self, TreeItemId item) -> Font"""
return _controls_.TreeCtrl_GetItemFont(*args, **kwargs)
def GetItemState(*args, **kwargs):
"""GetItemState(self, TreeItemId item) -> int"""
return _controls_.TreeCtrl_GetItemState(*args, **kwargs)
def SetItemText(*args, **kwargs):
"""SetItemText(self, TreeItemId item, String text)"""
return _controls_.TreeCtrl_SetItemText(*args, **kwargs)
def SetItemImage(*args, **kwargs):
"""SetItemImage(self, TreeItemId item, int image, int which=TreeItemIcon_Normal)"""
return _controls_.TreeCtrl_SetItemImage(*args, **kwargs)
def SetItemData(*args, **kwargs):
"""SetItemData(self, TreeItemId item, TreeItemData data)"""
return _controls_.TreeCtrl_SetItemData(*args, **kwargs)
def SetItemPyData(*args, **kwargs):
"""SetItemPyData(self, TreeItemId item, PyObject obj)"""
return _controls_.TreeCtrl_SetItemPyData(*args, **kwargs)
SetPyData = SetItemPyData
def SetItemHasChildren(*args, **kwargs):
"""SetItemHasChildren(self, TreeItemId item, bool has=True)"""
return _controls_.TreeCtrl_SetItemHasChildren(*args, **kwargs)
def SetItemBold(*args, **kwargs):
"""SetItemBold(self, TreeItemId item, bool bold=True)"""
return _controls_.TreeCtrl_SetItemBold(*args, **kwargs)
def SetItemDropHighlight(*args, **kwargs):
"""SetItemDropHighlight(self, TreeItemId item, bool highlight=True)"""
return _controls_.TreeCtrl_SetItemDropHighlight(*args, **kwargs)
def SetItemTextColour(*args, **kwargs):
"""SetItemTextColour(self, TreeItemId item, Colour col)"""
return _controls_.TreeCtrl_SetItemTextColour(*args, **kwargs)
def SetItemBackgroundColour(*args, **kwargs):
"""SetItemBackgroundColour(self, TreeItemId item, Colour col)"""
return _controls_.TreeCtrl_SetItemBackgroundColour(*args, **kwargs)
def SetItemFont(*args, **kwargs):
"""SetItemFont(self, TreeItemId item, Font font)"""
return _controls_.TreeCtrl_SetItemFont(*args, **kwargs)
def SetItemState(*args, **kwargs):
"""SetItemState(self, TreeItemId item, int state)"""
return _controls_.TreeCtrl_SetItemState(*args, **kwargs)
def IsVisible(*args, **kwargs):
"""IsVisible(self, TreeItemId item) -> bool"""
return _controls_.TreeCtrl_IsVisible(*args, **kwargs)
def ItemHasChildren(*args, **kwargs):
"""ItemHasChildren(self, TreeItemId item) -> bool"""
return _controls_.TreeCtrl_ItemHasChildren(*args, **kwargs)
def IsExpanded(*args, **kwargs):
"""IsExpanded(self, TreeItemId item) -> bool"""
return _controls_.TreeCtrl_IsExpanded(*args, **kwargs)
def IsSelected(*args, **kwargs):
"""IsSelected(self, TreeItemId item) -> bool"""
return _controls_.TreeCtrl_IsSelected(*args, **kwargs)
def IsBold(*args, **kwargs):
"""IsBold(self, TreeItemId item) -> bool"""
return _controls_.TreeCtrl_IsBold(*args, **kwargs)
def IsEmpty(*args, **kwargs):
"""IsEmpty(self) -> bool"""
return _controls_.TreeCtrl_IsEmpty(*args, **kwargs)
def GetChildrenCount(*args, **kwargs):
"""GetChildrenCount(self, TreeItemId item, bool recursively=True) -> size_t"""
return _controls_.TreeCtrl_GetChildrenCount(*args, **kwargs)
def GetRootItem(*args, **kwargs):
"""GetRootItem(self) -> TreeItemId"""
return _controls_.TreeCtrl_GetRootItem(*args, **kwargs)
def GetSelection(*args, **kwargs):
"""GetSelection(self) -> TreeItemId"""
return _controls_.TreeCtrl_GetSelection(*args, **kwargs)
def GetSelections(*args, **kwargs):
"""GetSelections(self) -> PyObject"""
return _controls_.TreeCtrl_GetSelections(*args, **kwargs)
def GetFocusedItem(*args, **kwargs):
"""GetFocusedItem(self) -> TreeItemId"""
return _controls_.TreeCtrl_GetFocusedItem(*args, **kwargs)
def ClearFocusedItem(*args, **kwargs):
"""ClearFocusedItem(self)"""
return _controls_.TreeCtrl_ClearFocusedItem(*args, **kwargs)
def SetFocusedItem(*args, **kwargs):
"""SetFocusedItem(self, TreeItemId item)"""
return _controls_.TreeCtrl_SetFocusedItem(*args, **kwargs)
def GetItemParent(*args, **kwargs):
"""GetItemParent(self, TreeItemId item) -> TreeItemId"""
return _controls_.TreeCtrl_GetItemParent(*args, **kwargs)
def GetFirstChild(*args, **kwargs):
"""GetFirstChild(self, TreeItemId item) -> PyObject"""
return _controls_.TreeCtrl_GetFirstChild(*args, **kwargs)
def GetNextChild(*args, **kwargs):
"""GetNextChild(self, TreeItemId item, void cookie) -> PyObject"""
return _controls_.TreeCtrl_GetNextChild(*args, **kwargs)
def GetLastChild(*args, **kwargs):
"""GetLastChild(self, TreeItemId item) -> TreeItemId"""
return _controls_.TreeCtrl_GetLastChild(*args, **kwargs)
def GetNextSibling(*args, **kwargs):
"""GetNextSibling(self, TreeItemId item) -> TreeItemId"""
return _controls_.TreeCtrl_GetNextSibling(*args, **kwargs)
def GetPrevSibling(*args, **kwargs):
"""GetPrevSibling(self, TreeItemId item) -> TreeItemId"""
return _controls_.TreeCtrl_GetPrevSibling(*args, **kwargs)
def GetFirstVisibleItem(*args, **kwargs):
"""GetFirstVisibleItem(self) -> TreeItemId"""
return _controls_.TreeCtrl_GetFirstVisibleItem(*args, **kwargs)
def GetNextVisible(*args, **kwargs):
"""GetNextVisible(self, TreeItemId item) -> TreeItemId"""
return _controls_.TreeCtrl_GetNextVisible(*args, **kwargs)
def GetPrevVisible(*args, **kwargs):
"""GetPrevVisible(self, TreeItemId item) -> TreeItemId"""
return _controls_.TreeCtrl_GetPrevVisible(*args, **kwargs)
def AddRoot(*args, **kwargs):
"""AddRoot(self, String text, int image=-1, int selectedImage=-1, TreeItemData data=None) -> TreeItemId"""
return _controls_.TreeCtrl_AddRoot(*args, **kwargs)
def PrependItem(*args, **kwargs):
"""
PrependItem(self, TreeItemId parent, String text, int image=-1, int selectedImage=-1,
TreeItemData data=None) -> TreeItemId
"""
return _controls_.TreeCtrl_PrependItem(*args, **kwargs)
def InsertItem(*args, **kwargs):
"""
InsertItem(self, TreeItemId parent, TreeItemId idPrevious, String text,
int image=-1, int selectedImage=-1, TreeItemData data=None) -> TreeItemId
"""
return _controls_.TreeCtrl_InsertItem(*args, **kwargs)
def InsertItemBefore(*args, **kwargs):
"""
InsertItemBefore(self, TreeItemId parent, size_t index, String text, int image=-1,
int selectedImage=-1, TreeItemData data=None) -> TreeItemId
"""
return _controls_.TreeCtrl_InsertItemBefore(*args, **kwargs)
def AppendItem(*args, **kwargs):
"""
AppendItem(self, TreeItemId parent, String text, int image=-1, int selectedImage=-1,
TreeItemData data=None) -> TreeItemId
"""
return _controls_.TreeCtrl_AppendItem(*args, **kwargs)
def Delete(*args, **kwargs):
"""Delete(self, TreeItemId item)"""
return _controls_.TreeCtrl_Delete(*args, **kwargs)
def DeleteChildren(*args, **kwargs):
"""DeleteChildren(self, TreeItemId item)"""
return _controls_.TreeCtrl_DeleteChildren(*args, **kwargs)
def DeleteAllItems(*args, **kwargs):
"""DeleteAllItems(self)"""
return _controls_.TreeCtrl_DeleteAllItems(*args, **kwargs)
def Expand(*args, **kwargs):
"""Expand(self, TreeItemId item)"""
return _controls_.TreeCtrl_Expand(*args, **kwargs)
def ExpandAllChildren(*args, **kwargs):
"""ExpandAllChildren(self, TreeItemId item)"""
return _controls_.TreeCtrl_ExpandAllChildren(*args, **kwargs)
def ExpandAll(*args, **kwargs):
"""ExpandAll(self)"""
return _controls_.TreeCtrl_ExpandAll(*args, **kwargs)
def Collapse(*args, **kwargs):
"""Collapse(self, TreeItemId item)"""
return _controls_.TreeCtrl_Collapse(*args, **kwargs)
def CollapseAllChildren(*args, **kwargs):
"""CollapseAllChildren(self, TreeItemId item)"""
return _controls_.TreeCtrl_CollapseAllChildren(*args, **kwargs)
def CollapseAll(*args, **kwargs):
"""CollapseAll(self)"""
return _controls_.TreeCtrl_CollapseAll(*args, **kwargs)
def CollapseAndReset(*args, **kwargs):
"""CollapseAndReset(self, TreeItemId item)"""
return _controls_.TreeCtrl_CollapseAndReset(*args, **kwargs)
def Toggle(*args, **kwargs):
"""Toggle(self, TreeItemId item)"""
return _controls_.TreeCtrl_Toggle(*args, **kwargs)
def Unselect(*args, **kwargs):
"""Unselect(self)"""
return _controls_.TreeCtrl_Unselect(*args, **kwargs)
def UnselectItem(*args, **kwargs):
"""UnselectItem(self, TreeItemId item)"""
return _controls_.TreeCtrl_UnselectItem(*args, **kwargs)
def UnselectAll(*args, **kwargs):
"""UnselectAll(self)"""
return _controls_.TreeCtrl_UnselectAll(*args, **kwargs)
def SelectItem(*args, **kwargs):
"""SelectItem(self, TreeItemId item, bool select=True)"""
return _controls_.TreeCtrl_SelectItem(*args, **kwargs)
def SelectChildren(*args, **kwargs):
"""SelectChildren(self, TreeItemId parent)"""
return _controls_.TreeCtrl_SelectChildren(*args, **kwargs)
def ToggleItemSelection(*args, **kwargs):
"""ToggleItemSelection(self, TreeItemId item)"""
return _controls_.TreeCtrl_ToggleItemSelection(*args, **kwargs)
def EnsureVisible(*args, **kwargs):
"""EnsureVisible(self, TreeItemId item)"""
return _controls_.TreeCtrl_EnsureVisible(*args, **kwargs)
def ScrollTo(*args, **kwargs):
"""ScrollTo(self, TreeItemId item)"""
return _controls_.TreeCtrl_ScrollTo(*args, **kwargs)
def EditLabel(*args, **kwargs):
"""EditLabel(self, TreeItemId item)"""
return _controls_.TreeCtrl_EditLabel(*args, **kwargs)
def GetEditControl(*args, **kwargs):
"""GetEditControl(self) -> TextCtrl"""
return _controls_.TreeCtrl_GetEditControl(*args, **kwargs)
def SortChildren(*args, **kwargs):
"""SortChildren(self, TreeItemId item)"""
return _controls_.TreeCtrl_SortChildren(*args, **kwargs)
def HitTest(*args, **kwargs):
"""
HitTest(Point point) -> (item, where)
Determine which item (if any) belongs the given point. The coordinates
specified are relative to the client area of tree ctrl and the where return
value is set to a bitmask of wxTREE_HITTEST_xxx constants.
"""
return _controls_.TreeCtrl_HitTest(*args, **kwargs)
def GetBoundingRect(*args, **kwargs):
"""GetBoundingRect(self, TreeItemId item, bool textOnly=False) -> PyObject"""
return _controls_.TreeCtrl_GetBoundingRect(*args, **kwargs)
def GetClassDefaultAttributes(*args, **kwargs):
"""
GetClassDefaultAttributes(int variant=WINDOW_VARIANT_NORMAL) -> VisualAttributes
Get the default attributes for this class. This is useful if you want
to use the same font or colour in your own control as in a standard
control -- which is a much better idea than hard coding specific
colours or fonts which might look completely out of place on the
user's system, especially if it uses themes.
The variant parameter is only relevant under Mac currently and is
ignore under other platforms. Under Mac, it will change the size of
the returned font. See `wx.Window.SetWindowVariant` for more about
this.
"""
return _controls_.TreeCtrl_GetClassDefaultAttributes(*args, **kwargs)
GetClassDefaultAttributes = staticmethod(GetClassDefaultAttributes)
def SetQuickBestSize(*args, **kwargs):
"""SetQuickBestSize(self, bool q)"""
return _controls_.TreeCtrl_SetQuickBestSize(*args, **kwargs)
def GetQuickBestSize(*args, **kwargs):
"""GetQuickBestSize(self) -> bool"""
return _controls_.TreeCtrl_GetQuickBestSize(*args, **kwargs)
Count = property(GetCount,doc="See `GetCount`")
EditControl = property(GetEditControl,doc="See `GetEditControl`")
FirstVisibleItem = property(GetFirstVisibleItem,doc="See `GetFirstVisibleItem`")
ImageList = property(GetImageList,SetImageList,doc="See `GetImageList` and `SetImageList`")
Indent = property(GetIndent,SetIndent,doc="See `GetIndent` and `SetIndent`")
QuickBestSize = property(GetQuickBestSize,SetQuickBestSize,doc="See `GetQuickBestSize` and `SetQuickBestSize`")
RootItem = property(GetRootItem,doc="See `GetRootItem`")
Selection = property(GetSelection,doc="See `GetSelection`")
Selections = property(GetSelections,doc="See `GetSelections`")
Spacing = property(GetSpacing,SetSpacing,doc="See `GetSpacing` and `SetSpacing`")
StateImageList = property(GetStateImageList,SetStateImageList,doc="See `GetStateImageList` and `SetStateImageList`")
_controls_.TreeCtrl_swigregister(TreeCtrl)
def PreTreeCtrl(*args, **kwargs):
"""PreTreeCtrl() -> TreeCtrl"""
val = _controls_.new_PreTreeCtrl(*args, **kwargs)
return val
def TreeCtrl_GetClassDefaultAttributes(*args, **kwargs):
"""
TreeCtrl_GetClassDefaultAttributes(int variant=WINDOW_VARIANT_NORMAL) -> VisualAttributes
Get the default attributes for this class. This is useful if you want
to use the same font or colour in your own control as in a standard
control -- which is a much better idea than hard coding specific
colours or fonts which might look completely out of place on the
user's system, especially if it uses themes.
The variant parameter is only relevant under Mac currently and is
ignore under other platforms. Under Mac, it will change the size of
the returned font. See `wx.Window.SetWindowVariant` for more about
this.
"""
return _controls_.TreeCtrl_GetClassDefaultAttributes(*args, **kwargs)
#---------------------------------------------------------------------------
DIRCTRL_DIR_ONLY = _controls_.DIRCTRL_DIR_ONLY
DIRCTRL_SELECT_FIRST = _controls_.DIRCTRL_SELECT_FIRST
DIRCTRL_SHOW_FILTERS = _controls_.DIRCTRL_SHOW_FILTERS
DIRCTRL_3D_INTERNAL = _controls_.DIRCTRL_3D_INTERNAL
DIRCTRL_EDIT_LABELS = _controls_.DIRCTRL_EDIT_LABELS
DIRCTRL_MULTIPLE = _controls_.DIRCTRL_MULTIPLE
class DirItemData(_core.Object):
"""Proxy of C++ DirItemData class"""
thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
def __init__(self): raise AttributeError, "No constructor defined"
__repr__ = _swig_repr
def SetNewDirName(*args, **kwargs):
"""SetNewDirName(self, String path)"""
return _controls_.DirItemData_SetNewDirName(*args, **kwargs)
m_path = property(_controls_.DirItemData_m_path_get, _controls_.DirItemData_m_path_set)
m_name = property(_controls_.DirItemData_m_name_get, _controls_.DirItemData_m_name_set)
m_isHidden = property(_controls_.DirItemData_m_isHidden_get, _controls_.DirItemData_m_isHidden_set)
m_isExpanded = property(_controls_.DirItemData_m_isExpanded_get, _controls_.DirItemData_m_isExpanded_set)
m_isDir = property(_controls_.DirItemData_m_isDir_get, _controls_.DirItemData_m_isDir_set)
_controls_.DirItemData_swigregister(DirItemData)
DirDialogDefaultFolderStr = cvar.DirDialogDefaultFolderStr
class GenericDirCtrl(_core.Control):
"""Proxy of C++ GenericDirCtrl class"""
thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
def __init__(self, *args, **kwargs):
"""
__init__(self, Window parent, int id=-1, String dir=DirDialogDefaultFolderStr,
Point pos=DefaultPosition, Size size=DefaultSize,
long style=DIRCTRL_3D_INTERNAL,
String filter=EmptyString, int defaultFilter=0,
String name=TreeCtrlNameStr) -> GenericDirCtrl
"""
_controls_.GenericDirCtrl_swiginit(self,_controls_.new_GenericDirCtrl(*args, **kwargs))
self._setOORInfo(self)
def Create(*args, **kwargs):
"""
Create(self, Window parent, int id=-1, String dir=DirDialogDefaultFolderStr,
Point pos=DefaultPosition, Size size=DefaultSize,
long style=DIRCTRL_3D_INTERNAL,
String filter=EmptyString, int defaultFilter=0,
String name=TreeCtrlNameStr) -> bool
"""
return _controls_.GenericDirCtrl_Create(*args, **kwargs)
def ExpandPath(*args, **kwargs):
"""ExpandPath(self, String path) -> bool"""
return _controls_.GenericDirCtrl_ExpandPath(*args, **kwargs)
def CollapsePath(*args, **kwargs):
"""CollapsePath(self, String path) -> bool"""
return _controls_.GenericDirCtrl_CollapsePath(*args, **kwargs)
def GetDefaultPath(*args, **kwargs):
"""GetDefaultPath(self) -> String"""
return _controls_.GenericDirCtrl_GetDefaultPath(*args, **kwargs)
def SetDefaultPath(*args, **kwargs):
"""SetDefaultPath(self, String path)"""
return _controls_.GenericDirCtrl_SetDefaultPath(*args, **kwargs)
def GetPath(*args, **kwargs):
"""GetPath(self) -> String"""
return _controls_.GenericDirCtrl_GetPath(*args, **kwargs)
def GetPaths(*args, **kwargs):
"""GetPaths(self) -> wxArrayString"""
return _controls_.GenericDirCtrl_GetPaths(*args, **kwargs)
def GetFilePath(*args, **kwargs):
"""GetFilePath(self) -> String"""
return _controls_.GenericDirCtrl_GetFilePath(*args, **kwargs)
def SetPath(*args, **kwargs):
"""SetPath(self, String path)"""
return _controls_.GenericDirCtrl_SetPath(*args, **kwargs)
def GetFilePaths(*args, **kwargs):
"""GetFilePaths(self) -> wxArrayString"""
return _controls_.GenericDirCtrl_GetFilePaths(*args, **kwargs)
def SelectPath(*args, **kwargs):
"""SelectPath(self, String path, bool select=True)"""
return _controls_.GenericDirCtrl_SelectPath(*args, **kwargs)
def SelectPaths(*args, **kwargs):
"""SelectPaths(self, wxArrayString paths)"""
return _controls_.GenericDirCtrl_SelectPaths(*args, **kwargs)
def ShowHidden(*args, **kwargs):
"""ShowHidden(self, bool show)"""
return _controls_.GenericDirCtrl_ShowHidden(*args, **kwargs)
def GetShowHidden(*args, **kwargs):
"""GetShowHidden(self) -> bool"""
return _controls_.GenericDirCtrl_GetShowHidden(*args, **kwargs)
def GetFilter(*args, **kwargs):
"""GetFilter(self) -> String"""
return _controls_.GenericDirCtrl_GetFilter(*args, **kwargs)
def SetFilter(*args, **kwargs):
"""SetFilter(self, String filter)"""
return _controls_.GenericDirCtrl_SetFilter(*args, **kwargs)
def GetFilterIndex(*args, **kwargs):
"""GetFilterIndex(self) -> int"""
return _controls_.GenericDirCtrl_GetFilterIndex(*args, **kwargs)
def SetFilterIndex(*args, **kwargs):
"""SetFilterIndex(self, int n)"""
return _controls_.GenericDirCtrl_SetFilterIndex(*args, **kwargs)
def GetRootId(*args, **kwargs):
"""GetRootId(self) -> TreeItemId"""
return _controls_.GenericDirCtrl_GetRootId(*args, **kwargs)
def GetTreeCtrl(*args, **kwargs):
"""GetTreeCtrl(self) -> TreeCtrl"""
return _controls_.GenericDirCtrl_GetTreeCtrl(*args, **kwargs)
def GetFilterListCtrl(*args, **kwargs):
"""GetFilterListCtrl(self) -> DirFilterListCtrl"""
return _controls_.GenericDirCtrl_GetFilterListCtrl(*args, **kwargs)
def UnselectAll(*args, **kwargs):
"""UnselectAll(self)"""
return _controls_.GenericDirCtrl_UnselectAll(*args, **kwargs)
def GetDirItemData(*args, **kwargs):
"""GetDirItemData(self, TreeItemId id) -> DirItemData"""
return _controls_.GenericDirCtrl_GetDirItemData(*args, **kwargs)
def FindChild(*args, **kwargs):
"""
FindChild(wxTreeItemId parentId, wxString path) -> (item, done)
Find the child that matches the first part of 'path'. E.g. if a child
path is "/usr" and 'path' is "/usr/include" then the child for
/usr is returned. If the path string has been used (we're at the
leaf), done is set to True.
"""
return _controls_.GenericDirCtrl_FindChild(*args, **kwargs)
def DoResize(*args, **kwargs):
"""DoResize(self)"""
return _controls_.GenericDirCtrl_DoResize(*args, **kwargs)
def ReCreateTree(*args, **kwargs):
"""ReCreateTree(self)"""
return _controls_.GenericDirCtrl_ReCreateTree(*args, **kwargs)
DefaultPath = property(GetDefaultPath,SetDefaultPath,doc="See `GetDefaultPath` and `SetDefaultPath`")
FilePath = property(GetFilePath,doc="See `GetFilePath`")
Filter = property(GetFilter,SetFilter,doc="See `GetFilter` and `SetFilter`")
FilterIndex = property(GetFilterIndex,SetFilterIndex,doc="See `GetFilterIndex` and `SetFilterIndex`")
FilterListCtrl = property(GetFilterListCtrl,doc="See `GetFilterListCtrl`")
Path = property(GetPath,SetPath,doc="See `GetPath` and `SetPath`")
RootId = property(GetRootId,doc="See `GetRootId`")
TreeCtrl = property(GetTreeCtrl,doc="See `GetTreeCtrl`")
_controls_.GenericDirCtrl_swigregister(GenericDirCtrl)
def PreGenericDirCtrl(*args, **kwargs):
"""PreGenericDirCtrl() -> GenericDirCtrl"""
val = _controls_.new_PreGenericDirCtrl(*args, **kwargs)
return val
class DirFilterListCtrl(Choice):
"""Proxy of C++ DirFilterListCtrl class"""
thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
def __init__(self, *args, **kwargs):
"""
__init__(self, GenericDirCtrl parent, int id=-1, Point pos=DefaultPosition,
Size size=DefaultSize, long style=0) -> DirFilterListCtrl
"""
_controls_.DirFilterListCtrl_swiginit(self,_controls_.new_DirFilterListCtrl(*args, **kwargs))
self._setOORInfo(self)
def Create(*args, **kwargs):
"""
Create(self, GenericDirCtrl parent, int id=-1, Point pos=DefaultPosition,
Size size=DefaultSize, long style=0) -> bool
"""
return _controls_.DirFilterListCtrl_Create(*args, **kwargs)
def FillFilterList(*args, **kwargs):
"""FillFilterList(self, String filter, int defaultFilter)"""
return _controls_.DirFilterListCtrl_FillFilterList(*args, **kwargs)
_controls_.DirFilterListCtrl_swigregister(DirFilterListCtrl)
def PreDirFilterListCtrl(*args, **kwargs):
"""PreDirFilterListCtrl() -> DirFilterListCtrl"""
val = _controls_.new_PreDirFilterListCtrl(*args, **kwargs)
return val
#---------------------------------------------------------------------------
class PyControl(_core.Control):
"""Proxy of C++ PyControl class"""
thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
def __init__(self, *args, **kwargs):
"""
__init__(self, Window parent, int id=-1, Point pos=DefaultPosition,
Size size=DefaultSize, long style=0, Validator validator=DefaultValidator,
String name=ControlNameStr) -> PyControl
"""
_controls_.PyControl_swiginit(self,_controls_.new_PyControl(*args, **kwargs))
self._setOORInfo(self);PyControl._setCallbackInfo(self, self, PyControl)
def _setCallbackInfo(*args, **kwargs):
"""_setCallbackInfo(self, PyObject self, PyObject _class)"""
return _controls_.PyControl__setCallbackInfo(*args, **kwargs)
SetBestSize = wx.Window.SetInitialSize
def DoEraseBackground(*args, **kwargs):
"""DoEraseBackground(self, DC dc) -> bool"""
return _controls_.PyControl_DoEraseBackground(*args, **kwargs)
def DoMoveWindow(*args, **kwargs):
"""DoMoveWindow(self, int x, int y, int width, int height)"""
return _controls_.PyControl_DoMoveWindow(*args, **kwargs)
def DoSetSize(*args, **kwargs):
"""DoSetSize(self, int x, int y, int width, int height, int sizeFlags=SIZE_AUTO)"""
return _controls_.PyControl_DoSetSize(*args, **kwargs)
def DoSetClientSize(*args, **kwargs):
"""DoSetClientSize(self, int width, int height)"""
return _controls_.PyControl_DoSetClientSize(*args, **kwargs)
def DoSetVirtualSize(*args, **kwargs):
"""DoSetVirtualSize(self, int x, int y)"""
return _controls_.PyControl_DoSetVirtualSize(*args, **kwargs)
def DoGetSize(*args, **kwargs):
"""DoGetSize() -> (width, height)"""
return _controls_.PyControl_DoGetSize(*args, **kwargs)
def DoGetClientSize(*args, **kwargs):
"""DoGetClientSize() -> (width, height)"""
return _controls_.PyControl_DoGetClientSize(*args, **kwargs)
def DoGetPosition(*args, **kwargs):
"""DoGetPosition() -> (x,y)"""
return _controls_.PyControl_DoGetPosition(*args, **kwargs)
def DoGetVirtualSize(*args, **kwargs):
"""DoGetVirtualSize(self) -> Size"""
return _controls_.PyControl_DoGetVirtualSize(*args, **kwargs)
def DoGetBestSize(*args, **kwargs):
"""DoGetBestSize(self) -> Size"""
return _controls_.PyControl_DoGetBestSize(*args, **kwargs)
def GetDefaultAttributes(*args, **kwargs):
"""GetDefaultAttributes(self) -> VisualAttributes"""
return _controls_.PyControl_GetDefaultAttributes(*args, **kwargs)
def OnInternalIdle(*args, **kwargs):
"""OnInternalIdle(self)"""
return _controls_.PyControl_OnInternalIdle(*args, **kwargs)
def base_DoMoveWindow(*args, **kw):
return PyControl.DoMoveWindow(*args, **kw)
base_DoMoveWindow = wx.deprecated(base_DoMoveWindow,
"Please use PyControl.DoMoveWindow instead.")
def base_DoSetSize(*args, **kw):
return PyControl.DoSetSize(*args, **kw)
base_DoSetSize = wx.deprecated(base_DoSetSize,
"Please use PyControl.DoSetSize instead.")
def base_DoSetClientSize(*args, **kw):
return PyControl.DoSetClientSize(*args, **kw)
base_DoSetClientSize = wx.deprecated(base_DoSetClientSize,
"Please use PyControl.DoSetClientSize instead.")
def base_DoSetVirtualSize(*args, **kw):
return PyControl.DoSetVirtualSize(*args, **kw)
base_DoSetVirtualSize = wx.deprecated(base_DoSetVirtualSize,
"Please use PyControl.DoSetVirtualSize instead.")
def base_DoGetSize(*args, **kw):
return PyControl.DoGetSize(*args, **kw)
base_DoGetSize = wx.deprecated(base_DoGetSize,
"Please use PyControl.DoGetSize instead.")
def base_DoGetClientSize(*args, **kw):
return PyControl.DoGetClientSize(*args, **kw)
base_DoGetClientSize = wx.deprecated(base_DoGetClientSize,
"Please use PyControl.DoGetClientSize instead.")
def base_DoGetPosition(*args, **kw):
return PyControl.DoGetPosition(*args, **kw)
base_DoGetPosition = wx.deprecated(base_DoGetPosition,
"Please use PyControl.DoGetPosition instead.")
def base_DoGetVirtualSize(*args, **kw):
return PyControl.DoGetVirtualSize(*args, **kw)
base_DoGetVirtualSize = wx.deprecated(base_DoGetVirtualSize,
"Please use PyControl.DoGetVirtualSize instead.")
def base_DoGetBestSize(*args, **kw):
return PyControl.DoGetBestSize(*args, **kw)
base_DoGetBestSize = wx.deprecated(base_DoGetBestSize,
"Please use PyControl.DoGetBestSize instead.")
def base_InitDialog(*args, **kw):
return PyControl.InitDialog(*args, **kw)
base_InitDialog = wx.deprecated(base_InitDialog,
"Please use PyControl.InitDialog instead.")
def base_TransferDataToWindow(*args, **kw):
return PyControl.TransferDataToWindow(*args, **kw)
base_TransferDataToWindow = wx.deprecated(base_TransferDataToWindow,
"Please use PyControl.TransferDataToWindow instead.")
def base_TransferDataFromWindow(*args, **kw):
return PyControl.TransferDataFromWindow(*args, **kw)
base_TransferDataFromWindow = wx.deprecated(base_TransferDataFromWindow,
"Please use PyControl.TransferDataFromWindow instead.")
def base_Validate(*args, **kw):
return PyControl.Validate(*args, **kw)
base_Validate = wx.deprecated(base_Validate,
"Please use PyControl.Validate instead.")
def base_AcceptsFocus(*args, **kw):
return PyControl.AcceptsFocus(*args, **kw)
base_AcceptsFocus = wx.deprecated(base_AcceptsFocus,
"Please use PyControl.AcceptsFocus instead.")
def base_AcceptsFocusFromKeyboard(*args, **kw):
return PyControl.AcceptsFocusFromKeyboard(*args, **kw)
base_AcceptsFocusFromKeyboard = wx.deprecated(base_AcceptsFocusFromKeyboard,
"Please use PyControl.AcceptsFocusFromKeyboard instead.")
def base_GetMaxSize(*args, **kw):
return PyControl.GetMaxSize(*args, **kw)
base_GetMaxSize = wx.deprecated(base_GetMaxSize,
"Please use PyControl.GetMaxSize instead.")
def base_Enable(*args, **kw):
return PyControl.Enable(*args, **kw)
base_Enable = wx.deprecated(base_Enable,
"Please use PyControl.Enable instead.")
def base_AddChild(*args, **kw):
return PyControl.AddChild(*args, **kw)
base_AddChild = wx.deprecated(base_AddChild,
"Please use PyControl.AddChild instead.")
def base_RemoveChild(*args, **kw):
return PyControl.RemoveChild(*args, **kw)
base_RemoveChild = wx.deprecated(base_RemoveChild,
"Please use PyControl.RemoveChild instead.")
def base_ShouldInheritColours(*args, **kw):
return PyControl.ShouldInheritColours(*args, **kw)
base_ShouldInheritColours = wx.deprecated(base_ShouldInheritColours,
"Please use PyControl.ShouldInheritColours instead.")
def base_GetDefaultAttributes(*args, **kw):
return PyControl.GetDefaultAttributes(*args, **kw)
base_GetDefaultAttributes = wx.deprecated(base_GetDefaultAttributes,
"Please use PyControl.GetDefaultAttributes instead.")
def base_OnInternalIdle(*args, **kw):
return PyControl.OnInternalIdle(*args, **kw)
base_OnInternalIdle = wx.deprecated(base_OnInternalIdle,
"Please use PyControl.OnInternalIdle instead.")
_controls_.PyControl_swigregister(PyControl)
def PrePyControl(*args, **kwargs):
"""PrePyControl() -> PyControl"""
val = _controls_.new_PrePyControl(*args, **kwargs)
return val
#---------------------------------------------------------------------------
wxEVT_HELP = _controls_.wxEVT_HELP
wxEVT_DETAILED_HELP = _controls_.wxEVT_DETAILED_HELP
EVT_HELP = wx.PyEventBinder( wxEVT_HELP, 1)
EVT_HELP_RANGE = wx.PyEventBinder( wxEVT_HELP, 2)
EVT_DETAILED_HELP = wx.PyEventBinder( wxEVT_DETAILED_HELP, 1)
EVT_DETAILED_HELP_RANGE = wx.PyEventBinder( wxEVT_DETAILED_HELP, 2)
class HelpEvent(_core.CommandEvent):
"""
A help event is sent when the user has requested context-sensitive
help. This can either be caused by the application requesting
context-sensitive help mode via wx.ContextHelp, or (on MS Windows) by
the system generating a WM_HELP message when the user pressed F1 or
clicked on the query button in a dialog caption.
A help event is sent to the window that the user clicked on, and is
propagated up the window hierarchy until the event is processed or
there are no more event handlers. The application should call
event.GetId to check the identity of the clicked-on window, and then
either show some suitable help or call event.Skip if the identifier is
unrecognised. Calling Skip is important because it allows wxWindows to
generate further events for ancestors of the clicked-on
window. Otherwise it would be impossible to show help for container
windows, since processing would stop after the first window found.
"""
thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
Origin_Unknown = _controls_.HelpEvent_Origin_Unknown
Origin_Keyboard = _controls_.HelpEvent_Origin_Keyboard
Origin_HelpButton = _controls_.HelpEvent_Origin_HelpButton
def __init__(self, *args, **kwargs):
"""
__init__(self, EventType type=wxEVT_NULL, int winid=0, Point pt=DefaultPosition,
int origin=Origin_Unknown) -> HelpEvent
"""
_controls_.HelpEvent_swiginit(self,_controls_.new_HelpEvent(*args, **kwargs))
def GetPosition(*args, **kwargs):
"""
GetPosition(self) -> Point
Returns the left-click position of the mouse, in screen
coordinates. This allows the application to position the help
appropriately.
"""
return _controls_.HelpEvent_GetPosition(*args, **kwargs)
def SetPosition(*args, **kwargs):
"""
SetPosition(self, Point pos)
Sets the left-click position of the mouse, in screen coordinates.
"""
return _controls_.HelpEvent_SetPosition(*args, **kwargs)
def GetLink(*args, **kwargs):
"""
GetLink(self) -> String
Get an optional link to further help
"""
return _controls_.HelpEvent_GetLink(*args, **kwargs)
def SetLink(*args, **kwargs):
"""
SetLink(self, String link)
Set an optional link to further help
"""
return _controls_.HelpEvent_SetLink(*args, **kwargs)
def GetTarget(*args, **kwargs):
"""
GetTarget(self) -> String
Get an optional target to display help in. E.g. a window specification
"""
return _controls_.HelpEvent_GetTarget(*args, **kwargs)
def SetTarget(*args, **kwargs):
"""
SetTarget(self, String target)
Set an optional target to display help in. E.g. a window specification
"""
return _controls_.HelpEvent_SetTarget(*args, **kwargs)
def GetOrigin(*args, **kwargs):
"""
GetOrigin(self) -> int
Optiononal indication of the source of the event.
"""
return _controls_.HelpEvent_GetOrigin(*args, **kwargs)
def SetOrigin(*args, **kwargs):
"""SetOrigin(self, int origin)"""
return _controls_.HelpEvent_SetOrigin(*args, **kwargs)
Link = property(GetLink,SetLink,doc="See `GetLink` and `SetLink`")
Origin = property(GetOrigin,SetOrigin,doc="See `GetOrigin` and `SetOrigin`")
Position = property(GetPosition,SetPosition,doc="See `GetPosition` and `SetPosition`")
Target = property(GetTarget,SetTarget,doc="See `GetTarget` and `SetTarget`")
_controls_.HelpEvent_swigregister(HelpEvent)
class ContextHelp(_core.Object):
"""
This class changes the cursor to a query and puts the application into
a 'context-sensitive help mode'. When the user left-clicks on a window
within the specified window, a ``EVT_HELP`` event is sent to that
control, and the application may respond to it by popping up some
help.
There are a couple of ways to invoke this behaviour implicitly:
* Use the wx.WS_EX_CONTEXTHELP extended style for a dialog or frame
(Windows only). This will put a question mark in the titlebar,
and Windows will put the application into context-sensitive help
mode automatically, with further programming.
* Create a `wx.ContextHelpButton`, whose predefined behaviour is
to create a context help object. Normally you will write your
application so that this button is only added to a dialog for
non-Windows platforms (use ``wx.WS_EX_CONTEXTHELP`` on
Windows).
:see: `wx.ContextHelpButton`
"""
thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
def __init__(self, *args, **kwargs):
"""
__init__(self, Window window=None, bool doNow=True) -> ContextHelp
Constructs a context help object, calling BeginContextHelp if doNow is
true (the default).
If window is None, the top window is used.
"""
_controls_.ContextHelp_swiginit(self,_controls_.new_ContextHelp(*args, **kwargs))
__swig_destroy__ = _controls_.delete_ContextHelp
__del__ = lambda self : None;
def BeginContextHelp(*args, **kwargs):
"""
BeginContextHelp(self, Window window=None) -> bool
Puts the application into context-sensitive help mode. window is the
window which will be used to catch events; if NULL, the top window
will be used.
Returns true if the application was successfully put into
context-sensitive help mode. This function only returns when the event
loop has finished.
"""
return _controls_.ContextHelp_BeginContextHelp(*args, **kwargs)
def EndContextHelp(*args, **kwargs):
"""
EndContextHelp(self) -> bool
Ends context-sensitive help mode. Not normally called by the
application.
"""
return _controls_.ContextHelp_EndContextHelp(*args, **kwargs)
_controls_.ContextHelp_swigregister(ContextHelp)
class ContextHelpButton(BitmapButton):
"""
Instances of this class may be used to add a question mark button that
when pressed, puts the application into context-help mode. It does
this by creating a wx.ContextHelp object which itself generates a
``EVT_HELP`` event when the user clicks on a window.
On Windows, you may add a question-mark icon to a dialog by use of the
``wx.DIALOG_EX_CONTEXTHELP`` extra style, but on other platforms you
will have to add a button explicitly, usually next to OK, Cancel or
similar buttons.
:see: `wx.ContextHelp`, `wx.ContextHelpButton`
"""
thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
def __init__(self, *args, **kwargs):
"""
__init__(self, Window parent, int id=ID_CONTEXT_HELP, Point pos=DefaultPosition,
Size size=DefaultSize, long style=BU_AUTODRAW) -> ContextHelpButton
Constructor, creating and showing a context help button.
"""
_controls_.ContextHelpButton_swiginit(self,_controls_.new_ContextHelpButton(*args, **kwargs))
self._setOORInfo(self)
_controls_.ContextHelpButton_swigregister(ContextHelpButton)
class HelpProvider(object):
"""
wx.HelpProvider is an abstract class used by a program
implementing context-sensitive help to show the help text for the
given window.
The current help provider must be explicitly set by the
application using wx.HelpProvider.Set().
"""
thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
def __init__(self): raise AttributeError, "No constructor defined"
__repr__ = _swig_repr
__swig_destroy__ = _controls_.delete_HelpProvider
__del__ = lambda self : None;
def Set(*args, **kwargs):
"""
Set(HelpProvider helpProvider) -> HelpProvider
Sset the current, application-wide help provider. Returns the previous
one. Unlike some other classes, the help provider is not created on
demand. This must be explicitly done by the application.
"""
return _controls_.HelpProvider_Set(*args, **kwargs)
Set = staticmethod(Set)
def Get(*args, **kwargs):
"""
Get() -> HelpProvider
Return the current application-wide help provider.
"""
return _controls_.HelpProvider_Get(*args, **kwargs)
Get = staticmethod(Get)
def GetHelp(*args, **kwargs):
"""
GetHelp(self, Window window) -> String
Gets the help string for this window. Its interpretation is dependent
on the help provider except that empty string always means that no
help is associated with the window.
"""
return _controls_.HelpProvider_GetHelp(*args, **kwargs)
def ShowHelp(*args, **kwargs):
"""
ShowHelp(self, Window window) -> bool
Shows help for the given window. Uses GetHelp internally if
applicable. Returns True if it was done, or False if no help was
available for this window.
"""
return _controls_.HelpProvider_ShowHelp(*args, **kwargs)
def ShowHelpAtPoint(*args, **kwargs):
"""
ShowHelpAtPoint(self, wxWindowBase window, Point pt, int origin) -> bool
Show help for the given window (uses window.GetHelpAtPoint()
internally if applicable), return true if it was done or false if no
help available for this window.
"""
return _controls_.HelpProvider_ShowHelpAtPoint(*args, **kwargs)
def AddHelp(*args, **kwargs):
"""
AddHelp(self, Window window, String text)
Associates the text with the given window.
"""
return _controls_.HelpProvider_AddHelp(*args, **kwargs)
def AddHelpById(*args, **kwargs):
"""
AddHelpById(self, int id, String text)
This version associates the given text with all windows with this
id. May be used to set the same help string for all Cancel buttons in
the application, for example.
"""
return _controls_.HelpProvider_AddHelpById(*args, **kwargs)
def RemoveHelp(*args, **kwargs):
"""
RemoveHelp(self, Window window)
Removes the association between the window pointer and the help
text. This is called by the wx.Window destructor. Without this, the
table of help strings will fill up and when window pointers are
reused, the wrong help string will be found.
"""
return _controls_.HelpProvider_RemoveHelp(*args, **kwargs)
def Destroy(*args, **kwargs):
"""Destroy(self)"""
args[0].this.own(False)
return _controls_.HelpProvider_Destroy(*args, **kwargs)
_controls_.HelpProvider_swigregister(HelpProvider)
def HelpProvider_Set(*args, **kwargs):
"""
HelpProvider_Set(HelpProvider helpProvider) -> HelpProvider
Sset the current, application-wide help provider. Returns the previous
one. Unlike some other classes, the help provider is not created on
demand. This must be explicitly done by the application.
"""
return _controls_.HelpProvider_Set(*args, **kwargs)
def HelpProvider_Get(*args):
"""
HelpProvider_Get() -> HelpProvider
Return the current application-wide help provider.
"""
return _controls_.HelpProvider_Get(*args)
class SimpleHelpProvider(HelpProvider):
"""
wx.SimpleHelpProvider is an implementation of `wx.HelpProvider` which
supports only plain text help strings, and shows the string associated
with the control (if any) in a tooltip.
"""
thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
def __init__(self, *args, **kwargs):
"""
__init__(self) -> SimpleHelpProvider
wx.SimpleHelpProvider is an implementation of `wx.HelpProvider` which
supports only plain text help strings, and shows the string associated
with the control (if any) in a tooltip.
"""
_controls_.SimpleHelpProvider_swiginit(self,_controls_.new_SimpleHelpProvider(*args, **kwargs))
_controls_.SimpleHelpProvider_swigregister(SimpleHelpProvider)
#---------------------------------------------------------------------------
class DragImage(_core.Object):
"""Proxy of C++ DragImage class"""
thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
def __init__(self, *args, **kwargs):
"""__init__(self, Bitmap image, Cursor cursor=wxNullCursor) -> DragImage"""
_controls_.DragImage_swiginit(self,_controls_.new_DragImage(*args, **kwargs))
__swig_destroy__ = _controls_.delete_DragImage
__del__ = lambda self : None;
def SetBackingBitmap(*args, **kwargs):
"""SetBackingBitmap(self, Bitmap bitmap)"""
return _controls_.DragImage_SetBackingBitmap(*args, **kwargs)
def BeginDrag(*args, **kwargs):
"""
BeginDrag(self, Point hotspot, Window window, bool fullScreen=False,
Rect rect=None) -> bool
"""
return _controls_.DragImage_BeginDrag(*args, **kwargs)
def BeginDragBounded(*args, **kwargs):
"""BeginDragBounded(self, Point hotspot, Window window, Window boundingWindow) -> bool"""
return _controls_.DragImage_BeginDragBounded(*args, **kwargs)
def EndDrag(*args, **kwargs):
"""EndDrag(self) -> bool"""
return _controls_.DragImage_EndDrag(*args, **kwargs)
def Move(*args, **kwargs):
"""Move(self, Point pt) -> bool"""
return _controls_.DragImage_Move(*args, **kwargs)
def Show(*args, **kwargs):
"""Show(self) -> bool"""
return _controls_.DragImage_Show(*args, **kwargs)
def Hide(*args, **kwargs):
"""Hide(self) -> bool"""
return _controls_.DragImage_Hide(*args, **kwargs)
def GetImageRect(*args, **kwargs):
"""GetImageRect(self, Point pos) -> Rect"""
return _controls_.DragImage_GetImageRect(*args, **kwargs)
def DoDrawImage(*args, **kwargs):
"""DoDrawImage(self, DC dc, Point pos) -> bool"""
return _controls_.DragImage_DoDrawImage(*args, **kwargs)
def UpdateBackingFromWindow(*args, **kwargs):
"""UpdateBackingFromWindow(self, DC windowDC, MemoryDC destDC, Rect sourceRect, Rect destRect) -> bool"""
return _controls_.DragImage_UpdateBackingFromWindow(*args, **kwargs)
def RedrawImage(*args, **kwargs):
"""RedrawImage(self, Point oldPos, Point newPos, bool eraseOld, bool drawNew) -> bool"""
return _controls_.DragImage_RedrawImage(*args, **kwargs)
ImageRect = property(GetImageRect,doc="See `GetImageRect`")
_controls_.DragImage_swigregister(DragImage)
def DragIcon(*args, **kwargs):
"""DragIcon(Icon image, Cursor cursor=wxNullCursor) -> DragImage"""
val = _controls_.new_DragIcon(*args, **kwargs)
return val
def DragString(*args, **kwargs):
"""DragString(String str, Cursor cursor=wxNullCursor) -> DragImage"""
val = _controls_.new_DragString(*args, **kwargs)
return val
def DragTreeItem(*args, **kwargs):
"""DragTreeItem(TreeCtrl treeCtrl, TreeItemId id) -> DragImage"""
val = _controls_.new_DragTreeItem(*args, **kwargs)
return val
def DragListItem(*args, **kwargs):
"""DragListItem(ListCtrl listCtrl, long id) -> DragImage"""
val = _controls_.new_DragListItem(*args, **kwargs)
return val
#---------------------------------------------------------------------------
DP_DEFAULT = _controls_.DP_DEFAULT
DP_SPIN = _controls_.DP_SPIN
DP_DROPDOWN = _controls_.DP_DROPDOWN
DP_SHOWCENTURY = _controls_.DP_SHOWCENTURY
DP_ALLOWNONE = _controls_.DP_ALLOWNONE
class DatePickerCtrlBase(_core.Control):
"""Proxy of C++ DatePickerCtrlBase class"""
thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
def __init__(self): raise AttributeError, "No constructor defined"
__repr__ = _swig_repr
def SetValue(*args, **kwargs):
"""
SetValue(self, DateTime dt)
Changes the current value of the control. The date should be valid and
included in the currently selected range, if any.
Calling this method does not result in a date change event.
"""
return _controls_.DatePickerCtrlBase_SetValue(*args, **kwargs)
def GetValue(*args, **kwargs):
"""
GetValue(self) -> DateTime
Returns the currently selected date. If there is no selection or the
selection is outside of the current range, an invalid `wx.DateTime`
object is returned.
"""
return _controls_.DatePickerCtrlBase_GetValue(*args, **kwargs)
def SetRange(*args, **kwargs):
"""
SetRange(self, DateTime dt1, DateTime dt2)
Sets the valid range for the date selection. If dt1 is valid, it
becomes the earliest date (inclusive) accepted by the control. If dt2
is valid, it becomes the latest possible date.
If the current value of the control is outside of the newly set range
bounds, the behaviour is undefined.
"""
return _controls_.DatePickerCtrlBase_SetRange(*args, **kwargs)
def GetLowerLimit(*args, **kwargs):
"""
GetLowerLimit(self) -> DateTime
Get the lower limit of the valid range for the date selection, if any.
If there is no range or there is no lower limit, then the
`wx.DateTime` value returned will be invalid.
"""
return _controls_.DatePickerCtrlBase_GetLowerLimit(*args, **kwargs)
def GetUpperLimit(*args, **kwargs):
"""
GetUpperLimit(self) -> DateTime
Get the upper limit of the valid range for the date selection, if any.
If there is no range or there is no upper limit, then the
`wx.DateTime` value returned will be invalid.
"""
return _controls_.DatePickerCtrlBase_GetUpperLimit(*args, **kwargs)
LowerLimit = property(GetLowerLimit,doc="See `GetLowerLimit`")
UpperLimit = property(GetUpperLimit,doc="See `GetUpperLimit`")
Value = property(GetValue,SetValue,doc="See `GetValue` and `SetValue`")
_controls_.DatePickerCtrlBase_swigregister(DatePickerCtrlBase)
DatePickerCtrlNameStr = cvar.DatePickerCtrlNameStr
class DatePickerCtrl(DatePickerCtrlBase):
"""
This control allows the user to select a date. Unlike
`wx.calendar.CalendarCtrl`, which is a relatively big control,
`wx.DatePickerCtrl` is implemented as a small window showing the
currently selected date. The control can be edited using the keyboard,
and can also display a popup window for more user-friendly date
selection, depending on the styles used and the platform.
"""
thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
def __init__(self, *args, **kwargs):
"""
__init__(self, Window parent, int id=-1, DateTime dt=wxDefaultDateTime,
Point pos=DefaultPosition, Size size=DefaultSize,
long style=wxDP_DEFAULT|wxDP_SHOWCENTURY,
Validator validator=DefaultValidator,
String name=DatePickerCtrlNameStr) -> DatePickerCtrl
Create a new DatePickerCtrl.
"""
_controls_.DatePickerCtrl_swiginit(self,_controls_.new_DatePickerCtrl(*args, **kwargs))
self._setOORInfo(self)
def Create(*args, **kwargs):
"""
Create(self, Window parent, int id=-1, DateTime dt=wxDefaultDateTime,
Point pos=DefaultPosition, Size size=DefaultSize,
long style=wxDP_DEFAULT|wxDP_SHOWCENTURY,
Validator validator=DefaultValidator,
String name=DatePickerCtrlNameStr) -> bool
Create the GUI parts of the DatePickerCtrl, for use in 2-phase
creation.
"""
return _controls_.DatePickerCtrl_Create(*args, **kwargs)
_controls_.DatePickerCtrl_swigregister(DatePickerCtrl)
def PreDatePickerCtrl(*args, **kwargs):
"""
PreDatePickerCtrl() -> DatePickerCtrl
Precreate a DatePickerCtrl for use in 2-phase creation.
"""
val = _controls_.new_PreDatePickerCtrl(*args, **kwargs)
return val
class GenericDatePickerCtrl(DatePickerCtrlBase):
"""Proxy of C++ GenericDatePickerCtrl class"""
thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
def __init__(self, *args, **kwargs):
"""
__init__(self, Window parent, int id=-1, DateTime dt=wxDefaultDateTime,
Point pos=DefaultPosition, Size size=DefaultSize,
long style=wxDP_DEFAULT|wxDP_SHOWCENTURY,
Validator validator=DefaultValidator,
String name=DatePickerCtrlNameStr) -> GenericDatePickerCtrl
Create a new GenericDatePickerCtrl.
"""
_controls_.GenericDatePickerCtrl_swiginit(self,_controls_.new_GenericDatePickerCtrl(*args, **kwargs))
self._setOORInfo(self)
def Create(*args, **kwargs):
"""
Create(self, Window parent, int id=-1, DateTime dt=wxDefaultDateTime,
Point pos=DefaultPosition, Size size=DefaultSize,
long style=wxDP_DEFAULT|wxDP_SHOWCENTURY,
Validator validator=DefaultValidator,
String name=DatePickerCtrlNameStr) -> bool
Create the GUI parts of the GenericDatePickerCtrl, for use in 2-phase
creation.
"""
return _controls_.GenericDatePickerCtrl_Create(*args, **kwargs)
_controls_.GenericDatePickerCtrl_swigregister(GenericDatePickerCtrl)
def PreGenericDatePickerCtrl(*args, **kwargs):
"""
PreGenericDatePickerCtrl() -> GenericDatePickerCtrl
Precreate a GenericDatePickerCtrl for use in 2-phase creation.
"""
val = _controls_.new_PreGenericDatePickerCtrl(*args, **kwargs)
return val
HL_CONTEXTMENU = _controls_.HL_CONTEXTMENU
HL_ALIGN_LEFT = _controls_.HL_ALIGN_LEFT
HL_ALIGN_RIGHT = _controls_.HL_ALIGN_RIGHT
HL_ALIGN_CENTRE = _controls_.HL_ALIGN_CENTRE
HL_DEFAULT_STYLE = _controls_.HL_DEFAULT_STYLE
#---------------------------------------------------------------------------
class HyperlinkCtrl(_core.Control):
"""
A static text control that emulates a hyperlink. The link is displayed
in an appropriate text style, derived from the control's normal font.
When the mouse rolls over the link, the cursor changes to a hand and
the link's color changes to the active color.
Clicking on the link does not launch a web browser; instead, a
wx.HyperlinkEvent is fired. Use the wx.EVT_HYPERLINK to catch link
events.
"""
thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
def __init__(self, *args, **kwargs):
"""
__init__(self, Window parent, int id=-1, String label=wxEmptyString,
String url=wxEmptyString, Point pos=DefaultPosition,
Size size=DefaultSize, long style=HL_DEFAULT_STYLE,
String name=HyperlinkCtrlNameStr) -> HyperlinkCtrl
A static text control that emulates a hyperlink. The link is displayed
in an appropriate text style, derived from the control's normal font.
When the mouse rolls over the link, the cursor changes to a hand and
the link's color changes to the active color.
Clicking on the link does not launch a web browser; instead, a
wx.HyperlinkEvent is fired. Use the wx.EVT_HYPERLINK to catch link
events.
"""
_controls_.HyperlinkCtrl_swiginit(self,_controls_.new_HyperlinkCtrl(*args, **kwargs))
self._setOORInfo(self)
def Create(*args, **kwargs):
"""
Create(self, Window parent, int id=-1, String label=wxEmptyString,
String url=wxEmptyString, Point pos=DefaultPosition,
Size size=DefaultSize, long style=HL_DEFAULT_STYLE,
String name=HyperlinkCtrlNameStr) -> bool
"""
return _controls_.HyperlinkCtrl_Create(*args, **kwargs)
def GetHoverColour(*args, **kwargs):
"""GetHoverColour(self) -> Colour"""
return _controls_.HyperlinkCtrl_GetHoverColour(*args, **kwargs)
def SetHoverColour(*args, **kwargs):
"""SetHoverColour(self, Colour colour)"""
return _controls_.HyperlinkCtrl_SetHoverColour(*args, **kwargs)
def GetNormalColour(*args, **kwargs):
"""GetNormalColour(self) -> Colour"""
return _controls_.HyperlinkCtrl_GetNormalColour(*args, **kwargs)
def SetNormalColour(*args, **kwargs):
"""SetNormalColour(self, Colour colour)"""
return _controls_.HyperlinkCtrl_SetNormalColour(*args, **kwargs)
def GetVisitedColour(*args, **kwargs):
"""GetVisitedColour(self) -> Colour"""
return _controls_.HyperlinkCtrl_GetVisitedColour(*args, **kwargs)
def SetVisitedColour(*args, **kwargs):
"""SetVisitedColour(self, Colour colour)"""
return _controls_.HyperlinkCtrl_SetVisitedColour(*args, **kwargs)
def GetURL(*args, **kwargs):
"""GetURL(self) -> String"""
return _controls_.HyperlinkCtrl_GetURL(*args, **kwargs)
def SetURL(*args, **kwargs):
"""SetURL(self, String url)"""
return _controls_.HyperlinkCtrl_SetURL(*args, **kwargs)
def SetVisited(*args, **kwargs):
"""SetVisited(self, bool visited=True)"""
return _controls_.HyperlinkCtrl_SetVisited(*args, **kwargs)
def GetVisited(*args, **kwargs):
"""GetVisited(self) -> bool"""
return _controls_.HyperlinkCtrl_GetVisited(*args, **kwargs)
HoverColour = property(GetHoverColour,SetHoverColour,doc="See `GetHoverColour` and `SetHoverColour`")
NormalColour = property(GetNormalColour,SetNormalColour,doc="See `GetNormalColour` and `SetNormalColour`")
URL = property(GetURL,SetURL,doc="See `GetURL` and `SetURL`")
Visited = property(GetVisited,SetVisited,doc="See `GetVisited` and `SetVisited`")
VisitedColour = property(GetVisitedColour,SetVisitedColour,doc="See `GetVisitedColour` and `SetVisitedColour`")
_controls_.HyperlinkCtrl_swigregister(HyperlinkCtrl)
HyperlinkCtrlNameStr = cvar.HyperlinkCtrlNameStr
def PreHyperlinkCtrl(*args, **kwargs):
"""
PreHyperlinkCtrl() -> HyperlinkCtrl
A static text control that emulates a hyperlink. The link is displayed
in an appropriate text style, derived from the control's normal font.
When the mouse rolls over the link, the cursor changes to a hand and
the link's color changes to the active color.
Clicking on the link does not launch a web browser; instead, a
wx.HyperlinkEvent is fired. Use the wx.EVT_HYPERLINK to catch link
events.
"""
val = _controls_.new_PreHyperlinkCtrl(*args, **kwargs)
return val
wxEVT_COMMAND_HYPERLINK = _controls_.wxEVT_COMMAND_HYPERLINK
class HyperlinkEvent(_core.CommandEvent):
"""Proxy of C++ HyperlinkEvent class"""
thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
def __init__(self, *args, **kwargs):
"""__init__(self, Object generator, int id, String url) -> HyperlinkEvent"""
_controls_.HyperlinkEvent_swiginit(self,_controls_.new_HyperlinkEvent(*args, **kwargs))
def GetURL(*args, **kwargs):
"""GetURL(self) -> String"""
return _controls_.HyperlinkEvent_GetURL(*args, **kwargs)
def SetURL(*args, **kwargs):
"""SetURL(self, String url)"""
return _controls_.HyperlinkEvent_SetURL(*args, **kwargs)
URL = property(GetURL,SetURL,doc="See `GetURL` and `SetURL`")
_controls_.HyperlinkEvent_swigregister(HyperlinkEvent)
EVT_HYPERLINK = wx.PyEventBinder( wxEVT_COMMAND_HYPERLINK, 1 )
#---------------------------------------------------------------------------
PB_USE_TEXTCTRL = _controls_.PB_USE_TEXTCTRL
class PickerBase(_core.Control):
"""
Base abstract class for all pickers which support an auxiliary text
control. This class handles all positioning and sizing of the text
control like a horizontal `wx.BoxSizer` would do, with the text
control on the left of the picker button and the proportion of the
picker fixed to value 1.
"""
thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
def __init__(self): raise AttributeError, "No constructor defined"
__repr__ = _swig_repr
def CreateBase(*args, **kwargs):
"""
CreateBase(self, Window parent, int id, String text=wxEmptyString, Point pos=DefaultPosition,
Size size=DefaultSize,
long style=0, Validator validator=DefaultValidator,
String name=wxButtonNameStr) -> bool
"""
return _controls_.PickerBase_CreateBase(*args, **kwargs)
def SetInternalMargin(*args, **kwargs):
"""
SetInternalMargin(self, int newmargin)
Sets the margin (in pixels) between the picker and the text control.
"""
return _controls_.PickerBase_SetInternalMargin(*args, **kwargs)
def GetInternalMargin(*args, **kwargs):
"""
GetInternalMargin(self) -> int
Returns the margin (in pixels) between the picker and the text
control.
"""
return _controls_.PickerBase_GetInternalMargin(*args, **kwargs)
def SetTextCtrlProportion(*args, **kwargs):
"""
SetTextCtrlProportion(self, int prop)
Sets the proportion between the text control and the picker button.
This is used to set relative sizes of the text contorl and the picker.
The value passed to this function must be >= 1.
"""
return _controls_.PickerBase_SetTextCtrlProportion(*args, **kwargs)
def GetTextCtrlProportion(*args, **kwargs):
"""
GetTextCtrlProportion(self) -> int
Returns the proportion between the text control and the picker.
"""
return _controls_.PickerBase_GetTextCtrlProportion(*args, **kwargs)
def SetPickerCtrlProportion(*args, **kwargs):
"""
SetPickerCtrlProportion(self, int prop)
Sets the proportion value of the picker.
"""
return _controls_.PickerBase_SetPickerCtrlProportion(*args, **kwargs)
def GetPickerCtrlProportion(*args, **kwargs):
"""
GetPickerCtrlProportion(self) -> int
Gets the proportion value of the picker.
"""
return _controls_.PickerBase_GetPickerCtrlProportion(*args, **kwargs)
def IsTextCtrlGrowable(*args, **kwargs):
"""IsTextCtrlGrowable(self) -> bool"""
return _controls_.PickerBase_IsTextCtrlGrowable(*args, **kwargs)
def SetTextCtrlGrowable(*args, **kwargs):
"""SetTextCtrlGrowable(self, bool grow=True)"""
return _controls_.PickerBase_SetTextCtrlGrowable(*args, **kwargs)
def IsPickerCtrlGrowable(*args, **kwargs):
"""IsPickerCtrlGrowable(self) -> bool"""
return _controls_.PickerBase_IsPickerCtrlGrowable(*args, **kwargs)
def SetPickerCtrlGrowable(*args, **kwargs):
"""SetPickerCtrlGrowable(self, bool grow=True)"""
return _controls_.PickerBase_SetPickerCtrlGrowable(*args, **kwargs)
def HasTextCtrl(*args, **kwargs):
"""
HasTextCtrl(self) -> bool
Returns true if this class has a valid text control (i.e. if the
wx.PB_USE_TEXTCTRL style was given when creating this control).
"""
return _controls_.PickerBase_HasTextCtrl(*args, **kwargs)
def GetTextCtrl(*args, **kwargs):
"""
GetTextCtrl(self) -> TextCtrl
Returns a pointer to the text control handled by this class or None if
the wx.PB_USE_TEXTCTRL style was not specified when this control was
created.
Very important: the contents of the text control could be containing
an invalid representation of the entity which can be chosen through
the picker (e.g. the user entered an invalid colour syntax because of
a typo). Thus you should never parse the content of the textctrl to
get the user's input; rather use the derived-class getter
(e.g. `wx.ColourPickerCtrl.GetColour`, `wx.FilePickerCtrl.GetPath`,
etc).
"""
return _controls_.PickerBase_GetTextCtrl(*args, **kwargs)
def GetPickerCtrl(*args, **kwargs):
"""GetPickerCtrl(self) -> Control"""
return _controls_.PickerBase_GetPickerCtrl(*args, **kwargs)
InternalMargin = property(GetInternalMargin,SetInternalMargin,doc="See `GetInternalMargin` and `SetInternalMargin`")
PickerCtrl = property(GetPickerCtrl,doc="See `GetPickerCtrl`")
PickerCtrlProportion = property(GetPickerCtrlProportion,SetPickerCtrlProportion,doc="See `GetPickerCtrlProportion` and `SetPickerCtrlProportion`")
TextCtrl = property(GetTextCtrl,doc="See `GetTextCtrl`")
TextCtrlProportion = property(GetTextCtrlProportion,SetTextCtrlProportion,doc="See `GetTextCtrlProportion` and `SetTextCtrlProportion`")
TextCtrlGrowable = property(IsTextCtrlGrowable,SetTextCtrlGrowable,doc="See `IsTextCtrlGrowable` and `SetTextCtrlGrowable`")
PickerCtrlGrowable = property(IsPickerCtrlGrowable,SetPickerCtrlGrowable,doc="See `IsPickerCtrlGrowable` and `SetPickerCtrlGrowable`")
_controls_.PickerBase_swigregister(PickerBase)
class PyPickerBase(PickerBase):
"""Proxy of C++ PyPickerBase class"""
thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
def __init__(self, *args, **kwargs):
"""
__init__(self, Window parent, int id=-1, String text=wxEmptyString,
Point pos=DefaultPosition, Size size=DefaultSize,
long style=0, Validator validator=DefaultValidator,
String name=wxButtonNameStr) -> PyPickerBase
"""
_controls_.PyPickerBase_swiginit(self,_controls_.new_PyPickerBase(*args, **kwargs))
self._setOORInfo(self);PyPickerBase._setCallbackInfo(self, self, PyPickerBase)
def _setCallbackInfo(*args, **kwargs):
"""_setCallbackInfo(self, PyObject self, PyObject _class)"""
return _controls_.PyPickerBase__setCallbackInfo(*args, **kwargs)
def UpdatePickerFromTextCtrl(*args, **kwargs):
"""UpdatePickerFromTextCtrl(self)"""
return _controls_.PyPickerBase_UpdatePickerFromTextCtrl(*args, **kwargs)
def UpdateTextCtrlFromPicker(*args, **kwargs):
"""UpdateTextCtrlFromPicker(self)"""
return _controls_.PyPickerBase_UpdateTextCtrlFromPicker(*args, **kwargs)
def GetTextCtrlStyle(*args, **kwargs):
"""GetTextCtrlStyle(self, long style) -> long"""
return _controls_.PyPickerBase_GetTextCtrlStyle(*args, **kwargs)
def GetPickerStyle(*args, **kwargs):
"""GetPickerStyle(self, long style) -> long"""
return _controls_.PyPickerBase_GetPickerStyle(*args, **kwargs)
def SetTextCtrl(*args, **kwargs):
"""SetTextCtrl(self, TextCtrl text)"""
return _controls_.PyPickerBase_SetTextCtrl(*args, **kwargs)
def SetPickerCtrl(*args, **kwargs):
"""SetPickerCtrl(self, Control picker)"""
return _controls_.PyPickerBase_SetPickerCtrl(*args, **kwargs)
def PostCreation(*args, **kwargs):
"""PostCreation(self)"""
return _controls_.PyPickerBase_PostCreation(*args, **kwargs)
_controls_.PyPickerBase_swigregister(PyPickerBase)
def PrePyPickerBase(*args, **kwargs):
"""PrePyPickerBase() -> PyPickerBase"""
val = _controls_.new_PrePyPickerBase(*args, **kwargs)
return val
#---------------------------------------------------------------------------
CLRP_SHOW_LABEL = _controls_.CLRP_SHOW_LABEL
CLRP_USE_TEXTCTRL = _controls_.CLRP_USE_TEXTCTRL
CLRP_DEFAULT_STYLE = _controls_.CLRP_DEFAULT_STYLE
class ColourPickerCtrl(PickerBase):
"""
This control allows the user to select a colour. The implementation
varies by platform but is usually a button which brings up a
`wx.ColourDialog` when clicked.
"""
thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
def __init__(self, *args, **kwargs):
"""
__init__(self, Window parent, int id=-1, Colour col=*wxBLACK, Point pos=DefaultPosition,
Size size=DefaultSize,
long style=CLRP_DEFAULT_STYLE, Validator validator=DefaultValidator,
String name=ColourPickerCtrlNameStr) -> ColourPickerCtrl
This control allows the user to select a colour. The implementation
varies by platform but is usually a button which brings up a
`wx.ColourDialog` when clicked.
"""
_controls_.ColourPickerCtrl_swiginit(self,_controls_.new_ColourPickerCtrl(*args, **kwargs))
self._setOORInfo(self)
def Create(*args, **kwargs):
"""
Create(self, Window parent, int id, Colour col=*wxBLACK, Point pos=DefaultPosition,
Size size=DefaultSize, long style=CLRP_DEFAULT_STYLE,
Validator validator=DefaultValidator,
String name=ColourPickerCtrlNameStr) -> bool
"""
return _controls_.ColourPickerCtrl_Create(*args, **kwargs)
def GetColour(*args, **kwargs):
"""
GetColour(self) -> Colour
Returns the currently selected colour.
"""
return _controls_.ColourPickerCtrl_GetColour(*args, **kwargs)
def SetColour(*args, **kwargs):
"""
SetColour(self, Colour col)
Set the displayed colour.
"""
return _controls_.ColourPickerCtrl_SetColour(*args, **kwargs)
Colour = property(GetColour,SetColour,doc="See `GetColour` and `SetColour`")
_controls_.ColourPickerCtrl_swigregister(ColourPickerCtrl)
ColourPickerCtrlNameStr = cvar.ColourPickerCtrlNameStr
def PreColourPickerCtrl(*args, **kwargs):
"""
PreColourPickerCtrl() -> ColourPickerCtrl
This control allows the user to select a colour. The implementation
varies by platform but is usually a button which brings up a
`wx.ColourDialog` when clicked.
"""
val = _controls_.new_PreColourPickerCtrl(*args, **kwargs)
return val
wxEVT_COMMAND_COLOURPICKER_CHANGED = _controls_.wxEVT_COMMAND_COLOURPICKER_CHANGED
EVT_COLOURPICKER_CHANGED = wx.PyEventBinder( wxEVT_COMMAND_COLOURPICKER_CHANGED, 1 )
class ColourPickerEvent(_core.CommandEvent):
"""Proxy of C++ ColourPickerEvent class"""
thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
def __init__(self, *args, **kwargs):
"""__init__(self, Object generator, int id, Colour col) -> ColourPickerEvent"""
_controls_.ColourPickerEvent_swiginit(self,_controls_.new_ColourPickerEvent(*args, **kwargs))
def GetColour(*args, **kwargs):
"""GetColour(self) -> Colour"""
return _controls_.ColourPickerEvent_GetColour(*args, **kwargs)
def SetColour(*args, **kwargs):
"""SetColour(self, Colour c)"""
return _controls_.ColourPickerEvent_SetColour(*args, **kwargs)
Colour = property(GetColour,SetColour,doc="See `GetColour` and `SetColour`")
_controls_.ColourPickerEvent_swigregister(ColourPickerEvent)
#---------------------------------------------------------------------------
FLP_OPEN = _controls_.FLP_OPEN
FLP_SAVE = _controls_.FLP_SAVE
FLP_OVERWRITE_PROMPT = _controls_.FLP_OVERWRITE_PROMPT
FLP_FILE_MUST_EXIST = _controls_.FLP_FILE_MUST_EXIST
FLP_CHANGE_DIR = _controls_.FLP_CHANGE_DIR
FLP_SMALL = _controls_.FLP_SMALL
DIRP_DIR_MUST_EXIST = _controls_.DIRP_DIR_MUST_EXIST
DIRP_CHANGE_DIR = _controls_.DIRP_CHANGE_DIR
DIRP_SMALL = _controls_.DIRP_SMALL
FLP_USE_TEXTCTRL = _controls_.FLP_USE_TEXTCTRL
FLP_DEFAULT_STYLE = _controls_.FLP_DEFAULT_STYLE
DIRP_USE_TEXTCTRL = _controls_.DIRP_USE_TEXTCTRL
DIRP_DEFAULT_STYLE = _controls_.DIRP_DEFAULT_STYLE
class FilePickerCtrl(PickerBase):
"""Proxy of C++ FilePickerCtrl class"""
thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
def __init__(self, *args, **kwargs):
"""
__init__(self, Window parent, int id=-1, String path=EmptyString,
String message=FileSelectorPromptStr, String wildcard=FileSelectorDefaultWildcardStr,
Point pos=DefaultPosition,
Size size=DefaultSize,
long style=FLP_DEFAULT_STYLE, Validator validator=DefaultValidator,
String name=FilePickerCtrlNameStr) -> FilePickerCtrl
"""
_controls_.FilePickerCtrl_swiginit(self,_controls_.new_FilePickerCtrl(*args, **kwargs))
self._setOORInfo(self)
def Create(*args, **kwargs):
"""
Create(self, Window parent, int id=-1, String path=EmptyString,
String message=FileSelectorPromptStr, String wildcard=FileSelectorDefaultWildcardStr,
Point pos=DefaultPosition,
Size size=DefaultSize,
long style=FLP_DEFAULT_STYLE, Validator validator=DefaultValidator,
String name=FilePickerCtrlNameStr) -> bool
"""
return _controls_.FilePickerCtrl_Create(*args, **kwargs)
def GetPath(*args, **kwargs):
"""GetPath(self) -> String"""
return _controls_.FilePickerCtrl_GetPath(*args, **kwargs)
def SetPath(*args, **kwargs):
"""SetPath(self, String str)"""
return _controls_.FilePickerCtrl_SetPath(*args, **kwargs)
def GetTextCtrlValue(*args, **kwargs):
"""GetTextCtrlValue(self) -> String"""
return _controls_.FilePickerCtrl_GetTextCtrlValue(*args, **kwargs)
def SetInitialDirectory(*args, **kwargs):
"""SetInitialDirectory(self, String dir)"""
return _controls_.FilePickerCtrl_SetInitialDirectory(*args, **kwargs)
Path = property(GetPath,SetPath,doc="See `GetPath` and `SetPath`")
TextCtrlValue = property(GetTextCtrlValue,doc="See `GetTextCtrlValue`")
_controls_.FilePickerCtrl_swigregister(FilePickerCtrl)
FilePickerCtrlNameStr = cvar.FilePickerCtrlNameStr
FileSelectorPromptStr = cvar.FileSelectorPromptStr
DirPickerCtrlNameStr = cvar.DirPickerCtrlNameStr
DirSelectorPromptStr = cvar.DirSelectorPromptStr
FileSelectorDefaultWildcardStr = cvar.FileSelectorDefaultWildcardStr
def PreFilePickerCtrl(*args, **kwargs):
"""PreFilePickerCtrl() -> FilePickerCtrl"""
val = _controls_.new_PreFilePickerCtrl(*args, **kwargs)
return val
class DirPickerCtrl(PickerBase):
"""Proxy of C++ DirPickerCtrl class"""
thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
def __init__(self, *args, **kwargs):
"""
__init__(self, Window parent, int id=-1, String path=EmptyString,
String message=DirSelectorPromptStr, Point pos=DefaultPosition,
Size size=DefaultSize, long style=DIRP_DEFAULT_STYLE,
Validator validator=DefaultValidator,
String name=DirPickerCtrlNameStr) -> DirPickerCtrl
"""
_controls_.DirPickerCtrl_swiginit(self,_controls_.new_DirPickerCtrl(*args, **kwargs))
self._setOORInfo(self)
def Create(*args, **kwargs):
"""
Create(self, Window parent, int id=-1, String path=EmptyString,
String message=DirSelectorPromptStr, Point pos=DefaultPosition,
Size size=DefaultSize, long style=DIRP_DEFAULT_STYLE,
Validator validator=DefaultValidator,
String name=DirPickerCtrlNameStr) -> bool
"""
return _controls_.DirPickerCtrl_Create(*args, **kwargs)
def GetPath(*args, **kwargs):
"""GetPath(self) -> String"""
return _controls_.DirPickerCtrl_GetPath(*args, **kwargs)
def SetPath(*args, **kwargs):
"""SetPath(self, String str)"""
return _controls_.DirPickerCtrl_SetPath(*args, **kwargs)
def GetTextCtrlValue(*args, **kwargs):
"""GetTextCtrlValue(self) -> String"""
return _controls_.DirPickerCtrl_GetTextCtrlValue(*args, **kwargs)
Path = property(GetPath,SetPath,doc="See `GetPath` and `SetPath`")
TextCtrlValue = property(GetTextCtrlValue,doc="See `GetTextCtrlValue`")
_controls_.DirPickerCtrl_swigregister(DirPickerCtrl)
def PreDirPickerCtrl(*args, **kwargs):
"""PreDirPickerCtrl() -> DirPickerCtrl"""
val = _controls_.new_PreDirPickerCtrl(*args, **kwargs)
return val
wxEVT_COMMAND_FILEPICKER_CHANGED = _controls_.wxEVT_COMMAND_FILEPICKER_CHANGED
wxEVT_COMMAND_DIRPICKER_CHANGED = _controls_.wxEVT_COMMAND_DIRPICKER_CHANGED
EVT_FILEPICKER_CHANGED = wx.PyEventBinder( wxEVT_COMMAND_FILEPICKER_CHANGED, 1 )
EVT_DIRPICKER_CHANGED = wx.PyEventBinder( wxEVT_COMMAND_DIRPICKER_CHANGED, 1 )
class FileDirPickerEvent(_core.CommandEvent):
"""Proxy of C++ FileDirPickerEvent class"""
thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
def __init__(self, *args, **kwargs):
"""__init__(self, EventType type, Object generator, int id, String path) -> FileDirPickerEvent"""
_controls_.FileDirPickerEvent_swiginit(self,_controls_.new_FileDirPickerEvent(*args, **kwargs))
def GetPath(*args, **kwargs):
"""GetPath(self) -> String"""
return _controls_.FileDirPickerEvent_GetPath(*args, **kwargs)
def SetPath(*args, **kwargs):
"""SetPath(self, String p)"""
return _controls_.FileDirPickerEvent_SetPath(*args, **kwargs)
Path = property(GetPath,SetPath,doc="See `GetPath` and `SetPath`")
_controls_.FileDirPickerEvent_swigregister(FileDirPickerEvent)
#---------------------------------------------------------------------------
FNTP_FONTDESC_AS_LABEL = _controls_.FNTP_FONTDESC_AS_LABEL
FNTP_USEFONT_FOR_LABEL = _controls_.FNTP_USEFONT_FOR_LABEL
FNTP_USE_TEXTCTRL = _controls_.FNTP_USE_TEXTCTRL
FNTP_DEFAULT_STYLE = _controls_.FNTP_DEFAULT_STYLE
class FontPickerCtrl(PickerBase):
"""Proxy of C++ FontPickerCtrl class"""
thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
def __init__(self, *args, **kwargs):
"""
__init__(self, Window parent, int id=-1, Font initial=wxNullFont,
Point pos=DefaultPosition, Size size=DefaultSize,
long style=FNTP_DEFAULT_STYLE, Validator validator=DefaultValidator,
String name=FontPickerCtrlNameStr) -> FontPickerCtrl
"""
_controls_.FontPickerCtrl_swiginit(self,_controls_.new_FontPickerCtrl(*args, **kwargs))
self._setOORInfo(self)
def Create(*args, **kwargs):
"""
Create(self, Window parent, int id=-1, Font initial=wxNullFont,
Point pos=DefaultPosition, Size size=DefaultSize,
long style=FNTP_DEFAULT_STYLE, Validator validator=DefaultValidator,
String name=FontPickerCtrlNameStr) -> bool
"""
return _controls_.FontPickerCtrl_Create(*args, **kwargs)
def GetSelectedFont(*args, **kwargs):
"""GetSelectedFont(self) -> Font"""
return _controls_.FontPickerCtrl_GetSelectedFont(*args, **kwargs)
def SetSelectedFont(*args, **kwargs):
"""SetSelectedFont(self, Font f)"""
return _controls_.FontPickerCtrl_SetSelectedFont(*args, **kwargs)
def SetMaxPointSize(*args, **kwargs):
"""SetMaxPointSize(self, unsigned int max)"""
return _controls_.FontPickerCtrl_SetMaxPointSize(*args, **kwargs)
def GetMaxPointSize(*args, **kwargs):
"""GetMaxPointSize(self) -> unsigned int"""
return _controls_.FontPickerCtrl_GetMaxPointSize(*args, **kwargs)
MaxPointSize = property(GetMaxPointSize,SetMaxPointSize,doc="See `GetMaxPointSize` and `SetMaxPointSize`")
SelectedFont = property(GetSelectedFont,SetSelectedFont,doc="See `GetSelectedFont` and `SetSelectedFont`")
_controls_.FontPickerCtrl_swigregister(FontPickerCtrl)
FontPickerCtrlNameStr = cvar.FontPickerCtrlNameStr
def PreFontPickerCtrl(*args, **kwargs):
"""PreFontPickerCtrl() -> FontPickerCtrl"""
val = _controls_.new_PreFontPickerCtrl(*args, **kwargs)
return val
wxEVT_COMMAND_FONTPICKER_CHANGED = _controls_.wxEVT_COMMAND_FONTPICKER_CHANGED
EVT_FONTPICKER_CHANGED = wx.PyEventBinder( wxEVT_COMMAND_FONTPICKER_CHANGED, 1 )
class FontPickerEvent(_core.CommandEvent):
"""Proxy of C++ FontPickerEvent class"""
thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
def __init__(self, *args, **kwargs):
"""__init__(self, Object generator, int id, Font f) -> FontPickerEvent"""
_controls_.FontPickerEvent_swiginit(self,_controls_.new_FontPickerEvent(*args, **kwargs))
def GetFont(*args, **kwargs):
"""GetFont(self) -> Font"""
return _controls_.FontPickerEvent_GetFont(*args, **kwargs)
def SetFont(*args, **kwargs):
"""SetFont(self, Font c)"""
return _controls_.FontPickerEvent_SetFont(*args, **kwargs)
Font = property(GetFont,SetFont,doc="See `GetFont` and `SetFont`")
_controls_.FontPickerEvent_swigregister(FontPickerEvent)
#---------------------------------------------------------------------------
CP_DEFAULT_STYLE = _controls_.CP_DEFAULT_STYLE
CP_NO_TLW_RESIZE = _controls_.CP_NO_TLW_RESIZE
class CollapsiblePane(_core.Control):
"""
A collapsable pane is a container with an embedded button-like
control which can be used by the user to collapse or expand the pane's
contents.
Once constructed you should use the `GetPane` function to access the
pane and add your controls inside it (i.e. use the window returned
from `GetPane` as the parent for the controls which must go in the
pane, NOT the wx.CollapsiblePane itself!).
Note that because of its nature of control which can dynamically (and
drastically) change its size at run-time under user-input, when
putting a wx.CollapsiblePane inside a `wx.Sizer` you should be careful
to add it with a proportion value of zero; this is because otherwise
all other windows with non-zero proportion values would automatically
get resized each time the user expands or collapses the pane window,
usually resulting a weird, flickering effect.
"""
thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
def __init__(self, *args, **kwargs):
"""
__init__(self, Window parent, int winid=-1, String label=EmptyString,
Point pos=DefaultPosition, Size size=DefaultSize,
long style=CP_DEFAULT_STYLE, Validator val=DefaultValidator,
String name=CollapsiblePaneNameStr) -> CollapsiblePane
Create and show a wx.CollapsiblePane
"""
_controls_.CollapsiblePane_swiginit(self,_controls_.new_CollapsiblePane(*args, **kwargs))
self._setOORInfo(self)
def Create(*args, **kwargs):
"""
Create(self, Window parent, int winid=-1, String label=EmptyString,
Point pos=DefaultPosition, Size size=DefaultSize,
long style=CP_DEFAULT_STYLE, Validator val=DefaultValidator,
String name=CollapsiblePaneNameStr) -> bool
"""
return _controls_.CollapsiblePane_Create(*args, **kwargs)
def Collapse(*args, **kwargs):
"""
Collapse(self, bool collapse=True)
Collapses or expands the pane window.
"""
return _controls_.CollapsiblePane_Collapse(*args, **kwargs)
def Expand(*args, **kwargs):
"""
Expand(self)
Same as Collapse(False).
"""
return _controls_.CollapsiblePane_Expand(*args, **kwargs)
def IsCollapsed(*args, **kwargs):
"""
IsCollapsed(self) -> bool
Returns ``True`` if the pane window is currently hidden.
"""
return _controls_.CollapsiblePane_IsCollapsed(*args, **kwargs)
def IsExpanded(*args, **kwargs):
"""
IsExpanded(self) -> bool
Returns ``True`` if the pane window is currently shown.
"""
return _controls_.CollapsiblePane_IsExpanded(*args, **kwargs)
def GetPane(*args, **kwargs):
"""
GetPane(self) -> Window
Returns a reference to the pane window. Use the returned `wx.Window`
as the parent of widgets to make them part of the collapsible area.
"""
return _controls_.CollapsiblePane_GetPane(*args, **kwargs)
Expanded = property(IsExpanded)
Collapsed = property(IsCollapsed)
_controls_.CollapsiblePane_swigregister(CollapsiblePane)
CollapsiblePaneNameStr = cvar.CollapsiblePaneNameStr
def PreCollapsiblePane(*args, **kwargs):
"""
PreCollapsiblePane() -> CollapsiblePane
Precreate a wx.CollapsiblePane for 2-phase creation.
"""
val = _controls_.new_PreCollapsiblePane(*args, **kwargs)
return val
wxEVT_COMMAND_COLLPANE_CHANGED = _controls_.wxEVT_COMMAND_COLLPANE_CHANGED
EVT_COLLAPSIBLEPANE_CHANGED = wx.PyEventBinder( wxEVT_COMMAND_COLLPANE_CHANGED, 1 )
class CollapsiblePaneEvent(_core.CommandEvent):
"""Proxy of C++ CollapsiblePaneEvent class"""
thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
def __init__(self, *args, **kwargs):
"""__init__(self, Object generator, int id, bool collapsed) -> CollapsiblePaneEvent"""
_controls_.CollapsiblePaneEvent_swiginit(self,_controls_.new_CollapsiblePaneEvent(*args, **kwargs))
def GetCollapsed(*args, **kwargs):
"""GetCollapsed(self) -> bool"""
return _controls_.CollapsiblePaneEvent_GetCollapsed(*args, **kwargs)
def SetCollapsed(*args, **kwargs):
"""SetCollapsed(self, bool c)"""
return _controls_.CollapsiblePaneEvent_SetCollapsed(*args, **kwargs)
Collapsed = property(GetCollapsed,SetCollapsed)
_controls_.CollapsiblePaneEvent_swigregister(CollapsiblePaneEvent)
#---------------------------------------------------------------------------
class SearchCtrlBase(_core.Control,_core.TextCtrlIface):
"""Proxy of C++ SearchCtrlBase class"""
thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
def __init__(self): raise AttributeError, "No constructor defined"
__repr__ = _swig_repr
_controls_.SearchCtrlBase_swigregister(SearchCtrlBase)
SearchCtrlNameStr = cvar.SearchCtrlNameStr
class SearchCtrl(SearchCtrlBase):
"""
A search control is a composite of a `wx.TextCtrl` with optional
bitmap buttons and a drop-down menu. Controls like this can typically
be found on a toolbar of applications that support some form of search
functionality. On the Mac this control is implemented using the
native HISearchField control, on the other platforms a generic control
is used, although that may change in the future as more platforms
introduce native search widgets.
If you wish to use a drop-down menu with your wx.SearchCtrl then you
will need to manage its content and handle the menu events yourself,
but this is an easy thing to do. Simply build the menu, pass it to
`SetMenu`, and also bind a handler for a range of EVT_MENU events.
This gives you the flexibility to use the drop-down menu however you
wish, such as for a history of searches, or as a way to select
different kinds of searches. The ToolBar.py sample in the demo shows
one way to do this.
Since the control derives from `wx.TextCtrl` it is convenient to use
the styles and events designed for `wx.TextCtrl`. For example you can
use the ``wx.TE_PROCESS_ENTER`` style and catch the
``wx.EVT_TEXT_ENTER`` event to know when the user has pressed the
Enter key in the control and wishes to start a search.
"""
thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
def __init__(self, *args, **kwargs):
"""
__init__(self, Window parent, int id=-1, String value=wxEmptyString,
Point pos=DefaultPosition, Size size=DefaultSize,
long style=0, Validator validator=DefaultValidator,
String name=SearchCtrlNameStr) -> SearchCtrl
A search control is a composite of a `wx.TextCtrl` with optional
bitmap buttons and a drop-down menu. Controls like this can typically
be found on a toolbar of applications that support some form of search
functionality. On the Mac this control is implemented using the
native HISearchField control, on the other platforms a generic control
is used, although that may change in the future as more platforms
introduce native search widgets.
If you wish to use a drop-down menu with your wx.SearchCtrl then you
will need to manage its content and handle the menu events yourself,
but this is an easy thing to do. Simply build the menu, pass it to
`SetMenu`, and also bind a handler for a range of EVT_MENU events.
This gives you the flexibility to use the drop-down menu however you
wish, such as for a history of searches, or as a way to select
different kinds of searches. The ToolBar.py sample in the demo shows
one way to do this.
Since the control derives from `wx.TextCtrl` it is convenient to use
the styles and events designed for `wx.TextCtrl`. For example you can
use the ``wx.TE_PROCESS_ENTER`` style and catch the
``wx.EVT_TEXT_ENTER`` event to know when the user has pressed the
Enter key in the control and wishes to start a search.
"""
_controls_.SearchCtrl_swiginit(self,_controls_.new_SearchCtrl(*args, **kwargs))
self._setOORInfo(self)
def Create(*args, **kwargs):
"""
Create(self, Window parent, int id=-1, String value=wxEmptyString,
Point pos=DefaultPosition, Size size=DefaultSize,
long style=0, Validator validator=DefaultValidator,
String name=SearchCtrlNameStr) -> bool
"""
return _controls_.SearchCtrl_Create(*args, **kwargs)
def SetMenu(*args, **kwargs):
"""
SetMenu(self, Menu menu)
Sets the search control's menu object. If there is already a menu
associated with the search control it is deleted.
"""
return _controls_.SearchCtrl_SetMenu(*args, **kwargs)
def GetMenu(*args, **kwargs):
"""
GetMenu(self) -> Menu
Returns a pointer to the search control's menu object or None if there
is no menu attached.
"""
return _controls_.SearchCtrl_GetMenu(*args, **kwargs)
def ShowSearchButton(*args, **kwargs):
"""
ShowSearchButton(self, bool show)
Sets the search button visibility value on the search control. If
there is a menu attached, the search button will be visible regardless
of the search button visibility value. This has no effect in Mac OS X
v10.3
"""
return _controls_.SearchCtrl_ShowSearchButton(*args, **kwargs)
def IsSearchButtonVisible(*args, **kwargs):
"""
IsSearchButtonVisible(self) -> bool
Returns the search button visibility value. If there is a menu
attached, the search button will be visible regardless of the search
button visibility value. This always returns false in Mac OS X v10.3
"""
return _controls_.SearchCtrl_IsSearchButtonVisible(*args, **kwargs)
def ShowCancelButton(*args, **kwargs):
"""
ShowCancelButton(self, bool show)
Shows or hides the cancel button.
"""
return _controls_.SearchCtrl_ShowCancelButton(*args, **kwargs)
def IsCancelButtonVisible(*args, **kwargs):
"""
IsCancelButtonVisible(self) -> bool
Indicates whether the cancel button is visible.
"""
return _controls_.SearchCtrl_IsCancelButtonVisible(*args, **kwargs)
def SetDescriptiveText(*args, **kwargs):
"""
SetDescriptiveText(self, String text)
Set the text to be displayed when the user has not yet typed anything
in the control.
"""
return _controls_.SearchCtrl_SetDescriptiveText(*args, **kwargs)
def GetDescriptiveText(*args, **kwargs):
"""
GetDescriptiveText(self) -> String
Get the text to be displayed when the user has not yet typed anything
in the control.
"""
return _controls_.SearchCtrl_GetDescriptiveText(*args, **kwargs)
def SetSearchBitmap(*args, **kwargs):
"""
SetSearchBitmap(self, Bitmap bitmap)
Sets the bitmap to use for the search button. This currently does not
work on the Mac.
"""
return _controls_.SearchCtrl_SetSearchBitmap(*args, **kwargs)
def SetSearchMenuBitmap(*args, **kwargs):
"""
SetSearchMenuBitmap(self, Bitmap bitmap)
Sets the bitmap to use for the search button when there is a drop-down
menu associated with the search control. This currently does not work
on the Mac.
"""
return _controls_.SearchCtrl_SetSearchMenuBitmap(*args, **kwargs)
def SetCancelBitmap(*args, **kwargs):
"""
SetCancelBitmap(self, Bitmap bitmap)
Sets the bitmap to use for the cancel button. This currently does not
work on the Mac.
"""
return _controls_.SearchCtrl_SetCancelBitmap(*args, **kwargs)
Menu = property(GetMenu,SetMenu)
SearchButtonVisible = property(IsSearchButtonVisible,ShowSearchButton)
CancelButtonVisible = property(IsCancelButtonVisible,ShowCancelButton)
DescriptiveText = property(GetDescriptiveText,SetDescriptiveText)
_controls_.SearchCtrl_swigregister(SearchCtrl)
def PreSearchCtrl(*args, **kwargs):
"""
PreSearchCtrl() -> SearchCtrl
Precreate a wx.SearchCtrl for 2-phase creation.
"""
val = _controls_.new_PreSearchCtrl(*args, **kwargs)
return val
wxEVT_COMMAND_SEARCHCTRL_CANCEL_BTN = _controls_.wxEVT_COMMAND_SEARCHCTRL_CANCEL_BTN
wxEVT_COMMAND_SEARCHCTRL_SEARCH_BTN = _controls_.wxEVT_COMMAND_SEARCHCTRL_SEARCH_BTN
EVT_SEARCHCTRL_CANCEL_BTN = wx.PyEventBinder( wxEVT_COMMAND_SEARCHCTRL_CANCEL_BTN, 1)
EVT_SEARCHCTRL_SEARCH_BTN = wx.PyEventBinder( wxEVT_COMMAND_SEARCHCTRL_SEARCH_BTN, 1)
#---------------------------------------------------------------------------
FC_OPEN = _controls_.FC_OPEN
FC_SAVE = _controls_.FC_SAVE
FC_MULTIPLE = _controls_.FC_MULTIPLE
FC_NOSHOWHIDDEN = _controls_.FC_NOSHOWHIDDEN
FC_DEFAULT_STYLE = _controls_.FC_DEFAULT_STYLE
class FileCtrl(_core.Window):
"""
"""
thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
def __init__(self, *args, **kwargs):
"""
__init__(self, Window parent, int id=-1, String defaultDirectory=wxEmptyString,
String defaultFilename=wxEmptyString,
String wildCard=wxFileSelectorDefaultWildcardStr,
long style=FC_DEFAULT_STYLE, Point pos=DefaultPosition,
Size size=DefaultSize,
String name=FileCtrlNameStr) -> FileCtrl
"""
_controls_.FileCtrl_swiginit(self,_controls_.new_FileCtrl(*args, **kwargs))
self._setOORInfo(self)
def Create(*args, **kwargs):
"""
Create(self, Window parent, int id=-1, String defaultDirectory=wxEmptyString,
String defaultFilename=wxEmptyString,
String wildCard=wxFileSelectorDefaultWildcardStr,
long style=FC_DEFAULT_STYLE, Point pos=DefaultPosition,
Size size=DefaultSize,
String name=FileCtrlNameStr) -> bool
"""
return _controls_.FileCtrl_Create(*args, **kwargs)
def SetWildcard(*args, **kwargs):
"""SetWildcard(self, String wildCard)"""
return _controls_.FileCtrl_SetWildcard(*args, **kwargs)
def SetFilterIndex(*args, **kwargs):
"""SetFilterIndex(self, int filterindex)"""
return _controls_.FileCtrl_SetFilterIndex(*args, **kwargs)
def SetDirectory(*args, **kwargs):
"""SetDirectory(self, String dir) -> bool"""
return _controls_.FileCtrl_SetDirectory(*args, **kwargs)
def SetFilename(*args, **kwargs):
"""SetFilename(self, String name) -> bool"""
return _controls_.FileCtrl_SetFilename(*args, **kwargs)
def SetPath(*args, **kwargs):
"""SetPath(self, String path) -> bool"""
return _controls_.FileCtrl_SetPath(*args, **kwargs)
def GetFilename(*args, **kwargs):
"""GetFilename(self) -> String"""
return _controls_.FileCtrl_GetFilename(*args, **kwargs)
def GetDirectory(*args, **kwargs):
"""GetDirectory(self) -> String"""
return _controls_.FileCtrl_GetDirectory(*args, **kwargs)
def GetWildcard(*args, **kwargs):
"""GetWildcard(self) -> String"""
return _controls_.FileCtrl_GetWildcard(*args, **kwargs)
def GetPath(*args, **kwargs):
"""GetPath(self) -> String"""
return _controls_.FileCtrl_GetPath(*args, **kwargs)
def GetFilterIndex(*args, **kwargs):
"""GetFilterIndex(self) -> int"""
return _controls_.FileCtrl_GetFilterIndex(*args, **kwargs)
def GetPaths(*args, **kwargs):
"""GetPaths(self) -> wxArrayString"""
return _controls_.FileCtrl_GetPaths(*args, **kwargs)
def GetFilenames(*args, **kwargs):
"""GetFilenames(self) -> wxArrayString"""
return _controls_.FileCtrl_GetFilenames(*args, **kwargs)
def HasMultipleFileSelection(*args, **kwargs):
"""HasMultipleFileSelection(self) -> bool"""
return _controls_.FileCtrl_HasMultipleFileSelection(*args, **kwargs)
def ShowHidden(*args, **kwargs):
"""ShowHidden(self, bool show)"""
return _controls_.FileCtrl_ShowHidden(*args, **kwargs)
Filename = property(GetFilename,SetFilename)
Directory = property(GetDirectory,SetDirectory)
Wildcard = property(GetWildcard,SetWildcard)
Path = property(GetPath,SetPath)
FilterIndex = property(GetFilterIndex,SetFilterIndex)
Paths = property(GetPaths)
Filenames = property(GetFilenames)
_controls_.FileCtrl_swigregister(FileCtrl)
FileCtrlNameStr = cvar.FileCtrlNameStr
def PreFileCtrl(*args, **kwargs):
"""
PreFileCtrl() -> FileCtrl
Precreate a wx.FileCtrl for 2-phase creation.
"""
val = _controls_.new_PreFileCtrl(*args, **kwargs)
return val
class FileCtrlEvent(_core.CommandEvent):
"""Proxy of C++ FileCtrlEvent class"""
thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
def __init__(self, *args, **kwargs):
"""__init__(self, EventType type, Object evtObject, int id) -> FileCtrlEvent"""
_controls_.FileCtrlEvent_swiginit(self,_controls_.new_FileCtrlEvent(*args, **kwargs))
def SetFiles(*args, **kwargs):
"""SetFiles(self, wxArrayString files)"""
return _controls_.FileCtrlEvent_SetFiles(*args, **kwargs)
def SetDirectory(*args, **kwargs):
"""SetDirectory(self, String directory)"""
return _controls_.FileCtrlEvent_SetDirectory(*args, **kwargs)
def SetFilterIndex(*args, **kwargs):
"""SetFilterIndex(self, int filterIndex)"""
return _controls_.FileCtrlEvent_SetFilterIndex(*args, **kwargs)
def GetFiles(*args, **kwargs):
"""GetFiles(self) -> wxArrayString"""
return _controls_.FileCtrlEvent_GetFiles(*args, **kwargs)
def GetDirectory(*args, **kwargs):
"""GetDirectory(self) -> String"""
return _controls_.FileCtrlEvent_GetDirectory(*args, **kwargs)
def GetFilterIndex(*args, **kwargs):
"""GetFilterIndex(self) -> int"""
return _controls_.FileCtrlEvent_GetFilterIndex(*args, **kwargs)
def GetFile(*args, **kwargs):
"""GetFile(self) -> String"""
return _controls_.FileCtrlEvent_GetFile(*args, **kwargs)
Files = property(GetFiles,SetFiles)
Directory = property(GetDirectory,SetDirectory)
FilterIndex = property(GetFilterIndex,SetFilterIndex)
_controls_.FileCtrlEvent_swigregister(FileCtrlEvent)
wxEVT_FILECTRL_SELECTIONCHANGED = _controls_.wxEVT_FILECTRL_SELECTIONCHANGED
wxEVT_FILECTRL_FILEACTIVATED = _controls_.wxEVT_FILECTRL_FILEACTIVATED
wxEVT_FILECTRL_FOLDERCHANGED = _controls_.wxEVT_FILECTRL_FOLDERCHANGED
wxEVT_FILECTRL_FILTERCHANGED = _controls_.wxEVT_FILECTRL_FILTERCHANGED
EVT_FILECTRL_SELECTIONCHANGED = wx.PyEventBinder( wxEVT_FILECTRL_SELECTIONCHANGED, 1)
EVT_FILECTRL_FILEACTIVATED = wx.PyEventBinder( wxEVT_FILECTRL_FILEACTIVATED, 1)
EVT_FILECTRL_FOLDERCHANGED = wx.PyEventBinder( wxEVT_FILECTRL_FOLDERCHANGED, 1)
EVT_FILECTRL_FILTERCHANGED = wx.PyEventBinder( wxEVT_FILECTRL_FILTERCHANGED, 1)
#---------------------------------------------------------------------------
class InfoBar(_core.Control):
"""
An info bar is a transient window shown at top or bottom of its parent
window to display non-critical information to the user. It works
similarly to message bars in current web browsers.
"""
thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
def __init__(self, *args, **kwargs):
"""
__init__(self, Window parent, int winid=ID_ANY) -> InfoBar
An info bar is a transient window shown at top or bottom of its parent
window to display non-critical information to the user. It works
similarly to message bars in current web browsers.
"""
_controls_.InfoBar_swiginit(self,_controls_.new_InfoBar(*args, **kwargs))
self._setOORInfo(self)
def Create(*args, **kwargs):
"""
Create(self, Window parent, int winid=ID_ANY) -> bool
Do the 2nd phase and create the GUI control.
"""
return _controls_.InfoBar_Create(*args, **kwargs)
def ShowMessage(*args, **kwargs):
"""ShowMessage(self, String msg, int flags=ICON_INFORMATION)"""
return _controls_.InfoBar_ShowMessage(*args, **kwargs)
def Dismiss(*args, **kwargs):
"""Dismiss(self)"""
return _controls_.InfoBar_Dismiss(*args, **kwargs)
def AddButton(*args, **kwargs):
"""AddButton(self, int btnid, String label=wxEmptyString)"""
return _controls_.InfoBar_AddButton(*args, **kwargs)
def RemoveButton(*args, **kwargs):
"""RemoveButton(self, int btnid)"""
return _controls_.InfoBar_RemoveButton(*args, **kwargs)
def SetShowHideEffects(*args, **kwargs):
"""SetShowHideEffects(self, int showEffect, int hideEffect)"""
return _controls_.InfoBar_SetShowHideEffects(*args, **kwargs)
def GetShowEffect(*args, **kwargs):
"""GetShowEffect(self) -> int"""
return _controls_.InfoBar_GetShowEffect(*args, **kwargs)
def GetHideEffect(*args, **kwargs):
"""GetHideEffect(self) -> int"""
return _controls_.InfoBar_GetHideEffect(*args, **kwargs)
def SetEffectDuration(*args, **kwargs):
"""SetEffectDuration(self, int duration)"""
return _controls_.InfoBar_SetEffectDuration(*args, **kwargs)
def GetEffectDuration(*args, **kwargs):
"""GetEffectDuration(self) -> int"""
return _controls_.InfoBar_GetEffectDuration(*args, **kwargs)
_controls_.InfoBar_swigregister(InfoBar)
def PreInfoBar(*args, **kwargs):
"""
PreInfoBar() -> InfoBar
An info bar is a transient window shown at top or bottom of its parent
window to display non-critical information to the user. It works
similarly to message bars in current web browsers.
"""
val = _controls_.new_PreInfoBar(*args, **kwargs)
return val
#---------------------------------------------------------------------------
class CommandLinkButton(Button):
"""Proxy of C++ CommandLinkButton class"""
thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
def __init__(self, *args, **kwargs):
"""
__init__(self, Window parent, int id=-1, String mainLabel=wxEmptyString,
String note=wxEmptyString, Point pos=DefaultPosition,
Size size=DefaultSize, long style=0,
Validator validator=DefaultValidator,
String name=wxButtonNameStr) -> CommandLinkButton
"""
_controls_.CommandLinkButton_swiginit(self,_controls_.new_CommandLinkButton(*args, **kwargs))
self._setOORInfo(self)
def Create(*args, **kwargs):
"""
Create(self, Window parent, int id=-1, String mainLabel=wxEmptyString,
String note=wxEmptyString, Point pos=DefaultPosition,
Size size=DefaultSize, long style=0,
Validator validator=DefaultValidator,
String name=wxButtonNameStr) -> bool
"""
return _controls_.CommandLinkButton_Create(*args, **kwargs)
def SetMainLabelAndNote(*args, **kwargs):
"""SetMainLabelAndNote(self, String mainLabel, String note)"""
return _controls_.CommandLinkButton_SetMainLabelAndNote(*args, **kwargs)
def SetMainLabel(*args, **kwargs):
"""SetMainLabel(self, String mainLabel)"""
return _controls_.CommandLinkButton_SetMainLabel(*args, **kwargs)
def SetNote(*args, **kwargs):
"""SetNote(self, String note)"""
return _controls_.CommandLinkButton_SetNote(*args, **kwargs)
def GetMainLabel(*args, **kwargs):
"""GetMainLabel(self) -> String"""
return _controls_.CommandLinkButton_GetMainLabel(*args, **kwargs)
def GetNote(*args, **kwargs):
"""GetNote(self) -> String"""
return _controls_.CommandLinkButton_GetNote(*args, **kwargs)
MainLabel = property(GetMainLabel,SetMainLabel)
Note = property(GetNote,SetNote)
_controls_.CommandLinkButton_swigregister(CommandLinkButton)
def PreCommandLinkButton(*args, **kwargs):
"""
PreCommandLinkButton() -> CommandLinkButton
Precreate a Button for 2-phase creation.
"""
val = _controls_.new_PreCommandLinkButton(*args, **kwargs)
return val
| gpl-3.0 | -3,839,353,247,363,315,700 | 41.465057 | 151 | 0.65503 | false | 3.857592 | false | false | false |
blackbliss/callme | flask/lib/python2.7/site-packages/werkzeug/contrib/cache.py | 306 | 23519 | # -*- coding: utf-8 -*-
"""
werkzeug.contrib.cache
~~~~~~~~~~~~~~~~~~~~~~
The main problem with dynamic Web sites is, well, they're dynamic. Each
time a user requests a page, the webserver executes a lot of code, queries
the database, renders templates until the visitor gets the page he sees.
This is a lot more expensive than just loading a file from the file system
and sending it to the visitor.
For most Web applications, this overhead isn't a big deal but once it
becomes, you will be glad to have a cache system in place.
How Caching Works
=================
Caching is pretty simple. Basically you have a cache object lurking around
somewhere that is connected to a remote cache or the file system or
something else. When the request comes in you check if the current page
is already in the cache and if so, you're returning it from the cache.
Otherwise you generate the page and put it into the cache. (Or a fragment
of the page, you don't have to cache the full thing)
Here is a simple example of how to cache a sidebar for a template::
def get_sidebar(user):
identifier = 'sidebar_for/user%d' % user.id
value = cache.get(identifier)
if value is not None:
return value
value = generate_sidebar_for(user=user)
cache.set(identifier, value, timeout=60 * 5)
return value
Creating a Cache Object
=======================
To create a cache object you just import the cache system of your choice
from the cache module and instantiate it. Then you can start working
with that object:
>>> from werkzeug.contrib.cache import SimpleCache
>>> c = SimpleCache()
>>> c.set("foo", "value")
>>> c.get("foo")
'value'
>>> c.get("missing") is None
True
Please keep in mind that you have to create the cache and put it somewhere
you have access to it (either as a module global you can import or you just
put it into your WSGI application).
:copyright: (c) 2013 by the Werkzeug Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
import os
import re
import tempfile
from hashlib import md5
from time import time
try:
import cPickle as pickle
except ImportError:
import pickle
from werkzeug._compat import iteritems, string_types, text_type, \
integer_types, to_bytes
from werkzeug.posixemulation import rename
def _items(mappingorseq):
"""Wrapper for efficient iteration over mappings represented by dicts
or sequences::
>>> for k, v in _items((i, i*i) for i in xrange(5)):
... assert k*k == v
>>> for k, v in _items(dict((i, i*i) for i in xrange(5))):
... assert k*k == v
"""
if hasattr(mappingorseq, "iteritems"):
return mappingorseq.iteritems()
elif hasattr(mappingorseq, "items"):
return mappingorseq.items()
return mappingorseq
class BaseCache(object):
"""Baseclass for the cache systems. All the cache systems implement this
API or a superset of it.
:param default_timeout: the default timeout that is used if no timeout is
specified on :meth:`set`.
"""
def __init__(self, default_timeout=300):
self.default_timeout = default_timeout
def get(self, key):
"""Looks up key in the cache and returns the value for it.
If the key does not exist `None` is returned instead.
:param key: the key to be looked up.
"""
return None
def delete(self, key):
"""Deletes `key` from the cache. If it does not exist in the cache
nothing happens.
:param key: the key to delete.
"""
pass
def get_many(self, *keys):
"""Returns a list of values for the given keys.
For each key a item in the list is created. Example::
foo, bar = cache.get_many("foo", "bar")
If a key can't be looked up `None` is returned for that key
instead.
:param keys: The function accepts multiple keys as positional
arguments.
"""
return map(self.get, keys)
def get_dict(self, *keys):
"""Works like :meth:`get_many` but returns a dict::
d = cache.get_dict("foo", "bar")
foo = d["foo"]
bar = d["bar"]
:param keys: The function accepts multiple keys as positional
arguments.
"""
return dict(zip(keys, self.get_many(*keys)))
def set(self, key, value, timeout=None):
"""Adds a new key/value to the cache (overwrites value, if key already
exists in the cache).
:param key: the key to set
:param value: the value for the key
:param timeout: the cache timeout for the key (if not specified,
it uses the default timeout).
"""
pass
def add(self, key, value, timeout=None):
"""Works like :meth:`set` but does not overwrite the values of already
existing keys.
:param key: the key to set
:param value: the value for the key
:param timeout: the cache timeout for the key or the default
timeout if not specified.
"""
pass
def set_many(self, mapping, timeout=None):
"""Sets multiple keys and values from a mapping.
:param mapping: a mapping with the keys/values to set.
:param timeout: the cache timeout for the key (if not specified,
it uses the default timeout).
"""
for key, value in _items(mapping):
self.set(key, value, timeout)
def delete_many(self, *keys):
"""Deletes multiple keys at once.
:param keys: The function accepts multiple keys as positional
arguments.
"""
for key in keys:
self.delete(key)
def clear(self):
"""Clears the cache. Keep in mind that not all caches support
completely clearing the cache.
"""
pass
def inc(self, key, delta=1):
"""Increments the value of a key by `delta`. If the key does
not yet exist it is initialized with `delta`.
For supporting caches this is an atomic operation.
:param key: the key to increment.
:param delta: the delta to add.
"""
self.set(key, (self.get(key) or 0) + delta)
def dec(self, key, delta=1):
"""Decrements the value of a key by `delta`. If the key does
not yet exist it is initialized with `-delta`.
For supporting caches this is an atomic operation.
:param key: the key to increment.
:param delta: the delta to subtract.
"""
self.set(key, (self.get(key) or 0) - delta)
class NullCache(BaseCache):
"""A cache that doesn't cache. This can be useful for unit testing.
:param default_timeout: a dummy parameter that is ignored but exists
for API compatibility with other caches.
"""
class SimpleCache(BaseCache):
"""Simple memory cache for single process environments. This class exists
mainly for the development server and is not 100% thread safe. It tries
to use as many atomic operations as possible and no locks for simplicity
but it could happen under heavy load that keys are added multiple times.
:param threshold: the maximum number of items the cache stores before
it starts deleting some.
:param default_timeout: the default timeout that is used if no timeout is
specified on :meth:`~BaseCache.set`.
"""
def __init__(self, threshold=500, default_timeout=300):
BaseCache.__init__(self, default_timeout)
self._cache = {}
self.clear = self._cache.clear
self._threshold = threshold
def _prune(self):
if len(self._cache) > self._threshold:
now = time()
for idx, (key, (expires, _)) in enumerate(self._cache.items()):
if expires <= now or idx % 3 == 0:
self._cache.pop(key, None)
def get(self, key):
expires, value = self._cache.get(key, (0, None))
if expires > time():
return pickle.loads(value)
def set(self, key, value, timeout=None):
if timeout is None:
timeout = self.default_timeout
self._prune()
self._cache[key] = (time() + timeout, pickle.dumps(value,
pickle.HIGHEST_PROTOCOL))
def add(self, key, value, timeout=None):
if timeout is None:
timeout = self.default_timeout
if len(self._cache) > self._threshold:
self._prune()
item = (time() + timeout, pickle.dumps(value,
pickle.HIGHEST_PROTOCOL))
self._cache.setdefault(key, item)
def delete(self, key):
self._cache.pop(key, None)
_test_memcached_key = re.compile(br'[^\x00-\x21\xff]{1,250}$').match
class MemcachedCache(BaseCache):
"""A cache that uses memcached as backend.
The first argument can either be an object that resembles the API of a
:class:`memcache.Client` or a tuple/list of server addresses. In the
event that a tuple/list is passed, Werkzeug tries to import the best
available memcache library.
Implementation notes: This cache backend works around some limitations in
memcached to simplify the interface. For example unicode keys are encoded
to utf-8 on the fly. Methods such as :meth:`~BaseCache.get_dict` return
the keys in the same format as passed. Furthermore all get methods
silently ignore key errors to not cause problems when untrusted user data
is passed to the get methods which is often the case in web applications.
:param servers: a list or tuple of server addresses or alternatively
a :class:`memcache.Client` or a compatible client.
:param default_timeout: the default timeout that is used if no timeout is
specified on :meth:`~BaseCache.set`.
:param key_prefix: a prefix that is added before all keys. This makes it
possible to use the same memcached server for different
applications. Keep in mind that
:meth:`~BaseCache.clear` will also clear keys with a
different prefix.
"""
def __init__(self, servers=None, default_timeout=300, key_prefix=None):
BaseCache.__init__(self, default_timeout)
if servers is None or isinstance(servers, (list, tuple)):
if servers is None:
servers = ['127.0.0.1:11211']
self._client = self.import_preferred_memcache_lib(servers)
if self._client is None:
raise RuntimeError('no memcache module found')
else:
# NOTE: servers is actually an already initialized memcache
# client.
self._client = servers
self.key_prefix = to_bytes(key_prefix)
def get(self, key):
if isinstance(key, text_type):
key = key.encode('utf-8')
if self.key_prefix:
key = self.key_prefix + key
# memcached doesn't support keys longer than that. Because often
# checks for so long keys can occour because it's tested from user
# submitted data etc we fail silently for getting.
if _test_memcached_key(key):
return self._client.get(key)
def get_dict(self, *keys):
key_mapping = {}
have_encoded_keys = False
for key in keys:
if isinstance(key, unicode):
encoded_key = key.encode('utf-8')
have_encoded_keys = True
else:
encoded_key = key
if self.key_prefix:
encoded_key = self.key_prefix + encoded_key
if _test_memcached_key(key):
key_mapping[encoded_key] = key
d = rv = self._client.get_multi(key_mapping.keys())
if have_encoded_keys or self.key_prefix:
rv = {}
for key, value in iteritems(d):
rv[key_mapping[key]] = value
if len(rv) < len(keys):
for key in keys:
if key not in rv:
rv[key] = None
return rv
def add(self, key, value, timeout=None):
if timeout is None:
timeout = self.default_timeout
if isinstance(key, text_type):
key = key.encode('utf-8')
if self.key_prefix:
key = self.key_prefix + key
self._client.add(key, value, timeout)
def set(self, key, value, timeout=None):
if timeout is None:
timeout = self.default_timeout
if isinstance(key, text_type):
key = key.encode('utf-8')
if self.key_prefix:
key = self.key_prefix + key
self._client.set(key, value, timeout)
def get_many(self, *keys):
d = self.get_dict(*keys)
return [d[key] for key in keys]
def set_many(self, mapping, timeout=None):
if timeout is None:
timeout = self.default_timeout
new_mapping = {}
for key, value in _items(mapping):
if isinstance(key, text_type):
key = key.encode('utf-8')
if self.key_prefix:
key = self.key_prefix + key
new_mapping[key] = value
self._client.set_multi(new_mapping, timeout)
def delete(self, key):
if isinstance(key, unicode):
key = key.encode('utf-8')
if self.key_prefix:
key = self.key_prefix + key
if _test_memcached_key(key):
self._client.delete(key)
def delete_many(self, *keys):
new_keys = []
for key in keys:
if isinstance(key, unicode):
key = key.encode('utf-8')
if self.key_prefix:
key = self.key_prefix + key
if _test_memcached_key(key):
new_keys.append(key)
self._client.delete_multi(new_keys)
def clear(self):
self._client.flush_all()
def inc(self, key, delta=1):
if isinstance(key, unicode):
key = key.encode('utf-8')
if self.key_prefix:
key = self.key_prefix + key
self._client.incr(key, delta)
def dec(self, key, delta=1):
if isinstance(key, unicode):
key = key.encode('utf-8')
if self.key_prefix:
key = self.key_prefix + key
self._client.decr(key, delta)
def import_preferred_memcache_lib(self, servers):
"""Returns an initialized memcache client. Used by the constructor."""
try:
import pylibmc
except ImportError:
pass
else:
return pylibmc.Client(servers)
try:
from google.appengine.api import memcache
except ImportError:
pass
else:
return memcache.Client()
try:
import memcache
except ImportError:
pass
else:
return memcache.Client(servers)
# backwards compatibility
GAEMemcachedCache = MemcachedCache
class RedisCache(BaseCache):
"""Uses the Redis key-value store as a cache backend.
The first argument can be either a string denoting address of the Redis
server or an object resembling an instance of a redis.Redis class.
Note: Python Redis API already takes care of encoding unicode strings on
the fly.
.. versionadded:: 0.7
.. versionadded:: 0.8
`key_prefix` was added.
.. versionchanged:: 0.8
This cache backend now properly serializes objects.
.. versionchanged:: 0.8.3
This cache backend now supports password authentication.
:param host: address of the Redis server or an object which API is
compatible with the official Python Redis client (redis-py).
:param port: port number on which Redis server listens for connections.
:param password: password authentication for the Redis server.
:param db: db (zero-based numeric index) on Redis Server to connect.
:param default_timeout: the default timeout that is used if no timeout is
specified on :meth:`~BaseCache.set`.
:param key_prefix: A prefix that should be added to all keys.
"""
def __init__(self, host='localhost', port=6379, password=None,
db=0, default_timeout=300, key_prefix=None):
BaseCache.__init__(self, default_timeout)
if isinstance(host, string_types):
try:
import redis
except ImportError:
raise RuntimeError('no redis module found')
self._client = redis.Redis(host=host, port=port, password=password, db=db)
else:
self._client = host
self.key_prefix = key_prefix or ''
def dump_object(self, value):
"""Dumps an object into a string for redis. By default it serializes
integers as regular string and pickle dumps everything else.
"""
t = type(value)
if t in integer_types:
return str(value).encode('ascii')
return b'!' + pickle.dumps(value)
def load_object(self, value):
"""The reversal of :meth:`dump_object`. This might be callde with
None.
"""
if value is None:
return None
if value.startswith(b'!'):
return pickle.loads(value[1:])
try:
return int(value)
except ValueError:
# before 0.8 we did not have serialization. Still support that.
return value
def get(self, key):
return self.load_object(self._client.get(self.key_prefix + key))
def get_many(self, *keys):
if self.key_prefix:
keys = [self.key_prefix + key for key in keys]
return [self.load_object(x) for x in self._client.mget(keys)]
def set(self, key, value, timeout=None):
if timeout is None:
timeout = self.default_timeout
dump = self.dump_object(value)
self._client.setex(self.key_prefix + key, dump, timeout)
def add(self, key, value, timeout=None):
if timeout is None:
timeout = self.default_timeout
dump = self.dump_object(value)
added = self._client.setnx(self.key_prefix + key, dump)
if added:
self._client.expire(self.key_prefix + key, timeout)
def set_many(self, mapping, timeout=None):
if timeout is None:
timeout = self.default_timeout
pipe = self._client.pipeline()
for key, value in _items(mapping):
dump = self.dump_object(value)
pipe.setex(self.key_prefix + key, dump, timeout)
pipe.execute()
def delete(self, key):
self._client.delete(self.key_prefix + key)
def delete_many(self, *keys):
if not keys:
return
if self.key_prefix:
keys = [self.key_prefix + key for key in keys]
self._client.delete(*keys)
def clear(self):
if self.key_prefix:
keys = self._client.keys(self.key_prefix + '*')
if keys:
self._client.delete(*keys)
else:
self._client.flushdb()
def inc(self, key, delta=1):
return self._client.incr(self.key_prefix + key, delta)
def dec(self, key, delta=1):
return self._client.decr(self.key_prefix + key, delta)
class FileSystemCache(BaseCache):
"""A cache that stores the items on the file system. This cache depends
on being the only user of the `cache_dir`. Make absolutely sure that
nobody but this cache stores files there or otherwise the cache will
randomly delete files therein.
:param cache_dir: the directory where cache files are stored.
:param threshold: the maximum number of items the cache stores before
it starts deleting some.
:param default_timeout: the default timeout that is used if no timeout is
specified on :meth:`~BaseCache.set`.
:param mode: the file mode wanted for the cache files, default 0600
"""
#: used for temporary files by the FileSystemCache
_fs_transaction_suffix = '.__wz_cache'
def __init__(self, cache_dir, threshold=500, default_timeout=300, mode=0o600):
BaseCache.__init__(self, default_timeout)
self._path = cache_dir
self._threshold = threshold
self._mode = mode
if not os.path.exists(self._path):
os.makedirs(self._path)
def _list_dir(self):
"""return a list of (fully qualified) cache filenames
"""
return [os.path.join(self._path, fn) for fn in os.listdir(self._path)
if not fn.endswith(self._fs_transaction_suffix)]
def _prune(self):
entries = self._list_dir()
if len(entries) > self._threshold:
now = time()
for idx, fname in enumerate(entries):
remove = False
f = None
try:
try:
f = open(fname, 'rb')
expires = pickle.load(f)
remove = expires <= now or idx % 3 == 0
finally:
if f is not None:
f.close()
except Exception:
pass
if remove:
try:
os.remove(fname)
except (IOError, OSError):
pass
def clear(self):
for fname in self._list_dir():
try:
os.remove(fname)
except (IOError, OSError):
pass
def _get_filename(self, key):
if isinstance(key, text_type):
key = key.encode('utf-8') #XXX unicode review
hash = md5(key).hexdigest()
return os.path.join(self._path, hash)
def get(self, key):
filename = self._get_filename(key)
try:
f = open(filename, 'rb')
try:
if pickle.load(f) >= time():
return pickle.load(f)
finally:
f.close()
os.remove(filename)
except Exception:
return None
def add(self, key, value, timeout=None):
filename = self._get_filename(key)
if not os.path.exists(filename):
self.set(key, value, timeout)
def set(self, key, value, timeout=None):
if timeout is None:
timeout = self.default_timeout
filename = self._get_filename(key)
self._prune()
try:
fd, tmp = tempfile.mkstemp(suffix=self._fs_transaction_suffix,
dir=self._path)
f = os.fdopen(fd, 'wb')
try:
pickle.dump(int(time() + timeout), f, 1)
pickle.dump(value, f, pickle.HIGHEST_PROTOCOL)
finally:
f.close()
rename(tmp, filename)
os.chmod(filename, self._mode)
except (IOError, OSError):
pass
def delete(self, key):
try:
os.remove(self._get_filename(key))
except (IOError, OSError):
pass
| mit | -7,111,811,701,270,589,000 | 33.637703 | 86 | 0.579106 | false | 4.281631 | false | false | false |
pipet/pipet | pipet/sources/zendesk/tasks.py | 2 | 1544 | from contextlib import contextmanager
from datetime import datetime
from inspect import isclass
from celery import chord, group
from celery_once import QueueOnce
from celery.schedules import crontab
from celery.utils.log import get_task_logger
from sqlalchemy.orm.attributes import flag_modified
# from pipet import celery
from pipet.models import db, Organization
from pipet.sources.zendesk import ZendeskAccount
from pipet.sources.zendesk.models import (
Base,
CLASS_REGISTRY,
)
logger = get_task_logger(__name__)
# @celery.task(base=QueueOnce, once={'graceful': True})
def sync(account_id):
with app.app_context():
account = ZendeskAccount.query.get(account_id)
session = account.organization.create_session()
for cls in [m for n, m in CLASS_REGISTRY.items() if isclass(m) and issubclass(m, Base)]:
# TODO: Make these parallel to speed up execution
while True:
conn = session.connection()
statments, cursor, has_more = cls.sync(account)
account.cursors[cls.__tablename__] = cursor
flag_modified(account, 'cursors')
for statement in statments:
conn.execute(statement)
session.commit()
db.session.add(account)
db.session.commit()
if not has_more:
break
# @celery.task
def sync_all():
job = group([sync.s(account.id) for account in ZendeskAccount.query.all()])
job.apply_async()
| apache-2.0 | 156,606,072,465,059,940 | 28.692308 | 96 | 0.645725 | false | 4.084656 | false | false | false |
prutseltje/ansible | test/units/modules/network/f5/test_bigip_gtm_datacenter.py | 23 | 6819 | # -*- coding: utf-8 -*-
#
# Copyright (c) 2017 F5 Networks Inc.
# GNU General Public License v3.0 (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import os
import json
import sys
from nose.plugins.skip import SkipTest
if sys.version_info < (2, 7):
raise SkipTest("F5 Ansible modules require Python >= 2.7")
from ansible.compat.tests import unittest
from ansible.compat.tests.mock import Mock
from ansible.compat.tests.mock import patch
from ansible.module_utils.basic import AnsibleModule
try:
from library.modules.bigip_gtm_datacenter import ApiParameters
from library.modules.bigip_gtm_datacenter import ModuleParameters
from library.modules.bigip_gtm_datacenter import ModuleManager
from library.modules.bigip_gtm_datacenter import ArgumentSpec
from library.module_utils.network.f5.common import F5ModuleError
from library.module_utils.network.f5.common import iControlUnexpectedHTTPError
from test.unit.modules.utils import set_module_args
except ImportError:
try:
from ansible.modules.network.f5.bigip_gtm_datacenter import ApiParameters
from ansible.modules.network.f5.bigip_gtm_datacenter import ModuleParameters
from ansible.modules.network.f5.bigip_gtm_datacenter import ModuleManager
from ansible.modules.network.f5.bigip_gtm_datacenter import ArgumentSpec
from ansible.module_utils.network.f5.common import F5ModuleError
from ansible.module_utils.network.f5.common import iControlUnexpectedHTTPError
from units.modules.utils import set_module_args
except ImportError:
raise SkipTest("F5 Ansible modules require the f5-sdk Python library")
fixture_path = os.path.join(os.path.dirname(__file__), 'fixtures')
fixture_data = {}
def load_fixture(name):
path = os.path.join(fixture_path, name)
if path in fixture_data:
return fixture_data[path]
with open(path) as f:
data = f.read()
try:
data = json.loads(data)
except Exception:
pass
fixture_data[path] = data
return data
class TestParameters(unittest.TestCase):
def test_module_parameters(self):
args = dict(
state='present',
contact='foo',
description='bar',
location='baz',
name='datacenter'
)
p = ModuleParameters(params=args)
assert p.state == 'present'
def test_api_parameters(self):
args = load_fixture('load_gtm_datacenter_default.json')
p = ApiParameters(params=args)
assert p.name == 'asd'
def test_module_parameters_state_present(self):
args = dict(
state='present'
)
p = ModuleParameters(params=args)
assert p.state == 'present'
assert p.enabled is True
def test_module_parameters_state_absent(self):
args = dict(
state='absent'
)
p = ModuleParameters(params=args)
assert p.state == 'absent'
def test_module_parameters_state_enabled(self):
args = dict(
state='enabled'
)
p = ModuleParameters(params=args)
assert p.state == 'enabled'
assert p.enabled is True
assert p.disabled is None
def test_module_parameters_state_disabled(self):
args = dict(
state='disabled'
)
p = ModuleParameters(params=args)
assert p.state == 'disabled'
assert p.enabled is None
assert p.disabled is True
class TestManager(unittest.TestCase):
def setUp(self):
self.spec = ArgumentSpec()
def test_create_datacenter(self, *args):
set_module_args(dict(
state='present',
password='admin',
server='localhost',
user='admin',
name='foo'
))
module = AnsibleModule(
argument_spec=self.spec.argument_spec,
supports_check_mode=self.spec.supports_check_mode
)
mm = ModuleManager(module=module)
# Override methods to force specific logic in the module to happen
mm.exists = Mock(side_effect=[False, True])
mm.create_on_device = Mock(return_value=True)
results = mm.exec_module()
assert results['changed'] is True
assert results['state'] == 'present'
def test_create_disabled_datacenter(self, *args):
set_module_args(dict(
state='disabled',
password='admin',
server='localhost',
user='admin',
name='foo'
))
module = AnsibleModule(
argument_spec=self.spec.argument_spec,
supports_check_mode=self.spec.supports_check_mode
)
mm = ModuleManager(module=module)
# Override methods to force specific logic in the module to happen
mm.exists = Mock(side_effect=[False, True])
mm.create_on_device = Mock(return_value=True)
results = mm.exec_module()
assert results['changed'] is True
assert results['enabled'] is False
assert results['disabled'] is True
def test_create_enabled_datacenter(self, *args):
set_module_args(dict(
state='enabled',
password='admin',
server='localhost',
user='admin',
name='foo'
))
module = AnsibleModule(
argument_spec=self.spec.argument_spec,
supports_check_mode=self.spec.supports_check_mode
)
mm = ModuleManager(module=module)
# Override methods to force specific logic in the module to happen
mm.exists = Mock(side_effect=[False, True])
mm.create_on_device = Mock(return_value=True)
results = mm.exec_module()
assert results['changed'] is True
assert results['enabled'] is True
assert results['disabled'] is False
def test_idempotent_disable_datacenter(self, *args):
set_module_args(dict(
state='disabled',
password='admin',
server='localhost',
user='admin',
name='foo'
))
module = AnsibleModule(
argument_spec=self.spec.argument_spec,
supports_check_mode=self.spec.supports_check_mode
)
current = ApiParameters(params=load_fixture('load_gtm_datacenter_disabled.json'))
mm = ModuleManager(module=module)
# Override methods to force specific logic in the module to happen
mm.exists = Mock(return_value=True)
mm.update_on_device = Mock(return_value=True)
mm.read_current_from_device = Mock(return_value=current)
results = mm.exec_module()
assert results['changed'] is False
| gpl-3.0 | 1,435,203,684,349,960,200 | 30.716279 | 91 | 0.628685 | false | 4.235404 | true | false | false |
antb/TPT----My-old-mod | src/python/stdlib/ctypes/test/test_errno.py | 115 | 2330 | import unittest, os, errno
from ctypes import *
from ctypes.util import find_library
from test import test_support
try:
import threading
except ImportError:
threading = None
class Test(unittest.TestCase):
def test_open(self):
libc_name = find_library("c")
if libc_name is None:
raise unittest.SkipTest("Unable to find C library")
libc = CDLL(libc_name, use_errno=True)
if os.name == "nt":
libc_open = libc._open
else:
libc_open = libc.open
libc_open.argtypes = c_char_p, c_int
self.assertEqual(libc_open("", 0), -1)
self.assertEqual(get_errno(), errno.ENOENT)
self.assertEqual(set_errno(32), errno.ENOENT)
self.assertEqual(get_errno(), 32)
if threading:
def _worker():
set_errno(0)
libc = CDLL(libc_name, use_errno=False)
if os.name == "nt":
libc_open = libc._open
else:
libc_open = libc.open
libc_open.argtypes = c_char_p, c_int
self.assertEqual(libc_open("", 0), -1)
self.assertEqual(get_errno(), 0)
t = threading.Thread(target=_worker)
t.start()
t.join()
self.assertEqual(get_errno(), 32)
set_errno(0)
@unittest.skipUnless(os.name == "nt", 'Test specific to Windows')
def test_GetLastError(self):
dll = WinDLL("kernel32", use_last_error=True)
GetModuleHandle = dll.GetModuleHandleA
GetModuleHandle.argtypes = [c_wchar_p]
self.assertEqual(0, GetModuleHandle("foo"))
self.assertEqual(get_last_error(), 126)
self.assertEqual(set_last_error(32), 126)
self.assertEqual(get_last_error(), 32)
def _worker():
set_last_error(0)
dll = WinDLL("kernel32", use_last_error=False)
GetModuleHandle = dll.GetModuleHandleW
GetModuleHandle.argtypes = [c_wchar_p]
GetModuleHandle("bar")
self.assertEqual(get_last_error(), 0)
t = threading.Thread(target=_worker)
t.start()
t.join()
self.assertEqual(get_last_error(), 32)
set_last_error(0)
if __name__ == "__main__":
unittest.main()
| gpl-2.0 | 785,952,512,028,991,400 | 28.125 | 69 | 0.554077 | false | 3.782468 | true | false | false |
marcoantoniooliveira/labweb | oscar/lib/python2.7/site-packages/debug_toolbar/panels/sql/forms.py | 36 | 2784 | from __future__ import absolute_import, unicode_literals
import json
import hashlib
from django import forms
from django.conf import settings
from django.db import connections
from django.utils.encoding import force_text
from django.utils.functional import cached_property
from django.core.exceptions import ValidationError
from debug_toolbar.panels.sql.utils import reformat_sql
class SQLSelectForm(forms.Form):
"""
Validate params
sql: The sql statement with interpolated params
raw_sql: The sql statement with placeholders
params: JSON encoded parameter values
duration: time for SQL to execute passed in from toolbar just for redisplay
hash: the hash of (secret + sql + params) for tamper checking
"""
sql = forms.CharField()
raw_sql = forms.CharField()
params = forms.CharField()
alias = forms.CharField(required=False, initial='default')
duration = forms.FloatField()
hash = forms.CharField()
def __init__(self, *args, **kwargs):
initial = kwargs.get('initial', None)
if initial is not None:
initial['hash'] = self.make_hash(initial)
super(SQLSelectForm, self).__init__(*args, **kwargs)
for name in self.fields:
self.fields[name].widget = forms.HiddenInput()
def clean_raw_sql(self):
value = self.cleaned_data['raw_sql']
if not value.lower().strip().startswith('select'):
raise ValidationError("Only 'select' queries are allowed.")
return value
def clean_params(self):
value = self.cleaned_data['params']
try:
return json.loads(value)
except ValueError:
raise ValidationError('Is not valid JSON')
def clean_alias(self):
value = self.cleaned_data['alias']
if value not in connections:
raise ValidationError("Database alias '%s' not found" % value)
return value
def clean_hash(self):
hash = self.cleaned_data['hash']
if hash != self.make_hash(self.data):
raise ValidationError('Tamper alert')
return hash
def reformat_sql(self):
return reformat_sql(self.cleaned_data['sql'])
def make_hash(self, data):
items = [settings.SECRET_KEY, data['sql'], data['params']]
# Replace lines endings with spaces to preserve the hash value
# even when the browser normalizes \r\n to \n in inputs.
items = [' '.join(force_text(item).splitlines()) for item in items]
return hashlib.sha1(''.join(items).encode('utf-8')).hexdigest()
@property
def connection(self):
return connections[self.cleaned_data['alias']]
@cached_property
def cursor(self):
return self.connection.cursor()
| bsd-3-clause | -2,574,129,591,306,319,400 | 29.26087 | 83 | 0.64727 | false | 4.309598 | false | false | false |
2asoft/tdesktop | Telegram/build/release.py | 4 | 7388 | import os, sys, requests, pprint, re, json
from uritemplate import URITemplate, expand
from subprocess import call
changelog_file = '../../changelog.txt'
token_file = '../../../TelegramPrivate/github-releases-token.txt'
version = ''
commit = ''
for arg in sys.argv:
if re.match(r'\d+\.\d+', arg):
version = arg
elif re.match(r'^[a-f0-9]{40}$', arg):
commit = arg
# thanks http://stackoverflow.com/questions/13909900/progress-of-python-requests-post
class upload_in_chunks(object):
def __init__(self, filename, chunksize=1 << 13):
self.filename = filename
self.chunksize = chunksize
self.totalsize = os.path.getsize(filename)
self.readsofar = 0
def __iter__(self):
with open(self.filename, 'rb') as file:
while True:
data = file.read(self.chunksize)
if not data:
sys.stderr.write("\n")
break
self.readsofar += len(data)
percent = self.readsofar * 1e2 / self.totalsize
sys.stderr.write("\r{percent:3.0f}%".format(percent=percent))
yield data
def __len__(self):
return self.totalsize
class IterableToFileAdapter(object):
def __init__(self, iterable):
self.iterator = iter(iterable)
self.length = len(iterable)
def read(self, size=-1): # TBD: add buffer for `len(data) > size` case
return next(self.iterator, b'')
def __len__(self):
return self.length
def checkResponseCode(result, right_code):
if (result.status_code != right_code):
print('Wrong result code: ' + str(result.status_code) + ', should be ' + str(right_code))
sys.exit(1)
pp = pprint.PrettyPrinter(indent=2)
url = 'https://api.github.com/'
version_parts = version.split('.')
stable = 1
alpha = 0
dev = 0
if len(version_parts) < 2:
print('Error: expected at least major version ' + version)
sys.exit(1)
if len(version_parts) > 4:
print('Error: bad version passed ' + version)
sys.exit(1)
version_major = version_parts[0] + '.' + version_parts[1]
if len(version_parts) == 2:
version = version_major + '.0'
version_full = version
else:
version = version_major + '.' + version_parts[2]
version_full = version
if len(version_parts) == 4:
if version_parts[3] == 'dev':
dev = 1
stable = 0
version_full = version + '.dev'
elif version_parts[3] == 'alpha':
alpha = 1
stable = 0
version_full = version + '.alpha'
else:
print('Error: unexpected version part ' + version_parts[3])
sys.exit(1)
access_token = ''
if os.path.isfile(token_file):
with open(token_file) as f:
for line in f:
access_token = line.replace('\n', '')
if access_token == '':
print('Access token not found!')
sys.exit(1)
print('Version: ' + version_full);
local_folder = '/Volumes/Storage/backup/' + version_major + '/' + version_full
if stable == 1:
if os.path.isdir(local_folder + '.dev'):
dev = 1
stable = 0
version_full = version + '.dev'
local_folder = local_folder + '.dev'
elif os.path.isdir(local_folder + '.alpha'):
alpha = 1
stable = 0
version_full = version + '.alpha'
local_folder = local_folder + '.alpha'
if not os.path.isdir(local_folder):
print('Storage path not found!')
sys.exit(1)
local_folder = local_folder + '/'
files = []
files.append({
'local': 'tsetup.' + version_full + '.exe',
'remote': 'tsetup.' + version_full + '.exe',
'backup_folder': 'tsetup',
'mime': 'application/octet-stream',
'label': 'Windows: Installer',
})
files.append({
'local': 'tportable.' + version_full + '.zip',
'remote': 'tportable.' + version_full + '.zip',
'backup_folder': 'tsetup',
'mime': 'application/zip',
'label': 'Windows: Portable',
})
files.append({
'local': 'tsetup.' + version_full + '.dmg',
'remote': 'tsetup.' + version_full + '.dmg',
'backup_folder': 'tmac',
'mime': 'application/octet-stream',
'label': 'macOS and OS X 10.8+: Installer',
})
files.append({
'local': 'tsetup32.' + version_full + '.dmg',
'remote': 'tsetup32.' + version_full + '.dmg',
'backup_folder': 'tmac32',
'mime': 'application/octet-stream',
'label': 'OS X 10.6 and 10.7: Installer',
})
files.append({
'local': 'tsetup.' + version_full + '.tar.xz',
'remote': 'tsetup.' + version_full + '.tar.xz',
'backup_folder': 'tlinux',
'mime': 'application/octet-stream',
'label': 'Linux 64 bit: Binary',
})
files.append({
'local': 'tsetup32.' + version_full + '.tar.xz',
'remote': 'tsetup32.' + version_full + '.tar.xz',
'backup_folder': 'tlinux32',
'mime': 'application/octet-stream',
'label': 'Linux 32 bit: Binary',
})
r = requests.get(url + 'repos/telegramdesktop/tdesktop/releases/tags/v' + version)
if r.status_code == 404:
print('Release not found, creating.')
if commit == '':
print('Error: specify the commit.')
sys.exit(1)
if not os.path.isfile(changelog_file):
print('Error: Changelog file not found.')
sys.exit(1)
changelog = ''
started = 0
with open(changelog_file) as f:
for line in f:
if started == 1:
if re.match(r'^\d+\.\d+', line):
break;
if re.match(r'^\s+$', line):
continue
changelog += line
else:
if re.match(r'^\d+\.\d+', line):
if line[0:len(version) + 1] == version + ' ':
started = 1
elif line[0:len(version_major) + 1] == version_major + ' ':
if version_major + '.0' == version:
started = 1
if started != 1:
print('Error: Changelog not found.')
sys.exit(1)
changelog = changelog.strip()
print('Changelog: ');
print(changelog);
r = requests.post(url + 'repos/telegramdesktop/tdesktop/releases', headers={'Authorization': 'token ' + access_token}, data=json.dumps({
'tag_name': 'v' + version,
'target_commitish': commit,
'name': 'v ' + version,
'body': changelog,
'prerelease': (dev == 1 or alpha == 1),
}))
checkResponseCode(r, 201)
r = requests.get(url + 'repos/telegramdesktop/tdesktop/releases/tags/v' + version)
checkResponseCode(r, 200);
release_data = r.json()
#pp.pprint(release_data)
release_id = release_data['id']
print('Release ID: ' + str(release_id))
r = requests.get(url + 'repos/telegramdesktop/tdesktop/releases/' + str(release_id) + '/assets');
checkResponseCode(r, 200);
assets = release_data['assets']
for asset in assets:
name = asset['name']
found = 0
for file in files:
if file['remote'] == name:
print('Already uploaded: ' + name)
file['already'] = 1
found = 1
break
if found == 0:
print('Warning: strange asset: ' + name)
for file in files:
if 'already' in file:
continue
file_path = local_folder + file['backup_folder'] + '/' + file['local']
if not os.path.isfile(file_path):
print('Warning: file not found ' + file['local'])
continue
upload_url = expand(release_data['upload_url'], {'name': file['remote'], 'label': file['label']}) + '&access_token=' + access_token;
content = upload_in_chunks(file_path, 10)
print('Uploading: ' + file['remote'] + ' (' + str(round(len(content) / 10000) / 100.) + ' MB)')
r = requests.post(upload_url, headers={"Content-Type": file['mime']}, data=IterableToFileAdapter(content))
checkResponseCode(r, 201)
print('Success! Removing.')
return_code = call(["rm", file_path])
if return_code != 0:
print('Bad rm code: ' + str(return_code))
sys.exit(1)
sys.exit()
| gpl-3.0 | -4,684,818,419,198,945,000 | 27.859375 | 138 | 0.614781 | false | 3.20799 | false | false | false |
UASLab/ImageAnalysis | video/hud.py | 1 | 43557 | import datetime
import ephem # dnf install python3-pyephem
import math
import navpy
import numpy as np
# find our custom built opencv first
import sys
sys.path.insert(0, "/usr/local/opencv3/lib/python2.7/site-packages/")
import cv2
sys.path.append('../scripts')
from lib import transformations
import airports
# helpful constants
d2r = math.pi / 180.0
r2d = 180.0 / math.pi
mps2kt = 1.94384
kt2mps = 1 / mps2kt
ft2m = 0.3048
m2ft = 1 / ft2m
# color definitions
green2 = (0, 238, 0)
red2 = (0, 0, 238)
medium_orchid = (186, 85, 211)
yellow = (50, 255, 255)
white = (255, 255, 255)
class HUD:
def __init__(self, K):
self.K = K
self.PROJ = None
self.cam_yaw = 0.0
self.cam_pitch = 0.0
self.cam_roll = 0.0
self.line_width = 1
self.color = green2
self.font = cv2.FONT_HERSHEY_SIMPLEX
self.font_size = 0.6
self.render_w = 0
self.render_h = 0
self.lla = [0.0, 0.0, 0.0]
self.time = 0
self.unixtime = 0
self.ned = [0.0, 0.0, 0.0]
self.ned_history = []
self.ned_last_time = 0.0
self.grid = []
self.ref = None
self.vn = 0.0
self.ve = 0.0
self.vd = 0.0
self.vel_filt = [0.0, 0.0, 0.0]
self.phi_rad = 0
self.the_rad = 0
self.psi_rad = 0
self.frame = None
self.airspeed_units = 'kt'
self.altitude_units = 'ft'
self.airspeed_kt = 0
self.altitude_m = 0
self.ground_m = 0
self.flight_mode = 'none'
self.ap_roll = 0
self.ap_pitch = 0
self.ap_hdg = 0
self.ap_speed = 0
self.ap_altitude_ft = 0
self.alpha_rad = 0
self.beta_rad = 0
self.filter_vn = 0.0
self.filter_ve = 0.0
self.tf_vel = 0.5
self.pilot_ail = 0.0
self.pilot_ele = 0.0
self.pilot_thr = 0.0
self.pilot_rud = 0.0
self.act_ail = 0.0
self.act_ele = 0.0
self.act_thr = 0.0
self.act_rud = 0.0
self.airports = []
self.features = []
def set_render_size(self, w, h):
self.render_w = w
self.render_h = h
def set_line_width(self, line_width):
self.line_width = line_width
if self.line_width < 1:
self.line_width = 1
def set_color(self, color):
self.color = color
def set_font_size(self, font_size):
self.font_size = font_size
if self.font_size < 0.4:
self.font_size = 0.4
def set_units(self, airspeed_units, altitude_units):
self.airspeed_units = airspeed_units
self.altitude_units = altitude_units
def set_ned_ref(self, lat, lon):
self.ref = [ lat, lon, 0.0]
def load_airports(self):
if self.ref:
self.airports = airports.load('apt.csv', self.ref, 30000)
else:
print('no ned ref set, unable to load nearby airports.')
def set_ground_m(self, ground_m):
self.ground_m = ground_m
def update_frame(self, frame):
self.frame = frame
def update_lla(self, lla):
self.lla = lla
def update_time(self, time, unixtime):
self.time = time
self.unixtime = unixtime
def update_test_index(self, mode, index):
self.excite_mode = mode
self.test_index = index
def update_ned_history(self, ned, seconds):
if int(self.time) > self.ned_last_time:
self.ned_last_time = int(self.time)
self.ned_history.append(ned)
while len(self.ned_history) > seconds:
self.ned_history.pop(0)
def update_ned(self, ned, seconds):
self.ned = ned[:]
self.update_ned_history(ned, seconds)
def update_features(self, feature_list):
self.features = feature_list
def update_proj(self, PROJ):
self.PROJ = PROJ
def update_cam_att(self, cam_yaw, cam_pitch, cam_roll):
self.cam_yaw = cam_yaw
self.cam_pitch = cam_pitch
self.cam_roll = cam_roll
def update_vel(self, vn, ve, vd):
self.vn = vn
self.ve = ve
self.vd = vd
def update_att_rad(self, phi_rad, the_rad, psi_rad):
self.phi_rad = phi_rad
self.the_rad = the_rad
self.psi_rad = psi_rad
def update_airdata(self, airspeed_kt, altitude_m, alpha_rad=0, beta_rad=0):
self.airspeed_kt = airspeed_kt
self.altitude_m = altitude_m
self.alpha_rad = alpha_rad
self.beta_rad = beta_rad
def update_ap(self, flight_mode, ap_roll, ap_pitch, ap_hdg,
ap_speed, ap_altitude_ft):
self.flight_mode = flight_mode
self.ap_roll = ap_roll
self.ap_pitch = ap_pitch
self.ap_hdg = ap_hdg
self.ap_speed = ap_speed
self.ap_altitude_ft = ap_altitude_ft
def update_pilot(self, aileron, elevator, throttle, rudder):
self.pilot_ail = aileron
self.pilot_ele = elevator
self.pilot_thr = throttle
self.pilot_rud = rudder
def update_act(self, aileron, elevator, throttle, rudder):
self.act_ail = aileron
self.act_ele = elevator
self.act_thr = throttle
self.act_rud = rudder
def compute_sun_moon_ned(self, lon_deg, lat_deg, alt_m, timestamp):
d = datetime.datetime.utcfromtimestamp(timestamp)
#d = datetime.datetime.utcnow()
ed = ephem.Date(d)
#print 'ephem time utc:', ed
#print 'localtime:', ephem.localtime(ed)
ownship = ephem.Observer()
ownship.lon = '%.8f' % lon_deg
ownship.lat = '%.8f' % lat_deg
ownship.elevation = alt_m
ownship.date = ed
sun = ephem.Sun(ownship)
moon = ephem.Moon(ownship)
sun_ned = [ math.cos(sun.az) * math.cos(sun.alt),
math.sin(sun.az) * math.cos(sun.alt),
-math.sin(sun.alt) ]
moon_ned = [ math.cos(moon.az) * math.cos(moon.alt),
math.sin(moon.az) * math.cos(moon.alt),
-math.sin(moon.alt) ]
return sun_ned, moon_ned
def project_point(self, ned):
uvh = self.K.dot( self.PROJ.dot( [ned[0], ned[1], ned[2], 1.0] ).T )
if uvh[2] > 0.2:
uvh /= uvh[2]
uv = ( int(np.squeeze(uvh[0,0])), int(np.squeeze(uvh[1,0])) )
return uv
else:
return None
def draw_horizon(self):
divs = 10
pts = []
for i in range(divs + 1):
a = (float(i) * 360/float(divs)) * d2r
n = math.cos(a)
e = math.sin(a)
d = 0.0
pts.append( [n, e, d] )
for i in range(divs):
p1 = pts[i]
p2 = pts[i+1]
uv1 = self.project_point( [self.ned[0] + p1[0],
self.ned[1] + p1[1],
self.ned[2] + p1[2]] )
uv2 = self.project_point( [self.ned[0] + p2[0],
self.ned[1] + p2[1],
self.ned[2] + p2[2]] )
if uv1 != None and uv2 != None:
cv2.line(self.frame, uv1, uv2, self.color, self.line_width,
cv2.LINE_AA)
def ladder_helper(self, q0, a0, a1):
q1 = transformations.quaternion_from_euler(-a1*d2r, -a0*d2r, 0.0,
'rzyx')
q = transformations.quaternion_multiply(q1, q0)
v = transformations.quaternion_transform(q, [1.0, 0.0, 0.0])
uv = self.project_point( [self.ned[0] + v[0],
self.ned[1] + v[1],
self.ned[2] + v[2]] )
return uv
def draw_pitch_ladder(self, beta_rad=0.0):
a1 = 2.0
a2 = 8.0
#slide_rad = self.psi_rad - beta_rad
slide_rad = self.psi_rad
q0 = transformations.quaternion_about_axis(slide_rad, [0.0, 0.0, -1.0])
for a0 in range(5,35,5):
# above horizon
# right horizontal
uv1 = self.ladder_helper(q0, a0, a1)
uv2 = self.ladder_helper(q0, a0, a2)
if uv1 != None and uv2 != None:
cv2.line(self.frame, uv1, uv2, self.color, self.line_width,
cv2.LINE_AA)
du = uv2[0] - uv1[0]
dv = uv2[1] - uv1[1]
uv = ( uv1[0] + int(1.25*du), uv1[1] + int(1.25*dv) )
self.draw_label("%d" % a0, uv, self.font_size, self.line_width)
# right tick
uv1 = self.ladder_helper(q0, a0-0.5, a1)
uv2 = self.ladder_helper(q0, a0, a1)
if uv1 != None and uv2 != None:
cv2.line(self.frame, uv1, uv2, self.color, self.line_width,
cv2.LINE_AA)
# left horizontal
uv1 = self.ladder_helper(q0, a0, -a1)
uv2 = self.ladder_helper(q0, a0, -a2)
if uv1 != None and uv2 != None:
cv2.line(self.frame, uv1, uv2, self.color, self.line_width,
cv2.LINE_AA)
du = uv2[0] - uv1[0]
dv = uv2[1] - uv1[1]
uv = ( uv1[0] + int(1.25*du), uv1[1] + int(1.25*dv) )
self.draw_label("%d" % a0, uv, self.font_size, self.line_width)
# left tick
uv1 = self.ladder_helper(q0, a0-0.5, -a1)
uv2 = self.ladder_helper(q0, a0, -a1)
if uv1 != None and uv2 != None:
cv2.line(self.frame, uv1, uv2, self.color, self.line_width,
cv2.LINE_AA)
# below horizon
# right horizontal
uv1 = self.ladder_helper(q0, -a0, a1)
uv2 = self.ladder_helper(q0, -a0-0.5, a2)
if uv1 != None and uv2 != None:
du = uv2[0] - uv1[0]
dv = uv2[1] - uv1[1]
for i in range(0,3):
tmp1 = (uv1[0] + int(0.375*i*du), uv1[1] + int(0.375*i*dv))
tmp2 = (tmp1[0] + int(0.25*du), tmp1[1] + int(0.25*dv))
cv2.line(self.frame, tmp1, tmp2, self.color,
self.line_width, cv2.LINE_AA)
uv = ( uv1[0] + int(1.25*du), uv1[1] + int(1.25*dv) )
self.draw_label("%d" % a0, uv, self.font_size, self.line_width)
# right tick
uv1 = self.ladder_helper(q0, -a0+0.5, a1)
uv2 = self.ladder_helper(q0, -a0, a1)
if uv1 != None and uv2 != None:
cv2.line(self.frame, uv1, uv2, self.color, self.line_width,
cv2.LINE_AA)
# left horizontal
uv1 = self.ladder_helper(q0, -a0, -a1)
uv2 = self.ladder_helper(q0, -a0-0.5, -a2)
if uv1 != None and uv2 != None:
du = uv2[0] - uv1[0]
dv = uv2[1] - uv1[1]
for i in range(0,3):
tmp1 = (uv1[0] + int(0.375*i*du), uv1[1] + int(0.375*i*dv))
tmp2 = (tmp1[0] + int(0.25*du), tmp1[1] + int(0.25*dv))
cv2.line(self.frame, tmp1, tmp2, self.color,
self.line_width, cv2.LINE_AA)
uv = ( uv1[0] + int(1.25*du), uv1[1] + int(1.25*dv) )
self.draw_label("%d" % a0, uv, self.font_size, self.line_width)
# left tick
uv1 = self.ladder_helper(q0, -a0+0.5, -a1)
uv2 = self.ladder_helper(q0, -a0, -a1)
if uv1 != None and uv2 != None:
cv2.line(self.frame, uv1, uv2, self.color, self.line_width,
cv2.LINE_AA)
def draw_alpha_beta_marker(self):
if self.alpha_rad == None or self.beta_rad == None:
return
q0 = transformations.quaternion_about_axis(self.psi_rad, [0.0, 0.0, -1.0])
a0 = self.the_rad * r2d
center = self.ladder_helper(q0, a0, 0.0)
alpha = self.alpha_rad * r2d
beta = self.beta_rad * r2d
tmp = self.ladder_helper(q0, a0-alpha, beta)
if tmp != None:
uv = self.rotate_pt(tmp, center, self.phi_rad)
if uv != None:
r1 = int(round(self.render_h / 60))
r2 = int(round(self.render_h / 30))
uv1 = (uv[0]+r1, uv[1])
uv2 = (uv[0]+r2, uv[1])
uv3 = (uv[0]-r1, uv[1])
uv4 = (uv[0]-r2, uv[1])
uv5 = (uv[0], uv[1]-r1)
uv6 = (uv[0], uv[1]-r2)
cv2.circle(self.frame, uv, r1, self.color, self.line_width,
cv2.LINE_AA)
cv2.line(self.frame, uv1, uv2, self.color, self.line_width,
cv2.LINE_AA)
cv2.line(self.frame, uv3, uv4, self.color, self.line_width,
cv2.LINE_AA)
cv2.line(self.frame, uv5, uv6, self.color, self.line_width,
cv2.LINE_AA)
def rotate_pt(self, p, center, a):
#print p, center
x = math.cos(a) * (p[0]-center[0]) - math.sin(a) * (p[1]-center[1]) + center[0]
y = math.sin(a) * (p[0]-center[0]) + math.cos(a) * (p[1]-center[1]) + center[1]
return (int(x), int(y))
def draw_vbars(self):
color = medium_orchid
size = self.line_width
a1 = 10.0
a2 = 1.5
a3 = 3.0
q0 = transformations.quaternion_about_axis(self.psi_rad,
[0.0, 0.0, -1.0])
a0 = self.ap_pitch
# rotation point (about nose)
rot = self.ladder_helper(q0, self.the_rad*r2d, 0.0)
if rot == None:
return
# center point
tmp1 = self.ladder_helper(q0, a0, 0.0)
if tmp1 == None:
return
center = self.rotate_pt(tmp1, rot, self.ap_roll*d2r)
# right vbar
tmp1 = self.ladder_helper(q0, a0-a3, a1)
tmp2 = self.ladder_helper(q0, a0-a3, a1+a3)
tmp3 = self.ladder_helper(q0, a0-a2, a1+a3)
if tmp1 != None and tmp2 != None and tmp3 != None:
uv1 = self.rotate_pt(tmp1, rot, self.ap_roll*d2r)
uv2 = self.rotate_pt(tmp2, rot, self.ap_roll*d2r)
uv3 = self.rotate_pt(tmp3, rot, self.ap_roll*d2r)
if uv1 != None and uv2 != None and uv3 != None:
cv2.line(self.frame, center, uv1, color, self.line_width, cv2.LINE_AA)
cv2.line(self.frame, center, uv3, color, self.line_width, cv2.LINE_AA)
cv2.line(self.frame, uv1, uv2, color, self.line_width, cv2.LINE_AA)
cv2.line(self.frame, uv1, uv3, color, self.line_width, cv2.LINE_AA)
cv2.line(self.frame, uv2, uv3, color, self.line_width, cv2.LINE_AA)
# left vbar
tmp1 = self.ladder_helper(q0, a0-a3, -a1)
tmp2 = self.ladder_helper(q0, a0-a3, -a1-a3)
tmp3 = self.ladder_helper(q0, a0-a2, -a1-a3)
if tmp1 != None and tmp2 != None and tmp3 != None:
uv1 = self.rotate_pt(tmp1, rot, self.ap_roll*d2r)
uv2 = self.rotate_pt(tmp2, rot, self.ap_roll*d2r)
uv3 = self.rotate_pt(tmp3, rot, self.ap_roll*d2r)
if uv1 != None and uv2 != None and uv3 != None:
cv2.line(self.frame, center, uv1, color, self.line_width, cv2.LINE_AA)
cv2.line(self.frame, center, uv3, color, self.line_width, cv2.LINE_AA)
cv2.line(self.frame, uv1, uv2, color, self.line_width, cv2.LINE_AA)
cv2.line(self.frame, uv1, uv3, color, self.line_width, cv2.LINE_AA)
cv2.line(self.frame, uv2, uv3, color, self.line_width, cv2.LINE_AA)
def draw_heading_bug(self):
color = medium_orchid
size = 2
a = math.atan2(self.ve, self.vn)
q0 = transformations.quaternion_about_axis(self.ap_hdg*d2r,
[0.0, 0.0, -1.0])
center = self.ladder_helper(q0, 0, 0)
pts = []
pts.append( self.ladder_helper(q0, 0, 2.0) )
pts.append( self.ladder_helper(q0, 0.0, -2.0) )
pts.append( self.ladder_helper(q0, 1.5, -2.0) )
pts.append( self.ladder_helper(q0, 1.5, -1.0) )
pts.append( center )
pts.append( self.ladder_helper(q0, 1.5, 1.0) )
pts.append( self.ladder_helper(q0, 1.5, 2.0) )
for i, p in enumerate(pts):
if p == None or center == None:
return
cv2.line(self.frame, pts[0], pts[1], color, self.line_width, cv2.LINE_AA)
cv2.line(self.frame, pts[1], pts[2], color, self.line_width, cv2.LINE_AA)
cv2.line(self.frame, pts[2], pts[3], color, self.line_width, cv2.LINE_AA)
cv2.line(self.frame, pts[3], pts[4], color, self.line_width, cv2.LINE_AA)
cv2.line(self.frame, pts[4], pts[5], color, self.line_width, cv2.LINE_AA)
cv2.line(self.frame, pts[5], pts[6], color, self.line_width, cv2.LINE_AA)
cv2.line(self.frame, pts[6], pts[0], color, self.line_width, cv2.LINE_AA)
def draw_bird(self):
color = yellow
size = 2
a1 = 10.0
a2 = 3.0
q0 = transformations.quaternion_about_axis(self.psi_rad, [0.0, 0.0, -1.0])
a0 = self.the_rad*r2d
# print 'pitch:', a0, 'ap:', self.ap_pitch
# center point
center = self.ladder_helper(q0, a0, 0.0)
if center == None:
return
# right vbar
tmp1 = self.ladder_helper(q0, a0-a2, a1)
tmp2 = self.ladder_helper(q0, a0-a2, a1-a2)
if tmp1 != None and tmp2 != None:
uv1 = self.rotate_pt(tmp1, center, self.phi_rad)
uv2 = self.rotate_pt(tmp2, center, self.phi_rad)
if uv1 != None and uv2 != None:
cv2.line(self.frame, center, uv1, color, self.line_width, cv2.LINE_AA)
cv2.line(self.frame, center, uv2, color, self.line_width, cv2.LINE_AA)
cv2.line(self.frame, uv1, uv2, color, self.line_width, cv2.LINE_AA)
# left vbar
tmp1 = self.ladder_helper(q0, a0-a2, -a1)
tmp2 = self.ladder_helper(q0, a0-a2, -a1+a2)
if tmp1 != None and tmp2 != None:
uv1 = self.rotate_pt(tmp1, center, self.phi_rad)
uv2 = self.rotate_pt(tmp2, center, self.phi_rad)
if uv1 != None and uv2 != None:
cv2.line(self.frame, center, uv1, color, self.line_width, cv2.LINE_AA)
cv2.line(self.frame, center, uv2, color, self.line_width, cv2.LINE_AA)
cv2.line(self.frame, uv1, uv2, color, self.line_width, cv2.LINE_AA)
def draw_course(self):
color = yellow
size = 2
self.filter_vn = (1.0 - self.tf_vel) * self.filter_vn + self.tf_vel * self.vn
self.filter_ve = (1.0 - self.tf_vel) * self.filter_ve + self.tf_vel * self.ve
a = math.atan2(self.filter_ve, self.filter_vn)
q0 = transformations.quaternion_about_axis(a, [0.0, 0.0, -1.0])
uv1 = self.ladder_helper(q0, 0, 0)
uv2 = self.ladder_helper(q0, 1.5, 1.0)
uv3 = self.ladder_helper(q0, 1.5, -1.0)
if uv1 != None and uv2 != None and uv3 != None :
#uv2 = self.rotate_pt(tmp2, tmp1, -self.cam_roll*d2r)
#uv3 = self.rotate_pt(tmp3, tmp1, -self.cam_roll*d2r)
cv2.line(self.frame, uv1, uv2, color, self.line_width, cv2.LINE_AA)
cv2.line(self.frame, uv1, uv3, color, self.line_width, cv2.LINE_AA)
def draw_label(self, label, uv, font_scale, thickness,
horiz='center', vert='center'):
size = cv2.getTextSize(label, self.font, font_scale, thickness)
if horiz == 'center':
u = uv[0] - (size[0][0] / 2)
else:
u = uv[0]
if vert == 'above':
v = uv[1]
elif vert == 'below':
v = uv[1] + size[0][1]
elif vert == 'center':
v = uv[1] + (size[0][1] / 2)
uv = (int(u), int(v))
cv2.putText(self.frame, label, uv, self.font, font_scale,
self.color, thickness, cv2.LINE_AA)
def draw_ned_point(self, ned, label=None, scale=1, vert='above'):
uv = self.project_point([ned[0], ned[1], ned[2]])
if uv != None:
cv2.circle(self.frame, uv, 4+self.line_width, self.color,
self.line_width, cv2.LINE_AA)
if label:
if vert == 'above':
uv = self.project_point([ned[0], ned[1], ned[2] - 0.02])
else:
uv = self.project_point([ned[0], ned[1], ned[2] + 0.02])
if uv != None:
self.draw_label(label, uv, scale, self.line_width, vert=vert)
def draw_lla_point(self, lla, label):
pt_ned = navpy.lla2ned( lla[0], lla[1], lla[2],
self.ref[0], self.ref[1], self.ref[2] )
rel_ned = [ pt_ned[0] - self.ned[0],
pt_ned[1] - self.ned[1],
pt_ned[2] - self.ned[2] ]
hdist = math.sqrt(rel_ned[0]*rel_ned[0] + rel_ned[1]*rel_ned[1])
dist = math.sqrt(rel_ned[0]*rel_ned[0] + rel_ned[1]*rel_ned[1]
+ rel_ned[2]*rel_ned[2])
m2sm = 0.000621371
hdist_sm = hdist * m2sm
if hdist_sm <= 10.0:
scale = 0.7 - (hdist_sm / 10.0) * 0.4
if hdist_sm <= 7.5:
label += " (%.1f)" % hdist_sm
# normalize, and draw relative to aircraft ned so that label
# separation works better
rel_ned[0] /= dist
rel_ned[1] /= dist
rel_ned[2] /= dist
self.draw_ned_point([self.ned[0] + rel_ned[0],
self.ned[1] + rel_ned[1],
self.ned[2] + rel_ned[2]],
label, scale=scale, vert='below')
def draw_compass_points(self):
# 30 Ticks
divs = 12
pts = []
for i in range(divs):
a = (float(i) * 360/float(divs)) * d2r
n = math.cos(a)
e = math.sin(a)
uv1 = self.project_point([self.ned[0] + n,
self.ned[1] + e,
self.ned[2] - 0.0])
uv2 = self.project_point([self.ned[0] + n,
self.ned[1] + e,
self.ned[2] - 0.02])
if uv1 != None and uv2 != None:
cv2.line(self.frame, uv1, uv2, self.color, self.line_width,
cv2.LINE_AA)
# North
uv = self.project_point([self.ned[0] + 1.0, self.ned[1] + 0.0, self.ned[2] - 0.03])
if uv != None:
self.draw_label('N', uv, 1, self.line_width, vert='above')
# South
uv = self.project_point([self.ned[0] - 1.0, self.ned[1] + 0.0, self.ned[2] - 0.03])
if uv != None:
self.draw_label('S', uv, 1, self.line_width, vert='above')
# East
uv = self.project_point([self.ned[0] + 0.0, self.ned[1] + 1.0, self.ned[2] - 0.03])
if uv != None:
self.draw_label('E', uv, 1, self.line_width, vert='above')
# West
uv = self.project_point([self.ned[0] + 0.0, self.ned[1] - 1.0, self.ned[2] - 0.03])
if uv != None:
self.draw_label('W', uv, 1, self.line_width, vert='above')
def draw_astro(self):
sun_ned, moon_ned = self.compute_sun_moon_ned(self.lla[1],
self.lla[0],
self.lla[2],
self.unixtime)
if sun_ned == None or moon_ned == None:
return
# Sun
self.draw_ned_point([self.ned[0] + sun_ned[0],
self.ned[1] + sun_ned[1],
self.ned[2] + sun_ned[2]],
'Sun')
# shadow (if sun above horizon)
if sun_ned[2] < 0.0:
self.draw_ned_point([self.ned[0] - sun_ned[0],
self.ned[1] - sun_ned[1],
self.ned[2] - sun_ned[2]],
'shadow', scale=0.7)
# Moon
self.draw_ned_point([self.ned[0] + moon_ned[0],
self.ned[1] + moon_ned[1],
self.ned[2] + moon_ned[2]],
'Moon')
def draw_airports(self):
for apt in self.airports:
self.draw_lla_point([ apt[1], apt[2], apt[3] ], apt[0])
def draw_nose(self):
ned2body = transformations.quaternion_from_euler(self.psi_rad,
self.the_rad,
self.phi_rad,
'rzyx')
body2ned = transformations.quaternion_inverse(ned2body)
vec = transformations.quaternion_transform(body2ned, [1.0, 0.0, 0.0])
uv = self.project_point([self.ned[0] + vec[0],
self.ned[1] + vec[1],
self.ned[2]+ vec[2]])
r1 = int(round(self.render_h / 80))
r2 = int(round(self.render_h / 40))
if uv != None:
cv2.circle(self.frame, uv, r1, self.color, self.line_width, cv2.LINE_AA)
cv2.circle(self.frame, uv, r2, self.color, self.line_width, cv2.LINE_AA)
def draw_velocity_vector(self):
tf = 0.2
vel = [self.vn, self.ve, self.vd] # filter coding convenience
for i in range(3):
self.vel_filt[i] = (1.0 - tf) * self.vel_filt[i] + tf * vel[i]
uv = self.project_point([self.ned[0] + self.vel_filt[0],
self.ned[1] + self.vel_filt[1],
self.ned[2] + self.vel_filt[2]])
if uv != None:
cv2.circle(self.frame, uv, 4, self.color, 1, cv2.LINE_AA)
def draw_speed_tape(self, airspeed, ap_speed, units_label):
color = self.color
size = 1
pad = 5 + self.line_width*2
h, w, d = self.frame.shape
# reference point
cy = int(h * 0.5)
cx = int(w * 0.2)
miny = int(h * 0.2)
maxy = int(h - miny)
# current airspeed
label = "%.0f" % airspeed
lsize = cv2.getTextSize(label, self.font, self.font_size, self.line_width)
xsize = lsize[0][0] + pad
ysize = lsize[0][1] + pad
uv = ( int(cx + ysize*0.7), int(cy + lsize[0][1] / 2))
cv2.putText(self.frame, label, uv, self.font, self.font_size, color, self.line_width, cv2.LINE_AA)
uv1 = (cx, cy)
uv2 = (cx + int(ysize*0.7), int(cy - ysize / 2) )
uv3 = (cx + int(ysize*0.7) + xsize, int(cy - ysize / 2) )
uv4 = (cx + int(ysize*0.7) + xsize, int(cy + ysize / 2 + 1) )
uv5 = (cx + int(ysize*0.7), int(cy + ysize / 2 + 1) )
cv2.line(self.frame, uv1, uv2, color, self.line_width, cv2.LINE_AA)
cv2.line(self.frame, uv2, uv3, color, self.line_width, cv2.LINE_AA)
cv2.line(self.frame, uv3, uv4, color, self.line_width, cv2.LINE_AA)
cv2.line(self.frame, uv4, uv5, color, self.line_width, cv2.LINE_AA)
cv2.line(self.frame, uv5, uv1, color, self.line_width, cv2.LINE_AA)
# speed tics
spacing = lsize[0][1]
y = cy - int((0 - airspeed) * spacing)
if y < miny: y = miny
if y > maxy: y = maxy
uv1 = (cx, y)
y = cy - int((70 - airspeed) * spacing)
if y < miny: y = miny
if y > maxy: y = maxy
uv2 = (cx, y)
cv2.line(self.frame, uv1, uv2, color, self.line_width, cv2.LINE_AA)
for i in range(0, 65, 1):
offset = int((i - airspeed) * spacing)
if cy - offset >= miny and cy - offset <= maxy:
uv1 = (cx, cy - offset)
if i % 5 == 0:
uv2 = (cx - 6, cy - offset)
else:
uv2 = (cx - 4, cy - offset)
cv2.line(self.frame, uv1, uv2, color, self.line_width, cv2.LINE_AA)
for i in range(0, 65, 5):
offset = int((i - airspeed) * spacing)
if cy - offset >= miny and cy - offset <= maxy:
label = "%d" % i
lsize = cv2.getTextSize(label, self.font, self.font_size, self.line_width)
uv3 = (cx - 8 - lsize[0][0], cy - offset + int(lsize[0][1] / 2))
cv2.putText(self.frame, label, uv3, self.font, self.font_size, color, self.line_width, cv2.LINE_AA)
# units
lsize = cv2.getTextSize(units_label, self.font, self.font_size, self.line_width)
uv = (cx - int(lsize[0][1]*0.5), maxy + lsize[0][1] + self.line_width*2)
cv2.putText(self.frame, units_label, uv, self.font, self.font_size, color, self.line_width, cv2.LINE_AA)
# speed bug
offset = int((ap_speed - airspeed) * spacing)
if self.flight_mode == 'auto' and cy - offset >= miny and cy - offset <= maxy:
uv1 = (cx, cy - offset)
uv2 = (cx + int(ysize*0.7), cy - offset - int(ysize / 2) )
uv3 = (cx + int(ysize*0.7), cy - offset - ysize )
uv4 = (cx, cy - offset - ysize )
uv5 = (cx, cy - offset + ysize )
uv6 = (cx + int(ysize*0.7), cy - offset + ysize )
uv7 = (cx + int(ysize*0.7), cy - offset + int(ysize / 2) )
cv2.line(self.frame, uv1, uv2, color, self.line_width, cv2.LINE_AA)
cv2.line(self.frame, uv2, uv3, color, self.line_width, cv2.LINE_AA)
cv2.line(self.frame, uv3, uv4, color, self.line_width, cv2.LINE_AA)
cv2.line(self.frame, uv4, uv5, color, self.line_width, cv2.LINE_AA)
cv2.line(self.frame, uv5, uv6, color, self.line_width, cv2.LINE_AA)
cv2.line(self.frame, uv6, uv7, color, self.line_width, cv2.LINE_AA)
cv2.line(self.frame, uv7, uv1, color, self.line_width, cv2.LINE_AA)
def draw_altitude_tape(self, altitude, ap_alt, units_label):
color = self.color
size = 1
pad = 5 + self.line_width*2
h, w, d = self.frame.shape
# reference point
cy = int(h * 0.5)
cx = int(w * 0.8)
miny = int(h * 0.2)
maxy = int(h - miny)
minrange = int(altitude/100)*10 - 30
maxrange = int(altitude/100)*10 + 30
# current altitude (computed first so we can size all elements)
label = "%.0f" % (round(altitude/10.0) * 10)
lsize = cv2.getTextSize(label, self.font, self.font_size, self.line_width)
spacing = lsize[0][1]
xsize = lsize[0][0] + pad
ysize = lsize[0][1] + pad
# draw ground
if self.altitude_units == 'm':
offset = int((self.ground_m - altitude)/10.0 * spacing)
else:
offset = int((self.ground_m*m2ft - altitude)/10.0 * spacing)
if cy - offset >= miny and cy - offset <= maxy:
uv1 = (cx, cy - offset)
uv2 = (cx + int(ysize*3), cy - offset)
cv2.line(self.frame, uv1, uv2, red2, self.line_width*2, cv2.LINE_AA)
# draw max altitude
if self.altitude_units == 'm':
offset = int((self.ground_m + 121.92 - altitude)/10.0 * spacing)
else:
offset = int((self.ground_m*m2ft + 400.0 - altitude)/10.0 * spacing)
if cy - offset >= miny and cy - offset <= maxy:
uv1 = (cx, cy - offset)
uv2 = (cx + int(ysize*2), cy - offset)
cv2.line(self.frame, uv1, uv2, yellow, self.line_width*2, cv2.LINE_AA)
# draw current altitude
uv = ( int(cx - ysize*0.7 - lsize[0][0]), cy + int(lsize[0][1] / 2))
cv2.putText(self.frame, label, uv, self.font, self.font_size, color, self.line_width, cv2.LINE_AA)
uv1 = (cx, cy)
uv2 = (cx - int(ysize*0.7), cy - int(ysize / 2) )
uv3 = (cx - int(ysize*0.7) - xsize, cy - int(ysize / 2) )
uv4 = (cx - int(ysize*0.7) - xsize, cy + int(ysize / 2) + 1 )
uv5 = (cx - int(ysize*0.7), cy + int(ysize / 2) + 1 )
cv2.line(self.frame, uv1, uv2, color, self.line_width, cv2.LINE_AA)
cv2.line(self.frame, uv2, uv3, color, self.line_width, cv2.LINE_AA)
cv2.line(self.frame, uv3, uv4, color, self.line_width, cv2.LINE_AA)
cv2.line(self.frame, uv4, uv5, color, self.line_width, cv2.LINE_AA)
cv2.line(self.frame, uv5, uv1, color, self.line_width, cv2.LINE_AA)
# msl tics
y = cy - int((minrange*10 - altitude)/10 * spacing)
if y < miny: y = miny
if y > maxy: y = maxy
uv1 = (cx, y)
y = cy - int((maxrange*10 - altitude)/10 * spacing)
if y < miny: y = miny
if y > maxy: y = maxy
uv2 = (cx, y)
cv2.line(self.frame, uv1, uv2, color, self.line_width, cv2.LINE_AA)
for i in range(minrange, maxrange, 1):
offset = int((i*10 - altitude)/10 * spacing)
if cy - offset >= miny and cy - offset <= maxy:
uv1 = (cx, cy - offset)
if i % 5 == 0:
uv2 = (cx + 6, cy - offset)
else:
uv2 = (cx + 4, cy - offset)
cv2.line(self.frame, uv1, uv2, color, self.line_width, cv2.LINE_AA)
for i in range(minrange, maxrange, 5):
offset = int((i*10 - altitude)/10 * spacing)
if cy - offset >= miny and cy - offset <= maxy:
label = "%d" % (i*10)
lsize = cv2.getTextSize(label, self.font, self.font_size, self.line_width)
uv3 = (cx + 8 , cy - offset + int(lsize[0][1] / 2))
cv2.putText(self.frame, label, uv3, self.font, self.font_size, color, self.line_width, cv2.LINE_AA)
# units
lsize = cv2.getTextSize(units_label, self.font, self.font_size, self.line_width)
uv = (cx - int(lsize[0][1]*0.5), maxy + lsize[0][1] + self.line_width*2)
cv2.putText(self.frame, units_label, uv, self.font, self.font_size, color, self.line_width, cv2.LINE_AA)
# altitude bug
offset = int((ap_alt - altitude)/10.0 * spacing)
if self.flight_mode == 'auto' and cy - offset >= miny and cy - offset <= maxy:
uv1 = (cx, cy - offset)
uv2 = (cx - int(ysize*0.7), cy - offset - int(ysize / 2) )
uv3 = (cx - int(ysize*0.7), cy - offset - ysize )
uv4 = (cx, cy - offset - ysize )
uv5 = (cx, cy - offset + ysize )
uv6 = (cx - int(ysize*0.7), cy - offset + ysize )
uv7 = (cx - int(ysize*0.7), cy - offset + int(ysize / 2) )
cv2.line(self.frame, uv1, uv2, color, self.line_width, cv2.LINE_AA)
cv2.line(self.frame, uv2, uv3, color, self.line_width, cv2.LINE_AA)
cv2.line(self.frame, uv3, uv4, color, self.line_width, cv2.LINE_AA)
cv2.line(self.frame, uv4, uv5, color, self.line_width, cv2.LINE_AA)
cv2.line(self.frame, uv5, uv6, color, self.line_width, cv2.LINE_AA)
cv2.line(self.frame, uv6, uv7, color, self.line_width, cv2.LINE_AA)
cv2.line(self.frame, uv7, uv1, color, self.line_width, cv2.LINE_AA)
# draw stick positions (rc transmitter sticks)
def draw_sticks(self):
if self.flight_mode == 'auto':
aileron = self.act_ail
elevator = self.act_ele
throttle = self.act_thr
rudder = self.act_rud
else:
aileron = self.pilot_ail
elevator = self.pilot_ele
throttle = self.pilot_thr
rudder = self.pilot_rud
h, w, d = self.frame.shape
lx = int(h * 0.1)
ly = int(h * 0.8)
rx = w - int(h * 0.1)
ry = int(h * 0.8)
r1 = int(round(h * 0.09))
if r1 < 10: r1 = 10
r2 = int(round(h * 0.01))
if r2 < 2: r2 = 2
cv2.circle(self.frame, (lx,ly), r1, self.color, self.line_width,
cv2.LINE_AA)
cv2.line(self.frame, (lx,ly-r1), (lx,ly+r1), self.color, 1,
cv2.LINE_AA)
cv2.line(self.frame, (lx-r1,ly), (lx+r1,ly), self.color, 1,
cv2.LINE_AA)
cv2.circle(self.frame, (rx,ry), r1, self.color, self.line_width,
cv2.LINE_AA)
cv2.line(self.frame, (rx,ry-r1), (rx,ry+r1), self.color, 1,
cv2.LINE_AA)
cv2.line(self.frame, (rx-r1,ry), (rx+r1,ry), self.color, 1,
cv2.LINE_AA)
lsx = lx + int(round(rudder * r1))
lsy = ly + r1 - int(round(2 * throttle * r1))
cv2.circle(self.frame, (lsx,lsy), r2, self.color, self.line_width,
cv2.LINE_AA)
rsx = rx + int(round(aileron * r1))
rsy = ry - int(round(elevator * r1))
cv2.circle(self.frame, (rsx,rsy), r2, self.color, self.line_width,
cv2.LINE_AA)
def draw_time(self):
h, w, d = self.frame.shape
label = '%.1f' % self.time
size = cv2.getTextSize(label, self.font, 0.7, self.line_width)
uv = (2, h - int(size[0][1]*0.5) + 2)
cv2.putText(self.frame, label, uv, self.font, 0.7,
self.color, self.line_width, cv2.LINE_AA)
def draw_test_index(self):
if not hasattr(self, 'excite_mode'):
return
if not self.excite_mode:
return
h, w, d = self.frame.shape
label = 'T%d' % self.test_index
size = cv2.getTextSize(label, self.font, 0.7, self.line_width)
uv = (w - int(size[0][0]) - 2, h - int(size[0][1]*0.5) + 2)
cv2.putText(self.frame, label, uv, self.font, 0.7,
self.color, self.line_width, cv2.LINE_AA)
# draw actual flight track in 3d
def draw_track(self):
uv_list = []
dist_list = []
for ned in self.ned_history:
dn = self.ned[0] - ned[0]
de = self.ned[1] - ned[1]
dd = self.ned[2] - ned[2]
dist = math.sqrt(dn*dn + de*de + dd*dd)
dist_list.append(dist)
if dist > 5:
uv = self.project_point([ned[0], ned[1], ned[2]])
else:
uv = None
uv_list.append(uv)
if len(uv_list) > 1:
for i in range(len(uv_list) - 1):
dist = dist_list[i]
if dist > 0.0:
size = int(round(200.0 / dist))
else:
size = 2
if size < 2: size = 2
uv1 = uv_list[i]
uv2 = uv_list[i+1]
if uv1 != None and uv2 != None:
if uv1[0] < -self.render_w * 0.25 and uv2[0] > self.render_w * 1.25:
pass
elif uv2[0] < -self.render_w * 0.25 and uv1[0] > self.render_w * 1.25:
pass
elif abs(uv1[0] - uv2[0]) > self.render_w * 1.5:
pass
elif uv1[1] < -self.render_h * 0.25 and uv2[1] > self.render_h * 1.25:
pass
elif uv2[1] < -self.render_h * 0.25 and uv1[1] > self.render_h * 1.25:
pass
elif abs(uv1[1] - uv2[1]) > self.render_h * 1.5:
pass
else:
cv2.line(self.frame, uv1, uv2, white, 1,
cv2.LINE_AA)
if uv1 != None:
cv2.circle(self.frame, uv1, size, white,
self.line_width, cv2.LINE_AA)
# draw externally provided point db features
def draw_features(self):
uv_list = []
for ned in self.features:
uv = self.project_point([ned[0], ned[1], ned[2]])
if uv != None:
uv_list.append(uv)
for uv in uv_list:
size = 2
if uv[0] > -self.render_w * 0.25 \
and uv[0] < self.render_w * 1.25 \
and uv[1] > -self.render_h * 0.25 \
and uv[1] < self.render_h * 1.25:
cv2.circle(self.frame, uv, size, white,
self.line_width, cv2.LINE_AA)
# draw a 3d reference grid in space
def draw_grid(self):
if len(self.grid) == 0:
# build the grid
h = 100
v = 75
for n in range(-5*h, 5*h+1, h):
for e in range(-5*h, 5*h+1, h):
for d in range(int(-self.ground_m) - 4*v, int(-self.ground_m) + 1, v):
self.grid.append( [n, e, d] )
uv_list = []
dist_list = []
for ned in self.grid:
dn = self.ned[0] - ned[0]
de = self.ned[1] - ned[1]
dd = self.ned[2] - ned[2]
dist = math.sqrt(dn*dn + de*de + dd*dd)
dist_list.append(dist)
uv = self.project_point( ned )
uv_list.append(uv)
for i in range(len(uv_list)):
dist = dist_list[i]
size = int(round(1000.0 / dist))
if size < 1: size = 1
uv = uv_list[i]
if uv != None:
cv2.circle(self.frame, uv, size, white, 1, cv2.LINE_AA)
# draw the conformal components of the hud (those that should
# 'stick' to the real world view.
def draw_conformal(self):
# things near infinity
self.draw_horizon()
self.draw_compass_points()
self.draw_astro()
# midrange things
self.draw_airports()
self.draw_track()
self.draw_features()
# cockpit things
self.draw_pitch_ladder(beta_rad=0.0)
self.draw_alpha_beta_marker()
self.draw_velocity_vector()
# draw the fixed indications (that always stay in the same place
# on the hud.) note: also draw speed/alt bugs here
def draw_fixed(self):
if self.airspeed_units == 'mps':
airspeed = self.airspeed_kt * kt2mps
ap_speed = self.ap_speed * kt2mps
else:
airspeed = self.airspeed_kt
ap_speed = self.ap_speed
self.draw_speed_tape(airspeed, ap_speed,
self.airspeed_units.capitalize())
if self.altitude_units == 'm':
altitude = self.altitude_m
ap_altitude = self.ap_altitude_ft * ft2m
else:
altitude = self.altitude_m * m2ft
ap_altitude = self.ap_altitude_ft
self.draw_altitude_tape(altitude, ap_altitude,
self.altitude_units.capitalize())
self.draw_sticks()
self.draw_time()
self.draw_test_index()
# draw autopilot symbology
def draw_ap(self):
if self.flight_mode == 'manual':
self.draw_nose()
else:
self.draw_vbars()
self.draw_heading_bug()
self.draw_bird()
self.draw_course()
def draw(self):
self.draw_conformal()
self.draw_fixed()
self.draw_ap()
| mit | -679,292,853,521,603,500 | 40.601719 | 115 | 0.489497 | false | 3.026053 | false | false | false |
jdemel/gnuradio | gr-utils/modtool/templates/gr-newmod/docs/doxygen/doxyxml/text.py | 3 | 1295 | #
# Copyright 2010 Free Software Foundation, Inc.
#
# This file was generated by gr_modtool, a tool from the GNU Radio framework
# This file is a part of gr-howto
#
# SPDX-License-Identifier: GPL-3.0-or-later
#
#
"""
Utilities for extracting text from generated classes.
"""
from __future__ import unicode_literals
def is_string(txt):
if isinstance(txt, str):
return True
try:
if isinstance(txt, str):
return True
except NameError:
pass
return False
def description(obj):
if obj is None:
return None
return description_bit(obj).strip()
def description_bit(obj):
if hasattr(obj, 'content'):
contents = [description_bit(item) for item in obj.content]
result = ''.join(contents)
elif hasattr(obj, 'content_'):
contents = [description_bit(item) for item in obj.content_]
result = ''.join(contents)
elif hasattr(obj, 'value'):
result = description_bit(obj.value)
elif is_string(obj):
return obj
else:
raise Exception('Expecting a string or something with content, content_ or value attribute')
# If this bit is a paragraph then add one some line breaks.
if hasattr(obj, 'name') and obj.name == 'para':
result += "\n\n"
return result
| gpl-3.0 | -4,949,053,946,127,237,000 | 27.152174 | 100 | 0.642471 | false | 3.912387 | false | false | false |
4rado/RepositoryForProject | Lib/site-packages/scipy/linalg/decomp_schur.py | 55 | 5250 | """Schur decomposition functions."""
import numpy
from numpy import asarray_chkfinite, single
# Local imports.
import misc
from misc import LinAlgError, _datacopied
from lapack import get_lapack_funcs
from decomp import eigvals
__all__ = ['schur', 'rsf2csf']
_double_precision = ['i','l','d']
def schur(a, output='real', lwork=None, overwrite_a=False):
"""Compute Schur decomposition of a matrix.
The Schur decomposition is
A = Z T Z^H
where Z is unitary and T is either upper-triangular, or for real
Schur decomposition (output='real'), quasi-upper triangular. In
the quasi-triangular form, 2x2 blocks describing complex-valued
eigenvalue pairs may extrude from the diagonal.
Parameters
----------
a : array, shape (M, M)
Matrix to decompose
output : {'real', 'complex'}
Construct the real or complex Schur decomposition (for real matrices).
lwork : integer
Work array size. If None or -1, it is automatically computed.
overwrite_a : boolean
Whether to overwrite data in a (may improve performance)
Returns
-------
T : array, shape (M, M)
Schur form of A. It is real-valued for the real Schur decomposition.
Z : array, shape (M, M)
An unitary Schur transformation matrix for A.
It is real-valued for the real Schur decomposition.
See also
--------
rsf2csf : Convert real Schur form to complex Schur form
"""
if not output in ['real','complex','r','c']:
raise ValueError("argument must be 'real', or 'complex'")
a1 = asarray_chkfinite(a)
if len(a1.shape) != 2 or (a1.shape[0] != a1.shape[1]):
raise ValueError('expected square matrix')
typ = a1.dtype.char
if output in ['complex','c'] and typ not in ['F','D']:
if typ in _double_precision:
a1 = a1.astype('D')
typ = 'D'
else:
a1 = a1.astype('F')
typ = 'F'
overwrite_a = overwrite_a or (_datacopied(a1, a))
gees, = get_lapack_funcs(('gees',), (a1,))
if lwork is None or lwork == -1:
# get optimal work array
result = gees(lambda x: None, a1, lwork=-1)
lwork = result[-2][0].real.astype(numpy.int)
result = gees(lambda x: None, a1, lwork=lwork, overwrite_a=overwrite_a)
info = result[-1]
if info < 0:
raise ValueError('illegal value in %d-th argument of internal gees'
% -info)
elif info > 0:
raise LinAlgError("Schur form not found. Possibly ill-conditioned.")
return result[0], result[-3]
eps = numpy.finfo(float).eps
feps = numpy.finfo(single).eps
_array_kind = {'b':0, 'h':0, 'B': 0, 'i':0, 'l': 0, 'f': 0, 'd': 0, 'F': 1, 'D': 1}
_array_precision = {'i': 1, 'l': 1, 'f': 0, 'd': 1, 'F': 0, 'D': 1}
_array_type = [['f', 'd'], ['F', 'D']]
def _commonType(*arrays):
kind = 0
precision = 0
for a in arrays:
t = a.dtype.char
kind = max(kind, _array_kind[t])
precision = max(precision, _array_precision[t])
return _array_type[kind][precision]
def _castCopy(type, *arrays):
cast_arrays = ()
for a in arrays:
if a.dtype.char == type:
cast_arrays = cast_arrays + (a.copy(),)
else:
cast_arrays = cast_arrays + (a.astype(type),)
if len(cast_arrays) == 1:
return cast_arrays[0]
else:
return cast_arrays
def rsf2csf(T, Z):
"""Convert real Schur form to complex Schur form.
Convert a quasi-diagonal real-valued Schur form to the upper triangular
complex-valued Schur form.
Parameters
----------
T : array, shape (M, M)
Real Schur form of the original matrix
Z : array, shape (M, M)
Schur transformation matrix
Returns
-------
T : array, shape (M, M)
Complex Schur form of the original matrix
Z : array, shape (M, M)
Schur transformation matrix corresponding to the complex form
See also
--------
schur : Schur decompose a matrix
"""
Z, T = map(asarray_chkfinite, (Z, T))
if len(Z.shape) != 2 or Z.shape[0] != Z.shape[1]:
raise ValueError("matrix must be square.")
if len(T.shape) != 2 or T.shape[0] != T.shape[1]:
raise ValueError("matrix must be square.")
if T.shape[0] != Z.shape[0]:
raise ValueError("matrices must be same dimension.")
N = T.shape[0]
arr = numpy.array
t = _commonType(Z, T, arr([3.0],'F'))
Z, T = _castCopy(t, Z, T)
conj = numpy.conj
dot = numpy.dot
r_ = numpy.r_
transp = numpy.transpose
for m in range(N-1, 0, -1):
if abs(T[m,m-1]) > eps*(abs(T[m-1,m-1]) + abs(T[m,m])):
k = slice(m-1, m+1)
mu = eigvals(T[k,k]) - T[m,m]
r = misc.norm([mu[0], T[m,m-1]])
c = mu[0] / r
s = T[m,m-1] / r
G = r_[arr([[conj(c), s]], dtype=t), arr([[-s, c]], dtype=t)]
Gc = conj(transp(G))
j = slice(m-1, N)
T[k,j] = dot(G, T[k,j])
i = slice(0, m+1)
T[i,k] = dot(T[i,k], Gc)
i = slice(0, N)
Z[i,k] = dot(Z[i,k], Gc)
T[m,m-1] = 0.0;
return T, Z
| gpl-3.0 | -8,418,565,791,650,039,000 | 30.437126 | 83 | 0.555619 | false | 3.252788 | false | false | false |
savi-dev/keystone | keystone/common/kvs.py | 4 | 1477 | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2012 OpenStack LLC
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from keystone import exception
class DictKvs(dict):
def get(self, key, default=None):
try:
return self[key]
except KeyError:
if default is not None:
return default
raise exception.NotFound(target=key)
def set(self, key, value):
if isinstance(value, dict):
self[key] = value.copy()
else:
self[key] = value[:]
def delete(self, key):
"""Deletes an item, returning True on success, False otherwise."""
try:
del self[key]
except KeyError:
raise exception.NotFound(target=key)
INMEMDB = DictKvs()
class Base(object):
def __init__(self, db=None):
if db is None:
db = INMEMDB
elif isinstance(db, dict):
db = DictKvs(db)
self.db = db
| apache-2.0 | 1,685,284,111,099,958,500 | 27.403846 | 75 | 0.631009 | false | 4.125698 | false | false | false |
zasdfgbnm/tensorflow | tensorflow/examples/tutorials/mnist/mnist_softmax_xla.py | 37 | 3631 | # Copyright 2015 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Simple MNIST classifier example with JIT XLA and timelines.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import argparse
import sys
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
from tensorflow.python.client import timeline
FLAGS = None
def main(_):
# Import data
mnist = input_data.read_data_sets(FLAGS.data_dir)
# Create the model
x = tf.placeholder(tf.float32, [None, 784])
w = tf.Variable(tf.zeros([784, 10]))
b = tf.Variable(tf.zeros([10]))
y = tf.matmul(x, w) + b
# Define loss and optimizer
y_ = tf.placeholder(tf.int64, [None])
# The raw formulation of cross-entropy,
#
# tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(tf.nn.softmax(y)),
# reduction_indices=[1]))
#
# can be numerically unstable.
#
# So here we use tf.losses.sparse_softmax_cross_entropy on the raw
# logit outputs of 'y', and then average across the batch.
cross_entropy = tf.losses.sparse_softmax_cross_entropy(labels=y_, logits=y)
train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy)
config = tf.ConfigProto()
jit_level = 0
if FLAGS.xla:
# Turns on XLA JIT compilation.
jit_level = tf.OptimizerOptions.ON_1
config.graph_options.optimizer_options.global_jit_level = jit_level
run_metadata = tf.RunMetadata()
sess = tf.Session(config=config)
tf.global_variables_initializer().run(session=sess)
# Train
train_loops = 1000
for i in range(train_loops):
batch_xs, batch_ys = mnist.train.next_batch(100)
# Create a timeline for the last loop and export to json to view with
# chrome://tracing/.
if i == train_loops - 1:
sess.run(train_step,
feed_dict={x: batch_xs,
y_: batch_ys},
options=tf.RunOptions(trace_level=tf.RunOptions.FULL_TRACE),
run_metadata=run_metadata)
trace = timeline.Timeline(step_stats=run_metadata.step_stats)
with open('timeline.ctf.json', 'w') as trace_file:
trace_file.write(trace.generate_chrome_trace_format())
else:
sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys})
# Test trained model
correct_prediction = tf.equal(tf.argmax(y, 1), y_)
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
print(sess.run(accuracy,
feed_dict={x: mnist.test.images,
y_: mnist.test.labels}))
sess.close()
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument(
'--data_dir',
type=str,
default='/tmp/tensorflow/mnist/input_data',
help='Directory for storing input data')
parser.add_argument(
'--xla', type=bool, default=True, help='Turn xla via JIT on')
FLAGS, unparsed = parser.parse_known_args()
tf.app.run(main=main, argv=[sys.argv[0]] + unparsed)
| apache-2.0 | 5,282,069,357,783,920,000 | 33.254717 | 80 | 0.657119 | false | 3.57734 | false | false | false |
alex/fabric | fabric/network.py | 8 | 24613 | """
Classes and subroutines dealing with network connections and related topics.
"""
from __future__ import with_statement
from functools import wraps
import getpass
import os
import re
import time
import socket
import sys
from StringIO import StringIO
from fabric.auth import get_password, set_password
from fabric.utils import abort, handle_prompt_abort, warn
from fabric.exceptions import NetworkError
try:
import warnings
warnings.simplefilter('ignore', DeprecationWarning)
import paramiko as ssh
except ImportError, e:
import traceback
traceback.print_exc()
msg = """
There was a problem importing our SSH library (see traceback above).
Please make sure all dependencies are installed and importable.
""".rstrip()
sys.stderr.write(msg + '\n')
sys.exit(1)
ipv6_regex = re.compile('^\[?(?P<host>[0-9A-Fa-f:]+)\]?(:(?P<port>\d+))?$')
def direct_tcpip(client, host, port):
return client.get_transport().open_channel(
'direct-tcpip',
(host, int(port)),
('', 0)
)
def is_key_load_error(e):
return (
e.__class__ is ssh.SSHException
and 'Unable to parse key file' in str(e)
)
def _tried_enough(tries):
from fabric.state import env
return tries >= env.connection_attempts
def get_gateway(host, port, cache, replace=False):
"""
Create and return a gateway socket, if one is needed.
This function checks ``env`` for gateway or proxy-command settings and
returns the necessary socket-like object for use by a final host
connection.
:param host:
Hostname of target server.
:param port:
Port to connect to on target server.
:param cache:
A ``HostConnectionCache`` object, in which gateway ``SSHClient``
objects are to be retrieved/cached.
:param replace:
Whether to forcibly replace a cached gateway client object.
:returns:
A ``socket.socket``-like object, or ``None`` if none was created.
"""
from fabric.state import env, output
sock = None
proxy_command = ssh_config().get('proxycommand', None)
if env.gateway:
gateway = normalize_to_string(env.gateway)
# ensure initial gateway connection
if replace or gateway not in cache:
if output.debug:
print "Creating new gateway connection to %r" % gateway
cache[gateway] = connect(*normalize(gateway) + (cache, False))
# now we should have an open gw connection and can ask it for a
# direct-tcpip channel to the real target. (bypass cache's own
# __getitem__ override to avoid hilarity - this is usually called
# within that method.)
sock = direct_tcpip(dict.__getitem__(cache, gateway), host, port)
elif proxy_command:
sock = ssh.ProxyCommand(proxy_command)
return sock
class HostConnectionCache(dict):
"""
Dict subclass allowing for caching of host connections/clients.
This subclass will intelligently create new client connections when keys
are requested, or return previously created connections instead.
It also handles creating new socket-like objects when required to implement
gateway connections and `ProxyCommand`, and handing them to the inner
connection methods.
Key values are the same as host specifiers throughout Fabric: optional
username + ``@``, mandatory hostname, optional ``:`` + port number.
Examples:
* ``example.com`` - typical Internet host address.
* ``firewall`` - atypical, but still legal, local host address.
* ``user@example.com`` - with specific username attached.
* ``bob@smith.org:222`` - with specific nonstandard port attached.
When the username is not given, ``env.user`` is used. ``env.user``
defaults to the currently running user at startup but may be overwritten by
user code or by specifying a command-line flag.
Note that differing explicit usernames for the same hostname will result in
multiple client connections being made. For example, specifying
``user1@example.com`` will create a connection to ``example.com``, logged
in as ``user1``; later specifying ``user2@example.com`` will create a new,
2nd connection as ``user2``.
The same applies to ports: specifying two different ports will result in
two different connections to the same host being made. If no port is given,
22 is assumed, so ``example.com`` is equivalent to ``example.com:22``.
"""
def connect(self, key):
"""
Force a new connection to ``key`` host string.
"""
user, host, port = normalize(key)
key = normalize_to_string(key)
self[key] = connect(user, host, port, cache=self)
def __getitem__(self, key):
"""
Autoconnect + return connection object
"""
key = normalize_to_string(key)
if key not in self:
self.connect(key)
return dict.__getitem__(self, key)
#
# Dict overrides that normalize input keys
#
def __setitem__(self, key, value):
return dict.__setitem__(self, normalize_to_string(key), value)
def __delitem__(self, key):
return dict.__delitem__(self, normalize_to_string(key))
def __contains__(self, key):
return dict.__contains__(self, normalize_to_string(key))
def ssh_config(host_string=None):
"""
Return ssh configuration dict for current env.host_string host value.
Memoizes the loaded SSH config file, but not the specific per-host results.
This function performs the necessary "is SSH config enabled?" checks and
will simply return an empty dict if not. If SSH config *is* enabled and the
value of env.ssh_config_path is not a valid file, it will abort.
May give an explicit host string as ``host_string``.
"""
from fabric.state import env
dummy = {}
if not env.use_ssh_config:
return dummy
if '_ssh_config' not in env:
try:
conf = ssh.SSHConfig()
path = os.path.expanduser(env.ssh_config_path)
with open(path) as fd:
conf.parse(fd)
env._ssh_config = conf
except IOError:
warn("Unable to load SSH config file '%s'" % path)
return dummy
host = parse_host_string(host_string or env.host_string)['host']
return env._ssh_config.lookup(host)
def key_filenames():
"""
Returns list of SSH key filenames for the current env.host_string.
Takes into account ssh_config and env.key_filename, including normalization
to a list. Also performs ``os.path.expanduser`` expansion on any key
filenames.
"""
from fabric.state import env
keys = env.key_filename
# For ease of use, coerce stringish key filename into list
if isinstance(env.key_filename, basestring) or env.key_filename is None:
keys = [keys]
# Strip out any empty strings (such as the default value...meh)
keys = filter(bool, keys)
# Honor SSH config
conf = ssh_config()
if 'identityfile' in conf:
# Assume a list here as we require Paramiko 1.10+
keys.extend(conf['identityfile'])
return map(os.path.expanduser, keys)
def key_from_env(passphrase=None):
"""
Returns a paramiko-ready key from a text string of a private key
"""
from fabric.state import env, output
if 'key' in env:
if output.debug:
# NOTE: this may not be the most secure thing; OTOH anybody running
# the process must by definition have access to the key value,
# so only serious problem is if they're logging the output.
sys.stderr.write("Trying to honor in-memory key %r\n" % env.key)
for pkey_class in (ssh.rsakey.RSAKey, ssh.dsskey.DSSKey):
if output.debug:
sys.stderr.write("Trying to load it as %s\n" % pkey_class)
try:
return pkey_class.from_private_key(StringIO(env.key), passphrase)
except Exception, e:
# File is valid key, but is encrypted: raise it, this will
# cause cxn loop to prompt for passphrase & retry
if 'Private key file is encrypted' in e:
raise
# Otherwise, it probably means it wasn't a valid key of this
# type, so try the next one.
else:
pass
def parse_host_string(host_string):
# Split host_string to user (optional) and host/port
user_hostport = host_string.rsplit('@', 1)
hostport = user_hostport.pop()
user = user_hostport[0] if user_hostport and user_hostport[0] else None
# Split host/port string to host and optional port
# For IPv6 addresses square brackets are mandatory for host/port separation
if hostport.count(':') > 1:
# Looks like IPv6 address
r = ipv6_regex.match(hostport).groupdict()
host = r['host'] or None
port = r['port'] or None
else:
# Hostname or IPv4 address
host_port = hostport.rsplit(':', 1)
host = host_port.pop(0) or None
port = host_port[0] if host_port and host_port[0] else None
return {'user': user, 'host': host, 'port': port}
def normalize(host_string, omit_port=False):
"""
Normalizes a given host string, returning explicit host, user, port.
If ``omit_port`` is given and is True, only the host and user are returned.
This function will process SSH config files if Fabric is configured to do
so, and will use them to fill in some default values or swap in hostname
aliases.
"""
from fabric.state import env
# Gracefully handle "empty" input by returning empty output
if not host_string:
return ('', '') if omit_port else ('', '', '')
# Parse host string (need this early on to look up host-specific ssh_config
# values)
r = parse_host_string(host_string)
host = r['host']
# Env values (using defaults if somehow earlier defaults were replaced with
# empty values)
user = env.user or env.local_user
port = env.port or env.default_port
# SSH config data
conf = ssh_config(host_string)
# Only use ssh_config values if the env value appears unmodified from
# the true defaults. If the user has tweaked them, that new value
# takes precedence.
if user == env.local_user and 'user' in conf:
user = conf['user']
if port == env.default_port and 'port' in conf:
port = conf['port']
# Also override host if needed
if 'hostname' in conf:
host = conf['hostname']
# Merge explicit user/port values with the env/ssh_config derived ones
# (Host is already done at this point.)
user = r['user'] or user
port = r['port'] or port
if omit_port:
return user, host
return user, host, port
def to_dict(host_string):
user, host, port = normalize(host_string)
return {
'user': user, 'host': host, 'port': port, 'host_string': host_string
}
def from_dict(arg):
return join_host_strings(arg['user'], arg['host'], arg['port'])
def denormalize(host_string):
"""
Strips out default values for the given host string.
If the user part is the default user, it is removed;
if the port is port 22, it also is removed.
"""
from fabric.state import env
r = parse_host_string(host_string)
user = ''
if r['user'] is not None and r['user'] != env.user:
user = r['user'] + '@'
port = ''
if r['port'] is not None and r['port'] != '22':
port = ':' + r['port']
host = r['host']
host = '[%s]' % host if port and host.count(':') > 1 else host
return user + host + port
def join_host_strings(user, host, port=None):
"""
Turns user/host/port strings into ``user@host:port`` combined string.
This function is not responsible for handling missing user/port strings;
for that, see the ``normalize`` function.
If ``host`` looks like IPv6 address, it will be enclosed in square brackets
If ``port`` is omitted, the returned string will be of the form
``user@host``.
"""
if port:
# Square brackets are necessary for IPv6 host/port separation
template = "%s@[%s]:%s" if host.count(':') > 1 else "%s@%s:%s"
return template % (user, host, port)
else:
return "%s@%s" % (user, host)
def normalize_to_string(host_string):
"""
normalize() returns a tuple; this returns another valid host string.
"""
return join_host_strings(*normalize(host_string))
def connect(user, host, port, cache, seek_gateway=True):
"""
Create and return a new SSHClient instance connected to given host.
:param user: Username to connect as.
:param host: Network hostname.
:param port: SSH daemon port.
:param cache:
A ``HostConnectionCache`` instance used to cache/store gateway hosts
when gatewaying is enabled.
:param seek_gateway:
Whether to try setting up a gateway socket for this connection. Used so
the actual gateway connection can prevent recursion.
"""
from state import env, output
#
# Initialization
#
# Init client
client = ssh.SSHClient()
# Load system hosts file (e.g. /etc/ssh/ssh_known_hosts)
known_hosts = env.get('system_known_hosts')
if known_hosts:
client.load_system_host_keys(known_hosts)
# Load known host keys (e.g. ~/.ssh/known_hosts) unless user says not to.
if not env.disable_known_hosts:
client.load_system_host_keys()
# Unless user specified not to, accept/add new, unknown host keys
if not env.reject_unknown_hosts:
client.set_missing_host_key_policy(ssh.AutoAddPolicy())
#
# Connection attempt loop
#
# Initialize loop variables
connected = False
password = get_password(user, host, port)
tries = 0
sock = None
# Loop until successful connect (keep prompting for new password)
while not connected:
# Attempt connection
try:
tries += 1
# (Re)connect gateway socket, if needed.
# Nuke cached client object if not on initial try.
if seek_gateway:
sock = get_gateway(host, port, cache, replace=tries > 0)
# Ready to connect
client.connect(
hostname=host,
port=int(port),
username=user,
password=password,
pkey=key_from_env(password),
key_filename=key_filenames(),
timeout=env.timeout,
allow_agent=not env.no_agent,
look_for_keys=not env.no_keys,
sock=sock
)
connected = True
# set a keepalive if desired
if env.keepalive:
client.get_transport().set_keepalive(env.keepalive)
return client
# BadHostKeyException corresponds to key mismatch, i.e. what on the
# command line results in the big banner error about man-in-the-middle
# attacks.
except ssh.BadHostKeyException, e:
raise NetworkError("Host key for %s did not match pre-existing key! Server's key was changed recently, or possible man-in-the-middle attack." % host, e)
# Prompt for new password to try on auth failure
except (
ssh.AuthenticationException,
ssh.PasswordRequiredException,
ssh.SSHException
), e:
msg = str(e)
# If we get SSHExceptionError and the exception message indicates
# SSH protocol banner read failures, assume it's caused by the
# server load and try again.
if e.__class__ is ssh.SSHException \
and msg == 'Error reading SSH protocol banner':
if _tried_enough(tries):
raise NetworkError(msg, e)
continue
# For whatever reason, empty password + no ssh key or agent
# results in an SSHException instead of an
# AuthenticationException. Since it's difficult to do
# otherwise, we must assume empty password + SSHException ==
# auth exception.
#
# Conversely: if we get SSHException and there
# *was* a password -- it is probably something non auth
# related, and should be sent upwards. (This is not true if the
# exception message does indicate key parse problems.)
#
# This also holds true for rejected/unknown host keys: we have to
# guess based on other heuristics.
if e.__class__ is ssh.SSHException \
and (password or msg.startswith('Unknown server')) \
and not is_key_load_error(e):
raise NetworkError(msg, e)
# Otherwise, assume an auth exception, and prompt for new/better
# password.
# Paramiko doesn't handle prompting for locked private
# keys (i.e. keys with a passphrase and not loaded into an agent)
# so we have to detect this and tweak our prompt slightly.
# (Otherwise, however, the logic flow is the same, because
# ssh's connect() method overrides the password argument to be
# either the login password OR the private key passphrase. Meh.)
#
# NOTE: This will come up if you normally use a
# passphrase-protected private key with ssh-agent, and enter an
# incorrect remote username, because ssh.connect:
# * Tries the agent first, which will fail as you gave the wrong
# username, so obviously any loaded keys aren't gonna work for a
# nonexistent remote account;
# * Then tries the on-disk key file, which is passphrased;
# * Realizes there's no password to try unlocking that key with,
# because you didn't enter a password, because you're using
# ssh-agent;
# * In this condition (trying a key file, password is None)
# ssh raises PasswordRequiredException.
text = None
if e.__class__ is ssh.PasswordRequiredException \
or is_key_load_error(e):
# NOTE: we can't easily say WHICH key's passphrase is needed,
# because ssh doesn't provide us with that info, and
# env.key_filename may be a list of keys, so we can't know
# which one raised the exception. Best not to try.
prompt = "[%s] Passphrase for private key"
text = prompt % env.host_string
password = prompt_for_password(text)
# Update env.password, env.passwords if empty
set_password(user, host, port, password)
# Ctrl-D / Ctrl-C for exit
except (EOFError, TypeError):
# Print a newline (in case user was sitting at prompt)
print('')
sys.exit(0)
# Handle DNS error / name lookup failure
except socket.gaierror, e:
raise NetworkError('Name lookup failed for %s' % host, e)
# Handle timeouts and retries, including generic errors
# NOTE: In 2.6, socket.error subclasses IOError
except socket.error, e:
not_timeout = type(e) is not socket.timeout
giving_up = _tried_enough(tries)
# Baseline error msg for when debug is off
msg = "Timed out trying to connect to %s" % host
# Expanded for debug on
err = msg + " (attempt %s of %s)" % (tries, env.connection_attempts)
if giving_up:
err += ", giving up"
err += ")"
# Debuggin'
if output.debug:
sys.stderr.write(err + '\n')
# Having said our piece, try again
if not giving_up:
# Sleep if it wasn't a timeout, so we still get timeout-like
# behavior
if not_timeout:
time.sleep(env.timeout)
continue
# Override eror msg if we were retrying other errors
if not_timeout:
msg = "Low level socket error connecting to host %s on port %s: %s" % (
host, port, e[1]
)
# Here, all attempts failed. Tweak error msg to show # tries.
# TODO: find good humanization module, jeez
s = "s" if env.connection_attempts > 1 else ""
msg += " (tried %s time%s)" % (env.connection_attempts, s)
raise NetworkError(msg, e)
# Ensure that if we terminated without connecting and we were given an
# explicit socket, close it out.
finally:
if not connected and sock is not None:
sock.close()
def _password_prompt(prompt, stream):
# NOTE: Using encode-to-ascii to prevent (Windows, at least) getpass from
# choking if given Unicode.
return getpass.getpass(prompt.encode('ascii', 'ignore'), stream)
def prompt_for_password(prompt=None, no_colon=False, stream=None):
"""
Prompts for and returns a new password if required; otherwise, returns
None.
A trailing colon is appended unless ``no_colon`` is True.
If the user supplies an empty password, the user will be re-prompted until
they enter a non-empty password.
``prompt_for_password`` autogenerates the user prompt based on the current
host being connected to. To override this, specify a string value for
``prompt``.
``stream`` is the stream the prompt will be printed to; if not given,
defaults to ``sys.stderr``.
"""
from fabric.state import env
handle_prompt_abort("a connection or sudo password")
stream = stream or sys.stderr
# Construct prompt
default = "[%s] Login password for '%s'" % (env.host_string, env.user)
password_prompt = prompt if (prompt is not None) else default
if not no_colon:
password_prompt += ": "
# Get new password value
new_password = _password_prompt(password_prompt, stream)
# Otherwise, loop until user gives us a non-empty password (to prevent
# returning the empty string, and to avoid unnecessary network overhead.)
while not new_password:
print("Sorry, you can't enter an empty password. Please try again.")
new_password = _password_prompt(password_prompt, stream)
return new_password
def needs_host(func):
"""
Prompt user for value of ``env.host_string`` when ``env.host_string`` is
empty.
This decorator is basically a safety net for silly users who forgot to
specify the host/host list in one way or another. It should be used to wrap
operations which require a network connection.
Due to how we execute commands per-host in ``main()``, it's not possible to
specify multiple hosts at this point in time, so only a single host will be
prompted for.
Because this decorator sets ``env.host_string``, it will prompt once (and
only once) per command. As ``main()`` clears ``env.host_string`` between
commands, this decorator will also end up prompting the user once per
command (in the case where multiple commands have no hosts set, of course.)
"""
from fabric.state import env
@wraps(func)
def host_prompting_wrapper(*args, **kwargs):
while not env.get('host_string', False):
handle_prompt_abort("the target host connection string")
host_string = raw_input("No hosts found. Please specify (single)"
" host string for connection: ")
env.update(to_dict(host_string))
return func(*args, **kwargs)
host_prompting_wrapper.undecorated = func
return host_prompting_wrapper
def disconnect_all():
"""
Disconnect from all currently connected servers.
Used at the end of ``fab``'s main loop, and also intended for use by
library users.
"""
from fabric.state import connections, output
# Explicitly disconnect from all servers
for key in connections.keys():
if output.status:
# Here we can't use the py3k print(x, end=" ")
# because 2.5 backwards compatibility
sys.stdout.write("Disconnecting from %s... " % denormalize(key))
connections[key].close()
del connections[key]
if output.status:
sys.stdout.write("done.\n")
| bsd-2-clause | -4,666,307,345,220,745,000 | 36.236006 | 164 | 0.621826 | false | 4.222508 | true | false | false |
adrianholovaty/django | django/contrib/gis/admin/widgets.py | 10 | 4344 | from django.forms.widgets import Textarea
from django.template import loader, Context
from django.templatetags.static import static
from django.utils import translation
from django.contrib.gis.gdal import OGRException
from django.contrib.gis.geos import GEOSGeometry, GEOSException
# Creating a template context that contains Django settings
# values needed by admin map templates.
geo_context = Context({'LANGUAGE_BIDI' : translation.get_language_bidi()})
class OpenLayersWidget(Textarea):
"""
Renders an OpenLayers map using the WKT of the geometry.
"""
def render(self, name, value, attrs=None):
# Update the template parameters with any attributes passed in.
if attrs: self.params.update(attrs)
# Defaulting the WKT value to a blank string -- this
# will be tested in the JavaScript and the appropriate
# interface will be constructed.
self.params['wkt'] = ''
# If a string reaches here (via a validation error on another
# field) then just reconstruct the Geometry.
if isinstance(value, basestring):
try:
value = GEOSGeometry(value)
except (GEOSException, ValueError):
value = None
if value and value.geom_type.upper() != self.geom_type:
value = None
# Constructing the dictionary of the map options.
self.params['map_options'] = self.map_options()
# Constructing the JavaScript module name using the name of
# the GeometryField (passed in via the `attrs` keyword).
# Use the 'name' attr for the field name (rather than 'field')
self.params['name'] = name
# note: we must switch out dashes for underscores since js
# functions are created using the module variable
js_safe_name = self.params['name'].replace('-','_')
self.params['module'] = 'geodjango_%s' % js_safe_name
if value:
# Transforming the geometry to the projection used on the
# OpenLayers map.
srid = self.params['srid']
if value.srid != srid:
try:
ogr = value.ogr
ogr.transform(srid)
wkt = ogr.wkt
except OGRException:
wkt = ''
else:
wkt = value.wkt
# Setting the parameter WKT with that of the transformed
# geometry.
self.params['wkt'] = wkt
return loader.render_to_string(self.template, self.params,
context_instance=geo_context)
def map_options(self):
"Builds the map options hash for the OpenLayers template."
# JavaScript construction utilities for the Bounds and Projection.
def ol_bounds(extent):
return 'new OpenLayers.Bounds(%s)' % str(extent)
def ol_projection(srid):
return 'new OpenLayers.Projection("EPSG:%s")' % srid
# An array of the parameter name, the name of their OpenLayers
# counterpart, and the type of variable they are.
map_types = [('srid', 'projection', 'srid'),
('display_srid', 'displayProjection', 'srid'),
('units', 'units', str),
('max_resolution', 'maxResolution', float),
('max_extent', 'maxExtent', 'bounds'),
('num_zoom', 'numZoomLevels', int),
('max_zoom', 'maxZoomLevels', int),
('min_zoom', 'minZoomLevel', int),
]
# Building the map options hash.
map_options = {}
for param_name, js_name, option_type in map_types:
if self.params.get(param_name, False):
if option_type == 'srid':
value = ol_projection(self.params[param_name])
elif option_type == 'bounds':
value = ol_bounds(self.params[param_name])
elif option_type in (float, int):
value = self.params[param_name]
elif option_type in (str,):
value = '"%s"' % self.params[param_name]
else:
raise TypeError
map_options[js_name] = value
return map_options
| bsd-3-clause | 8,129,332,532,780,420,000 | 39.981132 | 74 | 0.5686 | false | 4.636073 | false | false | false |
vikatory/kbengine | kbe/src/lib/python/Lib/encodings/cp863.py | 272 | 34252 | """ Python Character Mapping Codec generated from 'VENDORS/MICSFT/PC/CP863.TXT' with gencodec.py.
"""#"
import codecs
### Codec APIs
class Codec(codecs.Codec):
def encode(self,input,errors='strict'):
return codecs.charmap_encode(input,errors,encoding_map)
def decode(self,input,errors='strict'):
return codecs.charmap_decode(input,errors,decoding_table)
class IncrementalEncoder(codecs.IncrementalEncoder):
def encode(self, input, final=False):
return codecs.charmap_encode(input,self.errors,encoding_map)[0]
class IncrementalDecoder(codecs.IncrementalDecoder):
def decode(self, input, final=False):
return codecs.charmap_decode(input,self.errors,decoding_table)[0]
class StreamWriter(Codec,codecs.StreamWriter):
pass
class StreamReader(Codec,codecs.StreamReader):
pass
### encodings module API
def getregentry():
return codecs.CodecInfo(
name='cp863',
encode=Codec().encode,
decode=Codec().decode,
incrementalencoder=IncrementalEncoder,
incrementaldecoder=IncrementalDecoder,
streamreader=StreamReader,
streamwriter=StreamWriter,
)
### Decoding Map
decoding_map = codecs.make_identity_dict(range(256))
decoding_map.update({
0x0080: 0x00c7, # LATIN CAPITAL LETTER C WITH CEDILLA
0x0081: 0x00fc, # LATIN SMALL LETTER U WITH DIAERESIS
0x0082: 0x00e9, # LATIN SMALL LETTER E WITH ACUTE
0x0083: 0x00e2, # LATIN SMALL LETTER A WITH CIRCUMFLEX
0x0084: 0x00c2, # LATIN CAPITAL LETTER A WITH CIRCUMFLEX
0x0085: 0x00e0, # LATIN SMALL LETTER A WITH GRAVE
0x0086: 0x00b6, # PILCROW SIGN
0x0087: 0x00e7, # LATIN SMALL LETTER C WITH CEDILLA
0x0088: 0x00ea, # LATIN SMALL LETTER E WITH CIRCUMFLEX
0x0089: 0x00eb, # LATIN SMALL LETTER E WITH DIAERESIS
0x008a: 0x00e8, # LATIN SMALL LETTER E WITH GRAVE
0x008b: 0x00ef, # LATIN SMALL LETTER I WITH DIAERESIS
0x008c: 0x00ee, # LATIN SMALL LETTER I WITH CIRCUMFLEX
0x008d: 0x2017, # DOUBLE LOW LINE
0x008e: 0x00c0, # LATIN CAPITAL LETTER A WITH GRAVE
0x008f: 0x00a7, # SECTION SIGN
0x0090: 0x00c9, # LATIN CAPITAL LETTER E WITH ACUTE
0x0091: 0x00c8, # LATIN CAPITAL LETTER E WITH GRAVE
0x0092: 0x00ca, # LATIN CAPITAL LETTER E WITH CIRCUMFLEX
0x0093: 0x00f4, # LATIN SMALL LETTER O WITH CIRCUMFLEX
0x0094: 0x00cb, # LATIN CAPITAL LETTER E WITH DIAERESIS
0x0095: 0x00cf, # LATIN CAPITAL LETTER I WITH DIAERESIS
0x0096: 0x00fb, # LATIN SMALL LETTER U WITH CIRCUMFLEX
0x0097: 0x00f9, # LATIN SMALL LETTER U WITH GRAVE
0x0098: 0x00a4, # CURRENCY SIGN
0x0099: 0x00d4, # LATIN CAPITAL LETTER O WITH CIRCUMFLEX
0x009a: 0x00dc, # LATIN CAPITAL LETTER U WITH DIAERESIS
0x009b: 0x00a2, # CENT SIGN
0x009c: 0x00a3, # POUND SIGN
0x009d: 0x00d9, # LATIN CAPITAL LETTER U WITH GRAVE
0x009e: 0x00db, # LATIN CAPITAL LETTER U WITH CIRCUMFLEX
0x009f: 0x0192, # LATIN SMALL LETTER F WITH HOOK
0x00a0: 0x00a6, # BROKEN BAR
0x00a1: 0x00b4, # ACUTE ACCENT
0x00a2: 0x00f3, # LATIN SMALL LETTER O WITH ACUTE
0x00a3: 0x00fa, # LATIN SMALL LETTER U WITH ACUTE
0x00a4: 0x00a8, # DIAERESIS
0x00a5: 0x00b8, # CEDILLA
0x00a6: 0x00b3, # SUPERSCRIPT THREE
0x00a7: 0x00af, # MACRON
0x00a8: 0x00ce, # LATIN CAPITAL LETTER I WITH CIRCUMFLEX
0x00a9: 0x2310, # REVERSED NOT SIGN
0x00aa: 0x00ac, # NOT SIGN
0x00ab: 0x00bd, # VULGAR FRACTION ONE HALF
0x00ac: 0x00bc, # VULGAR FRACTION ONE QUARTER
0x00ad: 0x00be, # VULGAR FRACTION THREE QUARTERS
0x00ae: 0x00ab, # LEFT-POINTING DOUBLE ANGLE QUOTATION MARK
0x00af: 0x00bb, # RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK
0x00b0: 0x2591, # LIGHT SHADE
0x00b1: 0x2592, # MEDIUM SHADE
0x00b2: 0x2593, # DARK SHADE
0x00b3: 0x2502, # BOX DRAWINGS LIGHT VERTICAL
0x00b4: 0x2524, # BOX DRAWINGS LIGHT VERTICAL AND LEFT
0x00b5: 0x2561, # BOX DRAWINGS VERTICAL SINGLE AND LEFT DOUBLE
0x00b6: 0x2562, # BOX DRAWINGS VERTICAL DOUBLE AND LEFT SINGLE
0x00b7: 0x2556, # BOX DRAWINGS DOWN DOUBLE AND LEFT SINGLE
0x00b8: 0x2555, # BOX DRAWINGS DOWN SINGLE AND LEFT DOUBLE
0x00b9: 0x2563, # BOX DRAWINGS DOUBLE VERTICAL AND LEFT
0x00ba: 0x2551, # BOX DRAWINGS DOUBLE VERTICAL
0x00bb: 0x2557, # BOX DRAWINGS DOUBLE DOWN AND LEFT
0x00bc: 0x255d, # BOX DRAWINGS DOUBLE UP AND LEFT
0x00bd: 0x255c, # BOX DRAWINGS UP DOUBLE AND LEFT SINGLE
0x00be: 0x255b, # BOX DRAWINGS UP SINGLE AND LEFT DOUBLE
0x00bf: 0x2510, # BOX DRAWINGS LIGHT DOWN AND LEFT
0x00c0: 0x2514, # BOX DRAWINGS LIGHT UP AND RIGHT
0x00c1: 0x2534, # BOX DRAWINGS LIGHT UP AND HORIZONTAL
0x00c2: 0x252c, # BOX DRAWINGS LIGHT DOWN AND HORIZONTAL
0x00c3: 0x251c, # BOX DRAWINGS LIGHT VERTICAL AND RIGHT
0x00c4: 0x2500, # BOX DRAWINGS LIGHT HORIZONTAL
0x00c5: 0x253c, # BOX DRAWINGS LIGHT VERTICAL AND HORIZONTAL
0x00c6: 0x255e, # BOX DRAWINGS VERTICAL SINGLE AND RIGHT DOUBLE
0x00c7: 0x255f, # BOX DRAWINGS VERTICAL DOUBLE AND RIGHT SINGLE
0x00c8: 0x255a, # BOX DRAWINGS DOUBLE UP AND RIGHT
0x00c9: 0x2554, # BOX DRAWINGS DOUBLE DOWN AND RIGHT
0x00ca: 0x2569, # BOX DRAWINGS DOUBLE UP AND HORIZONTAL
0x00cb: 0x2566, # BOX DRAWINGS DOUBLE DOWN AND HORIZONTAL
0x00cc: 0x2560, # BOX DRAWINGS DOUBLE VERTICAL AND RIGHT
0x00cd: 0x2550, # BOX DRAWINGS DOUBLE HORIZONTAL
0x00ce: 0x256c, # BOX DRAWINGS DOUBLE VERTICAL AND HORIZONTAL
0x00cf: 0x2567, # BOX DRAWINGS UP SINGLE AND HORIZONTAL DOUBLE
0x00d0: 0x2568, # BOX DRAWINGS UP DOUBLE AND HORIZONTAL SINGLE
0x00d1: 0x2564, # BOX DRAWINGS DOWN SINGLE AND HORIZONTAL DOUBLE
0x00d2: 0x2565, # BOX DRAWINGS DOWN DOUBLE AND HORIZONTAL SINGLE
0x00d3: 0x2559, # BOX DRAWINGS UP DOUBLE AND RIGHT SINGLE
0x00d4: 0x2558, # BOX DRAWINGS UP SINGLE AND RIGHT DOUBLE
0x00d5: 0x2552, # BOX DRAWINGS DOWN SINGLE AND RIGHT DOUBLE
0x00d6: 0x2553, # BOX DRAWINGS DOWN DOUBLE AND RIGHT SINGLE
0x00d7: 0x256b, # BOX DRAWINGS VERTICAL DOUBLE AND HORIZONTAL SINGLE
0x00d8: 0x256a, # BOX DRAWINGS VERTICAL SINGLE AND HORIZONTAL DOUBLE
0x00d9: 0x2518, # BOX DRAWINGS LIGHT UP AND LEFT
0x00da: 0x250c, # BOX DRAWINGS LIGHT DOWN AND RIGHT
0x00db: 0x2588, # FULL BLOCK
0x00dc: 0x2584, # LOWER HALF BLOCK
0x00dd: 0x258c, # LEFT HALF BLOCK
0x00de: 0x2590, # RIGHT HALF BLOCK
0x00df: 0x2580, # UPPER HALF BLOCK
0x00e0: 0x03b1, # GREEK SMALL LETTER ALPHA
0x00e1: 0x00df, # LATIN SMALL LETTER SHARP S
0x00e2: 0x0393, # GREEK CAPITAL LETTER GAMMA
0x00e3: 0x03c0, # GREEK SMALL LETTER PI
0x00e4: 0x03a3, # GREEK CAPITAL LETTER SIGMA
0x00e5: 0x03c3, # GREEK SMALL LETTER SIGMA
0x00e6: 0x00b5, # MICRO SIGN
0x00e7: 0x03c4, # GREEK SMALL LETTER TAU
0x00e8: 0x03a6, # GREEK CAPITAL LETTER PHI
0x00e9: 0x0398, # GREEK CAPITAL LETTER THETA
0x00ea: 0x03a9, # GREEK CAPITAL LETTER OMEGA
0x00eb: 0x03b4, # GREEK SMALL LETTER DELTA
0x00ec: 0x221e, # INFINITY
0x00ed: 0x03c6, # GREEK SMALL LETTER PHI
0x00ee: 0x03b5, # GREEK SMALL LETTER EPSILON
0x00ef: 0x2229, # INTERSECTION
0x00f0: 0x2261, # IDENTICAL TO
0x00f1: 0x00b1, # PLUS-MINUS SIGN
0x00f2: 0x2265, # GREATER-THAN OR EQUAL TO
0x00f3: 0x2264, # LESS-THAN OR EQUAL TO
0x00f4: 0x2320, # TOP HALF INTEGRAL
0x00f5: 0x2321, # BOTTOM HALF INTEGRAL
0x00f6: 0x00f7, # DIVISION SIGN
0x00f7: 0x2248, # ALMOST EQUAL TO
0x00f8: 0x00b0, # DEGREE SIGN
0x00f9: 0x2219, # BULLET OPERATOR
0x00fa: 0x00b7, # MIDDLE DOT
0x00fb: 0x221a, # SQUARE ROOT
0x00fc: 0x207f, # SUPERSCRIPT LATIN SMALL LETTER N
0x00fd: 0x00b2, # SUPERSCRIPT TWO
0x00fe: 0x25a0, # BLACK SQUARE
0x00ff: 0x00a0, # NO-BREAK SPACE
})
### Decoding Table
decoding_table = (
'\x00' # 0x0000 -> NULL
'\x01' # 0x0001 -> START OF HEADING
'\x02' # 0x0002 -> START OF TEXT
'\x03' # 0x0003 -> END OF TEXT
'\x04' # 0x0004 -> END OF TRANSMISSION
'\x05' # 0x0005 -> ENQUIRY
'\x06' # 0x0006 -> ACKNOWLEDGE
'\x07' # 0x0007 -> BELL
'\x08' # 0x0008 -> BACKSPACE
'\t' # 0x0009 -> HORIZONTAL TABULATION
'\n' # 0x000a -> LINE FEED
'\x0b' # 0x000b -> VERTICAL TABULATION
'\x0c' # 0x000c -> FORM FEED
'\r' # 0x000d -> CARRIAGE RETURN
'\x0e' # 0x000e -> SHIFT OUT
'\x0f' # 0x000f -> SHIFT IN
'\x10' # 0x0010 -> DATA LINK ESCAPE
'\x11' # 0x0011 -> DEVICE CONTROL ONE
'\x12' # 0x0012 -> DEVICE CONTROL TWO
'\x13' # 0x0013 -> DEVICE CONTROL THREE
'\x14' # 0x0014 -> DEVICE CONTROL FOUR
'\x15' # 0x0015 -> NEGATIVE ACKNOWLEDGE
'\x16' # 0x0016 -> SYNCHRONOUS IDLE
'\x17' # 0x0017 -> END OF TRANSMISSION BLOCK
'\x18' # 0x0018 -> CANCEL
'\x19' # 0x0019 -> END OF MEDIUM
'\x1a' # 0x001a -> SUBSTITUTE
'\x1b' # 0x001b -> ESCAPE
'\x1c' # 0x001c -> FILE SEPARATOR
'\x1d' # 0x001d -> GROUP SEPARATOR
'\x1e' # 0x001e -> RECORD SEPARATOR
'\x1f' # 0x001f -> UNIT SEPARATOR
' ' # 0x0020 -> SPACE
'!' # 0x0021 -> EXCLAMATION MARK
'"' # 0x0022 -> QUOTATION MARK
'#' # 0x0023 -> NUMBER SIGN
'$' # 0x0024 -> DOLLAR SIGN
'%' # 0x0025 -> PERCENT SIGN
'&' # 0x0026 -> AMPERSAND
"'" # 0x0027 -> APOSTROPHE
'(' # 0x0028 -> LEFT PARENTHESIS
')' # 0x0029 -> RIGHT PARENTHESIS
'*' # 0x002a -> ASTERISK
'+' # 0x002b -> PLUS SIGN
',' # 0x002c -> COMMA
'-' # 0x002d -> HYPHEN-MINUS
'.' # 0x002e -> FULL STOP
'/' # 0x002f -> SOLIDUS
'0' # 0x0030 -> DIGIT ZERO
'1' # 0x0031 -> DIGIT ONE
'2' # 0x0032 -> DIGIT TWO
'3' # 0x0033 -> DIGIT THREE
'4' # 0x0034 -> DIGIT FOUR
'5' # 0x0035 -> DIGIT FIVE
'6' # 0x0036 -> DIGIT SIX
'7' # 0x0037 -> DIGIT SEVEN
'8' # 0x0038 -> DIGIT EIGHT
'9' # 0x0039 -> DIGIT NINE
':' # 0x003a -> COLON
';' # 0x003b -> SEMICOLON
'<' # 0x003c -> LESS-THAN SIGN
'=' # 0x003d -> EQUALS SIGN
'>' # 0x003e -> GREATER-THAN SIGN
'?' # 0x003f -> QUESTION MARK
'@' # 0x0040 -> COMMERCIAL AT
'A' # 0x0041 -> LATIN CAPITAL LETTER A
'B' # 0x0042 -> LATIN CAPITAL LETTER B
'C' # 0x0043 -> LATIN CAPITAL LETTER C
'D' # 0x0044 -> LATIN CAPITAL LETTER D
'E' # 0x0045 -> LATIN CAPITAL LETTER E
'F' # 0x0046 -> LATIN CAPITAL LETTER F
'G' # 0x0047 -> LATIN CAPITAL LETTER G
'H' # 0x0048 -> LATIN CAPITAL LETTER H
'I' # 0x0049 -> LATIN CAPITAL LETTER I
'J' # 0x004a -> LATIN CAPITAL LETTER J
'K' # 0x004b -> LATIN CAPITAL LETTER K
'L' # 0x004c -> LATIN CAPITAL LETTER L
'M' # 0x004d -> LATIN CAPITAL LETTER M
'N' # 0x004e -> LATIN CAPITAL LETTER N
'O' # 0x004f -> LATIN CAPITAL LETTER O
'P' # 0x0050 -> LATIN CAPITAL LETTER P
'Q' # 0x0051 -> LATIN CAPITAL LETTER Q
'R' # 0x0052 -> LATIN CAPITAL LETTER R
'S' # 0x0053 -> LATIN CAPITAL LETTER S
'T' # 0x0054 -> LATIN CAPITAL LETTER T
'U' # 0x0055 -> LATIN CAPITAL LETTER U
'V' # 0x0056 -> LATIN CAPITAL LETTER V
'W' # 0x0057 -> LATIN CAPITAL LETTER W
'X' # 0x0058 -> LATIN CAPITAL LETTER X
'Y' # 0x0059 -> LATIN CAPITAL LETTER Y
'Z' # 0x005a -> LATIN CAPITAL LETTER Z
'[' # 0x005b -> LEFT SQUARE BRACKET
'\\' # 0x005c -> REVERSE SOLIDUS
']' # 0x005d -> RIGHT SQUARE BRACKET
'^' # 0x005e -> CIRCUMFLEX ACCENT
'_' # 0x005f -> LOW LINE
'`' # 0x0060 -> GRAVE ACCENT
'a' # 0x0061 -> LATIN SMALL LETTER A
'b' # 0x0062 -> LATIN SMALL LETTER B
'c' # 0x0063 -> LATIN SMALL LETTER C
'd' # 0x0064 -> LATIN SMALL LETTER D
'e' # 0x0065 -> LATIN SMALL LETTER E
'f' # 0x0066 -> LATIN SMALL LETTER F
'g' # 0x0067 -> LATIN SMALL LETTER G
'h' # 0x0068 -> LATIN SMALL LETTER H
'i' # 0x0069 -> LATIN SMALL LETTER I
'j' # 0x006a -> LATIN SMALL LETTER J
'k' # 0x006b -> LATIN SMALL LETTER K
'l' # 0x006c -> LATIN SMALL LETTER L
'm' # 0x006d -> LATIN SMALL LETTER M
'n' # 0x006e -> LATIN SMALL LETTER N
'o' # 0x006f -> LATIN SMALL LETTER O
'p' # 0x0070 -> LATIN SMALL LETTER P
'q' # 0x0071 -> LATIN SMALL LETTER Q
'r' # 0x0072 -> LATIN SMALL LETTER R
's' # 0x0073 -> LATIN SMALL LETTER S
't' # 0x0074 -> LATIN SMALL LETTER T
'u' # 0x0075 -> LATIN SMALL LETTER U
'v' # 0x0076 -> LATIN SMALL LETTER V
'w' # 0x0077 -> LATIN SMALL LETTER W
'x' # 0x0078 -> LATIN SMALL LETTER X
'y' # 0x0079 -> LATIN SMALL LETTER Y
'z' # 0x007a -> LATIN SMALL LETTER Z
'{' # 0x007b -> LEFT CURLY BRACKET
'|' # 0x007c -> VERTICAL LINE
'}' # 0x007d -> RIGHT CURLY BRACKET
'~' # 0x007e -> TILDE
'\x7f' # 0x007f -> DELETE
'\xc7' # 0x0080 -> LATIN CAPITAL LETTER C WITH CEDILLA
'\xfc' # 0x0081 -> LATIN SMALL LETTER U WITH DIAERESIS
'\xe9' # 0x0082 -> LATIN SMALL LETTER E WITH ACUTE
'\xe2' # 0x0083 -> LATIN SMALL LETTER A WITH CIRCUMFLEX
'\xc2' # 0x0084 -> LATIN CAPITAL LETTER A WITH CIRCUMFLEX
'\xe0' # 0x0085 -> LATIN SMALL LETTER A WITH GRAVE
'\xb6' # 0x0086 -> PILCROW SIGN
'\xe7' # 0x0087 -> LATIN SMALL LETTER C WITH CEDILLA
'\xea' # 0x0088 -> LATIN SMALL LETTER E WITH CIRCUMFLEX
'\xeb' # 0x0089 -> LATIN SMALL LETTER E WITH DIAERESIS
'\xe8' # 0x008a -> LATIN SMALL LETTER E WITH GRAVE
'\xef' # 0x008b -> LATIN SMALL LETTER I WITH DIAERESIS
'\xee' # 0x008c -> LATIN SMALL LETTER I WITH CIRCUMFLEX
'\u2017' # 0x008d -> DOUBLE LOW LINE
'\xc0' # 0x008e -> LATIN CAPITAL LETTER A WITH GRAVE
'\xa7' # 0x008f -> SECTION SIGN
'\xc9' # 0x0090 -> LATIN CAPITAL LETTER E WITH ACUTE
'\xc8' # 0x0091 -> LATIN CAPITAL LETTER E WITH GRAVE
'\xca' # 0x0092 -> LATIN CAPITAL LETTER E WITH CIRCUMFLEX
'\xf4' # 0x0093 -> LATIN SMALL LETTER O WITH CIRCUMFLEX
'\xcb' # 0x0094 -> LATIN CAPITAL LETTER E WITH DIAERESIS
'\xcf' # 0x0095 -> LATIN CAPITAL LETTER I WITH DIAERESIS
'\xfb' # 0x0096 -> LATIN SMALL LETTER U WITH CIRCUMFLEX
'\xf9' # 0x0097 -> LATIN SMALL LETTER U WITH GRAVE
'\xa4' # 0x0098 -> CURRENCY SIGN
'\xd4' # 0x0099 -> LATIN CAPITAL LETTER O WITH CIRCUMFLEX
'\xdc' # 0x009a -> LATIN CAPITAL LETTER U WITH DIAERESIS
'\xa2' # 0x009b -> CENT SIGN
'\xa3' # 0x009c -> POUND SIGN
'\xd9' # 0x009d -> LATIN CAPITAL LETTER U WITH GRAVE
'\xdb' # 0x009e -> LATIN CAPITAL LETTER U WITH CIRCUMFLEX
'\u0192' # 0x009f -> LATIN SMALL LETTER F WITH HOOK
'\xa6' # 0x00a0 -> BROKEN BAR
'\xb4' # 0x00a1 -> ACUTE ACCENT
'\xf3' # 0x00a2 -> LATIN SMALL LETTER O WITH ACUTE
'\xfa' # 0x00a3 -> LATIN SMALL LETTER U WITH ACUTE
'\xa8' # 0x00a4 -> DIAERESIS
'\xb8' # 0x00a5 -> CEDILLA
'\xb3' # 0x00a6 -> SUPERSCRIPT THREE
'\xaf' # 0x00a7 -> MACRON
'\xce' # 0x00a8 -> LATIN CAPITAL LETTER I WITH CIRCUMFLEX
'\u2310' # 0x00a9 -> REVERSED NOT SIGN
'\xac' # 0x00aa -> NOT SIGN
'\xbd' # 0x00ab -> VULGAR FRACTION ONE HALF
'\xbc' # 0x00ac -> VULGAR FRACTION ONE QUARTER
'\xbe' # 0x00ad -> VULGAR FRACTION THREE QUARTERS
'\xab' # 0x00ae -> LEFT-POINTING DOUBLE ANGLE QUOTATION MARK
'\xbb' # 0x00af -> RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK
'\u2591' # 0x00b0 -> LIGHT SHADE
'\u2592' # 0x00b1 -> MEDIUM SHADE
'\u2593' # 0x00b2 -> DARK SHADE
'\u2502' # 0x00b3 -> BOX DRAWINGS LIGHT VERTICAL
'\u2524' # 0x00b4 -> BOX DRAWINGS LIGHT VERTICAL AND LEFT
'\u2561' # 0x00b5 -> BOX DRAWINGS VERTICAL SINGLE AND LEFT DOUBLE
'\u2562' # 0x00b6 -> BOX DRAWINGS VERTICAL DOUBLE AND LEFT SINGLE
'\u2556' # 0x00b7 -> BOX DRAWINGS DOWN DOUBLE AND LEFT SINGLE
'\u2555' # 0x00b8 -> BOX DRAWINGS DOWN SINGLE AND LEFT DOUBLE
'\u2563' # 0x00b9 -> BOX DRAWINGS DOUBLE VERTICAL AND LEFT
'\u2551' # 0x00ba -> BOX DRAWINGS DOUBLE VERTICAL
'\u2557' # 0x00bb -> BOX DRAWINGS DOUBLE DOWN AND LEFT
'\u255d' # 0x00bc -> BOX DRAWINGS DOUBLE UP AND LEFT
'\u255c' # 0x00bd -> BOX DRAWINGS UP DOUBLE AND LEFT SINGLE
'\u255b' # 0x00be -> BOX DRAWINGS UP SINGLE AND LEFT DOUBLE
'\u2510' # 0x00bf -> BOX DRAWINGS LIGHT DOWN AND LEFT
'\u2514' # 0x00c0 -> BOX DRAWINGS LIGHT UP AND RIGHT
'\u2534' # 0x00c1 -> BOX DRAWINGS LIGHT UP AND HORIZONTAL
'\u252c' # 0x00c2 -> BOX DRAWINGS LIGHT DOWN AND HORIZONTAL
'\u251c' # 0x00c3 -> BOX DRAWINGS LIGHT VERTICAL AND RIGHT
'\u2500' # 0x00c4 -> BOX DRAWINGS LIGHT HORIZONTAL
'\u253c' # 0x00c5 -> BOX DRAWINGS LIGHT VERTICAL AND HORIZONTAL
'\u255e' # 0x00c6 -> BOX DRAWINGS VERTICAL SINGLE AND RIGHT DOUBLE
'\u255f' # 0x00c7 -> BOX DRAWINGS VERTICAL DOUBLE AND RIGHT SINGLE
'\u255a' # 0x00c8 -> BOX DRAWINGS DOUBLE UP AND RIGHT
'\u2554' # 0x00c9 -> BOX DRAWINGS DOUBLE DOWN AND RIGHT
'\u2569' # 0x00ca -> BOX DRAWINGS DOUBLE UP AND HORIZONTAL
'\u2566' # 0x00cb -> BOX DRAWINGS DOUBLE DOWN AND HORIZONTAL
'\u2560' # 0x00cc -> BOX DRAWINGS DOUBLE VERTICAL AND RIGHT
'\u2550' # 0x00cd -> BOX DRAWINGS DOUBLE HORIZONTAL
'\u256c' # 0x00ce -> BOX DRAWINGS DOUBLE VERTICAL AND HORIZONTAL
'\u2567' # 0x00cf -> BOX DRAWINGS UP SINGLE AND HORIZONTAL DOUBLE
'\u2568' # 0x00d0 -> BOX DRAWINGS UP DOUBLE AND HORIZONTAL SINGLE
'\u2564' # 0x00d1 -> BOX DRAWINGS DOWN SINGLE AND HORIZONTAL DOUBLE
'\u2565' # 0x00d2 -> BOX DRAWINGS DOWN DOUBLE AND HORIZONTAL SINGLE
'\u2559' # 0x00d3 -> BOX DRAWINGS UP DOUBLE AND RIGHT SINGLE
'\u2558' # 0x00d4 -> BOX DRAWINGS UP SINGLE AND RIGHT DOUBLE
'\u2552' # 0x00d5 -> BOX DRAWINGS DOWN SINGLE AND RIGHT DOUBLE
'\u2553' # 0x00d6 -> BOX DRAWINGS DOWN DOUBLE AND RIGHT SINGLE
'\u256b' # 0x00d7 -> BOX DRAWINGS VERTICAL DOUBLE AND HORIZONTAL SINGLE
'\u256a' # 0x00d8 -> BOX DRAWINGS VERTICAL SINGLE AND HORIZONTAL DOUBLE
'\u2518' # 0x00d9 -> BOX DRAWINGS LIGHT UP AND LEFT
'\u250c' # 0x00da -> BOX DRAWINGS LIGHT DOWN AND RIGHT
'\u2588' # 0x00db -> FULL BLOCK
'\u2584' # 0x00dc -> LOWER HALF BLOCK
'\u258c' # 0x00dd -> LEFT HALF BLOCK
'\u2590' # 0x00de -> RIGHT HALF BLOCK
'\u2580' # 0x00df -> UPPER HALF BLOCK
'\u03b1' # 0x00e0 -> GREEK SMALL LETTER ALPHA
'\xdf' # 0x00e1 -> LATIN SMALL LETTER SHARP S
'\u0393' # 0x00e2 -> GREEK CAPITAL LETTER GAMMA
'\u03c0' # 0x00e3 -> GREEK SMALL LETTER PI
'\u03a3' # 0x00e4 -> GREEK CAPITAL LETTER SIGMA
'\u03c3' # 0x00e5 -> GREEK SMALL LETTER SIGMA
'\xb5' # 0x00e6 -> MICRO SIGN
'\u03c4' # 0x00e7 -> GREEK SMALL LETTER TAU
'\u03a6' # 0x00e8 -> GREEK CAPITAL LETTER PHI
'\u0398' # 0x00e9 -> GREEK CAPITAL LETTER THETA
'\u03a9' # 0x00ea -> GREEK CAPITAL LETTER OMEGA
'\u03b4' # 0x00eb -> GREEK SMALL LETTER DELTA
'\u221e' # 0x00ec -> INFINITY
'\u03c6' # 0x00ed -> GREEK SMALL LETTER PHI
'\u03b5' # 0x00ee -> GREEK SMALL LETTER EPSILON
'\u2229' # 0x00ef -> INTERSECTION
'\u2261' # 0x00f0 -> IDENTICAL TO
'\xb1' # 0x00f1 -> PLUS-MINUS SIGN
'\u2265' # 0x00f2 -> GREATER-THAN OR EQUAL TO
'\u2264' # 0x00f3 -> LESS-THAN OR EQUAL TO
'\u2320' # 0x00f4 -> TOP HALF INTEGRAL
'\u2321' # 0x00f5 -> BOTTOM HALF INTEGRAL
'\xf7' # 0x00f6 -> DIVISION SIGN
'\u2248' # 0x00f7 -> ALMOST EQUAL TO
'\xb0' # 0x00f8 -> DEGREE SIGN
'\u2219' # 0x00f9 -> BULLET OPERATOR
'\xb7' # 0x00fa -> MIDDLE DOT
'\u221a' # 0x00fb -> SQUARE ROOT
'\u207f' # 0x00fc -> SUPERSCRIPT LATIN SMALL LETTER N
'\xb2' # 0x00fd -> SUPERSCRIPT TWO
'\u25a0' # 0x00fe -> BLACK SQUARE
'\xa0' # 0x00ff -> NO-BREAK SPACE
)
### Encoding Map
encoding_map = {
0x0000: 0x0000, # NULL
0x0001: 0x0001, # START OF HEADING
0x0002: 0x0002, # START OF TEXT
0x0003: 0x0003, # END OF TEXT
0x0004: 0x0004, # END OF TRANSMISSION
0x0005: 0x0005, # ENQUIRY
0x0006: 0x0006, # ACKNOWLEDGE
0x0007: 0x0007, # BELL
0x0008: 0x0008, # BACKSPACE
0x0009: 0x0009, # HORIZONTAL TABULATION
0x000a: 0x000a, # LINE FEED
0x000b: 0x000b, # VERTICAL TABULATION
0x000c: 0x000c, # FORM FEED
0x000d: 0x000d, # CARRIAGE RETURN
0x000e: 0x000e, # SHIFT OUT
0x000f: 0x000f, # SHIFT IN
0x0010: 0x0010, # DATA LINK ESCAPE
0x0011: 0x0011, # DEVICE CONTROL ONE
0x0012: 0x0012, # DEVICE CONTROL TWO
0x0013: 0x0013, # DEVICE CONTROL THREE
0x0014: 0x0014, # DEVICE CONTROL FOUR
0x0015: 0x0015, # NEGATIVE ACKNOWLEDGE
0x0016: 0x0016, # SYNCHRONOUS IDLE
0x0017: 0x0017, # END OF TRANSMISSION BLOCK
0x0018: 0x0018, # CANCEL
0x0019: 0x0019, # END OF MEDIUM
0x001a: 0x001a, # SUBSTITUTE
0x001b: 0x001b, # ESCAPE
0x001c: 0x001c, # FILE SEPARATOR
0x001d: 0x001d, # GROUP SEPARATOR
0x001e: 0x001e, # RECORD SEPARATOR
0x001f: 0x001f, # UNIT SEPARATOR
0x0020: 0x0020, # SPACE
0x0021: 0x0021, # EXCLAMATION MARK
0x0022: 0x0022, # QUOTATION MARK
0x0023: 0x0023, # NUMBER SIGN
0x0024: 0x0024, # DOLLAR SIGN
0x0025: 0x0025, # PERCENT SIGN
0x0026: 0x0026, # AMPERSAND
0x0027: 0x0027, # APOSTROPHE
0x0028: 0x0028, # LEFT PARENTHESIS
0x0029: 0x0029, # RIGHT PARENTHESIS
0x002a: 0x002a, # ASTERISK
0x002b: 0x002b, # PLUS SIGN
0x002c: 0x002c, # COMMA
0x002d: 0x002d, # HYPHEN-MINUS
0x002e: 0x002e, # FULL STOP
0x002f: 0x002f, # SOLIDUS
0x0030: 0x0030, # DIGIT ZERO
0x0031: 0x0031, # DIGIT ONE
0x0032: 0x0032, # DIGIT TWO
0x0033: 0x0033, # DIGIT THREE
0x0034: 0x0034, # DIGIT FOUR
0x0035: 0x0035, # DIGIT FIVE
0x0036: 0x0036, # DIGIT SIX
0x0037: 0x0037, # DIGIT SEVEN
0x0038: 0x0038, # DIGIT EIGHT
0x0039: 0x0039, # DIGIT NINE
0x003a: 0x003a, # COLON
0x003b: 0x003b, # SEMICOLON
0x003c: 0x003c, # LESS-THAN SIGN
0x003d: 0x003d, # EQUALS SIGN
0x003e: 0x003e, # GREATER-THAN SIGN
0x003f: 0x003f, # QUESTION MARK
0x0040: 0x0040, # COMMERCIAL AT
0x0041: 0x0041, # LATIN CAPITAL LETTER A
0x0042: 0x0042, # LATIN CAPITAL LETTER B
0x0043: 0x0043, # LATIN CAPITAL LETTER C
0x0044: 0x0044, # LATIN CAPITAL LETTER D
0x0045: 0x0045, # LATIN CAPITAL LETTER E
0x0046: 0x0046, # LATIN CAPITAL LETTER F
0x0047: 0x0047, # LATIN CAPITAL LETTER G
0x0048: 0x0048, # LATIN CAPITAL LETTER H
0x0049: 0x0049, # LATIN CAPITAL LETTER I
0x004a: 0x004a, # LATIN CAPITAL LETTER J
0x004b: 0x004b, # LATIN CAPITAL LETTER K
0x004c: 0x004c, # LATIN CAPITAL LETTER L
0x004d: 0x004d, # LATIN CAPITAL LETTER M
0x004e: 0x004e, # LATIN CAPITAL LETTER N
0x004f: 0x004f, # LATIN CAPITAL LETTER O
0x0050: 0x0050, # LATIN CAPITAL LETTER P
0x0051: 0x0051, # LATIN CAPITAL LETTER Q
0x0052: 0x0052, # LATIN CAPITAL LETTER R
0x0053: 0x0053, # LATIN CAPITAL LETTER S
0x0054: 0x0054, # LATIN CAPITAL LETTER T
0x0055: 0x0055, # LATIN CAPITAL LETTER U
0x0056: 0x0056, # LATIN CAPITAL LETTER V
0x0057: 0x0057, # LATIN CAPITAL LETTER W
0x0058: 0x0058, # LATIN CAPITAL LETTER X
0x0059: 0x0059, # LATIN CAPITAL LETTER Y
0x005a: 0x005a, # LATIN CAPITAL LETTER Z
0x005b: 0x005b, # LEFT SQUARE BRACKET
0x005c: 0x005c, # REVERSE SOLIDUS
0x005d: 0x005d, # RIGHT SQUARE BRACKET
0x005e: 0x005e, # CIRCUMFLEX ACCENT
0x005f: 0x005f, # LOW LINE
0x0060: 0x0060, # GRAVE ACCENT
0x0061: 0x0061, # LATIN SMALL LETTER A
0x0062: 0x0062, # LATIN SMALL LETTER B
0x0063: 0x0063, # LATIN SMALL LETTER C
0x0064: 0x0064, # LATIN SMALL LETTER D
0x0065: 0x0065, # LATIN SMALL LETTER E
0x0066: 0x0066, # LATIN SMALL LETTER F
0x0067: 0x0067, # LATIN SMALL LETTER G
0x0068: 0x0068, # LATIN SMALL LETTER H
0x0069: 0x0069, # LATIN SMALL LETTER I
0x006a: 0x006a, # LATIN SMALL LETTER J
0x006b: 0x006b, # LATIN SMALL LETTER K
0x006c: 0x006c, # LATIN SMALL LETTER L
0x006d: 0x006d, # LATIN SMALL LETTER M
0x006e: 0x006e, # LATIN SMALL LETTER N
0x006f: 0x006f, # LATIN SMALL LETTER O
0x0070: 0x0070, # LATIN SMALL LETTER P
0x0071: 0x0071, # LATIN SMALL LETTER Q
0x0072: 0x0072, # LATIN SMALL LETTER R
0x0073: 0x0073, # LATIN SMALL LETTER S
0x0074: 0x0074, # LATIN SMALL LETTER T
0x0075: 0x0075, # LATIN SMALL LETTER U
0x0076: 0x0076, # LATIN SMALL LETTER V
0x0077: 0x0077, # LATIN SMALL LETTER W
0x0078: 0x0078, # LATIN SMALL LETTER X
0x0079: 0x0079, # LATIN SMALL LETTER Y
0x007a: 0x007a, # LATIN SMALL LETTER Z
0x007b: 0x007b, # LEFT CURLY BRACKET
0x007c: 0x007c, # VERTICAL LINE
0x007d: 0x007d, # RIGHT CURLY BRACKET
0x007e: 0x007e, # TILDE
0x007f: 0x007f, # DELETE
0x00a0: 0x00ff, # NO-BREAK SPACE
0x00a2: 0x009b, # CENT SIGN
0x00a3: 0x009c, # POUND SIGN
0x00a4: 0x0098, # CURRENCY SIGN
0x00a6: 0x00a0, # BROKEN BAR
0x00a7: 0x008f, # SECTION SIGN
0x00a8: 0x00a4, # DIAERESIS
0x00ab: 0x00ae, # LEFT-POINTING DOUBLE ANGLE QUOTATION MARK
0x00ac: 0x00aa, # NOT SIGN
0x00af: 0x00a7, # MACRON
0x00b0: 0x00f8, # DEGREE SIGN
0x00b1: 0x00f1, # PLUS-MINUS SIGN
0x00b2: 0x00fd, # SUPERSCRIPT TWO
0x00b3: 0x00a6, # SUPERSCRIPT THREE
0x00b4: 0x00a1, # ACUTE ACCENT
0x00b5: 0x00e6, # MICRO SIGN
0x00b6: 0x0086, # PILCROW SIGN
0x00b7: 0x00fa, # MIDDLE DOT
0x00b8: 0x00a5, # CEDILLA
0x00bb: 0x00af, # RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK
0x00bc: 0x00ac, # VULGAR FRACTION ONE QUARTER
0x00bd: 0x00ab, # VULGAR FRACTION ONE HALF
0x00be: 0x00ad, # VULGAR FRACTION THREE QUARTERS
0x00c0: 0x008e, # LATIN CAPITAL LETTER A WITH GRAVE
0x00c2: 0x0084, # LATIN CAPITAL LETTER A WITH CIRCUMFLEX
0x00c7: 0x0080, # LATIN CAPITAL LETTER C WITH CEDILLA
0x00c8: 0x0091, # LATIN CAPITAL LETTER E WITH GRAVE
0x00c9: 0x0090, # LATIN CAPITAL LETTER E WITH ACUTE
0x00ca: 0x0092, # LATIN CAPITAL LETTER E WITH CIRCUMFLEX
0x00cb: 0x0094, # LATIN CAPITAL LETTER E WITH DIAERESIS
0x00ce: 0x00a8, # LATIN CAPITAL LETTER I WITH CIRCUMFLEX
0x00cf: 0x0095, # LATIN CAPITAL LETTER I WITH DIAERESIS
0x00d4: 0x0099, # LATIN CAPITAL LETTER O WITH CIRCUMFLEX
0x00d9: 0x009d, # LATIN CAPITAL LETTER U WITH GRAVE
0x00db: 0x009e, # LATIN CAPITAL LETTER U WITH CIRCUMFLEX
0x00dc: 0x009a, # LATIN CAPITAL LETTER U WITH DIAERESIS
0x00df: 0x00e1, # LATIN SMALL LETTER SHARP S
0x00e0: 0x0085, # LATIN SMALL LETTER A WITH GRAVE
0x00e2: 0x0083, # LATIN SMALL LETTER A WITH CIRCUMFLEX
0x00e7: 0x0087, # LATIN SMALL LETTER C WITH CEDILLA
0x00e8: 0x008a, # LATIN SMALL LETTER E WITH GRAVE
0x00e9: 0x0082, # LATIN SMALL LETTER E WITH ACUTE
0x00ea: 0x0088, # LATIN SMALL LETTER E WITH CIRCUMFLEX
0x00eb: 0x0089, # LATIN SMALL LETTER E WITH DIAERESIS
0x00ee: 0x008c, # LATIN SMALL LETTER I WITH CIRCUMFLEX
0x00ef: 0x008b, # LATIN SMALL LETTER I WITH DIAERESIS
0x00f3: 0x00a2, # LATIN SMALL LETTER O WITH ACUTE
0x00f4: 0x0093, # LATIN SMALL LETTER O WITH CIRCUMFLEX
0x00f7: 0x00f6, # DIVISION SIGN
0x00f9: 0x0097, # LATIN SMALL LETTER U WITH GRAVE
0x00fa: 0x00a3, # LATIN SMALL LETTER U WITH ACUTE
0x00fb: 0x0096, # LATIN SMALL LETTER U WITH CIRCUMFLEX
0x00fc: 0x0081, # LATIN SMALL LETTER U WITH DIAERESIS
0x0192: 0x009f, # LATIN SMALL LETTER F WITH HOOK
0x0393: 0x00e2, # GREEK CAPITAL LETTER GAMMA
0x0398: 0x00e9, # GREEK CAPITAL LETTER THETA
0x03a3: 0x00e4, # GREEK CAPITAL LETTER SIGMA
0x03a6: 0x00e8, # GREEK CAPITAL LETTER PHI
0x03a9: 0x00ea, # GREEK CAPITAL LETTER OMEGA
0x03b1: 0x00e0, # GREEK SMALL LETTER ALPHA
0x03b4: 0x00eb, # GREEK SMALL LETTER DELTA
0x03b5: 0x00ee, # GREEK SMALL LETTER EPSILON
0x03c0: 0x00e3, # GREEK SMALL LETTER PI
0x03c3: 0x00e5, # GREEK SMALL LETTER SIGMA
0x03c4: 0x00e7, # GREEK SMALL LETTER TAU
0x03c6: 0x00ed, # GREEK SMALL LETTER PHI
0x2017: 0x008d, # DOUBLE LOW LINE
0x207f: 0x00fc, # SUPERSCRIPT LATIN SMALL LETTER N
0x2219: 0x00f9, # BULLET OPERATOR
0x221a: 0x00fb, # SQUARE ROOT
0x221e: 0x00ec, # INFINITY
0x2229: 0x00ef, # INTERSECTION
0x2248: 0x00f7, # ALMOST EQUAL TO
0x2261: 0x00f0, # IDENTICAL TO
0x2264: 0x00f3, # LESS-THAN OR EQUAL TO
0x2265: 0x00f2, # GREATER-THAN OR EQUAL TO
0x2310: 0x00a9, # REVERSED NOT SIGN
0x2320: 0x00f4, # TOP HALF INTEGRAL
0x2321: 0x00f5, # BOTTOM HALF INTEGRAL
0x2500: 0x00c4, # BOX DRAWINGS LIGHT HORIZONTAL
0x2502: 0x00b3, # BOX DRAWINGS LIGHT VERTICAL
0x250c: 0x00da, # BOX DRAWINGS LIGHT DOWN AND RIGHT
0x2510: 0x00bf, # BOX DRAWINGS LIGHT DOWN AND LEFT
0x2514: 0x00c0, # BOX DRAWINGS LIGHT UP AND RIGHT
0x2518: 0x00d9, # BOX DRAWINGS LIGHT UP AND LEFT
0x251c: 0x00c3, # BOX DRAWINGS LIGHT VERTICAL AND RIGHT
0x2524: 0x00b4, # BOX DRAWINGS LIGHT VERTICAL AND LEFT
0x252c: 0x00c2, # BOX DRAWINGS LIGHT DOWN AND HORIZONTAL
0x2534: 0x00c1, # BOX DRAWINGS LIGHT UP AND HORIZONTAL
0x253c: 0x00c5, # BOX DRAWINGS LIGHT VERTICAL AND HORIZONTAL
0x2550: 0x00cd, # BOX DRAWINGS DOUBLE HORIZONTAL
0x2551: 0x00ba, # BOX DRAWINGS DOUBLE VERTICAL
0x2552: 0x00d5, # BOX DRAWINGS DOWN SINGLE AND RIGHT DOUBLE
0x2553: 0x00d6, # BOX DRAWINGS DOWN DOUBLE AND RIGHT SINGLE
0x2554: 0x00c9, # BOX DRAWINGS DOUBLE DOWN AND RIGHT
0x2555: 0x00b8, # BOX DRAWINGS DOWN SINGLE AND LEFT DOUBLE
0x2556: 0x00b7, # BOX DRAWINGS DOWN DOUBLE AND LEFT SINGLE
0x2557: 0x00bb, # BOX DRAWINGS DOUBLE DOWN AND LEFT
0x2558: 0x00d4, # BOX DRAWINGS UP SINGLE AND RIGHT DOUBLE
0x2559: 0x00d3, # BOX DRAWINGS UP DOUBLE AND RIGHT SINGLE
0x255a: 0x00c8, # BOX DRAWINGS DOUBLE UP AND RIGHT
0x255b: 0x00be, # BOX DRAWINGS UP SINGLE AND LEFT DOUBLE
0x255c: 0x00bd, # BOX DRAWINGS UP DOUBLE AND LEFT SINGLE
0x255d: 0x00bc, # BOX DRAWINGS DOUBLE UP AND LEFT
0x255e: 0x00c6, # BOX DRAWINGS VERTICAL SINGLE AND RIGHT DOUBLE
0x255f: 0x00c7, # BOX DRAWINGS VERTICAL DOUBLE AND RIGHT SINGLE
0x2560: 0x00cc, # BOX DRAWINGS DOUBLE VERTICAL AND RIGHT
0x2561: 0x00b5, # BOX DRAWINGS VERTICAL SINGLE AND LEFT DOUBLE
0x2562: 0x00b6, # BOX DRAWINGS VERTICAL DOUBLE AND LEFT SINGLE
0x2563: 0x00b9, # BOX DRAWINGS DOUBLE VERTICAL AND LEFT
0x2564: 0x00d1, # BOX DRAWINGS DOWN SINGLE AND HORIZONTAL DOUBLE
0x2565: 0x00d2, # BOX DRAWINGS DOWN DOUBLE AND HORIZONTAL SINGLE
0x2566: 0x00cb, # BOX DRAWINGS DOUBLE DOWN AND HORIZONTAL
0x2567: 0x00cf, # BOX DRAWINGS UP SINGLE AND HORIZONTAL DOUBLE
0x2568: 0x00d0, # BOX DRAWINGS UP DOUBLE AND HORIZONTAL SINGLE
0x2569: 0x00ca, # BOX DRAWINGS DOUBLE UP AND HORIZONTAL
0x256a: 0x00d8, # BOX DRAWINGS VERTICAL SINGLE AND HORIZONTAL DOUBLE
0x256b: 0x00d7, # BOX DRAWINGS VERTICAL DOUBLE AND HORIZONTAL SINGLE
0x256c: 0x00ce, # BOX DRAWINGS DOUBLE VERTICAL AND HORIZONTAL
0x2580: 0x00df, # UPPER HALF BLOCK
0x2584: 0x00dc, # LOWER HALF BLOCK
0x2588: 0x00db, # FULL BLOCK
0x258c: 0x00dd, # LEFT HALF BLOCK
0x2590: 0x00de, # RIGHT HALF BLOCK
0x2591: 0x00b0, # LIGHT SHADE
0x2592: 0x00b1, # MEDIUM SHADE
0x2593: 0x00b2, # DARK SHADE
0x25a0: 0x00fe, # BLACK SQUARE
}
| lgpl-3.0 | -6,916,906,441,276,573,000 | 48.071633 | 97 | 0.602739 | false | 2.951232 | false | false | false |
vjmac15/Lyilis | lib/youtube_dl/extractor/baidu (VJ Washington's conflicted copy 2017-08-29).py | 90 | 1980 | # coding: utf-8
from __future__ import unicode_literals
import re
from .common import InfoExtractor
from ..utils import unescapeHTML
class BaiduVideoIE(InfoExtractor):
IE_DESC = '百度视频'
_VALID_URL = r'https?://v\.baidu\.com/(?P<type>[a-z]+)/(?P<id>\d+)\.htm'
_TESTS = [{
'url': 'http://v.baidu.com/comic/1069.htm?frp=bdbrand&q=%E4%B8%AD%E5%8D%8E%E5%B0%8F%E5%BD%93%E5%AE%B6',
'info_dict': {
'id': '1069',
'title': '中华小当家 TV版国语',
'description': 'md5:51be07afe461cf99fa61231421b5397c',
},
'playlist_count': 52,
}, {
'url': 'http://v.baidu.com/show/11595.htm?frp=bdbrand',
'info_dict': {
'id': '11595',
'title': 're:^奔跑吧兄弟',
'description': 'md5:1bf88bad6d850930f542d51547c089b8',
},
'playlist_mincount': 12,
}]
def _call_api(self, path, category, playlist_id, note):
return self._download_json('http://app.video.baidu.com/%s/?worktype=adnative%s&id=%s' % (
path, category, playlist_id), playlist_id, note)
def _real_extract(self, url):
category, playlist_id = re.match(self._VALID_URL, url).groups()
if category == 'show':
category = 'tvshow'
if category == 'tv':
category = 'tvplay'
playlist_detail = self._call_api(
'xqinfo', category, playlist_id, 'Download playlist JSON metadata')
playlist_title = playlist_detail['title']
playlist_description = unescapeHTML(playlist_detail.get('intro'))
episodes_detail = self._call_api(
'xqsingle', category, playlist_id, 'Download episodes JSON metadata')
entries = [self.url_result(
episode['url'], video_title=episode['title']
) for episode in episodes_detail['videos']]
return self.playlist_result(
entries, playlist_id, playlist_title, playlist_description)
| gpl-3.0 | 8,918,850,448,971,882,000 | 33.75 | 111 | 0.58222 | false | 3.13871 | false | false | false |
Solinea/horizon | openstack_dashboard/dashboards/admin/images/views.py | 3 | 8396 | # Copyright 2012 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# All Rights Reserved.
#
# Copyright 2012 Nebula, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import json
import logging
from oslo_utils import units
from django import conf
from django.core.urlresolvers import reverse
from django.core.urlresolvers import reverse_lazy
from django.utils.translation import ugettext_lazy as _
from horizon import exceptions
from horizon import forms
from horizon import tables
from horizon.utils import memoized
from openstack_dashboard import api
from openstack_dashboard.dashboards.project.images.images import views
from openstack_dashboard.dashboards.admin.images import forms as project_forms
from openstack_dashboard.dashboards.admin.images \
import tables as project_tables
LOG = logging.getLogger(__name__)
class IndexView(tables.DataTableView):
table_class = project_tables.AdminImagesTable
template_name = 'admin/images/index.html'
page_title = _("Images")
def has_prev_data(self, table):
return self._prev
def has_more_data(self, table):
return self._more
def get_data(self):
images = []
filters = self.get_filters()
prev_marker = self.request.GET.get(
project_tables.AdminImagesTable._meta.prev_pagination_param, None)
if prev_marker is not None:
sort_dir = 'asc'
marker = prev_marker
else:
sort_dir = 'desc'
marker = self.request.GET.get(
project_tables.AdminImagesTable._meta.pagination_param, None)
try:
images, self._more, self._prev = api.glance.image_list_detailed(
self.request,
marker=marker,
paginate=True,
filters=filters,
sort_dir=sort_dir)
if prev_marker is not None:
images = sorted(images, key=lambda image:
getattr(image, 'created_at'), reverse=True)
except Exception:
self._prev = False
self._more = False
msg = _('Unable to retrieve image list.')
exceptions.handle(self.request, msg)
return images
def get_filters(self):
filters = {'is_public': None}
filter_field = self.table.get_filter_field()
filter_string = self.table.get_filter_string()
filter_action = self.table._meta._filter_action
if filter_field and filter_string and (
filter_action.is_api_filter(filter_field)):
if filter_field in ['size_min', 'size_max']:
invalid_msg = ('API query is not valid and is ignored: %s=%s'
% (filter_field, filter_string))
try:
filter_string = long(float(filter_string) * (units.Mi))
if filter_string >= 0:
filters[filter_field] = filter_string
else:
LOG.warning(invalid_msg)
except ValueError:
LOG.warning(invalid_msg)
elif (filter_field == 'disk_format' and
filter_string.lower() == 'docker'):
filters['disk_format'] = 'raw'
filters['container_format'] = 'docker'
else:
filters[filter_field] = filter_string
return filters
class CreateView(views.CreateView):
template_name = 'admin/images/create.html'
form_class = project_forms.AdminCreateImageForm
submit_url = reverse_lazy('horizon:admin:images:create')
success_url = reverse_lazy('horizon:admin:images:index')
page_title = _("Create An Image")
class UpdateView(views.UpdateView):
template_name = 'admin/images/update.html'
form_class = project_forms.AdminUpdateImageForm
submit_url = "horizon:admin:images:update"
success_url = reverse_lazy('horizon:admin:images:index')
page_title = _("Update Image")
class DetailView(views.DetailView):
def get_context_data(self, **kwargs):
context = super(DetailView, self).get_context_data(**kwargs)
table = project_tables.AdminImagesTable(self.request)
context["url"] = reverse('horizon:admin:images:index')
context["actions"] = table.render_row_actions(context["image"])
return context
class UpdateMetadataView(forms.ModalFormView):
template_name = "admin/images/update_metadata.html"
modal_header = _("Update Image")
form_id = "update_image_form"
form_class = project_forms.UpdateMetadataForm
submit_url = "horizon:admin:images:update_metadata"
success_url = reverse_lazy('horizon:admin:images:index')
page_title = _("Update Image Metadata")
def get_initial(self):
image = self.get_object()
return {'id': self.kwargs["id"], 'metadata': image.properties}
def get_context_data(self, **kwargs):
context = super(UpdateMetadataView, self).get_context_data(**kwargs)
image = self.get_object()
reserved_props = getattr(conf.settings,
'IMAGE_RESERVED_CUSTOM_PROPERTIES', [])
image.properties = dict((k, v)
for (k, v) in image.properties.iteritems()
if k not in reserved_props)
context['existing_metadata'] = json.dumps(image.properties)
args = (self.kwargs['id'],)
context['submit_url'] = reverse(self.submit_url, args=args)
resource_type = 'OS::Glance::Image'
namespaces = []
try:
# metadefs_namespace_list() returns a tuple with list as 1st elem
available_namespaces = [x.namespace for x in
api.glance.metadefs_namespace_list(
self.request,
filters={"resource_types":
[resource_type]}
)[0]]
for namespace in available_namespaces:
details = api.glance.metadefs_namespace_get(self.request,
namespace,
resource_type)
# Filter out reserved custom properties from namespace
if reserved_props:
if hasattr(details, 'properties'):
details.properties = dict(
(k, v)
for (k, v) in details.properties.iteritems()
if k not in reserved_props
)
if hasattr(details, 'objects'):
for obj in details.objects:
obj['properties'] = dict(
(k, v)
for (k, v) in obj['properties'].iteritems()
if k not in reserved_props
)
namespaces.append(details)
except Exception:
msg = _('Unable to retrieve available properties for image.')
exceptions.handle(self.request, msg)
context['available_metadata'] = json.dumps({'namespaces': namespaces})
context['id'] = self.kwargs['id']
return context
@memoized.memoized_method
def get_object(self):
image_id = self.kwargs['id']
try:
return api.glance.image_get(self.request, image_id)
except Exception:
msg = _('Unable to retrieve the image to be updated.')
exceptions.handle(self.request, msg,
redirect=reverse('horizon:admin:images:index'))
| apache-2.0 | 3,675,810,975,928,954,000 | 38.051163 | 78 | 0.575989 | false | 4.548212 | false | false | false |
luiseduardohdbackup/odoo | addons/account/wizard/account_move_line_reconcile_select.py | 385 | 2362 | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
from openerp.osv import fields, osv
from openerp.tools.translate import _
class account_move_line_reconcile_select(osv.osv_memory):
_name = "account.move.line.reconcile.select"
_description = "Move line reconcile select"
_columns = {
'account_id': fields.many2one('account.account', 'Account', \
domain = [('reconcile', '=', 1)], required=True),
}
def action_open_window(self, cr, uid, ids, context=None):
"""
This function Open account move line window for reconcile on given account id
@param cr: the current row, from the database cursor,
@param uid: the current user’s ID for security checks,
@param ids: account move line reconcile select’s ID or list of IDs
@return: dictionary of Open account move line window for reconcile on given account id
"""
data = self.read(cr, uid, ids, context=context)[0]
return {
'domain': "[('account_id','=',%d),('reconcile_id','=',False),('state','<>','draft')]" % data['account_id'],
'name': _('Reconciliation'),
'view_type': 'form',
'view_mode': 'tree,form',
'view_id': False,
'res_model': 'account.move.line',
'type': 'ir.actions.act_window'
}
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
| agpl-3.0 | -3,165,510,815,337,637,000 | 42.666667 | 119 | 0.59542 | false | 4.203209 | false | false | false |
ruschelp/cortex-vfx | test/IECore/Shader.py | 12 | 3204 | ##########################################################################
#
# Copyright (c) 2007-2011, Image Engine Design 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 Image Engine Design nor the names of any
# other contributors to this software may be used to endorse or
# promote products derived from this software without specific prior
# written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
# IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
# THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
# PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
##########################################################################
import unittest
from IECore import *
class TestShader( unittest.TestCase ) :
def test( self ) :
s = Shader()
self.assertEqual( s.name, "defaultsurface" )
self.assertEqual( s.type, "surface" )
self.assertEqual( len( s.parameters ), 0 )
self.assertEqual( s.parameters.typeName(), "CompoundData" )
s = Shader( "marble", "surface" )
self.assertEqual( s.name, "marble" )
self.assertEqual( s.type, "surface" )
ss = s.copy()
self.assertEqual( ss.name, s.name )
self.assertEqual( ss.type, s.type )
def testConstructWithParameters( self ) :
s = Shader( "test", "surface", CompoundData( { "a" : StringData( "a" ) } ) )
self.assertEqual( s.name, "test" )
self.assertEqual( s.type, "surface" )
self.assertEqual( len( s.parameters ), 1 )
self.assertEqual( s.parameters.typeName(), CompoundData.staticTypeName() )
self.assertEqual( s.parameters["a"], StringData( "a" ) )
def testCopy( self ) :
s = Shader( "test", "surface", CompoundData( { "a" : StringData( "a" ) } ) )
ss = s.copy()
self.assertEqual( s, ss )
def testHash( self ) :
s = Shader()
h = s.hash()
s.name = "somethingElse"
self.assertNotEqual( s.hash(), h )
h = s.hash()
s.type = "somethingElse"
self.assertNotEqual( s.hash(), h )
h = s.hash()
s.parameters["a"] = StringData( "a" )
self.assertNotEqual( s.hash(), h )
if __name__ == "__main__":
unittest.main()
| bsd-3-clause | 8,937,002,234,067,745,000 | 34.208791 | 78 | 0.660737 | false | 3.751756 | true | false | false |
gangadharkadam/smrterp | erpnext/stock/doctype/warehouse/warehouse.py | 3 | 5175 | # Copyright (c) 2013, Web Notes 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 cint, validate_email_add
from frappe import throw, msgprint, _
from frappe.model.document import Document
class Warehouse(Document):
def autoname(self):
suffix = " - " + frappe.db.get_value("Company", self.company, "abbr")
if not self.warehouse_name.endswith(suffix):
self.name = self.warehouse_name + suffix
def validate(self):
if self.email_id and not validate_email_add(self.email_id):
throw(_("Please enter valid Email Id"))
self.update_parent_account()
def update_parent_account(self):
if not getattr(self, "__islocal", None) \
and (self.create_account_under != frappe.db.get_value("Warehouse", self.name, "create_account_under")):
self.validate_parent_account()
warehouse_account = frappe.db.get_value("Account",
{"account_type": "Warehouse", "company": self.company, "master_name": self.name},
["name", "parent_account"])
if warehouse_account and warehouse_account[1] != self.create_account_under:
acc_doc = frappe.get_doc("Account", warehouse_account[0])
acc_doc.parent_account = self.create_account_under
acc_doc.save()
def on_update(self):
self.create_account_head()
def create_account_head(self):
if cint(frappe.defaults.get_global_default("auto_accounting_for_stock")):
if not frappe.db.get_value("Account", {"account_type": "Warehouse",
"master_name": self.name}):
if self.get("__islocal") or not frappe.db.get_value(
"Stock Ledger Entry", {"warehouse": self.name}):
self.validate_parent_account()
ac_doc = frappe.get_doc({
"doctype": "Account",
'account_name': self.warehouse_name,
'parent_account': self.create_account_under,
'group_or_ledger':'Ledger',
'company':self.company,
"account_type": "Warehouse",
"master_name": self.name,
"freeze_account": "No"
})
ac_doc.ignore_permissions = True
ac_doc.insert()
msgprint(_("Account head {0} created").format(ac_doc.name))
def validate_parent_account(self):
if not self.company:
frappe.throw(_("Warehouse {0}: Company is mandatory").format(self.name))
if not self.create_account_under:
parent_account = frappe.db.get_value("Account",
{"account_name": "Stock Assets", "company": self.company})
if parent_account:
self.create_account_under = parent_account
else:
frappe.throw(_("Please enter parent account group for warehouse account"))
elif frappe.db.get_value("Account", self.create_account_under, "company") != self.company:
frappe.throw(_("Warehouse {0}: Parent account {1} does not bolong to the company {2}")
.format(self.name, self.create_account_under, self.company))
def on_trash(self):
# delete bin
bins = frappe.db.sql("select * from `tabBin` where warehouse = %s",
self.name, as_dict=1)
for d in bins:
if d['actual_qty'] or d['reserved_qty'] or d['ordered_qty'] or \
d['indented_qty'] or d['projected_qty'] or d['planned_qty']:
throw(_("Warehouse {0} can not be deleted as quantity exists for Item {1}").format(self.name, d['item_code']))
else:
frappe.db.sql("delete from `tabBin` where name = %s", d['name'])
warehouse_account = frappe.db.get_value("Account",
{"account_type": "Warehouse", "master_name": self.name})
if warehouse_account:
frappe.delete_doc("Account", warehouse_account)
if frappe.db.sql("""select name from `tabStock Ledger Entry`
where warehouse = %s""", self.name):
throw(_("Warehouse can not be deleted as stock ledger entry exists for this warehouse."))
def before_rename(self, olddn, newdn, merge=False):
# Add company abbr if not provided
from erpnext.setup.doctype.company.company import get_name_with_abbr
new_warehouse = get_name_with_abbr(newdn, self.company)
if merge:
if not frappe.db.exists("Warehouse", new_warehouse):
frappe.throw(_("Warehouse {0} does not exist").format(new_warehouse))
if self.company != frappe.db.get_value("Warehouse", new_warehouse, "company"):
frappe.throw(_("Both Warehouse must belong to same Company"))
frappe.db.sql("delete from `tabBin` where warehouse=%s", olddn)
from erpnext.accounts.utils import rename_account_for
rename_account_for("Warehouse", olddn, newdn, merge, self.company)
return new_warehouse
def after_rename(self, olddn, newdn, merge=False):
if merge:
self.recalculate_bin_qty(newdn)
def recalculate_bin_qty(self, newdn):
from erpnext.utilities.repost_stock import repost_stock
frappe.db.auto_commit_on_many_writes = 1
frappe.db.set_default("allow_negative_stock", 1)
for item in frappe.db.sql("""select distinct item_code from (
select name as item_code from `tabItem` where ifnull(is_stock_item, 'Yes')='Yes'
union
select distinct item_code from tabBin) a"""):
repost_stock(item[0], newdn)
frappe.db.set_default("allow_negative_stock",
frappe.db.get_value("Stock Settings", None, "allow_negative_stock"))
frappe.db.auto_commit_on_many_writes = 0
| agpl-3.0 | 6,077,781,720,569,020,000 | 36.773723 | 114 | 0.687343 | false | 3.224299 | false | false | false |
ajose01/rethinkdb | scripts/VirtuaBuild/builder.py | 46 | 6345 | #!/usr/bin/env python
# Copyright 2010-2012 RethinkDB, all rights reserved.
from vcoptparse import *
import vm_build
import sys
from threading import Thread, Semaphore
class Builder(Thread):
def __init__(self, name, branch, target, semaphore):
Thread.__init__(self)
self.name = name
self.branch = branch
self.target = target
self.semaphore = semaphore
def run(self):
self.success = False
try:
semaphore.acquire()
self.target.run(self.branch, self.name)
self.success = True
except vm_build.RunError, err:
self.exception = err
finally:
semaphore.release()
target_names = ["suse", "redhat5_1", "ubuntu", "debian", "centos5_5", "centos6"]
def help():
print >>sys.stderr, "Virtual builder:"
print >>sys.stderr, " --help Print this help."
print >>sys.stderr, " --target target1 [target2, target3]"
print >>sys.stderr, " Build just one target, options are:"
print >>sys.stderr, " ", target_names
print >>sys.stderr, " defaults to all of them."
print >>sys.stderr, " --branch branch_name"
print >>sys.stderr, " Build from a branch mutually exclusive with --tag."
print >>sys.stderr, " --tag tag-name"
print >>sys.stderr, " Build from a tag mutually exclusive with --branch."
print >>sys.stderr, " --threads number"
print >>sys.stderr, " The number of parallel threads to run."
print >>sys.stderr, " --debug"
print >>sys.stderr, " Whether to build the packages with debugging enabled."
print >>sys.stderr, " --interact"
print >>sys.stderr, " This starts a target so that you can interact with it."
print >>sys.stderr, " Requires a target."
print >>sys.stderr, " --clean-up"
print >>sys.stderr, " Shutdown all running vms"
print >>sys.stderr, " --username"
print >>sys.stderr, " Starts the Virtual Machine using VirtualBox from the specified username."
print >>sys.stderr, " --hostname"
print >>sys.stderr, " Starts the Virtual Machine using VirtualBox from the specified host machine."
o = OptParser()
o["help"] = BoolFlag("--help")
o["target"] = StringFlag("--target", None)
o["branch"] = StringFlag("--branch", None)
o["tag"] = StringFlag("--tag", None)
o["threads"] = IntFlag("--threads", 3)
o["clean-up"] = BoolFlag("--clean-up")
o["interact"] = BoolFlag("--interact")
o["debug"] = BoolFlag("--debug");
o["username"] = StringFlag("--username", "rethinkdb") # For now, these default values should always be the ones you should use
o["hostname"] = StringFlag("--hostname", "deadshot") # because the UUID values below are hard-coded to correspond with rethinkdb@deadshot
try:
opts = o.parse(sys.argv)
except OptError:
print >>sys.stderr, "Argument parsing error"
help()
exit(-1)
if opts["help"]:
help()
sys.exit(0)
if opts["branch"] and opts["tag"]:
print >>sys.stderr, "Error cannot use --tag and --branch together."
help()
sys.exit(1)
if opts["branch"]:
rspec = vm_build.Branch(opts["branch"])
elif opts["tag"]:
rspec = vm_build.Tag(opts["tag"])
else:
rspec = vm_build.Branch("master")
# Prepare the build flags
flags = "" # this will be given to the makefile
if opts["debug"]:
flags += " DEBUG=1 UNIT_TESTS=0"
else:
flags += " DEBUG=0"
suse = vm_build.target('765127b8-2007-43ff-8668-fe4c60176a2b', '192.168.0.173', 'rethinkdb', 'make LEGACY_LINUX=1 LEGACY_GCC=1 NO_EVENTFD=1 rpm-suse10 ' + flags, 'rpm', vm_build.rpm_install, vm_build.rpm_uninstall, vm_build.rpm_get_binary, opts["username"], opts["hostname"])
redhat5_1 = vm_build.target('32340f79-cea9-42ca-94d5-2da13d408d02', '192.168.0.159', 'rethinkdb', 'make rpm LEGACY_GCC=1 LEGACY_LINUX=1 NO_EVENTFD=1' + flags, 'rpm', vm_build.rpm_install, vm_build.rpm_uninstall, vm_build.rpm_get_binary, opts["username"], opts["hostname"])
ubuntu = vm_build.target('1f4521a0-6e74-4d20-b4b9-9ffd8e231423', '192.168.0.172', 'rethinkdb', 'make deb' + flags, 'deb', vm_build.deb_install, vm_build.deb_uninstall, vm_build.deb_get_binary, opts["username"], opts["hostname"])
debian = vm_build.target('cc76e2a5-92c0-4208-be08-5c02429c2c50', '192.168.0.176', 'root', 'make deb NO_EVENTFD=1 LEGACY_LINUX=1 ' + flags, 'deb', vm_build.deb_install, vm_build.deb_uninstall, vm_build.deb_get_binary, opts["username"], opts["hostname"])
centos5_5 = vm_build.target('25710682-666f-4449-bd28-68b25abd8bea', '192.168.0.153', 'root', 'make rpm LEGACY_GCC=1 LEGACY_LINUX=1 ' + flags, 'rpm', vm_build.rpm_install, vm_build.rpm_uninstall, vm_build.rpm_get_binary, opts["username"], opts["hostname"])
centos6 = vm_build.target('d9058650-a45a-44a5-953f-c2402253a614', '192.168.0.178', 'rethinkdb', 'make rpm LEGACY_GCC=1 LEGACY_LINUX=1 ' + flags, 'rpm', vm_build.rpm_install, vm_build.rpm_uninstall, vm_build.rpm_get_binary, opts["username"], opts["hostname"])
targets = {"suse": suse, "redhat5_1": redhat5_1, "ubuntu": ubuntu, "debian": debian, "centos5_5": centos5_5, "centos6": centos6}
if (opts["target"]):
targets = {opts["target"]: targets[opts["target"]]}
if opts["clean-up"]:
map(lambda x: x[1].clean_up(), targets.iteritems())
exit(0)
if opts["interact"]:
if not opts["target"]:
print >>sys.stderr, "Error must specify a --target for --interact mode."
exit(1)
for name, target in targets.iteritems():
target.interact(name)
else:
success = {}
exception = {}
semaphore = Semaphore(opts["threads"])
builders = map(lambda x: Builder(x[0], rspec, x[1], semaphore), targets.iteritems())
map(lambda x: x.start(), builders)
map(lambda x: x.join(), builders)
for b in builders:
success[b.name] = b.success
if not b.success:
exception[b.name] = b.exception
print "Build summary:"
from termcolor import colored
for name, val in success.iteritems():
print name, "." * (20 - len(name)), colored("[Pass]", "green") if val else colored("[Fail]", "red")
if (not val):
print "Failed on: ", exception[name]
raise exception[name]
print "Done."
| agpl-3.0 | 939,719,559,956,513,200 | 44.647482 | 275 | 0.626162 | false | 3.265569 | false | false | false |
c1728p9/pyOCD | pyOCD/target/target_stm32f103rc.py | 4 | 1457 | """
mbed CMSIS-DAP debugger
Copyright (c) 2006-2013 ARM Limited
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 cortex_m import CortexM, DHCSR, DBGKEY, C_DEBUGEN, C_MASKINTS, C_STEP, DEMCR, VC_CORERESET, NVIC_AIRCR, NVIC_AIRCR_VECTKEY, NVIC_AIRCR_SYSRESETREQ
from .memory_map import (FlashRegion, RamRegion, MemoryMap)
from pyOCD.target.target import TARGET_RUNNING, TARGET_HALTED
import logging
DBGMCU_CR = 0xE0042004
#0111 1110 0011 1111 1111 1111 0000 0000
DBGMCU_VAL = 0x7E3FFF00
class STM32F103RC(CortexM):
memoryMap = MemoryMap(
FlashRegion( start=0x08000000, length=0x80000, blocksize=0x800, isBootMemory=True),
RamRegion( start=0x20000000, length=0x10000)
)
def __init__(self, transport):
super(STM32F103RC, self).__init__(transport, self.memoryMap)
def init(self):
logging.debug('stm32f103rc init')
CortexM.init(self)
self.writeMemory(DBGMCU_CR, DBGMCU_VAL);
| apache-2.0 | -6,004,540,841,488,146,000 | 32.883721 | 151 | 0.728895 | false | 3.237778 | false | false | false |
technologiescollege/s2a_fr | s2a/Python/Lib/test/lock_tests.py | 110 | 15126 | """
Various tests for synchronization primitives.
"""
import sys
import time
from thread import start_new_thread, get_ident
import threading
import unittest
from test import test_support as support
def _wait():
# A crude wait/yield function not relying on synchronization primitives.
time.sleep(0.01)
class Bunch(object):
"""
A bunch of threads.
"""
def __init__(self, f, n, wait_before_exit=False):
"""
Construct a bunch of `n` threads running the same function `f`.
If `wait_before_exit` is True, the threads won't terminate until
do_finish() is called.
"""
self.f = f
self.n = n
self.started = []
self.finished = []
self._can_exit = not wait_before_exit
def task():
tid = get_ident()
self.started.append(tid)
try:
f()
finally:
self.finished.append(tid)
while not self._can_exit:
_wait()
for i in range(n):
start_new_thread(task, ())
def wait_for_started(self):
while len(self.started) < self.n:
_wait()
def wait_for_finished(self):
while len(self.finished) < self.n:
_wait()
def do_finish(self):
self._can_exit = True
class BaseTestCase(unittest.TestCase):
def setUp(self):
self._threads = support.threading_setup()
def tearDown(self):
support.threading_cleanup(*self._threads)
support.reap_children()
class BaseLockTests(BaseTestCase):
"""
Tests for both recursive and non-recursive locks.
"""
def test_constructor(self):
lock = self.locktype()
del lock
def test_acquire_destroy(self):
lock = self.locktype()
lock.acquire()
del lock
def test_acquire_release(self):
lock = self.locktype()
lock.acquire()
lock.release()
del lock
def test_try_acquire(self):
lock = self.locktype()
self.assertTrue(lock.acquire(False))
lock.release()
def test_try_acquire_contended(self):
lock = self.locktype()
lock.acquire()
result = []
def f():
result.append(lock.acquire(False))
Bunch(f, 1).wait_for_finished()
self.assertFalse(result[0])
lock.release()
def test_acquire_contended(self):
lock = self.locktype()
lock.acquire()
N = 5
def f():
lock.acquire()
lock.release()
b = Bunch(f, N)
b.wait_for_started()
_wait()
self.assertEqual(len(b.finished), 0)
lock.release()
b.wait_for_finished()
self.assertEqual(len(b.finished), N)
def test_with(self):
lock = self.locktype()
def f():
lock.acquire()
lock.release()
def _with(err=None):
with lock:
if err is not None:
raise err
_with()
# Check the lock is unacquired
Bunch(f, 1).wait_for_finished()
self.assertRaises(TypeError, _with, TypeError)
# Check the lock is unacquired
Bunch(f, 1).wait_for_finished()
def test_thread_leak(self):
# The lock shouldn't leak a Thread instance when used from a foreign
# (non-threading) thread.
lock = self.locktype()
def f():
lock.acquire()
lock.release()
n = len(threading.enumerate())
# We run many threads in the hope that existing threads ids won't
# be recycled.
Bunch(f, 15).wait_for_finished()
self.assertEqual(n, len(threading.enumerate()))
class LockTests(BaseLockTests):
"""
Tests for non-recursive, weak locks
(which can be acquired and released from different threads).
"""
def test_reacquire(self):
# Lock needs to be released before re-acquiring.
lock = self.locktype()
phase = []
def f():
lock.acquire()
phase.append(None)
lock.acquire()
phase.append(None)
start_new_thread(f, ())
while len(phase) == 0:
_wait()
_wait()
self.assertEqual(len(phase), 1)
lock.release()
while len(phase) == 1:
_wait()
self.assertEqual(len(phase), 2)
def test_different_thread(self):
# Lock can be released from a different thread.
lock = self.locktype()
lock.acquire()
def f():
lock.release()
b = Bunch(f, 1)
b.wait_for_finished()
lock.acquire()
lock.release()
class RLockTests(BaseLockTests):
"""
Tests for recursive locks.
"""
def test_reacquire(self):
lock = self.locktype()
lock.acquire()
lock.acquire()
lock.release()
lock.acquire()
lock.release()
lock.release()
def test_release_unacquired(self):
# Cannot release an unacquired lock
lock = self.locktype()
self.assertRaises(RuntimeError, lock.release)
lock.acquire()
lock.acquire()
lock.release()
lock.acquire()
lock.release()
lock.release()
self.assertRaises(RuntimeError, lock.release)
def test_different_thread(self):
# Cannot release from a different thread
lock = self.locktype()
def f():
lock.acquire()
b = Bunch(f, 1, True)
try:
self.assertRaises(RuntimeError, lock.release)
finally:
b.do_finish()
def test__is_owned(self):
lock = self.locktype()
self.assertFalse(lock._is_owned())
lock.acquire()
self.assertTrue(lock._is_owned())
lock.acquire()
self.assertTrue(lock._is_owned())
result = []
def f():
result.append(lock._is_owned())
Bunch(f, 1).wait_for_finished()
self.assertFalse(result[0])
lock.release()
self.assertTrue(lock._is_owned())
lock.release()
self.assertFalse(lock._is_owned())
class EventTests(BaseTestCase):
"""
Tests for Event objects.
"""
def test_is_set(self):
evt = self.eventtype()
self.assertFalse(evt.is_set())
evt.set()
self.assertTrue(evt.is_set())
evt.set()
self.assertTrue(evt.is_set())
evt.clear()
self.assertFalse(evt.is_set())
evt.clear()
self.assertFalse(evt.is_set())
def _check_notify(self, evt):
# All threads get notified
N = 5
results1 = []
results2 = []
def f():
results1.append(evt.wait())
results2.append(evt.wait())
b = Bunch(f, N)
b.wait_for_started()
_wait()
self.assertEqual(len(results1), 0)
evt.set()
b.wait_for_finished()
self.assertEqual(results1, [True] * N)
self.assertEqual(results2, [True] * N)
def test_notify(self):
evt = self.eventtype()
self._check_notify(evt)
# Another time, after an explicit clear()
evt.set()
evt.clear()
self._check_notify(evt)
def test_timeout(self):
evt = self.eventtype()
results1 = []
results2 = []
N = 5
def f():
results1.append(evt.wait(0.0))
t1 = time.time()
r = evt.wait(0.2)
t2 = time.time()
results2.append((r, t2 - t1))
Bunch(f, N).wait_for_finished()
self.assertEqual(results1, [False] * N)
for r, dt in results2:
self.assertFalse(r)
self.assertTrue(dt >= 0.2, dt)
# The event is set
results1 = []
results2 = []
evt.set()
Bunch(f, N).wait_for_finished()
self.assertEqual(results1, [True] * N)
for r, dt in results2:
self.assertTrue(r)
class ConditionTests(BaseTestCase):
"""
Tests for condition variables.
"""
def test_acquire(self):
cond = self.condtype()
# Be default we have an RLock: the condition can be acquired multiple
# times.
cond.acquire()
cond.acquire()
cond.release()
cond.release()
lock = threading.Lock()
cond = self.condtype(lock)
cond.acquire()
self.assertFalse(lock.acquire(False))
cond.release()
self.assertTrue(lock.acquire(False))
self.assertFalse(cond.acquire(False))
lock.release()
with cond:
self.assertFalse(lock.acquire(False))
def test_unacquired_wait(self):
cond = self.condtype()
self.assertRaises(RuntimeError, cond.wait)
def test_unacquired_notify(self):
cond = self.condtype()
self.assertRaises(RuntimeError, cond.notify)
def _check_notify(self, cond):
N = 5
results1 = []
results2 = []
phase_num = 0
def f():
cond.acquire()
cond.wait()
cond.release()
results1.append(phase_num)
cond.acquire()
cond.wait()
cond.release()
results2.append(phase_num)
b = Bunch(f, N)
b.wait_for_started()
_wait()
self.assertEqual(results1, [])
# Notify 3 threads at first
cond.acquire()
cond.notify(3)
_wait()
phase_num = 1
cond.release()
while len(results1) < 3:
_wait()
self.assertEqual(results1, [1] * 3)
self.assertEqual(results2, [])
# Notify 5 threads: they might be in their first or second wait
cond.acquire()
cond.notify(5)
_wait()
phase_num = 2
cond.release()
while len(results1) + len(results2) < 8:
_wait()
self.assertEqual(results1, [1] * 3 + [2] * 2)
self.assertEqual(results2, [2] * 3)
# Notify all threads: they are all in their second wait
cond.acquire()
cond.notify_all()
_wait()
phase_num = 3
cond.release()
while len(results2) < 5:
_wait()
self.assertEqual(results1, [1] * 3 + [2] * 2)
self.assertEqual(results2, [2] * 3 + [3] * 2)
b.wait_for_finished()
def test_notify(self):
cond = self.condtype()
self._check_notify(cond)
# A second time, to check internal state is still ok.
self._check_notify(cond)
def test_timeout(self):
cond = self.condtype()
results = []
N = 5
def f():
cond.acquire()
t1 = time.time()
cond.wait(0.2)
t2 = time.time()
cond.release()
results.append(t2 - t1)
Bunch(f, N).wait_for_finished()
self.assertEqual(len(results), 5)
for dt in results:
self.assertTrue(dt >= 0.2, dt)
class BaseSemaphoreTests(BaseTestCase):
"""
Common tests for {bounded, unbounded} semaphore objects.
"""
def test_constructor(self):
self.assertRaises(ValueError, self.semtype, value = -1)
self.assertRaises(ValueError, self.semtype, value = -sys.maxint)
def test_acquire(self):
sem = self.semtype(1)
sem.acquire()
sem.release()
sem = self.semtype(2)
sem.acquire()
sem.acquire()
sem.release()
sem.release()
def test_acquire_destroy(self):
sem = self.semtype()
sem.acquire()
del sem
def test_acquire_contended(self):
sem = self.semtype(7)
sem.acquire()
N = 10
results1 = []
results2 = []
phase_num = 0
def f():
sem.acquire()
results1.append(phase_num)
sem.acquire()
results2.append(phase_num)
b = Bunch(f, 10)
b.wait_for_started()
while len(results1) + len(results2) < 6:
_wait()
self.assertEqual(results1 + results2, [0] * 6)
phase_num = 1
for i in range(7):
sem.release()
while len(results1) + len(results2) < 13:
_wait()
self.assertEqual(sorted(results1 + results2), [0] * 6 + [1] * 7)
phase_num = 2
for i in range(6):
sem.release()
while len(results1) + len(results2) < 19:
_wait()
self.assertEqual(sorted(results1 + results2), [0] * 6 + [1] * 7 + [2] * 6)
# The semaphore is still locked
self.assertFalse(sem.acquire(False))
# Final release, to let the last thread finish
sem.release()
b.wait_for_finished()
def test_try_acquire(self):
sem = self.semtype(2)
self.assertTrue(sem.acquire(False))
self.assertTrue(sem.acquire(False))
self.assertFalse(sem.acquire(False))
sem.release()
self.assertTrue(sem.acquire(False))
def test_try_acquire_contended(self):
sem = self.semtype(4)
sem.acquire()
results = []
def f():
results.append(sem.acquire(False))
results.append(sem.acquire(False))
Bunch(f, 5).wait_for_finished()
# There can be a thread switch between acquiring the semaphore and
# appending the result, therefore results will not necessarily be
# ordered.
self.assertEqual(sorted(results), [False] * 7 + [True] * 3 )
def test_default_value(self):
# The default initial value is 1.
sem = self.semtype()
sem.acquire()
def f():
sem.acquire()
sem.release()
b = Bunch(f, 1)
b.wait_for_started()
_wait()
self.assertFalse(b.finished)
sem.release()
b.wait_for_finished()
def test_with(self):
sem = self.semtype(2)
def _with(err=None):
with sem:
self.assertTrue(sem.acquire(False))
sem.release()
with sem:
self.assertFalse(sem.acquire(False))
if err:
raise err
_with()
self.assertTrue(sem.acquire(False))
sem.release()
self.assertRaises(TypeError, _with, TypeError)
self.assertTrue(sem.acquire(False))
sem.release()
class SemaphoreTests(BaseSemaphoreTests):
"""
Tests for unbounded semaphores.
"""
def test_release_unacquired(self):
# Unbounded releases are allowed and increment the semaphore's value
sem = self.semtype(1)
sem.release()
sem.acquire()
sem.acquire()
sem.release()
class BoundedSemaphoreTests(BaseSemaphoreTests):
"""
Tests for bounded semaphores.
"""
def test_release_unacquired(self):
# Cannot go past the initial value
sem = self.semtype()
self.assertRaises(ValueError, sem.release)
sem.acquire()
sem.release()
self.assertRaises(ValueError, sem.release)
| gpl-3.0 | 1,044,183,361,976,538,100 | 26.703297 | 82 | 0.536229 | false | 3.940089 | true | false | false |
krishna-pandey-git/django | tests/template_tests/filter_tests/test_timesince.py | 207 | 5422 | from __future__ import unicode_literals
from datetime import datetime, timedelta
from django.template.defaultfilters import timesince_filter
from django.test import SimpleTestCase
from django.test.utils import requires_tz_support
from ..utils import setup
from .timezone_utils import TimezoneTestCase
class TimesinceTests(TimezoneTestCase):
"""
#20246 - \xa0 in output avoids line-breaks between value and unit
"""
# Default compare with datetime.now()
@setup({'timesince01': '{{ a|timesince }}'})
def test_timesince01(self):
output = self.engine.render_to_string('timesince01', {'a': datetime.now() + timedelta(minutes=-1, seconds=-10)})
self.assertEqual(output, '1\xa0minute')
@setup({'timesince02': '{{ a|timesince }}'})
def test_timesince02(self):
output = self.engine.render_to_string('timesince02', {'a': datetime.now() - timedelta(days=1, minutes=1)})
self.assertEqual(output, '1\xa0day')
@setup({'timesince03': '{{ a|timesince }}'})
def test_timesince03(self):
output = self.engine.render_to_string('timesince03', {'a': datetime.now() - timedelta(hours=1, minutes=25, seconds=10)})
self.assertEqual(output, '1\xa0hour, 25\xa0minutes')
# Compare to a given parameter
@setup({'timesince04': '{{ a|timesince:b }}'})
def test_timesince04(self):
output = self.engine.render_to_string(
'timesince04',
{'a': self.now - timedelta(days=2), 'b': self.now - timedelta(days=1)},
)
self.assertEqual(output, '1\xa0day')
@setup({'timesince05': '{{ a|timesince:b }}'})
def test_timesince05(self):
output = self.engine.render_to_string(
'timesince05',
{'a': self.now - timedelta(days=2, minutes=1), 'b': self.now - timedelta(days=2)},
)
self.assertEqual(output, '1\xa0minute')
# Check that timezone is respected
@setup({'timesince06': '{{ a|timesince:b }}'})
def test_timesince06(self):
output = self.engine.render_to_string('timesince06', {'a': self.now_tz - timedelta(hours=8), 'b': self.now_tz})
self.assertEqual(output, '8\xa0hours')
# Tests for #7443
@setup({'timesince07': '{{ earlier|timesince }}'})
def test_timesince07(self):
output = self.engine.render_to_string('timesince07', {'earlier': self.now - timedelta(days=7)})
self.assertEqual(output, '1\xa0week')
@setup({'timesince08': '{{ earlier|timesince:now }}'})
def test_timesince08(self):
output = self.engine.render_to_string('timesince08', {'now': self.now, 'earlier': self.now - timedelta(days=7)})
self.assertEqual(output, '1\xa0week')
@setup({'timesince09': '{{ later|timesince }}'})
def test_timesince09(self):
output = self.engine.render_to_string('timesince09', {'later': self.now + timedelta(days=7)})
self.assertEqual(output, '0\xa0minutes')
@setup({'timesince10': '{{ later|timesince:now }}'})
def test_timesince10(self):
output = self.engine.render_to_string('timesince10', {'now': self.now, 'later': self.now + timedelta(days=7)})
self.assertEqual(output, '0\xa0minutes')
# Ensures that differing timezones are calculated correctly.
@setup({'timesince11': '{{ a|timesince }}'})
def test_timesince11(self):
output = self.engine.render_to_string('timesince11', {'a': self.now})
self.assertEqual(output, '0\xa0minutes')
@requires_tz_support
@setup({'timesince12': '{{ a|timesince }}'})
def test_timesince12(self):
output = self.engine.render_to_string('timesince12', {'a': self.now_tz})
self.assertEqual(output, '0\xa0minutes')
@requires_tz_support
@setup({'timesince13': '{{ a|timesince }}'})
def test_timesince13(self):
output = self.engine.render_to_string('timesince13', {'a': self.now_tz_i})
self.assertEqual(output, '0\xa0minutes')
@setup({'timesince14': '{{ a|timesince:b }}'})
def test_timesince14(self):
output = self.engine.render_to_string('timesince14', {'a': self.now_tz, 'b': self.now_tz_i})
self.assertEqual(output, '0\xa0minutes')
@setup({'timesince15': '{{ a|timesince:b }}'})
def test_timesince15(self):
output = self.engine.render_to_string('timesince15', {'a': self.now, 'b': self.now_tz_i})
self.assertEqual(output, '')
@setup({'timesince16': '{{ a|timesince:b }}'})
def test_timesince16(self):
output = self.engine.render_to_string('timesince16', {'a': self.now_tz_i, 'b': self.now})
self.assertEqual(output, '')
# Tests for #9065 (two date objects).
@setup({'timesince17': '{{ a|timesince:b }}'})
def test_timesince17(self):
output = self.engine.render_to_string('timesince17', {'a': self.today, 'b': self.today})
self.assertEqual(output, '0\xa0minutes')
@setup({'timesince18': '{{ a|timesince:b }}'})
def test_timesince18(self):
output = self.engine.render_to_string('timesince18', {'a': self.today, 'b': self.today + timedelta(hours=24)})
self.assertEqual(output, '1\xa0day')
class FunctionTests(SimpleTestCase):
def test_since_now(self):
self.assertEqual(timesince_filter(datetime.now() - timedelta(1)), '1\xa0day')
def test_explicit_date(self):
self.assertEqual(timesince_filter(datetime(2005, 12, 29), datetime(2005, 12, 30)), '1\xa0day')
| bsd-3-clause | -8,209,475,703,017,608,000 | 41.031008 | 128 | 0.634821 | false | 3.571805 | true | false | false |
mne-tools/mne-tools.github.io | 0.20/_downloads/76822bb92a8465181ec2a7ee96ca8cf4/plot_decoding_csp_timefreq.py | 1 | 6457 | """
============================================================================
Decoding in time-frequency space data using the Common Spatial Pattern (CSP)
============================================================================
The time-frequency decomposition is estimated by iterating over raw data that
has been band-passed at different frequencies. This is used to compute a
covariance matrix over each epoch or a rolling time-window and extract the CSP
filtered signals. A linear discriminant classifier is then applied to these
signals.
"""
# Authors: Laura Gwilliams <laura.gwilliams@nyu.edu>
# Jean-Remi King <jeanremi.king@gmail.com>
# Alex Barachant <alexandre.barachant@gmail.com>
# Alexandre Gramfort <alexandre.gramfort@inria.fr>
#
# License: BSD (3-clause)
import numpy as np
import matplotlib.pyplot as plt
from mne import Epochs, create_info, events_from_annotations
from mne.io import concatenate_raws, read_raw_edf
from mne.datasets import eegbci
from mne.decoding import CSP
from mne.time_frequency import AverageTFR
from sklearn.discriminant_analysis import LinearDiscriminantAnalysis
from sklearn.model_selection import StratifiedKFold, cross_val_score
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import LabelEncoder
###############################################################################
# Set parameters and read data
event_id = dict(hands=2, feet=3) # motor imagery: hands vs feet
subject = 1
runs = [6, 10, 14]
raw_fnames = eegbci.load_data(subject, runs)
raw = concatenate_raws([read_raw_edf(f, preload=True) for f in raw_fnames])
# Extract information from the raw file
sfreq = raw.info['sfreq']
events, _ = events_from_annotations(raw, event_id=dict(T1=2, T2=3))
raw.pick_types(meg=False, eeg=True, stim=False, eog=False, exclude='bads')
# Assemble the classifier using scikit-learn pipeline
clf = make_pipeline(CSP(n_components=4, reg=None, log=True, norm_trace=False),
LinearDiscriminantAnalysis())
n_splits = 5 # how many folds to use for cross-validation
cv = StratifiedKFold(n_splits=n_splits, shuffle=True)
# Classification & Time-frequency parameters
tmin, tmax = -.200, 2.000
n_cycles = 10. # how many complete cycles: used to define window size
min_freq = 5.
max_freq = 25.
n_freqs = 8 # how many frequency bins to use
# Assemble list of frequency range tuples
freqs = np.linspace(min_freq, max_freq, n_freqs) # assemble frequencies
freq_ranges = list(zip(freqs[:-1], freqs[1:])) # make freqs list of tuples
# Infer window spacing from the max freq and number of cycles to avoid gaps
window_spacing = (n_cycles / np.max(freqs) / 2.)
centered_w_times = np.arange(tmin, tmax, window_spacing)[1:]
n_windows = len(centered_w_times)
# Instantiate label encoder
le = LabelEncoder()
###############################################################################
# Loop through frequencies, apply classifier and save scores
# init scores
freq_scores = np.zeros((n_freqs - 1,))
# Loop through each frequency range of interest
for freq, (fmin, fmax) in enumerate(freq_ranges):
# Infer window size based on the frequency being used
w_size = n_cycles / ((fmax + fmin) / 2.) # in seconds
# Apply band-pass filter to isolate the specified frequencies
raw_filter = raw.copy().filter(fmin, fmax, n_jobs=1, fir_design='firwin',
skip_by_annotation='edge')
# Extract epochs from filtered data, padded by window size
epochs = Epochs(raw_filter, events, event_id, tmin - w_size, tmax + w_size,
proj=False, baseline=None, preload=True)
epochs.drop_bad()
y = le.fit_transform(epochs.events[:, 2])
X = epochs.get_data()
# Save mean scores over folds for each frequency and time window
freq_scores[freq] = np.mean(cross_val_score(estimator=clf, X=X, y=y,
scoring='roc_auc', cv=cv,
n_jobs=1), axis=0)
###############################################################################
# Plot frequency results
plt.bar(freqs[:-1], freq_scores, width=np.diff(freqs)[0],
align='edge', edgecolor='black')
plt.xticks(freqs)
plt.ylim([0, 1])
plt.axhline(len(epochs['feet']) / len(epochs), color='k', linestyle='--',
label='chance level')
plt.legend()
plt.xlabel('Frequency (Hz)')
plt.ylabel('Decoding Scores')
plt.title('Frequency Decoding Scores')
###############################################################################
# Loop through frequencies and time, apply classifier and save scores
# init scores
tf_scores = np.zeros((n_freqs - 1, n_windows))
# Loop through each frequency range of interest
for freq, (fmin, fmax) in enumerate(freq_ranges):
# Infer window size based on the frequency being used
w_size = n_cycles / ((fmax + fmin) / 2.) # in seconds
# Apply band-pass filter to isolate the specified frequencies
raw_filter = raw.copy().filter(fmin, fmax, n_jobs=1, fir_design='firwin',
skip_by_annotation='edge')
# Extract epochs from filtered data, padded by window size
epochs = Epochs(raw_filter, events, event_id, tmin - w_size, tmax + w_size,
proj=False, baseline=None, preload=True)
epochs.drop_bad()
y = le.fit_transform(epochs.events[:, 2])
# Roll covariance, csp and lda over time
for t, w_time in enumerate(centered_w_times):
# Center the min and max of the window
w_tmin = w_time - w_size / 2.
w_tmax = w_time + w_size / 2.
# Crop data into time-window of interest
X = epochs.copy().crop(w_tmin, w_tmax).get_data()
# Save mean scores over folds for each frequency and time window
tf_scores[freq, t] = np.mean(cross_val_score(estimator=clf, X=X, y=y,
scoring='roc_auc', cv=cv,
n_jobs=1), axis=0)
###############################################################################
# Plot time-frequency results
# Set up time frequency object
av_tfr = AverageTFR(create_info(['freq'], sfreq), tf_scores[np.newaxis, :],
centered_w_times, freqs[1:], 1)
chance = np.mean(y) # set chance level to white in the plot
av_tfr.plot([0], vmin=chance, title="Time-Frequency Decoding Scores",
cmap=plt.cm.Reds)
| bsd-3-clause | 240,441,842,313,748,830 | 39.10559 | 79 | 0.611275 | false | 3.6834 | false | false | false |
pennersr/django-allauth | allauth/socialaccount/providers/orcid/provider.py | 2 | 1564 | from allauth.socialaccount.providers.base import ProviderAccount
from allauth.socialaccount.providers.oauth2.provider import OAuth2Provider
class Scope(object):
USERINFO_PROFILE = "/authenticate"
class OrcidAccount(ProviderAccount):
def get_profile_url(self):
return extract_from_dict(self.account.extra_data, ["orcid-identifier", "uri"])
def to_str(self):
return self.account.uid
class OrcidProvider(OAuth2Provider):
id = "orcid"
name = "Orcid.org"
account_class = OrcidAccount
def get_default_scope(self):
return [Scope.USERINFO_PROFILE]
def extract_uid(self, data):
return extract_from_dict(data, ["orcid-identifier", "path"])
def extract_common_fields(self, data):
common_fields = dict(
email=extract_from_dict(data, ["person", "emails", "email", 0, "email"]),
last_name=extract_from_dict(
data, ["person", "name", "family-name", "value"]
),
first_name=extract_from_dict(
data, ["person", "name", "given-names", "value"]
),
)
return dict((key, value) for (key, value) in common_fields.items() if value)
provider_classes = [OrcidProvider]
def extract_from_dict(data, path):
"""
Navigate `data`, a multidimensional array (list or dictionary), and returns
the object at `path`.
"""
value = data
try:
for key in path:
value = value[key]
return value
except (KeyError, IndexError, TypeError):
return ""
| mit | 6,449,739,463,738,600,000 | 27.436364 | 86 | 0.618926 | false | 3.777778 | false | false | false |
d40223223/2015cdbg6team0622 | static/Brython3.1.1-20150328-091302/Lib/importlib/basehook.py | 608 | 1396 | from javascript import JSObject
from browser import window
import urllib.request
class TempMod:
def __init__(self, name):
self.name=name
#define my custom import hook (just to see if it get called etc).
class BaseHook:
def __init__(self, fullname=None, path=None):
self._fullname=fullname
self._path=path # we don't are about this...
self._modpath=''
self._module=''
def find_module(self, name=None, path=None):
if name is None:
name=self._fullname
for _i in ('libs/%s.js' % name, 'Lib/%s.py' % name,
'Lib/%s/__init__.py' % name):
_path="%s%s" % (__BRYTHON__.brython_path, _i)
try:
_fp,_,_headers=urllib.request.urlopen(_path)
if _headers['status'] != 200:
continue
self._module=_fp.read()
self._modpath=_path
return self
except urllib.error.HTTPError as e:
print(str(e))
self._modpath=''
self._module=''
raise ImportError
def is_package(self):
return '.' in self._fullname
def load_module(self, name):
if name is None:
name=self._fullname
window.eval('__BRYTHON__.imported["%s"]={}' % name)
return JSObject(__BRYTHON__.run_py)(TempMod(name),
self._modpath, self._module)
| gpl-3.0 | 834,423,359,024,821,900 | 29.347826 | 70 | 0.537966 | false | 3.867036 | false | false | false |
fx2003/tensorflow-study | TensorFlow实战/models/syntaxnet/dragnn/python/composite_optimizer.py | 12 | 2604 | # Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""An optimizer that switches between several methods."""
import tensorflow as tf
from tensorflow.python.training import optimizer
class CompositeOptimizer(optimizer.Optimizer):
"""Optimizer that switches between several methods.
"""
def __init__(self,
optimizer1,
optimizer2,
switch,
use_locking=False,
name='Composite'):
"""Construct a new Composite optimizer.
Args:
optimizer1: A tf.python.training.optimizer.Optimizer object.
optimizer2: A tf.python.training.optimizer.Optimizer object.
switch: A tf.bool Tensor, selecting whether to use the first or the second
optimizer.
use_locking: Bool. If True apply use locks to prevent concurrent updates
to variables.
name: Optional name prefix for the operations created when applying
gradients. Defaults to "Composite".
"""
super(CompositeOptimizer, self).__init__(use_locking, name)
self._optimizer1 = optimizer1
self._optimizer2 = optimizer2
self._switch = switch
def apply_gradients(self, grads_and_vars, global_step=None, name=None):
return tf.cond(
self._switch,
lambda: self._optimizer1.apply_gradients(grads_and_vars,
global_step, name),
lambda: self._optimizer2.apply_gradients(grads_and_vars,
global_step, name)
)
def get_slot(self, var, name):
slot1 = self._optimizer1.get_slot(var, name)
slot2 = self._optimizer2.get_slot(var, name)
if slot1 and slot2:
raise LookupError('Slot named %s for variable %s populated for both '
'optimizers' % (name, var.name))
return slot1 or slot2
def get_slot_names(self):
return sorted(self._optimizer1.get_slot_names() +
self._optimizer2.get_slot_names())
| mit | 4,514,945,215,384,570,000 | 36.2 | 80 | 0.635177 | false | 4.458904 | false | false | false |
mshafiq9/django | django/views/generic/detail.py | 306 | 6922 | from __future__ import unicode_literals
from django.core.exceptions import ImproperlyConfigured
from django.db import models
from django.http import Http404
from django.utils.translation import ugettext as _
from django.views.generic.base import ContextMixin, TemplateResponseMixin, View
class SingleObjectMixin(ContextMixin):
"""
Provides the ability to retrieve a single object for further manipulation.
"""
model = None
queryset = None
slug_field = 'slug'
context_object_name = None
slug_url_kwarg = 'slug'
pk_url_kwarg = 'pk'
query_pk_and_slug = False
def get_object(self, queryset=None):
"""
Returns the object the view is displaying.
By default this requires `self.queryset` and a `pk` or `slug` argument
in the URLconf, but subclasses can override this to return any object.
"""
# Use a custom queryset if provided; this is required for subclasses
# like DateDetailView
if queryset is None:
queryset = self.get_queryset()
# Next, try looking up by primary key.
pk = self.kwargs.get(self.pk_url_kwarg)
slug = self.kwargs.get(self.slug_url_kwarg)
if pk is not None:
queryset = queryset.filter(pk=pk)
# Next, try looking up by slug.
if slug is not None and (pk is None or self.query_pk_and_slug):
slug_field = self.get_slug_field()
queryset = queryset.filter(**{slug_field: slug})
# If none of those are defined, it's an error.
if pk is None and slug is None:
raise AttributeError("Generic detail view %s must be called with "
"either an object pk or a slug."
% self.__class__.__name__)
try:
# Get the single item from the filtered queryset
obj = queryset.get()
except queryset.model.DoesNotExist:
raise Http404(_("No %(verbose_name)s found matching the query") %
{'verbose_name': queryset.model._meta.verbose_name})
return obj
def get_queryset(self):
"""
Return the `QuerySet` that will be used to look up the object.
Note that this method is called by the default implementation of
`get_object` and may not be called if `get_object` is overridden.
"""
if self.queryset is None:
if self.model:
return self.model._default_manager.all()
else:
raise ImproperlyConfigured(
"%(cls)s is missing a QuerySet. Define "
"%(cls)s.model, %(cls)s.queryset, or override "
"%(cls)s.get_queryset()." % {
'cls': self.__class__.__name__
}
)
return self.queryset.all()
def get_slug_field(self):
"""
Get the name of a slug field to be used to look up by slug.
"""
return self.slug_field
def get_context_object_name(self, obj):
"""
Get the name to use for the object.
"""
if self.context_object_name:
return self.context_object_name
elif isinstance(obj, models.Model):
if self.object._deferred:
obj = obj._meta.proxy_for_model
return obj._meta.model_name
else:
return None
def get_context_data(self, **kwargs):
"""
Insert the single object into the context dict.
"""
context = {}
if self.object:
context['object'] = self.object
context_object_name = self.get_context_object_name(self.object)
if context_object_name:
context[context_object_name] = self.object
context.update(kwargs)
return super(SingleObjectMixin, self).get_context_data(**context)
class BaseDetailView(SingleObjectMixin, View):
"""
A base view for displaying a single object
"""
def get(self, request, *args, **kwargs):
self.object = self.get_object()
context = self.get_context_data(object=self.object)
return self.render_to_response(context)
class SingleObjectTemplateResponseMixin(TemplateResponseMixin):
template_name_field = None
template_name_suffix = '_detail'
def get_template_names(self):
"""
Return a list of template names to be used for the request. May not be
called if render_to_response is overridden. Returns the following list:
* the value of ``template_name`` on the view (if provided)
* the contents of the ``template_name_field`` field on the
object instance that the view is operating upon (if available)
* ``<app_label>/<model_name><template_name_suffix>.html``
"""
try:
names = super(SingleObjectTemplateResponseMixin, self).get_template_names()
except ImproperlyConfigured:
# If template_name isn't specified, it's not a problem --
# we just start with an empty list.
names = []
# If self.template_name_field is set, grab the value of the field
# of that name from the object; this is the most specific template
# name, if given.
if self.object and self.template_name_field:
name = getattr(self.object, self.template_name_field, None)
if name:
names.insert(0, name)
# The least-specific option is the default <app>/<model>_detail.html;
# only use this if the object in question is a model.
if isinstance(self.object, models.Model):
object_meta = self.object._meta
if self.object._deferred:
object_meta = self.object._meta.proxy_for_model._meta
names.append("%s/%s%s.html" % (
object_meta.app_label,
object_meta.model_name,
self.template_name_suffix
))
elif hasattr(self, 'model') and self.model is not None and issubclass(self.model, models.Model):
names.append("%s/%s%s.html" % (
self.model._meta.app_label,
self.model._meta.model_name,
self.template_name_suffix
))
# If we still haven't managed to find any template names, we should
# re-raise the ImproperlyConfigured to alert the user.
if not names:
raise
return names
class DetailView(SingleObjectTemplateResponseMixin, BaseDetailView):
"""
Render a "detail" view of an object.
By default this is a model instance looked up from `self.queryset`, but the
view will support display of *any* object by overriding `self.get_object()`.
"""
| bsd-3-clause | -6,310,951,046,772,378,000 | 36.825137 | 108 | 0.582202 | false | 4.477361 | false | false | false |
takeflight/wagtailmodelchooser | wagtailmodelchooser/__init__.py | 1 | 2011 | from .utils import kwarg_decorator, last_arg_decorator
from .version import version as __version__
from .version import version_info
__all__ = [
'__version__', 'version_info', 'registry', 'register_model_chooser',
'register_simple_model_chooser', 'register_filter',
]
class Registry(object):
def __init__(self):
self.choosers = {}
self.filters = {}
def register_chooser(self, chooser, **kwargs):
"""Adds a model chooser definition to the registry."""
if not issubclass(chooser, Chooser):
return self.register_simple_chooser(chooser, **kwargs)
self.choosers[chooser.model] = chooser(**kwargs)
return chooser
def register_simple_chooser(self, model, **kwargs):
"""
Generates a model chooser definition from a model, and adds it to the
registry.
"""
name = '{}Chooser'.format(model._meta.object_name)
attrs = {'model': model}
attrs.update(kwargs)
chooser = type(name, (Chooser,), attrs)
self.register_chooser(chooser)
return model
def register_filter(self, model, name, filter):
assert model in self.choosers
self.filters[(model, name)] = filter
return filter
class Chooser(object):
model = None
icon = 'placeholder'
# Customize the chooser content for just this model
modal_template = None
modal_results_template = None
def get_queryset(self, request):
return self.model._default_manager.all()
def get_modal_template(self, request):
return self.modal_template or 'wagtailmodelchooser/modal.html'
def get_modal_results_template(self, request):
return self.modal_results_template or 'wagtailmodelchooser/results.html'
registry = Registry()
register_model_chooser = kwarg_decorator(registry.register_chooser)
register_simple_model_chooser = kwarg_decorator(registry.register_simple_chooser)
register_filter = last_arg_decorator(registry.register_filter)
| bsd-2-clause | -339,373,218,791,220,300 | 29.469697 | 81 | 0.665341 | false | 4.079108 | false | false | false |
hsuchie4/TACTIC | src/pyasm/deprecated/flash/flash_file_naming.py | 6 | 1678 | ###########################################################
#
# Copyright (c) 2005, Southpaw Technology
# All Rights Reserved
#
# PROPRIETARY INFORMATION. This software is proprietary to
# Southpaw Technology, and is not to be reproduced, transmitted,
# or disclosed in any way without written permission.
#
#
#
__all__ = ['FlashFileNaming']
import os, re
from pyasm.biz import FileNaming, Project, Snapshot, File
from pyasm.common import TacticException
class FlashFileNaming(FileNaming):
def add_ending(my, parts, auto_version=False):
context = my.snapshot.get_value("context")
version = my.snapshot.get_value("version")
version = "v%0.3d" % version
ext = my.get_ext()
# it is only unique if we use both context and version
parts.append(context)
parts.append(version)
filename = "_".join(parts)
filename = "%s%s" % (filename, ext)
# should I check if this filename is unique again?
return filename
# custom filename processing per sobject begins
def _get_unique_filename(my):
filename = my.file_object.get_full_file_name()
# find if this filename has been used for this project
file = File.get_by_filename(filename, skip_id=my.file_object.get_id())
if file:
root, ext = os.path.splitext(filename)
parts = [root]
filename = my.add_ending(parts, auto_version=True)
return filename
else:
return None
def flash_nat_pause(my):
return my._get_unique_filename()
def flash_final_wave(my):
return my._get_unique_filename()
| epl-1.0 | 7,258,592,367,855,573,000 | 26.966667 | 78 | 0.607867 | false | 3.884259 | false | false | false |
yongshengwang/hue | desktop/core/ext-py/pycrypto-2.6.1/build/lib.linux-x86_64-2.7/Crypto/PublicKey/DSA.py | 123 | 13695 | # -*- coding: utf-8 -*-
#
# PublicKey/DSA.py : DSA signature primitive
#
# Written in 2008 by Dwayne C. Litzenberger <dlitz@dlitz.net>
#
# ===================================================================
# The contents of this file are dedicated to the public domain. To
# the extent that dedication to the public domain is not available,
# everyone is granted a worldwide, perpetual, royalty-free,
# non-exclusive license to exercise all rights associated with the
# contents of this file for any purpose whatsoever.
# No rights are reserved.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
# BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
# ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
# ===================================================================
"""DSA public-key signature algorithm.
DSA_ is a widespread public-key signature algorithm. Its security is
based on the discrete logarithm problem (DLP_). Given a cyclic
group, a generator *g*, and an element *h*, it is hard
to find an integer *x* such that *g^x = h*. The problem is believed
to be difficult, and it has been proved such (and therefore secure) for
more than 30 years.
The group is actually a sub-group over the integers modulo *p*, with *p* prime.
The sub-group order is *q*, which is prime too; it always holds that *(p-1)* is a multiple of *q*.
The cryptographic strength is linked to the magnitude of *p* and *q*.
The signer holds a value *x* (*0<x<q-1*) as private key, and its public
key (*y* where *y=g^x mod p*) is distributed.
In 2012, a sufficient size is deemed to be 2048 bits for *p* and 256 bits for *q*.
For more information, see the most recent ECRYPT_ report.
DSA is reasonably secure for new designs.
The algorithm can only be used for authentication (digital signature).
DSA cannot be used for confidentiality (encryption).
The values *(p,q,g)* are called *domain parameters*;
they are not sensitive but must be shared by both parties (the signer and the verifier).
Different signers can share the same domain parameters with no security
concerns.
The DSA signature is twice as big as the size of *q* (64 bytes if *q* is 256 bit
long).
This module provides facilities for generating new DSA keys and for constructing
them from known components. DSA keys allows you to perform basic signing and
verification.
>>> from Crypto.Random import random
>>> from Crypto.PublicKey import DSA
>>> from Crypto.Hash import SHA
>>>
>>> message = "Hello"
>>> key = DSA.generate(1024)
>>> h = SHA.new(message).digest()
>>> k = random.StrongRandom().randint(1,key.q-1)
>>> sig = key.sign(h,k)
>>> ...
>>> if key.verify(h,sig):
>>> print "OK"
>>> else:
>>> print "Incorrect signature"
.. _DSA: http://en.wikipedia.org/wiki/Digital_Signature_Algorithm
.. _DLP: http://www.cosic.esat.kuleuven.be/publications/talk-78.pdf
.. _ECRYPT: http://www.ecrypt.eu.org/documents/D.SPA.17.pdf
"""
__revision__ = "$Id$"
__all__ = ['generate', 'construct', 'error', 'DSAImplementation', '_DSAobj']
import sys
if sys.version_info[0] == 2 and sys.version_info[1] == 1:
from Crypto.Util.py21compat import *
from Crypto.PublicKey import _DSA, _slowmath, pubkey
from Crypto import Random
try:
from Crypto.PublicKey import _fastmath
except ImportError:
_fastmath = None
class _DSAobj(pubkey.pubkey):
"""Class defining an actual DSA key.
:undocumented: __getstate__, __setstate__, __repr__, __getattr__
"""
#: Dictionary of DSA parameters.
#:
#: A public key will only have the following entries:
#:
#: - **y**, the public key.
#: - **g**, the generator.
#: - **p**, the modulus.
#: - **q**, the order of the sub-group.
#:
#: A private key will also have:
#:
#: - **x**, the private key.
keydata = ['y', 'g', 'p', 'q', 'x']
def __init__(self, implementation, key):
self.implementation = implementation
self.key = key
def __getattr__(self, attrname):
if attrname in self.keydata:
# For backward compatibility, allow the user to get (not set) the
# DSA key parameters directly from this object.
return getattr(self.key, attrname)
else:
raise AttributeError("%s object has no %r attribute" % (self.__class__.__name__, attrname,))
def sign(self, M, K):
"""Sign a piece of data with DSA.
:Parameter M: The piece of data to sign with DSA. It may
not be longer in bit size than the sub-group order (*q*).
:Type M: byte string or long
:Parameter K: A secret number, chosen randomly in the closed
range *[1,q-1]*.
:Type K: long (recommended) or byte string (not recommended)
:attention: selection of *K* is crucial for security. Generating a
random number larger than *q* and taking the modulus by *q* is
**not** secure, since smaller values will occur more frequently.
Generating a random number systematically smaller than *q-1*
(e.g. *floor((q-1)/8)* random bytes) is also **not** secure. In general,
it shall not be possible for an attacker to know the value of `any
bit of K`__.
:attention: The number *K* shall not be reused for any other
operation and shall be discarded immediately.
:attention: M must be a digest cryptographic hash, otherwise
an attacker may mount an existential forgery attack.
:Return: A tuple with 2 longs.
.. __: http://www.di.ens.fr/~pnguyen/pub_NgSh00.htm
"""
return pubkey.pubkey.sign(self, M, K)
def verify(self, M, signature):
"""Verify the validity of a DSA signature.
:Parameter M: The expected message.
:Type M: byte string or long
:Parameter signature: The DSA signature to verify.
:Type signature: A tuple with 2 longs as return by `sign`
:Return: True if the signature is correct, False otherwise.
"""
return pubkey.pubkey.verify(self, M, signature)
def _encrypt(self, c, K):
raise TypeError("DSA cannot encrypt")
def _decrypt(self, c):
raise TypeError("DSA cannot decrypt")
def _blind(self, m, r):
raise TypeError("DSA cannot blind")
def _unblind(self, m, r):
raise TypeError("DSA cannot unblind")
def _sign(self, m, k):
return self.key._sign(m, k)
def _verify(self, m, sig):
(r, s) = sig
return self.key._verify(m, r, s)
def has_private(self):
return self.key.has_private()
def size(self):
return self.key.size()
def can_blind(self):
return False
def can_encrypt(self):
return False
def can_sign(self):
return True
def publickey(self):
return self.implementation.construct((self.key.y, self.key.g, self.key.p, self.key.q))
def __getstate__(self):
d = {}
for k in self.keydata:
try:
d[k] = getattr(self.key, k)
except AttributeError:
pass
return d
def __setstate__(self, d):
if not hasattr(self, 'implementation'):
self.implementation = DSAImplementation()
t = []
for k in self.keydata:
if not d.has_key(k):
break
t.append(d[k])
self.key = self.implementation._math.dsa_construct(*tuple(t))
def __repr__(self):
attrs = []
for k in self.keydata:
if k == 'p':
attrs.append("p(%d)" % (self.size()+1,))
elif hasattr(self.key, k):
attrs.append(k)
if self.has_private():
attrs.append("private")
# PY3K: This is meant to be text, do not change to bytes (data)
return "<%s @0x%x %s>" % (self.__class__.__name__, id(self), ",".join(attrs))
class DSAImplementation(object):
"""
A DSA key factory.
This class is only internally used to implement the methods of the
`Crypto.PublicKey.DSA` module.
"""
def __init__(self, **kwargs):
"""Create a new DSA key factory.
:Keywords:
use_fast_math : bool
Specify which mathematic library to use:
- *None* (default). Use fastest math available.
- *True* . Use fast math.
- *False* . Use slow math.
default_randfunc : callable
Specify how to collect random data:
- *None* (default). Use Random.new().read().
- not *None* . Use the specified function directly.
:Raise RuntimeError:
When **use_fast_math** =True but fast math is not available.
"""
use_fast_math = kwargs.get('use_fast_math', None)
if use_fast_math is None: # Automatic
if _fastmath is not None:
self._math = _fastmath
else:
self._math = _slowmath
elif use_fast_math: # Explicitly select fast math
if _fastmath is not None:
self._math = _fastmath
else:
raise RuntimeError("fast math module not available")
else: # Explicitly select slow math
self._math = _slowmath
self.error = self._math.error
# 'default_randfunc' parameter:
# None (default) - use Random.new().read
# not None - use the specified function
self._default_randfunc = kwargs.get('default_randfunc', None)
self._current_randfunc = None
def _get_randfunc(self, randfunc):
if randfunc is not None:
return randfunc
elif self._current_randfunc is None:
self._current_randfunc = Random.new().read
return self._current_randfunc
def generate(self, bits, randfunc=None, progress_func=None):
"""Randomly generate a fresh, new DSA key.
:Parameters:
bits : int
Key length, or size (in bits) of the DSA modulus
*p*.
It must be a multiple of 64, in the closed
interval [512,1024].
randfunc : callable
Random number generation function; it should accept
a single integer N and return a string of random data
N bytes long.
If not specified, a new one will be instantiated
from ``Crypto.Random``.
progress_func : callable
Optional function that will be called with a short string
containing the key parameter currently being generated;
it's useful for interactive applications where a user is
waiting for a key to be generated.
:attention: You should always use a cryptographically secure random number generator,
such as the one defined in the ``Crypto.Random`` module; **don't** just use the
current time and the ``random`` module.
:Return: A DSA key object (`_DSAobj`).
:Raise ValueError:
When **bits** is too little, too big, or not a multiple of 64.
"""
# Check against FIPS 186-2, which says that the size of the prime p
# must be a multiple of 64 bits between 512 and 1024
for i in (0, 1, 2, 3, 4, 5, 6, 7, 8):
if bits == 512 + 64*i:
return self._generate(bits, randfunc, progress_func)
# The March 2006 draft of FIPS 186-3 also allows 2048 and 3072-bit
# primes, but only with longer q values. Since the current DSA
# implementation only supports a 160-bit q, we don't support larger
# values.
raise ValueError("Number of bits in p must be a multiple of 64 between 512 and 1024, not %d bits" % (bits,))
def _generate(self, bits, randfunc=None, progress_func=None):
rf = self._get_randfunc(randfunc)
obj = _DSA.generate_py(bits, rf, progress_func) # TODO: Don't use legacy _DSA module
key = self._math.dsa_construct(obj.y, obj.g, obj.p, obj.q, obj.x)
return _DSAobj(self, key)
def construct(self, tup):
"""Construct a DSA key from a tuple of valid DSA components.
The modulus *p* must be a prime.
The following equations must apply:
- p-1 = 0 mod q
- g^x = y mod p
- 0 < x < q
- 1 < g < p
:Parameters:
tup : tuple
A tuple of long integers, with 4 or 5 items
in the following order:
1. Public key (*y*).
2. Sub-group generator (*g*).
3. Modulus, finite field order (*p*).
4. Sub-group order (*q*).
5. Private key (*x*). Optional.
:Return: A DSA key object (`_DSAobj`).
"""
key = self._math.dsa_construct(*tup)
return _DSAobj(self, key)
_impl = DSAImplementation()
generate = _impl.generate
construct = _impl.construct
error = _impl.error
# vim:set ts=4 sw=4 sts=4 expandtab:
| apache-2.0 | 7,233,003,489,526,411,000 | 35.134565 | 116 | 0.584958 | false | 4.029126 | false | false | false |
FlaPer87/qpid-proton | proton-c/mllib/dom.py | 41 | 6497 | #
# 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.
#
"""
Simple DOM for both SGML and XML documents.
"""
from __future__ import division
from __future__ import generators
from __future__ import nested_scopes
import transforms
class Container:
def __init__(self):
self.children = []
def add(self, child):
child.parent = self
self.children.append(child)
def extend(self, children):
for child in children:
child.parent = self
self.children.append(child)
class Component:
def __init__(self):
self.parent = None
def index(self):
if self.parent:
return self.parent.children.index(self)
else:
return 0
def _line(self, file, line, column):
self.file = file
self.line = line
self.column = column
class DispatchError(Exception):
def __init__(self, scope, f):
msg = "no such attribtue"
class Dispatcher:
def is_type(self, type):
cls = self
while cls != None:
if cls.type == type:
return True
cls = cls.base
return False
def dispatch(self, f, attrs = ""):
cls = self
while cls != None:
if hasattr(f, cls.type):
return getattr(f, cls.type)(self)
else:
cls = cls.base
cls = self
while cls != None:
if attrs:
sep = ", "
if cls.base == None:
sep += "or "
else:
sep = ""
attrs += "%s'%s'" % (sep, cls.type)
cls = cls.base
raise AttributeError("'%s' object has no attribute %s" %
(f.__class__.__name__, attrs))
class Node(Container, Component, Dispatcher):
type = "node"
base = None
def __init__(self):
Container.__init__(self)
Component.__init__(self)
self.query = Query([self])
def __getitem__(self, name):
for nd in self.query[name]:
return nd
def text(self):
return self.dispatch(transforms.Text())
def tag(self, name, *attrs, **kwargs):
t = Tag(name, *attrs, **kwargs)
self.add(t)
return t
def data(self, s):
d = Data(s)
self.add(d)
return d
def entity(self, s):
e = Entity(s)
self.add(e)
return e
class Tree(Node):
type = "tree"
base = Node
class Tag(Node):
type = "tag"
base = Node
def __init__(self, _name, *attrs, **kwargs):
Node.__init__(self)
self.name = _name
self.attrs = list(attrs)
self.attrs.extend(kwargs.items())
self.singleton = False
def get_attr(self, name):
for k, v in self.attrs:
if name == k:
return v
def _idx(self, attr):
idx = 0
for k, v in self.attrs:
if k == attr:
return idx
idx += 1
return None
def set_attr(self, name, value):
idx = self._idx(name)
if idx is None:
self.attrs.append((name, value))
else:
self.attrs[idx] = (name, value)
def dispatch(self, f):
try:
attr = "do_" + self.name
method = getattr(f, attr)
except AttributeError:
return Dispatcher.dispatch(self, f, "'%s'" % attr)
return method(self)
class Leaf(Component, Dispatcher):
type = "leaf"
base = None
def __init__(self, data):
assert isinstance(data, basestring)
self.data = data
class Data(Leaf):
type = "data"
base = Leaf
class Entity(Leaf):
type = "entity"
base = Leaf
class Character(Leaf):
type = "character"
base = Leaf
class Comment(Leaf):
type = "comment"
base = Leaf
###################
## Query Classes ##
###########################################################################
class Adder:
def __add__(self, other):
return Sum(self, other)
class Sum(Adder):
def __init__(self, left, right):
self.left = left
self.right = right
def __iter__(self):
for x in self.left:
yield x
for x in self.right:
yield x
class View(Adder):
def __init__(self, source):
self.source = source
class Filter(View):
def __init__(self, predicate, source):
View.__init__(self, source)
self.predicate = predicate
def __iter__(self):
for nd in self.source:
if self.predicate(nd): yield nd
class Flatten(View):
def __iter__(self):
sources = [iter(self.source)]
while sources:
try:
nd = sources[-1].next()
if isinstance(nd, Tree):
sources.append(iter(nd.children))
else:
yield nd
except StopIteration:
sources.pop()
class Children(View):
def __iter__(self):
for nd in self.source:
for child in nd.children:
yield child
class Attributes(View):
def __iter__(self):
for nd in self.source:
for a in nd.attrs:
yield a
class Values(View):
def __iter__(self):
for name, value in self.source:
yield value
def flatten_path(path):
if isinstance(path, basestring):
for part in path.split("/"):
yield part
elif callable(path):
yield path
else:
for p in path:
for fp in flatten_path(p):
yield fp
class Query(View):
def __iter__(self):
for nd in self.source:
yield nd
def __getitem__(self, path):
query = self.source
for p in flatten_path(path):
if callable(p):
select = Query
pred = p
source = query
elif isinstance(p, basestring):
if p[0] == "@":
select = Values
pred = lambda x, n=p[1:]: x[0] == n
source = Attributes(query)
elif p[0] == "#":
select = Query
pred = lambda x, t=p[1:]: x.is_type(t)
source = Children(query)
else:
select = Query
pred = lambda x, n=p: isinstance(x, Tag) and x.name == n
source = Flatten(Children(query))
else:
raise ValueError(p)
query = select(Filter(pred, source))
return query
| apache-2.0 | -4,284,463,407,971,938,300 | 19.958065 | 75 | 0.583654 | false | 3.666479 | false | false | false |
happyleavesaoc/home-assistant | homeassistant/components/cover/myq.py | 3 | 2882 | """
Support for MyQ-Enabled Garage Doors.
For more details about this platform, please refer to the documentation
https://home-assistant.io/components/cover.myq/
"""
import logging
import voluptuous as vol
from homeassistant.components.cover import CoverDevice
from homeassistant.const import (
CONF_USERNAME, CONF_PASSWORD, CONF_TYPE, STATE_CLOSED)
import homeassistant.helpers.config_validation as cv
import homeassistant.loader as loader
REQUIREMENTS = ['pymyq==0.0.8']
_LOGGER = logging.getLogger(__name__)
DEFAULT_NAME = 'myq'
NOTIFICATION_ID = 'myq_notification'
NOTIFICATION_TITLE = 'MyQ Cover Setup'
COVER_SCHEMA = vol.Schema({
vol.Required(CONF_TYPE): cv.string,
vol.Required(CONF_USERNAME): cv.string,
vol.Required(CONF_PASSWORD): cv.string
})
def setup_platform(hass, config, add_devices, discovery_info=None):
"""Set up the MyQ component."""
from pymyq import MyQAPI as pymyq
username = config.get(CONF_USERNAME)
password = config.get(CONF_PASSWORD)
brand = config.get(CONF_TYPE)
persistent_notification = loader.get_component('persistent_notification')
myq = pymyq(username, password, brand)
try:
if not myq.is_supported_brand():
raise ValueError("Unsupported type. See documentation")
if not myq.is_login_valid():
raise ValueError("Username or Password is incorrect")
add_devices(MyQDevice(myq, door) for door in myq.get_garage_doors())
return True
except (TypeError, KeyError, NameError, ValueError) as ex:
_LOGGER.error("%s", ex)
persistent_notification.create(
hass, 'Error: {}<br />'
'You will need to restart hass after fixing.'
''.format(ex),
title=NOTIFICATION_TITLE,
notification_id=NOTIFICATION_ID)
return False
class MyQDevice(CoverDevice):
"""Representation of a MyQ cover."""
def __init__(self, myq, device):
"""Initialize with API object, device id."""
self.myq = myq
self.device_id = device['deviceid']
self._name = device['name']
self._status = STATE_CLOSED
@property
def should_poll(self):
"""Poll for state."""
return True
@property
def name(self):
"""Return the name of the garage door if any."""
return self._name if self._name else DEFAULT_NAME
@property
def is_closed(self):
"""Return true if cover is closed, else False."""
return self._status == STATE_CLOSED
def close_cover(self):
"""Issue close command to cover."""
self.myq.close_device(self.device_id)
def open_cover(self):
"""Issue open command to cover."""
self.myq.open_device(self.device_id)
def update(self):
"""Update status of cover."""
self._status = self.myq.get_status(self.device_id)
| apache-2.0 | -2,589,647,039,719,210,500 | 28.111111 | 77 | 0.649202 | false | 3.832447 | false | false | false |
destijl/grr | grr/lib/key_utils.py | 2 | 3080 | #!/usr/bin/env python
"""This file abstracts the loading of the private key."""
from cryptography import x509
from cryptography.hazmat.backends import openssl
from cryptography.hazmat.primitives import hashes
from cryptography.x509 import oid
from grr.lib import rdfvalue
from grr.lib.rdfvalues import crypto as rdf_crypto
def MakeCASignedCert(common_name,
private_key,
ca_cert,
ca_private_key,
serial_number=2):
"""Make a cert and sign it with the CA's private key."""
public_key = private_key.GetPublicKey()
builder = x509.CertificateBuilder()
builder = builder.issuer_name(ca_cert.GetIssuer())
subject = x509.Name(
[x509.NameAttribute(oid.NameOID.COMMON_NAME, common_name)])
builder = builder.subject_name(subject)
valid_from = rdfvalue.RDFDatetime.Now() - rdfvalue.Duration("1d")
valid_until = rdfvalue.RDFDatetime.Now() + rdfvalue.Duration("3650d")
builder = builder.not_valid_before(valid_from.AsDatetime())
builder = builder.not_valid_after(valid_until.AsDatetime())
builder = builder.serial_number(serial_number)
builder = builder.public_key(public_key.GetRawPublicKey())
builder = builder.add_extension(
x509.BasicConstraints(
ca=False, path_length=None), critical=True)
certificate = builder.sign(
private_key=ca_private_key.GetRawPrivateKey(),
algorithm=hashes.SHA256(),
backend=openssl.backend)
return rdf_crypto.RDFX509Cert(certificate)
def MakeCACert(private_key,
common_name=u"grr",
issuer_cn=u"grr_test",
issuer_c=u"US"):
"""Generate a CA certificate.
Args:
private_key: The private key to use.
common_name: Name for cert.
issuer_cn: Name for issuer.
issuer_c: Country for issuer.
Returns:
The certificate.
"""
public_key = private_key.GetPublicKey()
builder = x509.CertificateBuilder()
issuer = x509.Name([
x509.NameAttribute(oid.NameOID.COMMON_NAME, issuer_cn),
x509.NameAttribute(oid.NameOID.COUNTRY_NAME, issuer_c)
])
subject = x509.Name(
[x509.NameAttribute(oid.NameOID.COMMON_NAME, common_name)])
builder = builder.subject_name(subject)
builder = builder.issuer_name(issuer)
valid_from = rdfvalue.RDFDatetime.Now() - rdfvalue.Duration("1d")
valid_until = rdfvalue.RDFDatetime.Now() + rdfvalue.Duration("3650d")
builder = builder.not_valid_before(valid_from.AsDatetime())
builder = builder.not_valid_after(valid_until.AsDatetime())
builder = builder.serial_number(1)
builder = builder.public_key(public_key.GetRawPublicKey())
builder = builder.add_extension(
x509.BasicConstraints(
ca=True, path_length=None), critical=True)
builder = builder.add_extension(
x509.SubjectKeyIdentifier.from_public_key(public_key.GetRawPublicKey()),
critical=False)
certificate = builder.sign(
private_key=private_key.GetRawPrivateKey(),
algorithm=hashes.SHA256(),
backend=openssl.backend)
return rdf_crypto.RDFX509Cert(certificate)
| apache-2.0 | -7,206,638,405,950,660,000 | 31.765957 | 78 | 0.69513 | false | 3.589744 | false | false | false |
bbrezillon/linux-sunxi | scripts/gdb/linux/symbols.py | 68 | 6310 | #
# gdb helper commands and functions for Linux kernel debugging
#
# load kernel and module symbols
#
# Copyright (c) Siemens AG, 2011-2013
#
# Authors:
# Jan Kiszka <jan.kiszka@siemens.com>
#
# This work is licensed under the terms of the GNU GPL version 2.
#
import gdb
import os
import re
from linux import modules
if hasattr(gdb, 'Breakpoint'):
class LoadModuleBreakpoint(gdb.Breakpoint):
def __init__(self, spec, gdb_command):
super(LoadModuleBreakpoint, self).__init__(spec, internal=True)
self.silent = True
self.gdb_command = gdb_command
def stop(self):
module = gdb.parse_and_eval("mod")
module_name = module['name'].string()
cmd = self.gdb_command
# enforce update if object file is not found
cmd.module_files_updated = False
# Disable pagination while reporting symbol (re-)loading.
# The console input is blocked in this context so that we would
# get stuck waiting for the user to acknowledge paged output.
show_pagination = gdb.execute("show pagination", to_string=True)
pagination = show_pagination.endswith("on.\n")
gdb.execute("set pagination off")
if module_name in cmd.loaded_modules:
gdb.write("refreshing all symbols to reload module "
"'{0}'\n".format(module_name))
cmd.load_all_symbols()
else:
cmd.load_module_symbols(module)
# restore pagination state
gdb.execute("set pagination %s" % ("on" if pagination else "off"))
return False
class LxSymbols(gdb.Command):
"""(Re-)load symbols of Linux kernel and currently loaded modules.
The kernel (vmlinux) is taken from the current working directly. Modules (.ko)
are scanned recursively, starting in the same directory. Optionally, the module
search path can be extended by a space separated list of paths passed to the
lx-symbols command."""
module_paths = []
module_files = []
module_files_updated = False
loaded_modules = []
breakpoint = None
def __init__(self):
super(LxSymbols, self).__init__("lx-symbols", gdb.COMMAND_FILES,
gdb.COMPLETE_FILENAME)
def _update_module_files(self):
self.module_files = []
for path in self.module_paths:
gdb.write("scanning for modules in {0}\n".format(path))
for root, dirs, files in os.walk(path):
for name in files:
if name.endswith(".ko"):
self.module_files.append(root + "/" + name)
self.module_files_updated = True
def _get_module_file(self, module_name):
module_pattern = ".*/{0}\.ko$".format(
module_name.replace("_", r"[_\-]"))
for name in self.module_files:
if re.match(module_pattern, name) and os.path.exists(name):
return name
return None
def _section_arguments(self, module):
try:
sect_attrs = module['sect_attrs'].dereference()
except gdb.error:
return ""
attrs = sect_attrs['attrs']
section_name_to_address = {
attrs[n]['name'].string(): attrs[n]['address']
for n in range(int(sect_attrs['nsections']))}
args = []
for section_name in [".data", ".data..read_mostly", ".rodata", ".bss"]:
address = section_name_to_address.get(section_name)
if address:
args.append(" -s {name} {addr}".format(
name=section_name, addr=str(address)))
return "".join(args)
def load_module_symbols(self, module):
module_name = module['name'].string()
module_addr = str(module['core_layout']['base']).split()[0]
module_file = self._get_module_file(module_name)
if not module_file and not self.module_files_updated:
self._update_module_files()
module_file = self._get_module_file(module_name)
if module_file:
gdb.write("loading @{addr}: {filename}\n".format(
addr=module_addr, filename=module_file))
cmdline = "add-symbol-file {filename} {addr}{sections}".format(
filename=module_file,
addr=module_addr,
sections=self._section_arguments(module))
gdb.execute(cmdline, to_string=True)
if module_name not in self.loaded_modules:
self.loaded_modules.append(module_name)
else:
gdb.write("no module object found for '{0}'\n".format(module_name))
def load_all_symbols(self):
gdb.write("loading vmlinux\n")
# Dropping symbols will disable all breakpoints. So save their states
# and restore them afterward.
saved_states = []
if hasattr(gdb, 'breakpoints') and not gdb.breakpoints() is None:
for bp in gdb.breakpoints():
saved_states.append({'breakpoint': bp, 'enabled': bp.enabled})
# drop all current symbols and reload vmlinux
gdb.execute("symbol-file", to_string=True)
gdb.execute("symbol-file vmlinux")
self.loaded_modules = []
module_list = modules.module_list()
if not module_list:
gdb.write("no modules found\n")
else:
[self.load_module_symbols(module) for module in module_list]
for saved_state in saved_states:
saved_state['breakpoint'].enabled = saved_state['enabled']
def invoke(self, arg, from_tty):
self.module_paths = arg.split()
self.module_paths.append(os.getcwd())
# enforce update
self.module_files = []
self.module_files_updated = False
self.load_all_symbols()
if hasattr(gdb, 'Breakpoint'):
if self.breakpoint is not None:
self.breakpoint.delete()
self.breakpoint = None
self.breakpoint = LoadModuleBreakpoint(
"kernel/module.c:do_init_module", self)
else:
gdb.write("Note: symbol update on module loading not supported "
"with this gdb version\n")
LxSymbols()
| gpl-2.0 | -3,705,187,531,682,248,700 | 34.852273 | 79 | 0.58225 | false | 4.145861 | false | false | false |
dharmabumstead/ansible | lib/ansible/plugins/action/command.py | 117 | 1121 | # Copyright: (c) 2017, Ansible Project
# 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
from ansible import constants as C
from ansible.plugins.action import ActionBase
from ansible.utils.vars import merge_hash
class ActionModule(ActionBase):
def run(self, tmp=None, task_vars=None):
self._supports_async = True
results = super(ActionModule, self).run(tmp, task_vars)
del tmp # tmp no longer has any effect
# Command module has a special config option to turn off the command nanny warnings
if 'warn' not in self._task.args:
self._task.args['warn'] = C.COMMAND_WARNINGS
wrap_async = self._task.async_val and not self._connection.has_native_async
results = merge_hash(results, self._execute_module(task_vars=task_vars, wrap_async=wrap_async))
if not wrap_async:
# remove a temporary path we created
self._remove_tmp_path(self._connection._shell.tmpdir)
return results
| gpl-3.0 | 6,676,477,658,934,152,000 | 36.366667 | 103 | 0.683318 | false | 3.8 | false | false | false |
TESScience/httm | httm/transformations/metadata.py | 1 | 5125 | # HTTM: A transformation library for RAW and Electron Flux TESS Images
# Copyright (C) 2016, 2017 John Doty and Matthew Wampler-Doty of Noqsi Aerospace, Ltd.
#
# 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/>.
"""
``httm.transformations.metadata``
=================================
This module contains metadata related to transformation functions.
- ``electron_flux_transformations`` is metadata describing transformation functions from images in
electron counts to simulated raw images in *Analogue to Digital Converter Units* (ADU).
- ``raw_transformations`` is metadata describing transformation functions from raw images in
*Analogue to Digital Converter Units* (ADU) to calibrated images in electron counts.
"""
from collections import OrderedDict
from .raw_converters_to_calibrated import remove_pattern_noise, convert_adu_to_electrons, remove_baseline, \
remove_start_of_line_ringing, remove_undershoot, remove_smear
from .electron_flux_converters_to_raw import introduce_smear_rows, add_shot_noise, simulate_blooming, \
add_readout_noise, simulate_undershoot, simulate_start_of_line_ringing, add_baseline, convert_electrons_to_adu, \
add_pattern_noise
electron_flux_transformations = OrderedDict([
('introduce_smear_rows', {
'default': True,
'documentation': 'Introduce *smear rows* to each slice of the image.',
'function': introduce_smear_rows,
}),
('add_shot_noise', {
'default': True,
'documentation': 'Add *shot noise* to each pixel in each slice of the image.',
'function': add_shot_noise,
}),
('simulate_blooming', {
'default': True,
'documentation': 'Simulate *blooming* on for each column for each slice of the image.',
'function': simulate_blooming,
}),
('add_readout_noise', {
'default': True,
'documentation': 'Add *readout noise* to each pixel in each slice of the image.',
'function': add_readout_noise,
}),
('simulate_undershoot', {
'default': True,
'documentation': 'Simulate *undershoot* on each row of each slice in the image.',
'function': simulate_undershoot,
}),
('simulate_start_of_line_ringing', {
'default': True,
'documentation': 'Simulate *start of line ringing* on each row of each slice in the image.',
'function': simulate_start_of_line_ringing,
}),
('add_baseline', {
'default': True,
'documentation': 'Add a *baseline electron count* to each slice in the image.',
'function': add_baseline,
}),
('convert_electrons_to_adu', {
'default': True,
'documentation': 'Convert the image from having pixel units in electron counts to '
'*Analogue to Digital Converter Units* (ADU).',
'function': convert_electrons_to_adu,
}),
('add_pattern_noise', {
'default': True,
'documentation': 'Add a fixed *pattern noise* to each slice in the image.',
'function': add_pattern_noise,
}),
])
raw_transformations = OrderedDict([
('remove_pattern_noise', {
'default': True,
'documentation': 'Compensate for a fixed *pattern noise* on each slice of the image.',
'function': remove_pattern_noise,
}),
('convert_adu_to_electrons', {
'default': True,
'documentation': 'Convert the image from having units in '
'*Analogue to Digital Converter Units* (ADU) '
'to electron counts.',
'function': convert_adu_to_electrons,
}),
('remove_baseline', {
'default': True,
'documentation': 'Average the pixels in the dark columns and subtract '
'the result from each pixel in the image.',
'function': remove_baseline,
}),
('remove_start_of_line_ringing', {
'default': True,
'documentation': 'Compensate for *start of line ringing* on each row of each slice of the image.',
'function': remove_start_of_line_ringing,
}),
('remove_undershoot', {
'default': True,
'documentation': 'Compensate for *undershoot* for each row of each slice of the image.',
'function': remove_undershoot,
}),
('remove_smear', {
'default': True,
'documentation': 'Compensate for *smear* in the image by reading it from the '
'*smear rows* each slice and removing it from the rest of the slice.',
'function': remove_smear,
}),
])
| gpl-3.0 | 368,438,116,170,356,100 | 41.008197 | 117 | 0.642537 | false | 3.921194 | false | false | false |
aguedes/bluez | test/sap_client.py | 86 | 30639 | """ Copyright (C) 2010-2011 ST-Ericsson SA """
""" Author: Szymon Janc <szymon.janc@tieto.com> for ST-Ericsson. """
""" 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 St, Fifth Floor, Boston, MA 02110-1301 USA """
from array import array
from bluetooth import *
import time
import re
class SAPParam:
""" SAP Parameter Class """
MaxMsgSize = 0x00
ConnectionStatus = 0x01
ResultCode = 0x02
DisconnectionType = 0x03
CommandAPDU = 0x04
ResponseAPDU = 0x05
ATR = 0x06
CardReaderStatus = 0x07
StatusChange = 0x08
TransportProtocol = 0x09
CommandAPDU7816 = 0x10
def __init__(self, name, id, value = None):
self.name = name
self.id = id
self.value = value
def _padding(self, buf):
pad = array('B')
while ( (len(buf) + len(pad)) % 4 ) != 0:
pad.append(0)
return pad
def _basicCheck(self, buf):
if len(buf) < 4 or (len(buf) % 4) != 0 or buf[1] != 0:
return (-1, -1)
if buf[0] != self.id:
return (-1, -1)
plen = buf[2] * 256 + buf[3] + 4
if plen > len(buf):
return (-1, -1)
pad = plen
while (pad % 4) != 0:
if buf[pad] != 0:
return (-1, -1)
pad+=1
return (plen, pad)
def getID(self):
return self.id
def getValue(self):
return self.value
def getContent(self):
return "%s(id=0x%.2X), value=%s \n" % (self.name, self.id, self.value)
def serialize(self):
a = array('B', '\00\00\00\00')
a[0] = self.id
a[1] = 0 # reserved
a[2] = 0 # length
a[3] = 1 # length
a.append(self.value)
a.extend(self._padding(a))
return a
def deserialize(self, buf):
p = self._basicCheck(buf)
if p[0] == -1:
return -1
self.id = buf[0]
self.value = buf[4]
return p[1]
class SAPParam_MaxMsgSize(SAPParam):
"""MaxMsgSize Param """
def __init__(self, value = None):
SAPParam.__init__(self,"MaxMsgSize", SAPParam.MaxMsgSize, value)
self.__validate()
def __validate(self):
if self.value > 0xFFFF:
self.value = 0xFFFF
def serialize(self):
a = array('B', '\00\00\00\00')
a[0] = self.id
a[3] = 2
a.append(self.value / 256)
a.append(self.value % 256)
a.extend(self._padding(a))
return a
def deserialize(self, buf):
p = self._basicCheck(buf)
if p[0] == -1 :
return -1
self.value = buf[4] * 256 + buf[5]
return p[1]
class SAPParam_CommandAPDU(SAPParam):
def __init__(self, value = None):
if value is None:
SAPParam.__init__(self, "CommandAPDU", SAPParam.CommandAPDU, array('B'))
else:
SAPParam.__init__(self, "CommandAPDU", SAPParam.CommandAPDU, array('B', value))
def serialize(self):
a = array('B', '\00\00\00\00')
a[0] = self.id
plen = len(self.value)
a[2] = plen / 256
a[3] = plen % 256
a.extend(self.value)
a.extend(self._padding(a))
return a
def deserialize(self, buf):
p = self._basicCheck(buf)
if p[0] == -1:
return -1
self.value = buf[4:p[0]]
return p[1]
class SAPParam_ResponseAPDU(SAPParam_CommandAPDU):
"""ResponseAPDU Param """
def __init__(self, value = None):
if value is None:
SAPParam.__init__(self, "ResponseAPDU", SAPParam.ResponseAPDU, array('B'))
else:
SAPParam.__init__(self, "ResponseAPDU", SAPParam.ResponseAPDU, array('B', value))
class SAPParam_ATR(SAPParam_CommandAPDU):
"""ATR Param """
def __init__(self, value = None):
if value is None:
SAPParam.__init__(self, "ATR", SAPParam.ATR, array('B'))
else:
SAPParam.__init__(self, "ATR", SAPParam.ATR, array('B', value))
class SAPParam_CommandAPDU7816(SAPParam_CommandAPDU):
"""Command APDU7816 Param."""
def __init__(self, value = None):
if value is None:
SAPParam.__init__(self, "CommandAPDU7816", SAPParam.CommandAPDU7816, array('B'))
else:
SAPParam.__init__(self, "CommandAPDU7816", SAPParam.CommandAPDU7816, array('B', value))
class SAPParam_ConnectionStatus(SAPParam):
"""Connection status Param."""
def __init__(self, value = None):
SAPParam.__init__(self,"ConnectionStatus", SAPParam.ConnectionStatus, value)
self.__validate()
def __validate(self):
if self.value is not None and self.value not in (0x00, 0x01, 0x02, 0x03, 0x04):
print "Warning. ConnectionStatus value in reserved range (0x%x)" % self.value
def deserialize(self, buf):
ret = SAPParam.deserialize(self, buf)
if ret == -1:
return -1
self.__validate()
return ret
class SAPParam_ResultCode(SAPParam):
""" Result Code Param """
def __init__(self, value = None):
SAPParam.__init__(self,"ResultCode", SAPParam.ResultCode, value)
self.__validate()
def __validate(self):
if self.value is not None and self.value not in (0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07):
print "Warning. ResultCode value in reserved range (0x%x)" % self.value
def deserialize(self, buf):
ret = SAPParam.deserialize(self, buf)
if ret == -1:
return -1
self.__validate()
return ret
class SAPParam_DisconnectionType(SAPParam):
"""Disconnection Type Param."""
def __init__(self, value = None):
SAPParam.__init__(self,"DisconnectionType", SAPParam.DisconnectionType, value)
self.__validate()
def __validate(self):
if self.value is not None and self.value not in (0x00, 0x01):
print "Warning. DisconnectionType value in reserved range (0x%x)" % self.value
def deserialize(self, buf):
ret = SAPParam.deserialize(self, buf)
if ret == -1:
return -1
self.__validate()
return ret
class SAPParam_CardReaderStatus(SAPParam_CommandAPDU):
"""Card reader Status Param."""
def __init__(self, value = None):
if value is None:
SAPParam.__init__(self, "CardReaderStatus", SAPParam.CardReaderStatus, array('B'))
else:
SAPParam.__init__(self, "CardReaderStatus", SAPParam.CardReaderStatus, array('B', value))
class SAPParam_StatusChange(SAPParam):
"""Status Change Param """
def __init__(self, value = None):
SAPParam.__init__(self,"StatusChange", SAPParam.StatusChange, value)
def __validate(self):
if self.value is not None and self.value not in (0x00, 0x01, 0x02, 0x03, 0x04, 0x05):
print "Warning. StatusChange value in reserved range (0x%x)" % self.value
def deserialize(self, buf):
ret = SAPParam.deserialize(self, buf)
if ret == -1:
return -1
self.__validate()
return ret
class SAPParam_TransportProtocol(SAPParam):
"""Transport Protocol Param """
def __init__(self, value = None):
SAPParam.__init__(self,"TransportProtocol", SAPParam.TransportProtocol, value)
self.__validate()
def __validate(self):
if self.value is not None and self.value not in (0x00, 0x01):
print "Warning. TransportProtoco value in reserved range (0x%x)" % self.value
def deserialize(self, buf):
ret = SAPParam.deserialize(self, buf)
if ret == -1:
return -1
self.__validate()
return ret
class SAPMessage:
CONNECT_REQ = 0x00
CONNECT_RESP = 0x01
DISCONNECT_REQ = 0x02
DISCONNECT_RESP =0x03
DISCONNECT_IND = 0x04
TRANSFER_APDU_REQ = 0x05
TRANSFER_APDU_RESP = 0x06
TRANSFER_ATR_REQ = 0x07
TRANSFER_ATR_RESP = 0x08
POWER_SIM_OFF_REQ = 0x09
POWER_SIM_OFF_RESP = 0x0A
POWER_SIM_ON_REQ = 0x0B
POWER_SIM_ON_RESP = 0x0C
RESET_SIM_REQ = 0x0D
RESET_SIM_RESP = 0x0E
TRANSFER_CARD_READER_STATUS_REQ = 0x0F
TRANSFER_CARD_READER_STATUS_RESP = 0x10
STATUS_IND = 0x11
ERROR_RESP = 0x12
SET_TRANSPORT_PROTOCOL_REQ = 0x13
SET_TRANSPORT_PROTOCOL_RESP = 0x14
def __init__(self, name, id):
self.name = name
self.id = id
self.params = []
self.buf = array('B')
def _basicCheck(self, buf):
if len(buf) < 4 or (len(buf) % 4) != 0 :
return False
if buf[0] != self.id:
return False
return True
def getID(self):
return self.id
def getContent(self):
s = "%s(id=0x%.2X) " % (self.name, self.id)
if len( self.buf): s = s + "[%s]" % re.sub("(.{2})", "0x\\1 " , self.buf.tostring().encode("hex").upper(), re.DOTALL)
s = s + "\n\t"
for p in self.params:
s = s + "\t" + p.getContent()
return s
def getParams(self):
return self.params
def addParam(self, param):
self.params.append(param)
def serialize(self):
ret = array('B', '\00\00\00\00')
ret[0] = self.id
ret[1] = len(self.params)
ret[2] = 0 # reserved
ret[3] = 0 # reserved
for p in self.params:
ret.extend(p.serialize())
self.buf = ret
return ret
def deserialize(self, buf):
self.buf = buf
return len(buf) == 4 and buf[1] == 0 and self._basicCheck(buf)
class SAPMessage_CONNECT_REQ(SAPMessage):
def __init__(self, MaxMsgSize = None):
SAPMessage.__init__(self,"CONNECT_REQ", SAPMessage.CONNECT_REQ)
if MaxMsgSize is not None:
self.addParam(SAPParam_MaxMsgSize(MaxMsgSize))
def _validate(self):
if len(self.params) == 1:
if self.params[0].getID() == SAPParam.MaxMsgSize:
return True
return False
def deserialize(self, buf):
self.buf = buf
self.params[:] = []
if SAPMessage._basicCheck(self, buf):
p = SAPParam_MaxMsgSize()
if p.deserialize(buf[4:]) == len(buf[4:]):
self.addParam(p)
return self._validate()
return False
class SAPMessage_CONNECT_RESP(SAPMessage):
def __init__(self, ConnectionStatus = None, MaxMsgSize = None):
SAPMessage.__init__(self,"CONNECT_RESP", SAPMessage.CONNECT_RESP)
if ConnectionStatus is not None:
self.addParam(SAPParam_ConnectionStatus(ConnectionStatus))
if MaxMsgSize is not None:
self.addParam(SAPParam_MaxMsgSize(MaxMsgSize))
def _validate(self):
if len(self.params) > 0:
if self.params[0] .getID() == SAPParam.ConnectionStatus:
if self.params[0].getValue() == 0x02:
if len(self.params) == 2:
return True
else:
if len(self.params) == 1:
return True
return False
def deserialize(self, buf):
self.buf = buf
self.params[:] = []
if SAPMessage._basicCheck(self, buf):
p = SAPParam_ConnectionStatus()
r = p.deserialize(buf[4:])
if r != -1:
self.addParam(p)
if buf[1] == 2:
p = SAPParam_MaxMsgSize()
r = p.deserialize(buf[4+r:])
if r != -1:
self.addParam(p)
return self._validate()
return False
class SAPMessage_DISCONNECT_REQ(SAPMessage):
def __init__(self):
SAPMessage.__init__(self,"DISCONNECT_REQ", SAPMessage.DISCONNECT_REQ)
class SAPMessage_DISCONNECT_RESP(SAPMessage):
def __init__(self):
SAPMessage.__init__(self,"DISCONNECT_RESP", SAPMessage.DISCONNECT_RESP)
class SAPMessage_DISCONNECT_IND(SAPMessage):
def __init__(self, Type = None):
SAPMessage.__init__(self,"DISCONNECT_IND", SAPMessage.DISCONNECT_IND)
if Type is not None:
self.addParam(SAPParam_DisconnectionType(Type))
def _validate(self):
if len(self.params) == 1:
if self.params[0].getID() == SAPParam.DisconnectionType:
return True
return False
def deserialize(self, buf):
self.buf = buf
self.params[:] = []
if SAPMessage._basicCheck(self, buf):
p = SAPParam_DisconnectionType()
if p.deserialize(buf[4:]) == len(buf[4:]):
self.addParam(p)
return self._validate()
return False
class SAPMessage_TRANSFER_APDU_REQ(SAPMessage):
def __init__(self, APDU = None, T = False):
SAPMessage.__init__(self,"TRANSFER_APDU_REQ", SAPMessage.TRANSFER_APDU_REQ)
if APDU is not None:
if T :
self.addParam(SAPParam_CommandAPDU(APDU))
else:
self.addParam(SAPParam_CommandAPDU7816(APDU))
def _validate(self):
if len(self.params) == 1:
if self.params[0].getID() == SAPParam.CommandAPDU or self.params[0].getID() == SAPParam.CommandAPDU7816:
return True
return False
def deserialize(self, buf):
self.buf = buf
self.params[:] = []
if SAPMessage._basicCheck(self, buf):
p = SAPParam_CommandAPDU()
p2 = SAPParam_CommandAPDU7816()
if p.deserialize(buf[4:]) == len(buf[4:]):
self.addParam(p)
return self._validate()
elif p2.deserialize(buf[4:]) == len(buf[4:]):
self.addParam(p2)
return self._validate()
return False
class SAPMessage_TRANSFER_APDU_RESP(SAPMessage):
def __init__(self, ResultCode = None, Response = None):
SAPMessage.__init__(self,"TRANSFER_APDU_RESP", SAPMessage.TRANSFER_APDU_RESP)
if ResultCode is not None:
self.addParam(SAPParam_ResultCode(ResultCode))
if Response is not None:
self.addParam(SAPParam_ResponseAPDU(Response))
def _validate(self):
if len(self.params) > 0:
if self.params[0] .getID() == SAPParam.ResultCode:
if self.params[0].getValue() == 0x00:
if len(self.params) == 2:
return True
else:
if len(self.params) == 1:
return True
return False
def deserialize(self, buf):
self.buf = buf
self.params[:] = []
if SAPMessage._basicCheck(self, buf):
p = SAPParam_ResultCode()
r = p.deserialize(buf[4:])
if r != -1:
self.addParam(p)
if buf[1] == 2:
p = SAPParam_ResponseAPDU()
r = p.deserialize(buf[4+r:])
if r != -1:
self.addParam(p)
return self._validate()
return False
class SAPMessage_TRANSFER_ATR_REQ(SAPMessage):
def __init__(self):
SAPMessage.__init__(self,"TRANSFER_ATR_REQ", SAPMessage.TRANSFER_ATR_REQ)
class SAPMessage_TRANSFER_ATR_RESP(SAPMessage):
def __init__(self, ResultCode = None, ATR = None):
SAPMessage.__init__(self,"TRANSFER_ATR_RESP", SAPMessage.TRANSFER_ATR_RESP)
if ResultCode is not None:
self.addParam(SAPParam_ResultCode(ResultCode))
if ATR is not None:
self.addParam(SAPParam_ATR(ATR))
def _validate(self):
if len(self.params) > 0:
if self.params[0] .getID() == SAPParam.ResultCode:
if self.params[0].getValue() == 0x00:
if len(self.params) == 2:
return True
else:
if len(self.params) == 1:
return True
return False
def deserialize(self, buf):
self.buf = buf
self.params[:] = []
if SAPMessage._basicCheck(self, buf):
p = SAPParam_ResultCode()
r = p.deserialize(buf[4:])
if r != -1:
self.addParam(p)
if buf[1] == 2:
p = SAPParam_ATR()
r = p.deserialize(buf[4+r:])
if r != -1:
self.addParam(p)
return self._validate()
return False
class SAPMessage_POWER_SIM_OFF_REQ(SAPMessage):
def __init__(self):
SAPMessage.__init__(self,"POWER_SIM_OFF_REQ", SAPMessage.POWER_SIM_OFF_REQ)
class SAPMessage_POWER_SIM_OFF_RESP(SAPMessage):
def __init__(self, ResultCode = None):
SAPMessage.__init__(self,"POWER_SIM_OFF_RESP", SAPMessage.POWER_SIM_OFF_RESP)
if ResultCode is not None:
self.addParam(SAPParam_ResultCode(ResultCode))
def _validate(self):
if len(self.params) == 1:
if self.params[0].getID() == SAPParam.ResultCode:
return True
return False
def deserialize(self, buf):
self.buf = buf
self.params[:] = []
if SAPMessage._basicCheck(self, buf):
p = SAPParam_ResultCode()
if p.deserialize(buf[4:]) == len(buf[4:]):
self.addParam(p)
return self._validate()
return False
class SAPMessage_POWER_SIM_ON_REQ(SAPMessage):
def __init__(self):
SAPMessage.__init__(self,"POWER_SIM_ON_REQ", SAPMessage.POWER_SIM_ON_REQ)
class SAPMessage_POWER_SIM_ON_RESP(SAPMessage_POWER_SIM_OFF_RESP):
def __init__(self, ResultCode = None):
SAPMessage.__init__(self,"POWER_SIM_ON_RESP", SAPMessage.POWER_SIM_ON_RESP)
if ResultCode is not None:
self.addParam(SAPParam_ResultCode(ResultCode))
class SAPMessage_RESET_SIM_REQ(SAPMessage):
def __init__(self):
SAPMessage.__init__(self,"RESET_SIM_REQ", SAPMessage.RESET_SIM_REQ)
class SAPMessage_RESET_SIM_RESP(SAPMessage_POWER_SIM_OFF_RESP):
def __init__(self, ResultCode = None):
SAPMessage.__init__(self,"RESET_SIM_RESP", SAPMessage.RESET_SIM_RESP)
if ResultCode is not None:
self.addParam(SAPParam_ResultCode(ResultCode))
class SAPMessage_STATUS_IND(SAPMessage):
def __init__(self, StatusChange = None):
SAPMessage.__init__(self,"STATUS_IND", SAPMessage.STATUS_IND)
if StatusChange is not None:
self.addParam(SAPParam_StatusChange(StatusChange))
def _validate(self):
if len(self.params) == 1:
if self.params[0].getID() == SAPParam.StatusChange:
return True
return False
def deserialize(self, buf):
self.buf = buf
self.params[:] = []
if SAPMessage._basicCheck(self, buf):
p = SAPParam_StatusChange()
if p.deserialize(buf[4:]) == len(buf[4:]):
self.addParam(p)
return self._validate()
return False
class SAPMessage_TRANSFER_CARD_READER_STATUS_REQ(SAPMessage):
def __init__(self):
SAPMessage.__init__(self,"TRANSFER_CARD_READER_STATUS_REQ", SAPMessage.TRANSFER_CARD_READER_STATUS_REQ)
class SAPMessage_TRANSFER_CARD_READER_STATUS_RESP(SAPMessage):
def __init__(self, ResultCode = None, Status = None):
SAPMessage.__init__(self,"TRANSFER_CARD_READER_STATUS_RESP", SAPMessage.TRANSFER_CARD_READER_STATUS_RESP)
if ResultCode is not None:
self.addParam(SAPParam_ResultCode(ResultCode))
if Status is not None:
self.addParam(SAPParam_CardReaderStatus(Status))
def _validate(self):
if len(self.params) > 0:
if self.params[0] .getID() == SAPParam.ResultCode:
if self.params[0].getValue() == 0x00:
if len(self.params) == 2:
return True
else:
if len(self.params) == 1:
return True
return False
def deserialize(self, buf):
self.buf = buf
self.params[:] = []
if SAPMessage._basicCheck(self, buf):
p = SAPParam_ResultCode()
r = p.deserialize(buf[4:])
if r != -1:
self.addParam(p)
if buf[1] == 2:
p = SAPParam_CardReaderStatus()
r = p.deserialize(buf[4+r:])
if r != -1:
self.addParam(p)
return self._validate()
return False
class SAPMessage_ERROR_RESP(SAPMessage):
def __init__(self):
SAPMessage.__init__(self,"ERROR_RESP", SAPMessage.ERROR_RESP)
class SAPMessage_SET_TRANSPORT_PROTOCOL_REQ(SAPMessage):
def __init__(self, protocol = None):
SAPMessage.__init__(self,"SET_TRANSPORT_PROTOCOL_REQ", SAPMessage.SET_TRANSPORT_PROTOCOL_REQ)
if protocol is not None:
self.addParam(SAPParam_TransportProtocol(protocol))
def _validate(self):
if len(self.params) == 1:
if self.params[0].getID() == SAPParam.TransportProtocol:
return True
return False
def deserialize(self, buf):
self.buf = buf
self.params[:] = []
if SAPMessage._basicCheck(self, buf):
p = SAPParam_TransportProtocol()
if p.deserialize(buf[4:]) == len(buf[4:]):
self.addParam(p)
return self._validate()
return False
class SAPMessage_SET_TRANSPORT_PROTOCOL_RESP(SAPMessage_POWER_SIM_OFF_RESP):
def __init__(self, ResultCode = None):
SAPMessage.__init__(self,"SET_TRANSPORT_PROTOCOL_RESP", SAPMessage.SET_TRANSPORT_PROTOCOL_RESP)
if ResultCode is not None:
self.addParam(SAPParam_ResultCode(ResultCode))
class SAPClient:
CONNECTED = 1
DISCONNECTED = 0
uuid = "0000112D-0000-1000-8000-00805F9B34FB"
bufsize = 1024
timeout = 20
state = DISCONNECTED
def __init__(self, host = None, port = None):
self.sock = None
if host is None or is_valid_address(host):
self.host = host
else:
raise BluetoothError ("%s is not a valid BT address." % host)
self.host = None
return
if port is None:
self.__discover()
else:
self.port = port
self.__connectRFCOMM()
def __del__(self):
self.__disconnectRFCOMM()
def __disconnectRFCOMM(self):
if self.sock is not None:
self.sock.close()
self.state = self.DISCONNECTED
def __discover(self):
service_matches = find_service(self.uuid, self.host)
if len(service_matches) == 0:
raise BluetoothError ("No SAP service found")
return
first_match = service_matches[0]
self.port = first_match["port"]
self.host = first_match["host"]
print "SAP Service found on %s(%s)" % first_match["name"] % self.host
def __connectRFCOMM(self):
self.sock=BluetoothSocket( RFCOMM )
self.sock.connect((self.host, self.port))
self.sock.settimeout(self.timeout)
self.state = self.CONNECTED
def __sendMsg(self, msg):
if isinstance(msg, SAPMessage):
s = msg.serialize()
print "\tTX: " + msg.getContent()
return self.sock.send(s.tostring())
def __rcvMsg(self, msg):
if isinstance(msg, SAPMessage):
print "\tRX Wait: %s(id = 0x%.2x)" % (msg.name, msg.id)
data = self.sock.recv(self.bufsize)
if data:
if msg.deserialize(array('B',data)):
print "\tRX: len(%d) %s" % (len(data), msg.getContent())
return msg
else:
print "msg: %s" % array('B',data)
raise BluetoothError ("Message deserialization failed.")
else:
raise BluetoothError ("Timeout. No data received.")
def connect(self):
self.__connectRFCOMM()
def disconnect(self):
self.__disconnectRFCOMM()
def isConnected(self):
return self.state
def proc_connect(self):
try:
self.__sendMsg(SAPMessage_CONNECT_REQ(self.bufsize))
params = self.__rcvMsg(SAPMessage_CONNECT_RESP()).getParams()
if params[0].getValue() in (0x00, 0x04):
pass
elif params[0].getValue() == 0x02:
self.bufsize = params[1].getValue()
self.__sendMsg(SAPMessage_CONNECT_REQ(self.bufsize))
params = self.__rcvMsg(SAPMessage_CONNECT_RESP()).getParams()
if params[0].getValue() not in (0x00, 0x04):
return False
else:
return False
params = self.__rcvMsg(SAPMessage_STATUS_IND()).getParams()
if params[0].getValue() == 0x00:
return False
elif params[0].getValue() == 0x01:
"""OK, Card reset"""
return self.proc_transferATR()
elif params[0].getValue() == 0x02:
"""T0 not supported"""
if self.proc_transferATR():
return self.proc_setTransportProtocol(1)
else:
return False
else:
return False
except BluetoothError , e:
print "Error. " +str(e)
return False
def proc_disconnectByClient(self, timeout=0):
try:
self.__sendMsg(SAPMessage_DISCONNECT_REQ())
self.__rcvMsg(SAPMessage_DISCONNECT_RESP())
time.sleep(timeout) # let srv to close rfcomm
self.__disconnectRFCOMM()
return True
except BluetoothError , e:
print "Error. " +str(e)
return False
def proc_disconnectByServer(self, timeout=0):
try:
params = self.__rcvMsg(SAPMessage_DISCONNECT_IND()).getParams()
"""graceful"""
if params[0].getValue() == 0x00:
if not self.proc_transferAPDU():
return False
return self.proc_disconnectByClient(timeout)
except BluetoothError , e:
print "Error. " +str(e)
return False
def proc_transferAPDU(self, apdu = "Sample APDU command"):
try:
self.__sendMsg(SAPMessage_TRANSFER_APDU_REQ(apdu))
params = self.__rcvMsg(SAPMessage_TRANSFER_APDU_RESP()).getParams()
return True
except BluetoothError , e:
print "Error. " +str(e)
return False
def proc_transferATR(self):
try:
self.__sendMsg(SAPMessage_TRANSFER_ATR_REQ())
params = self.__rcvMsg(SAPMessage_TRANSFER_ATR_RESP()).getParams()
return True
except BluetoothError , e:
print "Error. " +str(e)
return False
def proc_powerSimOff(self):
try:
self.__sendMsg(SAPMessage_POWER_SIM_OFF_REQ())
params = self.__rcvMsg(SAPMessage_POWER_SIM_OFF_RESP()).getParams()
return True
except BluetoothError , e:
print "Error. " +str(e)
return False
def proc_powerSimOn(self):
try:
self.__sendMsg(SAPMessage_POWER_SIM_ON_REQ())
params = self.__rcvMsg(SAPMessage_POWER_SIM_ON_RESP()).getParams()
if params[0].getValue() == 0x00:
return self.proc_transferATR()
return True
except BluetoothError , e:
print "Error. " +str(e)
return False
def proc_resetSim(self):
try:
self.__sendMsg(SAPMessage_RESET_SIM_REQ())
params = self.__rcvMsg(SAPMessage_RESET_SIM_RESP()).getParams()
if params[0].getValue() == 0x00:
return self.proc_transferATR()
return True
except BluetoothError , e:
print "Error. " +str(e)
return False
def proc_reportStatus(self):
try:
params = self.__rcvMsg(SAPMessage_STATUS_IND()).getParams()
except BluetoothError , e:
print "Error. " +str(e)
return False
def proc_transferCardReaderStatus(self):
try:
self.__sendMsg(SAPMessage_TRANSFER_CARD_READER_STATUS_REQ())
params = self.__rcvMsg(SAPMessage_TRANSFER_CARD_READER_STATUS_RESP()).getParams()
except BluetoothError , e:
print "Error. " +str(e)
return False
def proc_errorResponse(self):
try:
""" send malformed message, no mandatory maxmsgsize parameter"""
self.__sendMsg(SAPMessage_CONNECT_REQ())
params = self.__rcvMsg(SAPMessage_ERROR_RESP()).getParams()
except BluetoothError , e:
print "Error. " +str(e)
return False
def proc_setTransportProtocol(self, protocol = 0):
try:
self.__sendMsg(SAPMessage_SET_TRANSPORT_PROTOCOL_REQ(protocol))
params = self.__rcvMsg(SAPMessage_SET_TRANSPORT_PROTOCOL_RESP()).getParams()
if params[0].getValue() == 0x00:
params = self.__rcvMsg(SAPMessage_STATUS_IND()).getParams()
if params[0].getValue() in (0x01, 0x02):
return self.proc_transferATR()
else:
return True
"""return False ???"""
elif params[0].getValue == 0x07:
"""not supported"""
return True
"""return False ???"""
else:
return False
except BluetoothError , e:
print "Error. " +str(e)
return False
if __name__ == "__main__":
pass
| gpl-2.0 | -5,468,918,267,625,201,000 | 31.490986 | 125 | 0.549561 | false | 3.621631 | false | false | false |
mvidalgarcia/indico | indico/core/webpack.py | 2 | 1598 | # This file is part of Indico.
# Copyright (C) 2002 - 2019 CERN
#
# Indico is free software; you can redistribute it and/or
# modify it under the terms of the MIT License; see the
# LICENSE file for more details.
from __future__ import unicode_literals
import os
from flask_webpackext import FlaskWebpackExt
from flask_webpackext.manifest import JinjaManifestLoader
from pywebpack import ManifestLoader
from indico.web.assets.util import get_custom_assets
class IndicoManifestLoader(JinjaManifestLoader):
cache = {}
def __init__(self, *args, **kwargs):
self.custom = kwargs.pop('custom', True)
super(IndicoManifestLoader, self).__init__(*args, **kwargs)
def load(self, filepath):
key = (filepath, os.path.getmtime(filepath))
if key not in IndicoManifestLoader.cache:
IndicoManifestLoader.cache[key] = manifest = ManifestLoader.load(self, filepath)
if self.custom:
self._add_custom_assets(manifest)
return IndicoManifestLoader.cache[key]
def _add_custom_assets(self, manifest):
# custom assets (from CUSTOMIZATION_DIR) are not part of the webpack manifest
# since they are not build with webpack (it's generally not available on the
# machine running indico), but we add them here anyway so they can be handled
# without too much extra code, e.g. when building a static site.
manifest.add(self.entry_cls('__custom.css', get_custom_assets('css')))
manifest.add(self.entry_cls('__custom.js', get_custom_assets('js')))
webpack = FlaskWebpackExt()
| mit | -9,097,333,290,528,816,000 | 36.162791 | 92 | 0.69587 | false | 3.859903 | false | false | false |
seanwestfall/django | django/views/static.py | 190 | 5142 | """
Views and functions for serving static files. These are only to be used
during development, and SHOULD NOT be used in a production setting.
"""
from __future__ import unicode_literals
import mimetypes
import os
import posixpath
import re
import stat
from django.http import (
FileResponse, Http404, HttpResponse, HttpResponseNotModified,
HttpResponseRedirect,
)
from django.template import Context, Engine, TemplateDoesNotExist, loader
from django.utils.http import http_date, parse_http_date
from django.utils.six.moves.urllib.parse import unquote
from django.utils.translation import ugettext as _, ugettext_lazy
def serve(request, path, document_root=None, show_indexes=False):
"""
Serve static files below a given point in the directory structure.
To use, put a URL pattern such as::
from django.views.static import serve
url(r'^(?P<path>.*)$', serve, {'document_root': '/path/to/my/files/'})
in your URLconf. You must provide the ``document_root`` param. You may
also set ``show_indexes`` to ``True`` if you'd like to serve a basic index
of the directory. This index view will use the template hardcoded below,
but if you'd like to override it, you can create a template called
``static/directory_index.html``.
"""
path = posixpath.normpath(unquote(path))
path = path.lstrip('/')
newpath = ''
for part in path.split('/'):
if not part:
# Strip empty path components.
continue
drive, part = os.path.splitdrive(part)
head, part = os.path.split(part)
if part in (os.curdir, os.pardir):
# Strip '.' and '..' in path.
continue
newpath = os.path.join(newpath, part).replace('\\', '/')
if newpath and path != newpath:
return HttpResponseRedirect(newpath)
fullpath = os.path.join(document_root, newpath)
if os.path.isdir(fullpath):
if show_indexes:
return directory_index(newpath, fullpath)
raise Http404(_("Directory indexes are not allowed here."))
if not os.path.exists(fullpath):
raise Http404(_('"%(path)s" does not exist') % {'path': fullpath})
# Respect the If-Modified-Since header.
statobj = os.stat(fullpath)
if not was_modified_since(request.META.get('HTTP_IF_MODIFIED_SINCE'),
statobj.st_mtime, statobj.st_size):
return HttpResponseNotModified()
content_type, encoding = mimetypes.guess_type(fullpath)
content_type = content_type or 'application/octet-stream'
response = FileResponse(open(fullpath, 'rb'), content_type=content_type)
response["Last-Modified"] = http_date(statobj.st_mtime)
if stat.S_ISREG(statobj.st_mode):
response["Content-Length"] = statobj.st_size
if encoding:
response["Content-Encoding"] = encoding
return response
DEFAULT_DIRECTORY_INDEX_TEMPLATE = """
{% load i18n %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="Content-type" content="text/html; charset=utf-8" />
<meta http-equiv="Content-Language" content="en-us" />
<meta name="robots" content="NONE,NOARCHIVE" />
<title>{% blocktrans %}Index of {{ directory }}{% endblocktrans %}</title>
</head>
<body>
<h1>{% blocktrans %}Index of {{ directory }}{% endblocktrans %}</h1>
<ul>
{% ifnotequal directory "/" %}
<li><a href="../">../</a></li>
{% endifnotequal %}
{% for f in file_list %}
<li><a href="{{ f|urlencode }}">{{ f }}</a></li>
{% endfor %}
</ul>
</body>
</html>
"""
template_translatable = ugettext_lazy("Index of %(directory)s")
def directory_index(path, fullpath):
try:
t = loader.select_template([
'static/directory_index.html',
'static/directory_index',
])
except TemplateDoesNotExist:
t = Engine().from_string(DEFAULT_DIRECTORY_INDEX_TEMPLATE)
files = []
for f in os.listdir(fullpath):
if not f.startswith('.'):
if os.path.isdir(os.path.join(fullpath, f)):
f += '/'
files.append(f)
c = Context({
'directory': path + '/',
'file_list': files,
})
return HttpResponse(t.render(c))
def was_modified_since(header=None, mtime=0, size=0):
"""
Was something modified since the user last downloaded it?
header
This is the value of the If-Modified-Since header. If this is None,
I'll just return True.
mtime
This is the modification time of the item we're talking about.
size
This is the size of the item we're talking about.
"""
try:
if header is None:
raise ValueError
matches = re.match(r"^([^;]+)(; length=([0-9]+))?$", header,
re.IGNORECASE)
header_mtime = parse_http_date(matches.group(1))
header_len = matches.group(3)
if header_len and int(header_len) != size:
raise ValueError
if int(mtime) > header_mtime:
raise ValueError
except (AttributeError, ValueError, OverflowError):
return True
return False
| bsd-3-clause | -7,987,543,726,296,927,000 | 33.05298 | 78 | 0.624854 | false | 3.931193 | false | false | false |
dionbosschieter/NetworkMonitor | src/Client/InfoContainer.py | 1 | 1892 | import terminal
import curses
import time
from curses import panel
class InfoContainer(object):
def __init__(self, stdscreen, title, debug_console):
self.debug_console = debug_console
self.height = int(terminal.height/2)
self.width = terminal.width - 2
self.title = title
self.window = stdscreen.subwin(self.height,self.width,1,1)
self.window.border(0)
self.window.addstr(0,1,title)
self.panel = panel.new_panel(self.window)
self.panel.hide()
panel.update_panels()
# Add the Border
self.second = time.time()
self.writebuffer = []
def display(self):
self.panel.top()
self.panel.show()
#self.window.clear()
def hide(self):
self.window.clear()
self.panel.hide()
panel.update_panels()
curses.doupdate()
def refresh(self):
self.window.clear()
self.window.border(0)
self.window.addstr(0,1,self.title)
#draw the last 20 log items
#foreach i from 0 till (self.height-2)
#draw string on i place
#self.writebuffer[-(self.height-2):]
maxlength = (self.height-3)
lengthofbuffer = len(self.writebuffer)
if(lengthofbuffer>maxlength):
startindex = (lengthofbuffer-1)-maxlength
else:
startindex = 0
maxlength = lengthofbuffer
for i in range(0, maxlength):
#self.window.addstr(i,1,str(i))
self.window.addstr(i+1,1,self.writebuffer[i+startindex])
self.window.refresh()
curses.doupdate()
def addPacket(self, packet):
#1 refresh per second// or 2?
if(time.time() - self.second >= 1):
self.writebuffer.append(packet)
self.second = time.time()
else:
self.writebuffer.append(packet)
| mit | 8,029,939,048,508,223,000 | 27.666667 | 68 | 0.581924 | false | 3.753968 | false | false | false |
eriol/circuits | examples/node/nodeserver.py | 3 | 2429 | #!/usr/bin/env python
"""Node Server Example
This example demonstrates how to create a very simple node server
that supports bi-diractional messaging between server and connected
clients forming a cluster of nodes.
"""
from __future__ import print_function
from os import getpid
from optparse import OptionParser
from circuits.node import Node
from circuits import Component, Debugger
__version__ = "0.0.1"
USAGE = "%prog [options]"
VERSION = "%prog v" + __version__
def parse_options():
parser = OptionParser(usage=USAGE, version=VERSION)
parser.add_option(
"-b", "--bind",
action="store", type="string",
default="0.0.0.0:8000", dest="bind",
help="Bind to address:[port]"
)
parser.add_option(
"-d", "--debug",
action="store_true",
default=False, dest="debug",
help="Enable debug mode"
)
opts, args = parser.parse_args()
return opts, args
class NodeServer(Component):
def init(self, args, opts):
"""Initialize our ``ChatServer`` Component.
This uses the convenience ``init`` method which is called after the
component is proeprly constructed and initialized and passed the
same args and kwargs that were passed during construction.
"""
self.args = args
self.opts = opts
self.clients = {}
if opts.debug:
Debugger().register(self)
if ":" in opts.bind:
address, port = opts.bind.split(":")
port = int(port)
else:
address, port = opts.bind, 8000
Node(port=port, server_ip=address).register(self)
def connect(self, sock, host, port):
"""Connect Event -- Triggered for new connecting clients"""
self.clients[sock] = {
"host": sock,
"port": port,
}
def disconnect(self, sock):
"""Disconnect Event -- Triggered for disconnecting clients"""
if sock not in self.clients:
return
del self.clients[sock]
def ready(self, server, bind):
print("Ready! Listening on {}:{}".format(*bind))
print("Waiting for remote events...")
def hello(self):
return "Hello World! ({0:d})".format(getpid())
def main():
opts, args = parse_options()
# Configure and "run" the System.
NodeServer(args, opts).run()
if __name__ == "__main__":
main()
| mit | -6,181,088,414,534,044,000 | 21.490741 | 75 | 0.59613 | false | 4.075503 | false | false | false |
krieger-od/nwjs_chromium.src | chrome/common/extensions/docs/server2/build_server.py | 80 | 3340 | #!/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.
# This script is used to copy all dependencies into the local directory.
# The package of files can then be uploaded to App Engine.
import os
import shutil
import stat
import sys
SRC_DIR = os.path.join(sys.path[0], os.pardir, os.pardir, os.pardir, os.pardir,
os.pardir)
THIRD_PARTY_DIR = os.path.join(SRC_DIR, 'third_party')
LOCAL_THIRD_PARTY_DIR = os.path.join(sys.path[0], 'third_party')
TOOLS_DIR = os.path.join(SRC_DIR, 'tools')
SCHEMA_COMPILER_FILES = ['memoize.py',
'model.py',
'idl_schema.py',
'schema_util.py',
'json_parse.py',
'json_schema.py']
def MakeInit(path):
path = os.path.join(path, '__init__.py')
with open(os.path.join(path), 'w') as f:
os.utime(os.path.join(path), None)
def OnError(function, path, excinfo):
os.chmod(path, stat.S_IWUSR)
function(path)
def CopyThirdParty(src, dest, files=None, make_init=True):
dest_path = os.path.join(LOCAL_THIRD_PARTY_DIR, dest)
if not files:
shutil.copytree(src, dest_path)
if make_init:
MakeInit(dest_path)
return
try:
os.makedirs(dest_path)
except Exception:
pass
if make_init:
MakeInit(dest_path)
for filename in files:
shutil.copy(os.path.join(src, filename), os.path.join(dest_path, filename))
def main():
if os.path.isdir(LOCAL_THIRD_PARTY_DIR):
try:
shutil.rmtree(LOCAL_THIRD_PARTY_DIR, False, OnError)
except OSError:
print('*-------------------------------------------------------------*\n'
'| If you are receiving an upload error, try removing |\n'
'| chrome/common/extensions/docs/server2/third_party manually. |\n'
'*-------------------------------------------------------------*\n')
CopyThirdParty(os.path.join(THIRD_PARTY_DIR, 'motemplate'), 'motemplate')
CopyThirdParty(os.path.join(THIRD_PARTY_DIR, 'markdown'), 'markdown',
make_init=False)
CopyThirdParty(os.path.join(SRC_DIR, 'ppapi', 'generators'),
'json_schema_compiler')
CopyThirdParty(os.path.join(THIRD_PARTY_DIR, 'ply'),
os.path.join('json_schema_compiler', 'ply'))
CopyThirdParty(os.path.join(TOOLS_DIR, 'json_schema_compiler'),
'json_schema_compiler',
SCHEMA_COMPILER_FILES)
CopyThirdParty(os.path.join(TOOLS_DIR, 'json_comment_eater'),
'json_schema_compiler',
['json_comment_eater.py'])
CopyThirdParty(os.path.join(THIRD_PARTY_DIR, 'simplejson'),
os.path.join('json_schema_compiler', 'simplejson'),
make_init=False)
MakeInit(LOCAL_THIRD_PARTY_DIR)
CopyThirdParty(os.path.join(THIRD_PARTY_DIR, 'google_appengine_cloudstorage',
'cloudstorage'), 'cloudstorage')
# To be able to use the Motemplate class we need this import in __init__.py.
with open(os.path.join(LOCAL_THIRD_PARTY_DIR,
'motemplate',
'__init__.py'), 'a') as f:
f.write('from motemplate import Motemplate\n')
if __name__ == '__main__':
main()
| bsd-3-clause | -4,363,357,893,083,128,000 | 36.52809 | 80 | 0.594611 | false | 3.380567 | false | false | false |
bijanfallah/OI_CCLM | src/RMSE_MAPS_INGO.py | 1 | 2007 | # Program to show the maps of RMSE averaged over time
import matplotlib.pyplot as plt
from sklearn.metrics import mean_squared_error
import os
from netCDF4 import Dataset as NetCDFFile
import numpy as np
from CCLM_OUTS import Plot_CCLM
# option == 1 -> shift 4 with default cclm domain and nboundlines = 3
# option == 2 -> shift 4 with smaller cclm domain and nboundlines = 3
# option == 3 -> shift 4 with smaller cclm domain and nboundlines = 6
# option == 4 -> shift 4 with corrected smaller cclm domain and nboundlines = 3
# option == 5 -> shift 4 with corrected smaller cclm domain and nboundlines = 4
# option == 6 -> shift 4 with corrected smaller cclm domain and nboundlines = 6
# option == 7 -> shift 4 with corrected smaller cclm domain and nboundlines = 9
# option == 8 -> shift 4 with corrected bigger cclm domain and nboundlines = 3
from CCLM_OUTS import Plot_CCLM
#def f(x):
# if x==-9999:
# return float('NaN')
# else:
# return x
def read_data_from_mistral(dir='/work/bb1029/b324045/work1/work/member/post/',name='member_T_2M_ts_seasmean.nc',var='T_2M'):
# type: (object, object, object) -> object
#a function to read the data from mistral work
"""
:rtype: object
"""
#CMD = 'scp $mistral:' + dir + name + ' ./'
CMD = 'wget users.met.fu-berlin.de/~BijanFallah/' + dir + name
os.system(CMD)
nc = NetCDFFile(name)
# for name2, variable in nc.variables.items():
# for attrname in variable.ncattrs():
# print(name2, variable, '-----------------',attrname)
# #print("{} -- {}".format(attrname, getattr(variable, attrname)))
os.remove(name)
lats = nc.variables['lat'][:]
lons = nc.variables['lon'][:]
t = nc.variables[var][:].squeeze()
rlats = nc.variables['rlat'][:] # extract/copy the data
rlons = nc.variables['rlon'][:]
#f2 = np.vectorize(f)
#t= f2(t)
#t=t.data
t=t.squeeze()
#print()
nc.close()
return(t, lats, lons, rlats, rlons)
| mit | 6,172,872,896,229,471,000 | 37.596154 | 124 | 0.63727 | false | 3.16063 | false | false | false |
steven-hadfield/dpxdt | deployment/appengine/appengine_config.py | 4 | 2989 | #!/usr/bin/env python
# Copyright 2013 Brett Slatkin
#
# 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.
"""App Engine configuration file.
See:
https://developers.google.com/appengine/docs/python/tools/appengineconfig
"""
import os
import logging
import os
import sys
# Log to disk for managed VMs:
# https://cloud.google.com/appengine/docs/managed-vms/custom-runtimes#logging
if os.environ.get('LOG_TO_DISK'):
log_dir = '/var/log/app_engine/custom_logs'
try:
os.makedirs(log_dir)
except OSError:
pass # Directory already exists
log_path = os.path.join(log_dir, 'app.log')
handler = logging.FileHandler(log_path)
handler.setLevel(logging.DEBUG)
handler.setFormatter(logging.Formatter(
'%(levelname)s %(filename)s:%(lineno)s] %(message)s'))
logging.getLogger().addHandler(handler)
# Load up our app and all its dependencies. Make the environment sane.
from dpxdt.tools import run_server
# Initialize flags from flags file or enviornment.
import gflags
gflags.FLAGS(['dpxdt_server', '--flagfile=flags.cfg'])
logging.info('BEGIN Flags')
for key, flag in gflags.FLAGS.FlagDict().iteritems():
logging.info('%s = %s', key, flag.value)
logging.info('END Flags')
# When in production use precompiled templates. Sometimes templates break
# in production. To debug templates there, comment this out entirely.
if os.environ.get('SERVER_SOFTWARE', '').startswith('Google App Engine'):
import jinja2
from dpxdt.server import app
app.jinja_env.auto_reload = False
app.jinja_env.loader = jinja2.ModuleLoader('templates_compiled.zip')
# Install dpxdt.server override hooks.
from dpxdt.server import api
import hooks
api._artifact_created = hooks._artifact_created
api._get_artifact_response = hooks._get_artifact_response
# Don't log when appstats is active.
appstats_DUMP_LEVEL = -1
# SQLAlchemy stacks are really deep.
appstats_MAX_STACK = 20
# Use very shallow local variable reprs to reduce noise.
appstats_MAX_DEPTH = 2
# Enable the remote shell, since the old admin interactive console doesn't
# work with managed VMs.
appstats_SHELL_OK = True
# These are only used if gae_mini_profiler was properly installed
def gae_mini_profiler_should_profile_production():
from google.appengine.api import users
return users.is_current_user_admin()
def gae_mini_profiler_should_profile_development():
return True
# Fix the appstats module's formatting helper function.
import appstats_monkey_patch
| apache-2.0 | 6,358,295,125,254,556,000 | 28.89 | 77 | 0.742389 | false | 3.694685 | false | false | false |
gangadharkadam/contributionerp | erpnext/projects/report/project_wise_stock_tracking/project_wise_stock_tracking.py | 46 | 3173 | # 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 import _
def execute(filters=None):
columns = get_columns()
proj_details = get_project_details()
pr_item_map = get_purchased_items_cost()
se_item_map = get_issued_items_cost()
dn_item_map = get_delivered_items_cost()
data = []
for project in proj_details:
data.append([project.name, pr_item_map.get(project.name, 0),
se_item_map.get(project.name, 0), dn_item_map.get(project.name, 0),
project.project_name, project.status, project.company,
project.customer, project.estimated_costing, project.expected_start_date,
project.expected_end_date])
return columns, data
def get_columns():
return [_("Project Id") + ":Link/Project:140", _("Cost of Purchased Items") + ":Currency:160",
_("Cost of Issued Items") + ":Currency:160", _("Cost of Delivered Items") + ":Currency:160",
_("Project Name") + "::120", _("Project Status") + "::120", _("Company") + ":Link/Company:100",
_("Customer") + ":Link/Customer:140", _("Project Value") + ":Currency:120",
_("Project Start Date") + ":Date:120", _("Completion Date") + ":Date:120"]
def get_project_details():
return frappe.db.sql(""" select name, project_name, status, company, customer, estimated_costing,
expected_start_date, expected_end_date from tabProject where docstatus < 2""", as_dict=1)
def get_purchased_items_cost():
pr_items = frappe.db.sql("""select project_name, sum(base_net_amount) as amount
from `tabPurchase Receipt Item` where ifnull(project_name, '') != ''
and docstatus = 1 group by project_name""", as_dict=1)
pr_item_map = {}
for item in pr_items:
pr_item_map.setdefault(item.project_name, item.amount)
return pr_item_map
def get_issued_items_cost():
se_items = frappe.db.sql("""select se.project_name, sum(se_item.amount) as amount
from `tabStock Entry` se, `tabStock Entry Detail` se_item
where se.name = se_item.parent and se.docstatus = 1 and ifnull(se_item.t_warehouse, '') = ''
and ifnull(se.project_name, '') != '' group by se.project_name""", as_dict=1)
se_item_map = {}
for item in se_items:
se_item_map.setdefault(item.project_name, item.amount)
return se_item_map
def get_delivered_items_cost():
dn_items = frappe.db.sql("""select dn.project_name, sum(dn_item.base_net_amount) as amount
from `tabDelivery Note` dn, `tabDelivery Note Item` dn_item
where dn.name = dn_item.parent and dn.docstatus = 1 and ifnull(dn.project_name, '') != ''
group by dn.project_name""", as_dict=1)
si_items = frappe.db.sql("""select si.project_name, sum(si_item.base_net_amount) as amount
from `tabSales Invoice` si, `tabSales Invoice Item` si_item
where si.name = si_item.parent and si.docstatus = 1 and ifnull(si.update_stock, 0) = 1
and ifnull(si.is_pos, 0) = 1 and ifnull(si.project_name, '') != ''
group by si.project_name""", as_dict=1)
dn_item_map = {}
for item in dn_items:
dn_item_map.setdefault(item.project_name, item.amount)
for item in si_items:
dn_item_map.setdefault(item.project_name, item.amount)
return dn_item_map
| agpl-3.0 | -2,526,490,087,109,348,000 | 39.164557 | 98 | 0.69209 | false | 2.987759 | false | false | false |
imsparsh/python-for-android | python3-alpha/extra_modules/gdata/books/__init__.py | 124 | 18532 | #!/usr/bin/python
"""
Data Models for books.service
All classes can be instantiated from an xml string using their FromString
class method.
Notes:
* Book.title displays the first dc:title because the returned XML
repeats that datum as atom:title.
There is an undocumented gbs:openAccess element that is not parsed.
"""
__author__ = "James Sams <sams.james@gmail.com>"
__copyright__ = "Apache License v2.0"
import atom
import gdata
BOOK_SEARCH_NAMESPACE = 'http://schemas.google.com/books/2008'
DC_NAMESPACE = 'http://purl.org/dc/terms'
ANNOTATION_REL = "http://schemas.google.com/books/2008/annotation"
INFO_REL = "http://schemas.google.com/books/2008/info"
LABEL_SCHEME = "http://schemas.google.com/books/2008/labels"
PREVIEW_REL = "http://schemas.google.com/books/2008/preview"
THUMBNAIL_REL = "http://schemas.google.com/books/2008/thumbnail"
FULL_VIEW = "http://schemas.google.com/books/2008#view_all_pages"
PARTIAL_VIEW = "http://schemas.google.com/books/2008#view_partial"
NO_VIEW = "http://schemas.google.com/books/2008#view_no_pages"
UNKNOWN_VIEW = "http://schemas.google.com/books/2008#view_unknown"
EMBEDDABLE = "http://schemas.google.com/books/2008#embeddable"
NOT_EMBEDDABLE = "http://schemas.google.com/books/2008#not_embeddable"
class _AtomFromString(atom.AtomBase):
#@classmethod
def FromString(cls, s):
return atom.CreateClassFromXMLString(cls, s)
FromString = classmethod(FromString)
class Creator(_AtomFromString):
"""
The <dc:creator> element identifies an author-or more generally, an entity
responsible for creating the volume in question. Examples of a creator
include a person, an organization, or a service. In the case of
anthologies, proceedings, or other edited works, this field may be used to
indicate editors or other entities responsible for collecting the volume's
contents.
This element appears as a child of <entry>. If there are multiple authors or
contributors to the book, there may be multiple <dc:creator> elements in the
volume entry (one for each creator or contributor).
"""
_tag = 'creator'
_namespace = DC_NAMESPACE
class Date(_AtomFromString): #iso 8601 / W3CDTF profile
"""
The <dc:date> element indicates the publication date of the specific volume
in question. If the book is a reprint, this is the reprint date, not the
original publication date. The date is encoded according to the ISO-8601
standard (and more specifically, the W3CDTF profile).
The <dc:date> element can appear only as a child of <entry>.
Usually only the year or the year and the month are given.
YYYY-MM-DDThh:mm:ssTZD TZD = -hh:mm or +hh:mm
"""
_tag = 'date'
_namespace = DC_NAMESPACE
class Description(_AtomFromString):
"""
The <dc:description> element includes text that describes a book or book
result. In a search result feed, this may be a search result "snippet" that
contains the words around the user's search term. For a single volume feed,
this element may contain a synopsis of the book.
The <dc:description> element can appear only as a child of <entry>
"""
_tag = 'description'
_namespace = DC_NAMESPACE
class Format(_AtomFromString):
"""
The <dc:format> element describes the physical properties of the volume.
Currently, it indicates the number of pages in the book, but more
information may be added to this field in the future.
This element can appear only as a child of <entry>.
"""
_tag = 'format'
_namespace = DC_NAMESPACE
class Identifier(_AtomFromString):
"""
The <dc:identifier> element provides an unambiguous reference to a
particular book.
* Every <entry> contains at least one <dc:identifier> child.
* The first identifier is always the unique string Book Search has assigned
to the volume (such as s1gVAAAAYAAJ). This is the ID that appears in the
book's URL in the Book Search GUI, as well as in the URL of that book's
single item feed.
* Many books contain additional <dc:identifier> elements. These provide
alternate, external identifiers to the volume. Such identifiers may
include the ISBNs, ISSNs, Library of Congress Control Numbers (LCCNs),
and OCLC numbers; they are prepended with a corresponding namespace
prefix (such as "ISBN:").
* Any <dc:identifier> can be passed to the Dynamic Links, used to
instantiate an Embedded Viewer, or even used to construct static links to
Book Search.
The <dc:identifier> element can appear only as a child of <entry>.
"""
_tag = 'identifier'
_namespace = DC_NAMESPACE
class Publisher(_AtomFromString):
"""
The <dc:publisher> element contains the name of the entity responsible for
producing and distributing the volume (usually the specific edition of this
book). Examples of a publisher include a person, an organization, or a
service.
This element can appear only as a child of <entry>. If there is more than
one publisher, multiple <dc:publisher> elements may appear.
"""
_tag = 'publisher'
_namespace = DC_NAMESPACE
class Subject(_AtomFromString):
"""
The <dc:subject> element identifies the topic of the book. Usually this is
a Library of Congress Subject Heading (LCSH) or Book Industry Standards
and Communications Subject Heading (BISAC).
The <dc:subject> element can appear only as a child of <entry>. There may
be multiple <dc:subject> elements per entry.
"""
_tag = 'subject'
_namespace = DC_NAMESPACE
class Title(_AtomFromString):
"""
The <dc:title> element contains the title of a book as it was published. If
a book has a subtitle, it appears as a second <dc:title> element in the book
result's <entry>.
"""
_tag = 'title'
_namespace = DC_NAMESPACE
class Viewability(_AtomFromString):
"""
Google Book Search respects the user's local copyright restrictions. As a
result, previews or full views of some books are not available in all
locations. The <gbs:viewability> element indicates whether a book is fully
viewable, can be previewed, or only has "about the book" information. These
three "viewability modes" are the same ones returned by the Dynamic Links
API.
The <gbs:viewability> element can appear only as a child of <entry>.
The value attribute will take the form of the following URIs to represent
the relevant viewing capability:
Full View: http://schemas.google.com/books/2008#view_all_pages
Limited Preview: http://schemas.google.com/books/2008#view_partial
Snippet View/No Preview: http://schemas.google.com/books/2008#view_no_pages
Unknown view: http://schemas.google.com/books/2008#view_unknown
"""
_tag = 'viewability'
_namespace = BOOK_SEARCH_NAMESPACE
_attributes = atom.AtomBase._attributes.copy()
_attributes['value'] = 'value'
def __init__(self, value=None, text=None,
extension_elements=None, extension_attributes=None):
self.value = value
_AtomFromString.__init__(self, extension_elements=extension_elements,
extension_attributes=extension_attributes, text=text)
class Embeddability(_AtomFromString):
"""
Many of the books found on Google Book Search can be embedded on third-party
sites using the Embedded Viewer. The <gbs:embeddability> element indicates
whether a particular book result is available for embedding. By definition,
a book that cannot be previewed on Book Search cannot be embedded on third-
party sites.
The <gbs:embeddability> element can appear only as a child of <entry>.
The value attribute will take on one of the following URIs:
embeddable: http://schemas.google.com/books/2008#embeddable
not embeddable: http://schemas.google.com/books/2008#not_embeddable
"""
_tag = 'embeddability'
_namespace = BOOK_SEARCH_NAMESPACE
_attributes = atom.AtomBase._attributes.copy()
_attributes['value'] = 'value'
def __init__(self, value=None, text=None, extension_elements=None,
extension_attributes=None):
self.value = value
_AtomFromString.__init__(self, extension_elements=extension_elements,
extension_attributes=extension_attributes, text=text)
class Review(_AtomFromString):
"""
When present, the <gbs:review> element contains a user-generated review for
a given book. This element currently appears only in the user library and
user annotation feeds, as a child of <entry>.
type: text, html, xhtml
xml:lang: id of the language, a guess, (always two letters?)
"""
_tag = 'review'
_namespace = BOOK_SEARCH_NAMESPACE
_attributes = atom.AtomBase._attributes.copy()
_attributes['type'] = 'type'
_attributes['{http://www.w3.org/XML/1998/namespace}lang'] = 'lang'
def __init__(self, type=None, lang=None, text=None,
extension_elements=None, extension_attributes=None):
self.type = type
self.lang = lang
_AtomFromString.__init__(self, extension_elements=extension_elements,
extension_attributes=extension_attributes, text=text)
class Rating(_AtomFromString):
"""All attributes must take an integral string between 1 and 5.
The min, max, and average attributes represent 'community' ratings. The
value attribute is the user's (of the feed from which the item is fetched,
not necessarily the authenticated user) rating of the book.
"""
_tag = 'rating'
_namespace = gdata.GDATA_NAMESPACE
_attributes = atom.AtomBase._attributes.copy()
_attributes['min'] = 'min'
_attributes['max'] = 'max'
_attributes['average'] = 'average'
_attributes['value'] = 'value'
def __init__(self, min=None, max=None, average=None, value=None, text=None,
extension_elements=None, extension_attributes=None):
self.min = min
self.max = max
self.average = average
self.value = value
_AtomFromString.__init__(self, extension_elements=extension_elements,
extension_attributes=extension_attributes, text=text)
class Book(_AtomFromString, gdata.GDataEntry):
"""
Represents an <entry> from either a search, annotation, library, or single
item feed. Note that dc_title attribute is the proper title of the volume,
title is an atom element and may not represent the full title.
"""
_tag = 'entry'
_namespace = atom.ATOM_NAMESPACE
_children = gdata.GDataEntry._children.copy()
for i in (Creator, Identifier, Publisher, Subject,):
_children['{%s}%s' % (i._namespace, i._tag)] = (i._tag, [i])
for i in (Date, Description, Format, Viewability, Embeddability,
Review, Rating): # Review, Rating maybe only in anno/lib entrys
_children['{%s}%s' % (i._namespace, i._tag)] = (i._tag, i)
# there is an atom title as well, should we clobber that?
del(i)
_children['{%s}%s' % (Title._namespace, Title._tag)] = ('dc_title', [Title])
def to_dict(self):
"""Returns a dictionary of the book's available metadata. If the data
cannot be discovered, it is not included as a key in the returned dict.
The possible keys are: authors, embeddability, date, description,
format, identifiers, publishers, rating, review, subjects, title, and
viewability.
Notes:
* Plural keys will be lists
* Singular keys will be strings
* Title, despite usually being a list, joins the title and subtitle
with a space as a single string.
* embeddability and viewability only return the portion of the URI
after #
* identifiers is a list of tuples, where the first item of each tuple
is the type of identifier and the second item is the identifying
string. Note that while doing dict() on this tuple may be possible,
some items may have multiple of the same identifier and converting
to a dict may resulted in collisions/dropped data.
* Rating returns only the user's rating. See Rating class for precise
definition.
"""
d = {}
if self.GetAnnotationLink():
d['annotation'] = self.GetAnnotationLink().href
if self.creator:
d['authors'] = [x.text for x in self.creator]
if self.embeddability:
d['embeddability'] = self.embeddability.value.split('#')[-1]
if self.date:
d['date'] = self.date.text
if self.description:
d['description'] = self.description.text
if self.format:
d['format'] = self.format.text
if self.identifier:
d['identifiers'] = [('google_id', self.identifier[0].text)]
for x in self.identifier[1:]:
l = x.text.split(':') # should we lower the case of the ids?
d['identifiers'].append((l[0], ':'.join(l[1:])))
if self.GetInfoLink():
d['info'] = self.GetInfoLink().href
if self.GetPreviewLink():
d['preview'] = self.GetPreviewLink().href
if self.publisher:
d['publishers'] = [x.text for x in self.publisher]
if self.rating:
d['rating'] = self.rating.value
if self.review:
d['review'] = self.review.text
if self.subject:
d['subjects'] = [x.text for x in self.subject]
if self.GetThumbnailLink():
d['thumbnail'] = self.GetThumbnailLink().href
if self.dc_title:
d['title'] = ' '.join([x.text for x in self.dc_title])
if self.viewability:
d['viewability'] = self.viewability.value.split('#')[-1]
return d
def __init__(self, creator=None, date=None,
description=None, format=None, author=None, identifier=None,
publisher=None, subject=None, dc_title=None, viewability=None,
embeddability=None, review=None, rating=None, category=None,
content=None, contributor=None, atom_id=None, link=None,
published=None, rights=None, source=None, summary=None,
title=None, control=None, updated=None, text=None,
extension_elements=None, extension_attributes=None):
self.creator = creator
self.date = date
self.description = description
self.format = format
self.identifier = identifier
self.publisher = publisher
self.subject = subject
self.dc_title = dc_title or []
self.viewability = viewability
self.embeddability = embeddability
self.review = review
self.rating = rating
gdata.GDataEntry.__init__(self, author=author, category=category,
content=content, contributor=contributor, atom_id=atom_id,
link=link, published=published, rights=rights, source=source,
summary=summary, title=title, control=control, updated=updated,
text=text, extension_elements=extension_elements,
extension_attributes=extension_attributes)
def GetThumbnailLink(self):
"""Returns the atom.Link object representing the thumbnail URI."""
for i in self.link:
if i.rel == THUMBNAIL_REL:
return i
def GetInfoLink(self):
"""
Returns the atom.Link object representing the human-readable info URI.
"""
for i in self.link:
if i.rel == INFO_REL:
return i
def GetPreviewLink(self):
"""Returns the atom.Link object representing the preview URI."""
for i in self.link:
if i.rel == PREVIEW_REL:
return i
def GetAnnotationLink(self):
"""
Returns the atom.Link object representing the Annotation URI.
Note that the use of www.books in the href of this link seems to make
this information useless. Using books.service.ANNOTATION_FEED and
BOOK_SERVER to construct your URI seems to work better.
"""
for i in self.link:
if i.rel == ANNOTATION_REL:
return i
def set_rating(self, value):
"""Set user's rating. Must be an integral string between 1 nad 5"""
assert (value in ('1','2','3','4','5'))
if not isinstance(self.rating, Rating):
self.rating = Rating()
self.rating.value = value
def set_review(self, text, type='text', lang='en'):
"""Set user's review text"""
self.review = Review(text=text, type=type, lang=lang)
def get_label(self):
"""Get users label for the item as a string"""
for i in self.category:
if i.scheme == LABEL_SCHEME:
return i.term
def set_label(self, term):
"""Clear pre-existing label for the item and set term as the label."""
self.remove_label()
self.category.append(atom.Category(term=term, scheme=LABEL_SCHEME))
def remove_label(self):
"""Clear the user's label for the item"""
ln = len(self.category)
for i, j in enumerate(self.category[::-1]):
if j.scheme == LABEL_SCHEME:
del(self.category[ln-1-i])
def clean_annotations(self):
"""Clear all annotations from an item. Useful for taking an item from
another user's library/annotation feed and adding it to the
authenticated user's library without adopting annotations."""
self.remove_label()
self.review = None
self.rating = None
def get_google_id(self):
"""Get Google's ID of the item."""
return self.id.text.split('/')[-1]
class BookFeed(_AtomFromString, gdata.GDataFeed):
"""Represents a feed of entries from a search."""
_tag = 'feed'
_namespace = atom.ATOM_NAMESPACE
_children = gdata.GDataFeed._children.copy()
_children['{%s}%s' % (Book._namespace, Book._tag)] = (Book._tag, [Book])
if __name__ == '__main__':
import doctest
doctest.testfile('datamodels.txt')
| apache-2.0 | 7,942,596,538,569,523,000 | 38.179704 | 80 | 0.642402 | false | 4.106359 | false | false | false |
jjmleiro/hue | desktop/core/ext-py/Django-1.6.10/tests/save_delete_hooks/models.py | 130 | 1035 | """
13. Adding hooks before/after saving and deleting
To execute arbitrary code around ``save()`` and ``delete()``, just subclass
the methods.
"""
from __future__ import unicode_literals
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
@python_2_unicode_compatible
class Person(models.Model):
first_name = models.CharField(max_length=20)
last_name = models.CharField(max_length=20)
def __init__(self, *args, **kwargs):
super(Person, self).__init__(*args, **kwargs)
self.data = []
def __str__(self):
return "%s %s" % (self.first_name, self.last_name)
def save(self, *args, **kwargs):
self.data.append("Before save")
# Call the "real" save() method
super(Person, self).save(*args, **kwargs)
self.data.append("After save")
def delete(self):
self.data.append("Before deletion")
# Call the "real" delete() method
super(Person, self).delete()
self.data.append("After deletion")
| apache-2.0 | 5,388,654,497,079,564,000 | 28.571429 | 75 | 0.635749 | false | 3.736462 | false | false | false |
kasioumis/invenio | invenio/modules/documentation/views.py | 1 | 3579 | # -*- coding: utf-8 -*-
#
# This file is part of Invenio.
# Copyright (C) 2013, 2014 CERN.
#
# Invenio is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 2 of the
# License, or (at your option) any later version.
#
# Invenio is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Invenio; if not, write to the Free Software Foundation, Inc.,
# 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
"""Documentation Flask Blueprint."""
import os
from flask import render_template, current_app, abort, url_for, Blueprint
from flask.helpers import send_from_directory
from werkzeug.utils import cached_property, import_string
from sphinx.websupport import WebSupport
from sphinx.websupport.errors import DocumentNotFoundError
from invenio.base.globals import cfg
from invenio.base.i18n import _
from flask.ext.breadcrumbs import (default_breadcrumb_root,
register_breadcrumb,
current_breadcrumbs)
from flask.ext.menu import register_menu
class DocsBlueprint(Blueprint):
"""Wrap blueprint with Sphinx ``WebSupport``."""
@cached_property
def documentation_package(self):
"""Return documentation package."""
try:
invenio_docs = import_string(cfg['DOCUMENTATION_PACKAGE'])
except ImportError:
import docs as invenio_docs
return invenio_docs
@cached_property
def support(self):
"""Return an instance of Sphinx ``WebSupport``."""
builddir = os.path.abspath(os.path.join(
current_app.instance_path, 'docs'))
return WebSupport(
srcdir=self.documentation_package.__path__[0],
builddir=builddir,
staticroot=os.path.join(blueprint.url_prefix, 'static'),
docroot=blueprint.url_prefix
)
def send_static_file(self, filename):
"""Return static file."""
try:
return super(self.__class__, self).send_static_file(filename)
except:
cache_timeout = self.get_send_file_max_age(filename)
return send_from_directory(
os.path.join(current_app.instance_path, "docs", "static"),
filename,
cache_timeout=cache_timeout)
blueprint = DocsBlueprint('documentation', __name__,
url_prefix="/documentation",
template_folder='templates', static_folder='static')
default_breadcrumb_root(blueprint, '.documentation')
@blueprint.route('/', strict_slashes=True)
@blueprint.route('/<path:docname>')
@register_menu(blueprint, 'main.documentation', _('Help'), order=99)
@register_breadcrumb(blueprint, '.', _('Help'))
def index(docname=None):
"""Render documentation page."""
try:
document = blueprint.support.get_document(
docname or cfg["DOCUMENTATION_INDEX"])
except DocumentNotFoundError:
abort(404)
additional_breadcrumbs = [{'text': document['title'],
'url': url_for('.index', docname=docname)}]
return render_template(
'documentation/index.html', document=document,
breadcrumbs=current_breadcrumbs + additional_breadcrumbs)
| gpl-2.0 | 9,194,547,294,458,207,000 | 35.520408 | 78 | 0.657726 | false | 4.260714 | false | false | false |
crosswalk-project/blink-crosswalk-efl | Source/devtools/scripts/concatenate_module_scripts.py | 11 | 2413 | #!/usr/bin/env python
#
# Copyright 2014 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.
"""
Concatenates module scripts based on the module.json descriptor.
Optionally, minifies the result using rjsmin.
"""
from cStringIO import StringIO
from os import path
import os
import re
import sys
try:
import simplejson as json
except ImportError:
import json
rjsmin_path = path.abspath(path.join(
path.dirname(__file__),
'..',
'..',
'build',
'scripts'))
sys.path.append(rjsmin_path)
import rjsmin
def read_file(filename):
with open(path.normpath(filename), 'rt') as file:
return file.read()
def write_file(filename, content):
# This is here to avoid overwriting source tree files due to hard links.
if path.exists(filename):
os.remove(filename)
with open(filename, 'wt') as file:
file.write(content)
def concatenate_scripts(file_names, module_dir, output_dir, output):
for file_name in file_names:
output.write('/* %s */\n' % file_name)
file_path = path.join(module_dir, file_name)
# This allows to also concatenate generated files found in output_dir.
if not path.isfile(file_path):
file_path = path.join(output_dir, path.basename(module_dir), file_name)
output.write(read_file(file_path))
output.write(';')
def main(argv):
if len(argv) < 3:
print('Usage: %s module_json output_file no_minify' % argv[0])
return 1
module_json_file_name = argv[1]
output_file_name = argv[2]
no_minify = len(argv) > 3 and argv[3]
module_dir = path.dirname(module_json_file_name)
output = StringIO()
descriptor = None
try:
descriptor = json.loads(read_file(module_json_file_name))
except:
print 'ERROR: Failed to load JSON from ' + module_json_file_name
raise
# pylint: disable=E1103
scripts = descriptor.get('scripts')
assert(scripts)
output_root_dir = path.join(path.dirname(output_file_name), '..')
concatenate_scripts(scripts, module_dir, output_root_dir, output)
output_script = output.getvalue()
output.close()
write_file(output_file_name, output_script if no_minify else rjsmin.jsmin(output_script))
if __name__ == '__main__':
sys.exit(main(sys.argv))
| bsd-3-clause | -1,551,874,067,306,360,800 | 26.735632 | 93 | 0.654787 | false | 3.548529 | false | false | false |
aman-iitj/scipy | scipy/ndimage/__init__.py | 46 | 5436 | """
=========================================================
Multi-dimensional image processing (:mod:`scipy.ndimage`)
=========================================================
.. currentmodule:: scipy.ndimage
This package contains various functions for multi-dimensional image
processing.
Filters :mod:`scipy.ndimage.filters`
====================================
.. module:: scipy.ndimage.filters
.. autosummary::
:toctree: generated/
convolve - Multi-dimensional convolution
convolve1d - 1-D convolution along the given axis
correlate - Multi-dimensional correlation
correlate1d - 1-D correlation along the given axis
gaussian_filter
gaussian_filter1d
gaussian_gradient_magnitude
gaussian_laplace
generic_filter - Multi-dimensional filter using a given function
generic_filter1d - 1-D generic filter along the given axis
generic_gradient_magnitude
generic_laplace
laplace - n-D Laplace filter based on approximate second derivatives
maximum_filter
maximum_filter1d
median_filter - Calculates a multi-dimensional median filter
minimum_filter
minimum_filter1d
percentile_filter - Calculates a multi-dimensional percentile filter
prewitt
rank_filter - Calculates a multi-dimensional rank filter
sobel
uniform_filter - Multi-dimensional uniform filter
uniform_filter1d - 1-D uniform filter along the given axis
Fourier filters :mod:`scipy.ndimage.fourier`
============================================
.. module:: scipy.ndimage.fourier
.. autosummary::
:toctree: generated/
fourier_ellipsoid
fourier_gaussian
fourier_shift
fourier_uniform
Interpolation :mod:`scipy.ndimage.interpolation`
================================================
.. module:: scipy.ndimage.interpolation
.. autosummary::
:toctree: generated/
affine_transform - Apply an affine transformation
geometric_transform - Apply an arbritrary geometric transform
map_coordinates - Map input array to new coordinates by interpolation
rotate - Rotate an array
shift - Shift an array
spline_filter
spline_filter1d
zoom - Zoom an array
Measurements :mod:`scipy.ndimage.measurements`
==============================================
.. module:: scipy.ndimage.measurements
.. autosummary::
:toctree: generated/
center_of_mass - The center of mass of the values of an array at labels
extrema - Min's and max's of an array at labels, with their positions
find_objects - Find objects in a labeled array
histogram - Histogram of the values of an array, optionally at labels
label - Label features in an array
labeled_comprehension
maximum
maximum_position
mean - Mean of the values of an array at labels
minimum
minimum_position
standard_deviation - Standard deviation of an n-D image array
sum - Sum of the values of the array
variance - Variance of the values of an n-D image array
watershed_ift
Morphology :mod:`scipy.ndimage.morphology`
==========================================
.. module:: scipy.ndimage.morphology
.. autosummary::
:toctree: generated/
binary_closing
binary_dilation
binary_erosion
binary_fill_holes
binary_hit_or_miss
binary_opening
binary_propagation
black_tophat
distance_transform_bf
distance_transform_cdt
distance_transform_edt
generate_binary_structure
grey_closing
grey_dilation
grey_erosion
grey_opening
iterate_structure
morphological_gradient
morphological_laplace
white_tophat
Utility
=======
.. currentmodule:: scipy.ndimage
.. autosummary::
:toctree: generated/
imread - Load an image from a file
"""
# Copyright (C) 2003-2005 Peter J. Verveer
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# 1. Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following
# disclaimer in the documentation and/or other materials provided
# with the distribution.
#
# 3. The name of the author may not be used to endorse or promote
# products derived from this software without specific prior
# written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS
# OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
# GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
# WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
from __future__ import division, print_function, absolute_import
from .filters import *
from .fourier import *
from .interpolation import *
from .measurements import *
from .morphology import *
from .io import *
__version__ = '2.0'
__all__ = [s for s in dir() if not s.startswith('_')]
from numpy.testing import Tester
test = Tester().test
| bsd-3-clause | -2,567,934,379,819,761,000 | 28.704918 | 74 | 0.702355 | false | 4.260188 | false | false | false |
JackDandy/SickGear | lib/guessit/transfo/guess_weak_episodes_rexps.py | 21 | 2127 | #!/usr/bin/env python2
# -*- coding: utf-8 -*-
#
# GuessIt - A library for guessing information from filenames
# Copyright (c) 2012 Nicolas Wack <wackou@gmail.com>
#
# GuessIt is free software; you can redistribute it and/or modify it under
# the terms of the Lesser GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# GuessIt is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# Lesser GNU General Public License for more details.
#
# You should have received a copy of the Lesser GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
from __future__ import unicode_literals
from guessit import Guess
from guessit.transfo import SingleNodeGuesser
from guessit.patterns import weak_episode_rexps
import re
import logging
log = logging.getLogger(__name__)
def guess_weak_episodes_rexps(string, node):
if 'episodeNumber' in node.root.info:
return None, None
for rexp, span_adjust in weak_episode_rexps:
match = re.search(rexp, string, re.IGNORECASE)
if match:
metadata = match.groupdict()
span = (match.start() + span_adjust[0],
match.end() + span_adjust[1])
epnum = int(metadata['episodeNumber'])
if epnum > 100:
season, epnum = epnum // 100, epnum % 100
# episodes which have a season > 25 are most likely errors
# (Simpsons is at 23!)
if season > 25:
continue
return Guess({ 'season': season,
'episodeNumber': epnum },
confidence=0.6), span
else:
return Guess(metadata, confidence=0.3), span
return None, None
guess_weak_episodes_rexps.use_node = True
def process(mtree):
SingleNodeGuesser(guess_weak_episodes_rexps, 0.6, log).process(mtree)
| gpl-3.0 | 7,319,974,327,149,637,000 | 33.306452 | 74 | 0.643159 | false | 3.99812 | false | false | false |
mrknow/filmkodi | plugin.video.fanfilm/resources/lib/resolvers/putstream.py | 2 | 1131 | # -*- coding: utf-8 -*-
'''
FanFilm Add-on
Copyright (C) 2015 lambda
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
'''
import re
from resources.lib.libraries import client
def resolve(url):
try:
url = url.replace('/embed-', '/')
url = re.compile('//.+?/([\w]+)').findall(url)[0]
url = 'http://putstream.com/embed-%s.html' % url
result = client.request(url)
url = re.compile('file *: *"(http.+?)"').findall(result)[-1]
return url
except:
return
| apache-2.0 | 8,110,821,232,460,552,000 | 28.763158 | 73 | 0.654288 | false | 4.127737 | false | false | false |
joewashear007/ScrappyDoo | copy.py | 1 | 3382 | import os
import shutil
import zipfile
import fnmatch
import uuid
def main():
kits = findAll(".")
for kit in kits:
print("* ", kit, " -> ", kits[kit])
print()
print()
print("Starting extraction:")
print("------------------------------------------")
extractKits(kits)
def findAll(dir):
print()
print("All zip files:")
print("---------------------------")
kits = {}
files = os.listdir(".")
for file in files:
if file.endswith(".zip"):
kits[file] = getType(file)
return kits
def getType(file):
if "-pp" in file:
return "paper"
if "-ap" in file:
return "alpha"
if "-ep" in file:
return "embellishment"
options = {1: "embellishment", 2: "alpha", 3: "paper", 4:"other"}
#DEBUG:
return options[1];
goodInput = False
while not goodInput:
print()
print("File: ", file)
print(" 1) Embellishment")
print(" 2) Alpha")
print(" 3) Paper")
print(" 4) Other")
action = input("Please Enter the Number (default = 1):")
if action is "":
return options[1];
if action.isdigit():
actionNum = int(action)
if actionNum > 0 and actionNum < len(options)+1:
return options[actionNum]
def extractKits(kits):
tmpDir = "./tmp";
kitNames = {}
x = 0
for kit in kits:
# kit = next(iter(kits.keys()))
x = x + 1
print()
print()
print()
print("Extracting: ", kit, " ( ", x, " of ", len(kits), ")")
kitStr = kit.rsplit("-", 1)[0]
print("Kit Name: ", kitStr)
if kitStr in kitNames:
name = input("Please Enter Kit Name (default = "+kitNames[kitStr]+"): ")
name = name or kitNames[kitStr]
else:
name = input("Please Enter Kit Name: ")
kitNames[kitStr] =name
if os.path.exists(tmpDir):
shutil.rmtree(tmpDir)
else:
os.makedirs(tmpDir)
if not os.path.exists("./" + name):
os.makedirs("./" + name)
kitzip = zipfile.ZipFile("./" + kit)
kitzip.extractall(tmpDir)
images = copyExtractedFiles("./" + name +"/")
createManifest(kit, name, images, kits[kit])
def copyExtractedFiles(dest):
matches = []
filenames = [".png", ".jpg"]
for rootpath, subdirs, files in os.walk("./tmp"):
for filename in files:
if os.path.splitext(filename)[1].lower() in filenames:
# print(os.path.join(rootpath, filename).replace('\\','/'))
shutil.move(os.path.join(rootpath, filename).replace('\\','/'), dest+filename)
matches.append(dest + filename)
return matches
def createManifest(kit, name, images, type):
manifest = []
manifest.append('<Manifest vendorid="0" vendorpackageid="0" maintaincopyright="True" dpi="300">')
manifest.append('<Groups />')
manifest.append('<Entries>')
for image in images:
manifest.append('<Image ID="'+str(uuid.uuid4())+'" Name="'+image+'" Group="Embellishment" />')
manifest.append('</Entries>')
manifest.append('</Manifest>')
with open('./'+name+'/package.manifestx', 'w') as f:
for line in manifest:
f.write(line + os.linesep)
if __name__ == "__main__":
main()
| mit | 7,577,268,462,791,354,000 | 27.905983 | 102 | 0.527794 | false | 3.704272 | false | false | false |
sasukeh/neutron | neutron/api/rpc/callbacks/resource_manager.py | 32 | 4710 | # 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 abc
import collections
from oslo_log import log as logging
import six
from neutron.api.rpc.callbacks import exceptions as rpc_exc
from neutron.api.rpc.callbacks import resources
from neutron.callbacks import exceptions
LOG = logging.getLogger(__name__)
# TODO(QoS): split the registry/resources_rpc modules into two separate things:
# one for pull and one for push APIs
def _validate_resource_type(resource_type):
if not resources.is_valid_resource_type(resource_type):
raise exceptions.Invalid(element='resource', value=resource_type)
@six.add_metaclass(abc.ABCMeta)
class ResourceCallbacksManager(object):
"""A callback system that allows information providers in a loose manner.
"""
# This hook is to allow tests to get new objects for the class
_singleton = True
def __new__(cls, *args, **kwargs):
if not cls._singleton:
return super(ResourceCallbacksManager, cls).__new__(cls)
if not hasattr(cls, '_instance'):
cls._instance = super(ResourceCallbacksManager, cls).__new__(cls)
return cls._instance
@abc.abstractmethod
def _add_callback(self, callback, resource_type):
pass
@abc.abstractmethod
def _delete_callback(self, callback, resource_type):
pass
def register(self, callback, resource_type):
"""Register a callback for a resource type.
:param callback: the callback. It must raise or return NeutronObject.
:param resource_type: must be a valid resource type.
"""
LOG.debug("Registering callback for %s", resource_type)
_validate_resource_type(resource_type)
self._add_callback(callback, resource_type)
def unregister(self, callback, resource_type):
"""Unregister callback from the registry.
:param callback: the callback.
:param resource_type: must be a valid resource type.
"""
LOG.debug("Unregistering callback for %s", resource_type)
_validate_resource_type(resource_type)
self._delete_callback(callback, resource_type)
@abc.abstractmethod
def clear(self):
"""Brings the manager to a clean state."""
def get_subscribed_types(self):
return list(self._callbacks.keys())
class ProducerResourceCallbacksManager(ResourceCallbacksManager):
_callbacks = dict()
def _add_callback(self, callback, resource_type):
if resource_type in self._callbacks:
raise rpc_exc.CallbacksMaxLimitReached(resource_type=resource_type)
self._callbacks[resource_type] = callback
def _delete_callback(self, callback, resource_type):
try:
del self._callbacks[resource_type]
except KeyError:
raise rpc_exc.CallbackNotFound(resource_type=resource_type)
def clear(self):
self._callbacks = dict()
def get_callback(self, resource_type):
_validate_resource_type(resource_type)
try:
return self._callbacks[resource_type]
except KeyError:
raise rpc_exc.CallbackNotFound(resource_type=resource_type)
class ConsumerResourceCallbacksManager(ResourceCallbacksManager):
_callbacks = collections.defaultdict(set)
def _add_callback(self, callback, resource_type):
self._callbacks[resource_type].add(callback)
def _delete_callback(self, callback, resource_type):
try:
self._callbacks[resource_type].remove(callback)
if not self._callbacks[resource_type]:
del self._callbacks[resource_type]
except KeyError:
raise rpc_exc.CallbackNotFound(resource_type=resource_type)
def clear(self):
self._callbacks = collections.defaultdict(set)
def get_callbacks(self, resource_type):
"""Return the callback if found, None otherwise.
:param resource_type: must be a valid resource type.
"""
_validate_resource_type(resource_type)
callbacks = self._callbacks[resource_type]
if not callbacks:
raise rpc_exc.CallbackNotFound(resource_type=resource_type)
return callbacks
| apache-2.0 | -3,525,136,190,414,913,000 | 32.884892 | 79 | 0.679193 | false | 4.313187 | false | false | false |
listamilton/supermilton.repository | script.module.youtube.dl/lib/youtube_dl/extractor/moniker.py | 66 | 3951 | # coding: utf-8
from __future__ import unicode_literals
import os.path
import re
from .common import InfoExtractor
from ..utils import (
ExtractorError,
remove_start,
sanitized_Request,
urlencode_postdata,
)
class MonikerIE(InfoExtractor):
IE_DESC = 'allmyvideos.net and vidspot.net'
_VALID_URL = r'https?://(?:www\.)?(?:allmyvideos|vidspot)\.net/(?:(?:2|v)/v-)?(?P<id>[a-zA-Z0-9_-]+)'
_TESTS = [{
'url': 'http://allmyvideos.net/jih3nce3x6wn',
'md5': '710883dee1bfc370ecf9fa6a89307c88',
'info_dict': {
'id': 'jih3nce3x6wn',
'ext': 'mp4',
'title': 'youtube-dl test video',
},
}, {
'url': 'http://allmyvideos.net/embed-jih3nce3x6wn',
'md5': '710883dee1bfc370ecf9fa6a89307c88',
'info_dict': {
'id': 'jih3nce3x6wn',
'ext': 'mp4',
'title': 'youtube-dl test video',
},
}, {
'url': 'http://vidspot.net/l2ngsmhs8ci5',
'md5': '710883dee1bfc370ecf9fa6a89307c88',
'info_dict': {
'id': 'l2ngsmhs8ci5',
'ext': 'mp4',
'title': 'youtube-dl test video',
},
}, {
'url': 'https://www.vidspot.net/l2ngsmhs8ci5',
'only_matching': True,
}, {
'url': 'http://vidspot.net/2/v-ywDf99',
'md5': '5f8254ce12df30479428b0152fb8e7ba',
'info_dict': {
'id': 'ywDf99',
'ext': 'mp4',
'title': 'IL FAIT LE MALIN EN PORSHE CAYENNE ( mais pas pour longtemps)',
'description': 'IL FAIT LE MALIN EN PORSHE CAYENNE.',
},
}, {
'url': 'http://allmyvideos.net/v/v-HXZm5t',
'only_matching': True,
}]
def _real_extract(self, url):
orig_video_id = self._match_id(url)
video_id = remove_start(orig_video_id, 'embed-')
url = url.replace(orig_video_id, video_id)
assert re.match(self._VALID_URL, url) is not None
orig_webpage = self._download_webpage(url, video_id)
if '>File Not Found<' in orig_webpage:
raise ExtractorError('Video %s does not exist' % video_id, expected=True)
error = self._search_regex(
r'class="err">([^<]+)<', orig_webpage, 'error', default=None)
if error:
raise ExtractorError(
'%s returned error: %s' % (self.IE_NAME, error), expected=True)
builtin_url = self._search_regex(
r'<iframe[^>]+src=(["\'])(?P<url>.+?/builtin-.+?)\1',
orig_webpage, 'builtin URL', default=None, group='url')
if builtin_url:
req = sanitized_Request(builtin_url)
req.add_header('Referer', url)
webpage = self._download_webpage(req, video_id, 'Downloading builtin page')
title = self._og_search_title(orig_webpage).strip()
description = self._og_search_description(orig_webpage).strip()
else:
fields = re.findall(r'type="hidden" name="(.+?)"\s* value="?(.+?)">', orig_webpage)
data = dict(fields)
post = urlencode_postdata(data)
headers = {
b'Content-Type': b'application/x-www-form-urlencoded',
}
req = sanitized_Request(url, post, headers)
webpage = self._download_webpage(
req, video_id, note='Downloading video page ...')
title = os.path.splitext(data['fname'])[0]
description = None
# Could be several links with different quality
links = re.findall(r'"file" : "?(.+?)",', webpage)
# Assume the links are ordered in quality
formats = [{
'url': l,
'quality': i,
} for i, l in enumerate(links)]
self._sort_formats(formats)
return {
'id': video_id,
'title': title,
'description': description,
'formats': formats,
}
| gpl-2.0 | 2,729,320,049,983,951,400 | 33.060345 | 105 | 0.529486 | false | 3.39433 | false | false | false |
gohin/django | django/contrib/auth/management/commands/createsuperuser.py | 65 | 7695 | """
Management utility to create superusers.
"""
from __future__ import unicode_literals
import getpass
import sys
from django.contrib.auth import get_user_model
from django.contrib.auth.management import get_default_username
from django.core import exceptions
from django.core.management.base import BaseCommand, CommandError
from django.db import DEFAULT_DB_ALIAS
from django.utils.encoding import force_str
from django.utils.six.moves import input
from django.utils.text import capfirst
class NotRunningInTTYException(Exception):
pass
class Command(BaseCommand):
help = 'Used to create a superuser.'
def __init__(self, *args, **kwargs):
super(Command, self).__init__(*args, **kwargs)
self.UserModel = get_user_model()
self.username_field = self.UserModel._meta.get_field(self.UserModel.USERNAME_FIELD)
def add_arguments(self, parser):
parser.add_argument('--%s' % self.UserModel.USERNAME_FIELD,
dest=self.UserModel.USERNAME_FIELD, default=None,
help='Specifies the login for the superuser.')
parser.add_argument('--noinput', action='store_false', dest='interactive', default=True,
help=('Tells Django to NOT prompt the user for input of any kind. '
'You must use --%s with --noinput, along with an option for '
'any other required field. Superusers created with --noinput will '
' not be able to log in until they\'re given a valid password.' %
self.UserModel.USERNAME_FIELD))
parser.add_argument('--database', action='store', dest='database',
default=DEFAULT_DB_ALIAS,
help='Specifies the database to use. Default is "default".')
for field in self.UserModel.REQUIRED_FIELDS:
parser.add_argument('--%s' % field, dest=field, default=None,
help='Specifies the %s for the superuser.' % field)
def execute(self, *args, **options):
self.stdin = options.get('stdin', sys.stdin) # Used for testing
return super(Command, self).execute(*args, **options)
def handle(self, *args, **options):
username = options.get(self.UserModel.USERNAME_FIELD)
database = options.get('database')
# If not provided, create the user with an unusable password
password = None
user_data = {}
# Do quick and dirty validation if --noinput
if not options['interactive']:
try:
if not username:
raise CommandError("You must use --%s with --noinput." %
self.UserModel.USERNAME_FIELD)
username = self.username_field.clean(username, None)
for field_name in self.UserModel.REQUIRED_FIELDS:
if options.get(field_name):
field = self.UserModel._meta.get_field(field_name)
user_data[field_name] = field.clean(options[field_name], None)
else:
raise CommandError("You must use --%s with --noinput." % field_name)
except exceptions.ValidationError as e:
raise CommandError('; '.join(e.messages))
else:
# Prompt for username/password, and any other required fields.
# Enclose this whole thing in a try/except to catch
# KeyboardInterrupt and exit gracefully.
default_username = get_default_username()
try:
if hasattr(self.stdin, 'isatty') and not self.stdin.isatty():
raise NotRunningInTTYException("Not running in a TTY")
# Get a username
verbose_field_name = self.username_field.verbose_name
while username is None:
input_msg = capfirst(verbose_field_name)
if default_username:
input_msg += " (leave blank to use '%s')" % default_username
username_rel = self.username_field.remote_field
input_msg = force_str('%s%s: ' % (
input_msg,
' (%s.%s)' % (
username_rel.model._meta.object_name,
username_rel.field_name
) if username_rel else '')
)
username = self.get_input_data(self.username_field, input_msg, default_username)
if not username:
continue
if self.username_field.unique:
try:
self.UserModel._default_manager.db_manager(database).get_by_natural_key(username)
except self.UserModel.DoesNotExist:
pass
else:
self.stderr.write("Error: That %s is already taken." % verbose_field_name)
username = None
for field_name in self.UserModel.REQUIRED_FIELDS:
field = self.UserModel._meta.get_field(field_name)
user_data[field_name] = options.get(field_name)
while user_data[field_name] is None:
message = force_str('%s%s: ' % (
capfirst(field.verbose_name),
' (%s.%s)' % (
field.remote_field.model._meta.object_name,
field.remote_field.field_name,
) if field.remote_field else '',
))
user_data[field_name] = self.get_input_data(field, message)
# Get a password
while password is None:
if not password:
password = getpass.getpass()
password2 = getpass.getpass(force_str('Password (again): '))
if password != password2:
self.stderr.write("Error: Your passwords didn't match.")
password = None
continue
if password.strip() == '':
self.stderr.write("Error: Blank passwords aren't allowed.")
password = None
continue
except KeyboardInterrupt:
self.stderr.write("\nOperation cancelled.")
sys.exit(1)
except NotRunningInTTYException:
self.stdout.write(
"Superuser creation skipped due to not running in a TTY. "
"You can run `manage.py createsuperuser` in your project "
"to create one manually."
)
if username:
user_data[self.UserModel.USERNAME_FIELD] = username
user_data['password'] = password
self.UserModel._default_manager.db_manager(database).create_superuser(**user_data)
if options['verbosity'] >= 1:
self.stdout.write("Superuser created successfully.")
def get_input_data(self, field, message, default=None):
"""
Override this method if you want to customize data inputs or
validation exceptions.
"""
raw_value = input(message)
if default and raw_value == '':
raw_value = default
try:
val = field.clean(raw_value, None)
except exceptions.ValidationError as e:
self.stderr.write("Error: %s" % '; '.join(e.messages))
val = None
return val
| bsd-3-clause | 6,320,757,852,442,747,000 | 43.738372 | 109 | 0.538532 | false | 4.764706 | false | false | false |
wwright2/dcim3-angstrom1 | sources/openembedded-core/scripts/pybootchartgui/pybootchartgui/samples.py | 7 | 5537 | # This file is part of pybootchartgui.
# pybootchartgui 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.
# pybootchartgui 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 pybootchartgui. If not, see <http://www.gnu.org/licenses/>.
class DiskStatSample:
def __init__(self, time):
self.time = time
self.diskdata = [0, 0, 0]
def add_diskdata(self, new_diskdata):
self.diskdata = [ a + b for a, b in zip(self.diskdata, new_diskdata) ]
class CPUSample:
def __init__(self, time, user, sys, io = 0.0, swap = 0.0):
self.time = time
self.user = user
self.sys = sys
self.io = io
self.swap = swap
@property
def cpu(self):
return self.user + self.sys
def __str__(self):
return str(self.time) + "\t" + str(self.user) + "\t" + \
str(self.sys) + "\t" + str(self.io) + "\t" + str (self.swap)
class MemSample:
used_values = ('MemTotal', 'MemFree', 'Buffers', 'Cached', 'SwapTotal', 'SwapFree',)
def __init__(self, time):
self.time = time
self.records = {}
def add_value(self, name, value):
if name in MemSample.used_values:
self.records[name] = value
def valid(self):
keys = self.records.keys()
# discard incomplete samples
return [v for v in MemSample.used_values if v not in keys] == []
class ProcessSample:
def __init__(self, time, state, cpu_sample):
self.time = time
self.state = state
self.cpu_sample = cpu_sample
def __str__(self):
return str(self.time) + "\t" + str(self.state) + "\t" + str(self.cpu_sample)
class ProcessStats:
def __init__(self, writer, process_map, sample_count, sample_period, start_time, end_time):
self.process_map = process_map
self.sample_count = sample_count
self.sample_period = sample_period
self.start_time = start_time
self.end_time = end_time
writer.info ("%d samples, avg. sample length %f" % (self.sample_count, self.sample_period))
writer.info ("process list size: %d" % len (self.process_map.values()))
class Process:
def __init__(self, writer, pid, cmd, ppid, start_time):
self.writer = writer
self.pid = pid
self.cmd = cmd
self.exe = cmd
self.args = []
self.ppid = ppid
self.start_time = start_time
self.duration = 0
self.samples = []
self.parent = None
self.child_list = []
self.active = None
self.last_user_cpu_time = None
self.last_sys_cpu_time = None
self.last_cpu_ns = 0
self.last_blkio_delay_ns = 0
self.last_swapin_delay_ns = 0
# split this process' run - triggered by a name change
def split(self, writer, pid, cmd, ppid, start_time):
split = Process (writer, pid, cmd, ppid, start_time)
split.last_cpu_ns = self.last_cpu_ns
split.last_blkio_delay_ns = self.last_blkio_delay_ns
split.last_swapin_delay_ns = self.last_swapin_delay_ns
return split
def __str__(self):
return " ".join([str(self.pid), self.cmd, str(self.ppid), '[ ' + str(len(self.samples)) + ' samples ]' ])
def calc_stats(self, samplePeriod):
if self.samples:
firstSample = self.samples[0]
lastSample = self.samples[-1]
self.start_time = min(firstSample.time, self.start_time)
self.duration = lastSample.time - self.start_time + samplePeriod
activeCount = sum( [1 for sample in self.samples if sample.cpu_sample and sample.cpu_sample.sys + sample.cpu_sample.user + sample.cpu_sample.io > 0.0] )
activeCount = activeCount + sum( [1 for sample in self.samples if sample.state == 'D'] )
self.active = (activeCount>2)
def calc_load(self, userCpu, sysCpu, interval):
userCpuLoad = float(userCpu - self.last_user_cpu_time) / interval
sysCpuLoad = float(sysCpu - self.last_sys_cpu_time) / interval
cpuLoad = userCpuLoad + sysCpuLoad
# normalize
if cpuLoad > 1.0:
userCpuLoad = userCpuLoad / cpuLoad
sysCpuLoad = sysCpuLoad / cpuLoad
return (userCpuLoad, sysCpuLoad)
def set_parent(self, processMap):
if self.ppid != None:
self.parent = processMap.get (self.ppid)
if self.parent == None and self.pid // 1000 > 1 and \
not (self.ppid == 2000 or self.pid == 2000): # kernel threads: ppid=2
self.writer.warn("Missing CONFIG_PROC_EVENTS: no parent for pid '%i' ('%s') with ppid '%i'" \
% (self.pid,self.cmd,self.ppid))
def get_end_time(self):
return self.start_time + self.duration
class DiskSample:
def __init__(self, time, read, write, util):
self.time = time
self.read = read
self.write = write
self.util = util
self.tput = read + write
def __str__(self):
return "\t".join([str(self.time), str(self.read), str(self.write), str(self.util)])
| mit | 4,583,296,552,943,260,700 | 35.668874 | 160 | 0.601409 | false | 3.50443 | false | false | false |
rickerc/neutron_audit | neutron/plugins/nec/ofc_manager.py | 9 | 9461 | # vim: tabstop=4 shiftwidth=4 softtabstop=4
#
# Copyright 2012 NEC Corporation. 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.
# @author: Ryota MIBU
# @author: Akihiro MOTOKI
import netaddr
from neutron.common import utils
from neutron.openstack.common import log as logging
from neutron.plugins.nec.common import config
from neutron.plugins.nec.common import exceptions as nexc
from neutron.plugins.nec.db import api as ndb
from neutron.plugins.nec import drivers
LOG = logging.getLogger(__name__)
class OFCManager(object):
"""This class manages an OpenFlow Controller and map resources.
This class manage an OpenFlow Controller (OFC) with a driver specified in
a configuration of this plugin. This keeps mappings between IDs on Neutron
and OFC for various entities such as Tenant, Network and Filter. A Port on
OFC is identified by a switch ID 'datapath_id' and a port number 'port_no'
of the switch. An ID named as 'ofc_*' is used to identify resource on OFC.
"""
def __init__(self):
self.driver = drivers.get_driver(config.OFC.driver)(config.OFC)
def _get_ofc_id(self, context, resource, neutron_id):
return ndb.get_ofc_id_lookup_both(context.session,
resource, neutron_id)
def _exists_ofc_item(self, context, resource, neutron_id):
return ndb.exists_ofc_item_lookup_both(context.session,
resource, neutron_id)
def _add_ofc_item(self, context, resource, neutron_id, ofc_id):
# Ensure a new item is added to the new mapping table
ndb.add_ofc_item(context.session, resource, neutron_id, ofc_id)
def _del_ofc_item(self, context, resource, neutron_id):
ndb.del_ofc_item_lookup_both(context.session, resource, neutron_id)
def ensure_ofc_tenant(self, context, tenant_id):
if not self.exists_ofc_tenant(context, tenant_id):
self.create_ofc_tenant(context, tenant_id)
def create_ofc_tenant(self, context, tenant_id):
desc = "ID=%s at OpenStack." % tenant_id
ofc_tenant_id = self.driver.create_tenant(desc, tenant_id)
self._add_ofc_item(context, "ofc_tenant", tenant_id, ofc_tenant_id)
def exists_ofc_tenant(self, context, tenant_id):
return self._exists_ofc_item(context, "ofc_tenant", tenant_id)
def delete_ofc_tenant(self, context, tenant_id):
ofc_tenant_id = self._get_ofc_id(context, "ofc_tenant", tenant_id)
ofc_tenant_id = self.driver.convert_ofc_tenant_id(
context, ofc_tenant_id)
self.driver.delete_tenant(ofc_tenant_id)
self._del_ofc_item(context, "ofc_tenant", tenant_id)
def create_ofc_network(self, context, tenant_id, network_id,
network_name=None):
ofc_tenant_id = self._get_ofc_id(context, "ofc_tenant", tenant_id)
ofc_tenant_id = self.driver.convert_ofc_tenant_id(
context, ofc_tenant_id)
desc = "ID=%s Name=%s at Neutron." % (network_id, network_name)
ofc_net_id = self.driver.create_network(ofc_tenant_id, desc,
network_id)
self._add_ofc_item(context, "ofc_network", network_id, ofc_net_id)
def exists_ofc_network(self, context, network_id):
return self._exists_ofc_item(context, "ofc_network", network_id)
def delete_ofc_network(self, context, network_id, network):
ofc_net_id = self._get_ofc_id(context, "ofc_network", network_id)
ofc_net_id = self.driver.convert_ofc_network_id(
context, ofc_net_id, network['tenant_id'])
self.driver.delete_network(ofc_net_id)
self._del_ofc_item(context, "ofc_network", network_id)
def create_ofc_port(self, context, port_id, port):
ofc_net_id = self._get_ofc_id(context, "ofc_network",
port['network_id'])
ofc_net_id = self.driver.convert_ofc_network_id(
context, ofc_net_id, port['tenant_id'])
portinfo = ndb.get_portinfo(context.session, port_id)
if not portinfo:
raise nexc.PortInfoNotFound(id=port_id)
ofc_port_id = self.driver.create_port(ofc_net_id, portinfo, port_id)
self._add_ofc_item(context, "ofc_port", port_id, ofc_port_id)
def exists_ofc_port(self, context, port_id):
return self._exists_ofc_item(context, "ofc_port", port_id)
def delete_ofc_port(self, context, port_id, port):
ofc_port_id = self._get_ofc_id(context, "ofc_port", port_id)
ofc_port_id = self.driver.convert_ofc_port_id(
context, ofc_port_id, port['tenant_id'], port['network_id'])
self.driver.delete_port(ofc_port_id)
self._del_ofc_item(context, "ofc_port", port_id)
def create_ofc_packet_filter(self, context, filter_id, filter_dict):
ofc_net_id = self._get_ofc_id(context, "ofc_network",
filter_dict['network_id'])
ofc_net_id = self.driver.convert_ofc_network_id(
context, ofc_net_id, filter_dict['tenant_id'])
in_port_id = filter_dict.get('in_port')
portinfo = None
if in_port_id:
portinfo = ndb.get_portinfo(context.session, in_port_id)
if not portinfo:
raise nexc.PortInfoNotFound(id=in_port_id)
ofc_pf_id = self.driver.create_filter(ofc_net_id,
filter_dict, portinfo, filter_id)
self._add_ofc_item(context, "ofc_packet_filter", filter_id, ofc_pf_id)
def exists_ofc_packet_filter(self, context, filter_id):
return self._exists_ofc_item(context, "ofc_packet_filter", filter_id)
def delete_ofc_packet_filter(self, context, filter_id):
ofc_pf_id = self._get_ofc_id(context, "ofc_packet_filter", filter_id)
ofc_pf_id = self.driver.convert_ofc_filter_id(context, ofc_pf_id)
self.driver.delete_filter(ofc_pf_id)
self._del_ofc_item(context, "ofc_packet_filter", filter_id)
def create_ofc_router(self, context, tenant_id, router_id, name=None):
ofc_tenant_id = self._get_ofc_id(context, "ofc_tenant", tenant_id)
ofc_tenant_id = self.driver.convert_ofc_tenant_id(
context, ofc_tenant_id)
desc = "ID=%s Name=%s at Neutron." % (router_id, name)
ofc_router_id = self.driver.create_router(ofc_tenant_id, router_id,
desc)
self._add_ofc_item(context, "ofc_router", router_id, ofc_router_id)
def exists_ofc_router(self, context, router_id):
return self._exists_ofc_item(context, "ofc_router", router_id)
def delete_ofc_router(self, context, router_id, router):
ofc_router_id = self._get_ofc_id(context, "ofc_router", router_id)
self.driver.delete_router(ofc_router_id)
self._del_ofc_item(context, "ofc_router", router_id)
def add_ofc_router_interface(self, context, router_id, port_id, port):
# port must have the following fields:
# network_id, cidr, ip_address, mac_address
ofc_router_id = self._get_ofc_id(context, "ofc_router", router_id)
ofc_net_id = self._get_ofc_id(context, "ofc_network",
port['network_id'])
ip_address = '%s/%s' % (port['ip_address'],
netaddr.IPNetwork(port['cidr']).prefixlen)
mac_address = port['mac_address']
ofc_inf_id = self.driver.add_router_interface(
ofc_router_id, ofc_net_id, ip_address, mac_address)
# Use port mapping table to maintain an interface of OFC router
self._add_ofc_item(context, "ofc_port", port_id, ofc_inf_id)
def delete_ofc_router_interface(self, context, router_id, port_id):
# Use port mapping table to maintain an interface of OFC router
ofc_inf_id = self._get_ofc_id(context, "ofc_port", port_id)
self.driver.delete_router_interface(ofc_inf_id)
self._del_ofc_item(context, "ofc_port", port_id)
def update_ofc_router_route(self, context, router_id, new_routes):
ofc_router_id = self._get_ofc_id(context, "ofc_router", router_id)
ofc_routes = self.driver.list_router_routes(ofc_router_id)
route_dict = {}
cur_routes = []
for r in ofc_routes:
key = ','.join((r['destination'], r['nexthop']))
route_dict[key] = r['id']
del r['id']
cur_routes.append(r)
added, removed = utils.diff_list_of_dict(cur_routes, new_routes)
for r in removed:
key = ','.join((r['destination'], r['nexthop']))
route_id = route_dict[key]
self.driver.delete_router_route(route_id)
for r in added:
self.driver.add_router_route(ofc_router_id, r['destination'],
r['nexthop'])
| apache-2.0 | -5,019,626,671,642,997,000 | 45.377451 | 79 | 0.621499 | false | 3.4217 | false | false | false |
vmobi-gogh/android_kernel_samsung_gogh | Documentation/networking/cxacru-cf.py | 14668 | 1626 | #!/usr/bin/env python
# Copyright 2009 Simon Arlott
#
# 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., 59
# Temple Place - Suite 330, Boston, MA 02111-1307, USA.
#
# Usage: cxacru-cf.py < cxacru-cf.bin
# Output: values string suitable for the sysfs adsl_config attribute
#
# Warning: cxacru-cf.bin with MD5 hash cdbac2689969d5ed5d4850f117702110
# contains mis-aligned values which will stop the modem from being able
# to make a connection. If the first and last two bytes are removed then
# the values become valid, but the modulation will be forced to ANSI
# T1.413 only which may not be appropriate.
#
# The original binary format is a packed list of le32 values.
import sys
import struct
i = 0
while True:
buf = sys.stdin.read(4)
if len(buf) == 0:
break
elif len(buf) != 4:
sys.stdout.write("\n")
sys.stderr.write("Error: read {0} not 4 bytes\n".format(len(buf)))
sys.exit(1)
if i > 0:
sys.stdout.write(" ")
sys.stdout.write("{0:x}={1}".format(i, struct.unpack("<I", buf)[0]))
i += 1
sys.stdout.write("\n")
| gpl-2.0 | 1,200,256,328,089,234,400 | 32.875 | 78 | 0.730012 | false | 3.318367 | false | false | false |
slockit/DAO | tests/scenarios/fuel/run.py | 4 | 1429 | import random
from utils import constrained_sum_sample_pos, arr_str
scenario_description = (
"During the fueling period of the DAO, send enough ether from all "
"accounts to create tokens and then assert that the user's balance is "
"indeed correct and that the minimum fueling goal has been reached"
)
def run(ctx):
ctx.assert_scenario_ran('deploy')
creation_secs = ctx.remaining_time()
ctx.total_supply = (
ctx.args.deploy_min_tokens_to_create + random.randint(1, 100)
)
ctx.token_amounts = constrained_sum_sample_pos(
len(ctx.accounts), ctx.total_supply
)
ctx.create_js_file(substitutions={
"dao_abi": ctx.dao_abi,
"dao_address": ctx.dao_address,
"wait_ms": (creation_secs-3)*1000,
"amounts": arr_str(ctx.token_amounts)
}
)
print(
"Notice: Fueling period is {} seconds so the test will wait "
"as much".format(creation_secs)
)
adjusted_amounts = (
[x/1.5 for x in ctx.token_amounts]
if ctx.scenario_uses_extrabalance() else ctx.token_amounts
)
adjusted_supply = (
ctx.total_supply / 1.5
if ctx.scenario_uses_extrabalance() else ctx.total_supply
)
ctx.execute(expected={
"dao_fueled": True,
"total_supply": adjusted_supply,
"balances": adjusted_amounts,
"user0_after": adjusted_amounts[0]
})
| lgpl-3.0 | -5,488,954,882,271,867,000 | 28.770833 | 75 | 0.621414 | false | 3.435096 | false | false | false |
tarzan0820/odoo | openerp/tools/lru.py | 237 | 3197 | # -*- coding: utf-8 -*-
# taken from http://code.activestate.com/recipes/252524-length-limited-o1-lru-cache-implementation/
import threading
from func import synchronized
__all__ = ['LRU']
class LRUNode(object):
__slots__ = ['prev', 'next', 'me']
def __init__(self, prev, me):
self.prev = prev
self.me = me
self.next = None
class LRU(object):
"""
Implementation of a length-limited O(1) LRU queue.
Built for and used by PyPE:
http://pype.sourceforge.net
Copyright 2003 Josiah Carlson.
"""
def __init__(self, count, pairs=[]):
self._lock = threading.RLock()
self.count = max(count, 1)
self.d = {}
self.first = None
self.last = None
for key, value in pairs:
self[key] = value
@synchronized()
def __contains__(self, obj):
return obj in self.d
@synchronized()
def __getitem__(self, obj):
a = self.d[obj].me
self[a[0]] = a[1]
return a[1]
@synchronized()
def __setitem__(self, obj, val):
if obj in self.d:
del self[obj]
nobj = LRUNode(self.last, (obj, val))
if self.first is None:
self.first = nobj
if self.last:
self.last.next = nobj
self.last = nobj
self.d[obj] = nobj
if len(self.d) > self.count:
if self.first == self.last:
self.first = None
self.last = None
return
a = self.first
a.next.prev = None
self.first = a.next
a.next = None
del self.d[a.me[0]]
del a
@synchronized()
def __delitem__(self, obj):
nobj = self.d[obj]
if nobj.prev:
nobj.prev.next = nobj.next
else:
self.first = nobj.next
if nobj.next:
nobj.next.prev = nobj.prev
else:
self.last = nobj.prev
del self.d[obj]
@synchronized()
def __iter__(self):
cur = self.first
while cur is not None:
cur2 = cur.next
yield cur.me[1]
cur = cur2
@synchronized()
def __len__(self):
return len(self.d)
@synchronized()
def iteritems(self):
cur = self.first
while cur is not None:
cur2 = cur.next
yield cur.me
cur = cur2
@synchronized()
def iterkeys(self):
return iter(self.d)
@synchronized()
def itervalues(self):
for i,j in self.iteritems():
yield j
@synchronized()
def keys(self):
return self.d.keys()
@synchronized()
def pop(self,key):
v=self[key]
del self[key]
return v
@synchronized()
def clear(self):
self.d = {}
self.first = None
self.last = None
@synchronized()
def clear_prefix(self, prefix):
""" Remove from `self` all the items with the given `prefix`. """
n = len(prefix)
for key in self.keys():
if key[:n] == prefix:
del self[key]
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
| agpl-3.0 | 7,655,114,437,631,426,000 | 23.592308 | 99 | 0.510166 | false | 3.674713 | false | false | false |
Ircam-Web/mezzanine-organization | organization/projects/migrations/0085_auto_20190619_2023.py | 1 | 1116 | # -*- coding: utf-8 -*-
# Generated by Django 1.10.8 on 2019-06-19 18:23
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('organization-projects', '0084_auto_20190304_2221'),
]
operations = [
migrations.AlterModelOptions(
name='projectpage',
options={'permissions': (('user_edit', 'Mezzo - User can edit its own content'), ('user_delete', 'Mezzo - User can delete its own content'), ('team_edit', "Mezzo - User can edit his team's content"), ('team_delete', "Mezzo - User can delete his team's content"))},
),
migrations.AddField(
model_name='projectpage',
name='user',
field=models.ForeignKey(default=4, on_delete=django.db.models.deletion.CASCADE, related_name='projectpages', to=settings.AUTH_USER_MODEL, verbose_name='Author'),
preserve_default=False,
),
]
| agpl-3.0 | 4,549,997,135,370,149,400 | 38.857143 | 276 | 0.650538 | false | 3.943463 | false | false | false |
sdague/home-assistant | homeassistant/components/dyson/sensor.py | 5 | 6457 | """Support for Dyson Pure Cool Link Sensors."""
import logging
from libpurecool.dyson_pure_cool import DysonPureCool
from libpurecool.dyson_pure_cool_link import DysonPureCoolLink
from homeassistant.const import PERCENTAGE, STATE_OFF, TEMP_CELSIUS, TIME_HOURS
from homeassistant.helpers.entity import Entity
from . import DYSON_DEVICES
SENSOR_UNITS = {
"air_quality": None,
"dust": None,
"filter_life": TIME_HOURS,
"humidity": PERCENTAGE,
}
SENSOR_ICONS = {
"air_quality": "mdi:fan",
"dust": "mdi:cloud",
"filter_life": "mdi:filter-outline",
"humidity": "mdi:water-percent",
"temperature": "mdi:thermometer",
}
DYSON_SENSOR_DEVICES = "dyson_sensor_devices"
_LOGGER = logging.getLogger(__name__)
def setup_platform(hass, config, add_entities, discovery_info=None):
"""Set up the Dyson Sensors."""
if discovery_info is None:
return
hass.data.setdefault(DYSON_SENSOR_DEVICES, [])
unit = hass.config.units.temperature_unit
devices = hass.data[DYSON_SENSOR_DEVICES]
# Get Dyson Devices from parent component
device_ids = [device.unique_id for device in hass.data[DYSON_SENSOR_DEVICES]]
new_entities = []
for device in hass.data[DYSON_DEVICES]:
if isinstance(device, DysonPureCool):
if f"{device.serial}-temperature" not in device_ids:
new_entities.append(DysonTemperatureSensor(device, unit))
if f"{device.serial}-humidity" not in device_ids:
new_entities.append(DysonHumiditySensor(device))
elif isinstance(device, DysonPureCoolLink):
new_entities.append(DysonFilterLifeSensor(device))
new_entities.append(DysonDustSensor(device))
new_entities.append(DysonHumiditySensor(device))
new_entities.append(DysonTemperatureSensor(device, unit))
new_entities.append(DysonAirQualitySensor(device))
if not new_entities:
return
devices.extend(new_entities)
add_entities(devices)
class DysonSensor(Entity):
"""Representation of a generic Dyson sensor."""
def __init__(self, device, sensor_type):
"""Create a new generic Dyson sensor."""
self._device = device
self._old_value = None
self._name = None
self._sensor_type = sensor_type
async def async_added_to_hass(self):
"""Call when entity is added to hass."""
self._device.add_message_listener(self.on_message)
def on_message(self, message):
"""Handle new messages which are received from the fan."""
# Prevent refreshing if not needed
if self._old_value is None or self._old_value != self.state:
_LOGGER.debug("Message received for %s device: %s", self.name, message)
self._old_value = self.state
self.schedule_update_ha_state()
@property
def should_poll(self):
"""No polling needed."""
return False
@property
def name(self):
"""Return the name of the Dyson sensor name."""
return self._name
@property
def unit_of_measurement(self):
"""Return the unit the value is expressed in."""
return SENSOR_UNITS[self._sensor_type]
@property
def icon(self):
"""Return the icon for this sensor."""
return SENSOR_ICONS[self._sensor_type]
@property
def unique_id(self):
"""Return the sensor's unique id."""
return f"{self._device.serial}-{self._sensor_type}"
class DysonFilterLifeSensor(DysonSensor):
"""Representation of Dyson Filter Life sensor (in hours)."""
def __init__(self, device):
"""Create a new Dyson Filter Life sensor."""
super().__init__(device, "filter_life")
self._name = f"{self._device.name} Filter Life"
@property
def state(self):
"""Return filter life in hours."""
if self._device.state:
return int(self._device.state.filter_life)
return None
class DysonDustSensor(DysonSensor):
"""Representation of Dyson Dust sensor (lower is better)."""
def __init__(self, device):
"""Create a new Dyson Dust sensor."""
super().__init__(device, "dust")
self._name = f"{self._device.name} Dust"
@property
def state(self):
"""Return Dust value."""
if self._device.environmental_state:
return self._device.environmental_state.dust
return None
class DysonHumiditySensor(DysonSensor):
"""Representation of Dyson Humidity sensor."""
def __init__(self, device):
"""Create a new Dyson Humidity sensor."""
super().__init__(device, "humidity")
self._name = f"{self._device.name} Humidity"
@property
def state(self):
"""Return Humidity value."""
if self._device.environmental_state:
if self._device.environmental_state.humidity == 0:
return STATE_OFF
return self._device.environmental_state.humidity
return None
class DysonTemperatureSensor(DysonSensor):
"""Representation of Dyson Temperature sensor."""
def __init__(self, device, unit):
"""Create a new Dyson Temperature sensor."""
super().__init__(device, "temperature")
self._name = f"{self._device.name} Temperature"
self._unit = unit
@property
def state(self):
"""Return Temperature value."""
if self._device.environmental_state:
temperature_kelvin = self._device.environmental_state.temperature
if temperature_kelvin == 0:
return STATE_OFF
if self._unit == TEMP_CELSIUS:
return float(f"{(temperature_kelvin - 273.15):.1f}")
return float(f"{(temperature_kelvin * 9 / 5 - 459.67):.1f}")
return None
@property
def unit_of_measurement(self):
"""Return the unit the value is expressed in."""
return self._unit
class DysonAirQualitySensor(DysonSensor):
"""Representation of Dyson Air Quality sensor (lower is better)."""
def __init__(self, device):
"""Create a new Dyson Air Quality sensor."""
super().__init__(device, "air_quality")
self._name = f"{self._device.name} AQI"
@property
def state(self):
"""Return Air Quality value."""
if self._device.environmental_state:
return int(self._device.environmental_state.volatil_organic_compounds)
return None
| apache-2.0 | 5,239,885,266,624,850,000 | 30.807882 | 83 | 0.627536 | false | 3.827504 | false | false | false |
suninsky/ReceiptOCR | Python/server/lib/python2.7/site-packages/markupsafe/__init__.py | 144 | 10697 | # -*- coding: utf-8 -*-
"""
markupsafe
~~~~~~~~~~
Implements a Markup string.
:copyright: (c) 2010 by Armin Ronacher.
:license: BSD, see LICENSE for more details.
"""
import re
import string
from collections import Mapping
from markupsafe._compat import text_type, string_types, int_types, \
unichr, iteritems, PY2
__version__ = "1.0"
__all__ = ['Markup', 'soft_unicode', 'escape', 'escape_silent']
_striptags_re = re.compile(r'(<!--.*?-->|<[^>]*>)')
_entity_re = re.compile(r'&([^& ;]+);')
class Markup(text_type):
r"""Marks a string as being safe for inclusion in HTML/XML output without
needing to be escaped. This implements the `__html__` interface a couple
of frameworks and web applications use. :class:`Markup` is a direct
subclass of `unicode` and provides all the methods of `unicode` just that
it escapes arguments passed and always returns `Markup`.
The `escape` function returns markup objects so that double escaping can't
happen.
The constructor of the :class:`Markup` class can be used for three
different things: When passed an unicode object it's assumed to be safe,
when passed an object with an HTML representation (has an `__html__`
method) that representation is used, otherwise the object passed is
converted into a unicode string and then assumed to be safe:
>>> Markup("Hello <em>World</em>!")
Markup(u'Hello <em>World</em>!')
>>> class Foo(object):
... def __html__(self):
... return '<a href="#">foo</a>'
...
>>> Markup(Foo())
Markup(u'<a href="#">foo</a>')
If you want object passed being always treated as unsafe you can use the
:meth:`escape` classmethod to create a :class:`Markup` object:
>>> Markup.escape("Hello <em>World</em>!")
Markup(u'Hello <em>World</em>!')
Operations on a markup string are markup aware which means that all
arguments are passed through the :func:`escape` function:
>>> em = Markup("<em>%s</em>")
>>> em % "foo & bar"
Markup(u'<em>foo & bar</em>')
>>> strong = Markup("<strong>%(text)s</strong>")
>>> strong % {'text': '<blink>hacker here</blink>'}
Markup(u'<strong><blink>hacker here</blink></strong>')
>>> Markup("<em>Hello</em> ") + "<foo>"
Markup(u'<em>Hello</em> <foo>')
"""
__slots__ = ()
def __new__(cls, base=u'', encoding=None, errors='strict'):
if hasattr(base, '__html__'):
base = base.__html__()
if encoding is None:
return text_type.__new__(cls, base)
return text_type.__new__(cls, base, encoding, errors)
def __html__(self):
return self
def __add__(self, other):
if isinstance(other, string_types) or hasattr(other, '__html__'):
return self.__class__(super(Markup, self).__add__(self.escape(other)))
return NotImplemented
def __radd__(self, other):
if hasattr(other, '__html__') or isinstance(other, string_types):
return self.escape(other).__add__(self)
return NotImplemented
def __mul__(self, num):
if isinstance(num, int_types):
return self.__class__(text_type.__mul__(self, num))
return NotImplemented
__rmul__ = __mul__
def __mod__(self, arg):
if isinstance(arg, tuple):
arg = tuple(_MarkupEscapeHelper(x, self.escape) for x in arg)
else:
arg = _MarkupEscapeHelper(arg, self.escape)
return self.__class__(text_type.__mod__(self, arg))
def __repr__(self):
return '%s(%s)' % (
self.__class__.__name__,
text_type.__repr__(self)
)
def join(self, seq):
return self.__class__(text_type.join(self, map(self.escape, seq)))
join.__doc__ = text_type.join.__doc__
def split(self, *args, **kwargs):
return list(map(self.__class__, text_type.split(self, *args, **kwargs)))
split.__doc__ = text_type.split.__doc__
def rsplit(self, *args, **kwargs):
return list(map(self.__class__, text_type.rsplit(self, *args, **kwargs)))
rsplit.__doc__ = text_type.rsplit.__doc__
def splitlines(self, *args, **kwargs):
return list(map(self.__class__, text_type.splitlines(
self, *args, **kwargs)))
splitlines.__doc__ = text_type.splitlines.__doc__
def unescape(self):
r"""Unescape markup again into an text_type string. This also resolves
known HTML4 and XHTML entities:
>>> Markup("Main » <em>About</em>").unescape()
u'Main \xbb <em>About</em>'
"""
from markupsafe._constants import HTML_ENTITIES
def handle_match(m):
name = m.group(1)
if name in HTML_ENTITIES:
return unichr(HTML_ENTITIES[name])
try:
if name[:2] in ('#x', '#X'):
return unichr(int(name[2:], 16))
elif name.startswith('#'):
return unichr(int(name[1:]))
except ValueError:
pass
# Don't modify unexpected input.
return m.group()
return _entity_re.sub(handle_match, text_type(self))
def striptags(self):
r"""Unescape markup into an text_type string and strip all tags. This
also resolves known HTML4 and XHTML entities. Whitespace is
normalized to one:
>>> Markup("Main » <em>About</em>").striptags()
u'Main \xbb About'
"""
stripped = u' '.join(_striptags_re.sub('', self).split())
return Markup(stripped).unescape()
@classmethod
def escape(cls, s):
"""Escape the string. Works like :func:`escape` with the difference
that for subclasses of :class:`Markup` this function would return the
correct subclass.
"""
rv = escape(s)
if rv.__class__ is not cls:
return cls(rv)
return rv
def make_simple_escaping_wrapper(name):
orig = getattr(text_type, name)
def func(self, *args, **kwargs):
args = _escape_argspec(list(args), enumerate(args), self.escape)
_escape_argspec(kwargs, iteritems(kwargs), self.escape)
return self.__class__(orig(self, *args, **kwargs))
func.__name__ = orig.__name__
func.__doc__ = orig.__doc__
return func
for method in '__getitem__', 'capitalize', \
'title', 'lower', 'upper', 'replace', 'ljust', \
'rjust', 'lstrip', 'rstrip', 'center', 'strip', \
'translate', 'expandtabs', 'swapcase', 'zfill':
locals()[method] = make_simple_escaping_wrapper(method)
# new in python 2.5
if hasattr(text_type, 'partition'):
def partition(self, sep):
return tuple(map(self.__class__,
text_type.partition(self, self.escape(sep))))
def rpartition(self, sep):
return tuple(map(self.__class__,
text_type.rpartition(self, self.escape(sep))))
# new in python 2.6
if hasattr(text_type, 'format'):
def format(*args, **kwargs):
self, args = args[0], args[1:]
formatter = EscapeFormatter(self.escape)
kwargs = _MagicFormatMapping(args, kwargs)
return self.__class__(formatter.vformat(self, args, kwargs))
def __html_format__(self, format_spec):
if format_spec:
raise ValueError('Unsupported format specification '
'for Markup.')
return self
# not in python 3
if hasattr(text_type, '__getslice__'):
__getslice__ = make_simple_escaping_wrapper('__getslice__')
del method, make_simple_escaping_wrapper
class _MagicFormatMapping(Mapping):
"""This class implements a dummy wrapper to fix a bug in the Python
standard library for string formatting.
See http://bugs.python.org/issue13598 for information about why
this is necessary.
"""
def __init__(self, args, kwargs):
self._args = args
self._kwargs = kwargs
self._last_index = 0
def __getitem__(self, key):
if key == '':
idx = self._last_index
self._last_index += 1
try:
return self._args[idx]
except LookupError:
pass
key = str(idx)
return self._kwargs[key]
def __iter__(self):
return iter(self._kwargs)
def __len__(self):
return len(self._kwargs)
if hasattr(text_type, 'format'):
class EscapeFormatter(string.Formatter):
def __init__(self, escape):
self.escape = escape
def format_field(self, value, format_spec):
if hasattr(value, '__html_format__'):
rv = value.__html_format__(format_spec)
elif hasattr(value, '__html__'):
if format_spec:
raise ValueError('No format specification allowed '
'when formatting an object with '
'its __html__ method.')
rv = value.__html__()
else:
# We need to make sure the format spec is unicode here as
# otherwise the wrong callback methods are invoked. For
# instance a byte string there would invoke __str__ and
# not __unicode__.
rv = string.Formatter.format_field(
self, value, text_type(format_spec))
return text_type(self.escape(rv))
def _escape_argspec(obj, iterable, escape):
"""Helper for various string-wrapped functions."""
for key, value in iterable:
if hasattr(value, '__html__') or isinstance(value, string_types):
obj[key] = escape(value)
return obj
class _MarkupEscapeHelper(object):
"""Helper for Markup.__mod__"""
def __init__(self, obj, escape):
self.obj = obj
self.escape = escape
__getitem__ = lambda s, x: _MarkupEscapeHelper(s.obj[x], s.escape)
__unicode__ = __str__ = lambda s: text_type(s.escape(s.obj))
__repr__ = lambda s: str(s.escape(repr(s.obj)))
__int__ = lambda s: int(s.obj)
__float__ = lambda s: float(s.obj)
# we have to import it down here as the speedups and native
# modules imports the markup type which is define above.
try:
from markupsafe._speedups import escape, escape_silent, soft_unicode
except ImportError:
from markupsafe._native import escape, escape_silent, soft_unicode
if not PY2:
soft_str = soft_unicode
__all__.append('soft_str')
| mit | 2,225,617,646,636,672,500 | 34.072131 | 82 | 0.567355 | false | 4.029002 | false | false | false |
ahmadio/edx-platform | lms/djangoapps/mobile_api/social_facebook/groups/views.py | 86 | 4938 | """
Views for groups info API
"""
from rest_framework import generics, status, mixins
from rest_framework.response import Response
from django.conf import settings
import facebook
from ...utils import mobile_view
from . import serializers
@mobile_view()
class Groups(generics.CreateAPIView, mixins.DestroyModelMixin):
"""
**Use Case**
An API to Create or Delete course groups.
Note: The Delete is not invoked from the current version of the app
and is used only for testing with facebook dependencies.
**Creation Example request**:
POST /api/mobile/v0.5/social/facebook/groups/
Parameters: name : string,
description : string,
privacy : open/closed
**Creation Response Values**
{"id": group_id}
**Deletion Example request**:
DELETE /api/mobile/v0.5/social/facebook/groups/<group_id>
**Deletion Response Values**
{"success" : "true"}
"""
serializer_class = serializers.GroupSerializer
def create(self, request, *args, **kwargs):
serializer = self.get_serializer(data=request.DATA, files=request.FILES)
if not serializer.is_valid():
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
try:
app_groups_response = facebook_graph_api().request(
settings.FACEBOOK_API_VERSION + '/' + settings.FACEBOOK_APP_ID + "/groups",
post_args=request.POST.dict()
)
return Response(app_groups_response)
except facebook.GraphAPIError, ex:
return Response({'error': ex.result['error']['message']}, status=status.HTTP_400_BAD_REQUEST)
def delete(self, request, *args, **kwargs): # pylint: disable=unused-argument
"""
Deletes the course group.
"""
try:
return Response(
facebook_graph_api().request(
settings.FACEBOOK_API_VERSION + '/' + settings.FACEBOOK_APP_ID + "/groups/" + kwargs['group_id'],
post_args={'method': 'delete'}
)
)
except facebook.GraphAPIError, ex:
return Response({'error': ex.result['error']['message']}, status=status.HTTP_400_BAD_REQUEST)
@mobile_view()
class GroupsMembers(generics.CreateAPIView, mixins.DestroyModelMixin):
"""
**Use Case**
An API to Invite and Remove members to a group
Note: The Remove is not invoked from the current version
of the app and is used only for testing with facebook dependencies.
**Invite Example request**:
POST /api/mobile/v0.5/social/facebook/groups/<group_id>/member/
Parameters: members : int,int,int...
**Invite Response Values**
{"member_id" : success/error_message}
A response with each member_id and whether or not the member was added successfully.
If the member was not added successfully the Facebook error message is provided.
**Remove Example request**:
DELETE /api/mobile/v0.5/social/facebook/groups/<group_id>/member/<member_id>
**Remove Response Values**
{"success" : "true"}
"""
serializer_class = serializers.GroupsMembersSerializer
def create(self, request, *args, **kwargs):
serializer = self.get_serializer(data=request.DATA, files=request.FILES)
if not serializer.is_valid():
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
graph = facebook_graph_api()
url = settings.FACEBOOK_API_VERSION + '/' + kwargs['group_id'] + "/members"
member_ids = serializer.object['member_ids'].split(',')
response = {}
for member_id in member_ids:
try:
if 'success' in graph.request(url, post_args={'member': member_id}):
response[member_id] = 'success'
except facebook.GraphAPIError, ex:
response[member_id] = ex.result['error']['message']
return Response(response, status=status.HTTP_200_OK)
def delete(self, request, *args, **kwargs): # pylint: disable=unused-argument
"""
Deletes the member from the course group.
"""
try:
return Response(
facebook_graph_api().request(
settings.FACEBOOK_API_VERSION + '/' + kwargs['group_id'] + "/members",
post_args={'method': 'delete', 'member': kwargs['member_id']}
)
)
except facebook.GraphAPIError, ex:
return Response({'error': ex.result['error']['message']}, status=status.HTTP_400_BAD_REQUEST)
def facebook_graph_api():
"""
Returns the result from calling Facebook's Graph API with the app's access token.
"""
return facebook.GraphAPI(facebook.get_app_access_token(settings.FACEBOOK_APP_ID, settings.FACEBOOK_APP_SECRET))
| agpl-3.0 | -5,134,061,850,296,026,000 | 33.531469 | 117 | 0.614824 | false | 4.216909 | false | false | false |
skidzen/grit-i18n | grit/tool/build.py | 2 | 19603 | #!/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.
'''The 'grit build' tool along with integration for this tool with the
SCons build system.
'''
import filecmp
import getopt
import os
import shutil
import sys
from grit import grd_reader
from grit import util
from grit.tool import interface
from grit import shortcuts
# It would be cleaner to have each module register itself, but that would
# require importing all of them on every run of GRIT.
'''Map from <output> node types to modules under grit.format.'''
_format_modules = {
'android': 'android_xml',
'c_format': 'c_format',
'chrome_messages_json': 'chrome_messages_json',
'data_package': 'data_pack',
'js_map_format': 'js_map_format',
'rc_all': 'rc',
'rc_translateable': 'rc',
'rc_nontranslateable': 'rc',
'rc_header': 'rc_header',
'resource_map_header': 'resource_map',
'resource_map_source': 'resource_map',
'resource_file_map_source': 'resource_map',
}
_format_modules.update(
(type, 'policy_templates.template_formatter') for type in
[ 'adm', 'admx', 'adml', 'reg', 'doc', 'json',
'plist', 'plist_strings', 'ios_plist', 'android_policy' ])
def GetFormatter(type):
modulename = 'grit.format.' + _format_modules[type]
__import__(modulename)
module = sys.modules[modulename]
try:
return module.Format
except AttributeError:
return module.GetFormatter(type)
class RcBuilder(interface.Tool):
'''A tool that builds RC files and resource header files for compilation.
Usage: grit build [-o OUTPUTDIR] [-D NAME[=VAL]]*
All output options for this tool are specified in the input file (see
'grit help' for details on how to specify the input file - it is a global
option).
Options:
-a FILE Assert that the given file is an output. There can be
multiple "-a" flags listed for multiple outputs. If a "-a"
or "--assert-file-list" argument is present, then the list
of asserted files must match the output files or the tool
will fail. The use-case is for the build system to maintain
separate lists of output files and to catch errors if the
build system's list and the grit list are out-of-sync.
--assert-file-list Provide a file listing multiple asserted output files.
There is one file name per line. This acts like specifying
each file with "-a" on the command line, but without the
possibility of running into OS line-length limits for very
long lists.
-o OUTPUTDIR Specify what directory output paths are relative to.
Defaults to the current directory.
-D NAME[=VAL] Specify a C-preprocessor-like define NAME with optional
value VAL (defaults to 1) which will be used to control
conditional inclusion of resources.
-E NAME=VALUE Set environment variable NAME to VALUE (within grit).
-f FIRSTIDSFILE Path to a python file that specifies the first id of
value to use for resources. A non-empty value here will
override the value specified in the <grit> node's
first_ids_file.
-w WHITELISTFILE Path to a file containing the string names of the
resources to include. Anything not listed is dropped.
-t PLATFORM Specifies the platform the build is targeting; defaults
to the value of sys.platform. The value provided via this
flag should match what sys.platform would report for your
target platform; see grit.node.base.EvaluateCondition.
-h HEADERFORMAT Custom format string to use for generating rc header files.
The string should have two placeholders: {textual_id}
and {numeric_id}. E.g. "#define {textual_id} {numeric_id}"
Otherwise it will use the default "#define SYMBOL 1234"
--output-all-resource-defines
--no-output-all-resource-defines If specified, overrides the value of the
output_all_resource_defines attribute of the root <grit>
element of the input .grd file.
--write-only-new flag
If flag is non-0, write output files to a temporary file
first, and copy it to the real output only if the new file
is different from the old file. This allows some build
systems to realize that dependent build steps might be
unnecessary, at the cost of comparing the output data at
grit time.
--depend-on-stamp
If specified along with --depfile and --depdir, the depfile
generated will depend on a stampfile instead of the first
output in the input .grd file.
Conditional inclusion of resources only affects the output of files which
control which resources get linked into a binary, e.g. it affects .rc files
meant for compilation but it does not affect resource header files (that define
IDs). This helps ensure that values of IDs stay the same, that all messages
are exported to translation interchange files (e.g. XMB files), etc.
'''
def ShortDescription(self):
return 'A tool that builds RC files for compilation.'
def Run(self, opts, args):
self.output_directory = '.'
first_ids_file = None
whitelist_filenames = []
assert_output_files = []
target_platform = None
depfile = None
depdir = None
rc_header_format = None
output_all_resource_defines = None
write_only_new = False
depend_on_stamp = False
(own_opts, args) = getopt.getopt(args, 'a:o:D:E:f:w:t:h:',
('depdir=','depfile=','assert-file-list=',
'output-all-resource-defines',
'no-output-all-resource-defines',
'depend-on-stamp',
'write-only-new='))
for (key, val) in own_opts:
if key == '-a':
assert_output_files.append(val)
elif key == '--assert-file-list':
with open(val) as f:
assert_output_files += f.read().splitlines()
elif key == '-o':
self.output_directory = val
elif key == '-D':
name, val = util.ParseDefine(val)
self.defines[name] = val
elif key == '-E':
(env_name, env_value) = val.split('=', 1)
os.environ[env_name] = env_value
elif key == '-f':
# TODO(joi@chromium.org): Remove this override once change
# lands in WebKit.grd to specify the first_ids_file in the
# .grd itself.
first_ids_file = val
elif key == '-w':
whitelist_filenames.append(val)
elif key == '--output-all-resource-defines':
output_all_resource_defines = True
elif key == '--no-output-all-resource-defines':
output_all_resource_defines = False
elif key == '-t':
target_platform = val
elif key == '-h':
rc_header_format = val
elif key == '--depdir':
depdir = val
elif key == '--depfile':
depfile = val
elif key == '--write-only-new':
write_only_new = val != '0'
elif key == '--depend-on-stamp':
depend_on_stamp = True
if len(args):
print 'This tool takes no tool-specific arguments.'
return 2
self.SetOptions(opts)
if self.scons_targets:
self.VerboseOut('Using SCons targets to identify files to output.\n')
else:
self.VerboseOut('Output directory: %s (absolute path: %s)\n' %
(self.output_directory,
os.path.abspath(self.output_directory)))
if whitelist_filenames:
self.whitelist_names = set()
for whitelist_filename in whitelist_filenames:
self.VerboseOut('Using whitelist: %s\n' % whitelist_filename);
whitelist_contents = util.ReadFile(whitelist_filename, util.RAW_TEXT)
self.whitelist_names.update(whitelist_contents.strip().split('\n'))
self.write_only_new = write_only_new
self.res = grd_reader.Parse(opts.input,
debug=opts.extra_verbose,
first_ids_file=first_ids_file,
defines=self.defines,
target_platform=target_platform)
# If the output_all_resource_defines option is specified, override the value
# found in the grd file.
if output_all_resource_defines is not None:
self.res.SetShouldOutputAllResourceDefines(output_all_resource_defines)
# Set an output context so that conditionals can use defines during the
# gathering stage; we use a dummy language here since we are not outputting
# a specific language.
self.res.SetOutputLanguage('en')
if rc_header_format:
self.res.AssignRcHeaderFormat(rc_header_format)
self.res.RunGatherers()
self.Process()
if assert_output_files:
if not self.CheckAssertedOutputFiles(assert_output_files):
return 2
if depfile and depdir:
self.GenerateDepfile(depfile, depdir, first_ids_file, depend_on_stamp)
return 0
def __init__(self, defines=None):
# Default file-creation function is built-in open(). Only done to allow
# overriding by unit test.
self.fo_create = open
# key/value pairs of C-preprocessor like defines that are used for
# conditional output of resources
self.defines = defines or {}
# self.res is a fully-populated resource tree if Run()
# has been called, otherwise None.
self.res = None
# Set to a list of filenames for the output nodes that are relative
# to the current working directory. They are in the same order as the
# output nodes in the file.
self.scons_targets = None
# The set of names that are whitelisted to actually be included in the
# output.
self.whitelist_names = None
# Whether to compare outputs to their old contents before writing.
self.write_only_new = False
@staticmethod
def AddWhitelistTags(start_node, whitelist_names):
# Walk the tree of nodes added attributes for the nodes that shouldn't
# be written into the target files (skip markers).
from grit.node import include
from grit.node import message
from grit.node import structure
for node in start_node:
# Same trick data_pack.py uses to see what nodes actually result in
# real items.
if (isinstance(node, include.IncludeNode) or
isinstance(node, message.MessageNode) or
isinstance(node, structure.StructureNode)):
text_ids = node.GetTextualIds()
# Mark the item to be skipped if it wasn't in the whitelist.
if text_ids and text_ids[0] not in whitelist_names:
node.SetWhitelistMarkedAsSkip(True)
@staticmethod
def ProcessNode(node, output_node, outfile):
'''Processes a node in-order, calling its formatter before and after
recursing to its children.
Args:
node: grit.node.base.Node subclass
output_node: grit.node.io.OutputNode
outfile: open filehandle
'''
base_dir = util.dirname(output_node.GetOutputFilename())
formatter = GetFormatter(output_node.GetType())
formatted = formatter(node, output_node.GetLanguage(), output_dir=base_dir)
outfile.writelines(formatted)
def Process(self):
# Update filenames with those provided by SCons if we're being invoked
# from SCons. The list of SCons targets also includes all <structure>
# node outputs, but it starts with our output files, in the order they
# occur in the .grd
if self.scons_targets:
assert len(self.scons_targets) >= len(self.res.GetOutputFiles())
outfiles = self.res.GetOutputFiles()
for ix in range(len(outfiles)):
outfiles[ix].output_filename = os.path.abspath(
self.scons_targets[ix])
else:
for output in self.res.GetOutputFiles():
output.output_filename = os.path.abspath(os.path.join(
self.output_directory, output.GetFilename()))
# If there are whitelisted names, tag the tree once up front, this way
# while looping through the actual output, it is just an attribute check.
if self.whitelist_names:
self.AddWhitelistTags(self.res, self.whitelist_names)
for output in self.res.GetOutputFiles():
self.VerboseOut('Creating %s...' % output.GetFilename())
# Microsoft's RC compiler can only deal with single-byte or double-byte
# files (no UTF-8), so we make all RC files UTF-16 to support all
# character sets.
if output.GetType() in ('rc_header', 'resource_map_header',
'resource_map_source', 'resource_file_map_source'):
encoding = 'cp1252'
elif output.GetType() in ('android', 'c_format', 'js_map_format', 'plist',
'plist_strings', 'doc', 'json', 'android_policy'):
encoding = 'utf_8'
elif output.GetType() in ('chrome_messages_json'):
# Chrome Web Store currently expects BOM for UTF-8 files :-(
encoding = 'utf-8-sig'
else:
# TODO(gfeher) modify here to set utf-8 encoding for admx/adml
encoding = 'utf_16'
# Set the context, for conditional inclusion of resources
self.res.SetOutputLanguage(output.GetLanguage())
self.res.SetOutputContext(output.GetContext())
self.res.SetFallbackToDefaultLayout(output.GetFallbackToDefaultLayout())
self.res.SetDefines(self.defines)
# Make the output directory if it doesn't exist.
self.MakeDirectoriesTo(output.GetOutputFilename())
# Write the results to a temporary file and only overwrite the original
# if the file changed. This avoids unnecessary rebuilds.
outfile = self.fo_create(output.GetOutputFilename() + '.tmp', 'wb')
if output.GetType() != 'data_package':
outfile = util.WrapOutputStream(outfile, encoding)
# Iterate in-order through entire resource tree, calling formatters on
# the entry into a node and on exit out of it.
with outfile:
self.ProcessNode(self.res, output, outfile)
# Now copy from the temp file back to the real output, but on Windows,
# only if the real output doesn't exist or the contents of the file
# changed. This prevents identical headers from being written and .cc
# files from recompiling (which is painful on Windows).
if not os.path.exists(output.GetOutputFilename()):
os.rename(output.GetOutputFilename() + '.tmp',
output.GetOutputFilename())
else:
# CHROMIUM SPECIFIC CHANGE.
# This clashes with gyp + vstudio, which expect the output timestamp
# to change on a rebuild, even if nothing has changed, so only do
# it when opted in.
if not self.write_only_new:
write_file = True
else:
files_match = filecmp.cmp(output.GetOutputFilename(),
output.GetOutputFilename() + '.tmp')
write_file = not files_match
if write_file:
shutil.copy2(output.GetOutputFilename() + '.tmp',
output.GetOutputFilename())
os.remove(output.GetOutputFilename() + '.tmp')
self.VerboseOut(' done.\n')
# Print warnings if there are any duplicate shortcuts.
warnings = shortcuts.GenerateDuplicateShortcutsWarnings(
self.res.UberClique(), self.res.GetTcProject())
if warnings:
print '\n'.join(warnings)
# Print out any fallback warnings, and missing translation errors, and
# exit with an error code if there are missing translations in a non-pseudo
# and non-official build.
warnings = (self.res.UberClique().MissingTranslationsReport().
encode('ascii', 'replace'))
if warnings:
self.VerboseOut(warnings)
if self.res.UberClique().HasMissingTranslations():
print self.res.UberClique().missing_translations_
sys.exit(-1)
def CheckAssertedOutputFiles(self, assert_output_files):
'''Checks that the asserted output files are specified in the given list.
Returns true if the asserted files are present. If they are not, returns
False and prints the failure.
'''
# Compare the absolute path names, sorted.
asserted = sorted([os.path.abspath(i) for i in assert_output_files])
actual = sorted([
os.path.abspath(os.path.join(self.output_directory, i.GetFilename()))
for i in self.res.GetOutputFiles()])
if asserted != actual:
missing = list(set(actual) - set(asserted))
extra = list(set(asserted) - set(actual))
error = '''Asserted file list does not match.
Expected output files:
%s
Actual output files:
%s
Missing output files:
%s
Extra output files:
%s
'''
print error % ('\n'.join(asserted), '\n'.join(actual), '\n'.join(missing),
'\n'.join(extra))
return False
return True
def GenerateDepfile(self, depfile, depdir, first_ids_file, depend_on_stamp):
'''Generate a depfile that contains the imlicit dependencies of the input
grd. The depfile will be in the same format as a makefile, and will contain
references to files relative to |depdir|. It will be put in |depfile|.
For example, supposing we have three files in a directory src/
src/
blah.grd <- depends on input{1,2}.xtb
input1.xtb
input2.xtb
and we run
grit -i blah.grd -o ../out/gen --depdir ../out --depfile ../out/gen/blah.rd.d
from the directory src/ we will generate a depfile ../out/gen/blah.grd.d
that has the contents
gen/blah.h: ../src/input1.xtb ../src/input2.xtb
Where "gen/blah.h" is the first output (Ninja expects the .d file to list
the first output in cases where there is more than one). If the flag
--depend-on-stamp is specified, "gen/blah.rd.d.stamp" will be used that is
'touched' whenever a new depfile is generated.
Note that all paths in the depfile are relative to ../out, the depdir.
'''
depfile = os.path.abspath(depfile)
depdir = os.path.abspath(depdir)
infiles = self.res.GetInputFiles()
# We want to trigger a rebuild if the first ids change.
if first_ids_file is not None:
infiles.append(first_ids_file)
if (depend_on_stamp):
output_file = depfile + ".stamp"
# Touch the stamp file before generating the depfile.
with open(output_file, 'a'):
os.utime(output_file, None)
else:
# Get the first output file relative to the depdir.
outputs = self.res.GetOutputFiles()
output_file = os.path.join(self.output_directory,
outputs[0].GetFilename())
output_file = os.path.relpath(output_file, depdir)
# The path prefix to prepend to dependencies in the depfile.
prefix = os.path.relpath(os.getcwd(), depdir)
deps_text = ' '.join([os.path.join(prefix, i) for i in infiles])
depfile_contents = output_file + ': ' + deps_text
self.MakeDirectoriesTo(depfile)
outfile = self.fo_create(depfile, 'wb')
outfile.writelines(depfile_contents)
@staticmethod
def MakeDirectoriesTo(file):
'''Creates directories necessary to contain |file|.'''
dir = os.path.split(file)[0]
if not os.path.exists(dir):
os.makedirs(dir)
| bsd-2-clause | -7,293,954,927,933,790,000 | 38.363454 | 83 | 0.644442 | false | 4.028566 | false | false | false |
jonwright/ImageD11 | scripts/plotImageD11map.py | 1 | 1829 | #!/usr/bin/env python
from __future__ import print_function
from ImageD11.grain import read_grain_file
import sys, os
gf = read_grain_file(sys.argv[1])
mapfile=open(sys.argv[2],"w")
def dodot(xyz,k):
mapfile.write("%f %f %f %d\n"%(xyz[0],xyz[1],xyz[2],k))
def getmedian(s):
items=s.split()
j = -1
for i in range(len(items)):
if items[i] == "median":
j = i
if j == -1:
return 0
return abs(float(items[j+2]))
try:
outersf = float(sys.argv[3])
except:
outersf = 1.0
print("Scale factor is",outersf)
for g in gf:
#print g.translation, g.ubi
mapfile.write("\n\n")
o = g.translation
try:
sf = pow(getmedian(g.intensity_info),0.3333)*outersf
except:
sf = outersf
try:
k = int(g.npks)
except:
k = 1
for u in g.ubi:
dodot(o,k)
dodot(o+u*sf,int(g.npks))
for u in g.ubi:
dodot(o,k)
dodot(o-u*sf,int(g.npks))
# dodot(o,k)
# dodot(o+sf*(-g.ubi[0]-g.ubi[1]),k)
# dodot(o,k)
# dodot(o+sf*(g.ubi[0]+g.ubi[1]),k)
mapfile.close()
term = " "
if "linux" in sys.platform:
term = "set term x11"
if "win32" in sys.platform:
term = "set term windows"
open("gnuplot.in","w").write("""
%s
set ticslevel 0
set title "Color proportional to number of peaks"
set palette model RGB
set palette defined ( 0 "violet", 1 "blue", 2 "green", 3 "yellow", 4 "orange", 5 "red" )
set view equal xyz
set view 75,0,1,1
#set terminal gif animate delay 10 loop 1 optimize size 1024,768
set nokey
set hidden3d
#set output "ImageD11map.gif"
splot "%s" u 1:2:3:4 w l lw 2 lc pal z
"""%(term, sys.argv[2])
# "".join(["set view 75,%d\n replot\n"%(i) for i in range(1,360,1)])
)
os.system("gnuplot -background white gnuplot.in -")
| gpl-2.0 | -5,133,550,507,565,548,000 | 21.304878 | 88 | 0.574631 | false | 2.57969 | false | false | false |
eicher31/compassion-modules | child_compassion/mappings/household_mapping.py | 3 | 3536 | # -*- coding: utf-8 -*-
##############################################################################
#
# Copyright (C) 2016 Compassion CH (http://www.compassion.ch)
# Releasing children from poverty in Jesus' name
# @author: Emanuel Cino <ecino@compassion.ch>
#
# The licence is in the file __manifest__.py
#
##############################################################################
from odoo.addons.message_center_compassion.mappings.base_mapping import \
OnrampMapping
class HouseHoldMapping(OnrampMapping):
ODOO_MODEL = 'compassion.household'
CONNECT_MAPPING = {
"BeneficiaryHouseholdMemberList": ('member_ids',
'compassion.household.member'),
"BeneficiaryHouseholdMemberDetails": ('member_ids',
'compassion.household.member'),
"FemaleGuardianEmploymentStatus": 'female_guardian_job_type',
"FemaleGuardianOccupation": 'female_guardian_job',
"Household_ID": "household_id",
"Household_Name": "name",
"IsNaturalFatherLivingWithChild": 'father_living_with_child',
"IsNaturalMotherLivingWithChild": 'mother_living_with_child',
"MaleGuardianEmploymentStatus": 'male_guardian_job_type',
"MaleGuardianOccupation": "male_guardian_job",
"NaturalFatherAlive": "father_alive",
"NaturalMotherAlive": "mother_alive",
"NumberOfSiblingBeneficiaries": "number_beneficiaries",
"ParentsMaritalStatus": "marital_status",
"ParentsTogether": "parents_together",
'RevisedValues': 'revised_value_ids',
# Not define
"SourceKitName": None,
}
def _process_odoo_data(self, odoo_data):
# Unlink old revised values and create new ones
if isinstance(odoo_data.get('revised_value_ids'), list):
household = self.env[self.ODOO_MODEL].search(
[('household_id', '=', odoo_data['household_id'])])
household.revised_value_ids.unlink()
for value in odoo_data['revised_value_ids']:
self.env['compassion.major.revision'].create({
'name': value,
'household_id': household.id,
})
del odoo_data['revised_value_ids']
# Replace dict by a tuple for the ORM update/create
if 'member_ids' in odoo_data:
# Remove all members
household = self.env[self.ODOO_MODEL].search(
[('household_id', '=', odoo_data['household_id'])])
household.member_ids.unlink()
member_list = list()
for member in odoo_data['member_ids']:
orm_tuple = (0, 0, member)
member_list.append(orm_tuple)
odoo_data['member_ids'] = member_list or False
for key in odoo_data.iterkeys():
val = odoo_data[key]
if isinstance(val, basestring) and val.lower() in (
'null', 'false', 'none', 'other', 'unknown'):
odoo_data[key] = False
class HouseholdMemberMapping(OnrampMapping):
ODOO_MODEL = 'compassion.household.member'
CONNECT_MAPPING = {
"Beneficiary_GlobalID": ('child_id.global_id', 'compassion.child'),
"Beneficiary_LocalID": 'beneficiary_local_id',
"FullName": None,
"HouseholdMemberRole": 'role',
"HouseholdMember_Name": 'name',
"IsCaregiver": 'is_caregiver',
"IsPrimaryCaregiver": 'is_primary_caregiver',
}
| agpl-3.0 | 8,306,735,830,094,433,000 | 40.116279 | 78 | 0.565328 | false | 3.69488 | false | false | false |
go-bears/nupic | src/nupic/encoders/category.py | 39 | 7798 | # ----------------------------------------------------------------------
# Numenta Platform for Intelligent Computing (NuPIC)
# Copyright (C) 2013, Numenta, Inc. Unless you have an agreement
# with Numenta, Inc., for a separate license for this software code, the
# following terms and conditions apply:
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero Public License version 3 as
# published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
# See the GNU Affero Public License for more details.
#
# You should have received a copy of the GNU Affero Public License
# along with this program. If not, see http://www.gnu.org/licenses.
#
# http://numenta.org/licenses/
# ----------------------------------------------------------------------
import numpy
from nupic.data.fieldmeta import FieldMetaType
from nupic.data import SENTINEL_VALUE_FOR_MISSING_DATA
from nupic.encoders.base import Encoder, EncoderResult
from nupic.encoders.scalar import ScalarEncoder
UNKNOWN = "<UNKNOWN>"
class CategoryEncoder(Encoder):
"""Encodes a list of discrete categories (described by strings), that aren't
related to each other, so we never emit a mixture of categories.
The value of zero is reserved for "unknown category"
Internally we use a ScalarEncoder with a radius of 1, but since we only encode
integers, we never get mixture outputs.
The SDRCategoryEncoder uses a different method to encode categories"""
def __init__(self, w, categoryList, name="category", verbosity=0, forced=False):
"""params:
forced (default False) : if True, skip checks for parameters' settings; see encoders/scalar.py for details
"""
self.encoders = None
self.verbosity = verbosity
# number of categories includes "unknown"
self.ncategories = len(categoryList) + 1
self.categoryToIndex = dict()
self.indexToCategory = dict()
self.indexToCategory[0] = UNKNOWN
for i in xrange(len(categoryList)):
self.categoryToIndex[categoryList[i]] = i+1
self.indexToCategory[i+1] = categoryList[i]
self.encoder = ScalarEncoder(w, minval=0, maxval=self.ncategories - 1,
radius=1, periodic=False, forced=forced)
self.width = w * self.ncategories
assert self.encoder.getWidth() == self.width
self.description = [(name, 0)]
self.name = name
# These are used to support the topDownCompute method
self._topDownMappingM = None
# This gets filled in by getBucketValues
self._bucketValues = None
def getDecoderOutputFieldTypes(self):
""" [Encoder class virtual method override]
"""
# TODO: change back to string meta-type after the decoding logic is fixed
# to output strings instead of internal index values.
#return (FieldMetaType.string,)
return (FieldMetaType.integer,)
def getWidth(self):
return self.width
def getDescription(self):
return self.description
def getScalars(self, input):
""" See method description in base.py """
if input == SENTINEL_VALUE_FOR_MISSING_DATA:
return numpy.array([None])
else:
return numpy.array([self.categoryToIndex.get(input, 0)])
def getBucketIndices(self, input):
""" See method description in base.py """
# Get the bucket index from the underlying scalar encoder
if input == SENTINEL_VALUE_FOR_MISSING_DATA:
return [None]
else:
return self.encoder.getBucketIndices(self.categoryToIndex.get(input, 0))
def encodeIntoArray(self, input, output):
# if not found, we encode category 0
if input == SENTINEL_VALUE_FOR_MISSING_DATA:
output[0:] = 0
val = "<missing>"
else:
val = self.categoryToIndex.get(input, 0)
self.encoder.encodeIntoArray(val, output)
if self.verbosity >= 2:
print "input:", input, "va:", val, "output:", output
print "decoded:", self.decodedToStr(self.decode(output))
def decode(self, encoded, parentFieldName=''):
""" See the function description in base.py
"""
# Get the scalar values from the underlying scalar encoder
(fieldsDict, fieldNames) = self.encoder.decode(encoded)
if len(fieldsDict) == 0:
return (fieldsDict, fieldNames)
# Expect only 1 field
assert(len(fieldsDict) == 1)
# Get the list of categories the scalar values correspond to and
# generate the description from the category name(s).
(inRanges, inDesc) = fieldsDict.values()[0]
outRanges = []
desc = ""
for (minV, maxV) in inRanges:
minV = int(round(minV))
maxV = int(round(maxV))
outRanges.append((minV, maxV))
while minV <= maxV:
if len(desc) > 0:
desc += ", "
desc += self.indexToCategory[minV]
minV += 1
# Return result
if parentFieldName != '':
fieldName = "%s.%s" % (parentFieldName, self.name)
else:
fieldName = self.name
return ({fieldName: (outRanges, desc)}, [fieldName])
def closenessScores(self, expValues, actValues, fractional=True,):
""" See the function description in base.py
kwargs will have the keyword "fractional", which is ignored by this encoder
"""
expValue = expValues[0]
actValue = actValues[0]
if expValue == actValue:
closeness = 1.0
else:
closeness = 0.0
if not fractional:
closeness = 1.0 - closeness
return numpy.array([closeness])
def getBucketValues(self):
""" See the function description in base.py """
if self._bucketValues is None:
numBuckets = len(self.encoder.getBucketValues())
self._bucketValues = []
for bucketIndex in range(numBuckets):
self._bucketValues.append(self.getBucketInfo([bucketIndex])[0].value)
return self._bucketValues
def getBucketInfo(self, buckets):
""" See the function description in base.py
"""
# For the category encoder, the bucket index is the category index
bucketInfo = self.encoder.getBucketInfo(buckets)[0]
categoryIndex = int(round(bucketInfo.value))
category = self.indexToCategory[categoryIndex]
return [EncoderResult(value=category, scalar=categoryIndex,
encoding=bucketInfo.encoding)]
def topDownCompute(self, encoded):
""" See the function description in base.py
"""
encoderResult = self.encoder.topDownCompute(encoded)[0]
value = encoderResult.value
categoryIndex = int(round(value))
category = self.indexToCategory[categoryIndex]
return EncoderResult(value=category, scalar=categoryIndex,
encoding=encoderResult.encoding)
@classmethod
def read(cls, proto):
encoder = object.__new__(cls)
encoder.verbosity = proto.verbosity
encoder.encoder = ScalarEncoder.read(proto.encoder)
encoder.width = proto.width
encoder.description = [(proto.name, 0)]
encoder.name = proto.name
encoder.indexToCategory = {x.index: x.category
for x in proto.indexToCategory}
encoder.categoryToIndex = {category: index
for index, category
in encoder.indexToCategory.items()
if category != UNKNOWN}
encoder._topDownMappingM = None
encoder._bucketValues = None
return encoder
def write(self, proto):
proto.width = self.width
proto.indexToCategory = [
{"index": index, "category": category}
for index, category in self.indexToCategory.items()
]
proto.name = self.name
proto.verbosity = self.verbosity
self.encoder.write(proto.encoder)
| agpl-3.0 | -742,178,916,835,247,100 | 29.944444 | 113 | 0.662349 | false | 4.093438 | false | false | false |
dvliman/jaikuengine | .google_appengine/lib/django-1.5/tests/regressiontests/extra_regress/models.py | 114 | 1365 | from __future__ import unicode_literals
import copy
import datetime
from django.contrib.auth.models import User
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
@python_2_unicode_compatible
class RevisionableModel(models.Model):
base = models.ForeignKey('self', null=True)
title = models.CharField(blank=True, max_length=255)
when = models.DateTimeField(default=datetime.datetime.now)
def __str__(self):
return "%s (%s, %s)" % (self.title, self.id, self.base.id)
def save(self, *args, **kwargs):
super(RevisionableModel, self).save(*args, **kwargs)
if not self.base:
self.base = self
kwargs.pop('force_insert', None)
kwargs.pop('force_update', None)
super(RevisionableModel, self).save(*args, **kwargs)
def new_revision(self):
new_revision = copy.copy(self)
new_revision.pk = None
return new_revision
class Order(models.Model):
created_by = models.ForeignKey(User)
text = models.TextField()
@python_2_unicode_compatible
class TestObject(models.Model):
first = models.CharField(max_length=20)
second = models.CharField(max_length=20)
third = models.CharField(max_length=20)
def __str__(self):
return 'TestObject: %s,%s,%s' % (self.first,self.second,self.third)
| apache-2.0 | -6,502,126,748,451,387,000 | 29.333333 | 75 | 0.667399 | false | 3.611111 | false | false | false |
goFrendiAsgard/kokoropy | kokoropy/packages/sqlalchemy/dialects/mysql/pyodbc.py | 32 | 2640 | # mysql/pyodbc.py
# Copyright (C) 2005-2014 the SQLAlchemy authors and contributors
# <see AUTHORS file>
#
# This module is part of SQLAlchemy and is released under
# the MIT License: http://www.opensource.org/licenses/mit-license.php
"""
.. dialect:: mysql+pyodbc
:name: PyODBC
:dbapi: pyodbc
:connectstring: mysql+pyodbc://<username>:<password>@<dsnname>
:url: http://pypi.python.org/pypi/pyodbc/
Limitations
-----------
The mysql-pyodbc dialect is subject to unresolved character encoding issues
which exist within the current ODBC drivers available.
(see http://code.google.com/p/pyodbc/issues/detail?id=25). Consider usage
of OurSQL, MySQLdb, or MySQL-connector/Python.
"""
from .base import MySQLDialect, MySQLExecutionContext
from ...connectors.pyodbc import PyODBCConnector
from ... import util
import re
class MySQLExecutionContext_pyodbc(MySQLExecutionContext):
def get_lastrowid(self):
cursor = self.create_cursor()
cursor.execute("SELECT LAST_INSERT_ID()")
lastrowid = cursor.fetchone()[0]
cursor.close()
return lastrowid
class MySQLDialect_pyodbc(PyODBCConnector, MySQLDialect):
supports_unicode_statements = False
execution_ctx_cls = MySQLExecutionContext_pyodbc
pyodbc_driver_name = "MySQL"
def __init__(self, **kw):
# deal with http://code.google.com/p/pyodbc/issues/detail?id=25
kw.setdefault('convert_unicode', True)
super(MySQLDialect_pyodbc, self).__init__(**kw)
def _detect_charset(self, connection):
"""Sniff out the character set in use for connection results."""
# Prefer 'character_set_results' for the current connection over the
# value in the driver. SET NAMES or individual variable SETs will
# change the charset without updating the driver's view of the world.
#
# If it's decided that issuing that sort of SQL leaves you SOL, then
# this can prefer the driver value.
rs = connection.execute("SHOW VARIABLES LIKE 'character_set%%'")
opts = dict([(row[0], row[1]) for row in self._compat_fetchall(rs)])
for key in ('character_set_connection', 'character_set'):
if opts.get(key, None):
return opts[key]
util.warn("Could not detect the connection character set. "
"Assuming latin1.")
return 'latin1'
def _extract_error_code(self, exception):
m = re.compile(r"\((\d+)\)").search(str(exception.args))
c = m.group(1)
if c:
return int(c)
else:
return None
dialect = MySQLDialect_pyodbc
| mit | -6,467,777,041,147,659,000 | 31.195122 | 77 | 0.660606 | false | 3.776824 | false | false | false |
chienlieu2017/it_management | odoo/addons/website_event/controllers/main.py | 7 | 11571 | # -*- coding: utf-8 -*-
import babel.dates
import re
import werkzeug
from datetime import datetime, timedelta
from dateutil.relativedelta import relativedelta
from odoo import fields, http, _
from odoo.addons.website.models.website import slug
from odoo.http import request
class WebsiteEventController(http.Controller):
@http.route(['/event', '/event/page/<int:page>', '/events', '/events/page/<int:page>'], type='http', auth="public", website=True)
def events(self, page=1, **searches):
Event = request.env['event.event']
EventType = request.env['event.type']
searches.setdefault('date', 'all')
searches.setdefault('type', 'all')
searches.setdefault('country', 'all')
domain_search = {}
def sdn(date):
return fields.Datetime.to_string(date.replace(hour=23, minute=59, second=59))
def sd(date):
return fields.Datetime.to_string(date)
today = datetime.today()
dates = [
['all', _('Next Events'), [("date_end", ">", sd(today))], 0],
['today', _('Today'), [
("date_end", ">", sd(today)),
("date_begin", "<", sdn(today))],
0],
['week', _('This Week'), [
("date_end", ">=", sd(today + relativedelta(days=-today.weekday()))),
("date_begin", "<", sdn(today + relativedelta(days=6-today.weekday())))],
0],
['nextweek', _('Next Week'), [
("date_end", ">=", sd(today + relativedelta(days=7-today.weekday()))),
("date_begin", "<", sdn(today + relativedelta(days=13-today.weekday())))],
0],
['month', _('This month'), [
("date_end", ">=", sd(today.replace(day=1))),
("date_begin", "<", (today.replace(day=1) + relativedelta(months=1)).strftime('%Y-%m-%d 00:00:00'))],
0],
['nextmonth', _('Next month'), [
("date_end", ">=", sd(today.replace(day=1) + relativedelta(months=1))),
("date_begin", "<", (today.replace(day=1) + relativedelta(months=2)).strftime('%Y-%m-%d 00:00:00'))],
0],
['old', _('Old Events'), [
("date_end", "<", today.strftime('%Y-%m-%d 00:00:00'))],
0],
]
# search domains
# TDE note: WTF ???
current_date = None
current_type = None
current_country = None
for date in dates:
if searches["date"] == date[0]:
domain_search["date"] = date[2]
if date[0] != 'all':
current_date = date[1]
if searches["type"] != 'all':
current_type = EventType.browse(int(searches['type']))
domain_search["type"] = [("event_type_id", "=", int(searches["type"]))]
if searches["country"] != 'all' and searches["country"] != 'online':
current_country = request.env['res.country'].browse(int(searches['country']))
domain_search["country"] = ['|', ("country_id", "=", int(searches["country"])), ("country_id", "=", False)]
elif searches["country"] == 'online':
domain_search["country"] = [("country_id", "=", False)]
def dom_without(without):
domain = [('state', "in", ['draft', 'confirm', 'done'])]
for key, search in domain_search.items():
if key != without:
domain += search
return domain
# count by domains without self search
for date in dates:
if date[0] != 'old':
date[3] = Event.search_count(dom_without('date') + date[2])
domain = dom_without('type')
types = Event.read_group(domain, ["id", "event_type_id"], groupby=["event_type_id"], orderby="event_type_id")
types.insert(0, {
'event_type_id_count': sum([int(type['event_type_id_count']) for type in types]),
'event_type_id': ("all", _("All Categories"))
})
domain = dom_without('country')
countries = Event.read_group(domain, ["id", "country_id"], groupby="country_id", orderby="country_id")
countries.insert(0, {
'country_id_count': sum([int(country['country_id_count']) for country in countries]),
'country_id': ("all", _("All Countries"))
})
step = 10 # Number of events per page
event_count = Event.search_count(dom_without("none"))
pager = request.website.pager(
url="/event",
url_args={'date': searches.get('date'), 'type': searches.get('type'), 'country': searches.get('country')},
total=event_count,
page=page,
step=step,
scope=5)
order = 'website_published desc, date_begin'
if searches.get('date', 'all') == 'old':
order = 'website_published desc, date_begin desc'
events = Event.search(dom_without("none"), limit=step, offset=pager['offset'], order=order)
values = {
'current_date': current_date,
'current_country': current_country,
'current_type': current_type,
'event_ids': events, # event_ids used in website_event_track so we keep name as it is
'dates': dates,
'types': types,
'countries': countries,
'pager': pager,
'searches': searches,
'search_path': "?%s" % werkzeug.url_encode(searches),
}
return request.render("website_event.index", values)
@http.route(['/event/<model("event.event"):event>/page/<path:page>'], type='http', auth="public", website=True)
def event_page(self, event, page, **post):
values = {
'event': event,
'main_object': event
}
if '.' not in page:
page = 'website_event.%s' % page
try:
request.website.get_template(page)
except ValueError:
# page not found
values['path'] = re.sub(r"^website_event\.", '', page)
values['from_template'] = 'website_event.default_page' # .strip('website_event.')
page = 'website.page_404'
return request.render(page, values)
@http.route(['/event/<model("event.event"):event>'], type='http', auth="public", website=True)
def event(self, event, **post):
if event.menu_id and event.menu_id.child_id:
target_url = event.menu_id.child_id[0].url
else:
target_url = '/event/%s/register' % str(event.id)
if post.get('enable_editor') == '1':
target_url += '?enable_editor=1'
return request.redirect(target_url)
@http.route(['/event/<model("event.event"):event>/register'], type='http', auth="public", website=True)
def event_register(self, event, **post):
values = {
'event': event,
'main_object': event,
'range': range,
}
return request.render("website_event.event_description_full", values)
@http.route('/event/add_event', type='http', auth="user", methods=['POST'], website=True)
def add_event(self, event_name="New Event", **kwargs):
event = self._add_event(event_name, request.context)
return request.redirect("/event/%s/register?enable_editor=1" % slug(event))
def _add_event(self, event_name=None, context=None, **kwargs):
if not event_name:
event_name = _("New Event")
date_begin = datetime.today() + timedelta(days=(14))
vals = {
'name': event_name,
'date_begin': fields.Date.to_string(date_begin),
'date_end': fields.Date.to_string((date_begin + timedelta(days=(1)))),
'seats_available': 1000,
}
return request.env['event.event'].with_context(context or {}).create(vals)
def get_formated_date(self, event):
start_date = fields.Datetime.from_string(event.date_begin).date()
end_date = fields.Datetime.from_string(event.date_end).date()
month = babel.dates.get_month_names('abbreviated', locale=event.env.context.get('lang', 'en_US'))[start_date.month]
return ('%s %s%s') % (month, start_date.strftime("%e"), (end_date != start_date and ("-" + end_date.strftime("%e")) or ""))
@http.route('/event/get_country_event_list', type='http', auth='public', website=True)
def get_country_events(self, **post):
Event = request.env['event.event']
country_code = request.session['geoip'].get('country_code')
result = {'events': [], 'country': False}
events = None
if country_code:
country = request.env['res.country'].search([('code', '=', country_code)], limit=1)
events = Event.search(['|', ('address_id', '=', None), ('country_id.code', '=', country_code), ('date_begin', '>=', '%s 00:00:00' % fields.Date.today()), ('state', '=', 'confirm')], order="date_begin")
if not events:
events = Event.search([('date_begin', '>=', '%s 00:00:00' % fields.Date.today()), ('state', '=', 'confirm')], order="date_begin")
for event in events:
if country_code and event.country_id.code == country_code:
result['country'] = country
result['events'].append({
"date": self.get_formated_date(event),
"event": event,
"url": event.website_url})
return request.render("website_event.country_events_list", result)
def _process_tickets_details(self, data):
nb_register = int(data.get('nb_register-0', 0))
if nb_register:
return [{'id': 0, 'name': 'Registration', 'quantity': nb_register, 'price': 0}]
return []
@http.route(['/event/<model("event.event"):event>/registration/new'], type='json', auth="public", methods=['POST'], website=True)
def registration_new(self, event, **post):
tickets = self._process_tickets_details(post)
if not tickets:
return request.redirect("/event/%s" % slug(event))
return request.env['ir.ui.view'].render_template("website_event.registration_attendee_details", {'tickets': tickets, 'event': event})
def _process_registration_details(self, details):
''' Process data posted from the attendee details form. '''
registrations = {}
global_values = {}
for key, value in details.iteritems():
counter, field_name = key.split('-', 1)
if counter == '0':
global_values[field_name] = value
else:
registrations.setdefault(counter, dict())[field_name] = value
for key, value in global_values.iteritems():
for registration in registrations.values():
registration[key] = value
return registrations.values()
@http.route(['/event/<model("event.event"):event>/registration/confirm'], type='http', auth="public", methods=['POST'], website=True)
def registration_confirm(self, event, **post):
Attendees = request.env['event.registration']
registrations = self._process_registration_details(post)
for registration in registrations:
registration['event_id'] = event
Attendees += Attendees.sudo().create(
Attendees._prepare_attendee_values(registration))
return request.render("website_event.registration_complete", {
'attendees': Attendees,
'event': event,
})
| gpl-3.0 | 8,617,715,063,772,964,000 | 43.675676 | 213 | 0.551465 | false | 3.881583 | false | false | false |
derekjchow/models | research/deeplab/core/nas_cell.py | 1 | 8432 | # 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.
# ==============================================================================
"""Cell structure used by NAS."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import tensorflow as tf
from deeplab.core.utils import resize_bilinear
from deeplab.core.utils import scale_dimension
arg_scope = tf.contrib.framework.arg_scope
slim = tf.contrib.slim
class NASBaseCell(object):
"""NASNet Cell class that is used as a 'layer' in image architectures.
See https://arxiv.org/abs/1707.07012 and https://arxiv.org/abs/1712.00559.
Args:
num_conv_filters: The number of filters for each convolution operation.
operations: List of operations that are performed in the NASNet Cell in
order.
used_hiddenstates: Binary array that signals if the hiddenstate was used
within the cell. This is used to determine what outputs of the cell
should be concatenated together.
hiddenstate_indices: Determines what hiddenstates should be combined
together with the specified operations to create the NASNet cell.
"""
def __init__(self, num_conv_filters, operations, used_hiddenstates,
hiddenstate_indices, drop_path_keep_prob, total_num_cells,
total_training_steps):
if len(hiddenstate_indices) != len(operations):
raise ValueError(
'Number of hiddenstate_indices and operations should be the same.')
if len(operations) % 2:
raise ValueError('Number of operations should be even.')
self._num_conv_filters = num_conv_filters
self._operations = operations
self._used_hiddenstates = used_hiddenstates
self._hiddenstate_indices = hiddenstate_indices
self._drop_path_keep_prob = drop_path_keep_prob
self._total_num_cells = total_num_cells
self._total_training_steps = total_training_steps
def __call__(self, net, scope, filter_scaling, stride, prev_layer, cell_num):
"""Runs the conv cell."""
self._cell_num = cell_num
self._filter_scaling = filter_scaling
self._filter_size = int(self._num_conv_filters * filter_scaling)
with tf.variable_scope(scope):
net = self._cell_base(net, prev_layer)
for i in range(len(self._operations) // 2):
with tf.variable_scope('comb_iter_{}'.format(i)):
h1 = net[self._hiddenstate_indices[i * 2]]
h2 = net[self._hiddenstate_indices[i * 2 + 1]]
with tf.variable_scope('left'):
h1 = self._apply_conv_operation(
h1, self._operations[i * 2], stride,
self._hiddenstate_indices[i * 2] < 2)
with tf.variable_scope('right'):
h2 = self._apply_conv_operation(
h2, self._operations[i * 2 + 1], stride,
self._hiddenstate_indices[i * 2 + 1] < 2)
with tf.variable_scope('combine'):
h = h1 + h2
net.append(h)
with tf.variable_scope('cell_output'):
net = self._combine_unused_states(net)
return net
def _cell_base(self, net, prev_layer):
"""Runs the beginning of the conv cell before the chosen ops are run."""
filter_size = self._filter_size
if prev_layer is None:
prev_layer = net
else:
if net.shape[2] != prev_layer.shape[2]:
prev_layer = resize_bilinear(
prev_layer, tf.shape(net)[1:3], prev_layer.dtype)
if filter_size != prev_layer.shape[3]:
prev_layer = tf.nn.relu(prev_layer)
prev_layer = slim.conv2d(prev_layer, filter_size, 1, scope='prev_1x1')
prev_layer = slim.batch_norm(prev_layer, scope='prev_bn')
net = tf.nn.relu(net)
net = slim.conv2d(net, filter_size, 1, scope='1x1')
net = slim.batch_norm(net, scope='beginning_bn')
net = tf.split(axis=3, num_or_size_splits=1, value=net)
net.append(prev_layer)
return net
def _apply_conv_operation(self, net, operation, stride,
is_from_original_input):
"""Applies the predicted conv operation to net."""
if stride > 1 and not is_from_original_input:
stride = 1
input_filters = net.shape[3]
filter_size = self._filter_size
if 'separable' in operation:
num_layers = int(operation.split('_')[-1])
kernel_size = int(operation.split('x')[0][-1])
for layer_num in range(num_layers):
net = tf.nn.relu(net)
net = slim.separable_conv2d(
net,
filter_size,
kernel_size,
depth_multiplier=1,
scope='separable_{0}x{0}_{1}'.format(kernel_size, layer_num + 1),
stride=stride)
net = slim.batch_norm(
net, scope='bn_sep_{0}x{0}_{1}'.format(kernel_size, layer_num + 1))
stride = 1
elif 'atrous' in operation:
kernel_size = int(operation.split('x')[0][-1])
net = tf.nn.relu(net)
if stride == 2:
scaled_height = scale_dimension(tf.shape(net)[1], 0.5)
scaled_width = scale_dimension(tf.shape(net)[2], 0.5)
net = resize_bilinear(net, [scaled_height, scaled_width], net.dtype)
net = slim.conv2d(net, filter_size, kernel_size, rate=1,
scope='atrous_{0}x{0}'.format(kernel_size))
else:
net = slim.conv2d(net, filter_size, kernel_size, rate=2,
scope='atrous_{0}x{0}'.format(kernel_size))
net = slim.batch_norm(net, scope='bn_atr_{0}x{0}'.format(kernel_size))
elif operation in ['none']:
if stride > 1 or (input_filters != filter_size):
net = tf.nn.relu(net)
net = slim.conv2d(net, filter_size, 1, stride=stride, scope='1x1')
net = slim.batch_norm(net, scope='bn_1')
elif 'pool' in operation:
pooling_type = operation.split('_')[0]
pooling_shape = int(operation.split('_')[-1].split('x')[0])
if pooling_type == 'avg':
net = slim.avg_pool2d(net, pooling_shape, stride=stride, padding='SAME')
elif pooling_type == 'max':
net = slim.max_pool2d(net, pooling_shape, stride=stride, padding='SAME')
else:
raise ValueError('Unimplemented pooling type: ', pooling_type)
if input_filters != filter_size:
net = slim.conv2d(net, filter_size, 1, stride=1, scope='1x1')
net = slim.batch_norm(net, scope='bn_1')
else:
raise ValueError('Unimplemented operation', operation)
if operation != 'none':
net = self._apply_drop_path(net)
return net
def _combine_unused_states(self, net):
"""Concatenates the unused hidden states of the cell."""
used_hiddenstates = self._used_hiddenstates
states_to_combine = ([
h for h, is_used in zip(net, used_hiddenstates) if not is_used])
net = tf.concat(values=states_to_combine, axis=3)
return net
@tf.contrib.framework.add_arg_scope
def _apply_drop_path(self, net):
"""Apply drop_path regularization."""
drop_path_keep_prob = self._drop_path_keep_prob
if drop_path_keep_prob < 1.0:
# Scale keep prob by layer number.
assert self._cell_num != -1
layer_ratio = (self._cell_num + 1) / float(self._total_num_cells)
drop_path_keep_prob = 1 - layer_ratio * (1 - drop_path_keep_prob)
# Decrease keep prob over time.
current_step = tf.cast(tf.train.get_or_create_global_step(), tf.float32)
current_ratio = tf.minimum(1.0, current_step / self._total_training_steps)
drop_path_keep_prob = (1 - current_ratio * (1 - drop_path_keep_prob))
# Drop path.
noise_shape = [tf.shape(net)[0], 1, 1, 1]
random_tensor = drop_path_keep_prob
random_tensor += tf.random_uniform(noise_shape, dtype=tf.float32)
binary_tensor = tf.cast(tf.floor(random_tensor), net.dtype)
keep_prob_inv = tf.cast(1.0 / drop_path_keep_prob, net.dtype)
net = net * keep_prob_inv * binary_tensor
return net
| apache-2.0 | 4,058,546,181,967,095,300 | 41.371859 | 80 | 0.629032 | false | 3.51187 | false | false | false |
sgarrity/bedrock | lib/l10n_utils/management/commands/fluent.py | 8 | 3597 | # This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
from pathlib import Path
import textwrap
from django.core.management.base import BaseCommand
class Command(BaseCommand):
help = 'Convert a template to use Fluent for l10n'
requires_system_checks = False
def add_arguments(self, parser):
subparsers = parser.add_subparsers(
title='subcommand', dest='subcommand'
)
subparsers.add_parser('help')
recipe_parser = subparsers.add_parser(
'recipe',
description='Create migration recipe from template'
)
recipe_parser.add_argument('template', type=Path)
ftl_parser = subparsers.add_parser(
'ftl',
description='Create Fluent file with existing recipe'
)
ftl_parser.add_argument(
'recipe_or_template', type=Path,
help='Path to the recipe or the template from which the recipe was generated'
)
ftl_parser.add_argument(
'locales', nargs='*', default=['en'], metavar='ab-CD',
help='Locale codes to create ftl files for'
)
template_parser = subparsers.add_parser(
'template',
description='Create template_ftl.html file with existing recipe'
)
template_parser.add_argument('template', type=Path)
activation_parser = subparsers.add_parser(
'activation',
description='Port activation data from .lang for a recipe/template'
)
activation_parser.add_argument(
'recipe_or_template', type=Path,
help='Path to the recipe or the template from which the recipe was generated'
)
def handle(self, subcommand, **kwargs):
if subcommand == 'recipe':
return self.create_recipe(**kwargs)
if subcommand == 'ftl':
return self.create_ftl(**kwargs)
if subcommand == 'template':
return self.create_template(**kwargs)
if subcommand == 'activation':
return self.activation(**kwargs)
return self.handle_help(**kwargs)
def handle_help(self, **kwargs):
self.stdout.write(textwrap.dedent('''\
To migrate a template from .lang to Fluent, use the subcommands like so
./manage.py fluent recipe bedrock/app/templates/app/some.html
# edit IDs in lib/fluent_migrations/app/some.py
./manage.py fluent template bedrock/app/templates/app/some.html
./manage.py fluent ftl bedrock/app/templates/app/some.html
More documentation on https://bedrock.readthedocs.io/en/latest/fluent-conversion.html.
'''))
def create_recipe(self, template, **kwargs):
from ._fluent_recipe import Recipe
recipe = Recipe(self)
recipe.handle(template)
def create_template(self, template, **kwargs):
from ._fluent_templater import Templater
templater = Templater(self)
templater.handle(template)
def create_ftl(self, recipe_or_template, locales, **kwargs):
from ._fluent_ftl import FTLCreator
ftl_creator = FTLCreator(self)
for locale in locales:
ftl_creator.handle(recipe_or_template, locale)
def activation(self, recipe_or_template, **kwargs):
from ._fluent_activation import Activation
activation = Activation(self)
activation.handle(recipe_or_template)
| mpl-2.0 | -920,462,829,349,169,400 | 35.333333 | 98 | 0.627189 | false | 4.221831 | false | false | false |
kevinmel2000/brython | www/src/Lib/test/unittests/test_cgitb.py | 113 | 2551 | from test.support import run_unittest
from test.script_helper import assert_python_failure, temp_dir
import unittest
import sys
import cgitb
class TestCgitb(unittest.TestCase):
def test_fonts(self):
text = "Hello Robbie!"
self.assertEqual(cgitb.small(text), "<small>{}</small>".format(text))
self.assertEqual(cgitb.strong(text), "<strong>{}</strong>".format(text))
self.assertEqual(cgitb.grey(text),
'<font color="#909090">{}</font>'.format(text))
def test_blanks(self):
self.assertEqual(cgitb.small(""), "")
self.assertEqual(cgitb.strong(""), "")
self.assertEqual(cgitb.grey(""), "")
def test_html(self):
try:
raise ValueError("Hello World")
except ValueError as err:
# If the html was templated we could do a bit more here.
# At least check that we get details on what we just raised.
html = cgitb.html(sys.exc_info())
self.assertIn("ValueError", html)
self.assertIn(str(err), html)
def test_text(self):
try:
raise ValueError("Hello World")
except ValueError as err:
text = cgitb.text(sys.exc_info())
self.assertIn("ValueError", text)
self.assertIn("Hello World", text)
def test_syshook_no_logdir_default_format(self):
with temp_dir() as tracedir:
rc, out, err = assert_python_failure(
'-c',
('import cgitb; cgitb.enable(logdir=%s); '
'raise ValueError("Hello World")') % repr(tracedir))
out = out.decode(sys.getfilesystemencoding())
self.assertIn("ValueError", out)
self.assertIn("Hello World", out)
# By default we emit HTML markup.
self.assertIn('<p>', out)
self.assertIn('</p>', out)
def test_syshook_no_logdir_text_format(self):
# Issue 12890: we were emitting the <p> tag in text mode.
with temp_dir() as tracedir:
rc, out, err = assert_python_failure(
'-c',
('import cgitb; cgitb.enable(format="text", logdir=%s); '
'raise ValueError("Hello World")') % repr(tracedir))
out = out.decode(sys.getfilesystemencoding())
self.assertIn("ValueError", out)
self.assertIn("Hello World", out)
self.assertNotIn('<p>', out)
self.assertNotIn('</p>', out)
def test_main():
run_unittest(TestCgitb)
if __name__ == "__main__":
test_main()
| bsd-3-clause | -8,993,424,027,276,596,000 | 35.442857 | 80 | 0.573501 | false | 3.900612 | true | false | false |
rhololkeolke/apo-website-devin | src/application/facebook/facebook.py | 2 | 8731 | """
This module contains helper classes and methods
for the facebook integration module
.. module:: application.facebook.facebook
.. moduleauthor:: Devin Schwab <dts34@case.edu>
"""
import facebooksdk as fb
import models
from flask import flash
class AlbumList(object):
def __init__(self, token):
"""
Given an an access token this class
will get all albums for the object associated with the token
(i.e. a page or a user)
It will lazily construct an Album instance for each of
the album ids returned
"""
self.graph = fb.GraphAPI(token.access_token)
albums_data = self.graph.get_connections('me', 'albums')['data']
self.album_ids = {}
self.album_names = {}
for data in albums_data:
self.album_ids[data['id']] = data
self.album_names[data['name']] = data
def get_albums_by_name(self, names):
"""
Given a list of names this method will
return album objects for each matching name.
If a name is not found then it is silently ignored.
This method returns a dictionary mapping name
to Album object.
"""
albums = {}
for name in names:
if name in self.album_names:
if isinstance(self.album_names[name], Album):
albums[name] = self.album_names[name]
else:
self.album_names[name] = Album(graph=self.graph,
album_data=self.album_names[name])
self.album_ids[self.album_names[name].me] = self.album_names[name]
albums[name] = self.album_names[name]
return albums
def get_albums_by_id(self, ids):
"""
Given a list of ids this method will
return album objects for each matching id.
If an id is not found then it is silently ignored.
This method returns a dictionary mapping id to
Album object
"""
albums = {}
for album_id in ids:
if album_id in self.album_ids:
if isinstance(self.album_ids[album_id], Album):
albums[album_id] = self.album_ids[album_id]
else:
self.album_ids[album_id] = Album(graph=self.graph,
album_data=self.album_ids[album_id])
self.album_names[self.album_ids[album_id].name] = self.album_ids[album_id]
albums[album_id] = self.album_ids[album_id]
return albums
def get_all_albums_by_id(self):
"""
This method returns a dictionary of all
albums with album ids as the keys
"""
for album_id in self.album_ids:
if not isinstance(self.album_ids[album_id], Album):
self.album_ids[album_id] = Album(graph=self.graph,
album_data=self.album_ids[album_id])
self.album_names[self.album_ids[album_id].name] = self.album_ids[album_id]
return self.album_ids
def get_all_albums_by_name(self):
"""
This method returns a dictionary of all
albums with album names as the keys
"""
for name in self.album_names:
if not isinstance(self.album_names[name], Album):
self.album_names[name] = Album(graph=self.graph,
album_data=self.album_names[name])
self.album_ids[self.album_names[name].me] = self.album_names[name]
return self.album_names
class Album(object):
def __init__(self, graph=None, token=None, album_id=None, album_data=None):
"""
Initializes a new Album object.
If graph is provided then the graph object is saved to this
instance.
If the token is provided then the graph object for this token
is created and saved to this instance.
If both are none then an error is raised.
If album_id is provided then the graph object is queried
for the id and the album object populates itself with this data
If album_data is provided then the graph object is populated
with the data in the json derived object
If both are None then an error is raised
"""
if graph is None and token is None:
raise TypeError("Either a graph object must be provided or a token must be provided")
if graph is not None:
self.graph = graph
query = models.AccessTokenModel.all()
query.filter('access_token =', graph.access_token)
try:
self.token = query.fetch(1)[0]
except IndexError:
raise TypeError('The token object provided was not an AccessTokenModel instance')
else:
self.graph = fb.GraphAPI(token.access_token)
self.token = token
if album_id is None and album_data is None:
raise TypeError("Either an album id or a album data must be provided")
if album_id is not None:
album_data = self.graph.get_object(album_id)
self.me = album_data['id']
self.name = album_data['name']
self.desc = album_data.get('description', None)
self.count = album_data.get('count', 0)
if 'cover_photo' in album_data:
self.cover_photo = Photo(self.me, graph=self.graph, photo_id=album_data['cover_photo']).thumbnail
else:
self.cover_photo = None
def get_model(self):
query = models.AlbumModel.all()
query.filter('me =', self.me)
try:
return query.fetch(1)[0]
except IndexError:
cover_thumb = None
if self.cover_photo is not None:
cover_thumb = self.cover_photo
entity = models.AlbumModel(me=self.me,
token=self.token,
name=self.name,
desc=self.desc,
cover_photo=cover_thumb)
entity.put()
return entity
def get_photos(self):
"""
Get a list of Photo objects
"""
photos_data = self.graph.get_connections(self.me, 'photos')['data']
photos = []
for photo_data in photos_data:
query = models.PhotoModel.all()
query.filter('me =', photo_data['id'])
try:
photos.append(query.fetch(1)[0])
except IndexError:
name = None
if 'name' in photo_data:
name = photo_data['name']
orig = photo_data['images'][0]['source']
entity = models.PhotoModel(me=photo_data['id'],
album_id=self.me,
name=name,
thumbnail=photo_data['picture'],
original=orig)
entity.put()
photos.append(entity)
return photos
class Photo(object):
def __init__(self, album_id, graph=None, token=None, photo_id=None, photo_data=None):
if graph is None and token is None:
raise TypeError("Either a graph object must be provided or a token must be provided")
if graph is not None:
self.graph = graph
else:
self.graph = fb.GraphAPI(token.access_token)
if photo_id is None and photo_data is None:
raise TypeError("Either an album id or a album data must be provided")
if photo_id is not None:
photo_data = self.graph.get_object(photo_id)
self.me = photo_data['id']
self.name = photo_data.get('name', None)
self.thumbnail = photo_data['picture']
self.original = photo_data['images'][0]['source']
self.album_id = album_id
def get_model(self):
query = models.PhotoModel.all()
query.filter('me =', self.me)
try:
return query.fetch(1)[0]
except IndexError:
entity = models.PhotoModel(me=self.me,
album_id=self.album_id,
name=self.name,
thumbnail=self.thumbnail,
original=self.original)
entity.put()
return entity
| bsd-3-clause | 2,272,791,862,150,649,300 | 33.928 | 109 | 0.529607 | false | 4.367684 | false | false | false |
hectord/lettuce | tests/integration/lib/Django-1.2.5/django/core/handlers/base.py | 44 | 9926 | import sys
from django import http
from django.core import signals
from django.utils.encoding import force_unicode
from django.utils.importlib import import_module
class BaseHandler(object):
# Changes that are always applied to a response (in this order).
response_fixes = [
http.fix_location_header,
http.conditional_content_removal,
http.fix_IE_for_attach,
http.fix_IE_for_vary,
]
def __init__(self):
self._request_middleware = self._view_middleware = self._response_middleware = self._exception_middleware = None
def load_middleware(self):
"""
Populate middleware lists from settings.MIDDLEWARE_CLASSES.
Must be called after the environment is fixed (see __call__).
"""
from django.conf import settings
from django.core import exceptions
self._view_middleware = []
self._response_middleware = []
self._exception_middleware = []
request_middleware = []
for middleware_path in settings.MIDDLEWARE_CLASSES:
try:
dot = middleware_path.rindex('.')
except ValueError:
raise exceptions.ImproperlyConfigured('%s isn\'t a middleware module' % middleware_path)
mw_module, mw_classname = middleware_path[:dot], middleware_path[dot+1:]
try:
mod = import_module(mw_module)
except ImportError, e:
raise exceptions.ImproperlyConfigured('Error importing middleware %s: "%s"' % (mw_module, e))
try:
mw_class = getattr(mod, mw_classname)
except AttributeError:
raise exceptions.ImproperlyConfigured('Middleware module "%s" does not define a "%s" class' % (mw_module, mw_classname))
try:
mw_instance = mw_class()
except exceptions.MiddlewareNotUsed:
continue
if hasattr(mw_instance, 'process_request'):
request_middleware.append(mw_instance.process_request)
if hasattr(mw_instance, 'process_view'):
self._view_middleware.append(mw_instance.process_view)
if hasattr(mw_instance, 'process_response'):
self._response_middleware.insert(0, mw_instance.process_response)
if hasattr(mw_instance, 'process_exception'):
self._exception_middleware.insert(0, mw_instance.process_exception)
# We only assign to this when initialization is complete as it is used
# as a flag for initialization being complete.
self._request_middleware = request_middleware
def get_response(self, request):
"Returns an HttpResponse object for the given HttpRequest"
from django.core import exceptions, urlresolvers
from django.conf import settings
try:
try:
# Setup default url resolver for this thread.
urlconf = settings.ROOT_URLCONF
urlresolvers.set_urlconf(urlconf)
resolver = urlresolvers.RegexURLResolver(r'^/', urlconf)
# Apply request middleware
for middleware_method in self._request_middleware:
response = middleware_method(request)
if response:
return response
if hasattr(request, "urlconf"):
# Reset url resolver with a custom urlconf.
urlconf = request.urlconf
urlresolvers.set_urlconf(urlconf)
resolver = urlresolvers.RegexURLResolver(r'^/', urlconf)
callback, callback_args, callback_kwargs = resolver.resolve(
request.path_info)
# Apply view middleware
for middleware_method in self._view_middleware:
response = middleware_method(request, callback, callback_args, callback_kwargs)
if response:
return response
try:
response = callback(request, *callback_args, **callback_kwargs)
except Exception, e:
# If the view raised an exception, run it through exception
# middleware, and if the exception middleware returns a
# response, use that. Otherwise, reraise the exception.
for middleware_method in self._exception_middleware:
response = middleware_method(request, e)
if response:
return response
raise
# Complain if the view returned None (a common error).
if response is None:
try:
view_name = callback.func_name # If it's a function
except AttributeError:
view_name = callback.__class__.__name__ + '.__call__' # If it's a class
raise ValueError("The view %s.%s didn't return an HttpResponse object." % (callback.__module__, view_name))
return response
except http.Http404, e:
if settings.DEBUG:
from django.views import debug
return debug.technical_404_response(request, e)
else:
try:
callback, param_dict = resolver.resolve404()
return callback(request, **param_dict)
except:
try:
return self.handle_uncaught_exception(request, resolver, sys.exc_info())
finally:
receivers = signals.got_request_exception.send(sender=self.__class__, request=request)
except exceptions.PermissionDenied:
return http.HttpResponseForbidden('<h1>Permission denied</h1>')
except SystemExit:
# Allow sys.exit() to actually exit. See tickets #1023 and #4701
raise
except: # Handle everything else, including SuspiciousOperation, etc.
# Get the exception info now, in case another exception is thrown later.
receivers = signals.got_request_exception.send(sender=self.__class__, request=request)
return self.handle_uncaught_exception(request, resolver, sys.exc_info())
finally:
# Reset URLconf for this thread on the way out for complete
# isolation of request.urlconf
urlresolvers.set_urlconf(None)
def handle_uncaught_exception(self, request, resolver, exc_info):
"""
Processing for any otherwise uncaught exceptions (those that will
generate HTTP 500 responses). Can be overridden by subclasses who want
customised 500 handling.
Be *very* careful when overriding this because the error could be
caused by anything, so assuming something like the database is always
available would be an error.
"""
from django.conf import settings
from django.core.mail import mail_admins
if settings.DEBUG_PROPAGATE_EXCEPTIONS:
raise
if settings.DEBUG:
from django.views import debug
return debug.technical_500_response(request, *exc_info)
# When DEBUG is False, send an error message to the admins.
subject = 'Error (%s IP): %s' % ((request.META.get('REMOTE_ADDR') in settings.INTERNAL_IPS and 'internal' or 'EXTERNAL'), request.path)
try:
request_repr = repr(request)
except:
request_repr = "Request repr() unavailable"
message = "%s\n\n%s" % (self._get_traceback(exc_info), request_repr)
mail_admins(subject, message, fail_silently=True)
# If Http500 handler is not installed, re-raise last exception
if resolver.urlconf_module is None:
raise exc_info[1], None, exc_info[2]
# Return an HttpResponse that displays a friendly error message.
callback, param_dict = resolver.resolve500()
return callback(request, **param_dict)
def _get_traceback(self, exc_info=None):
"Helper function to return the traceback as a string"
import traceback
return '\n'.join(traceback.format_exception(*(exc_info or sys.exc_info())))
def apply_response_fixes(self, request, response):
"""
Applies each of the functions in self.response_fixes to the request and
response, modifying the response in the process. Returns the new
response.
"""
for func in self.response_fixes:
response = func(request, response)
return response
def get_script_name(environ):
"""
Returns the equivalent of the HTTP request's SCRIPT_NAME environment
variable. If Apache mod_rewrite has been used, returns what would have been
the script name prior to any rewriting (so it's the script name as seen
from the client's perspective), unless DJANGO_USE_POST_REWRITE is set (to
anything).
"""
from django.conf import settings
if settings.FORCE_SCRIPT_NAME is not None:
return force_unicode(settings.FORCE_SCRIPT_NAME)
# If Apache's mod_rewrite had a whack at the URL, Apache set either
# SCRIPT_URL or REDIRECT_URL to the full resource URL before applying any
# rewrites. Unfortunately not every Web server (lighttpd!) passes this
# information through all the time, so FORCE_SCRIPT_NAME, above, is still
# needed.
script_url = environ.get('SCRIPT_URL', u'')
if not script_url:
script_url = environ.get('REDIRECT_URL', u'')
if script_url:
return force_unicode(script_url[:-len(environ.get('PATH_INFO', ''))])
return force_unicode(environ.get('SCRIPT_NAME', u''))
| gpl-3.0 | 7,864,434,311,480,931,000 | 44.118182 | 143 | 0.598428 | false | 4.887248 | false | false | false |
ahmadio/edx-platform | lms/lib/courseware_search/lms_filter_generator.py | 58 | 5634 | """
This file contains implementation override of SearchFilterGenerator which will allow
* Filter by all courses in which the user is enrolled in
"""
from microsite_configuration import microsite
from student.models import CourseEnrollment
from opaque_keys import InvalidKeyError
from opaque_keys.edx.keys import CourseKey
from opaque_keys.edx.locations import SlashSeparatedCourseKey
from xmodule.modulestore.django import modulestore
from search.filter_generator import SearchFilterGenerator
from openedx.core.djangoapps.user_api.partition_schemes import RandomUserPartitionScheme
from openedx.core.djangoapps.course_groups.partition_scheme import CohortPartitionScheme
from courseware.access import get_user_role
INCLUDE_SCHEMES = [CohortPartitionScheme, RandomUserPartitionScheme, ]
SCHEME_SUPPORTS_ASSIGNMENT = [RandomUserPartitionScheme, ]
class LmsSearchFilterGenerator(SearchFilterGenerator):
""" SearchFilterGenerator for LMS Search """
_user_enrollments = {}
def _enrollments_for_user(self, user):
""" Return the specified user's course enrollments """
if user not in self._user_enrollments:
self._user_enrollments[user] = CourseEnrollment.enrollments_for_user(user)
return self._user_enrollments[user]
def filter_dictionary(self, **kwargs):
""" LMS implementation, adds filtering by user partition, course id and user """
def get_group_for_user_partition(user_partition, course_key, user):
""" Returns the specified user's group for user partition """
if user_partition.scheme in SCHEME_SUPPORTS_ASSIGNMENT:
return user_partition.scheme.get_group_for_user(
course_key,
user,
user_partition,
assign=False,
)
else:
return user_partition.scheme.get_group_for_user(
course_key,
user,
user_partition,
)
def get_group_ids_for_user(course, user):
""" Collect user partition group ids for user for this course """
partition_groups = []
for user_partition in course.user_partitions:
if user_partition.scheme in INCLUDE_SCHEMES:
group = get_group_for_user_partition(user_partition, course.id, user)
if group:
partition_groups.append(group)
partition_group_ids = [unicode(partition_group.id) for partition_group in partition_groups]
return partition_group_ids if partition_group_ids else None
filter_dictionary = super(LmsSearchFilterGenerator, self).filter_dictionary(**kwargs)
if 'user' in kwargs:
user = kwargs['user']
if 'course_id' in kwargs and kwargs['course_id']:
try:
course_key = CourseKey.from_string(kwargs['course_id'])
except InvalidKeyError:
course_key = SlashSeparatedCourseKey.from_deprecated_string(kwargs['course_id'])
# Staff user looking at course as staff user
if get_user_role(user, course_key) in ('instructor', 'staff'):
return filter_dictionary
# Need to check course exist (if course gets deleted enrollments don't get cleaned up)
course = modulestore().get_course(course_key)
if course:
filter_dictionary['content_groups'] = get_group_ids_for_user(course, user)
else:
user_enrollments = self._enrollments_for_user(user)
content_groups = []
for enrollment in user_enrollments:
course = modulestore().get_course(enrollment.course_id)
if course:
enrollment_group_ids = get_group_ids_for_user(course, user)
if enrollment_group_ids:
content_groups.extend(enrollment_group_ids)
filter_dictionary['content_groups'] = content_groups if content_groups else None
return filter_dictionary
def field_dictionary(self, **kwargs):
""" add course if provided otherwise add courses in which the user is enrolled in """
field_dictionary = super(LmsSearchFilterGenerator, self).field_dictionary(**kwargs)
if not kwargs.get('user'):
field_dictionary['course'] = []
elif not kwargs.get('course_id'):
user_enrollments = self._enrollments_for_user(kwargs['user'])
field_dictionary['course'] = [unicode(enrollment.course_id) for enrollment in user_enrollments]
# if we have an org filter, only include results for this org filter
course_org_filter = microsite.get_value('course_org_filter')
if course_org_filter:
field_dictionary['org'] = course_org_filter
return field_dictionary
def exclude_dictionary(self, **kwargs):
""" If we are not on a microsite, then exclude any microsites that are defined """
exclude_dictionary = super(LmsSearchFilterGenerator, self).exclude_dictionary(**kwargs)
course_org_filter = microsite.get_value('course_org_filter')
# If we have a course filter we are ensuring that we only get those courses above
if not course_org_filter:
org_filter_out_set = microsite.get_all_orgs()
if org_filter_out_set:
exclude_dictionary['org'] = list(org_filter_out_set)
return exclude_dictionary
| agpl-3.0 | 7,445,365,950,426,380,000 | 45.561983 | 107 | 0.63241 | false | 4.648515 | false | false | false |
goliate/sarakha63-persomov | couchpotato/core/media/movie/providers/trailer/youtube_dl/extractor/twentyfourvideo.py | 32 | 3892 | # coding: utf-8
from __future__ import unicode_literals
from .common import InfoExtractor
from ..utils import (
parse_iso8601,
int_or_none,
)
class TwentyFourVideoIE(InfoExtractor):
IE_NAME = '24video'
_VALID_URL = r'https?://(?:www\.)?24video\.net/(?:video/(?:view|xml)/|player/new24_play\.swf\?id=)(?P<id>\d+)'
_TESTS = [
{
'url': 'http://www.24video.net/video/view/1044982',
'md5': '48dd7646775690a80447a8dca6a2df76',
'info_dict': {
'id': '1044982',
'ext': 'mp4',
'title': 'Эротика каменного века',
'description': 'Как смотрели порно в каменном веке.',
'thumbnail': 're:^https?://.*\.jpg$',
'uploader': 'SUPERTELO',
'duration': 31,
'timestamp': 1275937857,
'upload_date': '20100607',
'age_limit': 18,
'like_count': int,
'dislike_count': int,
},
},
{
'url': 'http://www.24video.net/player/new24_play.swf?id=1044982',
'only_matching': True,
}
]
def _real_extract(self, url):
video_id = self._match_id(url)
webpage = self._download_webpage(
'http://www.24video.net/video/view/%s' % video_id, video_id)
title = self._og_search_title(webpage)
description = self._html_search_regex(
r'<span itemprop="description">([^<]+)</span>', webpage, 'description', fatal=False)
thumbnail = self._og_search_thumbnail(webpage)
duration = int_or_none(self._og_search_property(
'duration', webpage, 'duration', fatal=False))
timestamp = parse_iso8601(self._search_regex(
r'<time id="video-timeago" datetime="([^"]+)" itemprop="uploadDate">',
webpage, 'upload date'))
uploader = self._html_search_regex(
r'Загрузил\s*<a href="/jsecUser/movies/[^"]+" class="link">([^<]+)</a>',
webpage, 'uploader', fatal=False)
view_count = int_or_none(self._html_search_regex(
r'<span class="video-views">(\d+) просмотр',
webpage, 'view count', fatal=False))
comment_count = int_or_none(self._html_search_regex(
r'<div class="comments-title" id="comments-count">(\d+) комментари',
webpage, 'comment count', fatal=False))
formats = []
pc_video = self._download_xml(
'http://www.24video.net/video/xml/%s?mode=play' % video_id,
video_id, 'Downloading PC video URL').find('.//video')
formats.append({
'url': pc_video.attrib['url'],
'format_id': 'pc',
'quality': 1,
})
like_count = int_or_none(pc_video.get('ratingPlus'))
dislike_count = int_or_none(pc_video.get('ratingMinus'))
age_limit = 18 if pc_video.get('adult') == 'true' else 0
mobile_video = self._download_xml(
'http://www.24video.net/video/xml/%s' % video_id,
video_id, 'Downloading mobile video URL').find('.//video')
formats.append({
'url': mobile_video.attrib['url'],
'format_id': 'mobile',
'quality': 0,
})
self._sort_formats(formats)
return {
'id': video_id,
'title': title,
'description': description,
'thumbnail': thumbnail,
'uploader': uploader,
'duration': duration,
'timestamp': timestamp,
'view_count': view_count,
'comment_count': comment_count,
'like_count': like_count,
'dislike_count': dislike_count,
'age_limit': age_limit,
'formats': formats,
}
| gpl-3.0 | 5,228,835,369,578,570,000 | 34.018349 | 114 | 0.517422 | false | 3.560634 | false | false | false |
longman694/youtube-dl | youtube_dl/extractor/watchbox.py | 14 | 5539 | # coding: utf-8
from __future__ import unicode_literals
import re
from .common import InfoExtractor
from ..compat import compat_str
from ..utils import (
int_or_none,
js_to_json,
strip_or_none,
try_get,
unified_timestamp,
)
class WatchBoxIE(InfoExtractor):
_VALID_URL = r'https?://(?:www\.)?watchbox\.de/(?P<kind>serien|filme)/(?:[^/]+/)*[^/]+-(?P<id>\d+)'
_TESTS = [{
# film
'url': 'https://www.watchbox.de/filme/free-jimmy-12325.html',
'info_dict': {
'id': '341368',
'ext': 'mp4',
'title': 'Free Jimmy',
'description': 'md5:bcd8bafbbf9dc0ef98063d344d7cc5f6',
'thumbnail': r're:^https?://.*\.jpg$',
'duration': 4890,
'age_limit': 16,
'release_year': 2009,
},
'params': {
'format': 'bestvideo',
'skip_download': True,
},
'expected_warnings': ['Failed to download m3u8 information'],
}, {
# episode
'url': 'https://www.watchbox.de/serien/ugly-americans-12231/staffel-1/date-in-der-hoelle-328286.html',
'info_dict': {
'id': '328286',
'ext': 'mp4',
'title': 'S01 E01 - Date in der Hölle',
'description': 'md5:2f31c74a8186899f33cb5114491dae2b',
'thumbnail': r're:^https?://.*\.jpg$',
'duration': 1291,
'age_limit': 12,
'release_year': 2010,
'series': 'Ugly Americans',
'season_number': 1,
'episode': 'Date in der Hölle',
'episode_number': 1,
},
'params': {
'format': 'bestvideo',
'skip_download': True,
},
'expected_warnings': ['Failed to download m3u8 information'],
}, {
'url': 'https://www.watchbox.de/serien/ugly-americans-12231/staffel-2/der-ring-des-powers-328270',
'only_matching': True,
}]
def _real_extract(self, url):
mobj = re.match(self._VALID_URL, url)
kind, video_id = mobj.group('kind', 'id')
webpage = self._download_webpage(url, video_id)
source = self._parse_json(
self._search_regex(
r'(?s)source\s*:\s*({.+?})\s*,\s*\n', webpage, 'source',
default='{}'),
video_id, transform_source=js_to_json, fatal=False) or {}
video_id = compat_str(source.get('videoId') or video_id)
devapi = self._download_json(
'http://api.watchbox.de/devapi/id/%s' % video_id, video_id, query={
'format': 'json',
'apikey': 'hbbtv',
}, fatal=False)
item = try_get(devapi, lambda x: x['items'][0], dict) or {}
title = item.get('title') or try_get(
item, lambda x: x['movie']['headline_movie'],
compat_str) or source['title']
formats = []
hls_url = item.get('media_videourl_hls') or source.get('hls')
if hls_url:
formats.extend(self._extract_m3u8_formats(
hls_url, video_id, 'mp4', entry_protocol='m3u8_native',
m3u8_id='hls', fatal=False))
dash_url = item.get('media_videourl_wv') or source.get('dash')
if dash_url:
formats.extend(self._extract_mpd_formats(
dash_url, video_id, mpd_id='dash', fatal=False))
mp4_url = item.get('media_videourl')
if mp4_url:
formats.append({
'url': mp4_url,
'format_id': 'mp4',
'width': int_or_none(item.get('width')),
'height': int_or_none(item.get('height')),
'tbr': int_or_none(item.get('bitrate')),
})
self._sort_formats(formats)
description = strip_or_none(item.get('descr'))
thumbnail = item.get('media_content_thumbnail_large') or source.get('poster') or item.get('media_thumbnail')
duration = int_or_none(item.get('media_length') or source.get('length'))
timestamp = unified_timestamp(item.get('pubDate'))
view_count = int_or_none(item.get('media_views'))
age_limit = int_or_none(try_get(item, lambda x: x['movie']['fsk']))
release_year = int_or_none(try_get(item, lambda x: x['movie']['rel_year']))
info = {
'id': video_id,
'title': title,
'description': description,
'thumbnail': thumbnail,
'duration': duration,
'timestamp': timestamp,
'view_count': view_count,
'age_limit': age_limit,
'release_year': release_year,
'formats': formats,
}
if kind.lower() == 'serien':
series = try_get(
item, lambda x: x['special']['title'],
compat_str) or source.get('format')
season_number = int_or_none(self._search_regex(
r'^S(\d{1,2})\s*E\d{1,2}', title, 'season number',
default=None) or self._search_regex(
r'/staffel-(\d+)/', url, 'season number', default=None))
episode = source.get('title')
episode_number = int_or_none(self._search_regex(
r'^S\d{1,2}\s*E(\d{1,2})', title, 'episode number',
default=None))
info.update({
'series': series,
'season_number': season_number,
'episode': episode,
'episode_number': episode_number,
})
return info
| unlicense | 2,893,657,285,305,545,700 | 35.668874 | 116 | 0.506773 | false | 3.5 | false | false | false |
mesocentrefc/easybuild-framework | easybuild/tools/version.py | 2 | 2926 | ##
# Copyright 2009-2014 Ghent University
#
# This file is part of EasyBuild,
# originally created by the HPC team of Ghent University (http://ugent.be/hpc/en),
# with support of Ghent University (http://ugent.be/hpc),
# the Flemish Supercomputer Centre (VSC) (https://vscentrum.be/nl/en),
# the Hercules foundation (http://www.herculesstichting.be/in_English)
# and the Department of Economy, Science and Innovation (EWI) (http://www.ewi-vlaanderen.be/en).
#
# http://github.com/hpcugent/easybuild
#
# EasyBuild 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 v2.
#
# EasyBuild 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 EasyBuild. If not, see <http://www.gnu.org/licenses/>.
##
"""
Module that takes control of versioning.
@author: Stijn De Weirdt (Ghent University)
@author: Dries Verdegem (Ghent University)
@author: Kenneth Hoste (Ghent University)
@author: Pieter De Baets (Ghent University)
@author: Jens Timmerman (Ghent University)
"""
import os
from distutils.version import LooseVersion
from socket import gethostname
# note: release candidates should be versioned as a pre-release, e.g. "1.1rc1"
# 1.1-rc1 would indicate a post-release, i.e., and update of 1.1, so beware!
VERSION = LooseVersion("1.14.0")
UNKNOWN = "UNKNOWN"
def get_git_revision():
"""
Returns the git revision (e.g. aab4afc016b742c6d4b157427e192942d0e131fe),
or UNKNOWN is getting the git revision fails
relies on GitPython (see http://gitorious.org/git-python)
"""
try:
import git
except ImportError:
return UNKNOWN
try:
path = os.path.dirname(__file__)
gitrepo = git.Git(path)
return gitrepo.rev_list("HEAD").splitlines()[0]
except git.GitCommandError:
return UNKNOWN
git_rev = get_git_revision()
if git_rev == UNKNOWN:
VERBOSE_VERSION = VERSION
else:
VERBOSE_VERSION = LooseVersion("%s-r%s" % (VERSION, get_git_revision()))
# alias
FRAMEWORK_VERSION = VERBOSE_VERSION
# EasyBlock version
try:
from easybuild.easyblocks import VERBOSE_VERSION as EASYBLOCKS_VERSION
except:
EASYBLOCKS_VERSION = '0.0.UNKNOWN.EASYBLOCKS' # make sure it is smaller then anything
def this_is_easybuild():
"""Standard starting message"""
top_version = max(FRAMEWORK_VERSION, EASYBLOCKS_VERSION)
# !!! bootstrap_eb.py script checks hard on the string below, so adjust with sufficient care !!!
msg = "This is EasyBuild %s (framework: %s, easyblocks: %s) on host %s." \
% (top_version, FRAMEWORK_VERSION, EASYBLOCKS_VERSION, gethostname())
return msg
| gpl-2.0 | -6,282,021,567,314,024,000 | 34.253012 | 100 | 0.719754 | false | 3.31746 | false | false | false |
broferek/ansible | test/units/modules/network/f5/test_bigip_service_policy.py | 38 | 4128 | # -*- coding: utf-8 -*-
#
# Copyright: (c) 2017, F5 Networks Inc.
# GNU General Public License v3.0 (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import os
import json
import pytest
import sys
if sys.version_info < (2, 7):
pytestmark = pytest.mark.skip("F5 Ansible modules require Python >= 2.7")
from ansible.module_utils.basic import AnsibleModule
try:
from library.modules.bigip_service_policy import ApiParameters
from library.modules.bigip_service_policy import ModuleParameters
from library.modules.bigip_service_policy import ModuleManager
from library.modules.bigip_service_policy import ArgumentSpec
# In Ansible 2.8, Ansible changed import paths.
from test.units.compat import unittest
from test.units.compat.mock import Mock
from test.units.compat.mock import patch
from test.units.modules.utils import set_module_args
except ImportError:
from ansible.modules.network.f5.bigip_service_policy import ApiParameters
from ansible.modules.network.f5.bigip_service_policy import ModuleParameters
from ansible.modules.network.f5.bigip_service_policy import ModuleManager
from ansible.modules.network.f5.bigip_service_policy import ArgumentSpec
# Ansible 2.8 imports
from units.compat import unittest
from units.compat.mock import Mock
from units.compat.mock import patch
from units.modules.utils import set_module_args
fixture_path = os.path.join(os.path.dirname(__file__), 'fixtures')
fixture_data = {}
def load_fixture(name):
path = os.path.join(fixture_path, name)
if path in fixture_data:
return fixture_data[path]
with open(path) as f:
data = f.read()
try:
data = json.loads(data)
except Exception:
pass
fixture_data[path] = data
return data
class TestParameters(unittest.TestCase):
def test_module_parameters(self):
args = dict(
name='foo',
description='my description',
timer_policy='timer1',
port_misuse_policy='misuse1',
)
p = ModuleParameters(params=args)
assert p.name == 'foo'
assert p.description == 'my description'
assert p.timer_policy == '/Common/timer1'
assert p.port_misuse_policy == '/Common/misuse1'
def test_api_parameters(self):
args = load_fixture('load_net_service_policy_1.json')
p = ApiParameters(params=args)
assert p.name == 'baz'
assert p.description == 'my description'
assert p.timer_policy == '/Common/foo'
assert p.port_misuse_policy == '/Common/bar'
class TestManager(unittest.TestCase):
def setUp(self):
self.spec = ArgumentSpec()
try:
self.p1 = patch('library.modules.bigip_service_policy.module_provisioned')
self.m1 = self.p1.start()
self.m1.return_value = True
except Exception:
self.p1 = patch('ansible.modules.network.f5.bigip_service_policy.module_provisioned')
self.m1 = self.p1.start()
self.m1.return_value = True
def test_create_selfip(self, *args):
set_module_args(dict(
name='foo',
description='my description',
timer_policy='timer1',
port_misuse_policy='misuse1',
partition='Common',
state='present',
provider=dict(
server='localhost',
password='password',
user='admin'
)
))
module = AnsibleModule(
argument_spec=self.spec.argument_spec,
supports_check_mode=self.spec.supports_check_mode
)
mm = ModuleManager(module=module)
# Override methods to force specific logic in the module to happen
mm.exists = Mock(side_effect=[False, True])
mm.create_on_device = Mock(return_value=True)
mm.module_provisioned = Mock(return_value=True)
results = mm.exec_module()
assert results['changed'] is True
| gpl-3.0 | -4,717,631,936,433,852,000 | 30.272727 | 97 | 0.644864 | false | 3.973051 | true | false | false |
wavelets/zipline | zipline/examples/dual_ema_talib.py | 2 | 3230 | #!/usr/bin/env python
#
# Copyright 2013 Quantopian, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import matplotlib.pyplot as plt
from zipline.algorithm import TradingAlgorithm
from zipline.utils.factory import load_from_yahoo
# Import exponential moving average from talib wrapper
from zipline.transforms.ta import EMA
from datetime import datetime
import pytz
class DualEMATaLib(TradingAlgorithm):
"""Dual Moving Average Crossover algorithm.
This algorithm buys apple once its short moving average crosses
its long moving average (indicating upwards momentum) and sells
its shares once the averages cross again (indicating downwards
momentum).
"""
def initialize(self, short_window=20, long_window=40):
# Add 2 mavg transforms, one with a long window, one
# with a short window.
self.short_ema_trans = EMA(timeperiod=short_window)
self.long_ema_trans = EMA(timeperiod=long_window)
# To keep track of whether we invested in the stock or not
self.invested = False
def handle_data(self, data):
self.short_ema = self.short_ema_trans.handle_data(data)
self.long_ema = self.long_ema_trans.handle_data(data)
if self.short_ema is None or self.long_ema is None:
return
self.buy = False
self.sell = False
if (self.short_ema > self.long_ema).all() and not self.invested:
self.order('AAPL', 100)
self.invested = True
self.buy = True
elif (self.short_ema < self.long_ema).all() and self.invested:
self.order('AAPL', -100)
self.invested = False
self.sell = True
self.record(AAPL=data['AAPL'].price,
short_ema=self.short_ema['AAPL'],
long_ema=self.long_ema['AAPL'],
buy=self.buy,
sell=self.sell)
if __name__ == '__main__':
start = datetime(1990, 1, 1, 0, 0, 0, 0, pytz.utc)
end = datetime(1991, 1, 1, 0, 0, 0, 0, pytz.utc)
data = load_from_yahoo(stocks=['AAPL'], indexes={}, start=start,
end=end)
dma = DualEMATaLib()
results = dma.run(data).dropna()
fig = plt.figure()
ax1 = fig.add_subplot(211, ylabel='portfolio value')
results.portfolio_value.plot(ax=ax1)
ax2 = fig.add_subplot(212)
results[['AAPL', 'short_ema', 'long_ema']].plot(ax=ax2)
ax2.plot(results.ix[results.buy].index, results.short_ema[results.buy],
'^', markersize=10, color='m')
ax2.plot(results.ix[results.sell].index, results.short_ema[results.sell],
'v', markersize=10, color='k')
plt.legend(loc=0)
plt.gcf().set_size_inches(18, 8)
| apache-2.0 | -1,037,034,474,115,704,300 | 34.108696 | 77 | 0.644892 | false | 3.410771 | false | false | false |
crmccreary/openerp_server | openerp/addons/account_bank_statement_extensions/account_bank_statement.py | 9 | 6553 | # -*- encoding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
#
# Copyright (c) 2011 Noviat nv/sa (www.noviat.be). 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 osv import osv, fields
import decimal_precision as dp
import netsvc
from tools.translate import _
class account_bank_statement(osv.osv):
_inherit = 'account.bank.statement'
def write(self, cr, uid, ids, vals, context=None):
if context is None:
context = {}
# bypass obsolete statement line resequencing
if vals.get('line_ids', False) or context.get('ebanking_import', False):
res = super(osv.osv, self).write(cr, uid, ids, vals, context=context)
else:
res = super(account_bank_statement, self).write(cr, uid, ids, vals, context=context)
return res
def button_confirm_bank(self, cr, uid, ids, context=None):
super(account_bank_statement, self).button_confirm_bank(cr, uid, ids, context=context)
for st in self.browse(cr, uid, ids, context=context):
cr.execute("UPDATE account_bank_statement_line \
SET state='confirm' WHERE id in %s ",
(tuple([x.id for x in st.line_ids]),))
return True
def button_cancel(self, cr, uid, ids, context=None):
super(account_bank_statement, self).button_cancel(cr, uid, ids, context=context)
for st in self.browse(cr, uid, ids, context=context):
if st.line_ids:
cr.execute("UPDATE account_bank_statement_line \
SET state='draft' WHERE id in %s ",
(tuple([x.id for x in st.line_ids]),))
return True
account_bank_statement()
class account_bank_statement_line_global(osv.osv):
_name = 'account.bank.statement.line.global'
_description = 'Batch Payment Info'
_columns = {
'name': fields.char('Communication', size=128, required=True),
'code': fields.char('Code', size=64, required=True),
'parent_id': fields.many2one('account.bank.statement.line.global', 'Parent Code', ondelete='cascade'),
'child_ids': fields.one2many('account.bank.statement.line.global', 'parent_id', 'Child Codes'),
'type': fields.selection([
('iso20022', 'ISO 20022'),
('coda', 'CODA'),
('manual', 'Manual'),
], 'Type', required=True),
'amount': fields.float('Amount', digits_compute=dp.get_precision('Account')),
'bank_statement_line_ids': fields.one2many('account.bank.statement.line', 'globalisation_id', 'Bank Statement Lines'),
}
_rec_name = 'code'
_defaults = {
'code': lambda s,c,u,ctx={}: s.pool.get('ir.sequence').get(c, u, 'account.bank.statement.line.global'),
'name': '/',
}
_sql_constraints = [
('code_uniq', 'unique (code)', 'The code must be unique !'),
]
def name_search(self, cr, user, name, args=None, operator='ilike', context=None, limit=100):
if not args:
args = []
ids = []
if name:
ids = self.search(cr, user, [('code', 'ilike', name)] + args, limit=limit)
if not ids:
ids = self.search(cr, user, [('name', operator, name)] + args, limit=limit)
if not ids and len(name.split()) >= 2:
#Separating code and name for searching
operand1, operand2 = name.split(' ', 1) #name can contain spaces
ids = self.search(cr, user, [('code', 'like', operand1), ('name', operator, operand2)] + args, limit=limit)
else:
ids = self.search(cr, user, args, context=context, limit=limit)
return self.name_get(cr, user, ids, context=context)
account_bank_statement_line_global()
class account_bank_statement_line(osv.osv):
_inherit = 'account.bank.statement.line'
_columns = {
'date': fields.date('Entry Date', required=True, states={'confirm': [('readonly', True)]}),
'val_date': fields.date('Valuta Date', states={'confirm': [('readonly', True)]}),
'globalisation_id': fields.many2one('account.bank.statement.line.global', 'Globalisation ID',
states={'confirm': [('readonly', True)]},
help="Code to identify transactions belonging to the same globalisation level within a batch payment"),
'globalisation_amount': fields.related('globalisation_id', 'amount', type='float',
relation='account.bank.statement.line.global', string='Glob. Amount', readonly=True),
'journal_id': fields.related('statement_id', 'journal_id', type='many2one', relation='account.journal', string='Journal', store=True, readonly=True),
'state': fields.selection([('draft', 'Draft'), ('confirm', 'Confirmed')],
'State', required=True, readonly=True),
'counterparty_name': fields.char('Counterparty Name', size=35),
'counterparty_bic': fields.char('Counterparty BIC', size=11),
'counterparty_number': fields.char('Counterparty Number', size=34),
'counterparty_currency': fields.char('Counterparty Currency', size=3),
}
_defaults = {
'state': 'draft',
}
def unlink(self, cr, uid, ids, context=None):
if context is None:
context = {}
if context.get('block_statement_line_delete', False):
raise osv.except_osv(_('Warning'), _('Delete operation not allowed ! \
Please go to the associated bank statement in order to delete and/or modify this bank statement line'))
return super(account_bank_statement_line, self).unlink(cr, uid, ids, context=context)
account_bank_statement_line()
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: | agpl-3.0 | 8,069,233,019,505,464,000 | 46.839416 | 157 | 0.610255 | false | 3.877515 | false | false | false |
ProfessionalIT/maxigenios-website | sdk/google_appengine/lib/django-1.2/django/db/models/sql/datastructures.py | 396 | 1157 | """
Useful auxilliary data structures for query construction. Not useful outside
the SQL domain.
"""
class EmptyResultSet(Exception):
pass
class FullResultSet(Exception):
pass
class MultiJoin(Exception):
"""
Used by join construction code to indicate the point at which a
multi-valued join was attempted (if the caller wants to treat that
exceptionally).
"""
def __init__(self, level):
self.level = level
class Empty(object):
pass
class RawValue(object):
def __init__(self, value):
self.value = value
class Date(object):
"""
Add a date selection column.
"""
def __init__(self, col, lookup_type):
self.col = col
self.lookup_type = lookup_type
def relabel_aliases(self, change_map):
c = self.col
if isinstance(c, (list, tuple)):
self.col = (change_map.get(c[0], c[0]), c[1])
def as_sql(self, qn, connection):
if isinstance(self.col, (list, tuple)):
col = '%s.%s' % tuple([qn(c) for c in self.col])
else:
col = self.col
return connection.ops.date_trunc_sql(self.lookup_type, col)
| mit | 2,795,459,522,885,896,000 | 24.152174 | 76 | 0.607606 | false | 3.708333 | false | false | false |
wuga214/Django-Wuga | env/lib/python2.7/site-packages/pip/_vendor/distlib/markers.py | 1261 | 6282 | # -*- coding: utf-8 -*-
#
# Copyright (C) 2012-2013 Vinay Sajip.
# Licensed to the Python Software Foundation under a contributor agreement.
# See LICENSE.txt and CONTRIBUTORS.txt.
#
"""Parser for the environment markers micro-language defined in PEP 345."""
import ast
import os
import sys
import platform
from .compat import python_implementation, string_types
from .util import in_venv
__all__ = ['interpret']
class Evaluator(object):
"""
A limited evaluator for Python expressions.
"""
operators = {
'eq': lambda x, y: x == y,
'gt': lambda x, y: x > y,
'gte': lambda x, y: x >= y,
'in': lambda x, y: x in y,
'lt': lambda x, y: x < y,
'lte': lambda x, y: x <= y,
'not': lambda x: not x,
'noteq': lambda x, y: x != y,
'notin': lambda x, y: x not in y,
}
allowed_values = {
'sys_platform': sys.platform,
'python_version': '%s.%s' % sys.version_info[:2],
# parsing sys.platform is not reliable, but there is no other
# way to get e.g. 2.7.2+, and the PEP is defined with sys.version
'python_full_version': sys.version.split(' ', 1)[0],
'os_name': os.name,
'platform_in_venv': str(in_venv()),
'platform_release': platform.release(),
'platform_version': platform.version(),
'platform_machine': platform.machine(),
'platform_python_implementation': python_implementation(),
}
def __init__(self, context=None):
"""
Initialise an instance.
:param context: If specified, names are looked up in this mapping.
"""
self.context = context or {}
self.source = None
def get_fragment(self, offset):
"""
Get the part of the source which is causing a problem.
"""
fragment_len = 10
s = '%r' % (self.source[offset:offset + fragment_len])
if offset + fragment_len < len(self.source):
s += '...'
return s
def get_handler(self, node_type):
"""
Get a handler for the specified AST node type.
"""
return getattr(self, 'do_%s' % node_type, None)
def evaluate(self, node, filename=None):
"""
Evaluate a source string or node, using ``filename`` when
displaying errors.
"""
if isinstance(node, string_types):
self.source = node
kwargs = {'mode': 'eval'}
if filename:
kwargs['filename'] = filename
try:
node = ast.parse(node, **kwargs)
except SyntaxError as e:
s = self.get_fragment(e.offset)
raise SyntaxError('syntax error %s' % s)
node_type = node.__class__.__name__.lower()
handler = self.get_handler(node_type)
if handler is None:
if self.source is None:
s = '(source not available)'
else:
s = self.get_fragment(node.col_offset)
raise SyntaxError("don't know how to evaluate %r %s" % (
node_type, s))
return handler(node)
def get_attr_key(self, node):
assert isinstance(node, ast.Attribute), 'attribute node expected'
return '%s.%s' % (node.value.id, node.attr)
def do_attribute(self, node):
if not isinstance(node.value, ast.Name):
valid = False
else:
key = self.get_attr_key(node)
valid = key in self.context or key in self.allowed_values
if not valid:
raise SyntaxError('invalid expression: %s' % key)
if key in self.context:
result = self.context[key]
else:
result = self.allowed_values[key]
return result
def do_boolop(self, node):
result = self.evaluate(node.values[0])
is_or = node.op.__class__ is ast.Or
is_and = node.op.__class__ is ast.And
assert is_or or is_and
if (is_and and result) or (is_or and not result):
for n in node.values[1:]:
result = self.evaluate(n)
if (is_or and result) or (is_and and not result):
break
return result
def do_compare(self, node):
def sanity_check(lhsnode, rhsnode):
valid = True
if isinstance(lhsnode, ast.Str) and isinstance(rhsnode, ast.Str):
valid = False
#elif (isinstance(lhsnode, ast.Attribute)
# and isinstance(rhsnode, ast.Attribute)):
# klhs = self.get_attr_key(lhsnode)
# krhs = self.get_attr_key(rhsnode)
# valid = klhs != krhs
if not valid:
s = self.get_fragment(node.col_offset)
raise SyntaxError('Invalid comparison: %s' % s)
lhsnode = node.left
lhs = self.evaluate(lhsnode)
result = True
for op, rhsnode in zip(node.ops, node.comparators):
sanity_check(lhsnode, rhsnode)
op = op.__class__.__name__.lower()
if op not in self.operators:
raise SyntaxError('unsupported operation: %r' % op)
rhs = self.evaluate(rhsnode)
result = self.operators[op](lhs, rhs)
if not result:
break
lhs = rhs
lhsnode = rhsnode
return result
def do_expression(self, node):
return self.evaluate(node.body)
def do_name(self, node):
valid = False
if node.id in self.context:
valid = True
result = self.context[node.id]
elif node.id in self.allowed_values:
valid = True
result = self.allowed_values[node.id]
if not valid:
raise SyntaxError('invalid expression: %s' % node.id)
return result
def do_str(self, node):
return node.s
def interpret(marker, execution_context=None):
"""
Interpret a marker and return a result depending on environment.
:param marker: The marker to interpret.
:type marker: str
:param execution_context: The context used for name lookup.
:type execution_context: mapping
"""
return Evaluator(execution_context).evaluate(marker.strip())
| apache-2.0 | 4,225,784,778,292,974,600 | 32.063158 | 77 | 0.552053 | false | 4.011494 | false | false | false |
paulgclark/rf_utilities | zmq_utils.py | 1 | 1239 | import zmq
import array
import time
import struct
import numpy as np
import pmt
import sys
class zmq_pull_socket():
def __init__(self, tcp_str, verbose=0):
self.context = zmq.Context()
self.receiver = self.context.socket(zmq.PULL)
self.receiver.connect(tcp_str)
def poll(self, type_str='f', verbose=0):
raw_data = self.receiver.recv()
a = array.array(type_str, raw_data)
return a
def poll_message(self):
msg = self.receiver.recv()
# this is a binary string, convert it to a list of ints
byte_list = []
for byte in msg:
byte_list.append(ord(byte))
return byte_list
# incomplete attempt to optimize data flow by
# sending bytes instead of floats; flowgraph
# changes needed to support this, as well
# as all downstream code reworked to use
# bytes
def poll_short(self, type_str='h', verbose=0):
raw_data = self.receiver.recv()
a = array.array(type_str, raw_data)
npa_s = np.asarray(a)
npa_f = npa_s.astype(float)
npa_f *= (1.0/10000.0)
#fmt = "<%dI" % (len(raw_data) //4)
#a = list(struct.unpack(fmt, raw_data))
return list(npa_f)
| mit | 2,149,555,878,925,307,400 | 27.813953 | 63 | 0.596449 | false | 3.422652 | false | false | false |
kcpawan/django | tests/many_to_one/models.py | 215 | 2785 | """
Many-to-one relationships
To define a many-to-one relationship, use ``ForeignKey()``.
"""
from __future__ import unicode_literals
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
@python_2_unicode_compatible
class Reporter(models.Model):
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=30)
email = models.EmailField()
def __str__(self):
return "%s %s" % (self.first_name, self.last_name)
@python_2_unicode_compatible
class Article(models.Model):
headline = models.CharField(max_length=100)
pub_date = models.DateField()
reporter = models.ForeignKey(Reporter, models.CASCADE)
def __str__(self):
return self.headline
class Meta:
ordering = ('headline',)
# If ticket #1578 ever slips back in, these models will not be able to be
# created (the field names being lower-cased versions of their opposite
# classes is important here).
class First(models.Model):
second = models.IntegerField()
class Second(models.Model):
first = models.ForeignKey(First, models.CASCADE, related_name='the_first')
# Protect against repetition of #1839, #2415 and #2536.
class Third(models.Model):
name = models.CharField(max_length=20)
third = models.ForeignKey('self', models.SET_NULL, null=True, related_name='child_set')
class Parent(models.Model):
name = models.CharField(max_length=20, unique=True)
bestchild = models.ForeignKey('Child', models.SET_NULL, null=True, related_name='favored_by')
class Child(models.Model):
name = models.CharField(max_length=20)
parent = models.ForeignKey(Parent, models.CASCADE)
class ToFieldChild(models.Model):
parent = models.ForeignKey(Parent, models.CASCADE, to_field='name')
# Multiple paths to the same model (#7110, #7125)
@python_2_unicode_compatible
class Category(models.Model):
name = models.CharField(max_length=20)
def __str__(self):
return self.name
class Record(models.Model):
category = models.ForeignKey(Category, models.CASCADE)
@python_2_unicode_compatible
class Relation(models.Model):
left = models.ForeignKey(Record, models.CASCADE, related_name='left_set')
right = models.ForeignKey(Record, models.CASCADE, related_name='right_set')
def __str__(self):
return "%s - %s" % (self.left.category.name, self.right.category.name)
# Test related objects visibility.
class SchoolManager(models.Manager):
def get_queryset(self):
return super(SchoolManager, self).get_queryset().filter(is_public=True)
class School(models.Model):
is_public = models.BooleanField(default=False)
objects = SchoolManager()
class Student(models.Model):
school = models.ForeignKey(School, models.CASCADE)
| bsd-3-clause | -1,773,659,522,397,237,800 | 26.85 | 97 | 0.712029 | false | 3.607513 | false | false | false |
xguse/ggplot | ggplot/geoms/geom_abline.py | 12 | 1487 | from __future__ import (absolute_import, division, print_function,
unicode_literals)
import numpy as np
from ggplot.utils import make_iterable_ntimes
from .geom import geom
# Note when documenting
# slope and intercept can be functions that compute the slope
# and intercept using the data. If that is the case then the
# x and y aesthetics must be mapped
class geom_abline(geom):
DEFAULT_AES = {'color': 'black', 'linetype': 'solid',
'alpha': None, 'size': 1.0, 'x': None,
'y': None}
REQUIRED_AES = {'slope', 'intercept'}
DEFAULT_PARAMS = {'stat': 'abline', 'position': 'identity'}
_aes_renames = {'linetype': 'linestyle', 'size': 'linewidth'}
def _plot_unit(self, pinfo, ax):
slope = pinfo['slope']
intercept = pinfo['intercept']
n = len(slope)
linewidth = make_iterable_ntimes(pinfo['linewidth'], n)
linestyle = make_iterable_ntimes(pinfo['linestyle'], n)
alpha = make_iterable_ntimes(pinfo['alpha'], n)
color = make_iterable_ntimes(pinfo['color'], n)
ax.set_autoscale_on(False)
xlim = ax.get_xlim()
_x = np.array([np.min(xlim), np.max(xlim)])
for i in range(len(slope)):
_y = _x * slope[i] + intercept[i]
ax.plot(_x, _y,
linewidth=linewidth[i],
linestyle=linestyle[i],
alpha=alpha[i],
color=color[i])
| bsd-2-clause | -1,214,483,387,473,522,000 | 34.404762 | 66 | 0.569603 | false | 3.662562 | false | false | false |
Vegasvikk/django-cms | cms/models/static_placeholder.py | 49 | 3452 | import uuid
from django.contrib.auth import get_permission_codename
from django.contrib.sites.models import Site
from django.core.exceptions import ValidationError
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
from django.utils.translation import ugettext_lazy as _
from cms.models.fields import PlaceholderField
from cms.utils.copy_plugins import copy_plugins_to
def static_slotname(instance):
"""
Returns a string to be used as the slot
for the static placeholder field.
"""
return instance.code
@python_2_unicode_compatible
class StaticPlaceholder(models.Model):
CREATION_BY_TEMPLATE = 'template'
CREATION_BY_CODE = 'code'
CREATION_METHODS = (
(CREATION_BY_TEMPLATE, _('by template')),
(CREATION_BY_CODE, _('by code')),
)
name = models.CharField(
verbose_name=_(u'static placeholder name'), max_length=255, blank=True, default='',
help_text=_(u'Descriptive name to identify this static placeholder. Not displayed to users.'))
code = models.CharField(
verbose_name=_(u'placeholder code'), max_length=255, blank=True,
help_text=_(u'To render the static placeholder in templates.'))
draft = PlaceholderField(static_slotname, verbose_name=_(u'placeholder content'), related_name='static_draft')
public = PlaceholderField(static_slotname, editable=False, related_name='static_public')
dirty = models.BooleanField(default=False, editable=False)
creation_method = models.CharField(
verbose_name=_('creation_method'), choices=CREATION_METHODS,
default=CREATION_BY_CODE, max_length=20, blank=True,
)
site = models.ForeignKey(Site, null=True, blank=True)
class Meta:
verbose_name = _(u'static placeholder')
verbose_name_plural = _(u'static placeholders')
app_label = 'cms'
unique_together = (('code', 'site'),)
def __str__(self):
return self.name
def clean(self):
# TODO: check for clashes if the random code is already taken
if not self.code:
self.code = u'static-%s' % uuid.uuid4()
if not self.site:
placeholders = StaticPlaceholder.objects.filter(code=self.code, site__isnull=True)
if self.pk:
placeholders = placeholders.exclude(pk=self.pk)
if placeholders.exists():
raise ValidationError(_("A static placeholder with the same site and code already exists"))
def publish(self, request, language, force=False):
if force or self.has_publish_permission(request):
self.public.clear(language=language)
plugins = self.draft.get_plugins_list(language=language)
copy_plugins_to(plugins, self.public, no_signals=True)
self.dirty = False
self.save()
return True
return False
def has_change_permission(self, request):
if request.user.is_superuser:
return True
opts = self._meta
return request.user.has_perm(opts.app_label + '.' + get_permission_codename('change', opts))
def has_publish_permission(self, request):
if request.user.is_superuser:
return True
opts = self._meta
return request.user.has_perm(opts.app_label + '.' + get_permission_codename('change', opts)) and \
request.user.has_perm(opts.app_label + '.' + 'publish_page')
| bsd-3-clause | 5,500,780,088,044,019,000 | 39.139535 | 114 | 0.659328 | false | 4.070755 | false | false | false |
ChanChiChoi/scikit-learn | examples/model_selection/plot_roc.py | 146 | 3697 | """
=======================================
Receiver Operating Characteristic (ROC)
=======================================
Example of Receiver Operating Characteristic (ROC) metric to evaluate
classifier output quality.
ROC curves typically feature true positive rate on the Y axis, and false
positive rate on the X axis. This means that the top left corner of the plot is
the "ideal" point - a false positive rate of zero, and a true positive rate of
one. This is not very realistic, but it does mean that a larger area under the
curve (AUC) is usually better.
The "steepness" of ROC curves is also important, since it is ideal to maximize
the true positive rate while minimizing the false positive rate.
ROC curves are typically used in binary classification to study the output of
a classifier. In order to extend ROC curve and ROC area to multi-class
or multi-label classification, it is necessary to binarize the output. One ROC
curve can be drawn per label, but one can also draw a ROC curve by considering
each element of the label indicator matrix as a binary prediction
(micro-averaging).
.. note::
See also :func:`sklearn.metrics.roc_auc_score`,
:ref:`example_model_selection_plot_roc_crossval.py`.
"""
print(__doc__)
import numpy as np
import matplotlib.pyplot as plt
from sklearn import svm, datasets
from sklearn.metrics import roc_curve, auc
from sklearn.cross_validation import train_test_split
from sklearn.preprocessing import label_binarize
from sklearn.multiclass import OneVsRestClassifier
# Import some data to play with
iris = datasets.load_iris()
X = iris.data
y = iris.target
# Binarize the output
y = label_binarize(y, classes=[0, 1, 2])
n_classes = y.shape[1]
# Add noisy features to make the problem harder
random_state = np.random.RandomState(0)
n_samples, n_features = X.shape
X = np.c_[X, random_state.randn(n_samples, 200 * n_features)]
# shuffle and split training and test sets
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=.5,
random_state=0)
# Learn to predict each class against the other
classifier = OneVsRestClassifier(svm.SVC(kernel='linear', probability=True,
random_state=random_state))
y_score = classifier.fit(X_train, y_train).decision_function(X_test)
# Compute ROC curve and ROC area for each class
fpr = dict()
tpr = dict()
roc_auc = dict()
for i in range(n_classes):
fpr[i], tpr[i], _ = roc_curve(y_test[:, i], y_score[:, i])
roc_auc[i] = auc(fpr[i], tpr[i])
# Compute micro-average ROC curve and ROC area
fpr["micro"], tpr["micro"], _ = roc_curve(y_test.ravel(), y_score.ravel())
roc_auc["micro"] = auc(fpr["micro"], tpr["micro"])
# Plot of a ROC curve for a specific class
plt.figure()
plt.plot(fpr[2], tpr[2], label='ROC curve (area = %0.2f)' % roc_auc[2])
plt.plot([0, 1], [0, 1], 'k--')
plt.xlim([0.0, 1.0])
plt.ylim([0.0, 1.05])
plt.xlabel('False Positive Rate')
plt.ylabel('True Positive Rate')
plt.title('Receiver operating characteristic example')
plt.legend(loc="lower right")
plt.show()
# Plot ROC curve
plt.figure()
plt.plot(fpr["micro"], tpr["micro"],
label='micro-average ROC curve (area = {0:0.2f})'
''.format(roc_auc["micro"]))
for i in range(n_classes):
plt.plot(fpr[i], tpr[i], label='ROC curve of class {0} (area = {1:0.2f})'
''.format(i, roc_auc[i]))
plt.plot([0, 1], [0, 1], 'k--')
plt.xlim([0.0, 1.0])
plt.ylim([0.0, 1.05])
plt.xlabel('False Positive Rate')
plt.ylabel('True Positive Rate')
plt.title('Some extension of Receiver operating characteristic to multi-class')
plt.legend(loc="lower right")
plt.show()
| bsd-3-clause | 7,034,067,062,988,640,000 | 34.548077 | 79 | 0.675412 | false | 3.260141 | true | false | false |
rcolasanti/CompaniesHouseScraper | DVLACompanyNmeMatchCoHoAPIFindMissing.py | 1 | 5174 |
import requests
import json
import numpy as np
import pandas as pd
import CoHouseToken
from difflib import SequenceMatcher
# In[3]:
def exactMatch(line1, line2):
line1=line1.upper().rstrip()
line2=line2.upper().rstrip()
#print("|"+line1+"|"+line2+"|",line1==line2)
return line1==line2
def aStopWord(word):
return word.upper().replace("COMPANY","CO").replace("LIMITED","LTD").replace("&","AND").rstrip()
def spaces(word):
w = word.upper().replace("/"," ")
w = w.replace("."," ").replace(","," ").replace("-"," ").rstrip()
return w
def removeAStopWord(word):
w = word.upper().replace("LTD"," ").replace("CO"," ").replace("AND"," ").replace("("," ").replace("/"," ")
w = w.replace(")"," ").replace("."," ").replace(","," ").replace("-"," ").rstrip()
return w
def removeABlank(word):
w = word.replace(" ","")
return w
def removeABracket (line):
flag = False
word=""
for a in line:
if a=="(":
flag = True
a=""
if a==")":
a=""
flag = False
if flag:
a=""
word+=a
return word
def stopWord(line1, line2):
line1=aStopWord(line1)
line2=aStopWord(line2)
#print("|"+line1+"|"+line2+"|",line1==line2)
return line1==line2
def removeStopWord(line1, line2):
line1=spaces(line1)
line2=spaces(line2)
line1=aStopWord(line1)
line2=aStopWord(line2)
line1=removeAStopWord(line1)
line2=removeAStopWord(line2)
#print("|"+line1+"|"+line2+"|",line1==line2)
return line1==line2
def removeBlanks(line1, line2):
line1=spaces(line1)
line2=spaces(line2)
line1=aStopWord(line1)
line2=aStopWord(line2)
line1=removeAStopWord(line1)
line2=removeAStopWord(line2)
line1=removeABlank(line1)
line2=removeABlank(line2)
return line1==line2
def removeBrackets(line1, line2):
line1=removeABracket(line1)
line2=removeABracket(line2)
line1=spaces(line1)
line2=spaces(line2)
line1=aStopWord(line1)
line2=aStopWord(line2)
line1=removeAStopWord(line1)
line2=removeAStopWord(line2)
line1=removeABlank(line1)
line2=removeABlank(line2)
#print("|"+line1+"|"+line2+"|",line1==line2)
return line1==line2
def strip(line1, line2):
line1=removeABracket(line1)
line2=removeABracket(line2)
line1=spaces(line1)
line2=spaces(line2)
line1=aStopWord(line1)
line2=aStopWord(line2)
line1=removeAStopWord(line1)
line2=removeAStopWord(line2)
line1=removeABlank(line1)
line2=removeABlank(line2)
return line1,line2
def match(company,results):
for i in results['items']:
line = i['title']
number = i['company_number']
if(exactMatch(company,line)):
return True,line,number
for i in results['items']:
line = i['title']
number = i['company_number']
if(stopWord(company,line)):
return True,line,number
for i in results['items']:
line = i['title']
number = i['company_number']
if(removeStopWord(company,line)):
return True,line,number
for i in results['items']:
line = i['title']
number = i['company_number']
if(removeBlanks(company,line)):
return True,line,number
for i in results['items']:
line = i['title']
number = i['company_number']
if(removeBrackets(company,line)):
return True,line,number
#old_match(company,results)
return False,"",""
def main(args):
print(args[0])
search_url ="https://api.companieshouse.gov.uk/search/companies?q="
token = CoHouseToken.getToken()
pw = ''
base_url = 'https://api.companieshouse.gov.uk'
file = args[1]
print(file)
df = pd.read_csv(file,names=['Organisation'])
companies = df.Organisation
count=0
found = open("found2.csv",'w')
missing = open("missing2.csv",'w')
for c in companies:
c =c.upper().replace("&","AND")
c = c.split(" T/A ")[0]
c = c.split("WAS ")[0]
c= spaces(c)
url=search_url+c
results = json.loads(requests.get(url, auth=(token,pw)).text)
for i , key in enumerate(results['items']):
a,b = strip(c, key['title'])
r = SequenceMatcher(None, a, b).ratio()
print("%s \t %s\t %.2f \t %s \t %s"%(i,c,r,key['company_number'],key['title']))
v = input('type number or return to reject: ')
if v =="":
print("reject")
missing.write("%s\n"%(c))
else:
key = results['items'][int(v)]
print("%s \t %s\t %.2f \t %s \t %s"%(v,c,r,key['company_number'],key['title']))
print("*************************")
found.write("%s,%s,%s,\n"%(c,key['title'],key['company_number']))
print()
#print(count/len(companies))
return 0
if __name__ == '__main__':
import sys
sys.exit(main(sys.argv))
| gpl-3.0 | -9,107,299,095,821,690,000 | 20.380165 | 110 | 0.55547 | false | 3.272612 | false | false | false |
javierTerry/odoo | addons/email_template/html2text.py | 440 | 14143 | #!/usr/bin/env python
"""html2text: Turn HTML into equivalent Markdown-structured text."""
__version__ = "2.36"
__author__ = "Aaron Swartz (me@aaronsw.com)"
__copyright__ = "(C) 2004-2008 Aaron Swartz. GNU GPL 3."
__contributors__ = ["Martin 'Joey' Schulze", "Ricardo Reyes", "Kevin Jay North"]
# TODO:
# Support decoded entities with unifiable.
if not hasattr(__builtins__, 'True'): True, False = 1, 0
import re, sys, urllib, htmlentitydefs, codecs
import sgmllib
import urlparse
sgmllib.charref = re.compile('&#([xX]?[0-9a-fA-F]+)[^0-9a-fA-F]')
try: from textwrap import wrap
except: pass
# Use Unicode characters instead of their ascii psuedo-replacements
UNICODE_SNOB = 0
# Put the links after each paragraph instead of at the end.
LINKS_EACH_PARAGRAPH = 0
# Wrap long lines at position. 0 for no wrapping. (Requires Python 2.3.)
BODY_WIDTH = 78
# Don't show internal links (href="#local-anchor") -- corresponding link targets
# won't be visible in the plain text file anyway.
SKIP_INTERNAL_LINKS = False
### Entity Nonsense ###
def name2cp(k):
if k == 'apos': return ord("'")
if hasattr(htmlentitydefs, "name2codepoint"): # requires Python 2.3
return htmlentitydefs.name2codepoint[k]
else:
k = htmlentitydefs.entitydefs[k]
if k.startswith("&#") and k.endswith(";"): return int(k[2:-1]) # not in latin-1
return ord(codecs.latin_1_decode(k)[0])
unifiable = {'rsquo':"'", 'lsquo':"'", 'rdquo':'"', 'ldquo':'"',
'copy':'(C)', 'mdash':'--', 'nbsp':' ', 'rarr':'->', 'larr':'<-', 'middot':'*',
'ndash':'-', 'oelig':'oe', 'aelig':'ae',
'agrave':'a', 'aacute':'a', 'acirc':'a', 'atilde':'a', 'auml':'a', 'aring':'a',
'egrave':'e', 'eacute':'e', 'ecirc':'e', 'euml':'e',
'igrave':'i', 'iacute':'i', 'icirc':'i', 'iuml':'i',
'ograve':'o', 'oacute':'o', 'ocirc':'o', 'otilde':'o', 'ouml':'o',
'ugrave':'u', 'uacute':'u', 'ucirc':'u', 'uuml':'u'}
unifiable_n = {}
for k in unifiable.keys():
unifiable_n[name2cp(k)] = unifiable[k]
def charref(name):
if name[0] in ['x','X']:
c = int(name[1:], 16)
else:
c = int(name)
if not UNICODE_SNOB and c in unifiable_n.keys():
return unifiable_n[c]
else:
return unichr(c)
def entityref(c):
if not UNICODE_SNOB and c in unifiable.keys():
return unifiable[c]
else:
try: name2cp(c)
except KeyError: return "&" + c
else: return unichr(name2cp(c))
def replaceEntities(s):
s = s.group(1)
if s[0] == "#":
return charref(s[1:])
else: return entityref(s)
r_unescape = re.compile(r"&(#?[xX]?(?:[0-9a-fA-F]+|\w{1,8}));")
def unescape(s):
return r_unescape.sub(replaceEntities, s)
def fixattrs(attrs):
# Fix bug in sgmllib.py
if not attrs: return attrs
newattrs = []
for attr in attrs:
newattrs.append((attr[0], unescape(attr[1])))
return newattrs
### End Entity Nonsense ###
def onlywhite(line):
"""Return true if the line does only consist of whitespace characters."""
for c in line:
if c is not ' ' and c is not ' ':
return c is ' '
return line
def optwrap(text):
"""Wrap all paragraphs in the provided text."""
if not BODY_WIDTH:
return text
assert wrap, "Requires Python 2.3."
result = ''
newlines = 0
for para in text.split("\n"):
if len(para) > 0:
if para[0] is not ' ' and para[0] is not '-' and para[0] is not '*':
for line in wrap(para, BODY_WIDTH):
result += line + "\n"
result += "\n"
newlines = 2
else:
if not onlywhite(para):
result += para + "\n"
newlines = 1
else:
if newlines < 2:
result += "\n"
newlines += 1
return result
def hn(tag):
if tag[0] == 'h' and len(tag) == 2:
try:
n = int(tag[1])
if n in range(1, 10): return n
except ValueError: return 0
class _html2text(sgmllib.SGMLParser):
def __init__(self, out=sys.stdout.write, baseurl=''):
sgmllib.SGMLParser.__init__(self)
if out is None: self.out = self.outtextf
else: self.out = out
self.outtext = u''
self.quiet = 0
self.p_p = 0
self.outcount = 0
self.start = 1
self.space = 0
self.a = []
self.astack = []
self.acount = 0
self.list = []
self.blockquote = 0
self.pre = 0
self.startpre = 0
self.lastWasNL = 0
self.abbr_title = None # current abbreviation definition
self.abbr_data = None # last inner HTML (for abbr being defined)
self.abbr_list = {} # stack of abbreviations to write later
self.baseurl = baseurl
def outtextf(self, s):
self.outtext += s
def close(self):
sgmllib.SGMLParser.close(self)
self.pbr()
self.o('', 0, 'end')
return self.outtext
def handle_charref(self, c):
self.o(charref(c))
def handle_entityref(self, c):
self.o(entityref(c))
def unknown_starttag(self, tag, attrs):
self.handle_tag(tag, attrs, 1)
def unknown_endtag(self, tag):
self.handle_tag(tag, None, 0)
def previousIndex(self, attrs):
""" returns the index of certain set of attributes (of a link) in the
self.a list
If the set of attributes is not found, returns None
"""
if not attrs.has_key('href'): return None
i = -1
for a in self.a:
i += 1
match = 0
if a.has_key('href') and a['href'] == attrs['href']:
if a.has_key('title') or attrs.has_key('title'):
if (a.has_key('title') and attrs.has_key('title') and
a['title'] == attrs['title']):
match = True
else:
match = True
if match: return i
def handle_tag(self, tag, attrs, start):
attrs = fixattrs(attrs)
if hn(tag):
self.p()
if start: self.o(hn(tag)*"#" + ' ')
if tag in ['p', 'div']: self.p()
if tag == "br" and start: self.o(" \n")
if tag == "hr" and start:
self.p()
self.o("* * *")
self.p()
if tag in ["head", "style", 'script']:
if start: self.quiet += 1
else: self.quiet -= 1
if tag in ["body"]:
self.quiet = 0 # sites like 9rules.com never close <head>
if tag == "blockquote":
if start:
self.p(); self.o('> ', 0, 1); self.start = 1
self.blockquote += 1
else:
self.blockquote -= 1
self.p()
if tag in ['em', 'i', 'u']: self.o("_")
if tag in ['strong', 'b']: self.o("**")
if tag == "code" and not self.pre: self.o('`') #TODO: `` `this` ``
if tag == "abbr":
if start:
attrsD = {}
for (x, y) in attrs: attrsD[x] = y
attrs = attrsD
self.abbr_title = None
self.abbr_data = ''
if attrs.has_key('title'):
self.abbr_title = attrs['title']
else:
if self.abbr_title != None:
self.abbr_list[self.abbr_data] = self.abbr_title
self.abbr_title = None
self.abbr_data = ''
if tag == "a":
if start:
attrsD = {}
for (x, y) in attrs: attrsD[x] = y
attrs = attrsD
if attrs.has_key('href') and not (SKIP_INTERNAL_LINKS and attrs['href'].startswith('#')):
self.astack.append(attrs)
self.o("[")
else:
self.astack.append(None)
else:
if self.astack:
a = self.astack.pop()
if a:
i = self.previousIndex(a)
if i is not None:
a = self.a[i]
else:
self.acount += 1
a['count'] = self.acount
a['outcount'] = self.outcount
self.a.append(a)
self.o("][" + `a['count']` + "]")
if tag == "img" and start:
attrsD = {}
for (x, y) in attrs: attrsD[x] = y
attrs = attrsD
if attrs.has_key('src'):
attrs['href'] = attrs['src']
alt = attrs.get('alt', '')
i = self.previousIndex(attrs)
if i is not None:
attrs = self.a[i]
else:
self.acount += 1
attrs['count'] = self.acount
attrs['outcount'] = self.outcount
self.a.append(attrs)
self.o("![")
self.o(alt)
self.o("]["+`attrs['count']`+"]")
if tag == 'dl' and start: self.p()
if tag == 'dt' and not start: self.pbr()
if tag == 'dd' and start: self.o(' ')
if tag == 'dd' and not start: self.pbr()
if tag in ["ol", "ul"]:
if start:
self.list.append({'name':tag, 'num':0})
else:
if self.list: self.list.pop()
self.p()
if tag == 'li':
if start:
self.pbr()
if self.list: li = self.list[-1]
else: li = {'name':'ul', 'num':0}
self.o(" "*len(self.list)) #TODO: line up <ol><li>s > 9 correctly.
if li['name'] == "ul": self.o("* ")
elif li['name'] == "ol":
li['num'] += 1
self.o(`li['num']`+". ")
self.start = 1
else:
self.pbr()
if tag in ["table", "tr"] and start: self.p()
if tag == 'td': self.pbr()
if tag == "pre":
if start:
self.startpre = 1
self.pre = 1
else:
self.pre = 0
self.p()
def pbr(self):
if self.p_p == 0: self.p_p = 1
def p(self):
self.p_p = 2
def o(self, data, puredata=0, force=0):
if self.abbr_data is not None: self.abbr_data += data
if not self.quiet:
if puredata and not self.pre:
data = re.sub('\s+', ' ', data)
if data and data[0] == ' ':
self.space = 1
data = data[1:]
if not data and not force: return
if self.startpre:
#self.out(" :") #TODO: not output when already one there
self.startpre = 0
bq = (">" * self.blockquote)
if not (force and data and data[0] == ">") and self.blockquote: bq += " "
if self.pre:
bq += " "
data = data.replace("\n", "\n"+bq)
if self.start:
self.space = 0
self.p_p = 0
self.start = 0
if force == 'end':
# It's the end.
self.p_p = 0
self.out("\n")
self.space = 0
if self.p_p:
self.out(('\n'+bq)*self.p_p)
self.space = 0
if self.space:
if not self.lastWasNL: self.out(' ')
self.space = 0
if self.a and ((self.p_p == 2 and LINKS_EACH_PARAGRAPH) or force == "end"):
if force == "end": self.out("\n")
newa = []
for link in self.a:
if self.outcount > link['outcount']:
self.out(" ["+`link['count']`+"]: " + urlparse.urljoin(self.baseurl, link['href']))
if link.has_key('title'): self.out(" ("+link['title']+")")
self.out("\n")
else:
newa.append(link)
if self.a != newa: self.out("\n") # Don't need an extra line when nothing was done.
self.a = newa
if self.abbr_list and force == "end":
for abbr, definition in self.abbr_list.items():
self.out(" *[" + abbr + "]: " + definition + "\n")
self.p_p = 0
self.out(data)
self.lastWasNL = data and data[-1] == '\n'
self.outcount += 1
def handle_data(self, data):
if r'\/script>' in data: self.quiet -= 1
self.o(data, 1)
def unknown_decl(self, data):
pass
def wrapwrite(text): sys.stdout.write(text.encode('utf8'))
def html2text_file(html, out=wrapwrite, baseurl=''):
h = _html2text(out, baseurl)
h.feed(html)
h.feed("")
return h.close()
def html2text(html, baseurl=''):
return optwrap(html2text_file(html, None, baseurl))
if __name__ == "__main__":
baseurl = ''
if sys.argv[1:]:
arg = sys.argv[1]
if arg.startswith('http://'):
baseurl = arg
j = urllib.urlopen(baseurl)
try:
from feedparser import _getCharacterEncoding as enc
except ImportError:
enc = lambda x, y: ('utf-8', 1)
text = j.read()
encoding = enc(j.headers, text)[0]
if encoding == 'us-ascii': encoding = 'utf-8'
data = text.decode(encoding)
else:
encoding = 'utf8'
if len(sys.argv) > 2:
encoding = sys.argv[2]
f = open(arg, 'r')
try:
data = f.read().decode(encoding)
finally:
f.close()
else:
data = sys.stdin.read().decode('utf8')
wrapwrite(html2text(data, baseurl))
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
| agpl-3.0 | -7,231,034,888,977,510,000 | 29.812636 | 109 | 0.466096 | false | 3.623623 | false | false | false |