repo_name stringlengths 5 100 | ref stringlengths 12 67 | path stringlengths 4 244 | copies stringlengths 1 8 | content stringlengths 0 1.05M ⌀ |
|---|---|---|---|---|
MoritzS/django | refs/heads/master | tests/migrations/test_migrations_squashed_complex_multi_apps/__init__.py | 12133432 | |
davemerwin/blue-channel | refs/heads/master | external_apps/voting/tests/__init__.py | 12133432 | |
damngamerz/coala-bears | refs/heads/master | tests/c_languages/CPPLintBearTest.py | 21 | from bears.c_languages.CPPLintBear import CPPLintBear
from coalib.testing.LocalBearTestHelper import verify_local_bear
test_file = """
int main() {
return 0;
}
"""
CPPLintBearTest = verify_local_bear(CPPLintBear,
valid_files=(),
invalid_files=(test_file,),
tempfile_kwargs={'suffix': '.cpp'})
CPPLintBearIgnoreConfigTest = verify_local_bear(
CPPLintBear,
valid_files=(test_file,),
invalid_files=(),
settings={'cpplint_ignore': 'legal'},
tempfile_kwargs={'suffix': '.cpp'})
CPPLintBearLineLengthConfigTest = verify_local_bear(
CPPLintBear,
valid_files=(),
invalid_files=(test_file,),
settings={'cpplint_ignore': 'legal',
'max_line_length': '13'},
tempfile_kwargs={'suffix': '.cpp'})
|
rahul67/hue | refs/heads/master | desktop/core/ext-py/django-extensions-1.5.0/django_extensions/jobs/weekly/__init__.py | 12133432 | |
sedden/django-basic-apps | refs/heads/fixing_event_detail | basic/movies/__init__.py | 12133432 | |
hellsgate1001/bookit | refs/heads/master | docs/env/Lib/site-packages/django/conf/locale/en/__init__.py | 12133432 | |
Learningtribes/edx-platform | refs/heads/master | openedx/core/djangoapps/user_api/course_tag/tests/__init__.py | 12133432 | |
ytjiang/django | refs/heads/master | tests/empty/__init__.py | 12133432 | |
mitya57/django | refs/heads/master | tests/admin_registration/__init__.py | 12133432 | |
neutrons/FastGR | refs/heads/master | addie/databases/oncat/__init__.py | 12133432 | |
pferreir/indico | refs/heads/master | indico/modules/events/sessions/controllers/__init__.py | 12133432 | |
varunarya10/jenkins-job-builder | refs/heads/master | tests/scm/__init__.py | 12133432 | |
itbabu/saleor | refs/heads/master | saleor/product/templatetags/product_images.py | 6 | import logging
import re
import warnings
from django import template
from django.conf import settings
from django.contrib.staticfiles.templatetags.staticfiles import static
logger = logging.getLogger(__name__)
register = template.Library()
# cache available sizes at module level
def get_available_sizes():
all_sizes = set()
keys = settings.VERSATILEIMAGEFIELD_RENDITION_KEY_SETS
for size_group, sizes in keys.items():
for size_name, size in sizes:
all_sizes.add(size)
return all_sizes
AVAILABLE_SIZES = get_available_sizes()
def choose_placeholder(size=''):
# type: (str) -> str
"""Assign placeholder at least as big as provided size if possible.
When size is bigger than available, return the biggest.
If size is invalid or not provided, return DEFAULT_PLACEHOLDER"""
placeholder = settings.DEFAULT_PLACEHOLDER
parsed_sizes = re.match(r'(\d+)x(\d+)', size)
available_sizes = sorted(settings.PLACEHOLDER_IMAGES.keys())
if parsed_sizes and available_sizes:
# check for placeholder equal or bigger than requested picture
x_size, y_size = parsed_sizes.groups()
max_size = max([int(x_size), int(y_size)])
bigger_or_eq = list(filter(lambda x: x >= max_size, available_sizes))
if len(bigger_or_eq) > 0:
placeholder = settings.PLACEHOLDER_IMAGES[bigger_or_eq[0]]
else:
placeholder = settings.PLACEHOLDER_IMAGES[available_sizes[-1]]
return placeholder
@register.simple_tag()
def get_thumbnail(instance, size, method='crop'):
size_name = '%s__%s' % (method, size)
if instance:
if (size_name not in AVAILABLE_SIZES and not
settings.VERSATILEIMAGEFIELD_SETTINGS['create_images_on_demand']):
msg = ('Thumbnail size %s is not defined in settings '
'and it won\'t be generated automatically' % size_name)
warnings.warn(msg)
try:
if method == 'crop':
thumbnail = instance.crop[size]
else:
thumbnail = instance.thumbnail[size]
except:
logger.exception('Thumbnail fetch failed',
extra={'instance': instance, 'size': size})
else:
return thumbnail.url
return static(choose_placeholder(size))
@register.simple_tag()
def product_first_image(product, size, method='crop'):
"""
Returns main product image
"""
all_images = product.images.all()
main_image = all_images[0].image if all_images else None
return get_thumbnail(main_image, size, method)
|
edmundgentle/schoolscript | refs/heads/master | SchoolScript/bin/Debug/pythonlib/Lib/test/json_tests/test_pass2.py | 3 | from test.json_tests import PyTest, CTest
# from http://json.org/JSON_checker/test/pass2.json
JSON = r'''
[[[[[[[[[[[[[[[[[[["Not too deep"]]]]]]]]]]]]]]]]]]]
'''
class TestPass2:
def test_parse(self):
# test in/out equivalence and parsing
res = self.loads(JSON)
out = self.dumps(res)
self.assertEqual(res, self.loads(out))
class TestPyPass2(TestPass2, PyTest): pass
class TestCPass2(TestPass2, CTest): pass
|
aptana/Pydev | refs/heads/development | bundles/org.python.pydev.jython/Lib/posixfile.py | 12 | """Extended file operations available in POSIX.
f = posixfile.open(filename, [mode, [bufsize]])
will create a new posixfile object
f = posixfile.fileopen(fileobject)
will create a posixfile object from a builtin file object
f.file()
will return the original builtin file object
f.dup()
will return a new file object based on a new filedescriptor
f.dup2(fd)
will return a new file object based on the given filedescriptor
f.flags(mode)
will turn on the associated flag (merge)
mode can contain the following characters:
(character representing a flag)
a append only flag
c close on exec flag
n no delay flag
s synchronization flag
(modifiers)
! turn flags 'off' instead of default 'on'
= copy flags 'as is' instead of default 'merge'
? return a string in which the characters represent the flags
that are set
note: - the '!' and '=' modifiers are mutually exclusive.
- the '?' modifier will return the status of the flags after they
have been changed by other characters in the mode string
f.lock(mode [, len [, start [, whence]]])
will (un)lock a region
mode can contain the following characters:
(character representing type of lock)
u unlock
r read lock
w write lock
(modifiers)
| wait until the lock can be granted
? return the first lock conflicting with the requested lock
or 'None' if there is no conflict. The lock returned is in the
format (mode, len, start, whence, pid) where mode is a
character representing the type of lock ('r' or 'w')
note: - the '?' modifier prevents a region from being locked; it is
query only
"""
import warnings
warnings.warn(
"The posixfile module is obsolete and will disappear in the future",
DeprecationWarning)
del warnings
class _posixfile_:
"""File wrapper class that provides extra POSIX file routines."""
states = ['open', 'closed']
#
# Internal routines
#
def __repr__(self):
file = self._file_
return "<%s posixfile '%s', mode '%s' at %s>" % \
(self.states[file.closed], file.name, file.mode, \
hex(id(self))[2:])
#
# Initialization routines
#
def open(self, name, mode='r', bufsize=-1):
import __builtin__
return self.fileopen(__builtin__.open(name, mode, bufsize))
def fileopen(self, file):
import types
if `type(file)` != "<type 'file'>":
raise TypeError, 'posixfile.fileopen() arg must be file object'
self._file_ = file
# Copy basic file methods
for maybemethod in dir(file):
if not maybemethod.startswith('_'):
attr = getattr(file, maybemethod)
if isinstance(attr, types.BuiltinMethodType):
setattr(self, maybemethod, attr)
return self
#
# New methods
#
def file(self):
return self._file_
def dup(self):
import posix
if not hasattr(posix, 'fdopen'):
raise AttributeError, 'dup() method unavailable'
return posix.fdopen(posix.dup(self._file_.fileno()), self._file_.mode)
def dup2(self, fd):
import posix
if not hasattr(posix, 'fdopen'):
raise AttributeError, 'dup() method unavailable'
posix.dup2(self._file_.fileno(), fd)
return posix.fdopen(fd, self._file_.mode)
def flags(self, *which):
import fcntl, os
if which:
if len(which) > 1:
raise TypeError, 'Too many arguments'
which = which[0]
else: which = '?'
l_flags = 0
if 'n' in which: l_flags = l_flags | os.O_NDELAY
if 'a' in which: l_flags = l_flags | os.O_APPEND
if 's' in which: l_flags = l_flags | os.O_SYNC
file = self._file_
if '=' not in which:
cur_fl = fcntl.fcntl(file.fileno(), fcntl.F_GETFL, 0)
if '!' in which: l_flags = cur_fl & ~ l_flags
else: l_flags = cur_fl | l_flags
l_flags = fcntl.fcntl(file.fileno(), fcntl.F_SETFL, l_flags)
if 'c' in which:
arg = ('!' not in which) # 0 is don't, 1 is do close on exec
l_flags = fcntl.fcntl(file.fileno(), fcntl.F_SETFD, arg)
if '?' in which:
which = '' # Return current flags
l_flags = fcntl.fcntl(file.fileno(), fcntl.F_GETFL, 0)
if os.O_APPEND & l_flags: which = which + 'a'
if fcntl.fcntl(file.fileno(), fcntl.F_GETFD, 0) & 1:
which = which + 'c'
if os.O_NDELAY & l_flags: which = which + 'n'
if os.O_SYNC & l_flags: which = which + 's'
return which
def lock(self, how, *args):
import struct, fcntl
if 'w' in how: l_type = fcntl.F_WRLCK
elif 'r' in how: l_type = fcntl.F_RDLCK
elif 'u' in how: l_type = fcntl.F_UNLCK
else: raise TypeError, 'no type of lock specified'
if '|' in how: cmd = fcntl.F_SETLKW
elif '?' in how: cmd = fcntl.F_GETLK
else: cmd = fcntl.F_SETLK
l_whence = 0
l_start = 0
l_len = 0
if len(args) == 1:
l_len = args[0]
elif len(args) == 2:
l_len, l_start = args
elif len(args) == 3:
l_len, l_start, l_whence = args
elif len(args) > 3:
raise TypeError, 'too many arguments'
# Hack by davem@magnet.com to get locking to go on freebsd;
# additions for AIX by Vladimir.Marangozov@imag.fr
import sys, os
if sys.platform in ('netbsd1',
'openbsd2',
'freebsd2', 'freebsd3', 'freebsd4', 'freebsd5',
'bsdos2', 'bsdos3', 'bsdos4'):
flock = struct.pack('lxxxxlxxxxlhh', \
l_start, l_len, os.getpid(), l_type, l_whence)
elif sys.platform in ['aix3', 'aix4']:
flock = struct.pack('hhlllii', \
l_type, l_whence, l_start, l_len, 0, 0, 0)
else:
flock = struct.pack('hhllhh', \
l_type, l_whence, l_start, l_len, 0, 0)
flock = fcntl.fcntl(self._file_.fileno(), cmd, flock)
if '?' in how:
if sys.platform in ('netbsd1',
'openbsd2',
'freebsd2', 'freebsd3', 'freebsd4', 'freebsd5',
'bsdos2', 'bsdos3', 'bsdos4'):
l_start, l_len, l_pid, l_type, l_whence = \
struct.unpack('lxxxxlxxxxlhh', flock)
elif sys.platform in ['aix3', 'aix4']:
l_type, l_whence, l_start, l_len, l_sysid, l_pid, l_vfs = \
struct.unpack('hhlllii', flock)
elif sys.platform == "linux2":
l_type, l_whence, l_start, l_len, l_pid, l_sysid = \
struct.unpack('hhllhh', flock)
else:
l_type, l_whence, l_start, l_len, l_sysid, l_pid = \
struct.unpack('hhllhh', flock)
if l_type != fcntl.F_UNLCK:
if l_type == fcntl.F_RDLCK:
return 'r', l_len, l_start, l_whence, l_pid
else:
return 'w', l_len, l_start, l_whence, l_pid
def open(name, mode='r', bufsize=-1):
"""Public routine to open a file as a posixfile object."""
return _posixfile_().open(name, mode, bufsize)
def fileopen(file):
"""Public routine to get a posixfile object from a Python file object."""
return _posixfile_().fileopen(file)
#
# Constants
#
SEEK_SET = 0
SEEK_CUR = 1
SEEK_END = 2
#
# End of posixfile.py
#
|
glwu/python-for-android | refs/heads/master | python3-alpha/python3-src/Lib/hashlib.py | 46 | # Copyright (C) 2005-2010 Gregory P. Smith (greg@krypto.org)
# Licensed to PSF under a Contributor Agreement.
#
__doc__ = """hashlib module - A common interface to many hash functions.
new(name, data=b'') - returns a new hash object implementing the
given hash function; initializing the hash
using the given binary data.
Named constructor functions are also available, these are faster
than using new(name):
md5(), sha1(), sha224(), sha256(), sha384(), and sha512()
More algorithms may be available on your platform but the above are guaranteed
to exist. See the algorithms_guaranteed and algorithms_available attributes
to find out what algorithm names can be passed to new().
NOTE: If you want the adler32 or crc32 hash functions they are available in
the zlib module.
Choose your hash function wisely. Some have known collision weaknesses.
sha384 and sha512 will be slow on 32 bit platforms.
Hash objects have these methods:
- update(arg): Update the hash object with the bytes in arg. Repeated calls
are equivalent to a single call with the concatenation of all
the arguments.
- digest(): Return the digest of the bytes passed to the update() method
so far.
- hexdigest(): Like digest() except the digest is returned as a unicode
object of double length, containing only hexadecimal digits.
- copy(): Return a copy (clone) of the hash object. This can be used to
efficiently compute the digests of strings that share a common
initial substring.
For example, to obtain the digest of the string 'Nobody inspects the
spammish repetition':
>>> import hashlib
>>> m = hashlib.md5()
>>> m.update(b"Nobody inspects")
>>> m.update(b" the spammish repetition")
>>> m.digest()
b'\\xbbd\\x9c\\x83\\xdd\\x1e\\xa5\\xc9\\xd9\\xde\\xc9\\xa1\\x8d\\xf0\\xff\\xe9'
More condensed:
>>> hashlib.sha224(b"Nobody inspects the spammish repetition").hexdigest()
'a4337bc45a8fc544c03f52dc550cd6e1e87021bc896588bd79e901e2'
"""
# This tuple and __get_builtin_constructor() must be modified if a new
# always available algorithm is added.
__always_supported = ('md5', 'sha1', 'sha224', 'sha256', 'sha384', 'sha512')
algorithms_guaranteed = set(__always_supported)
algorithms_available = set(__always_supported)
__all__ = __always_supported + ('new', 'algorithms_guaranteed',
'algorithms_available')
def __get_builtin_constructor(name):
try:
if name in ('SHA1', 'sha1'):
import _sha1
return _sha1.sha1
elif name in ('MD5', 'md5'):
import _md5
return _md5.md5
elif name in ('SHA256', 'sha256', 'SHA224', 'sha224'):
import _sha256
bs = name[3:]
if bs == '256':
return _sha256.sha256
elif bs == '224':
return _sha256.sha224
elif name in ('SHA512', 'sha512', 'SHA384', 'sha384'):
import _sha512
bs = name[3:]
if bs == '512':
return _sha512.sha512
elif bs == '384':
return _sha512.sha384
except ImportError:
pass # no extension module, this hash is unsupported.
raise ValueError('unsupported hash type %s' % name)
def __get_openssl_constructor(name):
try:
f = getattr(_hashlib, 'openssl_' + name)
# Allow the C module to raise ValueError. The function will be
# defined but the hash not actually available thanks to OpenSSL.
f()
# Use the C function directly (very fast)
return f
except (AttributeError, ValueError):
return __get_builtin_constructor(name)
def __py_new(name, data=b''):
"""new(name, data=b'') - Return a new hashing object using the named algorithm;
optionally initialized with data (which must be bytes).
"""
return __get_builtin_constructor(name)(data)
def __hash_new(name, data=b''):
"""new(name, data=b'') - Return a new hashing object using the named algorithm;
optionally initialized with data (which must be bytes).
"""
try:
return _hashlib.new(name, data)
except ValueError:
# If the _hashlib module (OpenSSL) doesn't support the named
# hash, try using our builtin implementations.
# This allows for SHA224/256 and SHA384/512 support even though
# the OpenSSL library prior to 0.9.8 doesn't provide them.
return __get_builtin_constructor(name)(data)
try:
import _hashlib
new = __hash_new
__get_hash = __get_openssl_constructor
algorithms_available = algorithms_available.union(
_hashlib.openssl_md_meth_names)
except ImportError:
new = __py_new
__get_hash = __get_builtin_constructor
for __func_name in __always_supported:
# try them all, some may not work due to the OpenSSL
# version not supporting that algorithm.
try:
globals()[__func_name] = __get_hash(__func_name)
except ValueError:
import logging
logging.exception('code for hash %s was not found.', __func_name)
# Cleanup locals()
del __always_supported, __func_name, __get_hash
del __py_new, __hash_new, __get_openssl_constructor
|
shubhamchaudhary/pulla | refs/heads/develop | tests/test_pulla.py | 1 | #!/usr/bin/env python
from __future__ import print_function
import os
from itertools import chain
try:
import unittest
import unittest.mock
from unittest.mock import patch
from unittest.mock import call
except ImportError as e:
import unittest2 as unittest
import mock
from mock import patch
from mock import call
from pulla import Pulla
@patch('os.walk')
@patch('pulla.pulla.is_this_a_git_dir')
@patch('multiprocessing.Process')
class TestPullAll(unittest.TestCase):
def setUp(self):
self.directories_folder = ('a', 'b', 'c')
self.directory_sub_folder = ('d', 'e', 'f')
def test_pull_all_starts_process_for_folders_in_passed_directory_when_not_recursive(
self, mock_multiprocess, mock_is_git, mock_walk
):
mock_walk.return_value = [
('foo', self.directories_folder, ('baz', )),
('foo/bar', ('d', 'e', 'f'), ('spam', 'eggs')),
]
mock_is_git.return_value = True
puller = Pulla()
puller.pull_all('foo')
directories_folder_to_be_pulled = [os.path.join('foo', dir) for dir in self.directories_folder]
calls = [call(dir) for dir in directories_folder_to_be_pulled]
mock_is_git.assert_has_calls(calls)
calls_for_process_creation = self.get_calls_for_process_creation(
directories_folder_to_be_pulled, puller)
mock_multiprocess.assert_has_calls(calls_for_process_creation)
def test_pull_all_starts_process_for_all_folders_when_recursive(
self, mock_multiprocess, mock_is_git, mock_walk
):
mock_walk.return_value = [
('foo', self.directories_folder, ('baz', )),
('foo/bar', self.directory_sub_folder, ('spam', 'eggs')),
]
mock_is_git.return_value = True
puller = Pulla(recursive=True)
puller.pull_all('foo')
directories_to_be_pulled = [os.path.join('foo', dir) for dir in self.directories_folder] + [os.path.join('foo', 'bar', dir) for dir in self.directory_sub_folder]
calls_for_process_creation = self.get_calls_for_process_creation(
directories_to_be_pulled, puller)
mock_multiprocess.assert_has_calls(calls_for_process_creation)
def get_calls_for_process_creation(self, directories_to_be_pulled, puller):
'''
:return: list with format
[
call(args=['dir1'], target=puller.do_pull_in),
call().start(),
call(args=['dir2'], target=puller.do_pull_in),
call().start(),
]
'''
calls_for_process_creation = list(chain.from_iterable(
(
call(args=[dir],
target=puller.do_pull_in), call().start()
) for dir in directories_to_be_pulled))
return calls_for_process_creation
@patch('pulla.pulla.Pulla.perform_git_pull')
class TestDoPullIn(unittest.TestCase):
def setUp(self):
self.directory = 'foo'
self.puller = Pulla()
def test_perform_git_pull_called_for_passed_directory(
self, mock_perform_git_pull
):
self.puller.do_pull_in(self.directory)
mock_perform_git_pull.assert_called_once_with(self.directory)
@patch('pulla.pulla.Pulla.get_formatted_status_message')
def test_status_success_when_git_command_successful(
self, mock_get_formatted_status_message, mock_perform_git_pull
):
mock_perform_git_pull.return_value = 0
self.puller.do_pull_in(self.directory)
mock_get_formatted_status_message.assert_called_once_with(
self.directory, 0)
@patch('pulla.pulla.Pulla.get_formatted_status_message')
def test_status_fail_when_git_command_successful(
self, mock_get_formatted_status_message, mock_perform_git_pull
):
mock_perform_git_pull.return_value = 128
self.puller.do_pull_in(self.directory)
mock_get_formatted_status_message.assert_called_once_with(
self.directory, 128)
class TestPerformGitPull(unittest.TestCase):
def setUp(self):
self.directory = 'foo'
self.puller = Pulla()
@patch('pulla.pulla.get_git_version')
@patch('os.system')
def test_pull_done_silently_when_no_verbosity(self, mock_os_system_cmd,
mock_git_ver):
expected_status = 128
mock_os_system_cmd.return_value = expected_status
mock_git_ver.return_value = '2.2.2'
expected_cmd = 'git -C foo pull &> /dev/null'
status = self.puller.perform_git_pull(self.directory)
mock_os_system_cmd.assert_called_once_with(expected_cmd)
self.assertEqual(status, expected_status)
@patch('pulla.pulla.get_git_version')
@patch('os.system')
def test_pull_done_when_verbosity_level_set_one(self, mock_os_system,
mock_git_ver):
self.puller.verbosity = 1
mock_git_ver.return_value = '2.2.2'
expected_cmd = 'git -C foo pull --verbose'
self.puller.perform_git_pull(self.directory)
mock_os_system.assert_called_once_with(expected_cmd)
class TestGetFormattedMessage(unittest.TestCase):
def setUp(self):
self.directory = 'foo'
self.puller = Pulla()
def test_proper_success_message_returned(self):
out = self.puller.get_formatted_status_message(self.directory, 128)
self.assertEqual(out, 'foo \x1b[31mFail\x1b[39m')
def test_proper_fail_message_returned(self):
out = self.puller.get_formatted_status_message(self.directory, 0)
self.assertEqual(out, 'foo \x1b[32mSuccess\x1b[39m')
if __name__ == '__main__':
unittest.main()
|
vmamidi/trafficserver | refs/heads/master | tests/gold_tests/pluginTest/compress/compress.test.py | 5 | '''
'''
# 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.
Test.Summary = '''
Test compress plugin
'''
# This test case is very bare-bones. It only covers a few scenarios that have caused problems.
# Skip if plugins not present.
#
Test.SkipUnless(
Condition.PluginExists('compress.so'),
Condition.PluginExists('conf_remap.so'),
Condition.HasATSFeature('TS_HAS_BROTLI')
)
server = Test.MakeOriginServer("server", options={'--load': '{}/compress_observer.py'.format(Test.TestDirectory)})
def repeat(str, count):
result = ""
while count > 0:
result += str
count -= 1
return result
# Need a fairly big body, otherwise the plugin will refuse to compress
body = repeat("lets go surfin now everybodys learnin how\n", 24)
body = body + "lets go surfin now everybodys learnin how"
# expected response from the origin server
response_header = {
"headers": "HTTP/1.1 200 OK\r\nConnection: close\r\n" +
'Etag: "359670651"\r\n' +
"Cache-Control: public, max-age=31536000\r\n" +
"Accept-Ranges: bytes\r\n" +
"Content-Type: text/javascript\r\n" +
"\r\n",
"timestamp": "1469733493.993",
"body": body
}
for i in range(3):
# add request/response to the server dictionary
request_header = {
"headers": "GET /obj{} HTTP/1.1\r\nHost: just.any.thing\r\n\r\n".format(i), "timestamp": "1469733493.993", "body": ""
}
server.addResponse("sessionfile.log", request_header, response_header)
# post for the origin server
post_request_header = {
"headers": "POST /obj3 HTTP/1.1\r\nHost: just.any.thing\r\nContent-Type: application/x-www-form-urlencoded\r\nContent-Length: 11\r\n\r\n",
"timestamp": "1469733493.993",
"body": "knock knock"}
server.addResponse("sessionfile.log", post_request_header, response_header)
def curl(ts, idx, encodingList):
return (
"curl --verbose --proxy http://127.0.0.1:{}".format(ts.Variables.port) +
" --header 'X-Ats-Compress-Test: {}/{}'".format(idx, encodingList) +
" --header 'Accept-Encoding: {0}' 'http://ae-{1}/obj{1}'".format(encodingList, idx) +
" 2>> compress_long.log ; printf '\n===\n' >> compress_long.log"
)
def curl_post(ts, idx, encodingList):
return (
"curl --verbose -d 'knock knock' --proxy http://127.0.0.1:{}".format(ts.Variables.port) +
" --header 'X-Ats-Compress-Test: {}/{}'".format(idx, encodingList) +
" --header 'Accept-Encoding: {0}' 'http://ae-{1}/obj{1}'".format(encodingList, idx) +
" 2>> compress_long.log ; printf '\n===\n' >> compress_long.log"
)
waitForServer = True
waitForTs = True
ts = Test.MakeATSProcess("ts", enable_cache=False)
ts.Disk.records_config.update({
'proxy.config.diags.debug.enabled': 1,
'proxy.config.diags.debug.tags': 'compress',
'proxy.config.http.normalize_ae': 0,
})
ts.Setup.Copy("compress.config")
ts.Setup.Copy("compress2.config")
ts.Disk.remap_config.AddLine(
'map http://ae-0/ http://127.0.0.1:{}/'.format(server.Variables.Port) +
' @plugin=compress.so @pparam={}/compress.config'.format(Test.RunDirectory)
)
ts.Disk.remap_config.AddLine(
'map http://ae-1/ http://127.0.0.1:{}/'.format(server.Variables.Port) +
' @plugin=conf_remap.so @pparam=proxy.config.http.normalize_ae=1' +
' @plugin=compress.so @pparam={}/compress.config'.format(Test.RunDirectory)
)
ts.Disk.remap_config.AddLine(
'map http://ae-2/ http://127.0.0.1:{}/'.format(server.Variables.Port) +
' @plugin=conf_remap.so @pparam=proxy.config.http.normalize_ae=2' +
' @plugin=compress.so @pparam={}/compress2.config'.format(Test.RunDirectory)
)
ts.Disk.remap_config.AddLine(
'map http://ae-3/ http://127.0.0.1:{}/'.format(server.Variables.Port) +
' @plugin=compress.so @pparam={}/compress.config'.format(Test.RunDirectory)
)
for i in range(3):
tr = Test.AddTestRun()
if (waitForTs):
tr.Processes.Default.StartBefore(ts)
waitForTs = False
if (waitForServer):
tr.Processes.Default.StartBefore(server, ready=When.PortOpen(server.Variables.Port))
waitForServer = False
tr.Processes.Default.ReturnCode = 0
tr.Processes.Default.Command = curl(ts, i, 'gzip, deflate, sdch, br')
tr = Test.AddTestRun()
tr.Processes.Default.ReturnCode = 0
tr.Processes.Default.Command = curl(ts, i, "gzip")
tr = Test.AddTestRun()
tr.Processes.Default.ReturnCode = 0
tr.Processes.Default.Command = curl(ts, i, "br")
tr = Test.AddTestRun()
tr.Processes.Default.ReturnCode = 0
tr.Processes.Default.Command = curl(ts, i, "deflate")
# Test Accept-Encoding normalization.
tr = Test.AddTestRun()
tr.Processes.Default.ReturnCode = 0
tr.Processes.Default.Command = curl(ts, 0, "gzip;q=0.666")
tr = Test.AddTestRun()
tr.Processes.Default.ReturnCode = 0
tr.Processes.Default.Command = curl(ts, 0, "gzip;q=0.666x")
tr = Test.AddTestRun()
tr.Processes.Default.ReturnCode = 0
tr.Processes.Default.Command = curl(ts, 0, "gzip;q=#0.666")
tr = Test.AddTestRun()
tr.Processes.Default.ReturnCode = 0
tr.Processes.Default.Command = curl(ts, 0, "gzip; Q = 0.666")
tr = Test.AddTestRun()
tr.Processes.Default.ReturnCode = 0
tr.Processes.Default.Command = curl(ts, 0, "gzip;q=0.0")
tr = Test.AddTestRun()
tr.Processes.Default.ReturnCode = 0
tr.Processes.Default.Command = curl(ts, 0, "gzip;q=-0.1")
tr = Test.AddTestRun()
tr.Processes.Default.ReturnCode = 0
tr.Processes.Default.Command = curl(ts, 0, "aaa, gzip;q=0.666, bbb")
tr = Test.AddTestRun()
tr.Processes.Default.ReturnCode = 0
tr.Processes.Default.Command = curl(ts, 0, " br ; q=0.666, bbb")
tr = Test.AddTestRun()
tr.Processes.Default.ReturnCode = 0
tr.Processes.Default.Command = curl(ts, 0, "aaa, gzip;q=0.666 , ")
# post
tr = Test.AddTestRun()
tr.Processes.Default.ReturnCode = 0
tr.Processes.Default.Command = curl_post(ts, 3, "gzip")
# compress_long.log contains all the output from the curl commands. The tr removes the carriage returns for easier
# readability. Curl seems to have a bug, where it will neglect to output an end of line before outputing an HTTP
# message header line. The sed command is a work-around for this problem. greplog.sh uses the grep command to
# select HTTP request/response line that should be consistent every time the test runs.
#
tr = Test.AddTestRun()
tr.Processes.Default.ReturnCode = 0
tr.Processes.Default.Command = (
r"tr -d '\r' < compress_long.log | sed 's/\(..*\)\([<>]\)/\1\n\2/' | {0}/greplog.sh > compress_short.log"
).format(Test.TestDirectory)
f = tr.Disk.File("compress_short.log")
f.Content = "compress.gold"
tr = Test.AddTestRun()
tr.Processes.Default.Command = "echo"
f = tr.Disk.File("compress_userver.log")
f.Content = "compress_userver.gold"
|
page-io/Cactus | refs/heads/master | cactus/tests/test_ignore.py | 14 | #coding:utf-8
import os
from cactus.tests import SiteTestCase
class TestIgnore(SiteTestCase):
def test_ignore_static(self):
with open(os.path.join(self.site.static_path, "koen.psd"), "w") as f:
f.write("Not really a psd")
with open(os.path.join(self.site.static_path, "koen.gif"), "w") as f:
f.write("Not really a gif")
self.site.config.set("ignore", ["*.psd"])
self.site.build()
self.assertFileDoesNotExist(os.path.join(self.site.build_path, "static", "koen.psd"))
self.assertFileExists(os.path.join(self.site.build_path, "static", "koen.gif"))
def test_ignore_pages(self):
with open(os.path.join(self.site.page_path, "page.html.swp"), "w") as f:
f.write("Not really a swap file")
with open(os.path.join(self.site.page_path, "page.txt"), "w") as f:
f.write("Actually a text file")
self.site.config.set("ignore", ["*.swp"])
self.site.build()
self.assertFileDoesNotExist(os.path.join(self.site.build_path, "page.html.swp"))
self.assertFileExists(os.path.join(self.site.build_path, "page.txt"))
|
aliaksandrb/anydo_api | refs/heads/master | tests/test_constants.py | 1 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
test_constants
----------------------------------
Tests for `Constants` module.
Checks if all the required constants are set in one place
"""
import unittest
import anydo_api.constants as constants
class TestConstants(unittest.TestCase):
def setUp(self):
self.consts = constants
def tearDown(self):
del self.consts
def test_all_constants_defined(self):
self.assertTrue(hasattr(self.consts, 'SERVER_API_URL'))
self.assertTrue(hasattr(self.consts, 'CONSTANTS'))
self.assertTrue(hasattr(self.consts, 'TASK_STATUSES'))
c_dict = self.consts.CONSTANTS
self.assertTrue(c_dict.get('SERVER_API_URL'))
self.assertTrue(c_dict.get('LOGIN_URL'))
self.assertTrue(c_dict.get('ME_URL'))
self.assertTrue(c_dict.get('USER_URL'))
self.assertTrue(c_dict.get('TASKS_URL'))
self.assertTrue(c_dict.get('CATEGORIES_URL'))
if __name__ == '__main__':
import sys
sys.exit(unittest.main())
|
froch/kubernetes-py | refs/heads/master | kubernetes_py/models/v1beta1/CronJob.py | 3 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# This file is subject to the terms and conditions defined in
# file 'LICENSE.md', which is part of this source code package.
#
from kubernetes_py.models.unversioned.BaseModel import BaseModel
from kubernetes_py.models.v1beta1.CronJobSpec import CronJobSpec
from kubernetes_py.models.v1beta1.CronJobStatus import CronJobStatus
class CronJob(BaseModel):
"""
http://kubernetes.io/docs/user-guide/cron-jobs/#creating-a-cron-job
"""
def __init__(self, model=None):
super(CronJob, self).__init__()
self.kind = "CronJob"
self.api_version = "batch/v1beta1"
self.spec = CronJobSpec()
self.status = CronJobStatus()
if model is not None:
self._build_with_model(model)
def _build_with_model(self, model=None):
super(CronJob, self).build_with_model(model)
if "spec" in model:
self.spec = CronJobSpec(model["spec"])
if "status" in model:
self.status = CronJobStatus(model["status"])
# ------------------------------------------------------------------------------------- spec
@property
def spec(self):
return self._spec
@spec.setter
def spec(self, spec=None):
if not isinstance(spec, CronJobSpec):
raise SyntaxError("CronJob: spec: [ {} ] is invalid.".format(spec))
self._spec = spec
# ------------------------------------------------------------------------------------- status
@property
def status(self):
return self._status
@status.setter
def status(self, status=None):
if not isinstance(status, CronJobStatus):
raise SyntaxError("CronJob: status: [ {} ] is invalid.".format(status))
self._status = status
# ------------------------------------------------------------------------------------- serialize
def serialize(self):
data = super(CronJob, self).serialize()
if self.spec is not None:
data["spec"] = self.spec.serialize()
if self.status is not None:
data["status"] = self.status.serialize()
return data
|
dims/test-infra | refs/heads/master | gubernator/__init__.py | 12133432 | |
adoosii/edx-platform | refs/heads/master | lms/djangoapps/dashboard/tests/__init__.py | 12133432 | |
harisibrahimkv/django | refs/heads/master | django/core/handlers/__init__.py | 12133432 | |
Gr1ph00n/staticwebanalyzer | refs/heads/master | SDK/mechanize-0.2.5/test-tools/twisted-ftpserver.py | 22 | import optparse
import sys
import twisted.cred.checkers
import twisted.cred.credentials
import twisted.cred.portal
import twisted.internet
import twisted.protocols.ftp
from twisted.python import filepath, log
from zope.interface import implements
def make_ftp_shell(avatar_id, root_path):
if avatar_id is twisted.cred.checkers.ANONYMOUS:
return twisted.protocols.ftp.FTPAnonymousShell(root_path)
else:
return twisted.protocols.ftp.FTPShell(root_path)
class FTPRealm(object):
implements(twisted.cred.portal.IRealm)
def __init__(self, root_path):
self._root_path = filepath.FilePath(root_path)
def requestAvatar(self, avatarId, mind, *interfaces):
for iface in interfaces:
if iface is twisted.protocols.ftp.IFTPShell:
avatar = make_ftp_shell(avatarId, self._root_path)
return (twisted.protocols.ftp.IFTPShell,
avatar,
getattr(avatar, "logout", lambda: None))
raise NotImplementedError()
class FtpServerFactory(object):
"""
port = FtpServerFactory("/tmp", 2121).makeListner()
self.addCleanup(port.stopListening)
"""
def __init__(self, root_path, port):
factory = twisted.protocols.ftp.FTPFactory()
realm = FTPRealm(root_path)
portal = twisted.cred.portal.Portal(realm)
portal.registerChecker(twisted.cred.checkers.AllowAnonymousAccess(),
twisted.cred.credentials.IAnonymous)
checker = twisted.cred.checkers.\
InMemoryUsernamePasswordDatabaseDontUse()
checker.addUser("john", "john")
portal.registerChecker(checker)
factory.tld = root_path
factory.userAnonymous = "anon"
factory.portal = portal
factory.protocol = twisted.protocols.ftp.FTP
self._factory = factory
self._port = port
def makeListener(self):
# XXX use 0 instead of self._port?
return twisted.internet.reactor.listenTCP(
self._port, self._factory, interface="127.0.0.1")
def parse_options(args):
parser = optparse.OptionParser()
parser.add_option("--log", action="store_true")
parser.add_option("--port", type="int", default=2121)
options, remaining_args = parser.parse_args(args)
options.root_path = remaining_args[0]
return options
def main(argv):
options = parse_options(argv[1:])
if options.log:
log.startLogging(sys.stdout)
factory = FtpServerFactory(options.root_path, options.port)
factory.makeListener()
twisted.internet.reactor.run()
if __name__ == "__main__":
main(sys.argv)
|
veegee/amqpy | refs/heads/master | amqpy/__init__.py | 1 | from __future__ import absolute_import, division, print_function
__metaclass__ = type
VERSION = (0, 13, 1)
__version__ = '.'.join(map(str, VERSION[0:3])) + ''.join(VERSION[3:])
__author__ = 'veegee'
__maintainer__ = 'veegee'
__contact__ = 'veegee@veegee.org'
__homepage__ = 'http://github.com/veegee/amqpy'
__docformat__ = 'restructuredtext'
from .connection import Connection
from .channel import Channel
from .message import Message
from .consumer import AbstractConsumer
from .spec import basic_return_t, queue_declare_ok_t, method_t
from .exceptions import (
Timeout,
AMQPError,
AMQPConnectionError,
RecoverableConnectionError,
IrrecoverableConnectionError,
ChannelError,
RecoverableChannelError,
IrrecoverableChannelError,
ConsumerCancelled,
ContentTooLarge,
NoConsumers,
ConnectionForced,
InvalidPath,
AccessRefused,
NotFound,
ResourceLocked,
PreconditionFailed,
FrameError,
FrameSyntaxError,
InvalidCommand,
ChannelNotOpen,
UnexpectedFrame,
ResourceError,
NotAllowed,
AMQPNotImplementedError,
InternalError,
error_for_code,
__all__ as _all_exceptions,
)
__all__ = ['Connection', 'Channel', 'Message', 'AbstractConsumer',
'basic_return_t', 'queue_declare_ok_t', 'method_t'] + _all_exceptions
|
kun--hust/libcloud_with_cn | refs/heads/development | libcloud/test/loadbalancer/__init__.py | 2443 | # 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.
|
navcat/wechatpy | refs/heads/master | wechatpy/client/api/material.py | 4 | # -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
from wechatpy._compat import json
from wechatpy.client.api.base import BaseWeChatAPI
class WeChatMaterial(BaseWeChatAPI):
def add_articles(self, articles):
"""
新增永久图文素材
详情请参考
http://mp.weixin.qq.com/wiki/14/7e6c03263063f4813141c3e17dd4350a.html
:param articles: 图文素材数组
:return: 返回的 JSON 数据包
"""
articles_data = []
for article in articles:
articles_data.append({
'thumb_media_id': article['thumb_media_id'],
'title': article['title'],
'content': article['content'],
'author': article.get('author', ''),
'content_source_url': article.get('content_source_url', ''),
'digest': article.get('digest', ''),
'show_cover_pic': article.get('show_cover_pic', 0)
})
return self._post(
'material/add_news',
data={
'articles': articles_data
}
)
def add(self, media_type, media_file, title=None, introduction=None):
"""
新增其它类型永久素材
详情请参考
http://mp.weixin.qq.com/wiki/14/7e6c03263063f4813141c3e17dd4350a.html
:param media_type: 媒体文件类型,分别有图片(image)、语音(voice)、视频(video)和缩略图(thumb)
:param media_file: 要上传的文件,一个 File-object
:param title: 视频素材标题,仅上传视频素材时需要
:param introduction: 视频素材简介,仅上传视频素材时需要
:return: 返回的 JSON 数据包
"""
params = {
'access_token': self.access_token,
'type': media_type
}
if media_type == 'video':
assert title, 'Video title must be set'
assert introduction, 'Video introduction must be set'
description = {
'title': title,
'introduction': introduction
}
params['description'] = json.dumps(description)
return self._post(
url='http://file.api.weixin.qq.com/cgi-bin/material/add_material',
params=params,
files={
'media': media_file
}
)
def get(self, media_id):
"""
获取永久素材
详情请参考
http://mp.weixin.qq.com/wiki/4/b3546879f07623cb30df9ca0e420a5d0.html
:param media_id: 素材的 media_id
:return: 图文素材返回图文列表,其它类型为素材的内容
"""
res = self._post(
url='https://api.weixin.qq.com/cgi-bin/material/get_material',
data={
'media_id': media_id
}
)
if isinstance(res, dict):
# 图文素材
return res.get('news_item', [])
return res
def delete(self, media_id):
"""
删除永久素材
详情请参考
http://mp.weixin.qq.com/wiki/5/e66f61c303db51a6c0f90f46b15af5f5.html
:param media_id: 素材的 media_id
:return: 返回的 JSON 数据包
"""
return self._post(
'material/del_material',
data={
'media_id': media_id
}
)
def update_articles(self, media_id, index, articles):
"""
修改永久图文素材
详情请参考
http://mp.weixin.qq.com/wiki/4/19a59cba020d506e767360ca1be29450.html
:param media_id: 要修改的图文消息的 id
:param index: 要更新的文章在图文消息中的位置(多图文消息时,此字段才有意义),第一篇为 0
:param articles: 图文素材数组
:return: 返回的 JSON 数据包
"""
articles_data = []
for article in articles:
articles_data.append({
'thumb_media_id': article['thumb_media_id'],
'title': article['title'],
'content': article['content'],
'author': article.get('author', ''),
'content_source_url': article.get('content_source_url', ''),
'digest': article.get('digest', ''),
'show_cover_pic': article.get('show_cover_pic', 0)
})
return self._post(
'material/update_news',
data={
'media_id': media_id,
'index': index,
'articles': articles_data
}
)
def batchget(self, media_type, offset=0, count=20):
"""
批量获取永久素材列表
详情请参考
http://mp.weixin.qq.com/wiki/12/2108cd7aafff7f388f41f37efa710204.html
:param media_type: 媒体文件类型,分别有图片(image)、语音(voice)、视频(video)和缩略图(news)
:param offset: 从全部素材的该偏移位置开始返回,0 表示从第一个素材返回
:param count: 返回素材的数量,取值在1到20之间
:return: 返回的 JSON 数据包
"""
return self._post(
'material/batchget_material',
data={
'type': media_type,
'offset': offset,
'count': count
}
)
def get_count(self):
"""
获取素材总数
详情请参考
http://mp.weixin.qq.com/wiki/16/8cc64f8c189674b421bee3ed403993b8.html
:return: 返回的 JSON 数据包
"""
return self._get('material/get_materialcount')
|
ennoborg/gramps | refs/heads/master | gramps/plugins/view/fanchartdescview.py | 3 | # Gramps - a GTK+/GNOME based genealogy program
#
# Copyright (C) 2001-2007 Donald N. Allingham, Martin Hawlisch
# Copyright (C) 2009 Douglas S. Blank
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
## Based on the paper:
## http://www.cs.utah.edu/~draperg/research/fanchart/draperg_FHT08.pdf
## and the applet:
## http://www.cs.utah.edu/~draperg/research/fanchart/demo/
## Found by redwood:
## http://www.gramps-project.org/bugs/view.php?id=2611
#-------------------------------------------------------------------------
#
# Python modules
#
#-------------------------------------------------------------------------
from gi.repository import Gdk
from gi.repository import Gtk
import cairo
from gramps.gen.const import GRAMPS_LOCALE as glocale
_ = glocale.translation.gettext
#-------------------------------------------------------------------------
#
# Gramps modules
#
#-------------------------------------------------------------------------
import gramps.gui.widgets.fanchart as fanchart
import gramps.gui.widgets.fanchartdesc as fanchartdesc
from gramps.gui.views.navigationview import NavigationView
from gramps.gui.views.bookmarks import PersonBookmarks
from gramps.gui.utils import SystemFonts
# the print settings to remember between print sessions
PRINT_SETTINGS = None
class FanChartDescView(fanchartdesc.FanChartDescGrampsGUI, NavigationView):
"""
The Gramplet code that realizes the FanChartWidget.
"""
#settings in the config file
CONFIGSETTINGS = (
('interface.fanview-maxgen', 9),
('interface.fanview-background', fanchart.BACKGROUND_GRAD_GEN),
('interface.fanview-radialtext', True),
('interface.fanview-twolinename', True),
('interface.fanview-flipupsidedownname', True),
('interface.fanview-font', 'Sans'),
('interface.fanview-form', fanchart.FORM_CIRCLE),
('interface.color-start-grad', '#ef2929'),
('interface.color-end-grad', '#3d37e9'),
('interface.angle-algorithm', fanchartdesc.ANGLE_WEIGHT),
('interface.duplicate-color', '#888a85')
)
def __init__(self, pdata, dbstate, uistate, nav_group=0):
self.dbstate = dbstate
self.uistate = uistate
NavigationView.__init__(self, _('Descendant Fan Chart'),
pdata, dbstate, uistate,
PersonBookmarks,
nav_group)
fanchartdesc.FanChartDescGrampsGUI.__init__(self, self.on_childmenu_changed)
#set needed values
self.maxgen = self._config.get('interface.fanview-maxgen')
self.background = self._config.get('interface.fanview-background')
self.radialtext = self._config.get('interface.fanview-radialtext')
self.twolinename = self._config.get('interface.fanview-twolinename')
self.flipupsidedownname = self._config.get('interface.fanview-flipupsidedownname')
self.fonttype = self._config.get('interface.fanview-font')
self.grad_start = self._config.get('interface.color-start-grad')
self.grad_end = self._config.get('interface.color-end-grad')
self.form = self._config.get('interface.fanview-form')
self.angle_algo = self._config.get('interface.angle-algorithm')
self.dupcolor = self._config.get('interface.duplicate-color')
self.generic_filter = None
self.alpha_filter = 0.2
dbstate.connect('active-changed', self.active_changed)
dbstate.connect('database-changed', self.change_db)
self.additional_uis.append(self.additional_ui())
self.allfonts = [x for x in enumerate(SystemFonts().get_system_fonts())]
self.func_list.update({
'<PRIMARY>J' : self.jump,
})
def navigation_type(self):
return 'Person'
def get_handle_from_gramps_id(self, gid):
"""
returns the handle of the specified object
"""
obj = self.dbstate.db.get_person_from_gramps_id(gid)
if obj:
return obj.get_handle()
else:
return None
def build_widget(self):
self.set_fan(fanchartdesc.FanChartDescWidget(self.dbstate, self.uistate,
self.on_popup))
self.scrolledwindow = Gtk.ScrolledWindow(hadjustment=None,
vadjustment=None)
self.scrolledwindow.set_policy(Gtk.PolicyType.AUTOMATIC,
Gtk.PolicyType.AUTOMATIC)
self.fan.show_all()
self.scrolledwindow.add(self.fan)
return self.scrolledwindow
def get_stock(self):
"""
The category stock icon
"""
return 'gramps-pedigree'
def get_viewtype_stock(self):
"""Type of view in category
"""
return 'gramps-fanchart'
def additional_ui(self):
return '''<ui>
<menubar name="MenuBar">
<menu action="GoMenu">
<placeholder name="CommonGo">
<menuitem action="Back"/>
<menuitem action="Forward"/>
<separator/>
<menuitem action="HomePerson"/>
<separator/>
</placeholder>
</menu>
<menu action="EditMenu">
<placeholder name="CommonEdit">
<menuitem action="PrintView"/>
</placeholder>
</menu>
<menu action="BookMenu">
<placeholder name="AddEditBook">
<menuitem action="AddBook"/>
<menuitem action="EditBook"/>
</placeholder>
</menu>
</menubar>
<toolbar name="ToolBar">
<placeholder name="CommonNavigation">
<toolitem action="Back"/>
<toolitem action="Forward"/>
<toolitem action="HomePerson"/>
</placeholder>
<placeholder name="CommonEdit">
<toolitem action="PrintView"/>
</placeholder>
</toolbar>
</ui>
'''
def define_actions(self):
"""
Required define_actions function for PageView. Builds the action
group information required.
"""
NavigationView.define_actions(self)
self._add_action('PrintView', 'document-print', _("_Print..."),
accel="<PRIMARY>P",
tip=_("Print or save the Fan Chart View"),
callback=self.printview)
def build_tree(self):
"""
Generic method called by PageView to construct the view.
Here the tree builds when active person changes or db changes or on
callbacks like person_rebuild, so build will be double sometimes.
However, change in generic filter also triggers build_tree ! So we
need to reset.
"""
self.update()
def active_changed(self, handle):
"""
Method called when active person changes.
"""
# Reset everything but rotation angle (leave it as is)
self.update()
def _connect_db_signals(self):
"""
Connect database signals.
"""
self._add_db_signal('person-add', self.person_rebuild)
self._add_db_signal('person-update', self.person_rebuild)
self._add_db_signal('person-delete', self.person_rebuild)
self._add_db_signal('person-rebuild', self.person_rebuild_bm)
self._add_db_signal('family-update', self.person_rebuild)
self._add_db_signal('family-add', self.person_rebuild)
self._add_db_signal('family-delete', self.person_rebuild)
self._add_db_signal('family-rebuild', self.person_rebuild)
def change_db(self, db):
self._change_db(db)
if self.active:
self.bookmarks.redraw()
self.update()
def update(self):
self.main()
def goto_handle(self, handle):
self.change_active(handle)
self.main()
def get_active(self, object):
"""overrule get_active, to support call as in Gramplets
"""
return NavigationView.get_active(self)
def person_rebuild(self, *args):
self.update()
def person_rebuild_bm(self, *args):
"""Large change to person database"""
self.person_rebuild()
if self.active:
self.bookmarks.redraw()
def printview(self, obj):
"""
Print or save the view that is currently shown
"""
widthpx = 2 * self.fan.halfdist()
heightpx = widthpx
if self.form == fanchart.FORM_HALFCIRCLE:
heightpx = heightpx / 2 + self.fan.CENTER + fanchart.PAD_PX
elif self.form == fanchart.FORM_QUADRANT:
heightpx = heightpx / 2 + self.fan.CENTER + fanchart.PAD_PX
widthpx = heightpx
prt = CairoPrintSave(widthpx, heightpx, self.fan.on_draw, self.uistate.window)
prt.run()
def on_childmenu_changed(self, obj, person_handle):
"""Callback for the pulldown menu selection, changing to the person
attached with menu item."""
self.change_active(person_handle)
return True
def can_configure(self):
"""
See :class:`~gui.views.pageview.PageView
:return: bool
"""
return True
def _get_configure_page_funcs(self):
"""
Return a list of functions that create gtk elements to use in the
notebook pages of the Configure dialog
:return: list of functions
"""
return [self.config_panel]
def config_panel(self, configdialog):
"""
Function that builds the widget in the configuration dialog
"""
nrentry = 9
grid = Gtk.Grid()
grid.set_border_width(12)
grid.set_column_spacing(6)
grid.set_row_spacing(6)
configdialog.add_spinner(grid, _("Max generations"), 0,
'interface.fanview-maxgen', (2, 16),
callback=self.cb_update_maxgen)
configdialog.add_combo(grid,
_('Text Font'),
1, 'interface.fanview-font',
self.allfonts, callback=self.cb_update_font, valueactive=True)
backgrvals = (
(fanchart.BACKGROUND_GENDER, _('Gender colors')),
(fanchart.BACKGROUND_GRAD_GEN, _('Generation based gradient')),
(fanchart.BACKGROUND_GRAD_AGE, _('Age (0-100) based gradient')),
(fanchart.BACKGROUND_SINGLE_COLOR,
_('Single main (filter) color')),
(fanchart.BACKGROUND_GRAD_PERIOD, _('Time period based gradient')),
(fanchart.BACKGROUND_WHITE, _('White')),
(fanchart.BACKGROUND_SCHEME1, _('Color scheme classic report')),
(fanchart.BACKGROUND_SCHEME2, _('Color scheme classic view')),
)
curval = self._config.get('interface.fanview-background')
nrval = 0
for nr, val in backgrvals:
if curval == nr:
break
nrval += 1
configdialog.add_combo(grid,
_('Background'),
2, 'interface.fanview-background',
backgrvals,
callback=self.cb_update_background, valueactive=False,
setactive=nrval
)
#colors, stored as hex values
configdialog.add_color(grid, _('Start gradient/Main color'), 3,
'interface.color-start-grad', col=1)
configdialog.add_color(grid, _('End gradient/2nd color'), 4,
'interface.color-end-grad', col=1)
configdialog.add_color(grid, _('Color for duplicates'), 5,
'interface.duplicate-color', col=1)
# form of the fan
configdialog.add_combo(grid, _('Fan chart type'), 6,
'interface.fanview-form',
((fanchart.FORM_CIRCLE, _('Full Circle')),
(fanchart.FORM_HALFCIRCLE, _('Half Circle')),
(fanchart.FORM_QUADRANT, _('Quadrant'))),
callback=self.cb_update_form)
# algo for the fan angle distribution
configdialog.add_combo(grid, _('Fan chart distribution'), 7,
'interface.angle-algorithm',
((fanchartdesc.ANGLE_CHEQUI,
_('Homogeneous children distribution')),
(fanchartdesc.ANGLE_WEIGHT,
_('Size proportional to number of descendants')),
),
callback=self.cb_update_anglealgo)
# show names one two line
configdialog.add_checkbox(grid,
_('Show names on two lines'),
8, 'interface.fanview-twolinename')
# Flip names
configdialog.add_checkbox(grid,
_('Flip name on the left of the fan'),
9, 'interface.fanview-flipupsidedownname')
return _('Layout'), grid
def config_connect(self):
"""
Overwriten from :class:`~gui.views.pageview.PageView method
This method will be called after the ini file is initialized,
use it to monitor changes in the ini file
"""
self._config.connect('interface.color-start-grad',
self.cb_update_color)
self._config.connect('interface.color-end-grad',
self.cb_update_color)
self._config.connect('interface.duplicate-color',
self.cb_update_color)
self._config.connect('interface.fanview-flipupsidedownname',
self.cb_update_flipupsidedownname)
self._config.connect('interface.fanview-twolinename',
self.cb_update_twolinename)
def cb_update_maxgen(self, spinbtn, constant):
self.maxgen = spinbtn.get_value_as_int()
self._config.set(constant, self.maxgen)
self.update()
def cb_update_twolinename(self, client, cnxn_id, entry, data):
"""
Called when the configuration menu changes the twolinename setting.
"""
self.twolinename = (entry == 'True')
self.update()
def cb_update_background(self, obj, constant):
entry = obj.get_active()
Gtk.TreePath.new_from_string('%d' % entry)
val = int(obj.get_model().get_value(
obj.get_model().get_iter_from_string('%d' % entry), 0))
self._config.set(constant, val)
self.background = val
self.update()
def cb_update_form(self, obj, constant):
entry = obj.get_active()
self._config.set(constant, entry)
self.form = entry
self.update()
def cb_update_anglealgo(self, obj, constant):
entry = obj.get_active()
self._config.set(constant, entry)
self.angle_algo = entry
self.update()
def cb_update_color(self, client, cnxn_id, entry, data):
"""
Called when the configuration menu changes the childrenring setting.
"""
self.grad_start = self._config.get('interface.color-start-grad')
self.grad_end = self._config.get('interface.color-end-grad')
self.dupcolor = self._config.get('interface.duplicate-color')
self.update()
def cb_update_flipupsidedownname(self, client, cnxn_id, entry, data):
"""
Called when the configuration menu changes the flipupsidedownname setting.
"""
self.flipupsidedownname = (entry == 'True')
self.update()
def cb_update_font(self, obj, constant):
entry = obj.get_active()
self._config.set(constant, self.allfonts[entry][1])
self.fonttype = self.allfonts[entry][1]
self.update()
def get_default_gramplets(self):
"""
Define the default gramplets for the sidebar and bottombar.
"""
return (("Person Filter",),
())
#------------------------------------------------------------------------
#
# CairoPrintSave class
#
#------------------------------------------------------------------------
class CairoPrintSave:
"""Act as an abstract document that can render onto a cairo context.
It can render the model onto cairo context pages, according to the received
page style.
"""
def __init__(self, widthpx, heightpx, drawfunc, parent):
"""
This class provides the things needed so as to dump a cairo drawing on
a context to output
"""
self.widthpx = widthpx
self.heightpx = heightpx
self.drawfunc = drawfunc
self.parent = parent
def run(self):
"""Create the physical output from the meta document.
"""
global PRINT_SETTINGS
# set up a print operation
operation = Gtk.PrintOperation()
operation.connect("draw_page", self.on_draw_page)
operation.connect("preview", self.on_preview)
operation.connect("paginate", self.on_paginate)
operation.set_n_pages(1)
#paper_size = Gtk.PaperSize.new(name="iso_a4")
## WHY no Gtk.Unit.PIXEL ?? Is there a better way to convert
## Pixels to MM ??
paper_size = Gtk.PaperSize.new_custom("custom",
"Custom Size",
round(self.widthpx * 0.2646),
round(self.heightpx * 0.2646),
Gtk.Unit.MM)
page_setup = Gtk.PageSetup()
page_setup.set_paper_size(paper_size)
#page_setup.set_orientation(Gtk.PageOrientation.PORTRAIT)
operation.set_default_page_setup(page_setup)
#operation.set_use_full_page(True)
if PRINT_SETTINGS is not None:
operation.set_print_settings(PRINT_SETTINGS)
# run print dialog
while True:
self.preview = None
res = operation.run(Gtk.PrintOperationAction.PRINT_DIALOG, self.parent)
if self.preview is None: # cancel or print
break
# set up printing again; can't reuse PrintOperation?
operation = Gtk.PrintOperation()
operation.set_default_page_setup(page_setup)
operation.connect("draw_page", self.on_draw_page)
operation.connect("preview", self.on_preview)
operation.connect("paginate", self.on_paginate)
# set print settings if it was stored previously
if PRINT_SETTINGS is not None:
operation.set_print_settings(PRINT_SETTINGS)
# store print settings if printing was successful
if res == Gtk.PrintOperationResult.APPLY:
PRINT_SETTINGS = operation.get_print_settings()
def on_draw_page(self, operation, context, page_nr):
"""Draw a page on a Cairo context.
"""
cr = context.get_cairo_context()
pxwidth = round(context.get_width())
pxheight = round(context.get_height())
scale = min(pxwidth/self.widthpx, pxheight/self.heightpx)
if scale > 1:
scale = 1
self.drawfunc(None, cr, scale=scale)
def on_paginate(self, operation, context):
"""Paginate the whole document in chunks.
We don't need this as there is only one page, however,
we provide a dummy holder here, because on_preview crashes if no
default application is set with gir 3.3.2 (typically evince not installed)!
It will provide the start of the preview dialog, which cannot be
started in on_preview
"""
finished = True
# update page number
operation.set_n_pages(1)
# start preview if needed
if self.preview:
self.preview.run()
return finished
def on_preview(self, operation, preview, context, parent):
"""Implement custom print preview functionality.
We provide a dummy holder here, because on_preview crashes if no
default application is set with gir 3.3.2 (typically evince not installed)!
"""
dlg = Gtk.MessageDialog(parent,
flags=Gtk.DialogFlags.MODAL,
type=Gtk.MessageType.WARNING,
buttons=Gtk.ButtonsType.CLOSE,
message_format=_('No preview available'))
self.preview = dlg
self.previewopr = operation
#dlg.format_secondary_markup(msg2)
dlg.set_title("Fan Chart Preview - Gramps")
dlg.connect('response', self.previewdestroy)
# give a dummy cairo context to Gtk.PrintContext,
try:
width = int(round(context.get_width()))
except ValueError:
width = 0
try:
height = int(round(context.get_height()))
except ValueError:
height = 0
surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, width, height)
cr = cairo.Context(surface)
context.set_cairo_context(cr, 72.0, 72.0)
return True
def previewdestroy(self, dlg, res):
self.preview.destroy()
self.previewopr.end_preview()
|
BuildingLink/sentry | refs/heads/master | src/sentry/api/endpoints/project_stats.py | 6 | from __future__ import absolute_import
from rest_framework.response import Response
from sentry.app import tsdb
from sentry.api.base import DocSection, StatsMixin
from sentry.api.bases.project import ProjectEndpoint
from sentry.utils.apidocs import scenario, attach_scenarios
@scenario('RetrieveEventCountsProjcet')
def retrieve_event_counts_project(runner):
runner.request(
method='GET',
path='/projects/%s/%s/stats/' % (
runner.org.slug, runner.default_project.slug)
)
class ProjectStatsEndpoint(ProjectEndpoint, StatsMixin):
doc_section = DocSection.PROJECTS
@attach_scenarios([retrieve_event_counts_project])
def get(self, request, project):
"""
Retrieve Event Counts for a Project
```````````````````````````````````
.. caution::
This endpoint may change in the future without notice.
Return a set of points representing a normalized timestamp and the
number of events seen in the period.
Query ranges are limited to Sentry's configured time-series
resolutions.
:pparam string organization_slug: the slug of the organization.
:pparam string project_slug: the slug of the project.
:qparam string stat: the name of the stat to query (``"received"``,
``"rejected"``, ``"blacklisted"``, ``generated``)
:qparam timestamp since: a timestamp to set the start of the query
in seconds since UNIX epoch.
:qparam timestamp until: a timestamp to set the end of the query
in seconds since UNIX epoch.
:qparam string resolution: an explicit resolution to search
for (eg: ``10s``). This should not be
used unless you are familiar with Sentry's
internals as it's restricted to pre-defined
values.
:auth: required
"""
stat = request.GET.get('stat', 'received')
if stat == 'received':
stat_model = tsdb.models.project_total_received
elif stat == 'rejected':
stat_model = tsdb.models.project_total_rejected
elif stat == 'blacklisted':
stat_model = tsdb.models.project_total_blacklisted
elif stat == 'generated':
stat_model = tsdb.models.project
else:
raise ValueError('Invalid stat: %s' % stat)
data = tsdb.get_range(
model=stat_model,
keys=[project.id],
**self._parse_args(request)
)[project.id]
return Response(data)
|
ollie314/browserscope | refs/heads/master | bin/reflow/__init__.py | 12133432 | |
RRCKI/panda-jedi | refs/heads/master | pandajedi/jedisetup/__init__.py | 12133432 | |
DukeOfHazard/crits | refs/heads/master | crits/backdoors/backdoor.py | 11 | from mongoengine import Document, StringField, ListField
from django.conf import settings
from crits.core.crits_mongoengine import CritsBaseAttributes, CritsSourceDocument
class Backdoor(CritsBaseAttributes, CritsSourceDocument, Document):
"""
Backdoor class.
"""
meta = {
"collection": settings.COL_BACKDOORS,
"crits_type": 'Backdoor',
"latest_schema_version": 1,
"schema_doc": {
},
"jtable_opts": {
'details_url': 'crits.backdoors.views.backdoor_detail',
'details_url_key': 'id',
'default_sort': "modified DESC",
'searchurl': 'crits.backdoors.views.backdoors_listing',
'fields': ["name", "version", "description", "modified", "source",
"campaign", "status", "id"],
'jtopts_fields': ["details", "name", "version", "description",
"modified", "source", "campaign", "status",
"favorite", "id"],
'hidden_fields': [],
'linked_fields': ["source", "campaign"],
'details_link': 'details',
'no_sort': ['details'],
}
}
name = StringField(required=True)
aliases = ListField(StringField())
version = StringField()
def migrate(self):
pass
# XXX: Identical to Actor.update_aliases()
def update_aliases(self, aliases):
"""
Update the aliases on an Backdoor.
:param aliases: The aliases we are setting.
:type aliases: list
"""
if isinstance(aliases, basestring):
aliases = aliases.split(',')
aliases = [a.strip() for a in aliases if a != '']
existing_aliases = None
if len(aliases) < len(self.aliases):
self.aliases = aliases
else:
existing_aliases = self.aliases
if existing_aliases is not None:
for a in aliases:
if a not in existing_aliases:
existing_aliases.append(a)
|
dkdewitt/werkzeug | refs/heads/master | examples/shorty/application.py | 44 | from sqlalchemy import create_engine
from werkzeug.wrappers import Request
from werkzeug.wsgi import ClosingIterator, SharedDataMiddleware
from werkzeug.exceptions import HTTPException, NotFound
from shorty.utils import STATIC_PATH, session, local, local_manager, \
metadata, url_map
import shorty.models
from shorty import views
class Shorty(object):
def __init__(self, db_uri):
local.application = self
self.database_engine = create_engine(db_uri, convert_unicode=True)
self.dispatch = SharedDataMiddleware(self.dispatch, {
'/static': STATIC_PATH
})
def init_database(self):
metadata.create_all(self.database_engine)
def dispatch(self, environ, start_response):
local.application = self
request = Request(environ)
local.url_adapter = adapter = url_map.bind_to_environ(environ)
try:
endpoint, values = adapter.match()
handler = getattr(views, endpoint)
response = handler(request, **values)
except NotFound, e:
response = views.not_found(request)
response.status_code = 404
except HTTPException, e:
response = e
return ClosingIterator(response(environ, start_response),
[session.remove, local_manager.cleanup])
def __call__(self, environ, start_response):
return self.dispatch(environ, start_response)
|
pjdelport/django | refs/heads/master | django/contrib/messages/utils.py | 1333 | from django.conf import settings
from django.contrib.messages import constants
def get_level_tags():
"""
Returns the message level tags.
"""
level_tags = constants.DEFAULT_TAGS.copy()
level_tags.update(getattr(settings, 'MESSAGE_TAGS', {}))
return level_tags
|
kswiat/django | refs/heads/master | tests/test_runner/__init__.py | 12133432 | |
EvaErzin/DragonHack | refs/heads/master | DragonHack/__init__.py | 12133432 | |
ahmed-mahran/hue | refs/heads/master | desktop/core/ext-py/Django-1.6.10/tests/m2m_multiple/__init__.py | 12133432 | |
arodic/three.js | refs/heads/master | utils/exporters/max/annotate/annotate.py | 160 | #!/usr/bin/env python
__author__ = 'Andrew Dunai <andrew@dun.ai>'
import sys
import json
import argparse
import re
from collections import namedtuple
try:
from PyQt4 import QtGui
import argparseui
except ImportError:
CAN_GUI = False
else:
CAN_GUI = True
range_regexp = re.compile(r'^([\w\d]+)\=([\d]+)\.\.([\d]+)$')
Range = namedtuple('Range', ('name', 'start', 'end'))
def parse_range(value):
match = range_regexp.match(value)
if not match:
raise argparse.ArgumentTypeError('Ranges should be in form "name=frame..frame"')
return Range(match.group(1), int(match.group(2)) - 1, int(match.group(3)) - 1)
epilog = 'example:\n %(prog)s -i model.js -o model.new.js idle=1..10 walk=11..20'
if not CAN_GUI:
epilog += '\npro tip:\n Install PyQt4 and argparseui packages to use GUI ("-u" option).'
epilog += '\nCreated by {}'.format(__author__)
parser = argparse.ArgumentParser(
description='Split THREE.js model animation into seperate parts.',
epilog=epilog,
formatter_class=argparse.RawDescriptionHelpFormatter
)
CAN_GUI and parser.add_argument('-u', '--gui', help='run in GUI', dest='gui', action='store_true')
parser.add_argument('-i', metavar='FILE', help='input file name', required=True, dest='source', type=argparse.FileType('r'))
parser.add_argument('-o', metavar='FILE', help='output file name', required=True, dest='destination', type=argparse.FileType('w'))
parser.add_argument('range', nargs='+', help='range in format "name=frame..frame"', type=parse_range)
def process(parser):
args = parser.parse_args()
data = json.loads(args.source.read())
animation = data.get('animation')
fps = float(animation.get('fps'))
length = float(animation.get('length'))
frame_count = int(length * fps)
frame_duration = 1.0 / fps
all_hierarchy = animation.get('hierarchy')
animations = {}
for r in args.range:
# Create animation & hierarchy
hierarchy = []
animation = {
'name': r.name,
'fps': fps,
'length': (r.end - r.start) * frame_duration,
'hierarchy': hierarchy
}
# Go through each bone animation
for bone in all_hierarchy:
keys = [key for key in bone['keys'] if (key['time'] >= r.start * frame_duration) and (key['time'] <= r.end * frame_duration)]
# Patch time
time = 0.0
for key in keys:
key['time'] = round(time, 3)
time += frame_duration
new_bone = {
'parent': bone['parent'],
'keys': keys
}
hierarchy.append(new_bone)
animations[r.name] = animation
del data['animation']
data['animations'] = animations
args.destination.write(json.dumps(data))
if '-u' in sys.argv and CAN_GUI:
app = QtGui.QApplication(sys.argv)
a = argparseui.ArgparseUi(parser)
a.show()
app.exec_()
if a.result() == 1:
process(a)
else:
process(parser)
|
YuxuanLing/trunk | refs/heads/master | trunk/code/study/python/core_python_appilication/ch11/myproject/poster/__init__.py | 12133432 | |
yamila-moreno/django | refs/heads/master | tests/gis_tests/layermap/__init__.py | 12133432 | |
kalxas/geonode | refs/heads/master | geonode/base/management/commands/load_thesaurus.py | 2 | # -*- coding: utf-8 -*-
#########################################################################
#
# Copyright (C) 2016 OSGeo
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
#########################################################################
from typing import List
from owslib.etree import etree as dlxml
from django.conf import settings
from django.core.management.base import BaseCommand, CommandError
from geonode.base.models import Thesaurus, ThesaurusKeyword, ThesaurusKeywordLabel, ThesaurusLabel
class Command(BaseCommand):
help = 'Load a thesaurus in RDF format into DB'
def add_arguments(self, parser):
# Named (optional) arguments
parser.add_argument(
'-d',
'--dry-run',
action="store_true",
dest='dryrun',
default=False,
help='Only parse and print the thesaurus file, without perform insertion in the DB.')
parser.add_argument(
'--name',
dest='name',
help='Identifier name for the thesaurus in this GeoNode instance.')
parser.add_argument(
'--file',
dest='file',
help='Full path to a thesaurus in RDF format.')
def handle(self, **options):
input_file = options.get('file')
name = options.get('name')
dryrun = options.get('dryrun')
if not input_file:
raise CommandError("Missing thesaurus rdf file path (--file)")
if not name:
raise CommandError("Missing identifier name for the thesaurus (--name)")
if name.startswith('fake'):
self.create_fake_thesaurus(name)
else:
self.load_thesaurus(input_file, name, not dryrun)
def load_thesaurus(self, input_file, name, store):
RDF_URI = 'http://www.w3.org/1999/02/22-rdf-syntax-ns#'
XML_URI = 'http://www.w3.org/XML/1998/namespace'
ABOUT_ATTRIB = f"{{{RDF_URI}}}about"
LANG_ATTRIB = f"{{{XML_URI}}}lang"
ns = {
'rdf': RDF_URI,
'foaf': 'http://xmlns.com/foaf/0.1/',
'dc': 'http://purl.org/dc/elements/1.1/',
'dcterms': 'http://purl.org/dc/terms/',
'skos': 'http://www.w3.org/2004/02/skos/core#'
}
tfile = dlxml.parse(input_file)
root = tfile.getroot()
scheme = root.find('skos:ConceptScheme', ns)
if not scheme:
raise CommandError("ConceptScheme not found in file")
titles = scheme.findall('dc:title', ns)
default_lang = getattr(settings, 'THESAURUS_DEFAULT_LANG', None)
available_lang = get_all_lang_available_with_title(titles, LANG_ATTRIB)
thesaurus_title = determinate_value(available_lang, default_lang)
descr = scheme.find('dc:description', ns).text if scheme.find('dc:description', ns) else thesaurus_title
date_issued = scheme.find('dcterms:issued', ns).text
about = scheme.attrib.get(ABOUT_ATTRIB)
print(f'Thesaurus "{thesaurus_title}" issued at {date_issued}')
thesaurus = Thesaurus()
thesaurus.identifier = name
thesaurus.title = thesaurus_title
thesaurus.description = descr
thesaurus.about = about
thesaurus.date = date_issued
if store:
thesaurus.save()
for lang in available_lang:
if lang[0] is not None:
thesaurus_label = ThesaurusLabel()
thesaurus_label.lang = lang[0]
thesaurus_label.label = lang[1]
thesaurus_label.thesaurus = thesaurus
thesaurus_label.save()
for concept in root.findall('skos:Concept', ns):
about = concept.attrib.get(ABOUT_ATTRIB)
alt_label = concept.find('skos:altLabel', ns)
if alt_label is not None:
alt_label = alt_label.text
else:
concepts = concept.findall('skos:prefLabel', ns)
available_lang = get_all_lang_available_with_title(concepts, LANG_ATTRIB)
alt_label = determinate_value(available_lang, default_lang)
print(f'Concept {alt_label} ({about})')
tk = ThesaurusKeyword()
tk.thesaurus = thesaurus
tk.about = about
tk.alt_label = alt_label
if store:
tk.save()
for pref_label in concept.findall('skos:prefLabel', ns):
lang = pref_label.attrib.get(LANG_ATTRIB)
label = pref_label.text
print(f' Label {lang}: {label}')
tkl = ThesaurusKeywordLabel()
tkl.keyword = tk
tkl.lang = lang
tkl.label = label
if store:
tkl.save()
def create_fake_thesaurus(self, name):
thesaurus = Thesaurus()
thesaurus.identifier = name
thesaurus.title = f"Title: {name}"
thesaurus.description = "SAMPLE FAKE THESAURUS USED FOR TESTING"
thesaurus.date = "2016-10-01"
thesaurus.save()
for keyword in ['aaa', 'bbb', 'ccc']:
tk = ThesaurusKeyword()
tk.thesaurus = thesaurus
tk.about = f"{keyword}_about"
tk.alt_label = f"{keyword}_alt"
tk.save()
for _l in ['it', 'en', 'es']:
tkl = ThesaurusKeywordLabel()
tkl.keyword = tk
tkl.lang = _l
tkl.label = f"{keyword}_l_{_l}_t_{name}"
tkl.save()
def get_all_lang_available_with_title(items: List, LANG_ATTRIB: str):
return [(item.attrib.get(LANG_ATTRIB), item.text) for item in items]
def determinate_value(available_lang: List, default_lang: str):
sorted_lang = sorted(available_lang, key=lambda lang: '' if lang[0] is None else lang[0])
for item in sorted_lang:
if item[0] is None:
return item[1]
elif item[0] == default_lang:
return item[1]
return available_lang[0][1]
|
marusak/C2ARTMC | refs/heads/master | tests/test_dirs/dll_concat/expected_program.py | 1 | # pointer variables are : v0=5, v1=6, x=1, y=2, yLast=4, z=3
# next pointers are : next=0, prev=1
# data values are :
def get_program():
program=[
("x=null","00000000",1,1,"NOABSTR"),
("x=null","00000001",2,2,"NOABSTR"),
("new","00000010",1,3,"NOABSTR"),
("x.next=null","00000011",1,0,4,"NOABSTR"),
("x.next=null","00000100",1,1,5,"NOABSTR"),
("if*","00000101",6,12),
("new","00000110",2,7,"NOABSTR"),
("x.next=y","00000111",2,1,0,8,3,"NOABSTR"),
("x.next=y","00001000",1,2,1,9,4,"NOABSTR"),
("x.next=null","00001001",2,1,10,"NOABSTR"),
("x=y","00001010",1,2,11,"NOABSTR"),
("goto","00001011",5,"NOABSTR"),
("x=null","00001100",3,13,"NOABSTR"),
("new","00001101",2,14,"NOABSTR"),
("x.next=null","00001110",2,0,15,"NOABSTR"),
("x.next=null","00001111",2,1,16,"NOABSTR"),
("x=y","00010000",4,2,17,"NOABSTR"),
("if*","00010001",18,24),
("new","00010010",3,19,"NOABSTR"),
("x.next=y","00010011",3,2,0,20,5,"NOABSTR"),
("x.next=y","00010100",2,3,1,21,6,"NOABSTR"),
("x.next=null","00010101",3,1,22,"NOABSTR"),
("x=y","00010110",2,3,23,"NOABSTR"),
("goto","00010111",17,"NOABSTR"),
("x.next=y","00011000",4,1,0,25,7,"NOABSTR"),
("x.next=y","00011001",1,4,1,26,8,"NOABSTR"),
("x=null","00011010",2,27,"NOABSTR"),
("x=null","00011011",3,28,"NOABSTR"),
("x=y","00011100",2,1,29,"NOABSTR"),
("ifx==null","00011101",2,32,30),
("x=y.next","00011110",2,2,0,31,"NOABSTR"),
("goto","00011111",29,"NOABSTR"),
("x=y.next","00100000",5,1,0,33),
("ifx==null","00100001",5,39,34,"NOABSTR"),
("x=y.next","00100010",2,1,0,35,"NOABSTR"),
("x=y.next","00100011",5,1,0,36,"NOABSTR"),
("x=y.next","00100100",6,5,0,37,"NOABSTR"),
("x.next=y","00100101",1,6,0,38,9,"NOABSTR"),
("goto","00100110",32,"NOABSTR"),
("x=y.next","00100111",5,1,1,40),
("ifx==null","00101000",5,46,41,"NOABSTR"),
("x=y.next","00101001",2,1,1,42,"NOABSTR"),
("x=y.next","00101010",5,1,1,43,"NOABSTR"),
("x=y.next","00101011",6,5,1,44,"NOABSTR"),
("x.next=y","00101100",1,6,1,45,10,"NOABSTR"),
("goto","00101101",39,"NOABSTR"),
("goto","00101110",47,"NOABSTR"),
("exit","00101111","NOABSTR")]
node_width=28
pointer_num=7
desc_num=11
next_num=2
err_line="11111111"
restrict_var=1
env=(node_width, pointer_num, desc_num, next_num, err_line,restrict_var)
return(program, env) |
aayushKumarJarvis/Algorithm-Implementations | refs/heads/master | Gnome_sort/Python/jcla1/gnome_sort.py | 25 | # Gnome sort runs in O(n^2), but if the array
# is nearly sorted already it runs in about O(n)
# http://en.wikipedia.org/wiki/Gnome_sort
def gnome_sort(arr):
pos = 1
while pos < len(arr):
if arr[pos] >= arr[pos-1]:
pos += 1
else:
arr[pos], arr[pos-1] = arr[pos-1], arr[pos]
if pos > 1:
pos -= 1
return arr |
denniszollo/MAVProxy | refs/heads/master | MAVProxy/modules/mavproxy_link.py | 2 | #!/usr/bin/env python
'''enable run-time addition and removal of master link, just like --master on the cnd line'''
''' TO USE:
link add 10.11.12.13:14550
link list
link remove 3 # to remove 3rd output
'''
from pymavlink import mavutil
import time, struct, math, sys, fnmatch, traceback
from MAVProxy.modules.lib import mp_module
from MAVProxy.modules.lib import mp_util
if mp_util.has_wxpython:
from MAVProxy.modules.lib.mp_menu import *
dataPackets = frozenset(['BAD_DATA','LOG_DATA'])
delayedPackets = frozenset([ 'MISSION_CURRENT', 'SYS_STATUS', 'VFR_HUD',
'GPS_RAW_INT', 'SCALED_PRESSURE', 'GLOBAL_POSITION_INT',
'NAV_CONTROLLER_OUTPUT' ])
activityPackets = frozenset([ 'HEARTBEAT', 'GPS_RAW_INT', 'GPS_RAW', 'GLOBAL_POSITION_INT', 'SYS_STATUS' ])
class LinkModule(mp_module.MPModule):
def __init__(self, mpstate):
super(LinkModule, self).__init__(mpstate, "link", "link control", public=True)
self.add_command('link', self.cmd_link, "link control",
["<list|ports>",
'add (SERIALPORT)',
'remove (LINKS)'])
self.no_fwd_types = set()
self.no_fwd_types.add("BAD_DATA")
self.add_completion_function('(SERIALPORT)', self.complete_serial_ports)
self.add_completion_function('(LINKS)', self.complete_links)
self.menu_added_console = False
if mp_util.has_wxpython:
self.menu_add = MPMenuSubMenu('Add', items=[])
self.menu_rm = MPMenuSubMenu('Remove', items=[])
self.menu = MPMenuSubMenu('Link',
items=[self.menu_add,
self.menu_rm,
MPMenuItem('Ports', 'Ports', '# link ports'),
MPMenuItem('List', 'List', '# link list'),
MPMenuItem('Status', 'Status', '# link')])
self.last_menu_update = 0
def idle_task(self):
'''called on idle'''
if mp_util.has_wxpython and (not self.menu_added_console and self.module('console') is not None):
self.menu_added_console = True
# we don't dynamically update these yet due to a wx bug
self.menu_add.items = [ MPMenuItem(p, p, '# link add %s' % p) for p in self.complete_serial_ports('') ]
self.menu_rm.items = [ MPMenuItem(p, p, '# link remove %s' % p) for p in self.complete_links('') ]
self.module('console').add_menu(self.menu)
for m in self.mpstate.mav_master:
m.source_system = self.settings.source_system
m.mav.srcSystem = m.source_system
m.mav.srcComponent = self.settings.source_component
def complete_serial_ports(self, text):
'''return list of serial ports'''
ports = mavutil.auto_detect_serial(preferred_list=['*FTDI*',"*Arduino_Mega_2560*", "*3D_Robotics*", "*USB_to_UART*", '*PX4*', '*FMU*'])
return [ p.device for p in ports ]
def complete_links(self, text):
'''return list of links'''
return [ m.address for m in self.mpstate.mav_master ]
def cmd_link(self, args):
'''handle link commands'''
if len(args) < 1:
self.show_link()
elif args[0] == "list":
self.cmd_link_list()
elif args[0] == "add":
if len(args) != 2:
print("Usage: link add LINK")
return
self.cmd_link_add(args[1:])
elif args[0] == "ports":
self.cmd_link_ports()
elif args[0] == "remove":
if len(args) != 2:
print("Usage: link remove LINK")
return
self.cmd_link_remove(args[1:])
else:
print("usage: link <list|add|remove>")
def show_link(self):
'''show link information'''
for master in self.mpstate.mav_master:
linkdelay = (self.status.highest_msec - master.highest_msec)*1.0e-3
if master.linkerror:
print("link %u down" % (master.linknum+1))
else:
print("link %u OK (%u packets, %.2fs delay, %u lost, %.1f%% loss)" % (master.linknum+1,
self.status.counters['MasterIn'][master.linknum],
linkdelay,
master.mav_loss,
master.packet_loss()))
def cmd_link_list(self):
'''list links'''
print("%u links" % len(self.mpstate.mav_master))
for i in range(len(self.mpstate.mav_master)):
conn = self.mpstate.mav_master[i]
print("%u: %s" % (i, conn.address))
def link_add(self, device):
'''add new link'''
try:
print("Connect %s source_system=%d" % (device, self.settings.source_system))
conn = mavutil.mavlink_connection(device, autoreconnect=True,
source_system=self.settings.source_system,
baud=self.settings.baudrate)
conn.mav.srcComponent = self.settings.source_component
except Exception as msg:
print("Failed to connect to %s : %s" % (device, msg))
return False
if self.settings.rtscts:
conn.set_rtscts(True)
conn.linknum = len(self.mpstate.mav_master)
conn.mav.set_callback(self.master_callback, conn)
if hasattr(conn.mav, 'set_send_callback'):
conn.mav.set_send_callback(self.master_send_callback, conn)
conn.linknum = len(self.mpstate.mav_master)
conn.linkerror = False
conn.link_delayed = False
conn.last_heartbeat = 0
conn.last_message = 0
conn.highest_msec = 0
self.mpstate.mav_master.append(conn)
self.status.counters['MasterIn'].append(0)
try:
mp_util.child_fd_list_add(conn.port.fileno())
except Exception:
pass
return True
def cmd_link_add(self, args):
'''add new link'''
device = args[0]
print("Adding link %s" % device)
self.link_add(device)
def cmd_link_ports(self):
'''show available ports'''
ports = mavutil.auto_detect_serial(preferred_list=['*FTDI*',"*Arduino_Mega_2560*", "*3D_Robotics*", "*USB_to_UART*", '*PX4*', '*FMU*'])
for p in ports:
print("%s : %s : %s" % (p.device, p.description, p.hwid))
def cmd_link_remove(self, args):
'''remove an link'''
device = args[0]
if len(self.mpstate.mav_master) <= 1:
print("Not removing last link")
return
for i in range(len(self.mpstate.mav_master)):
conn = self.mpstate.mav_master[i]
if str(i) == device or conn.address == device:
print("Removing link %s" % conn.address)
try:
try:
mp_util.child_fd_list_remove(conn.port.fileno())
except Exception:
pass
self.mpstate.mav_master[i].close()
except Exception as msg:
print(msg)
pass
self.mpstate.mav_master.pop(i)
self.status.counters['MasterIn'].pop(i)
# renumber the links
for j in range(len(self.mpstate.mav_master)):
conn = self.mpstate.mav_master[j]
conn.linknum = j
return
def get_usec(self):
'''time since 1970 in microseconds'''
return int(time.time() * 1.0e6)
def master_send_callback(self, m, master):
'''called on sending a message'''
if self.status.watch is not None:
if fnmatch.fnmatch(m.get_type().upper(), self.status.watch.upper()):
self.mpstate.console.writeln('> '+ str(m))
mtype = m.get_type()
if mtype != 'BAD_DATA' and self.mpstate.logqueue:
usec = self.get_usec()
usec = (usec & ~3) | 3 # linknum 3
self.mpstate.logqueue.put(str(struct.pack('>Q', usec) + m.get_msgbuf()))
def handle_msec_timestamp(self, m, master):
'''special handling for MAVLink packets with a time_boot_ms field'''
if m.get_type() == 'GLOBAL_POSITION_INT':
# this is fix time, not boot time
return
msec = m.time_boot_ms
if msec + 30000 < master.highest_msec:
self.say('Time has wrapped')
print('Time has wrapped', msec, master.highest_msec)
self.status.highest_msec = msec
for mm in self.mpstate.mav_master:
mm.link_delayed = False
mm.highest_msec = msec
return
# we want to detect when a link is delayed
master.highest_msec = msec
if msec > self.status.highest_msec:
self.status.highest_msec = msec
if msec < self.status.highest_msec and len(self.mpstate.mav_master) > 1:
master.link_delayed = True
else:
master.link_delayed = False
def report_altitude(self, altitude):
'''possibly report a new altitude'''
master = self.master
if getattr(self.console, 'ElevationMap', None) is not None and self.mpstate.settings.basealt != 0:
lat = master.field('GLOBAL_POSITION_INT', 'lat', 0)*1.0e-7
lon = master.field('GLOBAL_POSITION_INT', 'lon', 0)*1.0e-7
alt1 = self.console.ElevationMap.GetElevation(lat, lon)
if alt1 is not None:
alt2 = self.mpstate.settings.basealt
altitude += alt2 - alt1
self.status.altitude = altitude
if (int(self.mpstate.settings.altreadout) > 0 and
math.fabs(self.status.altitude - self.status.last_altitude_announce) >=
int(self.settings.altreadout)):
self.status.last_altitude_announce = self.status.altitude
rounded_alt = int(self.settings.altreadout) * ((self.settings.altreadout/2 + int(self.status.altitude)) / int(self.settings.altreadout))
self.say("height %u" % rounded_alt, priority='notification')
def master_callback(self, m, master):
'''process mavlink message m on master, sending any messages to recipients'''
if getattr(m, '_timestamp', None) is None:
master.post_message(m)
self.status.counters['MasterIn'][master.linknum] += 1
mtype = m.get_type()
# and log them
if mtype not in dataPackets and self.mpstate.logqueue:
# put link number in bottom 2 bits, so we can analyse packet
# delay in saved logs
usec = self.get_usec()
usec = (usec & ~3) | master.linknum
self.mpstate.logqueue.put(str(struct.pack('>Q', usec) + m.get_msgbuf()))
# keep the last message of each type around
self.status.msgs[m.get_type()] = m
if not m.get_type() in self.status.msg_count:
self.status.msg_count[m.get_type()] = 0
self.status.msg_count[m.get_type()] += 1
if m.get_srcComponent() == mavutil.mavlink.MAV_COMP_ID_GIMBAL and m.get_type() == 'HEARTBEAT':
# silence gimbal heartbeat packets for now
return
if getattr(m, 'time_boot_ms', None) is not None:
# update link_delayed attribute
self.handle_msec_timestamp(m, master)
if mtype in activityPackets:
if master.linkerror:
master.linkerror = False
self.say("link %u OK" % (master.linknum+1))
self.status.last_message = time.time()
master.last_message = self.status.last_message
if master.link_delayed:
# don't process delayed packets that cause double reporting
if mtype in delayedPackets:
return
if mtype == 'HEARTBEAT' and m.get_srcSystem() != 255:
if self.settings.target_system == 0 and self.settings.target_system != m.get_srcSystem():
self.settings.target_system = m.get_srcSystem()
self.say("online system %u" % self.settings.target_system,'message')
if self.status.heartbeat_error:
self.status.heartbeat_error = False
self.say("heartbeat OK")
if master.linkerror:
master.linkerror = False
self.say("link %u OK" % (master.linknum+1))
self.status.last_heartbeat = time.time()
master.last_heartbeat = self.status.last_heartbeat
armed = self.master.motors_armed()
if armed != self.status.armed:
self.status.armed = armed
if armed:
self.say("ARMED")
else:
self.say("DISARMED")
if master.flightmode != self.status.flightmode and time.time() > self.status.last_mode_announce + 2:
self.status.flightmode = master.flightmode
self.status.last_mode_announce = time.time()
if self.mpstate.functions.input_handler is None:
self.mpstate.rl.set_prompt(self.status.flightmode + "> ")
self.say("Mode " + self.status.flightmode)
if m.type == mavutil.mavlink.MAV_TYPE_FIXED_WING:
self.mpstate.vehicle_type = 'plane'
self.mpstate.vehicle_name = 'ArduPlane'
elif m.type in [mavutil.mavlink.MAV_TYPE_GROUND_ROVER,
mavutil.mavlink.MAV_TYPE_SURFACE_BOAT,
mavutil.mavlink.MAV_TYPE_SUBMARINE]:
self.mpstate.vehicle_type = 'rover'
self.mpstate.vehicle_name = 'APMrover2'
elif m.type in [mavutil.mavlink.MAV_TYPE_QUADROTOR,
mavutil.mavlink.MAV_TYPE_COAXIAL,
mavutil.mavlink.MAV_TYPE_HEXAROTOR,
mavutil.mavlink.MAV_TYPE_OCTOROTOR,
mavutil.mavlink.MAV_TYPE_TRICOPTER,
mavutil.mavlink.MAV_TYPE_HELICOPTER]:
self.mpstate.vehicle_type = 'copter'
self.mpstate.vehicle_name = 'ArduCopter'
elif m.type in [mavutil.mavlink.MAV_TYPE_ANTENNA_TRACKER]:
self.mpstate.vehicle_type = 'antenna'
self.mpstate.vehicle_name = 'AntennaTracker'
elif mtype == 'STATUSTEXT':
if m.text != self.status.last_apm_msg or time.time() > self.status.last_apm_msg_time+2:
self.mpstate.console.writeln("APM: %s" % m.text, bg='red')
self.status.last_apm_msg = m.text
self.status.last_apm_msg_time = time.time()
elif mtype == "VFR_HUD":
have_gps_lock = False
if 'GPS_RAW' in self.status.msgs and self.status.msgs['GPS_RAW'].fix_type == 2:
have_gps_lock = True
elif 'GPS_RAW_INT' in self.status.msgs and self.status.msgs['GPS_RAW_INT'].fix_type == 3:
have_gps_lock = True
if have_gps_lock and not self.status.have_gps_lock and m.alt != 0:
self.say("GPS lock at %u meters" % m.alt, priority='notification')
self.status.have_gps_lock = True
elif mtype == "GPS_RAW":
if self.status.have_gps_lock:
if m.fix_type != 2 and not self.status.lost_gps_lock and (time.time() - self.status.last_gps_lock) > 3:
self.say("GPS fix lost")
self.status.lost_gps_lock = True
if m.fix_type == 2 and self.status.lost_gps_lock:
self.say("GPS OK")
self.status.lost_gps_lock = False
if m.fix_type == 2:
self.status.last_gps_lock = time.time()
elif mtype == "GPS_RAW_INT":
if self.status.have_gps_lock:
if m.fix_type < 3 and not self.status.lost_gps_lock and (time.time() - self.status.last_gps_lock) > 3:
self.say("GPS fix lost")
self.status.lost_gps_lock = True
if m.fix_type >= 3 and self.status.lost_gps_lock:
self.say("GPS OK")
self.status.lost_gps_lock = False
if m.fix_type >= 3:
self.status.last_gps_lock = time.time()
elif mtype == "NAV_CONTROLLER_OUTPUT" and self.status.flightmode == "AUTO" and self.mpstate.settings.distreadout:
rounded_dist = int(m.wp_dist/self.mpstate.settings.distreadout)*self.mpstate.settings.distreadout
if math.fabs(rounded_dist - self.status.last_distance_announce) >= self.mpstate.settings.distreadout:
if rounded_dist != 0:
self.say("%u" % rounded_dist, priority="progress")
self.status.last_distance_announce = rounded_dist
elif mtype == "GLOBAL_POSITION_INT":
self.report_altitude(m.relative_alt*0.001)
elif mtype == "COMPASSMOT_STATUS":
print(m)
elif mtype == "BAD_DATA":
if self.mpstate.settings.shownoise and mavutil.all_printable(m.data):
self.mpstate.console.write(str(m.data), bg='red')
elif mtype in [ "COMMAND_ACK", "MISSION_ACK" ]:
self.mpstate.console.writeln("Got MAVLink msg: %s" % m)
if mtype == "COMMAND_ACK" and m.command == mavutil.mavlink.MAV_CMD_PREFLIGHT_CALIBRATION:
if m.result == mavutil.mavlink.MAV_RESULT_ACCEPTED:
self.say("Calibrated")
else:
#self.mpstate.console.writeln("Got MAVLink msg: %s" % m)
pass
if self.status.watch is not None:
if fnmatch.fnmatch(m.get_type().upper(), self.status.watch.upper()):
self.mpstate.console.writeln('< '+str(m))
# don't pass along bad data
if mtype != 'BAD_DATA':
# pass messages along to listeners, except for REQUEST_DATA_STREAM, which
# would lead a conflict in stream rate setting between mavproxy and the other
# GCS
if self.mpstate.settings.mavfwd_rate or mtype != 'REQUEST_DATA_STREAM':
if not mtype in self.no_fwd_types:
for r in self.mpstate.mav_outputs:
r.write(m.get_msgbuf())
# pass to modules
for (mod,pm) in self.mpstate.modules:
if not hasattr(mod, 'mavlink_packet'):
continue
try:
mod.mavlink_packet(m)
except Exception as msg:
if self.mpstate.settings.moddebug == 1:
print(msg)
elif self.mpstate.settings.moddebug > 1:
exc_type, exc_value, exc_traceback = sys.exc_info()
traceback.print_exception(exc_type, exc_value, exc_traceback,
limit=2, file=sys.stdout)
def init(mpstate):
'''initialise module'''
return LinkModule(mpstate)
|
JackDanger/sentry | refs/heads/master | src/sentry/south_migrations/0288_set_release_project_new_groups_to_zero.py | 3 | # -*- coding: utf-8 -*-
from south.utils import datetime_utils as datetime
from south.db import db
from south.v2 import DataMigration
from django.db import models
class Migration(DataMigration):
def forwards(self, orm):
"Write your forwards methods here."
db.commit_transaction()
modified = True
while modified:
rp_ids = list(orm.ReleaseProject.objects.filter(
new_groups__isnull=True
).values_list('id', flat=True)[:1000])
modified = orm.ReleaseProject.objects.filter(
id__in=rp_ids,
new_groups__isnull=True
).update(new_groups=0)
db.start_transaction()
def backwards(self, orm):
"Write your backwards methods here."
models = {
'sentry.activity': {
'Meta': {'object_name': 'Activity'},
'data': ('sentry.db.models.fields.gzippeddict.GzippedDictField', [], {'null': 'True'}),
'datetime': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'group': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'to': "orm['sentry.Group']", 'null': 'True'}),
'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}),
'ident': ('django.db.models.fields.CharField', [], {'max_length': '64', 'null': 'True'}),
'project': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'to': "orm['sentry.Project']"}),
'type': ('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {}),
'user': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'to': "orm['sentry.User']", 'null': 'True'})
},
'sentry.apikey': {
'Meta': {'object_name': 'ApiKey'},
'allowed_origins': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),
'date_added': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}),
'key': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '32'}),
'label': ('django.db.models.fields.CharField', [], {'default': "'Default'", 'max_length': '64', 'blank': 'True'}),
'organization': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'related_name': "'key_set'", 'to': "orm['sentry.Organization']"}),
'scopes': ('django.db.models.fields.BigIntegerField', [], {'default': 'None'}),
'status': ('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {'default': '0', 'db_index': 'True'})
},
'sentry.apitoken': {
'Meta': {'object_name': 'ApiToken'},
'date_added': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}),
'key': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'to': "orm['sentry.ApiKey']", 'null': 'True'}),
'scopes': ('django.db.models.fields.BigIntegerField', [], {'default': 'None'}),
'token': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '64'}),
'user': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'to': "orm['sentry.User']"})
},
'sentry.auditlogentry': {
'Meta': {'object_name': 'AuditLogEntry'},
'actor': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'blank': 'True', 'related_name': "'audit_actors'", 'null': 'True', 'to': "orm['sentry.User']"}),
'actor_key': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'to': "orm['sentry.ApiKey']", 'null': 'True', 'blank': 'True'}),
'actor_label': ('django.db.models.fields.CharField', [], {'max_length': '64', 'null': 'True', 'blank': 'True'}),
'data': ('sentry.db.models.fields.gzippeddict.GzippedDictField', [], {}),
'datetime': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'event': ('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {}),
'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}),
'ip_address': ('django.db.models.fields.GenericIPAddressField', [], {'max_length': '39', 'null': 'True'}),
'organization': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'to': "orm['sentry.Organization']"}),
'target_object': ('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {'null': 'True'}),
'target_user': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'blank': 'True', 'related_name': "'audit_targets'", 'null': 'True', 'to': "orm['sentry.User']"})
},
'sentry.authenticator': {
'Meta': {'unique_together': "(('user', 'type'),)", 'object_name': 'Authenticator', 'db_table': "'auth_authenticator'"},
'config': ('sentry.db.models.fields.pickle.UnicodePickledObjectField', [], {}),
'created_at': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'id': ('sentry.db.models.fields.bounded.BoundedAutoField', [], {'primary_key': 'True'}),
'last_used_at': ('django.db.models.fields.DateTimeField', [], {'null': 'True'}),
'type': ('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {}),
'user': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'to': "orm['sentry.User']"})
},
'sentry.authidentity': {
'Meta': {'unique_together': "(('auth_provider', 'ident'), ('auth_provider', 'user'))", 'object_name': 'AuthIdentity'},
'auth_provider': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'to': "orm['sentry.AuthProvider']"}),
'data': ('jsonfield.fields.JSONField', [], {'default': '{}'}),
'date_added': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}),
'ident': ('django.db.models.fields.CharField', [], {'max_length': '128'}),
'last_synced': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'last_verified': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'user': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'to': "orm['sentry.User']"})
},
'sentry.authprovider': {
'Meta': {'object_name': 'AuthProvider'},
'config': ('jsonfield.fields.JSONField', [], {'default': '{}'}),
'date_added': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'default_global_access': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'default_role': ('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {'default': '50'}),
'default_teams': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['sentry.Team']", 'symmetrical': 'False', 'blank': 'True'}),
'flags': ('django.db.models.fields.BigIntegerField', [], {'default': '0'}),
'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}),
'last_sync': ('django.db.models.fields.DateTimeField', [], {'null': 'True'}),
'organization': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'to': "orm['sentry.Organization']", 'unique': 'True'}),
'provider': ('django.db.models.fields.CharField', [], {'max_length': '128'}),
'sync_time': ('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {'null': 'True'})
},
'sentry.broadcast': {
'Meta': {'object_name': 'Broadcast'},
'date_added': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'date_expires': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime(2017, 2, 1, 0, 0)', 'null': 'True', 'blank': 'True'}),
'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}),
'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True', 'db_index': 'True'}),
'link': ('django.db.models.fields.URLField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'}),
'message': ('django.db.models.fields.CharField', [], {'max_length': '256'}),
'title': ('django.db.models.fields.CharField', [], {'max_length': '32'}),
'upstream_id': ('django.db.models.fields.CharField', [], {'max_length': '32', 'null': 'True', 'blank': 'True'})
},
'sentry.broadcastseen': {
'Meta': {'unique_together': "(('broadcast', 'user'),)", 'object_name': 'BroadcastSeen'},
'broadcast': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'to': "orm['sentry.Broadcast']"}),
'date_seen': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}),
'user': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'to': "orm['sentry.User']"})
},
'sentry.commit': {
'Meta': {'unique_together': "(('repository_id', 'key'),)", 'object_name': 'Commit', 'index_together': "(('repository_id', 'date_added'),)"},
'author': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'to': "orm['sentry.CommitAuthor']", 'null': 'True'}),
'date_added': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}),
'key': ('django.db.models.fields.CharField', [], {'max_length': '64'}),
'message': ('django.db.models.fields.TextField', [], {'null': 'True'}),
'organization_id': ('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {'db_index': 'True'}),
'repository_id': ('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {})
},
'sentry.commitauthor': {
'Meta': {'unique_together': "(('organization_id', 'email'),)", 'object_name': 'CommitAuthor'},
'email': ('django.db.models.fields.EmailField', [], {'max_length': '75'}),
'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '128', 'null': 'True'}),
'organization_id': ('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {'db_index': 'True'})
},
'sentry.commitfilechange': {
'Meta': {'unique_together': "(('commit', 'filename'),)", 'object_name': 'CommitFileChange'},
'commit': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'to': "orm['sentry.Commit']"}),
'filename': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}),
'organization_id': ('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {'db_index': 'True'}),
'type': ('django.db.models.fields.CharField', [], {'max_length': '1'})
},
'sentry.counter': {
'Meta': {'object_name': 'Counter', 'db_table': "'sentry_projectcounter'"},
'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}),
'project': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'to': "orm['sentry.Project']", 'unique': 'True'}),
'value': ('sentry.db.models.fields.bounded.BoundedBigIntegerField', [], {})
},
'sentry.dsymbundle': {
'Meta': {'object_name': 'DSymBundle'},
'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}),
'object': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'to': "orm['sentry.DSymObject']"}),
'sdk': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'to': "orm['sentry.DSymSDK']"})
},
'sentry.dsymobject': {
'Meta': {'object_name': 'DSymObject'},
'cpu_name': ('django.db.models.fields.CharField', [], {'max_length': '40'}),
'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}),
'object_path': ('django.db.models.fields.TextField', [], {'db_index': 'True'}),
'uuid': ('django.db.models.fields.CharField', [], {'max_length': '36', 'db_index': 'True'}),
'vmaddr': ('sentry.db.models.fields.bounded.BoundedBigIntegerField', [], {'null': 'True'}),
'vmsize': ('sentry.db.models.fields.bounded.BoundedBigIntegerField', [], {'null': 'True'})
},
'sentry.dsymsdk': {
'Meta': {'object_name': 'DSymSDK', 'index_together': "[('version_major', 'version_minor', 'version_patchlevel', 'version_build')]"},
'dsym_type': ('django.db.models.fields.CharField', [], {'max_length': '20', 'db_index': 'True'}),
'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}),
'sdk_name': ('django.db.models.fields.CharField', [], {'max_length': '20'}),
'version_build': ('django.db.models.fields.CharField', [], {'max_length': '40'}),
'version_major': ('django.db.models.fields.IntegerField', [], {}),
'version_minor': ('django.db.models.fields.IntegerField', [], {}),
'version_patchlevel': ('django.db.models.fields.IntegerField', [], {})
},
'sentry.dsymsymbol': {
'Meta': {'unique_together': "[('object', 'address')]", 'object_name': 'DSymSymbol'},
'address': ('sentry.db.models.fields.bounded.BoundedBigIntegerField', [], {'db_index': 'True'}),
'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}),
'object': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'to': "orm['sentry.DSymObject']"}),
'symbol': ('django.db.models.fields.TextField', [], {})
},
'sentry.environment': {
'Meta': {'unique_together': "(('project_id', 'name'),)", 'object_name': 'Environment'},
'date_added': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '64'}),
'project_id': ('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {})
},
'sentry.event': {
'Meta': {'unique_together': "(('project_id', 'event_id'),)", 'object_name': 'Event', 'db_table': "'sentry_message'", 'index_together': "(('group_id', 'datetime'),)"},
'data': ('sentry.db.models.fields.node.NodeField', [], {'null': 'True', 'blank': 'True'}),
'datetime': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'db_index': 'True'}),
'event_id': ('django.db.models.fields.CharField', [], {'max_length': '32', 'null': 'True', 'db_column': "'message_id'"}),
'group_id': ('sentry.db.models.fields.bounded.BoundedBigIntegerField', [], {'null': 'True', 'blank': 'True'}),
'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}),
'message': ('django.db.models.fields.TextField', [], {}),
'platform': ('django.db.models.fields.CharField', [], {'max_length': '64', 'null': 'True'}),
'project_id': ('sentry.db.models.fields.bounded.BoundedBigIntegerField', [], {'null': 'True', 'blank': 'True'}),
'time_spent': ('sentry.db.models.fields.bounded.BoundedIntegerField', [], {'null': 'True'})
},
'sentry.eventmapping': {
'Meta': {'unique_together': "(('project_id', 'event_id'),)", 'object_name': 'EventMapping'},
'date_added': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'event_id': ('django.db.models.fields.CharField', [], {'max_length': '32'}),
'group_id': ('sentry.db.models.fields.bounded.BoundedBigIntegerField', [], {}),
'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}),
'project_id': ('sentry.db.models.fields.bounded.BoundedBigIntegerField', [], {})
},
'sentry.eventtag': {
'Meta': {'unique_together': "(('event_id', 'key_id', 'value_id'),)", 'object_name': 'EventTag', 'index_together': "(('project_id', 'key_id', 'value_id'), ('group_id', 'key_id', 'value_id'))"},
'date_added': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'event_id': ('sentry.db.models.fields.bounded.BoundedBigIntegerField', [], {}),
'group_id': ('sentry.db.models.fields.bounded.BoundedBigIntegerField', [], {'null': 'True'}),
'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}),
'key_id': ('sentry.db.models.fields.bounded.BoundedBigIntegerField', [], {}),
'project_id': ('sentry.db.models.fields.bounded.BoundedBigIntegerField', [], {}),
'value_id': ('sentry.db.models.fields.bounded.BoundedBigIntegerField', [], {})
},
'sentry.eventuser': {
'Meta': {'unique_together': "(('project', 'ident'), ('project', 'hash'))", 'object_name': 'EventUser', 'index_together': "(('project', 'email'), ('project', 'username'), ('project', 'ip_address'))"},
'date_added': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'db_index': 'True'}),
'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'null': 'True'}),
'hash': ('django.db.models.fields.CharField', [], {'max_length': '32'}),
'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}),
'ident': ('django.db.models.fields.CharField', [], {'max_length': '128', 'null': 'True'}),
'ip_address': ('django.db.models.fields.GenericIPAddressField', [], {'max_length': '39', 'null': 'True'}),
'project': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'to': "orm['sentry.Project']"}),
'username': ('django.db.models.fields.CharField', [], {'max_length': '128', 'null': 'True'})
},
'sentry.file': {
'Meta': {'object_name': 'File'},
'blob': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'related_name': "'legacy_blob'", 'null': 'True', 'to': "orm['sentry.FileBlob']"}),
'blobs': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['sentry.FileBlob']", 'through': "orm['sentry.FileBlobIndex']", 'symmetrical': 'False'}),
'checksum': ('django.db.models.fields.CharField', [], {'max_length': '40', 'null': 'True'}),
'headers': ('jsonfield.fields.JSONField', [], {'default': '{}'}),
'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '128'}),
'path': ('django.db.models.fields.TextField', [], {'null': 'True'}),
'size': ('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {'null': 'True'}),
'timestamp': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'db_index': 'True'}),
'type': ('django.db.models.fields.CharField', [], {'max_length': '64'})
},
'sentry.fileblob': {
'Meta': {'object_name': 'FileBlob'},
'checksum': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '40'}),
'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}),
'path': ('django.db.models.fields.TextField', [], {'null': 'True'}),
'size': ('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {'null': 'True'}),
'timestamp': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'db_index': 'True'})
},
'sentry.fileblobindex': {
'Meta': {'unique_together': "(('file', 'blob', 'offset'),)", 'object_name': 'FileBlobIndex'},
'blob': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'to': "orm['sentry.FileBlob']"}),
'file': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'to': "orm['sentry.File']"}),
'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}),
'offset': ('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {})
},
'sentry.globaldsymfile': {
'Meta': {'object_name': 'GlobalDSymFile'},
'cpu_name': ('django.db.models.fields.CharField', [], {'max_length': '40'}),
'file': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'to': "orm['sentry.File']"}),
'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}),
'object_name': ('django.db.models.fields.TextField', [], {}),
'uuid': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '36'})
},
'sentry.group': {
'Meta': {'unique_together': "(('project', 'short_id'),)", 'object_name': 'Group', 'db_table': "'sentry_groupedmessage'", 'index_together': "(('project', 'first_release'),)"},
'active_at': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'db_index': 'True'}),
'culprit': ('django.db.models.fields.CharField', [], {'max_length': '200', 'null': 'True', 'db_column': "'view'", 'blank': 'True'}),
'data': ('sentry.db.models.fields.gzippeddict.GzippedDictField', [], {'null': 'True', 'blank': 'True'}),
'first_release': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'to': "orm['sentry.Release']", 'null': 'True', 'on_delete': 'models.PROTECT'}),
'first_seen': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'db_index': 'True'}),
'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}),
'is_public': ('django.db.models.fields.NullBooleanField', [], {'default': 'False', 'null': 'True', 'blank': 'True'}),
'last_seen': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'db_index': 'True'}),
'level': ('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {'default': '40', 'db_index': 'True', 'blank': 'True'}),
'logger': ('django.db.models.fields.CharField', [], {'default': "''", 'max_length': '64', 'db_index': 'True', 'blank': 'True'}),
'message': ('django.db.models.fields.TextField', [], {}),
'num_comments': ('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {'default': '0', 'null': 'True'}),
'platform': ('django.db.models.fields.CharField', [], {'max_length': '64', 'null': 'True'}),
'project': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'to': "orm['sentry.Project']", 'null': 'True'}),
'resolved_at': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'db_index': 'True'}),
'score': ('sentry.db.models.fields.bounded.BoundedIntegerField', [], {'default': '0'}),
'short_id': ('sentry.db.models.fields.bounded.BoundedBigIntegerField', [], {'null': 'True'}),
'status': ('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {'default': '0', 'db_index': 'True'}),
'time_spent_count': ('sentry.db.models.fields.bounded.BoundedIntegerField', [], {'default': '0'}),
'time_spent_total': ('sentry.db.models.fields.bounded.BoundedIntegerField', [], {'default': '0'}),
'times_seen': ('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {'default': '1', 'db_index': 'True'})
},
'sentry.groupassignee': {
'Meta': {'object_name': 'GroupAssignee', 'db_table': "'sentry_groupasignee'"},
'date_added': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'group': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'related_name': "'assignee_set'", 'unique': 'True', 'to': "orm['sentry.Group']"}),
'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}),
'project': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'related_name': "'assignee_set'", 'to': "orm['sentry.Project']"}),
'user': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'related_name': "'sentry_assignee_set'", 'to': "orm['sentry.User']"})
},
'sentry.groupbookmark': {
'Meta': {'unique_together': "(('project', 'user', 'group'),)", 'object_name': 'GroupBookmark'},
'date_added': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'null': 'True'}),
'group': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'related_name': "'bookmark_set'", 'to': "orm['sentry.Group']"}),
'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}),
'project': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'related_name': "'bookmark_set'", 'to': "orm['sentry.Project']"}),
'user': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'related_name': "'sentry_bookmark_set'", 'to': "orm['sentry.User']"})
},
'sentry.groupemailthread': {
'Meta': {'unique_together': "(('email', 'group'), ('email', 'msgid'))", 'object_name': 'GroupEmailThread'},
'date': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'db_index': 'True'}),
'email': ('django.db.models.fields.EmailField', [], {'max_length': '75'}),
'group': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'related_name': "'groupemail_set'", 'to': "orm['sentry.Group']"}),
'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}),
'msgid': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'project': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'related_name': "'groupemail_set'", 'to': "orm['sentry.Project']"})
},
'sentry.grouphash': {
'Meta': {'unique_together': "(('project', 'hash'),)", 'object_name': 'GroupHash'},
'group': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'to': "orm['sentry.Group']", 'null': 'True'}),
'hash': ('django.db.models.fields.CharField', [], {'max_length': '32'}),
'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}),
'project': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'to': "orm['sentry.Project']", 'null': 'True'})
},
'sentry.groupmeta': {
'Meta': {'unique_together': "(('group', 'key'),)", 'object_name': 'GroupMeta'},
'group': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'to': "orm['sentry.Group']"}),
'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}),
'key': ('django.db.models.fields.CharField', [], {'max_length': '64'}),
'value': ('django.db.models.fields.TextField', [], {})
},
'sentry.groupredirect': {
'Meta': {'object_name': 'GroupRedirect'},
'group_id': ('sentry.db.models.fields.bounded.BoundedBigIntegerField', [], {'db_index': 'True'}),
'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}),
'previous_group_id': ('sentry.db.models.fields.bounded.BoundedBigIntegerField', [], {'unique': 'True'})
},
'sentry.grouprelease': {
'Meta': {'unique_together': "(('group_id', 'release_id', 'environment'),)", 'object_name': 'GroupRelease'},
'environment': ('django.db.models.fields.CharField', [], {'default': "''", 'max_length': '64'}),
'first_seen': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'group_id': ('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {}),
'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}),
'last_seen': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'db_index': 'True'}),
'project_id': ('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {'db_index': 'True'}),
'release_id': ('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {'db_index': 'True'})
},
'sentry.groupresolution': {
'Meta': {'object_name': 'GroupResolution'},
'datetime': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'db_index': 'True'}),
'group': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'to': "orm['sentry.Group']", 'unique': 'True'}),
'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}),
'release': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'to': "orm['sentry.Release']"}),
'status': ('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {'default': '0'})
},
'sentry.grouprulestatus': {
'Meta': {'unique_together': "(('rule', 'group'),)", 'object_name': 'GroupRuleStatus'},
'date_added': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'group': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'to': "orm['sentry.Group']"}),
'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}),
'last_active': ('django.db.models.fields.DateTimeField', [], {'null': 'True'}),
'project': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'to': "orm['sentry.Project']"}),
'rule': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'to': "orm['sentry.Rule']"}),
'status': ('django.db.models.fields.PositiveSmallIntegerField', [], {'default': '0'})
},
'sentry.groupseen': {
'Meta': {'unique_together': "(('user', 'group'),)", 'object_name': 'GroupSeen'},
'group': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'to': "orm['sentry.Group']"}),
'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}),
'last_seen': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'project': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'to': "orm['sentry.Project']"}),
'user': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'to': "orm['sentry.User']", 'db_index': 'False'})
},
'sentry.groupsnooze': {
'Meta': {'object_name': 'GroupSnooze'},
'group': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'to': "orm['sentry.Group']", 'unique': 'True'}),
'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}),
'until': ('django.db.models.fields.DateTimeField', [], {})
},
'sentry.groupsubscription': {
'Meta': {'unique_together': "(('group', 'user'),)", 'object_name': 'GroupSubscription'},
'date_added': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'null': 'True'}),
'group': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'related_name': "'subscription_set'", 'to': "orm['sentry.Group']"}),
'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}),
'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'project': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'related_name': "'subscription_set'", 'to': "orm['sentry.Project']"}),
'reason': ('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {'default': '0'}),
'user': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'to': "orm['sentry.User']"})
},
'sentry.grouptagkey': {
'Meta': {'unique_together': "(('project', 'group', 'key'),)", 'object_name': 'GroupTagKey'},
'group': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'to': "orm['sentry.Group']"}),
'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}),
'key': ('django.db.models.fields.CharField', [], {'max_length': '32'}),
'project': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'to': "orm['sentry.Project']", 'null': 'True'}),
'values_seen': ('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {'default': '0'})
},
'sentry.grouptagvalue': {
'Meta': {'unique_together': "(('group', 'key', 'value'),)", 'object_name': 'GroupTagValue', 'db_table': "'sentry_messagefiltervalue'", 'index_together': "(('project', 'key', 'value', 'last_seen'),)"},
'first_seen': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'null': 'True', 'db_index': 'True'}),
'group': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'related_name': "'grouptag'", 'to': "orm['sentry.Group']"}),
'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}),
'key': ('django.db.models.fields.CharField', [], {'max_length': '32'}),
'last_seen': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'null': 'True', 'db_index': 'True'}),
'project': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'related_name': "'grouptag'", 'null': 'True', 'to': "orm['sentry.Project']"}),
'times_seen': ('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {'default': '0'}),
'value': ('django.db.models.fields.CharField', [], {'max_length': '200'})
},
'sentry.lostpasswordhash': {
'Meta': {'object_name': 'LostPasswordHash'},
'date_added': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'hash': ('django.db.models.fields.CharField', [], {'max_length': '32'}),
'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}),
'user': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'to': "orm['sentry.User']", 'unique': 'True'})
},
'sentry.option': {
'Meta': {'object_name': 'Option'},
'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}),
'key': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '64'}),
'last_updated': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'value': ('sentry.db.models.fields.pickle.UnicodePickledObjectField', [], {})
},
'sentry.organization': {
'Meta': {'object_name': 'Organization'},
'date_added': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'default_role': ('django.db.models.fields.CharField', [], {'default': "'member'", 'max_length': '32'}),
'flags': ('django.db.models.fields.BigIntegerField', [], {'default': '1'}),
'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}),
'members': ('django.db.models.fields.related.ManyToManyField', [], {'related_name': "'org_memberships'", 'symmetrical': 'False', 'through': "orm['sentry.OrganizationMember']", 'to': "orm['sentry.User']"}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '64'}),
'slug': ('django.db.models.fields.SlugField', [], {'unique': 'True', 'max_length': '50'}),
'status': ('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {'default': '0'})
},
'sentry.organizationaccessrequest': {
'Meta': {'unique_together': "(('team', 'member'),)", 'object_name': 'OrganizationAccessRequest'},
'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}),
'member': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'to': "orm['sentry.OrganizationMember']"}),
'team': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'to': "orm['sentry.Team']"})
},
'sentry.organizationmember': {
'Meta': {'unique_together': "(('organization', 'user'), ('organization', 'email'))", 'object_name': 'OrganizationMember'},
'date_added': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'null': 'True', 'blank': 'True'}),
'flags': ('django.db.models.fields.BigIntegerField', [], {'default': '0'}),
'has_global_access': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}),
'organization': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'related_name': "'member_set'", 'to': "orm['sentry.Organization']"}),
'role': ('django.db.models.fields.CharField', [], {'default': "'member'", 'max_length': '32'}),
'teams': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['sentry.Team']", 'symmetrical': 'False', 'through': "orm['sentry.OrganizationMemberTeam']", 'blank': 'True'}),
'token': ('django.db.models.fields.CharField', [], {'max_length': '64', 'unique': 'True', 'null': 'True', 'blank': 'True'}),
'type': ('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {'default': '50', 'blank': 'True'}),
'user': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'blank': 'True', 'related_name': "'sentry_orgmember_set'", 'null': 'True', 'to': "orm['sentry.User']"})
},
'sentry.organizationmemberteam': {
'Meta': {'unique_together': "(('team', 'organizationmember'),)", 'object_name': 'OrganizationMemberTeam', 'db_table': "'sentry_organizationmember_teams'"},
'id': ('sentry.db.models.fields.bounded.BoundedAutoField', [], {'primary_key': 'True'}),
'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'organizationmember': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'to': "orm['sentry.OrganizationMember']"}),
'team': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'to': "orm['sentry.Team']"})
},
'sentry.organizationonboardingtask': {
'Meta': {'unique_together': "(('organization', 'task'),)", 'object_name': 'OrganizationOnboardingTask'},
'data': ('jsonfield.fields.JSONField', [], {'default': '{}'}),
'date_completed': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}),
'organization': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'to': "orm['sentry.Organization']"}),
'project_id': ('sentry.db.models.fields.bounded.BoundedBigIntegerField', [], {'null': 'True', 'blank': 'True'}),
'status': ('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {}),
'task': ('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {}),
'user': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'to': "orm['sentry.User']", 'null': 'True'})
},
'sentry.organizationoption': {
'Meta': {'unique_together': "(('organization', 'key'),)", 'object_name': 'OrganizationOption', 'db_table': "'sentry_organizationoptions'"},
'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}),
'key': ('django.db.models.fields.CharField', [], {'max_length': '64'}),
'organization': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'to': "orm['sentry.Organization']"}),
'value': ('sentry.db.models.fields.pickle.UnicodePickledObjectField', [], {})
},
'sentry.project': {
'Meta': {'unique_together': "(('team', 'slug'), ('organization', 'slug'))", 'object_name': 'Project'},
'date_added': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'first_event': ('django.db.models.fields.DateTimeField', [], {'null': 'True'}),
'forced_color': ('django.db.models.fields.CharField', [], {'max_length': '6', 'null': 'True', 'blank': 'True'}),
'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '200'}),
'organization': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'to': "orm['sentry.Organization']"}),
'public': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'slug': ('django.db.models.fields.SlugField', [], {'max_length': '50', 'null': 'True'}),
'status': ('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {'default': '0', 'db_index': 'True'}),
'team': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'to': "orm['sentry.Team']"})
},
'sentry.projectbookmark': {
'Meta': {'unique_together': "(('project_id', 'user'),)", 'object_name': 'ProjectBookmark'},
'date_added': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'null': 'True'}),
'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}),
'project_id': ('sentry.db.models.fields.bounded.BoundedBigIntegerField', [], {'null': 'True', 'blank': 'True'}),
'user': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'to': "orm['sentry.User']"})
},
'sentry.projectdsymfile': {
'Meta': {'unique_together': "(('project', 'uuid'),)", 'object_name': 'ProjectDSymFile'},
'cpu_name': ('django.db.models.fields.CharField', [], {'max_length': '40'}),
'file': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'to': "orm['sentry.File']"}),
'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}),
'object_name': ('django.db.models.fields.TextField', [], {}),
'project': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'to': "orm['sentry.Project']", 'null': 'True'}),
'uuid': ('django.db.models.fields.CharField', [], {'max_length': '36'})
},
'sentry.projectkey': {
'Meta': {'object_name': 'ProjectKey'},
'date_added': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'null': 'True'}),
'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}),
'label': ('django.db.models.fields.CharField', [], {'max_length': '64', 'null': 'True', 'blank': 'True'}),
'project': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'related_name': "'key_set'", 'to': "orm['sentry.Project']"}),
'public_key': ('django.db.models.fields.CharField', [], {'max_length': '32', 'unique': 'True', 'null': 'True'}),
'roles': ('django.db.models.fields.BigIntegerField', [], {'default': '1'}),
'secret_key': ('django.db.models.fields.CharField', [], {'max_length': '32', 'unique': 'True', 'null': 'True'}),
'status': ('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {'default': '0', 'db_index': 'True'})
},
'sentry.projectoption': {
'Meta': {'unique_together': "(('project', 'key'),)", 'object_name': 'ProjectOption', 'db_table': "'sentry_projectoptions'"},
'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}),
'key': ('django.db.models.fields.CharField', [], {'max_length': '64'}),
'project': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'to': "orm['sentry.Project']"}),
'value': ('sentry.db.models.fields.pickle.UnicodePickledObjectField', [], {})
},
'sentry.projectplatform': {
'Meta': {'unique_together': "(('project_id', 'platform'),)", 'object_name': 'ProjectPlatform'},
'date_added': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}),
'last_seen': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'platform': ('django.db.models.fields.CharField', [], {'max_length': '64'}),
'project_id': ('sentry.db.models.fields.bounded.BoundedBigIntegerField', [], {})
},
'sentry.release': {
'Meta': {'unique_together': "(('project_id', 'version'),)", 'object_name': 'Release'},
'data': ('jsonfield.fields.JSONField', [], {'default': '{}'}),
'date_added': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'date_released': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}),
'date_started': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}),
'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}),
'new_groups': ('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {'default': '0'}),
'organization': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'to': "orm['sentry.Organization']"}),
'owner': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'to': "orm['sentry.User']", 'null': 'True', 'blank': 'True'}),
'project_id': ('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {'null': 'True'}),
'projects': ('django.db.models.fields.related.ManyToManyField', [], {'related_name': "'releases'", 'symmetrical': 'False', 'through': "orm['sentry.ReleaseProject']", 'to': "orm['sentry.Project']"}),
'ref': ('django.db.models.fields.CharField', [], {'max_length': '64', 'null': 'True', 'blank': 'True'}),
'url': ('django.db.models.fields.URLField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'}),
'version': ('django.db.models.fields.CharField', [], {'max_length': '64'})
},
'sentry.releasecommit': {
'Meta': {'unique_together': "(('release', 'commit'), ('release', 'order'))", 'object_name': 'ReleaseCommit'},
'commit': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'to': "orm['sentry.Commit']"}),
'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}),
'order': ('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {}),
'organization_id': ('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {'db_index': 'True'}),
'project_id': ('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {'null': 'True', 'db_index': 'True'}),
'release': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'to': "orm['sentry.Release']"})
},
'sentry.releaseenvironment': {
'Meta': {'unique_together': "(('project_id', 'release_id', 'environment_id'),)", 'object_name': 'ReleaseEnvironment', 'db_table': "'sentry_environmentrelease'"},
'environment_id': ('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {'db_index': 'True'}),
'first_seen': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}),
'last_seen': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'db_index': 'True'}),
'organization_id': ('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {'db_index': 'True'}),
'project_id': ('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {'db_index': 'True'}),
'release_id': ('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {'db_index': 'True'})
},
'sentry.releasefile': {
'Meta': {'unique_together': "(('release', 'ident'),)", 'object_name': 'ReleaseFile'},
'file': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'to': "orm['sentry.File']"}),
'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}),
'ident': ('django.db.models.fields.CharField', [], {'max_length': '40'}),
'name': ('django.db.models.fields.TextField', [], {}),
'organization': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'to': "orm['sentry.Organization']"}),
'project_id': ('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {'null': 'True'}),
'release': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'to': "orm['sentry.Release']"})
},
'sentry.releaseproject': {
'Meta': {'unique_together': "(('project', 'release'),)", 'object_name': 'ReleaseProject', 'db_table': "'sentry_release_project'"},
'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}),
'new_groups': ('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {'default': '0', 'null': 'True'}),
'project': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'to': "orm['sentry.Project']"}),
'release': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'to': "orm['sentry.Release']"})
},
'sentry.repository': {
'Meta': {'unique_together': "(('organization_id', 'name'), ('organization_id', 'provider', 'external_id'))", 'object_name': 'Repository'},
'config': ('jsonfield.fields.JSONField', [], {'default': '{}'}),
'date_added': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'external_id': ('django.db.models.fields.CharField', [], {'max_length': '64', 'null': 'True'}),
'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '200'}),
'organization_id': ('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {'db_index': 'True'}),
'provider': ('django.db.models.fields.CharField', [], {'max_length': '64', 'null': 'True'}),
'status': ('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {'default': '0', 'db_index': 'True'}),
'url': ('django.db.models.fields.URLField', [], {'max_length': '200', 'null': 'True'})
},
'sentry.rule': {
'Meta': {'object_name': 'Rule'},
'data': ('sentry.db.models.fields.gzippeddict.GzippedDictField', [], {}),
'date_added': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}),
'label': ('django.db.models.fields.CharField', [], {'max_length': '64'}),
'project': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'to': "orm['sentry.Project']"}),
'status': ('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {'default': '0', 'db_index': 'True'})
},
'sentry.savedsearch': {
'Meta': {'unique_together': "(('project', 'name'),)", 'object_name': 'SavedSearch'},
'date_added': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}),
'is_default': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '128'}),
'project': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'to': "orm['sentry.Project']"}),
'query': ('django.db.models.fields.TextField', [], {})
},
'sentry.savedsearchuserdefault': {
'Meta': {'unique_together': "(('project', 'user'),)", 'object_name': 'SavedSearchUserDefault', 'db_table': "'sentry_savedsearch_userdefault'"},
'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}),
'project': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'to': "orm['sentry.Project']"}),
'savedsearch': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'to': "orm['sentry.SavedSearch']"}),
'user': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'to': "orm['sentry.User']"})
},
'sentry.tagkey': {
'Meta': {'unique_together': "(('project', 'key'),)", 'object_name': 'TagKey', 'db_table': "'sentry_filterkey'"},
'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}),
'key': ('django.db.models.fields.CharField', [], {'max_length': '32'}),
'label': ('django.db.models.fields.CharField', [], {'max_length': '64', 'null': 'True'}),
'project': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'to': "orm['sentry.Project']"}),
'status': ('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {'default': '0'}),
'values_seen': ('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {'default': '0'})
},
'sentry.tagvalue': {
'Meta': {'unique_together': "(('project', 'key', 'value'),)", 'object_name': 'TagValue', 'db_table': "'sentry_filtervalue'"},
'data': ('sentry.db.models.fields.gzippeddict.GzippedDictField', [], {'null': 'True', 'blank': 'True'}),
'first_seen': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'null': 'True', 'db_index': 'True'}),
'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}),
'key': ('django.db.models.fields.CharField', [], {'max_length': '32'}),
'last_seen': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'null': 'True', 'db_index': 'True'}),
'project': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'to': "orm['sentry.Project']", 'null': 'True'}),
'times_seen': ('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {'default': '0'}),
'value': ('django.db.models.fields.CharField', [], {'max_length': '200'})
},
'sentry.team': {
'Meta': {'unique_together': "(('organization', 'slug'),)", 'object_name': 'Team'},
'date_added': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'null': 'True'}),
'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '64'}),
'organization': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'to': "orm['sentry.Organization']"}),
'slug': ('django.db.models.fields.SlugField', [], {'max_length': '50'}),
'status': ('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {'default': '0'})
},
'sentry.user': {
'Meta': {'object_name': 'User', 'db_table': "'auth_user'"},
'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}),
'id': ('sentry.db.models.fields.bounded.BoundedAutoField', [], {'primary_key': 'True'}),
'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'is_managed': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'is_password_expired': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'last_password_change': ('django.db.models.fields.DateTimeField', [], {'null': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '200', 'db_column': "'first_name'", 'blank': 'True'}),
'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}),
'session_nonce': ('django.db.models.fields.CharField', [], {'max_length': '12', 'null': 'True'}),
'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '128'})
},
'sentry.useravatar': {
'Meta': {'object_name': 'UserAvatar'},
'avatar_type': ('django.db.models.fields.PositiveSmallIntegerField', [], {'default': '0'}),
'file': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'to': "orm['sentry.File']", 'unique': 'True', 'null': 'True', 'on_delete': 'models.SET_NULL'}),
'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}),
'ident': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '32', 'db_index': 'True'}),
'user': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'related_name': "'avatar'", 'unique': 'True', 'to': "orm['sentry.User']"})
},
'sentry.useremail': {
'Meta': {'unique_together': "(('user', 'email'),)", 'object_name': 'UserEmail'},
'date_hash_added': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'email': ('django.db.models.fields.EmailField', [], {'max_length': '75'}),
'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}),
'is_verified': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'user': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'related_name': "'emails'", 'to': "orm['sentry.User']"}),
'validation_hash': ('django.db.models.fields.CharField', [], {'default': "u'YoBVmHTt0YsiMNhguIQNLyBfDixmJ0rm'", 'max_length': '32'})
},
'sentry.useroption': {
'Meta': {'unique_together': "(('user', 'project', 'key'),)", 'object_name': 'UserOption'},
'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}),
'key': ('django.db.models.fields.CharField', [], {'max_length': '64'}),
'project': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'to': "orm['sentry.Project']", 'null': 'True'}),
'user': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'to': "orm['sentry.User']"}),
'value': ('sentry.db.models.fields.pickle.UnicodePickledObjectField', [], {})
},
'sentry.userreport': {
'Meta': {'unique_together': "(('project', 'event_id'),)", 'object_name': 'UserReport', 'index_together': "(('project', 'event_id'), ('project', 'date_added'))"},
'comments': ('django.db.models.fields.TextField', [], {}),
'date_added': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'email': ('django.db.models.fields.EmailField', [], {'max_length': '75'}),
'event_id': ('django.db.models.fields.CharField', [], {'max_length': '32'}),
'group': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'to': "orm['sentry.Group']", 'null': 'True'}),
'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '128'}),
'project': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'to': "orm['sentry.Project']"})
}
}
complete_apps = ['sentry']
symmetrical = True
|
sergio-incaser/odoo | refs/heads/8.0 | addons/web/__init__.py | 435 | import sys
# Mock deprecated openerp.addons.web.http module
import openerp.http
sys.modules['openerp.addons.web.http'] = openerp.http
http = openerp.http
import controllers
|
bhargav/scikit-learn | refs/heads/master | examples/ensemble/plot_adaboost_regression.py | 311 | """
======================================
Decision Tree Regression with AdaBoost
======================================
A decision tree is boosted using the AdaBoost.R2 [1] algorithm on a 1D
sinusoidal dataset with a small amount of Gaussian noise.
299 boosts (300 decision trees) is compared with a single decision tree
regressor. As the number of boosts is increased the regressor can fit more
detail.
.. [1] H. Drucker, "Improving Regressors using Boosting Techniques", 1997.
"""
print(__doc__)
# Author: Noel Dawe <noel.dawe@gmail.com>
#
# License: BSD 3 clause
# importing necessary libraries
import numpy as np
import matplotlib.pyplot as plt
from sklearn.tree import DecisionTreeRegressor
from sklearn.ensemble import AdaBoostRegressor
# Create the dataset
rng = np.random.RandomState(1)
X = np.linspace(0, 6, 100)[:, np.newaxis]
y = np.sin(X).ravel() + np.sin(6 * X).ravel() + rng.normal(0, 0.1, X.shape[0])
# Fit regression model
regr_1 = DecisionTreeRegressor(max_depth=4)
regr_2 = AdaBoostRegressor(DecisionTreeRegressor(max_depth=4),
n_estimators=300, random_state=rng)
regr_1.fit(X, y)
regr_2.fit(X, y)
# Predict
y_1 = regr_1.predict(X)
y_2 = regr_2.predict(X)
# Plot the results
plt.figure()
plt.scatter(X, y, c="k", label="training samples")
plt.plot(X, y_1, c="g", label="n_estimators=1", linewidth=2)
plt.plot(X, y_2, c="r", label="n_estimators=300", linewidth=2)
plt.xlabel("data")
plt.ylabel("target")
plt.title("Boosted Decision Tree Regression")
plt.legend()
plt.show()
|
alshedivat/tensorflow | refs/heads/master | tensorflow/contrib/image/python/kernel_tests/dense_image_warp_test.py | 9 | # 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.
# ==============================================================================
"""Tests for dense_image_warp."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import math
import numpy as np
from tensorflow.contrib.image.python.ops import dense_image_warp
from tensorflow.python.framework import constant_op
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import test_util
from tensorflow.python.ops import array_ops
from tensorflow.python.ops import gradients
from tensorflow.python.ops import math_ops
from tensorflow.python.ops import random_ops
from tensorflow.python.ops import variables
from tensorflow.python.platform import googletest
from tensorflow.python.training import adam
class DenseImageWarpTest(test_util.TensorFlowTestCase):
def setUp(self):
np.random.seed(0)
def test_interpolate_small_grid_ij(self):
grid = constant_op.constant(
[[0., 1., 2.], [3., 4., 5.], [6., 7., 8.]], shape=[1, 3, 3, 1])
query_points = constant_op.constant(
[[0., 0.], [1., 0.], [2., 0.5], [1.5, 1.5]], shape=[1, 4, 2])
expected_results = np.reshape(np.array([0., 3., 6.5, 6.]), [1, 4, 1])
interp = dense_image_warp._interpolate_bilinear(grid, query_points)
with self.cached_session() as sess:
predicted = sess.run(interp)
self.assertAllClose(expected_results, predicted)
def test_interpolate_small_grid_xy(self):
grid = constant_op.constant(
[[0., 1., 2.], [3., 4., 5.], [6., 7., 8.]], shape=[1, 3, 3, 1])
query_points = constant_op.constant(
[[0., 0.], [0., 1.], [0.5, 2.0], [1.5, 1.5]], shape=[1, 4, 2])
expected_results = np.reshape(np.array([0., 3., 6.5, 6.]), [1, 4, 1])
interp = dense_image_warp._interpolate_bilinear(
grid, query_points, indexing='xy')
with self.cached_session() as sess:
predicted = sess.run(interp)
self.assertAllClose(expected_results, predicted)
def test_interpolate_small_grid_batched(self):
grid = constant_op.constant(
[[[0., 1.], [3., 4.]], [[5., 6.], [7., 8.]]], shape=[2, 2, 2, 1])
query_points = constant_op.constant([[[0., 0.], [1., 0.], [0.5, 0.5]],
[[0.5, 0.], [1., 0.], [1., 1.]]])
expected_results = np.reshape(
np.array([[0., 3., 2.], [6., 7., 8.]]), [2, 3, 1])
interp = dense_image_warp._interpolate_bilinear(grid, query_points)
with self.cached_session() as sess:
predicted = sess.run(interp)
self.assertAllClose(expected_results, predicted)
def get_image_and_flow_placeholders(self, shape, image_type, flow_type):
batch_size, height, width, numchannels = shape
image_shape = [batch_size, height, width, numchannels]
flow_shape = [batch_size, height, width, 2]
tf_type = {
'float16': dtypes.half,
'float32': dtypes.float32,
'float64': dtypes.float64
}
image = array_ops.placeholder(dtype=tf_type[image_type], shape=image_shape)
flows = array_ops.placeholder(dtype=tf_type[flow_type], shape=flow_shape)
return image, flows
def get_random_image_and_flows(self, shape, image_type, flow_type):
batch_size, height, width, numchannels = shape
image_shape = [batch_size, height, width, numchannels]
image = np.random.normal(size=image_shape)
flow_shape = [batch_size, height, width, 2]
flows = np.random.normal(size=flow_shape) * 3
return image.astype(image_type), flows.astype(flow_type)
def assert_correct_interpolation_value(self,
image,
flows,
pred_interpolation,
batch_index,
y_index,
x_index,
low_precision=False):
"""Assert that the tf interpolation matches hand-computed value."""
height = image.shape[1]
width = image.shape[2]
displacement = flows[batch_index, y_index, x_index, :]
float_y = y_index - displacement[0]
float_x = x_index - displacement[1]
floor_y = max(min(height - 2, math.floor(float_y)), 0)
floor_x = max(min(width - 2, math.floor(float_x)), 0)
ceil_y = floor_y + 1
ceil_x = floor_x + 1
alpha_y = min(max(0.0, float_y - floor_y), 1.0)
alpha_x = min(max(0.0, float_x - floor_x), 1.0)
floor_y = int(floor_y)
floor_x = int(floor_x)
ceil_y = int(ceil_y)
ceil_x = int(ceil_x)
top_left = image[batch_index, floor_y, floor_x, :]
top_right = image[batch_index, floor_y, ceil_x, :]
bottom_left = image[batch_index, ceil_y, floor_x, :]
bottom_right = image[batch_index, ceil_y, ceil_x, :]
interp_top = alpha_x * (top_right - top_left) + top_left
interp_bottom = alpha_x * (bottom_right - bottom_left) + bottom_left
interp = alpha_y * (interp_bottom - interp_top) + interp_top
atol = 1e-6
rtol = 1e-6
if low_precision:
atol = 1e-2
rtol = 1e-3
self.assertAllClose(
interp,
pred_interpolation[batch_index, y_index, x_index, :],
atol=atol,
rtol=rtol)
def check_zero_flow_correctness(self, shape, image_type, flow_type):
"""Assert using zero flows doesn't change the input image."""
image, flows = self.get_image_and_flow_placeholders(shape, image_type,
flow_type)
interp = dense_image_warp.dense_image_warp(image, flows)
with self.cached_session() as sess:
rand_image, rand_flows = self.get_random_image_and_flows(
shape, image_type, flow_type)
rand_flows *= 0
predicted_interpolation = sess.run(
interp, feed_dict={
image: rand_image,
flows: rand_flows
})
self.assertAllClose(rand_image, predicted_interpolation)
def test_zero_flows(self):
"""Apply check_zero_flow_correctness() for a few sizes and types."""
shapes_to_try = [[3, 4, 5, 6], [1, 2, 2, 1]]
for shape in shapes_to_try:
self.check_zero_flow_correctness(
shape, image_type='float32', flow_type='float32')
def check_interpolation_correctness(self,
shape,
image_type,
flow_type,
num_probes=5):
"""Interpolate, and then assert correctness for a few query locations."""
image, flows = self.get_image_and_flow_placeholders(shape, image_type,
flow_type)
interp = dense_image_warp.dense_image_warp(image, flows)
low_precision = image_type == 'float16' or flow_type == 'float16'
with self.cached_session() as sess:
rand_image, rand_flows = self.get_random_image_and_flows(
shape, image_type, flow_type)
pred_interpolation = sess.run(
interp, feed_dict={
image: rand_image,
flows: rand_flows
})
for _ in range(num_probes):
batch_index = np.random.randint(0, shape[0])
y_index = np.random.randint(0, shape[1])
x_index = np.random.randint(0, shape[2])
self.assert_correct_interpolation_value(
rand_image,
rand_flows,
pred_interpolation,
batch_index,
y_index,
x_index,
low_precision=low_precision)
def test_interpolation(self):
"""Apply check_interpolation_correctness() for a few sizes and types."""
shapes_to_try = [[3, 4, 5, 6], [1, 5, 5, 3], [1, 2, 2, 1]]
for im_type in ['float32', 'float64', 'float16']:
for flow_type in ['float32', 'float64', 'float16']:
for shape in shapes_to_try:
self.check_interpolation_correctness(shape, im_type, flow_type)
def test_gradients_exist(self):
"""Check that backprop can run.
The correctness of the gradients is assumed, since the forward propagation
is tested to be correct and we only use built-in tf ops.
However, we perform a simple test to make sure that backprop can actually
run. We treat the flows as a tf.Variable and optimize them to minimize
the difference between the interpolated image and the input image.
"""
batch_size, height, width, numchannels = [4, 5, 6, 7]
image_shape = [batch_size, height, width, numchannels]
image = random_ops.random_normal(image_shape)
flow_shape = [batch_size, height, width, 2]
init_flows = np.float32(np.random.normal(size=flow_shape) * 0.25)
flows = variables.Variable(init_flows)
interp = dense_image_warp.dense_image_warp(image, flows)
loss = math_ops.reduce_mean(math_ops.square(interp - image))
optimizer = adam.AdamOptimizer(1.0)
grad = gradients.gradients(loss, [flows])
opt_func = optimizer.apply_gradients(zip(grad, [flows]))
init_op = variables.global_variables_initializer()
with self.cached_session() as sess:
sess.run(init_op)
for _ in range(10):
sess.run(opt_func)
def test_size_exception(self):
"""Make sure it throws an exception for images that are too small."""
shape = [1, 2, 1, 1]
msg = 'Should have raised an exception for invalid image size'
with self.assertRaises(ValueError, msg=msg):
self.check_interpolation_correctness(shape, 'float32', 'float32')
if __name__ == '__main__':
googletest.main()
|
devendermishrajio/nova | refs/heads/master | nova/tests/unit/keymgr/test_key.py | 93 | # Copyright (c) 2013 The Johns Hopkins University/Applied Physics Laboratory
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
"""
Test cases for the key classes.
"""
import array
from nova.keymgr import key
from nova import test
class KeyTestCase(test.NoDBTestCase):
def _create_key(self):
raise NotImplementedError()
def setUp(self):
super(KeyTestCase, self).setUp()
self.key = self._create_key()
class SymmetricKeyTestCase(KeyTestCase):
def _create_key(self):
return key.SymmetricKey(self.algorithm, self.encoded)
def setUp(self):
self.algorithm = 'AES'
self.encoded = array.array('B', ('0' * 64).decode('hex')).tolist()
super(SymmetricKeyTestCase, self).setUp()
def test_get_algorithm(self):
self.assertEqual(self.key.get_algorithm(), self.algorithm)
def test_get_format(self):
self.assertEqual(self.key.get_format(), 'RAW')
def test_get_encoded(self):
self.assertEqual(self.key.get_encoded(), self.encoded)
def test___eq__(self):
self.assertTrue(self.key == self.key)
self.assertFalse(self.key is None)
self.assertFalse(None == self.key)
def test___ne__(self):
self.assertFalse(self.key != self.key)
self.assertTrue(self.key is not None)
self.assertTrue(None != self.key)
|
ojii/sandlib | refs/heads/master | lib/lib-python/2.7/_abcoll.py | 218 | # Copyright 2007 Google, Inc. All Rights Reserved.
# Licensed to PSF under a Contributor Agreement.
"""Abstract Base Classes (ABCs) for collections, according to PEP 3119.
DON'T USE THIS MODULE DIRECTLY! The classes here should be imported
via collections; they are defined here only to alleviate certain
bootstrapping issues. Unit tests are in test_collections.
"""
from abc import ABCMeta, abstractmethod
import sys
__all__ = ["Hashable", "Iterable", "Iterator",
"Sized", "Container", "Callable",
"Set", "MutableSet",
"Mapping", "MutableMapping",
"MappingView", "KeysView", "ItemsView", "ValuesView",
"Sequence", "MutableSequence",
]
### ONE-TRICK PONIES ###
def _hasattr(C, attr):
try:
return any(attr in B.__dict__ for B in C.__mro__)
except AttributeError:
# Old-style class
return hasattr(C, attr)
class Hashable:
__metaclass__ = ABCMeta
@abstractmethod
def __hash__(self):
return 0
@classmethod
def __subclasshook__(cls, C):
if cls is Hashable:
try:
for B in C.__mro__:
if "__hash__" in B.__dict__:
if B.__dict__["__hash__"]:
return True
break
except AttributeError:
# Old-style class
if getattr(C, "__hash__", None):
return True
return NotImplemented
class Iterable:
__metaclass__ = ABCMeta
@abstractmethod
def __iter__(self):
while False:
yield None
@classmethod
def __subclasshook__(cls, C):
if cls is Iterable:
if _hasattr(C, "__iter__"):
return True
return NotImplemented
Iterable.register(str)
class Iterator(Iterable):
@abstractmethod
def next(self):
raise StopIteration
def __iter__(self):
return self
@classmethod
def __subclasshook__(cls, C):
if cls is Iterator:
if _hasattr(C, "next") and _hasattr(C, "__iter__"):
return True
return NotImplemented
class Sized:
__metaclass__ = ABCMeta
@abstractmethod
def __len__(self):
return 0
@classmethod
def __subclasshook__(cls, C):
if cls is Sized:
if _hasattr(C, "__len__"):
return True
return NotImplemented
class Container:
__metaclass__ = ABCMeta
@abstractmethod
def __contains__(self, x):
return False
@classmethod
def __subclasshook__(cls, C):
if cls is Container:
if _hasattr(C, "__contains__"):
return True
return NotImplemented
class Callable:
__metaclass__ = ABCMeta
@abstractmethod
def __call__(self, *args, **kwds):
return False
@classmethod
def __subclasshook__(cls, C):
if cls is Callable:
if _hasattr(C, "__call__"):
return True
return NotImplemented
### SETS ###
class Set(Sized, Iterable, Container):
"""A set is a finite, iterable container.
This class provides concrete generic implementations of all
methods except for __contains__, __iter__ and __len__.
To override the comparisons (presumably for speed, as the
semantics are fixed), all you have to do is redefine __le__ and
then the other operations will automatically follow suit.
"""
def __le__(self, other):
if not isinstance(other, Set):
return NotImplemented
if len(self) > len(other):
return False
for elem in self:
if elem not in other:
return False
return True
def __lt__(self, other):
if not isinstance(other, Set):
return NotImplemented
return len(self) < len(other) and self.__le__(other)
def __gt__(self, other):
if not isinstance(other, Set):
return NotImplemented
return other < self
def __ge__(self, other):
if not isinstance(other, Set):
return NotImplemented
return other <= self
def __eq__(self, other):
if not isinstance(other, Set):
return NotImplemented
return len(self) == len(other) and self.__le__(other)
def __ne__(self, other):
return not (self == other)
@classmethod
def _from_iterable(cls, it):
'''Construct an instance of the class from any iterable input.
Must override this method if the class constructor signature
does not accept an iterable for an input.
'''
return cls(it)
def __and__(self, other):
if not isinstance(other, Iterable):
return NotImplemented
return self._from_iterable(value for value in other if value in self)
def isdisjoint(self, other):
for value in other:
if value in self:
return False
return True
def __or__(self, other):
if not isinstance(other, Iterable):
return NotImplemented
chain = (e for s in (self, other) for e in s)
return self._from_iterable(chain)
def __sub__(self, other):
if not isinstance(other, Set):
if not isinstance(other, Iterable):
return NotImplemented
other = self._from_iterable(other)
return self._from_iterable(value for value in self
if value not in other)
def __xor__(self, other):
if not isinstance(other, Set):
if not isinstance(other, Iterable):
return NotImplemented
other = self._from_iterable(other)
return (self - other) | (other - self)
# Sets are not hashable by default, but subclasses can change this
__hash__ = None
def _hash(self):
"""Compute the hash value of a set.
Note that we don't define __hash__: not all sets are hashable.
But if you define a hashable set type, its __hash__ should
call this function.
This must be compatible __eq__.
All sets ought to compare equal if they contain the same
elements, regardless of how they are implemented, and
regardless of the order of the elements; so there's not much
freedom for __eq__ or __hash__. We match the algorithm used
by the built-in frozenset type.
"""
MAX = sys.maxint
MASK = 2 * MAX + 1
n = len(self)
h = 1927868237 * (n + 1)
h &= MASK
for x in self:
hx = hash(x)
h ^= (hx ^ (hx << 16) ^ 89869747) * 3644798167
h &= MASK
h = h * 69069 + 907133923
h &= MASK
if h > MAX:
h -= MASK + 1
if h == -1:
h = 590923713
return h
Set.register(frozenset)
class MutableSet(Set):
@abstractmethod
def add(self, value):
"""Add an element."""
raise NotImplementedError
@abstractmethod
def discard(self, value):
"""Remove an element. Do not raise an exception if absent."""
raise NotImplementedError
def remove(self, value):
"""Remove an element. If not a member, raise a KeyError."""
if value not in self:
raise KeyError(value)
self.discard(value)
def pop(self):
"""Return the popped value. Raise KeyError if empty."""
it = iter(self)
try:
value = next(it)
except StopIteration:
raise KeyError
self.discard(value)
return value
def clear(self):
"""This is slow (creates N new iterators!) but effective."""
try:
while True:
self.pop()
except KeyError:
pass
def __ior__(self, it):
for value in it:
self.add(value)
return self
def __iand__(self, it):
for value in (self - it):
self.discard(value)
return self
def __ixor__(self, it):
if it is self:
self.clear()
else:
if not isinstance(it, Set):
it = self._from_iterable(it)
for value in it:
if value in self:
self.discard(value)
else:
self.add(value)
return self
def __isub__(self, it):
if it is self:
self.clear()
else:
for value in it:
self.discard(value)
return self
MutableSet.register(set)
### MAPPINGS ###
class Mapping(Sized, Iterable, Container):
@abstractmethod
def __getitem__(self, key):
raise KeyError
def get(self, key, default=None):
try:
return self[key]
except KeyError:
return default
def __contains__(self, key):
try:
self[key]
except KeyError:
return False
else:
return True
def iterkeys(self):
return iter(self)
def itervalues(self):
for key in self:
yield self[key]
def iteritems(self):
for key in self:
yield (key, self[key])
def keys(self):
return list(self)
def items(self):
return [(key, self[key]) for key in self]
def values(self):
return [self[key] for key in self]
# Mappings are not hashable by default, but subclasses can change this
__hash__ = None
def __eq__(self, other):
if not isinstance(other, Mapping):
return NotImplemented
return dict(self.items()) == dict(other.items())
def __ne__(self, other):
return not (self == other)
class MappingView(Sized):
def __init__(self, mapping):
self._mapping = mapping
def __len__(self):
return len(self._mapping)
def __repr__(self):
return '{0.__class__.__name__}({0._mapping!r})'.format(self)
class KeysView(MappingView, Set):
@classmethod
def _from_iterable(self, it):
return set(it)
def __contains__(self, key):
return key in self._mapping
def __iter__(self):
for key in self._mapping:
yield key
class ItemsView(MappingView, Set):
@classmethod
def _from_iterable(self, it):
return set(it)
def __contains__(self, item):
key, value = item
try:
v = self._mapping[key]
except KeyError:
return False
else:
return v == value
def __iter__(self):
for key in self._mapping:
yield (key, self._mapping[key])
class ValuesView(MappingView):
def __contains__(self, value):
for key in self._mapping:
if value == self._mapping[key]:
return True
return False
def __iter__(self):
for key in self._mapping:
yield self._mapping[key]
class MutableMapping(Mapping):
@abstractmethod
def __setitem__(self, key, value):
raise KeyError
@abstractmethod
def __delitem__(self, key):
raise KeyError
__marker = object()
def pop(self, key, default=__marker):
try:
value = self[key]
except KeyError:
if default is self.__marker:
raise
return default
else:
del self[key]
return value
def popitem(self):
try:
key = next(iter(self))
except StopIteration:
raise KeyError
value = self[key]
del self[key]
return key, value
def clear(self):
try:
while True:
self.popitem()
except KeyError:
pass
def update(*args, **kwds):
if len(args) > 2:
raise TypeError("update() takes at most 2 positional "
"arguments ({} given)".format(len(args)))
elif not args:
raise TypeError("update() takes at least 1 argument (0 given)")
self = args[0]
other = args[1] if len(args) >= 2 else ()
if isinstance(other, Mapping):
for key in other:
self[key] = other[key]
elif hasattr(other, "keys"):
for key in other.keys():
self[key] = other[key]
else:
for key, value in other:
self[key] = value
for key, value in kwds.items():
self[key] = value
def setdefault(self, key, default=None):
try:
return self[key]
except KeyError:
self[key] = default
return default
MutableMapping.register(dict)
### SEQUENCES ###
class Sequence(Sized, Iterable, Container):
"""All the operations on a read-only sequence.
Concrete subclasses must override __new__ or __init__,
__getitem__, and __len__.
"""
@abstractmethod
def __getitem__(self, index):
raise IndexError
def __iter__(self):
i = 0
try:
while True:
v = self[i]
yield v
i += 1
except IndexError:
return
def __contains__(self, value):
for v in self:
if v == value:
return True
return False
def __reversed__(self):
for i in reversed(range(len(self))):
yield self[i]
def index(self, value):
for i, v in enumerate(self):
if v == value:
return i
raise ValueError
def count(self, value):
return sum(1 for v in self if v == value)
Sequence.register(tuple)
Sequence.register(basestring)
Sequence.register(buffer)
Sequence.register(xrange)
class MutableSequence(Sequence):
@abstractmethod
def __setitem__(self, index, value):
raise IndexError
@abstractmethod
def __delitem__(self, index):
raise IndexError
@abstractmethod
def insert(self, index, value):
raise IndexError
def append(self, value):
self.insert(len(self), value)
def reverse(self):
n = len(self)
for i in range(n//2):
self[i], self[n-i-1] = self[n-i-1], self[i]
def extend(self, values):
for v in values:
self.append(v)
def pop(self, index=-1):
v = self[index]
del self[index]
return v
def remove(self, value):
del self[self.index(value)]
def __iadd__(self, values):
self.extend(values)
return self
MutableSequence.register(list)
|
gabrielfalcao/lettuce | refs/heads/master | tests/integration/lib/Django-1.2.5/django/contrib/gis/db/backends/mysql/base.py | 308 | from django.db.backends.mysql.base import *
from django.db.backends.mysql.base import DatabaseWrapper as MySQLDatabaseWrapper
from django.contrib.gis.db.backends.mysql.creation import MySQLCreation
from django.contrib.gis.db.backends.mysql.introspection import MySQLIntrospection
from django.contrib.gis.db.backends.mysql.operations import MySQLOperations
class DatabaseWrapper(MySQLDatabaseWrapper):
def __init__(self, *args, **kwargs):
super(DatabaseWrapper, self).__init__(*args, **kwargs)
self.creation = MySQLCreation(self)
self.ops = MySQLOperations()
self.introspection = MySQLIntrospection(self)
|
anhstudios/swganh | refs/heads/develop | data/scripts/templates/object/installation/base/shared_construction_installation_base.py | 2 | #### NOTICE: THIS FILE IS AUTOGENERATED
#### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY
#### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES
from swgpy.object import *
def create(kernel):
result = Installation()
result.template = "object/installation/base/shared_construction_installation_base.iff"
result.attribute_template_id = -1
result.stfName("player_structure","temporary_structure")
#### BEGIN MODIFICATIONS ####
#### END MODIFICATIONS ####
return result |
idovear/odoo | refs/heads/master | openerp/addons/test_convert/__openerp__.py | 437 | {
'name': 'test_convert',
'description': "Data for xml conversion tests",
'version': '0.0.1',
}
|
mhoffma/micropython | refs/heads/master | tests/misc/print_exception.py | 18 | try:
import uio as io
except ImportError:
import io
import sys
if hasattr(sys, 'print_exception'):
print_exception = sys.print_exception
else:
import traceback
print_exception = lambda e, f: traceback.print_exception(None, e, sys.exc_info()[2], file=f)
def print_exc(e):
buf = io.StringIO()
print_exception(e, buf)
s = buf.getvalue()
for l in s.split("\n"):
# uPy on pyboard prints <stdin> as file, so remove filename.
if l.startswith(" File "):
l = l.split('"')
print(l[0], l[2])
# uPy and CPy tracebacks differ in that CPy prints a source line for
# each traceback entry. In this case, we know that offending line
# has 4-space indent, so filter it out.
elif not l.startswith(" "):
print(l)
# basic exception message
try:
1/0
except Exception as e:
print('caught')
print_exc(e)
# exception message with more than 1 source-code line
def f():
g()
def g():
2/0
try:
f()
except Exception as e:
print('caught')
print_exc(e)
|
jonashaag/django-floppyforms | refs/heads/master | floppyforms/test_settings.py | 1 | DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': 'floppyforms.sqlite',
},
}
INSTALLED_APPS = [
'django.contrib.gis',
'floppyforms',
'floppyforms.tests',
]
STATIC_URL = '/static/'
TEST_RUNNER = 'discover_runner.DiscoverRunner'
SECRET_KEY = '0'
|
gangadharkadam/vlinkerp | refs/heads/master | erpnext/hr/doctype/salary_manager/__init__.py | 16 | # ERPNext - web based ERP (http://erpnext.com)
# Copyright (C) 2012 Frappe Technologies Pvt 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/>.
from __future__ import unicode_literals
from frappe import ValidationError
class SalarySlipExistsError(ValidationError): pass
|
flwh/KK_mt6589_iq451 | refs/heads/master | prebuilts/python/linux-x86/2.7.5/lib/python2.7/json/encoder.py | 105 | """Implementation of JSONEncoder
"""
import re
try:
from _json import encode_basestring_ascii as c_encode_basestring_ascii
except ImportError:
c_encode_basestring_ascii = None
try:
from _json import make_encoder as c_make_encoder
except ImportError:
c_make_encoder = None
ESCAPE = re.compile(r'[\x00-\x1f\\"\b\f\n\r\t]')
ESCAPE_ASCII = re.compile(r'([\\"]|[^\ -~])')
HAS_UTF8 = re.compile(r'[\x80-\xff]')
ESCAPE_DCT = {
'\\': '\\\\',
'"': '\\"',
'\b': '\\b',
'\f': '\\f',
'\n': '\\n',
'\r': '\\r',
'\t': '\\t',
}
for i in range(0x20):
ESCAPE_DCT.setdefault(chr(i), '\\u{0:04x}'.format(i))
#ESCAPE_DCT.setdefault(chr(i), '\\u%04x' % (i,))
INFINITY = float('inf')
FLOAT_REPR = repr
def encode_basestring(s):
"""Return a JSON representation of a Python string
"""
def replace(match):
return ESCAPE_DCT[match.group(0)]
return '"' + ESCAPE.sub(replace, s) + '"'
def py_encode_basestring_ascii(s):
"""Return an ASCII-only JSON representation of a Python string
"""
if isinstance(s, str) and HAS_UTF8.search(s) is not None:
s = s.decode('utf-8')
def replace(match):
s = match.group(0)
try:
return ESCAPE_DCT[s]
except KeyError:
n = ord(s)
if n < 0x10000:
return '\\u{0:04x}'.format(n)
#return '\\u%04x' % (n,)
else:
# surrogate pair
n -= 0x10000
s1 = 0xd800 | ((n >> 10) & 0x3ff)
s2 = 0xdc00 | (n & 0x3ff)
return '\\u{0:04x}\\u{1:04x}'.format(s1, s2)
#return '\\u%04x\\u%04x' % (s1, s2)
return '"' + str(ESCAPE_ASCII.sub(replace, s)) + '"'
encode_basestring_ascii = (
c_encode_basestring_ascii or py_encode_basestring_ascii)
class JSONEncoder(object):
"""Extensible JSON <http://json.org> encoder for Python data structures.
Supports the following objects and types by default:
+-------------------+---------------+
| Python | JSON |
+===================+===============+
| dict | object |
+-------------------+---------------+
| list, tuple | array |
+-------------------+---------------+
| str, unicode | string |
+-------------------+---------------+
| int, long, float | number |
+-------------------+---------------+
| True | true |
+-------------------+---------------+
| False | false |
+-------------------+---------------+
| None | null |
+-------------------+---------------+
To extend this to recognize other objects, subclass and implement a
``.default()`` method with another method that returns a serializable
object for ``o`` if possible, otherwise it should call the superclass
implementation (to raise ``TypeError``).
"""
item_separator = ', '
key_separator = ': '
def __init__(self, skipkeys=False, ensure_ascii=True,
check_circular=True, allow_nan=True, sort_keys=False,
indent=None, separators=None, encoding='utf-8', default=None):
"""Constructor for JSONEncoder, with sensible defaults.
If skipkeys is false, then it is a TypeError to attempt
encoding of keys that are not str, int, long, float or None. If
skipkeys is True, such items are simply skipped.
If *ensure_ascii* is true (the default), all non-ASCII
characters in the output are escaped with \uXXXX sequences,
and the results are str instances consisting of ASCII
characters only. If ensure_ascii is False, a result may be a
unicode instance. This usually happens if the input contains
unicode strings or the *encoding* parameter is used.
If check_circular is true, then lists, dicts, and custom encoded
objects will be checked for circular references during encoding to
prevent an infinite recursion (which would cause an OverflowError).
Otherwise, no such check takes place.
If allow_nan is true, then NaN, Infinity, and -Infinity will be
encoded as such. This behavior is not JSON specification compliant,
but is consistent with most JavaScript based encoders and decoders.
Otherwise, it will be a ValueError to encode such floats.
If sort_keys is true, then the output of dictionaries will be
sorted by key; this is useful for regression tests to ensure
that JSON serializations can be compared on a day-to-day basis.
If indent is a non-negative integer, then JSON array
elements and object members will be pretty-printed with that
indent level. An indent level of 0 will only insert newlines.
None is the most compact representation. Since the default
item separator is ', ', the output might include trailing
whitespace when indent is specified. You can use
separators=(',', ': ') to avoid this.
If specified, separators should be a (item_separator, key_separator)
tuple. The default is (', ', ': '). To get the most compact JSON
representation you should specify (',', ':') to eliminate whitespace.
If specified, default is a function that gets called for objects
that can't otherwise be serialized. It should return a JSON encodable
version of the object or raise a ``TypeError``.
If encoding is not None, then all input strings will be
transformed into unicode using that encoding prior to JSON-encoding.
The default is UTF-8.
"""
self.skipkeys = skipkeys
self.ensure_ascii = ensure_ascii
self.check_circular = check_circular
self.allow_nan = allow_nan
self.sort_keys = sort_keys
self.indent = indent
if separators is not None:
self.item_separator, self.key_separator = separators
if default is not None:
self.default = default
self.encoding = encoding
def default(self, o):
"""Implement this method in a subclass such that it returns
a serializable object for ``o``, or calls the base implementation
(to raise a ``TypeError``).
For example, to support arbitrary iterators, you could
implement default like this::
def default(self, o):
try:
iterable = iter(o)
except TypeError:
pass
else:
return list(iterable)
# Let the base class default method raise the TypeError
return JSONEncoder.default(self, o)
"""
raise TypeError(repr(o) + " is not JSON serializable")
def encode(self, o):
"""Return a JSON string representation of a Python data structure.
>>> JSONEncoder().encode({"foo": ["bar", "baz"]})
'{"foo": ["bar", "baz"]}'
"""
# This is for extremely simple cases and benchmarks.
if isinstance(o, basestring):
if isinstance(o, str):
_encoding = self.encoding
if (_encoding is not None
and not (_encoding == 'utf-8')):
o = o.decode(_encoding)
if self.ensure_ascii:
return encode_basestring_ascii(o)
else:
return encode_basestring(o)
# This doesn't pass the iterator directly to ''.join() because the
# exceptions aren't as detailed. The list call should be roughly
# equivalent to the PySequence_Fast that ''.join() would do.
chunks = self.iterencode(o, _one_shot=True)
if not isinstance(chunks, (list, tuple)):
chunks = list(chunks)
return ''.join(chunks)
def iterencode(self, o, _one_shot=False):
"""Encode the given object and yield each string
representation as available.
For example::
for chunk in JSONEncoder().iterencode(bigobject):
mysocket.write(chunk)
"""
if self.check_circular:
markers = {}
else:
markers = None
if self.ensure_ascii:
_encoder = encode_basestring_ascii
else:
_encoder = encode_basestring
if self.encoding != 'utf-8':
def _encoder(o, _orig_encoder=_encoder, _encoding=self.encoding):
if isinstance(o, str):
o = o.decode(_encoding)
return _orig_encoder(o)
def floatstr(o, allow_nan=self.allow_nan,
_repr=FLOAT_REPR, _inf=INFINITY, _neginf=-INFINITY):
# Check for specials. Note that this type of test is processor
# and/or platform-specific, so do tests which don't depend on the
# internals.
if o != o:
text = 'NaN'
elif o == _inf:
text = 'Infinity'
elif o == _neginf:
text = '-Infinity'
else:
return _repr(o)
if not allow_nan:
raise ValueError(
"Out of range float values are not JSON compliant: " +
repr(o))
return text
if (_one_shot and c_make_encoder is not None
and self.indent is None and not self.sort_keys):
_iterencode = c_make_encoder(
markers, self.default, _encoder, self.indent,
self.key_separator, self.item_separator, self.sort_keys,
self.skipkeys, self.allow_nan)
else:
_iterencode = _make_iterencode(
markers, self.default, _encoder, self.indent, floatstr,
self.key_separator, self.item_separator, self.sort_keys,
self.skipkeys, _one_shot)
return _iterencode(o, 0)
def _make_iterencode(markers, _default, _encoder, _indent, _floatstr,
_key_separator, _item_separator, _sort_keys, _skipkeys, _one_shot,
## HACK: hand-optimized bytecode; turn globals into locals
ValueError=ValueError,
basestring=basestring,
dict=dict,
float=float,
id=id,
int=int,
isinstance=isinstance,
list=list,
long=long,
str=str,
tuple=tuple,
):
def _iterencode_list(lst, _current_indent_level):
if not lst:
yield '[]'
return
if markers is not None:
markerid = id(lst)
if markerid in markers:
raise ValueError("Circular reference detected")
markers[markerid] = lst
buf = '['
if _indent is not None:
_current_indent_level += 1
newline_indent = '\n' + (' ' * (_indent * _current_indent_level))
separator = _item_separator + newline_indent
buf += newline_indent
else:
newline_indent = None
separator = _item_separator
first = True
for value in lst:
if first:
first = False
else:
buf = separator
if isinstance(value, basestring):
yield buf + _encoder(value)
elif value is None:
yield buf + 'null'
elif value is True:
yield buf + 'true'
elif value is False:
yield buf + 'false'
elif isinstance(value, (int, long)):
yield buf + str(value)
elif isinstance(value, float):
yield buf + _floatstr(value)
else:
yield buf
if isinstance(value, (list, tuple)):
chunks = _iterencode_list(value, _current_indent_level)
elif isinstance(value, dict):
chunks = _iterencode_dict(value, _current_indent_level)
else:
chunks = _iterencode(value, _current_indent_level)
for chunk in chunks:
yield chunk
if newline_indent is not None:
_current_indent_level -= 1
yield '\n' + (' ' * (_indent * _current_indent_level))
yield ']'
if markers is not None:
del markers[markerid]
def _iterencode_dict(dct, _current_indent_level):
if not dct:
yield '{}'
return
if markers is not None:
markerid = id(dct)
if markerid in markers:
raise ValueError("Circular reference detected")
markers[markerid] = dct
yield '{'
if _indent is not None:
_current_indent_level += 1
newline_indent = '\n' + (' ' * (_indent * _current_indent_level))
item_separator = _item_separator + newline_indent
yield newline_indent
else:
newline_indent = None
item_separator = _item_separator
first = True
if _sort_keys:
items = sorted(dct.items(), key=lambda kv: kv[0])
else:
items = dct.iteritems()
for key, value in items:
if isinstance(key, basestring):
pass
# JavaScript is weakly typed for these, so it makes sense to
# also allow them. Many encoders seem to do something like this.
elif isinstance(key, float):
key = _floatstr(key)
elif key is True:
key = 'true'
elif key is False:
key = 'false'
elif key is None:
key = 'null'
elif isinstance(key, (int, long)):
key = str(key)
elif _skipkeys:
continue
else:
raise TypeError("key " + repr(key) + " is not a string")
if first:
first = False
else:
yield item_separator
yield _encoder(key)
yield _key_separator
if isinstance(value, basestring):
yield _encoder(value)
elif value is None:
yield 'null'
elif value is True:
yield 'true'
elif value is False:
yield 'false'
elif isinstance(value, (int, long)):
yield str(value)
elif isinstance(value, float):
yield _floatstr(value)
else:
if isinstance(value, (list, tuple)):
chunks = _iterencode_list(value, _current_indent_level)
elif isinstance(value, dict):
chunks = _iterencode_dict(value, _current_indent_level)
else:
chunks = _iterencode(value, _current_indent_level)
for chunk in chunks:
yield chunk
if newline_indent is not None:
_current_indent_level -= 1
yield '\n' + (' ' * (_indent * _current_indent_level))
yield '}'
if markers is not None:
del markers[markerid]
def _iterencode(o, _current_indent_level):
if isinstance(o, basestring):
yield _encoder(o)
elif o is None:
yield 'null'
elif o is True:
yield 'true'
elif o is False:
yield 'false'
elif isinstance(o, (int, long)):
yield str(o)
elif isinstance(o, float):
yield _floatstr(o)
elif isinstance(o, (list, tuple)):
for chunk in _iterencode_list(o, _current_indent_level):
yield chunk
elif isinstance(o, dict):
for chunk in _iterencode_dict(o, _current_indent_level):
yield chunk
else:
if markers is not None:
markerid = id(o)
if markerid in markers:
raise ValueError("Circular reference detected")
markers[markerid] = o
o = _default(o)
for chunk in _iterencode(o, _current_indent_level):
yield chunk
if markers is not None:
del markers[markerid]
return _iterencode
|
DrDub/pilas | refs/heads/master | pilas/tutoriales.py | 5 | # -*- coding: utf-8 -*-
import os
import sys
try:
from PyQt4 import QtCore, QtGui
from .tutoriales_base import Ui_TutorialesWindow
except:
print("ERROR: No se encuentra pyqt")
Ui_TutorialesWindow = object
pass
import os
import pilas
class VentanaTutoriales(Ui_TutorialesWindow):
def setupUi(self, main):
self.main = main
Ui_TutorialesWindow.setupUi(self, main)
pilas.utils.centrar_ventana(main)
self.cargar_tutoriales()
def cargar_tutoriales(self):
file_path = pilas.utils.obtener_ruta_al_recurso('tutoriales/index.html')
file_path = os.path.abspath(file_path)
base_dir = QtCore.QUrl.fromLocalFile(file_path)
self.webView.load(base_dir)
self.webView.history().setMaximumItemCount(0)
def main(parent=None, do_raise=False):
dialog = QtGui.QMainWindow(parent)
dialog.setWindowFlags(dialog.windowFlags() | QtCore.Qt.WindowSystemMenuHint | QtCore.Qt.WindowMinMaxButtonsHint)
ui = VentanaTutoriales()
ui.setupUi(dialog)
dialog.setAttribute(QtCore.Qt.WA_DeleteOnClose)
#if sys.platform == 'darwin':
# if getattr(sys, 'frozen', None):
# dialog.showMinimized()
# dialog.showNormal()
dialog.show()
if do_raise:
dialog.raise_()
if __name__ == '__main__':
app = QtGui.QApplication(sys.argv)
app.setApplicationName("pilas-engine")
main()
|
ros2/ci | refs/heads/master | ros2_batch_job/vendor/osrf_pycommon/tests/unit/test_process_utils/impl_aep_asyncio.py | 2 | from osrf_pycommon.process_utils import asyncio
from osrf_pycommon.process_utils.async_execute_process import async_execute_process
from osrf_pycommon.process_utils import get_loop
from .impl_aep_protocol import create_protocol
loop = get_loop()
@asyncio.coroutine
def run(cmd, **kwargs):
transport, protocol = yield from async_execute_process(
create_protocol(), cmd, **kwargs)
retcode = yield from protocol.complete
return protocol.stdout_buffer, protocol.stderr_buffer, retcode
|
somehume/namebench | refs/heads/master | libnamebench/data_sources.py | 173 | #!/usr/bin/env python
# Copyright 2009 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Provides data sources to use for benchmarking."""
import ConfigParser
import glob
import os
import os.path
import random
import re
import subprocess
import sys
import time
# relative
import addr_util
import selectors
import util
# Pick the most accurate timer for a platform. Stolen from timeit.py:
if sys.platform[:3] == 'win':
DEFAULT_TIMER = time.clock
else:
DEFAULT_TIMER = time.time
GLOBAL_DATA_CACHE = {}
DEFAULT_CONFIG_PATH = 'config/data_sources.cfg'
MAX_NON_UNIQUE_RECORD_COUNT = 500000
MAX_FILE_MTIME_AGE_DAYS = 45
MIN_FILE_SIZE = 10000
MIN_RECOMMENDED_RECORD_COUNT = 200
MAX_FQDN_SYNTHESIZE_PERCENT = 4
class DataSources(object):
"""A collection of methods related to available hostname data sources."""
def __init__(self, config_path=DEFAULT_CONFIG_PATH, status_callback=None):
self.source_cache = GLOBAL_DATA_CACHE
self.source_config = {}
self.status_callback = status_callback
self._LoadConfigFromPath(config_path)
def msg(self, msg, **kwargs):
if self.status_callback:
self.status_callback(msg, **kwargs)
else:
print '- %s' % msg
def _LoadConfigFromPath(self, path):
"""Load a configuration file describing data sources that may be available."""
conf_file = util.FindDataFile(path)
config = ConfigParser.ConfigParser()
config.read(conf_file)
for section in config.sections():
if section not in self.source_config:
self.source_config[section] = {
'name': None,
'search_paths': set(),
'full_hostnames': True,
# Store whether or not this data source contains personal data
'synthetic': False,
'include_duplicates': False,
'max_mtime_days': MAX_FILE_MTIME_AGE_DAYS
}
for (key, value) in config.items(section):
if key == 'name':
self.source_config[section]['name'] = value
elif key == 'full_hostnames' and int(value) == 0:
self.source_config[section]['full_hostnames'] = False
elif key == 'max_mtime_days':
self.source_config[section]['max_mtime_days'] = int(value)
elif key == 'include_duplicates':
self.source_config[section]['include_duplicates'] = bool(value)
elif key == 'synthetic':
self.source_config[section]['synthetic'] = bool(value)
else:
self.source_config[section]['search_paths'].add(value)
def ListSourceTypes(self):
"""Get a list of all data sources we know about."""
return sorted(self.source_config.keys())
def ListSourcesWithDetails(self):
"""Get a list of all data sources found with total counts.
Returns:
List of tuples in form of (short_name, full_name, full_hosts, # of entries)
"""
for source in self.ListSourceTypes():
max_mtime = self.source_config[source]['max_mtime_days']
self._GetHostsFromSource(source, min_file_size=MIN_FILE_SIZE,
max_mtime_age_days=max_mtime)
details = []
for source in self.source_cache:
details.append((source,
self.source_config[source]['name'],
self.source_config[source]['synthetic'],
len(self.source_cache[source])))
return sorted(details, key=lambda x: (x[2], x[3] * -1))
def ListSourceTitles(self):
"""Return a list of sources in title + count format."""
titles = []
seen_synthetic = False
seen_organic = False
for (unused_type, name, is_synthetic, count) in self.ListSourcesWithDetails():
if not is_synthetic:
seen_organic = True
if is_synthetic and seen_organic and not seen_synthetic:
titles.append('-' * 36)
seen_synthetic = True
titles.append('%s (%s)' % (name, count))
return titles
def ConvertSourceTitleToType(self, detail):
"""Convert a detail name to a source type."""
for source_type in self.source_config:
if detail.startswith(self.source_config[source_type]['name']):
return source_type
def GetBestSourceDetails(self):
return self.ListSourcesWithDetails()[0]
def GetNameForSource(self, source):
if source in self.source_config:
return self.source_config[source]['name']
else:
# Most likely a custom file path
return source
def GetCachedRecordCountForSource(self, source):
return len(self.source_cache[source])
def _CreateRecordsFromHostEntries(self, entries, include_duplicates=False):
"""Create records from hosts, removing duplicate entries and IP's.
Args:
entries: A list of test-data entries.
include_duplicates: Whether or not to filter duplicates (optional: False)
Returns:
A tuple of (filtered records, full_host_names (Boolean)
Raises:
ValueError: If no records could be grokked from the input.
"""
last_entry = None
records = []
full_host_count = 0
for entry in entries:
if entry == last_entry and not include_duplicates:
continue
else:
last_entry = entry
if ' ' in entry:
(record_type, host) = entry.split(' ')
else:
record_type = 'A'
host = entry
if not addr_util.IP_RE.match(host) and not addr_util.INTERNAL_RE.search(host):
if not host.endswith('.'):
host += '.'
records.append((record_type, host))
if addr_util.FQDN_RE.match(host):
full_host_count += 1
if not records:
raise ValueError('No records could be created from: %s' % entries)
# Now that we've read everything, are we dealing with domains or full hostnames?
full_host_percent = full_host_count / float(len(records)) * 100
if full_host_percent < MAX_FQDN_SYNTHESIZE_PERCENT:
full_host_names = True
else:
full_host_names = False
return (records, full_host_names)
def GetTestsFromSource(self, source, count=50, select_mode=None):
"""Parse records from source, and return tuples to use for testing.
Args:
source: A source name (str) that has been configured.
count: Number of tests to generate from the source (int)
select_mode: automatic, weighted, random, chunk (str)
Returns:
A list of record tuples in the form of (req_type, hostname)
Raises:
ValueError: If no usable records are found from the data source.
This is tricky because we support 3 types of input data:
- List of domains
- List of hosts
- List of record_type + hosts
"""
records = []
if source in self.source_config:
include_duplicates = self.source_config[source].get('include_duplicates', False)
else:
include_duplicates = False
records = self._GetHostsFromSource(source)
if not records:
raise ValueError('Unable to generate records from %s (nothing found)' % source)
self.msg('Generating tests from %s (%s records, selecting %s %s)'
% (self.GetNameForSource(source), len(records), count, select_mode))
(records, are_records_fqdn) = self._CreateRecordsFromHostEntries(records,
include_duplicates=include_duplicates)
# First try to resolve whether to use weighted or random.
if select_mode in ('weighted', 'automatic', None):
# If we are in include_duplicates mode (cachemiss, cachehit, etc.), we have different rules.
if include_duplicates:
if count > len(records):
select_mode = 'random'
else:
select_mode = 'chunk'
elif len(records) != len(set(records)):
if select_mode == 'weighted':
self.msg('%s data contains duplicates, switching select_mode to random' % source)
select_mode = 'random'
else:
select_mode = 'weighted'
self.msg('Selecting %s out of %s sanitized records (%s mode).' %
(count, len(records), select_mode))
if select_mode == 'weighted':
records = selectors.WeightedDistribution(records, count)
elif select_mode == 'chunk':
records = selectors.ChunkSelect(records, count)
elif select_mode == 'random':
records = selectors.RandomSelect(records, count, include_duplicates=include_duplicates)
else:
raise ValueError('No such final selection mode: %s' % select_mode)
# For custom filenames
if source not in self.source_config:
self.source_config[source] = {'synthetic': True}
if are_records_fqdn:
self.source_config[source]['full_hostnames'] = False
self.msg('%s input appears to be predominantly domain names. Synthesizing FQDNs' % source)
synthesized = []
for (req_type, hostname) in records:
if not addr_util.FQDN_RE.match(hostname):
hostname = self._GenerateRandomHostname(hostname)
synthesized.append((req_type, hostname))
return synthesized
else:
return records
def _GenerateRandomHostname(self, domain):
"""Generate a random hostname f or a given domain."""
oracle = random.randint(0, 100)
if oracle < 70:
return 'www.%s' % domain
elif oracle < 95:
return domain
elif oracle < 98:
return 'static.%s' % domain
else:
return 'cache-%s.%s' % (random.randint(0, 10), domain)
def _GetHostsFromSource(self, source, min_file_size=None, max_mtime_age_days=None):
"""Get data for a particular source. This needs to be fast.
Args:
source: A configured source type (str)
min_file_size: What the minimum allowable file size is for this source (int)
max_mtime_age_days: Maximum days old the file can be for this source (int)
Returns:
list of hostnames gathered from data source.
The results of this function are cached by source type.
"""
if source in self.source_cache:
return self.source_cache[source]
filename = self._FindBestFileForSource(source, min_file_size=min_file_size,
max_mtime_age_days=max_mtime_age_days)
if not filename:
return None
size_mb = os.path.getsize(filename) / 1024.0 / 1024.0
# Minimize our output
if not self.source_config[source]['synthetic']:
self.msg('Reading %s: %s (%0.1fMB)' % (self.GetNameForSource(source), filename, size_mb))
start_clock = DEFAULT_TIMER()
if filename.endswith('.pcap') or filename.endswith('.tcp'):
hosts = self._ExtractHostsFromPcapFile(filename)
else:
hosts = self._ExtractHostsFromHistoryFile(filename)
if not hosts:
hosts = self._ReadDataFile(filename)
duration = DEFAULT_TIMER() - start_clock
if duration > 5:
self.msg('%s data took %1.1fs to read!' % (self.GetNameForSource(source), duration))
self.source_cache[source] = hosts
return hosts
def _ExtractHostsFromHistoryFile(self, path):
"""Get a list of sanitized records from a history file containing URLs."""
# This regexp is fairly general (no ip filtering), since we need speed more
# than precision at this stage.
parse_re = re.compile('https*://([\-\w]+\.[\-\w\.]+)')
return parse_re.findall(open(path, 'rb').read())
def _ExtractHostsFromPcapFile(self, path):
"""Get a list of requests out of a pcap file - requires tcpdump."""
self.msg('Extracting requests from pcap file using tcpdump')
cmd = 'tcpdump -r %s -n port 53' % path
pipe = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE).stdout
parse_re = re.compile(' ([A-Z]+)\? ([\-\w\.]+)')
requests = []
for line in pipe:
if '?' not in line:
continue
match = parse_re.search(line)
if match:
requests.append(' '.join(match.groups()))
return requests
def _ReadDataFile(self, path):
"""Read a line-based datafile."""
records = []
domains_re = re.compile('^\w[\w\.-]+[a-zA-Z]$')
requests_re = re.compile('^[A-Z]{1,4} \w[\w\.-]+\.$')
for line in open(path):
if domains_re.match(line) or requests_re.match(line):
records.append(line.rstrip())
return records
def _GetSourceSearchPaths(self, source):
"""Get a list of possible search paths (globs) for a given source."""
# This is likely a custom file path
if source not in self.source_config:
return [source]
search_paths = []
environment_re = re.compile('%(\w+)%')
# First get through resolving environment variables
for path in self.source_config[source]['search_paths']:
env_vars = set(environment_re.findall(path))
if env_vars:
for variable in env_vars:
env_var = os.getenv(variable, False)
if env_var:
path = path.replace('%%%s%%' % variable, env_var)
else:
path = None
# If everything is good, replace all '/' chars with the os path variable.
if path:
path = path.replace('/', os.sep)
search_paths.append(path)
# This moment of weirdness brought to you by Windows XP(tm). If we find
# a Local or Roaming keyword in path, add the other forms to the search
# path.
if sys.platform[:3] == 'win':
keywords = ['Local', 'Roaming']
for keyword in keywords:
if keyword in path:
replacement = keywords[keywords.index(keyword)-1]
search_paths.append(path.replace('\\%s' % keyword, '\\%s' % replacement))
search_paths.append(path.replace('\\%s' % keyword, ''))
return search_paths
def _FindBestFileForSource(self, source, min_file_size=None, max_mtime_age_days=None):
"""Find the best file (newest over X size) to use for a given source type.
Args:
source: source type
min_file_size: What the minimum allowable file size is for this source (int)
max_mtime_age_days: Maximum days old the file can be for this source (int)
Returns:
A file path.
"""
found = []
for path in self._GetSourceSearchPaths(source):
if not os.path.isabs(path):
path = util.FindDataFile(path)
for filename in glob.glob(path):
if min_file_size and os.path.getsize(filename) < min_file_size:
self.msg('Skipping %s (only %sb)' % (filename, os.path.getsize(filename)))
else:
try:
fp = open(filename, 'rb')
fp.close()
found.append(filename)
except IOError:
self.msg('Skipping %s (could not open)' % filename)
if found:
newest = sorted(found, key=os.path.getmtime)[-1]
age_days = (time.time() - os.path.getmtime(newest)) / 86400
if max_mtime_age_days and age_days > max_mtime_age_days:
pass
# self.msg('Skipping %s (%2.0fd old)' % (newest, age_days))
else:
return newest
else:
return None
if __name__ == '__main__':
parser = DataSources()
print parser.ListSourceTypes()
print parser.ListSourcesWithDetails()
best = parser.ListSourcesWithDetails()[0][0]
print len(parser.GetRecordsFromSource(best))
|
bangoocms/bangoo | refs/heads/master | bangoo/navigation/models.py | 3 | from django.db import models
from hvad.models import TranslatableModel, TranslatedFields, TranslationManager
from jsonfield import JSONField
from .debug import WrongMenuFormatException
from django.conf import settings
from django.template.defaultfilters import slugify
from mptt.models import MPTTModel, TreeForeignKey
from .noconflict import classmaker
from .signals import menu_created
class MenuManager(TranslationManager):
def get_queryset(self, *args, **kwargs):
return super(MenuManager, self).get_queryset(*args, **kwargs)
def add_menu(self, titles, plugin=None, user=None, **defaults):
default_locale = settings.LANGUAGE_CODE.split('-')[0]
try:
assert default_locale in list(titles.keys())
except AssertionError:
raise WrongMenuFormatException('Title keys must contain default locale (%s)' % default_locale)
try:
assert plugin in settings.INSTALLED_APPS
except AssertionError:
raise WrongMenuFormatException('plugin parameter must be listen in INSTALLED_APPS')
menu = Menu.objects.create(plugin=plugin, **defaults)
for lang, title in list(titles.items()):
menu.translate(lang)
menu.title = title
menu.path = '/%s/' % slugify(title)
if 'parent' in list(defaults.keys()):
menu.path = defaults['parent'].path + menu.path[1:]
menu.save()
menu_created.send(self.__class__, menu=menu, user=user)
return menu
class Menu(TranslatableModel, MPTTModel, metaclass=classmaker()):
"""
login_required: Is this menu public accessable
parent: The parent menu
plugin: Which apps urlconf to use?
weight: The weight of the menu item. Items in the same level are ordered by weight
"""
login_required = models.BooleanField(default=False)
parent = TreeForeignKey('self', null=True, blank=True, related_name='children')
plugin = models.CharField(max_length=100, blank=True, null=True)
weight = models.SmallIntegerField(default=0)
parameters = JSONField(blank=True, null=True)
translations = TranslatedFields(
path = models.CharField(max_length=255),
title = models.CharField(max_length=100),
meta = {'unique_together': [('path', 'language_code')]},
)
handler = MenuManager()
def __str__(self):
return self.title
|
holygits/incubator-airflow | refs/heads/master | tests/contrib/operators/test_dataflow_operator.py | 23 | # -*- coding: utf-8 -*-
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
import unittest
from airflow.contrib.operators.dataflow_operator import DataFlowPythonOperator
try:
from unittest import mock
except ImportError:
try:
import mock
except ImportError:
mock = None
TASK_ID = 'test-python-dataflow'
PY_FILE = 'gs://my-bucket/my-object.py'
PY_OPTIONS = ['-m']
DEFAULT_OPTIONS = {
'project': 'test',
'stagingLocation': 'gs://test/staging'
}
ADDITIONAL_OPTIONS = {
'output': 'gs://test/output'
}
GCS_HOOK_STRING = 'airflow.contrib.operators.dataflow_operator.{}'
class DataFlowPythonOperatorTest(unittest.TestCase):
def setUp(self):
self.dataflow = DataFlowPythonOperator(
task_id=TASK_ID,
py_file=PY_FILE,
py_options=PY_OPTIONS,
dataflow_default_options=DEFAULT_OPTIONS,
options=ADDITIONAL_OPTIONS)
def test_init(self):
"""Test DataFlowPythonOperator instance is properly initialized."""
self.assertEqual(self.dataflow.task_id, TASK_ID)
self.assertEqual(self.dataflow.py_file, PY_FILE)
self.assertEqual(self.dataflow.py_options, PY_OPTIONS)
self.assertEqual(self.dataflow.dataflow_default_options,
DEFAULT_OPTIONS)
self.assertEqual(self.dataflow.options,
ADDITIONAL_OPTIONS)
@mock.patch('airflow.contrib.operators.dataflow_operator.DataFlowHook')
@mock.patch(GCS_HOOK_STRING.format('GoogleCloudBucketHelper'))
def test_exec(self, gcs_hook, dataflow_mock):
"""Test DataFlowHook is created and the right args are passed to
start_python_workflow.
"""
start_python_hook = dataflow_mock.return_value.start_python_dataflow
gcs_download_hook = gcs_hook.return_value.google_cloud_to_local
self.dataflow.execute(None)
self.assertTrue(dataflow_mock.called)
expected_options = {
'project': 'test',
'staging_location': 'gs://test/staging',
'output': 'gs://test/output'
}
gcs_download_hook.assert_called_once_with(PY_FILE)
start_python_hook.assert_called_once_with(TASK_ID, expected_options,
mock.ANY, PY_OPTIONS)
self.assertTrue(self.dataflow.py_file.startswith('/tmp/dataflow'))
|
jaggu303619/asylum-v2.0 | refs/heads/master | openerp/addons/analytic/__openerp__.py | 112 | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
{
'name' : 'Analytic Accounting',
'version': '1.1',
'author' : 'OpenERP SA',
'website' : 'http://www.openerp.com',
'category': 'Hidden/Dependency',
'depends' : ['base', 'decimal_precision', 'mail'],
'description': """
Module for defining analytic accounting object.
===============================================
In OpenERP, analytic accounts are linked to general accounts but are treated
totally independently. So, you can enter various different analytic operations
that have no counterpart in the general financial accounts.
""",
'data': [
'security/analytic_security.xml',
'security/ir.model.access.csv',
'analytic_sequence.xml',
'analytic_view.xml',
'analytic_data.xml',
],
'demo': [],
'installable': True,
'auto_install': False,
}
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
|
pchmieli/h2o-3 | refs/heads/master | h2o-py/tests/testdir_jira/pyunit_hexdev_29_parse_false.py | 1 | import sys
sys.path.insert(1,"../../")
import h2o
from tests import pyunit_utils
################################################################################
##
## Verifying that Python can support importing without parsing.
##
################################################################################
def parse_false():
fraw = h2o.import_file(pyunit_utils.locate("smalldata/jira/hexdev_29.csv"), parse=False)
assert isinstance(fraw, list)
fhex = h2o.parse_raw(h2o.parse_setup(fraw))
fhex.summary()
assert fhex.__class__.__name__ == "H2OFrame"
if __name__ == "__main__":
pyunit_utils.standalone_test(parse_false)
else:
parse_false()
|
brev/nupic | refs/heads/master | tests/unit/nupic/regions/pyregion_test.py | 25 | #!/usr/bin/env python
# ----------------------------------------------------------------------
# Numenta Platform for Intelligent Computing (NuPIC)
# Copyright (C) 2014, 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 unittest2 as unittest
from nupic.regions.PyRegion import PyRegion
# Classes used for testing
class X(PyRegion):
def __init__(self):
self.x = 5
class Y(PyRegion):
def __init__(self):
self.zzz = 5
self._zzz = 3
def initialize(self): pass
def compute(self): pass
def getOutputElementCount(self): pass
class Z(object):
def __init__(self):
y = Y()
y.setParameter('zzz, 4')
class PyRegionTest(unittest.TestCase):
def testNoInit(self):
"""Test unimplemented init method"""
class NoInit(PyRegion):
pass
with self.assertRaises(TypeError) as cw:
_ni = NoInit()
self.assertEqual(str(cw.exception), "Can't instantiate abstract class " +
"NoInit with abstract methods __init__, compute, initialize")
def testUnimplementedAbstractMethods(self):
"""Test unimplemented abstract methods"""
# Test unimplemented getSpec (results in NotImplementedError)
with self.assertRaises(NotImplementedError):
X.getSpec()
# Test unimplemented abstract methods (x can't be instantiated)
with self.assertRaises(TypeError) as cw:
_x = X()
self.assertEqual(str(cw.exception), "Can't instantiate abstract class " +
"X with abstract methods compute, initialize")
def testUnimplementedNotImplementedMethods(self):
"""Test unimplemented @not_implemented methods"""
# Can instantiate because all abstract methods are implemented
y = Y()
# Can call the default getParameter() from PyRegion
self.assertEqual(y.getParameter('zzz', -1), 5)
# Accessing an attribute whose name starts with '_' via getParameter()
with self.assertRaises(Exception) as cw:
_ = y.getParameter('_zzz', -1) == 5
self.assertEqual(str(cw.exception), "Parameter name must not " +
"start with an underscore")
# Calling not implemented method result in NotImplementedError
with self.assertRaises(NotImplementedError) as cw:
y.setParameter('zzz', 4, 5)
self.assertEqual(str(cw.exception), "The unimplemented method " +
"setParameter() was called by " +
"PyRegionTest.testUnimplementedNotImplementedMethods()")
def testCallUnimplementedMethod(self):
"""Test calling an unimplemented method"""
with self.assertRaises(NotImplementedError) as cw:
_z = Z()
self.assertEqual(str(cw.exception), "The unimplemented method " +
"setParameter() was called by Z.__init__()")
if __name__ == "__main__":
unittest.main()
|
Adai0808/scikit-learn | refs/heads/master | sklearn/linear_model/omp.py | 127 | """Orthogonal matching pursuit algorithms
"""
# Author: Vlad Niculae
#
# License: BSD 3 clause
import warnings
from distutils.version import LooseVersion
import numpy as np
from scipy import linalg
from scipy.linalg.lapack import get_lapack_funcs
from .base import LinearModel, _pre_fit
from ..base import RegressorMixin
from ..utils import as_float_array, check_array, check_X_y
from ..cross_validation import check_cv
from ..externals.joblib import Parallel, delayed
import scipy
solve_triangular_args = {}
if LooseVersion(scipy.__version__) >= LooseVersion('0.12'):
# check_finite=False is an optimization available only in scipy >=0.12
solve_triangular_args = {'check_finite': False}
premature = """ Orthogonal matching pursuit ended prematurely due to linear
dependence in the dictionary. The requested precision might not have been met.
"""
def _cholesky_omp(X, y, n_nonzero_coefs, tol=None, copy_X=True,
return_path=False):
"""Orthogonal Matching Pursuit step using the Cholesky decomposition.
Parameters
----------
X : array, shape (n_samples, n_features)
Input dictionary. Columns are assumed to have unit norm.
y : array, shape (n_samples,)
Input targets
n_nonzero_coefs : int
Targeted number of non-zero elements
tol : float
Targeted squared error, if not None overrides n_nonzero_coefs.
copy_X : bool, optional
Whether the design matrix X must be copied by the algorithm. A false
value is only helpful if X is already Fortran-ordered, otherwise a
copy is made anyway.
return_path : bool, optional. Default: False
Whether to return every value of the nonzero coefficients along the
forward path. Useful for cross-validation.
Returns
-------
gamma : array, shape (n_nonzero_coefs,)
Non-zero elements of the solution
idx : array, shape (n_nonzero_coefs,)
Indices of the positions of the elements in gamma within the solution
vector
coef : array, shape (n_features, n_nonzero_coefs)
The first k values of column k correspond to the coefficient value
for the active features at that step. The lower left triangle contains
garbage. Only returned if ``return_path=True``.
n_active : int
Number of active features at convergence.
"""
if copy_X:
X = X.copy('F')
else: # even if we are allowed to overwrite, still copy it if bad order
X = np.asfortranarray(X)
min_float = np.finfo(X.dtype).eps
nrm2, swap = linalg.get_blas_funcs(('nrm2', 'swap'), (X,))
potrs, = get_lapack_funcs(('potrs',), (X,))
alpha = np.dot(X.T, y)
residual = y
gamma = np.empty(0)
n_active = 0
indices = np.arange(X.shape[1]) # keeping track of swapping
max_features = X.shape[1] if tol is not None else n_nonzero_coefs
if solve_triangular_args:
# new scipy, don't need to initialize because check_finite=False
L = np.empty((max_features, max_features), dtype=X.dtype)
else:
# old scipy, we need the garbage upper triangle to be non-Inf
L = np.zeros((max_features, max_features), dtype=X.dtype)
L[0, 0] = 1.
if return_path:
coefs = np.empty_like(L)
while True:
lam = np.argmax(np.abs(np.dot(X.T, residual)))
if lam < n_active or alpha[lam] ** 2 < min_float:
# atom already selected or inner product too small
warnings.warn(premature, RuntimeWarning, stacklevel=2)
break
if n_active > 0:
# Updates the Cholesky decomposition of X' X
L[n_active, :n_active] = np.dot(X[:, :n_active].T, X[:, lam])
linalg.solve_triangular(L[:n_active, :n_active],
L[n_active, :n_active],
trans=0, lower=1,
overwrite_b=True,
**solve_triangular_args)
v = nrm2(L[n_active, :n_active]) ** 2
if 1 - v <= min_float: # selected atoms are dependent
warnings.warn(premature, RuntimeWarning, stacklevel=2)
break
L[n_active, n_active] = np.sqrt(1 - v)
X.T[n_active], X.T[lam] = swap(X.T[n_active], X.T[lam])
alpha[n_active], alpha[lam] = alpha[lam], alpha[n_active]
indices[n_active], indices[lam] = indices[lam], indices[n_active]
n_active += 1
# solves LL'x = y as a composition of two triangular systems
gamma, _ = potrs(L[:n_active, :n_active], alpha[:n_active], lower=True,
overwrite_b=False)
if return_path:
coefs[:n_active, n_active - 1] = gamma
residual = y - np.dot(X[:, :n_active], gamma)
if tol is not None and nrm2(residual) ** 2 <= tol:
break
elif n_active == max_features:
break
if return_path:
return gamma, indices[:n_active], coefs[:, :n_active], n_active
else:
return gamma, indices[:n_active], n_active
def _gram_omp(Gram, Xy, n_nonzero_coefs, tol_0=None, tol=None,
copy_Gram=True, copy_Xy=True, return_path=False):
"""Orthogonal Matching Pursuit step on a precomputed Gram matrix.
This function uses the the Cholesky decomposition method.
Parameters
----------
Gram : array, shape (n_features, n_features)
Gram matrix of the input data matrix
Xy : array, shape (n_features,)
Input targets
n_nonzero_coefs : int
Targeted number of non-zero elements
tol_0 : float
Squared norm of y, required if tol is not None.
tol : float
Targeted squared error, if not None overrides n_nonzero_coefs.
copy_Gram : bool, optional
Whether the gram matrix must be copied by the algorithm. A false
value is only helpful if it is already Fortran-ordered, otherwise a
copy is made anyway.
copy_Xy : bool, optional
Whether the covariance vector Xy must be copied by the algorithm.
If False, it may be overwritten.
return_path : bool, optional. Default: False
Whether to return every value of the nonzero coefficients along the
forward path. Useful for cross-validation.
Returns
-------
gamma : array, shape (n_nonzero_coefs,)
Non-zero elements of the solution
idx : array, shape (n_nonzero_coefs,)
Indices of the positions of the elements in gamma within the solution
vector
coefs : array, shape (n_features, n_nonzero_coefs)
The first k values of column k correspond to the coefficient value
for the active features at that step. The lower left triangle contains
garbage. Only returned if ``return_path=True``.
n_active : int
Number of active features at convergence.
"""
Gram = Gram.copy('F') if copy_Gram else np.asfortranarray(Gram)
if copy_Xy:
Xy = Xy.copy()
min_float = np.finfo(Gram.dtype).eps
nrm2, swap = linalg.get_blas_funcs(('nrm2', 'swap'), (Gram,))
potrs, = get_lapack_funcs(('potrs',), (Gram,))
indices = np.arange(len(Gram)) # keeping track of swapping
alpha = Xy
tol_curr = tol_0
delta = 0
gamma = np.empty(0)
n_active = 0
max_features = len(Gram) if tol is not None else n_nonzero_coefs
if solve_triangular_args:
# new scipy, don't need to initialize because check_finite=False
L = np.empty((max_features, max_features), dtype=Gram.dtype)
else:
# old scipy, we need the garbage upper triangle to be non-Inf
L = np.zeros((max_features, max_features), dtype=Gram.dtype)
L[0, 0] = 1.
if return_path:
coefs = np.empty_like(L)
while True:
lam = np.argmax(np.abs(alpha))
if lam < n_active or alpha[lam] ** 2 < min_float:
# selected same atom twice, or inner product too small
warnings.warn(premature, RuntimeWarning, stacklevel=3)
break
if n_active > 0:
L[n_active, :n_active] = Gram[lam, :n_active]
linalg.solve_triangular(L[:n_active, :n_active],
L[n_active, :n_active],
trans=0, lower=1,
overwrite_b=True,
**solve_triangular_args)
v = nrm2(L[n_active, :n_active]) ** 2
if 1 - v <= min_float: # selected atoms are dependent
warnings.warn(premature, RuntimeWarning, stacklevel=3)
break
L[n_active, n_active] = np.sqrt(1 - v)
Gram[n_active], Gram[lam] = swap(Gram[n_active], Gram[lam])
Gram.T[n_active], Gram.T[lam] = swap(Gram.T[n_active], Gram.T[lam])
indices[n_active], indices[lam] = indices[lam], indices[n_active]
Xy[n_active], Xy[lam] = Xy[lam], Xy[n_active]
n_active += 1
# solves LL'x = y as a composition of two triangular systems
gamma, _ = potrs(L[:n_active, :n_active], Xy[:n_active], lower=True,
overwrite_b=False)
if return_path:
coefs[:n_active, n_active - 1] = gamma
beta = np.dot(Gram[:, :n_active], gamma)
alpha = Xy - beta
if tol is not None:
tol_curr += delta
delta = np.inner(gamma, beta[:n_active])
tol_curr -= delta
if abs(tol_curr) <= tol:
break
elif n_active == max_features:
break
if return_path:
return gamma, indices[:n_active], coefs[:, :n_active], n_active
else:
return gamma, indices[:n_active], n_active
def orthogonal_mp(X, y, n_nonzero_coefs=None, tol=None, precompute=False,
copy_X=True, return_path=False,
return_n_iter=False):
"""Orthogonal Matching Pursuit (OMP)
Solves n_targets Orthogonal Matching Pursuit problems.
An instance of the problem has the form:
When parametrized by the number of non-zero coefficients using
`n_nonzero_coefs`:
argmin ||y - X\gamma||^2 subject to ||\gamma||_0 <= n_{nonzero coefs}
When parametrized by error using the parameter `tol`:
argmin ||\gamma||_0 subject to ||y - X\gamma||^2 <= tol
Read more in the :ref:`User Guide <omp>`.
Parameters
----------
X : array, shape (n_samples, n_features)
Input data. Columns are assumed to have unit norm.
y : array, shape (n_samples,) or (n_samples, n_targets)
Input targets
n_nonzero_coefs : int
Desired number of non-zero entries in the solution. If None (by
default) this value is set to 10% of n_features.
tol : float
Maximum norm of the residual. If not None, overrides n_nonzero_coefs.
precompute : {True, False, 'auto'},
Whether to perform precomputations. Improves performance when n_targets
or n_samples is very large.
copy_X : bool, optional
Whether the design matrix X must be copied by the algorithm. A false
value is only helpful if X is already Fortran-ordered, otherwise a
copy is made anyway.
return_path : bool, optional. Default: False
Whether to return every value of the nonzero coefficients along the
forward path. Useful for cross-validation.
return_n_iter : bool, optional default False
Whether or not to return the number of iterations.
Returns
-------
coef : array, shape (n_features,) or (n_features, n_targets)
Coefficients of the OMP solution. If `return_path=True`, this contains
the whole coefficient path. In this case its shape is
(n_features, n_features) or (n_features, n_targets, n_features) and
iterating over the last axis yields coefficients in increasing order
of active features.
n_iters : array-like or int
Number of active features across every target. Returned only if
`return_n_iter` is set to True.
See also
--------
OrthogonalMatchingPursuit
orthogonal_mp_gram
lars_path
decomposition.sparse_encode
Notes
-----
Orthogonal matching pursuit was introduced in G. Mallat, Z. Zhang,
Matching pursuits with time-frequency dictionaries, IEEE Transactions on
Signal Processing, Vol. 41, No. 12. (December 1993), pp. 3397-3415.
(http://blanche.polytechnique.fr/~mallat/papiers/MallatPursuit93.pdf)
This implementation is based on Rubinstein, R., Zibulevsky, M. and Elad,
M., Efficient Implementation of the K-SVD Algorithm using Batch Orthogonal
Matching Pursuit Technical Report - CS Technion, April 2008.
http://www.cs.technion.ac.il/~ronrubin/Publications/KSVD-OMP-v2.pdf
"""
X = check_array(X, order='F', copy=copy_X)
copy_X = False
if y.ndim == 1:
y = y.reshape(-1, 1)
y = check_array(y)
if y.shape[1] > 1: # subsequent targets will be affected
copy_X = True
if n_nonzero_coefs is None and tol is None:
# default for n_nonzero_coefs is 0.1 * n_features
# but at least one.
n_nonzero_coefs = max(int(0.1 * X.shape[1]), 1)
if tol is not None and tol < 0:
raise ValueError("Epsilon cannot be negative")
if tol is None and n_nonzero_coefs <= 0:
raise ValueError("The number of atoms must be positive")
if tol is None and n_nonzero_coefs > X.shape[1]:
raise ValueError("The number of atoms cannot be more than the number "
"of features")
if precompute == 'auto':
precompute = X.shape[0] > X.shape[1]
if precompute:
G = np.dot(X.T, X)
G = np.asfortranarray(G)
Xy = np.dot(X.T, y)
if tol is not None:
norms_squared = np.sum((y ** 2), axis=0)
else:
norms_squared = None
return orthogonal_mp_gram(G, Xy, n_nonzero_coefs, tol, norms_squared,
copy_Gram=copy_X, copy_Xy=False,
return_path=return_path)
if return_path:
coef = np.zeros((X.shape[1], y.shape[1], X.shape[1]))
else:
coef = np.zeros((X.shape[1], y.shape[1]))
n_iters = []
for k in range(y.shape[1]):
out = _cholesky_omp(
X, y[:, k], n_nonzero_coefs, tol,
copy_X=copy_X, return_path=return_path)
if return_path:
_, idx, coefs, n_iter = out
coef = coef[:, :, :len(idx)]
for n_active, x in enumerate(coefs.T):
coef[idx[:n_active + 1], k, n_active] = x[:n_active + 1]
else:
x, idx, n_iter = out
coef[idx, k] = x
n_iters.append(n_iter)
if y.shape[1] == 1:
n_iters = n_iters[0]
if return_n_iter:
return np.squeeze(coef), n_iters
else:
return np.squeeze(coef)
def orthogonal_mp_gram(Gram, Xy, n_nonzero_coefs=None, tol=None,
norms_squared=None, copy_Gram=True,
copy_Xy=True, return_path=False,
return_n_iter=False):
"""Gram Orthogonal Matching Pursuit (OMP)
Solves n_targets Orthogonal Matching Pursuit problems using only
the Gram matrix X.T * X and the product X.T * y.
Read more in the :ref:`User Guide <omp>`.
Parameters
----------
Gram : array, shape (n_features, n_features)
Gram matrix of the input data: X.T * X
Xy : array, shape (n_features,) or (n_features, n_targets)
Input targets multiplied by X: X.T * y
n_nonzero_coefs : int
Desired number of non-zero entries in the solution. If None (by
default) this value is set to 10% of n_features.
tol : float
Maximum norm of the residual. If not None, overrides n_nonzero_coefs.
norms_squared : array-like, shape (n_targets,)
Squared L2 norms of the lines of y. Required if tol is not None.
copy_Gram : bool, optional
Whether the gram matrix must be copied by the algorithm. A false
value is only helpful if it is already Fortran-ordered, otherwise a
copy is made anyway.
copy_Xy : bool, optional
Whether the covariance vector Xy must be copied by the algorithm.
If False, it may be overwritten.
return_path : bool, optional. Default: False
Whether to return every value of the nonzero coefficients along the
forward path. Useful for cross-validation.
return_n_iter : bool, optional default False
Whether or not to return the number of iterations.
Returns
-------
coef : array, shape (n_features,) or (n_features, n_targets)
Coefficients of the OMP solution. If `return_path=True`, this contains
the whole coefficient path. In this case its shape is
(n_features, n_features) or (n_features, n_targets, n_features) and
iterating over the last axis yields coefficients in increasing order
of active features.
n_iters : array-like or int
Number of active features across every target. Returned only if
`return_n_iter` is set to True.
See also
--------
OrthogonalMatchingPursuit
orthogonal_mp
lars_path
decomposition.sparse_encode
Notes
-----
Orthogonal matching pursuit was introduced in G. Mallat, Z. Zhang,
Matching pursuits with time-frequency dictionaries, IEEE Transactions on
Signal Processing, Vol. 41, No. 12. (December 1993), pp. 3397-3415.
(http://blanche.polytechnique.fr/~mallat/papiers/MallatPursuit93.pdf)
This implementation is based on Rubinstein, R., Zibulevsky, M. and Elad,
M., Efficient Implementation of the K-SVD Algorithm using Batch Orthogonal
Matching Pursuit Technical Report - CS Technion, April 2008.
http://www.cs.technion.ac.il/~ronrubin/Publications/KSVD-OMP-v2.pdf
"""
Gram = check_array(Gram, order='F', copy=copy_Gram)
Xy = np.asarray(Xy)
if Xy.ndim > 1 and Xy.shape[1] > 1:
# or subsequent target will be affected
copy_Gram = True
if Xy.ndim == 1:
Xy = Xy[:, np.newaxis]
if tol is not None:
norms_squared = [norms_squared]
if n_nonzero_coefs is None and tol is None:
n_nonzero_coefs = int(0.1 * len(Gram))
if tol is not None and norms_squared is None:
raise ValueError('Gram OMP needs the precomputed norms in order '
'to evaluate the error sum of squares.')
if tol is not None and tol < 0:
raise ValueError("Epsilon cannot be negative")
if tol is None and n_nonzero_coefs <= 0:
raise ValueError("The number of atoms must be positive")
if tol is None and n_nonzero_coefs > len(Gram):
raise ValueError("The number of atoms cannot be more than the number "
"of features")
if return_path:
coef = np.zeros((len(Gram), Xy.shape[1], len(Gram)))
else:
coef = np.zeros((len(Gram), Xy.shape[1]))
n_iters = []
for k in range(Xy.shape[1]):
out = _gram_omp(
Gram, Xy[:, k], n_nonzero_coefs,
norms_squared[k] if tol is not None else None, tol,
copy_Gram=copy_Gram, copy_Xy=copy_Xy,
return_path=return_path)
if return_path:
_, idx, coefs, n_iter = out
coef = coef[:, :, :len(idx)]
for n_active, x in enumerate(coefs.T):
coef[idx[:n_active + 1], k, n_active] = x[:n_active + 1]
else:
x, idx, n_iter = out
coef[idx, k] = x
n_iters.append(n_iter)
if Xy.shape[1] == 1:
n_iters = n_iters[0]
if return_n_iter:
return np.squeeze(coef), n_iters
else:
return np.squeeze(coef)
class OrthogonalMatchingPursuit(LinearModel, RegressorMixin):
"""Orthogonal Matching Pursuit model (OMP)
Parameters
----------
n_nonzero_coefs : int, optional
Desired number of non-zero entries in the solution. If None (by
default) this value is set to 10% of n_features.
tol : float, optional
Maximum norm of the residual. If not None, overrides n_nonzero_coefs.
fit_intercept : boolean, optional
whether to calculate the intercept for this model. If set
to false, no intercept will be used in calculations
(e.g. data is expected to be already centered).
normalize : boolean, optional
If False, the regressors X are assumed to be already normalized.
precompute : {True, False, 'auto'}, default 'auto'
Whether to use a precomputed Gram and Xy matrix to speed up
calculations. Improves performance when `n_targets` or `n_samples` is
very large. Note that if you already have such matrices, you can pass
them directly to the fit method.
Read more in the :ref:`User Guide <omp>`.
Attributes
----------
coef_ : array, shape (n_features,) or (n_features, n_targets)
parameter vector (w in the formula)
intercept_ : float or array, shape (n_targets,)
independent term in decision function.
n_iter_ : int or array-like
Number of active features across every target.
Notes
-----
Orthogonal matching pursuit was introduced in G. Mallat, Z. Zhang,
Matching pursuits with time-frequency dictionaries, IEEE Transactions on
Signal Processing, Vol. 41, No. 12. (December 1993), pp. 3397-3415.
(http://blanche.polytechnique.fr/~mallat/papiers/MallatPursuit93.pdf)
This implementation is based on Rubinstein, R., Zibulevsky, M. and Elad,
M., Efficient Implementation of the K-SVD Algorithm using Batch Orthogonal
Matching Pursuit Technical Report - CS Technion, April 2008.
http://www.cs.technion.ac.il/~ronrubin/Publications/KSVD-OMP-v2.pdf
See also
--------
orthogonal_mp
orthogonal_mp_gram
lars_path
Lars
LassoLars
decomposition.sparse_encode
"""
def __init__(self, n_nonzero_coefs=None, tol=None, fit_intercept=True,
normalize=True, precompute='auto'):
self.n_nonzero_coefs = n_nonzero_coefs
self.tol = tol
self.fit_intercept = fit_intercept
self.normalize = normalize
self.precompute = precompute
def fit(self, X, y):
"""Fit the model using X, y as training data.
Parameters
----------
X : array-like, shape (n_samples, n_features)
Training data.
y : array-like, shape (n_samples,) or (n_samples, n_targets)
Target values.
Returns
-------
self : object
returns an instance of self.
"""
X, y = check_X_y(X, y, multi_output=True, y_numeric=True)
n_features = X.shape[1]
X, y, X_mean, y_mean, X_std, Gram, Xy = \
_pre_fit(X, y, None, self.precompute, self.normalize,
self.fit_intercept, copy=True)
if y.ndim == 1:
y = y[:, np.newaxis]
if self.n_nonzero_coefs is None and self.tol is None:
# default for n_nonzero_coefs is 0.1 * n_features
# but at least one.
self.n_nonzero_coefs_ = max(int(0.1 * n_features), 1)
else:
self.n_nonzero_coefs_ = self.n_nonzero_coefs
if Gram is False:
coef_, self.n_iter_ = orthogonal_mp(
X, y, self.n_nonzero_coefs_, self.tol,
precompute=False, copy_X=True,
return_n_iter=True)
else:
norms_sq = np.sum(y ** 2, axis=0) if self.tol is not None else None
coef_, self.n_iter_ = orthogonal_mp_gram(
Gram, Xy=Xy, n_nonzero_coefs=self.n_nonzero_coefs_,
tol=self.tol, norms_squared=norms_sq,
copy_Gram=True, copy_Xy=True,
return_n_iter=True)
self.coef_ = coef_.T
self._set_intercept(X_mean, y_mean, X_std)
return self
def _omp_path_residues(X_train, y_train, X_test, y_test, copy=True,
fit_intercept=True, normalize=True, max_iter=100):
"""Compute the residues on left-out data for a full LARS path
Parameters
-----------
X_train : array, shape (n_samples, n_features)
The data to fit the LARS on
y_train : array, shape (n_samples)
The target variable to fit LARS on
X_test : array, shape (n_samples, n_features)
The data to compute the residues on
y_test : array, shape (n_samples)
The target variable to compute the residues on
copy : boolean, optional
Whether X_train, X_test, y_train and y_test should be copied. If
False, they may be overwritten.
fit_intercept : boolean
whether to calculate the intercept for this model. If set
to false, no intercept will be used in calculations
(e.g. data is expected to be already centered).
normalize : boolean, optional, default False
If True, the regressors X will be normalized before regression.
max_iter : integer, optional
Maximum numbers of iterations to perform, therefore maximum features
to include. 100 by default.
Returns
-------
residues: array, shape (n_samples, max_features)
Residues of the prediction on the test data
"""
if copy:
X_train = X_train.copy()
y_train = y_train.copy()
X_test = X_test.copy()
y_test = y_test.copy()
if fit_intercept:
X_mean = X_train.mean(axis=0)
X_train -= X_mean
X_test -= X_mean
y_mean = y_train.mean(axis=0)
y_train = as_float_array(y_train, copy=False)
y_train -= y_mean
y_test = as_float_array(y_test, copy=False)
y_test -= y_mean
if normalize:
norms = np.sqrt(np.sum(X_train ** 2, axis=0))
nonzeros = np.flatnonzero(norms)
X_train[:, nonzeros] /= norms[nonzeros]
coefs = orthogonal_mp(X_train, y_train, n_nonzero_coefs=max_iter, tol=None,
precompute=False, copy_X=False,
return_path=True)
if coefs.ndim == 1:
coefs = coefs[:, np.newaxis]
if normalize:
coefs[nonzeros] /= norms[nonzeros][:, np.newaxis]
return np.dot(coefs.T, X_test.T) - y_test
class OrthogonalMatchingPursuitCV(LinearModel, RegressorMixin):
"""Cross-validated Orthogonal Matching Pursuit model (OMP)
Parameters
----------
copy : bool, optional
Whether the design matrix X must be copied by the algorithm. A false
value is only helpful if X is already Fortran-ordered, otherwise a
copy is made anyway.
fit_intercept : boolean, optional
whether to calculate the intercept for this model. If set
to false, no intercept will be used in calculations
(e.g. data is expected to be already centered).
normalize : boolean, optional
If False, the regressors X are assumed to be already normalized.
max_iter : integer, optional
Maximum numbers of iterations to perform, therefore maximum features
to include. 10% of ``n_features`` but at least 5 if available.
cv : cross-validation generator, optional
see :mod:`sklearn.cross_validation`. If ``None`` is passed, default to
a 5-fold strategy
n_jobs : integer, optional
Number of CPUs to use during the cross validation. If ``-1``, use
all the CPUs
verbose : boolean or integer, optional
Sets the verbosity amount
Read more in the :ref:`User Guide <omp>`.
Attributes
----------
intercept_ : float or array, shape (n_targets,)
Independent term in decision function.
coef_ : array, shape (n_features,) or (n_features, n_targets)
Parameter vector (w in the problem formulation).
n_nonzero_coefs_ : int
Estimated number of non-zero coefficients giving the best mean squared
error over the cross-validation folds.
n_iter_ : int or array-like
Number of active features across every target for the model refit with
the best hyperparameters got by cross-validating across all folds.
See also
--------
orthogonal_mp
orthogonal_mp_gram
lars_path
Lars
LassoLars
OrthogonalMatchingPursuit
LarsCV
LassoLarsCV
decomposition.sparse_encode
"""
def __init__(self, copy=True, fit_intercept=True, normalize=True,
max_iter=None, cv=None, n_jobs=1, verbose=False):
self.copy = copy
self.fit_intercept = fit_intercept
self.normalize = normalize
self.max_iter = max_iter
self.cv = cv
self.n_jobs = n_jobs
self.verbose = verbose
def fit(self, X, y):
"""Fit the model using X, y as training data.
Parameters
----------
X : array-like, shape [n_samples, n_features]
Training data.
y : array-like, shape [n_samples]
Target values.
Returns
-------
self : object
returns an instance of self.
"""
X, y = check_X_y(X, y, y_numeric=True)
X = as_float_array(X, copy=False, force_all_finite=False)
cv = check_cv(self.cv, X, y, classifier=False)
max_iter = (min(max(int(0.1 * X.shape[1]), 5), X.shape[1])
if not self.max_iter
else self.max_iter)
cv_paths = Parallel(n_jobs=self.n_jobs, verbose=self.verbose)(
delayed(_omp_path_residues)(
X[train], y[train], X[test], y[test], self.copy,
self.fit_intercept, self.normalize, max_iter)
for train, test in cv)
min_early_stop = min(fold.shape[0] for fold in cv_paths)
mse_folds = np.array([(fold[:min_early_stop] ** 2).mean(axis=1)
for fold in cv_paths])
best_n_nonzero_coefs = np.argmin(mse_folds.mean(axis=0)) + 1
self.n_nonzero_coefs_ = best_n_nonzero_coefs
omp = OrthogonalMatchingPursuit(n_nonzero_coefs=best_n_nonzero_coefs,
fit_intercept=self.fit_intercept,
normalize=self.normalize)
omp.fit(X, y)
self.coef_ = omp.coef_
self.intercept_ = omp.intercept_
self.n_iter_ = omp.n_iter_
return self
|
DiptoDas8/Biponi | refs/heads/master | lib/python2.7/site-packages/setuptools/launch.py | 59 | """
Launch the Python script on the command line after
setuptools is bootstrapped via import.
"""
# Note that setuptools gets imported implicitly by the
# invocation of this script using python -m setuptools.launch
import tokenize
import sys
def run():
"""
Run the script in sys.argv[1] as if it had
been invoked naturally.
"""
__builtins__
script_name = sys.argv[1]
namespace = dict(
__file__ = script_name,
__name__ = '__main__',
__doc__ = None,
)
sys.argv[:] = sys.argv[1:]
open_ = getattr(tokenize, 'open', open)
script = open_(script_name).read()
norm_script = script.replace('\\r\\n', '\\n')
code = compile(norm_script, script_name, 'exec')
exec(code, namespace)
if __name__ == '__main__':
run()
|
Anwesh43/numpy | refs/heads/master | numpy/core/_internal.py | 23 | """
A place for code to be called from core C-code.
Some things are more easily handled Python.
"""
from __future__ import division, absolute_import, print_function
import re
import sys
from numpy.compat import asbytes, basestring
from .multiarray import dtype, array, ndarray
import ctypes
from .numerictypes import object_
if (sys.byteorder == 'little'):
_nbo = asbytes('<')
else:
_nbo = asbytes('>')
def _makenames_list(adict, align):
allfields = []
fnames = list(adict.keys())
for fname in fnames:
obj = adict[fname]
n = len(obj)
if not isinstance(obj, tuple) or n not in [2, 3]:
raise ValueError("entry not a 2- or 3- tuple")
if (n > 2) and (obj[2] == fname):
continue
num = int(obj[1])
if (num < 0):
raise ValueError("invalid offset.")
format = dtype(obj[0], align=align)
if (format.itemsize == 0):
raise ValueError("all itemsizes must be fixed.")
if (n > 2):
title = obj[2]
else:
title = None
allfields.append((fname, format, num, title))
# sort by offsets
allfields.sort(key=lambda x: x[2])
names = [x[0] for x in allfields]
formats = [x[1] for x in allfields]
offsets = [x[2] for x in allfields]
titles = [x[3] for x in allfields]
return names, formats, offsets, titles
# Called in PyArray_DescrConverter function when
# a dictionary without "names" and "formats"
# fields is used as a data-type descriptor.
def _usefields(adict, align):
try:
names = adict[-1]
except KeyError:
names = None
if names is None:
names, formats, offsets, titles = _makenames_list(adict, align)
else:
formats = []
offsets = []
titles = []
for name in names:
res = adict[name]
formats.append(res[0])
offsets.append(res[1])
if (len(res) > 2):
titles.append(res[2])
else:
titles.append(None)
return dtype({"names": names,
"formats": formats,
"offsets": offsets,
"titles": titles}, align)
# construct an array_protocol descriptor list
# from the fields attribute of a descriptor
# This calls itself recursively but should eventually hit
# a descriptor that has no fields and then return
# a simple typestring
def _array_descr(descriptor):
fields = descriptor.fields
if fields is None:
subdtype = descriptor.subdtype
if subdtype is None:
if descriptor.metadata is None:
return descriptor.str
else:
new = descriptor.metadata.copy()
if new:
return (descriptor.str, new)
else:
return descriptor.str
else:
return (_array_descr(subdtype[0]), subdtype[1])
names = descriptor.names
ordered_fields = [fields[x] + (x,) for x in names]
result = []
offset = 0
for field in ordered_fields:
if field[1] > offset:
num = field[1] - offset
result.append(('', '|V%d' % num))
offset += num
if len(field) > 3:
name = (field[2], field[3])
else:
name = field[2]
if field[0].subdtype:
tup = (name, _array_descr(field[0].subdtype[0]),
field[0].subdtype[1])
else:
tup = (name, _array_descr(field[0]))
offset += field[0].itemsize
result.append(tup)
return result
# Build a new array from the information in a pickle.
# Note that the name numpy.core._internal._reconstruct is embedded in
# pickles of ndarrays made with NumPy before release 1.0
# so don't remove the name here, or you'll
# break backward compatibilty.
def _reconstruct(subtype, shape, dtype):
return ndarray.__new__(subtype, shape, dtype)
# format_re was originally from numarray by J. Todd Miller
format_re = re.compile(asbytes(
r'(?P<order1>[<>|=]?)'
r'(?P<repeats> *[(]?[ ,0-9L]*[)]? *)'
r'(?P<order2>[<>|=]?)'
r'(?P<dtype>[A-Za-z0-9.?]*(?:\[[a-zA-Z0-9,.]+\])?)'))
sep_re = re.compile(asbytes(r'\s*,\s*'))
space_re = re.compile(asbytes(r'\s+$'))
# astr is a string (perhaps comma separated)
_convorder = {asbytes('='): _nbo}
def _commastring(astr):
startindex = 0
result = []
while startindex < len(astr):
mo = format_re.match(astr, pos=startindex)
try:
(order1, repeats, order2, dtype) = mo.groups()
except (TypeError, AttributeError):
raise ValueError('format number %d of "%s" is not recognized' %
(len(result)+1, astr))
startindex = mo.end()
# Separator or ending padding
if startindex < len(astr):
if space_re.match(astr, pos=startindex):
startindex = len(astr)
else:
mo = sep_re.match(astr, pos=startindex)
if not mo:
raise ValueError(
'format number %d of "%s" is not recognized' %
(len(result)+1, astr))
startindex = mo.end()
if order2 == asbytes(''):
order = order1
elif order1 == asbytes(''):
order = order2
else:
order1 = _convorder.get(order1, order1)
order2 = _convorder.get(order2, order2)
if (order1 != order2):
raise ValueError(
'inconsistent byte-order specification %s and %s' %
(order1, order2))
order = order1
if order in [asbytes('|'), asbytes('='), _nbo]:
order = asbytes('')
dtype = order + dtype
if (repeats == asbytes('')):
newitem = dtype
else:
newitem = (dtype, eval(repeats))
result.append(newitem)
return result
def _getintp_ctype():
val = _getintp_ctype.cache
if val is not None:
return val
char = dtype('p').char
if (char == 'i'):
val = ctypes.c_int
elif char == 'l':
val = ctypes.c_long
elif char == 'q':
val = ctypes.c_longlong
else:
val = ctypes.c_long
_getintp_ctype.cache = val
return val
_getintp_ctype.cache = None
# Used for .ctypes attribute of ndarray
class _missing_ctypes(object):
def cast(self, num, obj):
return num
def c_void_p(self, num):
return num
class _ctypes(object):
def __init__(self, array, ptr=None):
try:
self._ctypes = ctypes
except ImportError:
self._ctypes = _missing_ctypes()
self._arr = array
self._data = ptr
if self._arr.ndim == 0:
self._zerod = True
else:
self._zerod = False
def data_as(self, obj):
return self._ctypes.cast(self._data, obj)
def shape_as(self, obj):
if self._zerod:
return None
return (obj*self._arr.ndim)(*self._arr.shape)
def strides_as(self, obj):
if self._zerod:
return None
return (obj*self._arr.ndim)(*self._arr.strides)
def get_data(self):
return self._data
def get_shape(self):
if self._zerod:
return None
return (_getintp_ctype()*self._arr.ndim)(*self._arr.shape)
def get_strides(self):
if self._zerod:
return None
return (_getintp_ctype()*self._arr.ndim)(*self._arr.strides)
def get_as_parameter(self):
return self._ctypes.c_void_p(self._data)
data = property(get_data, None, doc="c-types data")
shape = property(get_shape, None, doc="c-types shape")
strides = property(get_strides, None, doc="c-types strides")
_as_parameter_ = property(get_as_parameter, None, doc="_as parameter_")
# Given a datatype and an order object
# return a new names tuple
# with the order indicated
def _newnames(datatype, order):
oldnames = datatype.names
nameslist = list(oldnames)
if isinstance(order, str):
order = [order]
if isinstance(order, (list, tuple)):
for name in order:
try:
nameslist.remove(name)
except ValueError:
raise ValueError("unknown field name: %s" % (name,))
return tuple(list(order) + nameslist)
raise ValueError("unsupported order value: %s" % (order,))
def _index_fields(ary, names):
""" Given a structured array and a sequence of field names
construct new array with just those fields.
Parameters
----------
ary : ndarray
Structured array being subscripted
names : string or list of strings
Either a single field name, or a list of field names
Returns
-------
sub_ary : ndarray
If `names` is a single field name, the return value is identical to
ary.getfield, a writeable view into `ary`. If `names` is a list of
field names the return value is a copy of `ary` containing only those
fields. This is planned to return a view in the future.
Raises
------
ValueError
If `ary` does not contain a field given in `names`.
"""
dt = ary.dtype
#use getfield to index a single field
if isinstance(names, basestring):
try:
return ary.getfield(dt.fields[names][0], dt.fields[names][1])
except KeyError:
raise ValueError("no field of name %s" % names)
for name in names:
if name not in dt.fields:
raise ValueError("no field of name %s" % name)
formats = [dt.fields[name][0] for name in names]
offsets = [dt.fields[name][1] for name in names]
view_dtype = {'names': names, 'formats': formats,
'offsets': offsets, 'itemsize': dt.itemsize}
# return copy for now (future plan to return ary.view(dtype=view_dtype))
copy_dtype = {'names': view_dtype['names'],
'formats': view_dtype['formats']}
return array(ary.view(dtype=view_dtype), dtype=copy_dtype, copy=True)
def _get_all_field_offsets(dtype, base_offset=0):
""" Returns the types and offsets of all fields in a (possibly structured)
data type, including nested fields and subarrays.
Parameters
----------
dtype : data-type
Data type to extract fields from.
base_offset : int, optional
Additional offset to add to all field offsets.
Returns
-------
fields : list of (data-type, int) pairs
A flat list of (dtype, byte offset) pairs.
"""
fields = []
if dtype.fields is not None:
for name in dtype.names:
sub_dtype = dtype.fields[name][0]
sub_offset = dtype.fields[name][1] + base_offset
fields.extend(_get_all_field_offsets(sub_dtype, sub_offset))
else:
if dtype.shape:
sub_offsets = _get_all_field_offsets(dtype.base, base_offset)
count = 1
for dim in dtype.shape:
count *= dim
fields.extend((typ, off + dtype.base.itemsize*j)
for j in range(count) for (typ, off) in sub_offsets)
else:
fields.append((dtype, base_offset))
return fields
def _check_field_overlap(new_fields, old_fields):
""" Perform object memory overlap tests for two data-types (see
_view_is_safe).
This function checks that new fields only access memory contained in old
fields, and that non-object fields are not interpreted as objects and vice
versa.
Parameters
----------
new_fields : list of (data-type, int) pairs
Flat list of (dtype, byte offset) pairs for the new data type, as
returned by _get_all_field_offsets.
old_fields: list of (data-type, int) pairs
Flat list of (dtype, byte offset) pairs for the old data type, as
returned by _get_all_field_offsets.
Raises
------
TypeError
If the new fields are incompatible with the old fields
"""
#first go byte by byte and check we do not access bytes not in old_fields
new_bytes = set()
for tp, off in new_fields:
new_bytes.update(set(range(off, off+tp.itemsize)))
old_bytes = set()
for tp, off in old_fields:
old_bytes.update(set(range(off, off+tp.itemsize)))
if new_bytes.difference(old_bytes):
raise TypeError("view would access data parent array doesn't own")
#next check that we do not interpret non-Objects as Objects, and vv
obj_offsets = [off for (tp, off) in old_fields if tp.type is object_]
obj_size = dtype(object_).itemsize
for fld_dtype, fld_offset in new_fields:
if fld_dtype.type is object_:
# check we do not create object views where
# there are no objects.
if fld_offset not in obj_offsets:
raise TypeError("cannot view non-Object data as Object type")
else:
# next check we do not create non-object views
# where there are already objects.
# see validate_object_field_overlap for a similar computation.
for obj_offset in obj_offsets:
if (fld_offset < obj_offset + obj_size and
obj_offset < fld_offset + fld_dtype.itemsize):
raise TypeError("cannot view Object as non-Object type")
def _getfield_is_safe(oldtype, newtype, offset):
""" Checks safety of getfield for object arrays.
As in _view_is_safe, we need to check that memory containing objects is not
reinterpreted as a non-object datatype and vice versa.
Parameters
----------
oldtype : data-type
Data type of the original ndarray.
newtype : data-type
Data type of the field being accessed by ndarray.getfield
offset : int
Offset of the field being accessed by ndarray.getfield
Raises
------
TypeError
If the field access is invalid
"""
new_fields = _get_all_field_offsets(newtype, offset)
old_fields = _get_all_field_offsets(oldtype)
# raises if there is a problem
_check_field_overlap(new_fields, old_fields)
def _view_is_safe(oldtype, newtype):
""" Checks safety of a view involving object arrays, for example when
doing::
np.zeros(10, dtype=oldtype).view(newtype)
We need to check that
1) No memory that is not an object will be interpreted as a object,
2) No memory containing an object will be interpreted as an arbitrary type.
Both cases can cause segfaults, eg in the case the view is written to.
Strategy here is to also disallow views where newtype has any field in a
place oldtype doesn't.
Parameters
----------
oldtype : data-type
Data type of original ndarray
newtype : data-type
Data type of the view
Raises
------
TypeError
If the new type is incompatible with the old type.
"""
new_fields = _get_all_field_offsets(newtype)
new_size = newtype.itemsize
old_fields = _get_all_field_offsets(oldtype)
old_size = oldtype.itemsize
# if the itemsizes are not equal, we need to check that all the
# 'tiled positions' of the object match up. Here, we allow
# for arbirary itemsizes (even those possibly disallowed
# due to stride/data length issues).
if old_size == new_size:
new_num = old_num = 1
else:
gcd_new_old = _gcd(new_size, old_size)
new_num = old_size // gcd_new_old
old_num = new_size // gcd_new_old
# get position of fields within the tiling
new_fieldtile = [(tp, off + new_size*j)
for j in range(new_num) for (tp, off) in new_fields]
old_fieldtile = [(tp, off + old_size*j)
for j in range(old_num) for (tp, off) in old_fields]
# raises if there is a problem
_check_field_overlap(new_fieldtile, old_fieldtile)
# Given a string containing a PEP 3118 format specifier,
# construct a Numpy dtype
_pep3118_native_map = {
'?': '?',
'b': 'b',
'B': 'B',
'h': 'h',
'H': 'H',
'i': 'i',
'I': 'I',
'l': 'l',
'L': 'L',
'q': 'q',
'Q': 'Q',
'e': 'e',
'f': 'f',
'd': 'd',
'g': 'g',
'Zf': 'F',
'Zd': 'D',
'Zg': 'G',
's': 'S',
'w': 'U',
'O': 'O',
'x': 'V', # padding
}
_pep3118_native_typechars = ''.join(_pep3118_native_map.keys())
_pep3118_standard_map = {
'?': '?',
'b': 'b',
'B': 'B',
'h': 'i2',
'H': 'u2',
'i': 'i4',
'I': 'u4',
'l': 'i4',
'L': 'u4',
'q': 'i8',
'Q': 'u8',
'e': 'f2',
'f': 'f',
'd': 'd',
'Zf': 'F',
'Zd': 'D',
's': 'S',
'w': 'U',
'O': 'O',
'x': 'V', # padding
}
_pep3118_standard_typechars = ''.join(_pep3118_standard_map.keys())
def _dtype_from_pep3118(spec, byteorder='@', is_subdtype=False):
fields = {}
offset = 0
explicit_name = False
this_explicit_name = False
common_alignment = 1
is_padding = False
dummy_name_index = [0]
def next_dummy_name():
dummy_name_index[0] += 1
def get_dummy_name():
while True:
name = 'f%d' % dummy_name_index[0]
if name not in fields:
return name
next_dummy_name()
# Parse spec
while spec:
value = None
# End of structure, bail out to upper level
if spec[0] == '}':
spec = spec[1:]
break
# Sub-arrays (1)
shape = None
if spec[0] == '(':
j = spec.index(')')
shape = tuple(map(int, spec[1:j].split(',')))
spec = spec[j+1:]
# Byte order
if spec[0] in ('@', '=', '<', '>', '^', '!'):
byteorder = spec[0]
if byteorder == '!':
byteorder = '>'
spec = spec[1:]
# Byte order characters also control native vs. standard type sizes
if byteorder in ('@', '^'):
type_map = _pep3118_native_map
type_map_chars = _pep3118_native_typechars
else:
type_map = _pep3118_standard_map
type_map_chars = _pep3118_standard_typechars
# Item sizes
itemsize = 1
if spec[0].isdigit():
j = 1
for j in range(1, len(spec)):
if not spec[j].isdigit():
break
itemsize = int(spec[:j])
spec = spec[j:]
# Data types
is_padding = False
if spec[:2] == 'T{':
value, spec, align, next_byteorder = _dtype_from_pep3118(
spec[2:], byteorder=byteorder, is_subdtype=True)
elif spec[0] in type_map_chars:
next_byteorder = byteorder
if spec[0] == 'Z':
j = 2
else:
j = 1
typechar = spec[:j]
spec = spec[j:]
is_padding = (typechar == 'x')
dtypechar = type_map[typechar]
if dtypechar in 'USV':
dtypechar += '%d' % itemsize
itemsize = 1
numpy_byteorder = {'@': '=', '^': '='}.get(byteorder, byteorder)
value = dtype(numpy_byteorder + dtypechar)
align = value.alignment
else:
raise ValueError("Unknown PEP 3118 data type specifier %r" % spec)
#
# Native alignment may require padding
#
# Here we assume that the presence of a '@' character implicitly implies
# that the start of the array is *already* aligned.
#
extra_offset = 0
if byteorder == '@':
start_padding = (-offset) % align
intra_padding = (-value.itemsize) % align
offset += start_padding
if intra_padding != 0:
if itemsize > 1 or (shape is not None and _prod(shape) > 1):
# Inject internal padding to the end of the sub-item
value = _add_trailing_padding(value, intra_padding)
else:
# We can postpone the injection of internal padding,
# as the item appears at most once
extra_offset += intra_padding
# Update common alignment
common_alignment = (align*common_alignment
/ _gcd(align, common_alignment))
# Convert itemsize to sub-array
if itemsize != 1:
value = dtype((value, (itemsize,)))
# Sub-arrays (2)
if shape is not None:
value = dtype((value, shape))
# Field name
this_explicit_name = False
if spec and spec.startswith(':'):
i = spec[1:].index(':') + 1
name = spec[1:i]
spec = spec[i+1:]
explicit_name = True
this_explicit_name = True
else:
name = get_dummy_name()
if not is_padding or this_explicit_name:
if name in fields:
raise RuntimeError("Duplicate field name '%s' in PEP3118 format"
% name)
fields[name] = (value, offset)
if not this_explicit_name:
next_dummy_name()
byteorder = next_byteorder
offset += value.itemsize
offset += extra_offset
# Check if this was a simple 1-item type
if (len(fields) == 1 and not explicit_name and
fields['f0'][1] == 0 and not is_subdtype):
ret = fields['f0'][0]
else:
ret = dtype(fields)
# Trailing padding must be explicitly added
padding = offset - ret.itemsize
if byteorder == '@':
padding += (-offset) % common_alignment
if is_padding and not this_explicit_name:
ret = _add_trailing_padding(ret, padding)
# Finished
if is_subdtype:
return ret, spec, common_alignment, byteorder
else:
return ret
def _add_trailing_padding(value, padding):
"""Inject the specified number of padding bytes at the end of a dtype"""
if value.fields is None:
vfields = {'f0': (value, 0)}
else:
vfields = dict(value.fields)
if (value.names and value.names[-1] == '' and
value[''].char == 'V'):
# A trailing padding field is already present
vfields[''] = ('V%d' % (vfields[''][0].itemsize + padding),
vfields[''][1])
value = dtype(vfields)
else:
# Get a free name for the padding field
j = 0
while True:
name = 'pad%d' % j
if name not in vfields:
vfields[name] = ('V%d' % padding, value.itemsize)
break
j += 1
value = dtype(vfields)
if '' not in vfields:
# Strip out the name of the padding field
names = list(value.names)
names[-1] = ''
value.names = tuple(names)
return value
def _prod(a):
p = 1
for x in a:
p *= x
return p
def _gcd(a, b):
"""Calculate the greatest common divisor of a and b"""
while b:
a, b = b, a % b
return a
|
cshallue/models | refs/heads/master | research/attention_ocr/python/datasets/unittest_utils_test.py | 15 | # Copyright 2017 The TensorFlow Authors All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Tests for unittest_utils."""
import StringIO
import numpy as np
from PIL import Image as PILImage
import tensorflow as tf
import unittest_utils
class UnittestUtilsTest(tf.test.TestCase):
def test_creates_an_image_of_specified_shape(self):
image, _ = unittest_utils.create_random_image('PNG', (10, 20, 3))
self.assertEqual(image.shape, (10, 20, 3))
def test_encoded_image_corresponds_to_numpy_array(self):
image, encoded = unittest_utils.create_random_image('PNG', (20, 10, 3))
pil_image = PILImage.open(StringIO.StringIO(encoded))
self.assertAllEqual(image, np.array(pil_image))
def test_created_example_has_correct_values(self):
example_serialized = unittest_utils.create_serialized_example({
'labels': [1, 2, 3],
'data': ['FAKE']
})
example = tf.train.Example()
example.ParseFromString(example_serialized)
self.assertProtoEquals("""
features {
feature {
key: "labels"
value { int64_list {
value: 1
value: 2
value: 3
}}
}
feature {
key: "data"
value { bytes_list {
value: "FAKE"
}}
}
}
""", example)
if __name__ == '__main__':
tf.test.main()
|
richardcs/ansible | refs/heads/devel | lib/ansible/modules/network/f5/bigip_software_update.py | 11 | #!/usr/bin/python
# -*- 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
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['stableinterface'],
'supported_by': 'certified'}
DOCUMENTATION = r'''
---
module: bigip_software_update
short_description: Manage the software update settings of a BIG-IP
description:
- Manage the software update settings of a BIG-IP.
version_added: 2.5
options:
auto_check:
description:
- Specifies whether to automatically check for updates on the F5
Networks downloads server.
type: bool
auto_phone_home:
description:
- Specifies whether to automatically send phone home data to the
F5 Networks PhoneHome server.
type: bool
frequency:
description:
- Specifies the schedule for the automatic update check.
choices:
- daily
- monthly
- weekly
extends_documentation_fragment: f5
author:
- Tim Rupp (@caphrim007)
- Wojciech Wypior (@wojtek0806)
'''
EXAMPLES = r'''
- name: Enable automatic update checking
bigip_software_update:
auto_check: yes
provider:
password: secret
server: lb.mydomain.com
user: admin
delegate_to: localhost
- name: Disable automatic update checking and phoning home
bigip_software_update:
auto_check: no
auto_phone_home: no
provider:
password: secret
server: lb.mydomain.com
user: admin
delegate_to: localhost
'''
RETURN = r'''
auto_check:
description: Whether the system checks for updates automatically.
returned: changed
type: bool
sample: True
auto_phone_home:
description: Whether the system automatically sends phone home data.
returned: changed
type: bool
sample: True
frequency:
description: Frequency of auto update checks
returned: changed
type: string
sample: weekly
'''
from ansible.module_utils.basic import AnsibleModule
try:
from library.module_utils.network.f5.bigip import F5RestClient
from library.module_utils.network.f5.common import F5ModuleError
from library.module_utils.network.f5.common import AnsibleF5Parameters
from library.module_utils.network.f5.common import cleanup_tokens
from library.module_utils.network.f5.common import f5_argument_spec
from library.module_utils.network.f5.common import exit_json
from library.module_utils.network.f5.common import fail_json
except ImportError:
from ansible.module_utils.network.f5.bigip import F5RestClient
from ansible.module_utils.network.f5.common import F5ModuleError
from ansible.module_utils.network.f5.common import AnsibleF5Parameters
from ansible.module_utils.network.f5.common import cleanup_tokens
from ansible.module_utils.network.f5.common import f5_argument_spec
from ansible.module_utils.network.f5.common import exit_json
from ansible.module_utils.network.f5.common import fail_json
class Parameters(AnsibleF5Parameters):
api_map = {
'autoCheck': 'auto_check',
'autoPhonehome': 'auto_phone_home'
}
api_attributes = [
'autoCheck', 'autoPhonehome', 'frequency',
]
updatables = [
'auto_check', 'auto_phone_home', 'frequency',
]
returnables = [
'auto_check', 'auto_phone_home', 'frequency',
]
class ApiParameters(Parameters):
@property
def auto_check(self):
if self._values['auto_check'] is None:
return None
return self._values['auto_check']
class ModuleParameters(Parameters):
@property
def auto_check(self):
if self._values['auto_check'] is None:
return None
elif self._values['auto_check'] is True:
return 'enabled'
else:
return 'disabled'
@property
def auto_phone_home(self):
if self._values['auto_phone_home'] is None:
return None
elif self._values['auto_phone_home'] is True:
return 'enabled'
else:
return 'disabled'
class Changes(Parameters):
def to_return(self):
result = {}
try:
for returnable in self.returnables:
result[returnable] = getattr(self, returnable)
result = self._filter_params(result)
except Exception:
pass
return result
class UsableChanges(Changes):
pass
class ReportableChanges(Changes):
@property
def auto_check(self):
if self._values['auto_check'] == 'enabled':
return True
elif self._values['auto_check'] == 'disabled':
return False
@property
def auto_phone_home(self):
if self._values['auto_phone_home'] == 'enabled':
return True
elif self._values['auto_phone_home'] == 'disabled':
return False
class Difference(object):
def __init__(self, want, have=None):
self.want = want
self.have = have
def compare(self, param):
try:
result = getattr(self, param)
return result
except AttributeError:
return self.__default(param)
def __default(self, param):
attr1 = getattr(self.want, param)
try:
attr2 = getattr(self.have, param)
if attr1 != attr2:
return attr1
except AttributeError:
return attr1
class ModuleManager(object):
def __init__(self, *args, **kwargs):
self.module = kwargs.get('module', None)
self.client = kwargs.get('client', None)
self.have = None
self.want = ModuleParameters(params=self.module.params)
self.changes = UsableChanges()
def exec_module(self): # lgtm [py/similar-function]
result = dict()
changed = self.update()
reportable = ReportableChanges(params=self.changes.to_return())
changes = reportable.to_return()
result.update(**changes)
result.update(dict(changed=changed))
self._announce_deprecations(result)
return result
def _announce_deprecations(self, result):
warnings = result.pop('__warnings', [])
for warning in warnings:
self.module.deprecate(
msg=warning['msg'],
version=warning['version']
)
def _update_changed_options(self):
diff = Difference(self.want, self.have)
updatables = Parameters.updatables
changed = dict()
for k in updatables:
change = diff.compare(k)
if change is None:
continue
else:
if isinstance(change, dict):
changed.update(change)
else:
changed[k] = change
if changed:
self.changes = UsableChanges(params=changed)
return True
return False
def should_update(self):
result = self._update_changed_options()
if result:
return True
return False
def update(self):
self.have = self.read_current_from_device()
if not self.should_update():
return False
if self.module.check_mode:
return True
self.update_on_device()
return True
def read_current_from_device(self):
uri = "https://{0}:{1}/mgmt/tm/sys/software/update/".format(
self.client.provider['server'],
self.client.provider['server_port'],
)
resp = self.client.api.get(uri)
try:
response = resp.json()
except ValueError as ex:
raise F5ModuleError(str(ex))
if 'code' in response and response['code'] == 400:
if 'message' in response:
raise F5ModuleError(response['message'])
else:
raise F5ModuleError(resp.content)
return ApiParameters(params=response)
def update_on_device(self):
params = self.changes.api_params()
uri = "https://{0}:{1}/mgmt/tm/sys/software/update/".format(
self.client.provider['server'],
self.client.provider['server_port'],
)
resp = self.client.api.patch(uri, json=params)
try:
response = resp.json()
except ValueError as ex:
raise F5ModuleError(str(ex))
if 'code' in response and response['code'] == 400:
if 'message' in response:
raise F5ModuleError(response['message'])
else:
raise F5ModuleError(resp.content)
class ArgumentSpec(object):
def __init__(self):
self.supports_check_mode = True
argument_spec = dict(
auto_check=dict(
type='bool'
),
auto_phone_home=dict(
type='bool'
),
frequency=dict(
choices=['daily', 'monthly', 'weekly']
)
)
self.argument_spec = {}
self.argument_spec.update(f5_argument_spec)
self.argument_spec.update(argument_spec)
def main():
spec = ArgumentSpec()
module = AnsibleModule(
argument_spec=spec.argument_spec,
supports_check_mode=spec.supports_check_mode
)
client = F5RestClient(**module.params)
try:
mm = ModuleManager(module=module, client=client)
results = mm.exec_module()
cleanup_tokens(client)
exit_json(module, results, client)
except F5ModuleError as ex:
cleanup_tokens(client)
fail_json(module, ex, client)
if __name__ == '__main__':
main()
|
TNT-Samuel/Coding-Projects | refs/heads/master | DNS Server/Source - Copy/Lib/site-packages/urllib3/util/__init__.py | 204 | from __future__ import absolute_import
# For backwards compatibility, provide imports that used to be here.
from .connection import is_connection_dropped
from .request import make_headers
from .response import is_fp_closed
from .ssl_ import (
SSLContext,
HAS_SNI,
IS_PYOPENSSL,
IS_SECURETRANSPORT,
assert_fingerprint,
resolve_cert_reqs,
resolve_ssl_version,
ssl_wrap_socket,
)
from .timeout import (
current_time,
Timeout,
)
from .retry import Retry
from .url import (
get_host,
parse_url,
split_first,
Url,
)
from .wait import (
wait_for_read,
wait_for_write
)
__all__ = (
'HAS_SNI',
'IS_PYOPENSSL',
'IS_SECURETRANSPORT',
'SSLContext',
'Retry',
'Timeout',
'Url',
'assert_fingerprint',
'current_time',
'is_connection_dropped',
'is_fp_closed',
'get_host',
'parse_url',
'make_headers',
'resolve_cert_reqs',
'resolve_ssl_version',
'split_first',
'ssl_wrap_socket',
'wait_for_read',
'wait_for_write'
)
|
jwren/intellij-community | refs/heads/master | python/testData/inspections/PyTypeCheckerInspection/BuiltinInputPy2.py | 62 | class A:
pass
input(A())
input(b"b")
input(u"u") |
GheRivero/ansible | refs/heads/devel | lib/ansible/modules/cloud/ovirt/ovirt_disk_facts.py | 63 | #!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright (c) 2017 Red Hat, Inc.
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
#
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
DOCUMENTATION = '''
---
module: ovirt_disk_facts
short_description: Retrieve facts about one or more oVirt/RHV disks
author: "Katerina Koukiou (@kkoukiou)"
version_added: "2.5"
description:
- "Retrieve facts about one or more oVirt/RHV disks."
notes:
- "This module creates a new top-level C(ovirt_disks) fact, which
contains a list of disks."
options:
pattern:
description:
- "Search term which is accepted by oVirt/RHV search backend."
- "For example to search Disk X from storage Y use following pattern:
name=X and storage.name=Y"
extends_documentation_fragment: ovirt_facts
'''
EXAMPLES = '''
# Examples don't contain auth parameter for simplicity,
# look at ovirt_auth module to see how to reuse authentication:
# Gather facts about all Disks which names start with C(centos)
- ovirt_disk_facts:
pattern: name=centos*
- debug:
var: ovirt_disks
'''
RETURN = '''
ovirt_disks:
description: "List of dictionaries describing the Disks. Disk attributes are mapped to dictionary keys,
all Disks attributes can be found at following url: http://ovirt.github.io/ovirt-engine-api-model/master/#types/disk."
returned: On success.
type: list
'''
import traceback
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.ovirt import (
check_sdk,
create_connection,
get_dict_of_struct,
ovirt_facts_full_argument_spec,
)
def main():
argument_spec = ovirt_facts_full_argument_spec(
pattern=dict(default='', required=False),
)
module = AnsibleModule(argument_spec)
check_sdk(module)
try:
auth = module.params.pop('auth')
connection = create_connection(auth)
disks_service = connection.system_service().disks_service()
disks = disks_service.list(
search=module.params['pattern'],
)
module.exit_json(
changed=False,
ansible_facts=dict(
ovirt_disks=[
get_dict_of_struct(
struct=c,
connection=connection,
fetch_nested=module.params.get('fetch_nested'),
attributes=module.params.get('nested_attributes'),
) for c in disks
],
),
)
except Exception as e:
module.fail_json(msg=str(e), exception=traceback.format_exc())
finally:
connection.close(logout=auth.get('token') is None)
if __name__ == '__main__':
main()
|
brittanystoroz/kitsune | refs/heads/master | kitsune/search/tests/test_search_utils.py | 8 | from nose.tools import ok_
from kitsune.search.forms import SimpleSearchForm
from kitsune.search.search_utils import generate_simple_search
from kitsune.sumo.tests import TestCase
class SimpleSearchTests(TestCase):
def test_language_en_us(self):
form = SimpleSearchForm({'q': 'foo'})
ok_(form.is_valid())
s = generate_simple_search(form, 'en-US', with_highlights=False)
# NB: Comparing bits of big trees is hard, so we serialize it
# and look for strings.
s_string = str(s.build_search())
# Verify locale
ok_("{'term': {'document_locale': 'en-US'}}" in s_string)
# Verify en-US has the right synonym-enhanced analyzer
ok_("'analyzer': 'snowball-english-synonyms'" in s_string)
def test_language_fr(self):
form = SimpleSearchForm({'q': 'foo'})
ok_(form.is_valid())
s = generate_simple_search(form, 'fr', with_highlights=False)
s_string = str(s.build_search())
# Verify locale
ok_("{'term': {'document_locale': 'fr'}}" in s_string)
# Verify fr has right synonym-less analyzer
ok_("'analyzer': 'snowball-french'" in s_string)
def test_language_zh_cn(self):
form = SimpleSearchForm({'q': 'foo'})
ok_(form.is_valid())
s = generate_simple_search(form, 'zh-CN', with_highlights=False)
s_string = str(s.build_search())
# Verify locale
ok_("{'term': {'document_locale': 'zh-CN'}}" in s_string)
# Verify standard analyzer is used
ok_("'analyzer': 'chinese'" in s_string)
def test_with_highlights(self):
form = SimpleSearchForm({'q': 'foo'})
ok_(form.is_valid())
s = generate_simple_search(form, 'en-US', with_highlights=True)
ok_('highlight' in s.build_search())
s = generate_simple_search(form, 'en-US', with_highlights=False)
ok_('highlight' not in s.build_search())
|
zetaops/zengine | refs/heads/develop | zengine/views/task_manager_actions.py | 1 | # Copyright (C) 2015 ZetaOps Inc.
#
# This file is licensed under the GNU General Public License v3
# (GPLv3). See LICENSE.txt for details.
from zengine.views.base import BaseView
from zengine import forms
from zengine.forms import fields
from zengine.models import TaskInvitation
from pyoko.lib.utils import get_object_from_path
from pyoko.conf import settings
from datetime import datetime
from zengine.lib.utils import gettext as _
RoleModel = get_object_from_path(settings.ROLE_MODEL)
class TaskManagerActionsView(BaseView):
def __init__(self, current=None):
super(TaskManagerActionsView, self).__init__(current)
if 'task_inv_key' not in self.current.task_data:
self.current.task_data['task_inv_key'] = self.input['filters']['task_inv_id']['values'][
0]
self.task_invitation_key = self.current.task_data['task_inv_key']
# - Assign Yourself -
def assign_yourself(self):
"""
Assigning the workflow to itself.
The selected job is checked to see if there is an assigned role.
If it does not have a role assigned to it, it takes the job to itself
and displays a message that the process is successful.
If there is a role assigned to it, it does not do any operation
and the message is displayed on the screen.
.. code-block:: python
# request:
{
'task_inv_key': string,
}
"""
task_invitation = TaskInvitation.objects.get(self.task_invitation_key)
wfi = task_invitation.instance
if not wfi.current_actor.exist:
wfi.current_actor = self.current.role
wfi.save()
[inv.delete() for inv in TaskInvitation.objects.filter(instance=wfi) if
not inv == task_invitation]
title = _(u"Successful")
msg = _(u"You have successfully assigned the job to yourself.")
else:
title = _(u"Unsuccessful")
msg = _(u"Unfortunately, this job is already taken by someone else.")
self.current.msg_box(title=title, msg=msg)
# - Assign Yourself -
# - Assign to same abstract role and unit -
def select_role(self):
"""
The workflow method to be assigned to the person with the same role and unit as the user.
.. code-block:: python
# request:
{
'task_inv_key': string,
}
"""
roles = [(m.key, m.__unicode__()) for m in RoleModel.objects.filter(
abstract_role=self.current.role.abstract_role,
unit=self.current.role.unit) if m != self.current.role]
if roles:
_form = forms.JsonForm(title=_(u'Assign to workflow'))
_form.select_role = fields.Integer(_(u"Chose Role"), choices=roles)
_form.explain_text = fields.String(_(u"Explain Text"), required=False)
_form.send_button = fields.Button(_(u"Send"))
self.form_out(_form)
else:
title = _(u"Unsuccessful")
msg = _(u"Assign role not found")
self.current.msg_box(title=title, msg=msg)
def send_workflow(self):
"""
With the workflow instance and the task invitation is assigned a role.
"""
task_invitation = TaskInvitation.objects.get(self.task_invitation_key)
wfi = task_invitation.instance
select_role = self.input['form']['select_role']
if wfi.current_actor == self.current.role:
task_invitation.role = RoleModel.objects.get(select_role)
wfi.current_actor = RoleModel.objects.get(select_role)
wfi.save()
task_invitation.save()
[inv.delete() for inv in TaskInvitation.objects.filter(instance=wfi) if
not inv == task_invitation]
title = _(u"Successful")
msg = _(u"The workflow was assigned to someone else with success.")
else:
title = _(u"Unsuccessful")
msg = _(u"This workflow does not belong to you, you cannot assign it to someone else.")
self.current.msg_box(title=title, msg=msg)
# - Assign to same abstract role and unit -
# - Postponed workflow -
def select_postponed_date(self):
"""
The time intervals at which the workflow is to be extended are determined.
.. code-block:: python
# request:
{
'task_inv_key': string,
}
"""
_form = forms.JsonForm(title="Postponed Workflow")
_form.start_date = fields.DateTime("Start Date")
_form.finish_date = fields.DateTime("Finish Date")
_form.save_button = fields.Button("Save")
self.form_out(_form)
def save_date(self):
"""
Invitations with the same workflow status are deleted.
Workflow instance and invitation roles change.
"""
task_invitation = TaskInvitation.objects.get(self.task_invitation_key)
wfi = task_invitation.instance
if wfi.current_actor.exist and wfi.current_actor == self.current.role:
dt_start = datetime.strptime(self.input['form']['start_date'], "%d.%m.%Y")
dt_finish = datetime.strptime(self.input['form']['finish_date'], "%d.%m.%Y")
task_invitation.start_date = dt_start
task_invitation.finish_date = dt_finish
task_invitation.save()
wfi.start_date = dt_start
wfi.finish_date = dt_finish
wfi.save()
title = _(u"Successful")
msg = _(u"You've extended the workflow time.")
else:
title = _(u"Unsuccessful")
msg = _(u"This workflow does not belong to you.")
self.current.msg_box(title=title, msg=msg)
# - Postponed workflow -
# - Suspend workflow -
def suspend(self):
"""
If there is a role assigned to the workflow and
it is the same as the user, it can drop the workflow.
If it does not exist, it can not do anything.
.. code-block:: python
# request:
{
'task_inv_key': string,
}
"""
task_invitation = TaskInvitation.objects.get(self.task_invitation_key)
wfi = task_invitation.instance
if wfi.current_actor.exist and wfi.current_actor == self.current.role:
for m in RoleModel.objects.filter(abstract_role=self.current.role.abstract_role,
unit=self.current.role.unit):
if m != self.current.role:
task_invitation.key = ''
task_invitation.role = m
task_invitation.save()
wfi.current_actor = RoleModel()
wfi.save()
title = _(u"Successful")
msg = _(u"You left the workflow.")
else:
title = _(u"Unsuccessful")
msg = _(u"Unfortunately, this workflow does not belong to you or is already idle.")
self.current.msg_box(title=title, msg=msg)
# - Suspend workflow -
|
google/capirca | refs/heads/master | tests/lib/pcap_test.py | 1 | # Copyright 2016 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.
"""Unittest for pcap rendering module."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import datetime
import unittest
from capirca.lib import aclgenerator
from capirca.lib import nacaddr
from capirca.lib import naming
from capirca.lib import pcap
from capirca.lib import policy
import mock
GOOD_HEADER = """
header {
comment:: "this is a test acl"
target:: pcap test-filter
}
"""
GOOD_HEADER_IN = """
header {
comment:: "this is a test acl"
target:: pcap test-filter in
}
"""
GOOD_HEADER_OUT = """
header {
comment:: "this is a test acl"
target:: pcap test-filter out
}
"""
GOOD_TERM_ICMP = """
term good-term-icmp {
protocol:: icmp
action:: accept
}
"""
GOOD_TERM_ICMP_TYPES = """
term good-term-icmp-types {
protocol:: icmp
icmp-type:: echo-reply unreachable time-exceeded
action:: deny
}
"""
GOOD_TERM_ICMPV6 = """
term good-term-icmpv6 {
protocol:: icmpv6
action:: accept
}
"""
BAD_TERM_ICMP = """
term test-icmp {
icmp-type:: echo-request echo-reply
action:: accept
}
"""
BAD_TERM_ACTION = """
term bad-term-action {
protocol:: icmp
action:: undefined
}
"""
GOOD_TERM_TCP = """
term good-term-tcp {
comment:: "Test term 1"
destination-address:: PROD_NETWRK
destination-port:: SMTP
protocol:: tcp
action:: accept
}
"""
GOOD_WARNING_TERM = """
term good-warning-term {
comment:: "Test term 1"
destination-address:: PROD_NETWRK
destination-port:: SMTP
protocol:: tcp
policer:: batman
action:: accept
}
"""
GOOD_TERM_LOG = """
term good-term-log {
protocol:: tcp
logging:: true
action:: accept
}
"""
GOOD_ICMP_CODE = """
term good_term {
protocol:: icmp
icmp-type:: unreachable
icmp-code:: 3 4
action:: accept
}
"""
EXPIRED_TERM = """
term expired_test {
expiration:: 2000-1-1
action:: deny
}
"""
EXPIRING_TERM = """
term is_expiring {
expiration:: %s
action:: accept
}
"""
MULTIPLE_PROTOCOLS_TERM = """
term multi-proto {
protocol:: tcp udp icmp
action:: accept
}
"""
NEXT_TERM = """
term next {
action:: next
}
"""
NEXT_LOG_TERM = """
term next-log {
logging:: true
action:: next
}
"""
ESTABLISHED_TERM = """
term accept-established {
protocol:: tcp
option:: tcp-established
action:: accept
}
"""
VRRP_TERM = """
term vrrp-term {
protocol:: vrrp
action:: accept
}
"""
UNICAST_TERM = """
term unicast-term {
destination-address:: ANY
protocol:: tcp
action:: accept
}
"""
GOOD_TERM_HBH = """
term good-term-hbh {
protocol:: hopopt
action:: accept
}
"""
SUPPORTED_TOKENS = {
'action',
'comment',
'destination_address',
'destination_address_exclude',
'destination_port',
'expiration',
'icmp_code',
'icmp_type',
'stateless_reply',
'logging',
'name',
'option',
'platform',
'platform_exclude',
'protocol',
'source_address',
'source_address_exclude',
'source_port',
'translated',
}
SUPPORTED_SUB_TOKENS = {
'action': {'accept', 'deny', 'reject', 'next'},
'icmp_type': {
'alternate-address',
'certification-path-advertisement',
'certification-path-solicitation',
'conversion-error',
'destination-unreachable',
'echo-reply',
'echo-request',
'mobile-redirect',
'home-agent-address-discovery-reply',
'home-agent-address-discovery-request',
'icmp-node-information-query',
'icmp-node-information-response',
'information-request',
'inverse-neighbor-discovery-advertisement',
'inverse-neighbor-discovery-solicitation',
'mask-reply',
'mask-request',
'information-reply',
'mobile-prefix-advertisement',
'mobile-prefix-solicitation',
'multicast-listener-done',
'multicast-listener-query',
'multicast-listener-report',
'multicast-router-advertisement',
'multicast-router-solicitation',
'multicast-router-termination',
'neighbor-advertisement',
'neighbor-solicit',
'packet-too-big',
'parameter-problem',
'redirect',
'redirect-message',
'router-advertisement',
'router-renumbering',
'router-solicit',
'router-solicitation',
'source-quench',
'time-exceeded',
'timestamp-reply',
'timestamp-request',
'unreachable',
'version-2-multicast-listener-report',
},
'option': {'syn',
'ack',
'fin',
'rst',
'urg',
'psh',
'all',
'none',
'established',
'tcp-established'}
}
# Print a info message when a term is set to expire in that many weeks.
# This is normally passed from command line.
EXP_INFO = 2
class PcapFilter(unittest.TestCase):
def setUp(self):
super(PcapFilter, self).setUp()
self.naming = mock.create_autospec(naming.Naming)
def testTcp(self):
self.naming.GetNetAddr.return_value = [nacaddr.IP('10.0.0.0/8')]
self.naming.GetServiceByProto.return_value = ['25']
acl = pcap.PcapFilter(policy.ParsePolicy(
GOOD_HEADER + GOOD_TERM_TCP, self.naming), EXP_INFO)
result = str(acl)
self.assertIn(
'(dst net 10.0.0.0/8) and (proto \\tcp) and (dst port 25)', result,
'did not find actual term for good-term-tcp')
self.naming.GetNetAddr.assert_called_once_with('PROD_NETWRK')
self.naming.GetServiceByProto.assert_called_once_with('SMTP', 'tcp')
def testLog(self):
acl = pcap.PcapFilter(policy.ParsePolicy(
GOOD_HEADER + GOOD_TERM_LOG, self.naming), EXP_INFO)
result = str(acl)
self.assertIn(
'proto \\tcp', result,
'did not find actual term for good-term-log')
def testIcmp(self):
acl = pcap.PcapFilter(policy.ParsePolicy(
GOOD_HEADER + GOOD_TERM_ICMP, self.naming), EXP_INFO)
result = str(acl)
self.assertIn(
'proto \\icmp', result,
'did not find actual term for good-term-icmp')
def testIcmpCode(self):
acl = pcap.PcapFilter(policy.ParsePolicy(
GOOD_HEADER + GOOD_ICMP_CODE, self.naming), EXP_INFO)
result = str(acl)
self.assertIn('and icmp[icmpcode] == 3', result, result)
self.assertIn('and icmp[icmpcode] == 4', result, result)
def testIcmpTypes(self):
acl = pcap.PcapFilter(policy.ParsePolicy(
GOOD_HEADER + GOOD_TERM_ICMP_TYPES, self.naming), EXP_INFO)
result = str(acl)
self.assertIn(
'(proto \\icmp) and (icmp[icmptype] == 0 or icmp[icmptype] == 3'
' or icmp[icmptype] == 11)', result,
'did not find actual term for good-term-icmp-types')
def testIcmpv6(self):
acl = pcap.PcapFilter(policy.ParsePolicy(
GOOD_HEADER + GOOD_TERM_ICMPV6, self.naming), EXP_INFO)
result = str(acl)
self.assertIn(
'icmp6', result,
'did not find actual term for good-term-icmpv6')
def testBadIcmp(self):
acl = pcap.PcapFilter(policy.ParsePolicy(
GOOD_HEADER + BAD_TERM_ICMP, self.naming), EXP_INFO)
self.assertRaises(aclgenerator.UnsupportedFilterError,
str, acl)
@mock.patch.object(pcap.logging, 'warning')
def testExpiredTerm(self, mock_warn):
pcap.PcapFilter(policy.ParsePolicy(
GOOD_HEADER + EXPIRED_TERM, self.naming), EXP_INFO)
mock_warn.assert_called_once_with(
'WARNING: Term %s in policy %s is expired and '
'will not be rendered.', 'expired_test', 'test-filter')
@mock.patch.object(pcap.logging, 'info')
def testExpiringTerm(self, mock_info):
exp_date = datetime.date.today() + datetime.timedelta(weeks=EXP_INFO)
pcap.PcapFilter(policy.ParsePolicy(
GOOD_HEADER + EXPIRING_TERM % exp_date.strftime('%Y-%m-%d'),
self.naming), EXP_INFO)
mock_info.assert_called_once_with(
'INFO: Term %s in policy %s expires in '
'less than two weeks.', 'is_expiring', 'test-filter')
def testMultiprotocol(self):
acl = pcap.PcapFilter(policy.ParsePolicy(
GOOD_HEADER + MULTIPLE_PROTOCOLS_TERM, self.naming), EXP_INFO)
result = str(acl)
self.assertIn(
'(proto \\tcp or proto \\udp or proto \\icmp)', result,
'did not find actual term for multi-proto')
def testNextTerm(self):
acl = pcap.PcapFilter(policy.ParsePolicy(
GOOD_HEADER + NEXT_TERM, self.naming), EXP_INFO)
result = str(acl)
self.assertIn('', result,
'did not find actual term for good-term-icmpv6')
def testTcpOptions(self):
acl = pcap.PcapFilter(policy.ParsePolicy(
GOOD_HEADER + ESTABLISHED_TERM, self.naming), EXP_INFO)
result = str(acl)
self.assertIn(
'(tcp[tcpflags] & (tcp-ack) == (tcp-ack)', result,
'did not find actual term for established')
def testVrrpTerm(self):
acl = pcap.PcapFilter(policy.ParsePolicy(
GOOD_HEADER + VRRP_TERM, self.naming), EXP_INFO)
result = str(acl)
self.assertIn(
'(proto 112)', result,
'did not find actual term for vrrp')
def testMultiHeader(self):
acl = pcap.PcapFilter(policy.ParsePolicy(
GOOD_HEADER + GOOD_TERM_LOG + GOOD_HEADER + GOOD_TERM_ICMP,
self.naming), EXP_INFO)
result = str(acl)
self.assertIn(
'((((proto \\tcp))\n))\nor\n((((proto \\icmp))\n))', result,
'did not find actual terms for multi-header')
def testDirectional(self):
acl = pcap.PcapFilter(policy.ParsePolicy(
GOOD_HEADER_IN + GOOD_TERM_LOG + GOOD_HEADER_OUT + GOOD_TERM_ICMP,
self.naming), EXP_INFO)
result = str(acl)
self.assertIn(
'(((dst net localhost and ((proto \\tcp)))\n))\nor\n'
'(((src net localhost and ((proto \\icmp)))\n))', result,
'did not find actual terms for directional')
def testUnicastIPv6(self):
self.naming.GetNetAddr.return_value = [nacaddr.IP('::/0')]
acl = pcap.PcapFilter(policy.ParsePolicy(
GOOD_HEADER_IN + UNICAST_TERM, self.naming), EXP_INFO)
result = str(acl)
self.assertIn(
'(dst net localhost and ((proto \\tcp)))', result,
'did not find actual terms for unicast-term')
self.naming.GetNetAddr.assert_called_once_with('ANY')
def testHbh(self):
acl = pcap.PcapFilter(policy.ParsePolicy(
GOOD_HEADER + GOOD_TERM_HBH, self.naming), EXP_INFO)
result = str(acl)
self.assertIn(
'(ip6 protochain 0)', result,
'did not find actual terms for unicast-term')
def testBuildTokens(self):
self.naming.GetNetAddr.return_value = [nacaddr.IP('10.0.0.0/8')]
self.naming.GetServiceByProto.return_value = ['25']
pol1 = pcap.PcapFilter(policy.ParsePolicy(GOOD_HEADER + GOOD_TERM_TCP,
self.naming), EXP_INFO)
st, sst = pol1._BuildTokens()
self.assertEqual(st, SUPPORTED_TOKENS)
self.assertEqual(sst, SUPPORTED_SUB_TOKENS)
def testBuildWarningTokens(self):
self.naming.GetNetAddr.return_value = [nacaddr.IP('10.0.0.0/8')]
self.naming.GetServiceByProto.return_value = ['25']
pol1 = pcap.PcapFilter(
policy.ParsePolicy(GOOD_HEADER + GOOD_WARNING_TERM,
self.naming), EXP_INFO)
st, sst = pol1._BuildTokens()
self.assertEqual(st, SUPPORTED_TOKENS)
self.assertEqual(sst, SUPPORTED_SUB_TOKENS)
if __name__ == '__main__':
unittest.main()
|
JetBrains/intellij-community | refs/heads/master | python/testData/inspections/PyUnresolvedReferencesInspection/FunctionInIgnoredIdentifiers/mock/__init__.py | 72 | from mock.mock import * |
yohanko88/gem5-DC | refs/heads/master | src/arch/x86/isa/insts/simd128/integer/save_and_restore_state/save_and_restore_state.py | 31 | # Copyright (c) 2013 Andreas Sandberg
# 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 the copyright holders nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
# Authors: Andreas Sandberg
# Register usage:
# t1, t2 == temporaries
# t7 == base address (RIP or SIB)
loadX87RegTemplate = '''
ld t1, seg, %(mode)s, "DISPLACEMENT + 32 + 16 * %(idx)i", dataSize=8
ld t2, seg, %(mode)s, "DISPLACEMENT + 32 + 16 * %(idx)i + 8", dataSize=2
cvtint_fp80 st(%(idx)i), t1, t2
'''
storeX87RegTemplate = '''
cvtfp80h_int t1, st(%(idx)i)
cvtfp80l_int t2, st(%(idx)i)
st t1, seg, %(mode)s, "DISPLACEMENT + 32 + 16 * %(idx)i", dataSize=8
st t2, seg, %(mode)s, "DISPLACEMENT + 32 + 16 * %(idx)i + 8", dataSize=2
'''
loadXMMRegTemplate = '''
ldfp "InstRegIndex(FLOATREG_XMM_LOW(%(idx)i))", seg, %(mode)s, \
"DISPLACEMENT + 160 + 16 * %(idx)i", dataSize=8
ldfp "InstRegIndex(FLOATREG_XMM_HIGH(%(idx)i))", seg, %(mode)s, \
"DISPLACEMENT + 160 + 16 * %(idx)i + 8", dataSize=8
'''
storeXMMRegTemplate = '''
stfp "InstRegIndex(FLOATREG_XMM_LOW(%(idx)i))", seg, %(mode)s, \
"DISPLACEMENT + 160 + 16 * %(idx)i", dataSize=8
stfp "InstRegIndex(FLOATREG_XMM_HIGH(%(idx)i))", seg, %(mode)s, \
"DISPLACEMENT + 160 + 16 * %(idx)i + 8", dataSize=8
'''
loadAllDataRegs = \
"".join([loadX87RegTemplate % { "idx" : i, "mode" : "%(mode)s" }
for i in range(8)]) + \
"".join([loadXMMRegTemplate % { "idx" : i, "mode" : "%(mode)s" }
for i in range(16)])
storeAllDataRegs = \
"".join([storeX87RegTemplate % { "idx" : i, "mode" : "%(mode)s" }
for i in range(8)]) + \
"".join([storeXMMRegTemplate % { "idx" : i, "mode" : "%(mode)s" }
for i in range(16)])
fxsaveCommonTemplate = """
rdval t1, fcw
st t1, seg, %(mode)s, "DISPLACEMENT + 0", dataSize=2
# FSW includes TOP when read
rdval t1, fsw
st t1, seg, %(mode)s, "DISPLACEMENT + 2", dataSize=2
# FTW
rdxftw t1
st t1, seg, %(mode)s, "DISPLACEMENT + 4", dataSize=1
rdval t1, "InstRegIndex(MISCREG_FOP)"
st t1, seg, %(mode)s, "DISPLACEMENT + 6", dataSize=2
rdval t1, "InstRegIndex(MISCREG_MXCSR)"
st t1, seg, %(mode)s, "DISPLACEMENT + 16 + 8", dataSize=4
# MXCSR_MASK, software assumes the default (0xFFBF) if 0.
limm t1, 0xFFFF
st t1, seg, %(mode)s, "DISPLACEMENT + 16 + 12", dataSize=4
""" + storeAllDataRegs
fxsave32Template = """
rdval t1, "InstRegIndex(MISCREG_FIOFF)"
st t1, seg, %(mode)s, "DISPLACEMENT + 8", dataSize=4
rdval t1, "InstRegIndex(MISCREG_FISEG)"
st t1, seg, %(mode)s, "DISPLACEMENT + 12", dataSize=2
rdval t1, "InstRegIndex(MISCREG_FOOFF)"
st t1, seg, %(mode)s, "DISPLACEMENT + 16 + 0", dataSize=4
rdval t1, "InstRegIndex(MISCREG_FOSEG)"
st t1, seg, %(mode)s, "DISPLACEMENT + 16 + 4", dataSize=2
""" + fxsaveCommonTemplate
fxsave64Template = """
rdval t1, "InstRegIndex(MISCREG_FIOFF)"
st t1, seg, %(mode)s, "DISPLACEMENT + 8", dataSize=8
rdval t1, "InstRegIndex(MISCREG_FOOFF)"
st t1, seg, %(mode)s, "DISPLACEMENT + 16 + 0", dataSize=8
""" + fxsaveCommonTemplate
fxrstorCommonTemplate = """
ld t1, seg, %(mode)s, "DISPLACEMENT + 0", dataSize=2
wrval fcw, t1
# FSW includes TOP when read
ld t1, seg, %(mode)s, "DISPLACEMENT + 2", dataSize=2
wrval fsw, t1
# FTW
ld t1, seg, %(mode)s, "DISPLACEMENT + 4", dataSize=1
wrxftw t1
ld t1, seg, %(mode)s, "DISPLACEMENT + 6", dataSize=2
wrval "InstRegIndex(MISCREG_FOP)", t1
ld t1, seg, %(mode)s, "DISPLACEMENT + 16 + 8", dataSize=4
wrval "InstRegIndex(MISCREG_MXCSR)", t1
""" + loadAllDataRegs
fxrstor32Template = """
ld t1, seg, %(mode)s, "DISPLACEMENT + 8", dataSize=4
wrval "InstRegIndex(MISCREG_FIOFF)", t1
ld t1, seg, %(mode)s, "DISPLACEMENT + 12", dataSize=2
wrval "InstRegIndex(MISCREG_FISEG)", t1
ld t1, seg, %(mode)s, "DISPLACEMENT + 16 + 0", dataSize=4
wrval "InstRegIndex(MISCREG_FOOFF)", t1
ld t1, seg, %(mode)s, "DISPLACEMENT + 16 + 4", dataSize=2
wrval "InstRegIndex(MISCREG_FOSEG)", t1
""" + fxrstorCommonTemplate
fxrstor64Template = """
limm t2, 0, dataSize=8
ld t1, seg, %(mode)s, "DISPLACEMENT + 8", dataSize=8
wrval "InstRegIndex(MISCREG_FIOFF)", t1
wrval "InstRegIndex(MISCREG_FISEG)", t2
ld t1, seg, %(mode)s, "DISPLACEMENT + 16 + 0", dataSize=8
wrval "InstRegIndex(MISCREG_FOOFF)", t1
wrval "InstRegIndex(MISCREG_FOSEG)", t2
""" + fxrstorCommonTemplate
microcode = '''
def macroop FXSAVE_M {
''' + fxsave32Template % { "mode" : "sib" } + '''
};
def macroop FXSAVE_P {
rdip t7
''' + fxsave32Template % { "mode" : "riprel" } + '''
};
def macroop FXSAVE64_M {
''' + fxsave64Template % { "mode" : "sib" } + '''
};
def macroop FXSAVE64_P {
rdip t7
''' + fxsave64Template % { "mode" : "riprel" } + '''
};
def macroop FXRSTOR_M {
''' + fxrstor32Template % { "mode" : "sib" } + '''
};
def macroop FXRSTOR_P {
rdip t7
''' + fxrstor32Template % { "mode" : "riprel" } + '''
};
def macroop FXRSTOR64_M {
''' + fxrstor64Template % { "mode" : "sib" } + '''
};
def macroop FXRSTOR64_P {
rdip t7
''' + fxrstor64Template % { "mode" : "riprel" } + '''
};
'''
|
Horace1117/MKTCloud | refs/heads/master | openstack_dashboard/api/quantum.py | 5 | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2012 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# All Rights Reserved.
#
# Copyright 2012 Cisco Systems, Inc.
# Copyright 2012 NEC Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from __future__ import absolute_import
import logging
from quantumclient.v2_0 import client as quantum_client
from django.utils.datastructures import SortedDict
from horizon.conf import HORIZON_CONFIG
from openstack_dashboard.api.base import APIDictWrapper, url_for
from openstack_dashboard.api import network
from openstack_dashboard.api import nova
LOG = logging.getLogger(__name__)
IP_VERSION_DICT = {4: 'IPv4', 6: 'IPv6'}
class QuantumAPIDictWrapper(APIDictWrapper):
def set_id_as_name_if_empty(self, length=8):
try:
if not self._apidict['name']:
id = self._apidict['id']
if length:
id = id[:length]
self._apidict['name'] = '(%s)' % id
except KeyError:
pass
def items(self):
return self._apidict.items()
class Network(QuantumAPIDictWrapper):
"""Wrapper for quantum Networks"""
def __init__(self, apiresource):
apiresource['admin_state'] = \
'UP' if apiresource['admin_state_up'] else 'DOWN'
# Django cannot handle a key name with a colon, so remap another key
for key in apiresource.keys():
if key.find(':'):
apiresource['__'.join(key.split(':'))] = apiresource[key]
super(Network, self).__init__(apiresource)
class Subnet(QuantumAPIDictWrapper):
"""Wrapper for quantum subnets"""
def __init__(self, apiresource):
apiresource['ipver_str'] = get_ipver_str(apiresource['ip_version'])
super(Subnet, self).__init__(apiresource)
class Port(QuantumAPIDictWrapper):
"""Wrapper for quantum ports"""
def __init__(self, apiresource):
apiresource['admin_state'] = \
'UP' if apiresource['admin_state_up'] else 'DOWN'
super(Port, self).__init__(apiresource)
class Router(QuantumAPIDictWrapper):
"""Wrapper for quantum routers"""
def __init__(self, apiresource):
#apiresource['admin_state'] = \
# 'UP' if apiresource['admin_state_up'] else 'DOWN'
super(Router, self).__init__(apiresource)
class FloatingIp(APIDictWrapper):
_attrs = ['id', 'ip', 'fixed_ip', 'port_id', 'instance_id', 'pool']
def __init__(self, fip):
fip['ip'] = fip['floating_ip_address']
fip['fixed_ip'] = fip['fixed_ip_address']
fip['pool'] = fip['floating_network_id']
super(FloatingIp, self).__init__(fip)
class FloatingIpPool(APIDictWrapper):
pass
class FloatingIpTarget(APIDictWrapper):
pass
class FloatingIpManager(network.FloatingIpManager):
def __init__(self, request):
self.request = request
self.client = quantumclient(request)
def list_pools(self):
search_opts = {'router:external': True}
return [FloatingIpPool(pool) for pool
in self.client.list_networks(**search_opts).get('networks')]
def list(self):
fips = self.client.list_floatingips().get('floatingips')
# Get port list to add instance_id to floating IP list
# instance_id is stored in device_id attribute
ports = port_list(self.request)
device_id_dict = SortedDict([(p['id'], p['device_id']) for p in ports])
for fip in fips:
if fip['port_id']:
fip['instance_id'] = device_id_dict[fip['port_id']]
else:
fip['instance_id'] = None
return [FloatingIp(fip) for fip in fips]
def get(self, floating_ip_id):
fip = self.client.show_floatingip(floating_ip_id).get('floatingip')
if fip['port_id']:
fip['instance_id'] = port_get(self.request,
fip['port_id']).device_id
else:
fip['instance_id'] = None
return FloatingIp(fip)
def allocate(self, pool):
body = {'floatingip': {'floating_network_id': pool}}
fip = self.client.create_floatingip(body).get('floatingip')
fip['instance_id'] = None
return FloatingIp(fip)
def release(self, floating_ip_id):
self.client.delete_floatingip(floating_ip_id)
def associate(self, floating_ip_id, port_id):
# NOTE: In Quantum Horizon floating IP support, port_id is
# "<port_id>_<ip_address>" format to identify multiple ports.
pid, ip_address = port_id.split('_', 1)
update_dict = {'port_id': pid,
'fixed_ip_address': ip_address}
self.client.update_floatingip(floating_ip_id,
{'floatingip': update_dict})
def disassociate(self, floating_ip_id, port_id):
update_dict = {'port_id': None}
self.client.update_floatingip(floating_ip_id,
{'floatingip': update_dict})
def list_targets(self):
ports = port_list(self.request)
servers = nova.server_list(self.request)
server_dict = SortedDict([(s.id, s.name) for s in servers])
targets = []
for p in ports:
# Remove network ports from Floating IP targets
if p.device_owner.startswith('network:'):
continue
port_id = p.id
server_name = server_dict.get(p.device_id)
for ip in p.fixed_ips:
target = {'name': '%s: %s' % (server_name, ip['ip_address']),
'id': '%s_%s' % (port_id, ip['ip_address'])}
targets.append(FloatingIpTarget(target))
return targets
def get_target_id_by_instance(self, instance_id):
# In Quantum one port can have multiple ip addresses, so this method
# picks up the first one and generate target id.
if not instance_id:
return None
search_opts = {'device_id': instance_id}
ports = port_list(self.request, **search_opts)
if not ports:
return None
return '%s_%s' % (ports[0].id, ports[0].fixed_ips[0]['ip_address'])
def is_simple_associate_supported(self):
# NOTE: There are two reason that simple association support
# needs more considerations. (1) Quantum does not support the
# default floating IP pool at the moment. It can be avoided
# in case where only one floating IP pool exists.
# (2) Quantum floating IP is associated with each VIF and
# we need to check whether such VIF is only one for an instance
# to enable simple association support.
return False
def get_ipver_str(ip_version):
"""Convert an ip version number to a human-friendly string"""
return IP_VERSION_DICT.get(ip_version, '')
def quantumclient(request):
LOG.debug('quantumclient connection created using token "%s" and url "%s"'
% (request.user.token.id, url_for(request, 'network')))
LOG.debug('user_id=%(user)s, tenant_id=%(tenant)s' %
{'user': request.user.id, 'tenant': request.user.tenant_id})
c = quantum_client.Client(token=request.user.token.id,
endpoint_url=url_for(request, 'network'))
return c
def network_list(request, **params):
LOG.debug("network_list(): params=%s" % (params))
networks = quantumclient(request).list_networks(**params).get('networks')
# Get subnet list to expand subnet info in network list.
subnets = subnet_list(request)
subnet_dict = SortedDict([(s['id'], s) for s in subnets])
# Expand subnet list from subnet_id to values.
for n in networks:
n['subnets'] = [subnet_dict.get(s) for s in n.get('subnets', [])]
return [Network(n) for n in networks]
def network_list_for_tenant(request, tenant_id, **params):
"""Return a network list available for the tenant.
The list contains networks owned by the tenant and public networks.
If requested_networks specified, it searches requested_networks only.
"""
LOG.debug("network_list_for_tenant(): tenant_id=%s, params=%s"
% (tenant_id, params))
# If a user has admin role, network list returned by Quantum API
# contains networks that do not belong to that tenant.
# So we need to specify tenant_id when calling network_list().
networks = network_list(request, tenant_id=tenant_id,
shared=False, **params)
# In the current Quantum API, there is no way to retrieve
# both owner networks and public networks in a single API call.
networks += network_list(request, shared=True, **params)
return networks
def network_get(request, network_id, expand_subnet=True, **params):
LOG.debug("network_get(): netid=%s, params=%s" % (network_id, params))
network = quantumclient(request).show_network(network_id,
**params).get('network')
# Since the number of subnets per network must be small,
# call subnet_get() for each subnet instead of calling
# subnet_list() once.
if expand_subnet:
network['subnets'] = [subnet_get(request, sid)
for sid in network['subnets']]
return Network(network)
def network_create(request, **kwargs):
"""
Create a subnet on a specified network.
:param request: request context
:param tenant_id: (optional) tenant id of the network created
:param name: (optional) name of the network created
:returns: Subnet object
"""
LOG.debug("network_create(): kwargs = %s" % kwargs)
body = {'network': kwargs}
network = quantumclient(request).create_network(body=body).get('network')
return Network(network)
def network_modify(request, network_id, **kwargs):
LOG.debug("network_modify(): netid=%s, params=%s" % (network_id, kwargs))
body = {'network': kwargs}
network = quantumclient(request).update_network(network_id,
body=body).get('network')
return Network(network)
def network_delete(request, network_id):
LOG.debug("network_delete(): netid=%s" % network_id)
quantumclient(request).delete_network(network_id)
def subnet_list(request, **params):
LOG.debug("subnet_list(): params=%s" % (params))
subnets = quantumclient(request).list_subnets(**params).get('subnets')
return [Subnet(s) for s in subnets]
def subnet_get(request, subnet_id, **params):
LOG.debug("subnet_get(): subnetid=%s, params=%s" % (subnet_id, params))
subnet = quantumclient(request).show_subnet(subnet_id,
**params).get('subnet')
return Subnet(subnet)
def subnet_create(request, network_id, cidr, ip_version, **kwargs):
"""
Create a subnet on a specified network.
:param request: request context
:param network_id: network id a subnet is created on
:param cidr: subnet IP address range
:param ip_version: IP version (4 or 6)
:param gateway_ip: (optional) IP address of gateway
:param tenant_id: (optional) tenant id of the subnet created
:param name: (optional) name of the subnet created
:returns: Subnet object
"""
LOG.debug("subnet_create(): netid=%s, cidr=%s, ipver=%d, kwargs=%s"
% (network_id, cidr, ip_version, kwargs))
body = {'subnet':
{'network_id': network_id,
'ip_version': ip_version,
'cidr': cidr}}
body['subnet'].update(kwargs)
subnet = quantumclient(request).create_subnet(body=body).get('subnet')
return Subnet(subnet)
def subnet_modify(request, subnet_id, **kwargs):
LOG.debug("subnet_modify(): subnetid=%s, kwargs=%s" % (subnet_id, kwargs))
body = {'subnet': kwargs}
subnet = quantumclient(request).update_subnet(subnet_id,
body=body).get('subnet')
return Subnet(subnet)
def subnet_delete(request, subnet_id):
LOG.debug("subnet_delete(): subnetid=%s" % subnet_id)
quantumclient(request).delete_subnet(subnet_id)
def port_list(request, **params):
LOG.debug("port_list(): params=%s" % (params))
ports = quantumclient(request).list_ports(**params).get('ports')
return [Port(p) for p in ports]
def port_get(request, port_id, **params):
LOG.debug("port_get(): portid=%s, params=%s" % (port_id, params))
port = quantumclient(request).show_port(port_id, **params).get('port')
return Port(port)
def port_create(request, network_id, **kwargs):
"""
Create a port on a specified network.
:param request: request context
:param network_id: network id a subnet is created on
:param device_id: (optional) device id attached to the port
:param tenant_id: (optional) tenant id of the port created
:param name: (optional) name of the port created
:returns: Port object
"""
LOG.debug("port_create(): netid=%s, kwargs=%s" % (network_id, kwargs))
body = {'port': {'network_id': network_id}}
body['port'].update(kwargs)
port = quantumclient(request).create_port(body=body).get('port')
return Port(port)
def port_delete(request, port_id):
LOG.debug("port_delete(): portid=%s" % port_id)
quantumclient(request).delete_port(port_id)
def port_modify(request, port_id, **kwargs):
LOG.debug("port_modify(): portid=%s, kwargs=%s" % (port_id, kwargs))
body = {'port': kwargs}
port = quantumclient(request).update_port(port_id, body=body).get('port')
return Port(port)
def router_create(request, **kwargs):
LOG.debug("router_create():, kwargs=%s" % kwargs)
body = {'router': {}}
body['router'].update(kwargs)
router = quantumclient(request).create_router(body=body).get('router')
return Router(router)
def router_get(request, router_id, **params):
router = quantumclient(request).show_router(router_id,
**params).get('router')
return Router(router)
def router_list(request, **params):
routers = quantumclient(request).list_routers(**params).get('routers')
return [Router(r) for r in routers]
def router_delete(request, router_id):
quantumclient(request).delete_router(router_id)
def router_add_interface(request, router_id, subnet_id=None, port_id=None):
body = {}
if subnet_id:
body['subnet_id'] = subnet_id
if port_id:
body['port_id'] = port_id
quantumclient(request).add_interface_router(router_id, body)
def router_remove_interface(request, router_id, subnet_id=None, port_id=None):
body = {}
if subnet_id:
body['subnet_id'] = subnet_id
if port_id:
body['port_id'] = port_id
quantumclient(request).remove_interface_router(router_id, body)
def router_add_gateway(request, router_id, network_id):
body = {'network_id': network_id}
quantumclient(request).add_gateway_router(router_id, body)
def router_remove_gateway(request, router_id):
quantumclient(request).remove_gateway_router(router_id)
|
LinkHS/incubator-mxnet | refs/heads/master | example/reinforcement-learning/ddpg/ddpg.py | 42 | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
from replay_mem import ReplayMem
from utils import discount_return, sample_rewards
import rllab.misc.logger as logger
import pyprind
import mxnet as mx
import numpy as np
class DDPG(object):
def __init__(
self,
env,
policy,
qfunc,
strategy,
ctx=mx.gpu(0),
batch_size=32,
n_epochs=1000,
epoch_length=1000,
memory_size=1000000,
memory_start_size=1000,
discount=0.99,
max_path_length=1000,
eval_samples=10000,
qfunc_updater="adam",
qfunc_lr=1e-4,
policy_updater="adam",
policy_lr=1e-4,
soft_target_tau=1e-3,
n_updates_per_sample=1,
include_horizon_terminal=False,
seed=12345):
mx.random.seed(seed)
np.random.seed(seed)
self.env = env
self.ctx = ctx
self.policy = policy
self.qfunc = qfunc
self.strategy = strategy
self.batch_size = batch_size
self.n_epochs = n_epochs
self.epoch_length = epoch_length
self.memory_size = memory_size
self.memory_start_size = memory_start_size
self.discount = discount
self.max_path_length = max_path_length
self.eval_samples = eval_samples
self.qfunc_updater = qfunc_updater
self.qfunc_lr = qfunc_lr
self.policy_updater = policy_updater
self.policy_lr = policy_lr
self.soft_target_tau = soft_target_tau
self.n_updates_per_sample = n_updates_per_sample
self.include_horizon_terminal = include_horizon_terminal
self.init_net()
# logging
self.qfunc_loss_averages = []
self.policy_loss_averages = []
self.q_averages = []
self.y_averages = []
self.strategy_path_returns = []
def init_net(self):
# qfunc init
qfunc_init = mx.initializer.Normal()
loss_symbols = self.qfunc.get_loss_symbols()
qval_sym = loss_symbols["qval"]
yval_sym = loss_symbols["yval"]
# define loss here
loss = 1.0 / self.batch_size * mx.symbol.sum(
mx.symbol.square(qval_sym - yval_sym))
qfunc_loss = loss
qfunc_updater = mx.optimizer.get_updater(
mx.optimizer.create(self.qfunc_updater,
learning_rate=self.qfunc_lr))
self.qfunc_input_shapes = {
"obs": (self.batch_size, self.env.observation_space.flat_dim),
"act": (self.batch_size, self.env.action_space.flat_dim),
"yval": (self.batch_size, 1)}
self.qfunc.define_loss(qfunc_loss)
self.qfunc.define_exe(
ctx=self.ctx,
init=qfunc_init,
updater=qfunc_updater,
input_shapes=self.qfunc_input_shapes)
# qfunc_target init
qfunc_target_shapes = {
"obs": (self.batch_size, self.env.observation_space.flat_dim),
"act": (self.batch_size, self.env.action_space.flat_dim)
}
self.qfunc_target = qval_sym.simple_bind(ctx=self.ctx,
**qfunc_target_shapes)
# parameters are not shared but initialized the same
for name, arr in self.qfunc_target.arg_dict.items():
if name not in self.qfunc_input_shapes:
self.qfunc.arg_dict[name].copyto(arr)
# policy init
policy_init = mx.initializer.Normal()
loss_symbols = self.policy.get_loss_symbols()
act_sym = loss_symbols["act"]
policy_qval = qval_sym
# note the negative one here: the loss maximizes the average return
loss = -1.0 / self.batch_size * mx.symbol.sum(policy_qval)
policy_loss = loss
policy_loss = mx.symbol.MakeLoss(policy_loss, name="policy_loss")
policy_updater = mx.optimizer.get_updater(
mx.optimizer.create(self.policy_updater,
learning_rate=self.policy_lr))
self.policy_input_shapes = {
"obs": (self.batch_size, self.env.observation_space.flat_dim)}
self.policy.define_exe(
ctx=self.ctx,
init=policy_init,
updater=policy_updater,
input_shapes=self.policy_input_shapes)
# policy network and q-value network are combined to backpropage
# gradients from the policy loss
# since the loss is different, yval is not needed
args = {}
for name, arr in self.qfunc.arg_dict.items():
if name != "yval":
args[name] = arr
args_grad = {}
policy_grad_dict = dict(zip(self.qfunc.loss.list_arguments(), self.qfunc.exe.grad_arrays))
for name, arr in policy_grad_dict.items():
if name != "yval":
args_grad[name] = arr
self.policy_executor = policy_loss.bind(
ctx=self.ctx,
args=args,
args_grad=args_grad,
grad_req="write")
self.policy_executor_arg_dict = self.policy_executor.arg_dict
self.policy_executor_grad_dict = dict(zip(
policy_loss.list_arguments(),
self.policy_executor.grad_arrays))
# policy_target init
# target policy only needs to produce actions, not loss
# parameters are not shared but initialized the same
self.policy_target = act_sym.simple_bind(ctx=self.ctx,
**self.policy_input_shapes)
for name, arr in self.policy_target.arg_dict.items():
if name not in self.policy_input_shapes:
self.policy.arg_dict[name].copyto(arr)
def train(self):
memory = ReplayMem(
obs_dim=self.env.observation_space.flat_dim,
act_dim=self.env.action_space.flat_dim,
memory_size=self.memory_size)
itr = 0
path_length = 0
path_return = 0
end = False
obs = self.env.reset()
for epoch in xrange(self.n_epochs):
logger.push_prefix("epoch #%d | " % epoch)
logger.log("Training started")
for epoch_itr in pyprind.prog_bar(range(self.epoch_length)):
# run the policy
if end:
# reset the environment and stretegy when an episode ends
obs = self.env.reset()
self.strategy.reset()
# self.policy.reset()
self.strategy_path_returns.append(path_return)
path_length = 0
path_return = 0
# note action is sampled from the policy not the target policy
act = self.strategy.get_action(obs, self.policy)
nxt, rwd, end, _ = self.env.step(act)
path_length += 1
path_return += rwd
if not end and path_length >= self.max_path_length:
end = True
if self.include_horizon_terminal:
memory.add_sample(obs, act, rwd, end)
else:
memory.add_sample(obs, act, rwd, end)
obs = nxt
if memory.size >= self.memory_start_size:
for update_time in xrange(self.n_updates_per_sample):
batch = memory.get_batch(self.batch_size)
self.do_update(itr, batch)
itr += 1
logger.log("Training finished")
if memory.size >= self.memory_start_size:
self.evaluate(epoch, memory)
logger.dump_tabular(with_prefix=False)
logger.pop_prefix()
# self.env.terminate()
# self.policy.terminate()
def do_update(self, itr, batch):
obss, acts, rwds, ends, nxts = batch
self.policy_target.arg_dict["obs"][:] = nxts
self.policy_target.forward(is_train=False)
next_acts = self.policy_target.outputs[0].asnumpy()
policy_acts = self.policy.get_actions(obss)
self.qfunc_target.arg_dict["obs"][:] = nxts
self.qfunc_target.arg_dict["act"][:] = next_acts
self.qfunc_target.forward(is_train=False)
next_qvals = self.qfunc_target.outputs[0].asnumpy()
# executor accepts 2D tensors
rwds = rwds.reshape((-1, 1))
ends = ends.reshape((-1, 1))
ys = rwds + (1.0 - ends) * self.discount * next_qvals
# since policy_executor shares the grad arrays with qfunc
# the update order could not be changed
self.qfunc.update_params(obss, acts, ys)
# in update values all computed
# no need to recompute qfunc_loss and qvals
qfunc_loss = self.qfunc.exe.outputs[0].asnumpy()
qvals = self.qfunc.exe.outputs[1].asnumpy()
self.policy_executor.arg_dict["obs"][:] = obss
self.policy_executor.arg_dict["act"][:] = policy_acts
self.policy_executor.forward(is_train=True)
policy_loss = self.policy_executor.outputs[0].asnumpy()
self.policy_executor.backward()
self.policy.update_params(self.policy_executor_grad_dict["act"])
# update target networks
for name, arr in self.policy_target.arg_dict.items():
if name not in self.policy_input_shapes:
arr[:] = (1.0 - self.soft_target_tau) * arr[:] + \
self.soft_target_tau * self.policy.arg_dict[name][:]
for name, arr in self.qfunc_target.arg_dict.items():
if name not in self.qfunc_input_shapes:
arr[:] = (1.0 - self.soft_target_tau) * arr[:] + \
self.soft_target_tau * self.qfunc.arg_dict[name][:]
self.qfunc_loss_averages.append(qfunc_loss)
self.policy_loss_averages.append(policy_loss)
self.q_averages.append(qvals)
self.y_averages.append(ys)
def evaluate(self, epoch, memory):
if epoch == self.n_epochs - 1:
logger.log("Collecting samples for evaluation")
rewards = sample_rewards(env=self.env,
policy=self.policy,
eval_samples=self.eval_samples,
max_path_length=self.max_path_length)
average_discounted_return = np.mean(
[discount_return(reward, self.discount) for reward in rewards])
returns = [sum(reward) for reward in rewards]
all_qs = np.concatenate(self.q_averages)
all_ys = np.concatenate(self.y_averages)
average_qfunc_loss = np.mean(self.qfunc_loss_averages)
average_policy_loss = np.mean(self.policy_loss_averages)
logger.record_tabular('Epoch', epoch)
if epoch == self.n_epochs - 1:
logger.record_tabular('AverageReturn',
np.mean(returns))
logger.record_tabular('StdReturn',
np.std(returns))
logger.record_tabular('MaxReturn',
np.max(returns))
logger.record_tabular('MinReturn',
np.min(returns))
logger.record_tabular('AverageDiscountedReturn',
average_discounted_return)
if len(self.strategy_path_returns) > 0:
logger.record_tabular('AverageEsReturn',
np.mean(self.strategy_path_returns))
logger.record_tabular('StdEsReturn',
np.std(self.strategy_path_returns))
logger.record_tabular('MaxEsReturn',
np.max(self.strategy_path_returns))
logger.record_tabular('MinEsReturn',
np.min(self.strategy_path_returns))
logger.record_tabular('AverageQLoss', average_qfunc_loss)
logger.record_tabular('AveragePolicyLoss', average_policy_loss)
logger.record_tabular('AverageQ', np.mean(all_qs))
logger.record_tabular('AverageAbsQ', np.mean(np.abs(all_qs)))
logger.record_tabular('AverageY', np.mean(all_ys))
logger.record_tabular('AverageAbsY', np.mean(np.abs(all_ys)))
logger.record_tabular('AverageAbsQYDiff',
np.mean(np.abs(all_qs - all_ys)))
self.qfunc_loss_averages = []
self.policy_loss_averages = []
self.q_averages = []
self.y_averages = []
self.strategy_path_returns = []
|
zengluyang/ns3-d2d | refs/heads/master | examples/udp/examples-to-run.py | 199 | #! /usr/bin/env python
## -*- Mode: python; py-indent-offset: 4; indent-tabs-mode: nil; coding: utf-8; -*-
# A list of C++ examples to run in order to ensure that they remain
# buildable and runnable over time. Each tuple in the list contains
#
# (example_name, do_run, do_valgrind_run).
#
# See test.py for more information.
cpp_examples = [
("udp-echo", "True", "True"),
]
# A list of Python examples to run in order to ensure that they remain
# runnable over time. Each tuple in the list contains
#
# (example_name, do_run).
#
# See test.py for more information.
python_examples = []
|
ppy/angle | refs/heads/master | src/tests/gles_conformance_tests/generate_gles_conformance_tests.py | 9 | import os
import re
import sys
def ReadFileAsLines(filename):
"""Reads a file, removing blank lines and lines that start with #"""
file = open(filename, "r")
raw_lines = file.readlines()
file.close()
lines = []
for line in raw_lines:
line = line.strip()
if len(line) > 0 and not line.startswith("#"):
lines.append(line)
return lines
def GetSuiteName(testName):
return testName[:testName.find("/")]
def GetTestName(testName):
replacements = {".test": "", ".": "_"}
splitTestName = testName.split("/")
cleanName = splitTestName[-2] + "_" + splitTestName[-1]
for replaceKey in replacements:
cleanName = cleanName.replace(replaceKey, replacements[replaceKey])
return cleanName
def GenerateTests(outFile, testNames):
# Remove duplicate tests
testNames = list(set(testNames))
testSuites = []
outFile.write("#include \"gles_conformance_tests.h\"\n\n")
for test in testNames:
testSuite = GetSuiteName(test)
if not testSuite in testSuites:
outFile.write("DEFINE_CONFORMANCE_TEST_CLASS(" + testSuite + ");\n\n")
testSuites.append(testSuite)
outFile.write("TYPED_TEST(" + testSuite + ", " + GetTestName(test) + ")\n")
outFile.write("{\n")
outFile.write(" run(\"" + test + "\");\n")
outFile.write("}\n\n")
def GenerateTestList(sourceFile, rootDir):
tests = []
fileName, fileExtension = os.path.splitext(sourceFile)
if fileExtension == ".run":
lines = ReadFileAsLines(sourceFile)
for line in lines:
tests += GenerateTestList(os.path.join(os.path.dirname(sourceFile), line), rootDir)
elif fileExtension == ".test":
tests.append(os.path.relpath(os.path.realpath(sourceFile), rootDir).replace("\\", "/"))
return tests
def main(argv):
tests = GenerateTestList(argv[0], argv[1])
tests.sort()
output = open(argv[2], 'wb')
GenerateTests(output, tests)
output.close()
return 0
if __name__ == '__main__':
sys.exit(main(sys.argv[1:]))
|
highb/deep-learning | refs/heads/master | face_generation/problem_unittests.py | 159 | from copy import deepcopy
from unittest import mock
import tensorflow as tf
def test_safe(func):
"""
Isolate tests
"""
def func_wrapper(*args):
with tf.Graph().as_default():
result = func(*args)
print('Tests Passed')
return result
return func_wrapper
def _assert_tensor_shape(tensor, shape, display_name):
assert tf.assert_rank(tensor, len(shape), message='{} has wrong rank'.format(display_name))
tensor_shape = tensor.get_shape().as_list() if len(shape) else []
wrong_dimension = [ten_dim for ten_dim, cor_dim in zip(tensor_shape, shape)
if cor_dim is not None and ten_dim != cor_dim]
assert not wrong_dimension, \
'{} has wrong shape. Found {}'.format(display_name, tensor_shape)
def _check_input(tensor, shape, display_name, tf_name=None):
assert tensor.op.type == 'Placeholder', \
'{} is not a Placeholder.'.format(display_name)
_assert_tensor_shape(tensor, shape, 'Real Input')
if tf_name:
assert tensor.name == tf_name, \
'{} has bad name. Found name {}'.format(display_name, tensor.name)
class TmpMock():
"""
Mock a attribute. Restore attribute when exiting scope.
"""
def __init__(self, module, attrib_name):
self.original_attrib = deepcopy(getattr(module, attrib_name))
setattr(module, attrib_name, mock.MagicMock())
self.module = module
self.attrib_name = attrib_name
def __enter__(self):
return getattr(self.module, self.attrib_name)
def __exit__(self, type, value, traceback):
setattr(self.module, self.attrib_name, self.original_attrib)
@test_safe
def test_model_inputs(model_inputs):
image_width = 28
image_height = 28
image_channels = 3
z_dim = 100
input_real, input_z, learn_rate = model_inputs(image_width, image_height, image_channels, z_dim)
_check_input(input_real, [None, image_width, image_height, image_channels], 'Real Input')
_check_input(input_z, [None, z_dim], 'Z Input')
_check_input(learn_rate, [], 'Learning Rate')
@test_safe
def test_discriminator(discriminator, tf_module):
with TmpMock(tf_module, 'variable_scope') as mock_variable_scope:
image = tf.placeholder(tf.float32, [None, 28, 28, 3])
output, logits = discriminator(image)
_assert_tensor_shape(output, [None, 1], 'Discriminator Training(reuse=false) output')
_assert_tensor_shape(logits, [None, 1], 'Discriminator Training(reuse=false) Logits')
assert mock_variable_scope.called,\
'tf.variable_scope not called in Discriminator Training(reuse=false)'
assert mock_variable_scope.call_args == mock.call('discriminator', reuse=False), \
'tf.variable_scope called with wrong arguments in Discriminator Training(reuse=false)'
mock_variable_scope.reset_mock()
output_reuse, logits_reuse = discriminator(image, True)
_assert_tensor_shape(output_reuse, [None, 1], 'Discriminator Inference(reuse=True) output')
_assert_tensor_shape(logits_reuse, [None, 1], 'Discriminator Inference(reuse=True) Logits')
assert mock_variable_scope.called, \
'tf.variable_scope not called in Discriminator Inference(reuse=True)'
assert mock_variable_scope.call_args == mock.call('discriminator', reuse=True), \
'tf.variable_scope called with wrong arguments in Discriminator Inference(reuse=True)'
@test_safe
def test_generator(generator, tf_module):
with TmpMock(tf_module, 'variable_scope') as mock_variable_scope:
z = tf.placeholder(tf.float32, [None, 100])
out_channel_dim = 5
output = generator(z, out_channel_dim)
_assert_tensor_shape(output, [None, 28, 28, out_channel_dim], 'Generator output (is_train=True)')
assert mock_variable_scope.called, \
'tf.variable_scope not called in Generator Training(reuse=false)'
assert mock_variable_scope.call_args == mock.call('generator', reuse=False), \
'tf.variable_scope called with wrong arguments in Generator Training(reuse=false)'
mock_variable_scope.reset_mock()
output = generator(z, out_channel_dim, False)
_assert_tensor_shape(output, [None, 28, 28, out_channel_dim], 'Generator output (is_train=False)')
assert mock_variable_scope.called, \
'tf.variable_scope not called in Generator Inference(reuse=True)'
assert mock_variable_scope.call_args == mock.call('generator', reuse=True), \
'tf.variable_scope called with wrong arguments in Generator Inference(reuse=True)'
@test_safe
def test_model_loss(model_loss):
out_channel_dim = 4
input_real = tf.placeholder(tf.float32, [None, 28, 28, out_channel_dim])
input_z = tf.placeholder(tf.float32, [None, 100])
d_loss, g_loss = model_loss(input_real, input_z, out_channel_dim)
_assert_tensor_shape(d_loss, [], 'Discriminator Loss')
_assert_tensor_shape(d_loss, [], 'Generator Loss')
@test_safe
def test_model_opt(model_opt, tf_module):
with TmpMock(tf_module, 'trainable_variables') as mock_trainable_variables:
with tf.variable_scope('discriminator'):
discriminator_logits = tf.Variable(tf.zeros([3, 3]))
with tf.variable_scope('generator'):
generator_logits = tf.Variable(tf.zeros([3, 3]))
mock_trainable_variables.return_value = [discriminator_logits, generator_logits]
d_loss = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(
logits=discriminator_logits,
labels=[[0.0, 0.0, 1.0], [0.0, 1.0, 0.0], [1.0, 0.0, 0.0]]))
g_loss = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(
logits=generator_logits,
labels=[[0.0, 0.0, 1.0], [0.0, 1.0, 0.0], [1.0, 0.0, 0.0]]))
learning_rate = 0.001
beta1 = 0.9
d_train_opt, g_train_opt = model_opt(d_loss, g_loss, learning_rate, beta1)
assert mock_trainable_variables.called,\
'tf.mock_trainable_variables not called'
|
stephane-martin/salt-debian-packaging | refs/heads/master | salt-2016.3.2/salt/runners/asam.py | 2 | # -*- coding: utf-8 -*-
'''
Novell ASAM Runner
==================
.. versionadded:: Beryllium
Runner to interact with Novell ASAM Fan-Out Driver
:codeauthor: Nitin Madhok <nmadhok@clemson.edu>
To use this runner, set up the Novell Fan-Out Driver URL, username and password in the
master configuration at ``/etc/salt/master`` or ``/etc/salt/master.d/asam.conf``:
.. code-block:: yaml
asam:
prov1.domain.com
username: "testuser"
password: "verybadpass"
prov2.domain.com
username: "testuser"
password: "verybadpass"
.. note::
Optionally, ``protocol`` and ``port`` can be specified if the Fan-Out Driver server
is not using the defaults. Default is ``protocol: https`` and ``port: 3451``.
'''
from __future__ import absolute_import
# Import python libs
import logging
# Import third party libs
HAS_LIBS = False
HAS_SIX = False
try:
import requests
from salt.ext.six.moves.html_parser import HTMLParser # pylint: disable=E0611
try:
import salt.ext.six as six
HAS_SIX = True
except ImportError:
# Salt version <= 2014.7.0
try:
import six
except ImportError:
pass
HAS_LIBS = True
class ASAMHTMLParser(HTMLParser): # fix issue #30477
def __init__(self):
HTMLParser.__init__(self)
self.data = []
def handle_starttag(self, tag, attrs):
if tag != "a":
return
for attr in attrs:
if attr[0] != "href":
return
self.data.append(attr[1])
except ImportError:
pass
log = logging.getLogger(__name__)
def __virtual__():
'''
Check for ASAM Fan-Out driver configuration in master config file
or directory and load runner only if it is specified
'''
if not HAS_LIBS or not HAS_SIX:
return False
if _get_asam_configuration() is False:
return False
return True
def _get_asam_configuration(driver_url=''):
'''
Return the configuration read from the master configuration
file or directory
'''
asam_config = __opts__['asam'] if 'asam' in __opts__ else None
if asam_config:
try:
for asam_server, service_config in six.iteritems(asam_config):
username = service_config.get('username', None)
password = service_config.get('password', None)
protocol = service_config.get('protocol', 'https')
port = service_config.get('port', 3451)
if not username or not password:
log.error(
"Username or Password has not been specified in the master "
"configuration for {0}".format(asam_server)
)
return False
ret = {
'platform_edit_url': "{0}://{1}:{2}/config/PlatformEdit.html".format(protocol, asam_server, port),
'platform_config_url': "{0}://{1}:{2}/config/PlatformConfig.html".format(protocol, asam_server, port),
'platformset_edit_url': "{0}://{1}:{2}/config/PlatformSetEdit.html".format(protocol, asam_server, port),
'platformset_config_url': "{0}://{1}:{2}/config/PlatformSetConfig.html".format(protocol, asam_server, port),
'username': username,
'password': password
}
if (not driver_url) or (driver_url == asam_server):
return ret
except Exception as exc:
log.error(
"Exception encountered: {0}".format(exc)
)
return False
if driver_url:
log.error(
"Configuration for {0} has not been specified in the master "
"configuration".format(driver_url)
)
return False
return False
def _make_post_request(url, data, auth, verify=True):
r = requests.post(url, data=data, auth=auth, verify=verify)
if r.status_code != requests.codes.ok:
r.raise_for_status()
else:
return r.text.split('\n')
def _parse_html_content(html_content):
parser = ASAMHTMLParser()
for line in html_content:
if line.startswith("<META"):
html_content.remove(line)
else:
parser.feed(line)
return parser
def _get_platformset_name(data, platform_name):
for item in data:
if platform_name in item and item.startswith('PlatformEdit.html?'):
parameter_list = item.split('&')
for parameter in parameter_list:
if parameter.startswith("platformSetName"):
return parameter.split('=')[1]
return None
def _get_platforms(data):
platform_list = []
for item in data:
if item.startswith('PlatformEdit.html?'):
parameter_list = item.split('PlatformEdit.html?', 1)[1].split('&')
for parameter in parameter_list:
if parameter.startswith("platformName"):
platform_list.append(parameter.split('=')[1])
return platform_list
def _get_platform_sets(data):
platform_set_list = []
for item in data:
if item.startswith('PlatformSetEdit.html?'):
parameter_list = item.split('PlatformSetEdit.html?', 1)[1].split('&')
for parameter in parameter_list:
if parameter.startswith("platformSetName"):
platform_set_list.append(parameter.split('=')[1].replace('%20', ' '))
return platform_set_list
def remove_platform(name, server_url):
'''
To remove specified ASAM platform from the Novell Fan-Out Driver
CLI Example:
.. code-block:: bash
salt-run asam.remove_platform my-test-vm prov1.domain.com
'''
config = _get_asam_configuration(server_url)
if not config:
return False
url = config['platform_config_url']
data = {
'manual': 'false',
}
auth = (
config['username'],
config['password']
)
try:
html_content = _make_post_request(url, data, auth, verify=False)
except Exception as exc:
err_msg = "Failed to look up existing platforms on {0}".format(server_url)
log.error("{0}:\n{1}".format(err_msg, exc))
return {name: err_msg}
parser = _parse_html_content(html_content)
platformset_name = _get_platformset_name(parser.data, name)
if platformset_name:
log.debug(platformset_name)
data['platformName'] = name
data['platformSetName'] = str(platformset_name)
data['postType'] = 'platformRemove'
data['Submit'] = 'Yes'
try:
html_content = _make_post_request(url, data, auth, verify=False)
except Exception as exc:
err_msg = "Failed to delete platform from {1}".format(server_url)
log.error("{0}:\n{1}".format(err_msg, exc))
return {name: err_msg}
parser = _parse_html_content(html_content)
platformset_name = _get_platformset_name(parser.data, name)
if platformset_name:
return {name: "Failed to delete platform from {0}".format(server_url)}
else:
return {name: "Successfully deleted platform from {0}".format(server_url)}
else:
return {name: "Specified platform name does not exist on {0}".format(server_url)}
def list_platforms(server_url):
'''
To list all ASAM platforms present on the Novell Fan-Out Driver
CLI Example:
.. code-block:: bash
salt-run asam.list_platforms prov1.domain.com
'''
config = _get_asam_configuration(server_url)
if not config:
return False
url = config['platform_config_url']
data = {
'manual': 'false',
}
auth = (
config['username'],
config['password']
)
try:
html_content = _make_post_request(url, data, auth, verify=False)
except Exception as exc:
err_msg = "Failed to look up existing platforms"
log.error("{0}:\n{1}".format(err_msg, exc))
return {server_url: err_msg}
parser = _parse_html_content(html_content)
platform_list = _get_platforms(parser.data)
if platform_list:
return {server_url: platform_list}
else:
return {server_url: "No existing platforms found"}
def list_platform_sets(server_url):
'''
To list all ASAM platform sets present on the Novell Fan-Out Driver
CLI Example:
.. code-block:: bash
salt-run asam.list_platform_sets prov1.domain.com
'''
config = _get_asam_configuration(server_url)
if not config:
return False
url = config['platformset_config_url']
data = {
'manual': 'false',
}
auth = (
config['username'],
config['password']
)
try:
html_content = _make_post_request(url, data, auth, verify=False)
except Exception as exc:
err_msg = "Failed to look up existing platform sets"
log.error("{0}:\n{1}".format(err_msg, exc))
return {server_url: err_msg}
parser = _parse_html_content(html_content)
platform_set_list = _get_platform_sets(parser.data)
if platform_set_list:
return {server_url: platform_set_list}
else:
return {server_url: "No existing platform sets found"}
def add_platform(name, platform_set, server_url):
'''
To add an ASAM platform using the specified ASAM platform set on the Novell
Fan-Out Driver
CLI Example:
.. code-block:: bash
salt-run asam.add_platform my-test-vm test-platform-set prov1.domain.com
'''
config = _get_asam_configuration(server_url)
if not config:
return False
platforms = list_platforms(server_url)
if name in platforms[server_url]:
return {name: "Specified platform already exists on {0}".format(server_url)}
platform_sets = list_platform_sets(server_url)
if platform_set not in platform_sets[server_url]:
return {name: "Specified platform set does not exist on {0}".format(server_url)}
url = config['platform_edit_url']
data = {
'platformName': name,
'platformSetName': platform_set,
'manual': 'false',
'previousURL': '/config/platformAdd.html',
'postType': 'PlatformAdd',
'Submit': 'Apply'
}
auth = (
config['username'],
config['password']
)
try:
html_content = _make_post_request(url, data, auth, verify=False)
except Exception as exc:
err_msg = "Failed to add platform on {0}".format(server_url)
log.error("{0}:\n{1}".format(err_msg, exc))
return {name: err_msg}
platforms = list_platforms(server_url)
if name in platforms[server_url]:
return {name: "Successfully added platform on {0}".format(server_url)}
else:
return {name: "Failed to add platform on {0}".format(server_url)}
|
ddrmanxbxfr/servo | refs/heads/master | tests/wpt/web-platform-tests/tools/pywebsocket/src/test/test_stream.py | 496 | #!/usr/bin/env python
#
# Copyright 2011, Google Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following disclaimer
# in the documentation and/or other materials provided with the
# distribution.
# * Neither the name of Google Inc. nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""Tests for stream module."""
import unittest
import set_sys_path # Update sys.path to locate mod_pywebsocket module.
from mod_pywebsocket import common
from mod_pywebsocket import stream
class StreamTest(unittest.TestCase):
"""A unittest for stream module."""
def test_create_header(self):
# more, rsv1, ..., rsv4 are all true
header = stream.create_header(common.OPCODE_TEXT, 1, 1, 1, 1, 1, 1)
self.assertEqual('\xf1\x81', header)
# Maximum payload size
header = stream.create_header(
common.OPCODE_TEXT, (1 << 63) - 1, 0, 0, 0, 0, 0)
self.assertEqual('\x01\x7f\x7f\xff\xff\xff\xff\xff\xff\xff', header)
# Invalid opcode 0x10
self.assertRaises(ValueError,
stream.create_header,
0x10, 0, 0, 0, 0, 0, 0)
# Invalid value 0xf passed to more parameter
self.assertRaises(ValueError,
stream.create_header,
common.OPCODE_TEXT, 0, 0xf, 0, 0, 0, 0)
# Too long payload_length
self.assertRaises(ValueError,
stream.create_header,
common.OPCODE_TEXT, 1 << 63, 0, 0, 0, 0, 0)
if __name__ == '__main__':
unittest.main()
# vi:sts=4 sw=4 et
|
epall/selenium | refs/heads/master | selenium/src/py/mypydoc.py | 5 | import pydoc
if __name__ == "__main__":
pydoc.cli()
|
pratikmallya/hue | refs/heads/master | desktop/core/ext-py/Django-1.6.10/django/conf/locale/id/formats.py | 117 | # -*- encoding: utf-8 -*-
# This file is distributed under the same license as the Django package.
#
from __future__ import unicode_literals
# The *_FORMAT strings use the Django date format syntax,
# see http://docs.djangoproject.com/en/dev/ref/templates/builtins/#date
DATE_FORMAT = 'j N Y'
DATETIME_FORMAT = "j N Y, G.i.s"
TIME_FORMAT = 'G.i.s'
YEAR_MONTH_FORMAT = 'F Y'
MONTH_DAY_FORMAT = 'j F'
SHORT_DATE_FORMAT = 'd-m-Y'
SHORT_DATETIME_FORMAT = 'd-m-Y G.i.s'
FIRST_DAY_OF_WEEK = 1 #Monday
# The *_INPUT_FORMATS strings use the Python strftime format syntax,
# see http://docs.python.org/library/datetime.html#strftime-strptime-behavior
DATE_INPUT_FORMATS = (
'%d-%m-%y', '%d/%m/%y', # '25-10-09', 25/10/09'
'%d-%m-%Y', '%d/%m/%Y', # '25-10-2009', 25/10/2009'
'%d %b %Y', # '25 Oct 2006',
'%d %B %Y', # '25 October 2006'
)
TIME_INPUT_FORMATS = (
'%H.%M.%S', # '14.30.59'
'%H.%M', # '14.30'
)
DATETIME_INPUT_FORMATS = (
'%d-%m-%Y %H.%M.%S', # '25-10-2009 14.30.59'
'%d-%m-%Y %H.%M.%S.%f', # '25-10-2009 14.30.59.000200'
'%d-%m-%Y %H.%M', # '25-10-2009 14.30'
'%d-%m-%Y', # '25-10-2009'
'%d-%m-%y %H.%M.%S', # '25-10-09' 14.30.59'
'%d-%m-%y %H.%M.%S.%f', # '25-10-09' 14.30.59.000200'
'%d-%m-%y %H.%M', # '25-10-09' 14.30'
'%d-%m-%y', # '25-10-09''
'%m/%d/%y %H.%M.%S', # '10/25/06 14.30.59'
'%m/%d/%y %H.%M.%S.%f', # '10/25/06 14.30.59.000200'
'%m/%d/%y %H.%M', # '10/25/06 14.30'
'%m/%d/%y', # '10/25/06'
'%m/%d/%Y %H.%M.%S', # '25/10/2009 14.30.59'
'%m/%d/%Y %H.%M.%S.%f', # '25/10/2009 14.30.59.000200'
'%m/%d/%Y %H.%M', # '25/10/2009 14.30'
'%m/%d/%Y', # '10/25/2009'
)
DECIMAL_SEPARATOR = ','
THOUSAND_SEPARATOR = '.'
NUMBER_GROUPING = 3
|
erwilan/ansible | refs/heads/devel | test/units/modules/network/eos/test_eos_command.py | 41 | # (c) 2016 Red Hat Inc.
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
# Make coding more python3-ish
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import json
from ansible.compat.tests.mock import patch
from ansible.modules.network.eos import eos_command
from .eos_module import TestEosModule, load_fixture, set_module_args
class TestEosCommandModule(TestEosModule):
module = eos_command
def setUp(self):
self.mock_run_commands = patch('ansible.modules.network.eos.eos_command.run_commands')
self.run_commands = self.mock_run_commands.start()
def tearDown(self):
self.mock_run_commands.stop()
def load_fixtures(self, commands=None, transport='cli'):
def load_from_file(*args, **kwargs):
module, commands = args
output = list()
for item in commands:
try:
obj = json.loads(item['command'])
command = obj['command']
except ValueError:
command = item['command']
filename = str(command).replace(' ', '_')
filename = 'eos_command_%s.txt' % filename
output.append(load_fixture(filename))
return output
self.run_commands.side_effect = load_from_file
def test_eos_command_simple(self):
set_module_args(dict(commands=['show version']))
result = self.execute_module()
self.assertEqual(len(result['stdout']), 1)
self.assertTrue(result['stdout'][0].startswith('Arista'))
def test_eos_command_multiple(self):
set_module_args(dict(commands=['show version', 'show version']))
result = self.execute_module()
self.assertEqual(len(result['stdout']), 2)
self.assertTrue(result['stdout'][0].startswith('Arista'))
def test_eos_command_wait_for(self):
wait_for = 'result[0] contains "Arista vEOS"'
set_module_args(dict(commands=['show version'], wait_for=wait_for))
self.execute_module()
def test_eos_command_wait_for_fails(self):
wait_for = 'result[0] contains "test string"'
set_module_args(dict(commands=['show version'], wait_for=wait_for))
self.execute_module(failed=True)
self.assertEqual(self.run_commands.call_count, 10)
def test_eos_command_retries(self):
wait_for = 'result[0] contains "test string"'
set_module_args(dict(commands=['show version'], wait_for=wait_for, retries=2))
self.execute_module(failed=True)
self.assertEqual(self.run_commands.call_count, 2)
def test_eos_command_match_any(self):
wait_for = ['result[0] contains "Arista"',
'result[0] contains "test string"']
set_module_args(dict(commands=['show version'], wait_for=wait_for, match='any'))
self.execute_module()
def test_eos_command_match_all(self):
wait_for = ['result[0] contains "Arista"',
'result[0] contains "Software image"']
set_module_args(dict(commands=['show version'], wait_for=wait_for, match='all'))
self.execute_module()
def test_eos_command_match_all_failure(self):
wait_for = ['result[0] contains "Arista"',
'result[0] contains "test string"']
commands = ['show version', 'show version']
set_module_args(dict(commands=commands, wait_for=wait_for, match='all'))
self.execute_module(failed=True)
|
rajul/mne-python | refs/heads/master | examples/preprocessing/plot_define_target_events.py | 19 | """
============================================================
Define target events based on time lag, plot evoked response
============================================================
This script shows how to define higher order events based on
time lag between reference and target events. For
illustration, we will put face stimuli presented into two
classes, that is 1) followed by an early button press
(within 590 milliseconds) and followed by a late button
press (later than 590 milliseconds). Finally, we will
visualize the evoked responses to both 'quickly-processed'
and 'slowly-processed' face stimuli.
"""
# Authors: Denis Engemann <denis.engemann@gmail.com>
#
# License: BSD (3-clause)
import mne
from mne import io
from mne.event import define_target_events
from mne.datasets import sample
import matplotlib.pyplot as plt
print(__doc__)
data_path = sample.data_path()
###############################################################################
# Set parameters
raw_fname = data_path + '/MEG/sample/sample_audvis_filt-0-40_raw.fif'
event_fname = data_path + '/MEG/sample/sample_audvis_filt-0-40_raw-eve.fif'
# Setup for reading the raw data
raw = io.Raw(raw_fname)
events = mne.read_events(event_fname)
# Set up pick list: EEG + STI 014 - bad channels (modify to your needs)
include = [] # or stim channels ['STI 014']
raw.info['bads'] += ['EEG 053'] # bads
# pick MEG channels
picks = mne.pick_types(raw.info, meg='mag', eeg=False, stim=False, eog=True,
include=include, exclude='bads')
###############################################################################
# Find stimulus event followed by quick button presses
reference_id = 5 # presentation of a smiley face
target_id = 32 # button press
sfreq = raw.info['sfreq'] # sampling rate
tmin = 0.1 # trials leading to very early responses will be rejected
tmax = 0.59 # ignore face stimuli followed by button press later than 590 ms
new_id = 42 # the new event id for a hit. If None, reference_id is used.
fill_na = 99 # the fill value for misses
events_, lag = define_target_events(events, reference_id, target_id,
sfreq, tmin, tmax, new_id, fill_na)
print(events_) # The 99 indicates missing or too late button presses
# besides the events also the lag between target and reference is returned
# this could e.g. be used as parametric regressor in subsequent analyses.
print(lag[lag != fill_na]) # lag in milliseconds
# #############################################################################
# Construct epochs
tmin_ = -0.2
tmax_ = 0.4
event_id = dict(early=new_id, late=fill_na)
epochs = mne.Epochs(raw, events_, event_id, tmin_,
tmax_, picks=picks, baseline=(None, 0),
reject=dict(mag=4e-12))
# average epochs and get an Evoked dataset.
early, late = [epochs[k].average() for k in event_id]
###############################################################################
# View evoked response
times = 1e3 * epochs.times # time in milliseconds
title = 'Evoked response followed by %s button press'
plt.clf()
ax = plt.subplot(2, 1, 1)
early.plot(axes=ax)
plt.title(title % 'late')
plt.ylabel('Evoked field (fT)')
ax = plt.subplot(2, 1, 2)
late.plot(axes=ax)
plt.title(title % 'early')
plt.ylabel('Evoked field (fT)')
plt.show()
|
agimofcarmen/xen-api | refs/heads/master | scripts/examples/python/mini-xenrt.py | 25 | #!/usr/bin/env python
# Receive multiple VMs
# Issue parallel loops of: reboot, suspend/resume, migrate
import xmlrpclib
from threading import Thread
import time, sys
iso8601 = "%Y%m%dT%H:%M:%SZ"
stop_on_first_failure = True
stop = False
class Operation:
def __init__(self):
raise "this is supposed to be abstract, dummy"
def execute(self, server, session_id):
raise "this is supposed to be abstract, dummy"
class Reboot(Operation):
def __init__(self, vm):
self.vm = vm
def execute(self, server, session_id):
return server.VM.clean_reboot(session_id, self.vm)
def __str__(self):
return "clean_reboot(%s)" % self.vm
class SuspendResume(Operation):
def __init__(self, vm):
self.vm = vm
def execute(self, server, session_id):
x = { "ErrorDescription": [ "VM_MISSING_PV_DRIVERS" ] }
while "ErrorDescription" in x and x["ErrorDescription"][0] == "VM_MISSING_PV_DRIVERS":
x = server.VM.suspend(session_id, self.vm)
if "ErrorDescription" in x:
time.sleep(1)
if x["Status"] <> "Success":
return x
return server.VM.resume(session_id, self.vm, False, False)
def __str__(self):
return "suspendresume(%s)" % self.vm
class ShutdownStart(Operation):
def __init__(self, vm):
self.vm = vm
def execute(self, server, session_id):
x = server.VM.clean_shutdown(session_id, self.vm)
if x["Status"] <> "Success":
return x
return server.VM.start(session_id, self.vm, False, False)
#return { "Status": "bad", "ErrorDescription": "foo" }
def __str__(self):
return "shutdownstart(%s)" % self.vm
class LocalhostMigrate(Operation):
def __init__(self, vm):
self.vm = vm
def execute(self, server, session_id):
return server.VM.pool_migrate(session_id, self.vm, server.VM.get_resident_on(session_id, self.vm)["Value"], { "live": "true" } )
def __str__(self):
return "localhostmigrate(%s)" % self.vm
# Use this to give each thread a different ID
worker_count = 0
class Worker(Thread):
def __init__(self, server, session_id, operations):
Thread.__init__(self)
self.server = server
self.session_id = session_id
self.operations = operations
self.num_successes = 0
self.num_failures = 0
global worker_count
self.id = worker_count
worker_count = worker_count + 1
def run(self):
global iso8601
global stop_on_first_failure, stop
for op in self.operations:
description = str(op)
if stop:
return
start = time.strftime(iso8601, time.gmtime(time.time ()))
result = op.execute(self.server, self.session_id)
end = time.strftime(iso8601, time.gmtime(time.time ()))
if result["Status"] == "Success":
print "SUCCESS %d %s %s %s" % (self.id, start, end, description)
self.num_successes = self.num_successes + 1
else:
error_descr = result["ErrorDescription"]
print "FAILURE %d %s %s %s %s" % (self.id, start, end, error_descr[0], description)
self.num_failures = self.num_failures + 1
if stop_on_first_failure:
stop = True
def make_operation_list(vm):
return [ Reboot(vm), SuspendResume(vm), LocalhostMigrate(vm) ] * 100
if __name__ == "__main__":
if len(sys.argv) <> 3:
print "Usage:"
print " %s <URL> <other-config key>" % (sys.argv[0])
print " -- performs parallel operations on VMs with the specified other-config key"
sys.exit(1)
x = xmlrpclib.Server(sys.argv[1])
key = sys.argv[2]
session = x.session.login_with_password("root", "xenroot", "1.0", "xen-api-scripts-minixenrt.py")["Value"]
vms = x.VM.get_all_records(session)["Value"]
workers = []
for vm in vms.keys():
if vms[vm]["other_config"].has_key(key):
allowed_ops = vms[vm]["allowed_operations"]
for op in [ "clean_reboot", "suspend", "pool_migrate" ]:
if op not in allowed_ops:
raise "VM %s is not in a state where it can %s" % (vms[vm]["name_label"], op)
workers.append(Worker(x, session, make_operation_list(vm)))
for w in workers:
w.start()
for w in workers:
w.join()
successes = 0
failures = 0
for w in workers:
successes = successes + w.num_successes
failures = failures + w.num_failures
print "Total successes = %d" % successes
print "Total failures = %d" % failures
if failures == 0:
print "PASS"
sys.exit(0)
else:
print "FAIL"
sys.exit(1)
|
sergshabal/p2pool | refs/heads/master | SOAPpy/Types.py | 289 | from __future__ import nested_scopes
"""
################################################################################
# Copyright (c) 2003, Pfizer
# Copyright (c) 2001, Cayce Ullman.
# Copyright (c) 2001, Brian Matthews.
#
# 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 actzero, inc. nor the names of its contributors may
# be used to endorse or promote products derived from this software without
# specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS 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.
#
################################################################################
"""
ident = '$Id: Types.py 1496 2010-03-04 23:46:17Z pooryorick $'
from version import __version__
import UserList
import base64
import cgi
import urllib
import copy
import re
import time
from types import *
# SOAPpy modules
from Errors import *
from NS import NS
from Utilities import encodeHexString, cleanDate
from Config import Config
###############################################################################
# Utility functions
###############################################################################
def isPrivate(name): return name[0]=='_'
def isPublic(name): return name[0]!='_'
###############################################################################
# Types and Wrappers
###############################################################################
class anyType:
_validURIs = (NS.XSD, NS.XSD2, NS.XSD3, NS.ENC)
def __init__(self, data = None, name = None, typed = 1, attrs = None):
if self.__class__ == anyType:
raise Error, "anyType can't be instantiated directly"
if type(name) in (ListType, TupleType):
self._ns, self._name = name
else:
self._ns = self._validURIs[0]
self._name = name
self._typed = typed
self._attrs = {}
self._cache = None
self._type = self._typeName()
self._data = self._checkValueSpace(data)
if attrs != None:
self._setAttrs(attrs)
def __str__(self):
if hasattr(self,'_name') and self._name:
return "<%s %s at %d>" % (self.__class__, self._name, id(self))
return "<%s at %d>" % (self.__class__, id(self))
__repr__ = __str__
def _checkValueSpace(self, data):
return data
def _marshalData(self):
return str(self._data)
def _marshalAttrs(self, ns_map, builder):
a = ''
for attr, value in self._attrs.items():
ns, n = builder.genns(ns_map, attr[0])
a += n + ' %s%s="%s"' % \
(ns, attr[1], cgi.escape(str(value), 1))
return a
def _fixAttr(self, attr):
if type(attr) in (StringType, UnicodeType):
attr = (None, attr)
elif type(attr) == ListType:
attr = tuple(attr)
elif type(attr) != TupleType:
raise AttributeError, "invalid attribute type"
if len(attr) != 2:
raise AttributeError, "invalid attribute length"
if type(attr[0]) not in (NoneType, StringType, UnicodeType):
raise AttributeError, "invalid attribute namespace URI type"
return attr
def _getAttr(self, attr):
attr = self._fixAttr(attr)
try:
return self._attrs[attr]
except:
return None
def _setAttr(self, attr, value):
attr = self._fixAttr(attr)
if type(value) is StringType:
value = unicode(value)
self._attrs[attr] = value
def _setAttrs(self, attrs):
if type(attrs) in (ListType, TupleType):
for i in range(0, len(attrs), 2):
self._setAttr(attrs[i], attrs[i + 1])
return
if type(attrs) == DictType:
d = attrs
elif isinstance(attrs, anyType):
d = attrs._attrs
else:
raise AttributeError, "invalid attribute type"
for attr, value in d.items():
self._setAttr(attr, value)
def _setMustUnderstand(self, val):
self._setAttr((NS.ENV, "mustUnderstand"), val)
def _getMustUnderstand(self):
return self._getAttr((NS.ENV, "mustUnderstand"))
def _setActor(self, val):
self._setAttr((NS.ENV, "actor"), val)
def _getActor(self):
return self._getAttr((NS.ENV, "actor"))
def _typeName(self):
return self.__class__.__name__[:-4]
def _validNamespaceURI(self, URI, strict):
if not hasattr(self, '_typed') or not self._typed:
return None
if URI in self._validURIs:
return URI
if not strict:
return self._ns
raise AttributeError, \
"not a valid namespace for type %s" % self._type
class voidType(anyType):
pass
class stringType(anyType):
def _checkValueSpace(self, data):
if data == None:
raise ValueError, "must supply initial %s value" % self._type
if type(data) not in (StringType, UnicodeType):
raise AttributeError, "invalid %s type:" % self._type
return data
def _marshalData(self):
return self._data
class untypedType(stringType):
def __init__(self, data = None, name = None, attrs = None):
stringType.__init__(self, data, name, 0, attrs)
class IDType(stringType): pass
class NCNameType(stringType): pass
class NameType(stringType): pass
class ENTITYType(stringType): pass
class IDREFType(stringType): pass
class languageType(stringType): pass
class NMTOKENType(stringType): pass
class QNameType(stringType): pass
class tokenType(anyType):
_validURIs = (NS.XSD2, NS.XSD3)
__invalidre = '[\n\t]|^ | $| '
def _checkValueSpace(self, data):
if data == None:
raise ValueError, "must supply initial %s value" % self._type
if type(data) not in (StringType, UnicodeType):
raise AttributeError, "invalid %s type" % self._type
if type(self.__invalidre) == StringType:
self.__invalidre = re.compile(self.__invalidre)
if self.__invalidre.search(data):
raise ValueError, "invalid %s value" % self._type
return data
class normalizedStringType(anyType):
_validURIs = (NS.XSD3,)
__invalidre = '[\n\r\t]'
def _checkValueSpace(self, data):
if data == None:
raise ValueError, "must supply initial %s value" % self._type
if type(data) not in (StringType, UnicodeType):
raise AttributeError, "invalid %s type" % self._type
if type(self.__invalidre) == StringType:
self.__invalidre = re.compile(self.__invalidre)
if self.__invalidre.search(data):
raise ValueError, "invalid %s value" % self._type
return data
class CDATAType(normalizedStringType):
_validURIs = (NS.XSD2,)
class booleanType(anyType):
def __int__(self):
return self._data
__nonzero__ = __int__
def _marshalData(self):
return ['false', 'true'][self._data]
def _checkValueSpace(self, data):
if data == None:
raise ValueError, "must supply initial %s value" % self._type
if data in (0, '0', 'false', ''):
return 0
if data in (1, '1', 'true'):
return 1
raise ValueError, "invalid %s value" % self._type
class decimalType(anyType):
def _checkValueSpace(self, data):
if data == None:
raise ValueError, "must supply initial %s value" % self._type
if type(data) not in (IntType, LongType, FloatType):
raise Error, "invalid %s value" % self._type
return data
class floatType(anyType):
def _checkValueSpace(self, data):
if data == None:
raise ValueError, "must supply initial %s value" % self._type
if type(data) not in (IntType, LongType, FloatType) or \
data < -3.4028234663852886E+38 or \
data > 3.4028234663852886E+38:
raise ValueError, "invalid %s value: %s" % (self._type, repr(data))
return data
def _marshalData(self):
return "%.18g" % self._data # More precision
class doubleType(anyType):
def _checkValueSpace(self, data):
if data == None:
raise ValueError, "must supply initial %s value" % self._type
if type(data) not in (IntType, LongType, FloatType) or \
data < -1.7976931348623158E+308 or \
data > 1.7976931348623157E+308:
raise ValueError, "invalid %s value: %s" % (self._type, repr(data))
return data
def _marshalData(self):
return "%.18g" % self._data # More precision
class durationType(anyType):
_validURIs = (NS.XSD3,)
def _checkValueSpace(self, data):
if data == None:
raise ValueError, "must supply initial %s value" % self._type
try:
# A tuple or a scalar is OK, but make them into a list
if type(data) == TupleType:
data = list(data)
elif type(data) != ListType:
data = [data]
if len(data) > 6:
raise Exception, "too many values"
# Now check the types of all the components, and find
# the first nonzero element along the way.
f = -1
for i in range(len(data)):
if data[i] == None:
data[i] = 0
continue
if type(data[i]) not in \
(IntType, LongType, FloatType):
raise Exception, "element %d a bad type" % i
if data[i] and f == -1:
f = i
# If they're all 0, just use zero seconds.
if f == -1:
self._cache = 'PT0S'
return (0,) * 6
# Make sure only the last nonzero element has a decimal fraction
# and only the first element is negative.
d = -1
for i in range(f, len(data)):
if data[i]:
if d != -1:
raise Exception, \
"all except the last nonzero element must be " \
"integers"
if data[i] < 0 and i > f:
raise Exception, \
"only the first nonzero element can be negative"
elif data[i] != long(data[i]):
d = i
# Pad the list on the left if necessary.
if len(data) < 6:
n = 6 - len(data)
f += n
d += n
data = [0] * n + data
# Save index of the first nonzero element and the decimal
# element for _marshalData.
self.__firstnonzero = f
self.__decimal = d
except Exception, e:
raise ValueError, "invalid %s value - %s" % (self._type, e)
return tuple(data)
def _marshalData(self):
if self._cache == None:
d = self._data
t = 0
if d[self.__firstnonzero] < 0:
s = '-P'
else:
s = 'P'
t = 0
for i in range(self.__firstnonzero, len(d)):
if d[i]:
if i > 2 and not t:
s += 'T'
t = 1
if self.__decimal == i:
s += "%g" % abs(d[i])
else:
s += "%d" % long(abs(d[i]))
s += ['Y', 'M', 'D', 'H', 'M', 'S'][i]
self._cache = s
return self._cache
class timeDurationType(durationType):
_validURIs = (NS.XSD, NS.XSD2, NS.ENC)
class dateTimeType(anyType):
_validURIs = (NS.XSD3,)
def _checkValueSpace(self, data):
try:
if data == None:
data = time.time()
if (type(data) in (IntType, LongType)):
data = list(time.gmtime(data)[:6])
elif (type(data) == FloatType):
f = data - int(data)
data = list(time.gmtime(int(data))[:6])
data[5] += f
elif type(data) in (ListType, TupleType):
if len(data) < 6:
raise Exception, "not enough values"
if len(data) > 9:
raise Exception, "too many values"
data = list(data[:6])
cleanDate(data)
else:
raise Exception, "invalid type"
except Exception, e:
raise ValueError, "invalid %s value - %s" % (self._type, e)
return tuple(data)
def _marshalData(self):
if self._cache == None:
d = self._data
s = "%04d-%02d-%02dT%02d:%02d:%02d" % ((abs(d[0]),) + d[1:])
if d[0] < 0:
s = '-' + s
f = d[5] - int(d[5])
if f != 0:
s += ("%g" % f)[1:]
s += 'Z'
self._cache = s
return self._cache
class recurringInstantType(anyType):
_validURIs = (NS.XSD,)
def _checkValueSpace(self, data):
try:
if data == None:
data = list(time.gmtime(time.time())[:6])
if (type(data) in (IntType, LongType)):
data = list(time.gmtime(data)[:6])
elif (type(data) == FloatType):
f = data - int(data)
data = list(time.gmtime(int(data))[:6])
data[5] += f
elif type(data) in (ListType, TupleType):
if len(data) < 1:
raise Exception, "not enough values"
if len(data) > 9:
raise Exception, "too many values"
data = list(data[:6])
if len(data) < 6:
data += [0] * (6 - len(data))
f = len(data)
for i in range(f):
if data[i] == None:
if f < i:
raise Exception, \
"only leftmost elements can be none"
else:
f = i
break
cleanDate(data, f)
else:
raise Exception, "invalid type"
except Exception, e:
raise ValueError, "invalid %s value - %s" % (self._type, e)
return tuple(data)
def _marshalData(self):
if self._cache == None:
d = self._data
e = list(d)
neg = ''
if not e[0]:
e[0] = '--'
else:
if e[0] < 0:
neg = '-'
e[0] = abs(e[0])
if e[0] < 100:
e[0] = '-' + "%02d" % e[0]
else:
e[0] = "%04d" % e[0]
for i in range(1, len(e)):
if e[i] == None or (i < 3 and e[i] == 0):
e[i] = '-'
else:
if e[i] < 0:
neg = '-'
e[i] = abs(e[i])
e[i] = "%02d" % e[i]
if d[5]:
f = abs(d[5] - int(d[5]))
if f:
e[5] += ("%g" % f)[1:]
s = "%s%s-%s-%sT%s:%s:%sZ" % ((neg,) + tuple(e))
self._cache = s
return self._cache
class timeInstantType(dateTimeType):
_validURIs = (NS.XSD, NS.XSD2, NS.ENC)
class timePeriodType(dateTimeType):
_validURIs = (NS.XSD2, NS.ENC)
class timeType(anyType):
def _checkValueSpace(self, data):
try:
if data == None:
data = time.gmtime(time.time())[3:6]
elif (type(data) == FloatType):
f = data - int(data)
data = list(time.gmtime(int(data))[3:6])
data[2] += f
elif type(data) in (IntType, LongType):
data = time.gmtime(data)[3:6]
elif type(data) in (ListType, TupleType):
if len(data) == 9:
data = data[3:6]
elif len(data) > 3:
raise Exception, "too many values"
data = [None, None, None] + list(data)
if len(data) < 6:
data += [0] * (6 - len(data))
cleanDate(data, 3)
data = data[3:]
else:
raise Exception, "invalid type"
except Exception, e:
raise ValueError, "invalid %s value - %s" % (self._type, e)
return tuple(data)
def _marshalData(self):
if self._cache == None:
d = self._data
#s = ''
#
#s = time.strftime("%H:%M:%S", (0, 0, 0) + d + (0, 0, -1))
s = "%02d:%02d:%02d" % d
f = d[2] - int(d[2])
if f != 0:
s += ("%g" % f)[1:]
s += 'Z'
self._cache = s
return self._cache
class dateType(anyType):
def _checkValueSpace(self, data):
try:
if data == None:
data = time.gmtime(time.time())[0:3]
elif type(data) in (IntType, LongType, FloatType):
data = time.gmtime(data)[0:3]
elif type(data) in (ListType, TupleType):
if len(data) == 9:
data = data[0:3]
elif len(data) > 3:
raise Exception, "too many values"
data = list(data)
if len(data) < 3:
data += [1, 1, 1][len(data):]
data += [0, 0, 0]
cleanDate(data)
data = data[:3]
else:
raise Exception, "invalid type"
except Exception, e:
raise ValueError, "invalid %s value - %s" % (self._type, e)
return tuple(data)
def _marshalData(self):
if self._cache == None:
d = self._data
s = "%04d-%02d-%02dZ" % ((abs(d[0]),) + d[1:])
if d[0] < 0:
s = '-' + s
self._cache = s
return self._cache
class gYearMonthType(anyType):
_validURIs = (NS.XSD3,)
def _checkValueSpace(self, data):
try:
if data == None:
data = time.gmtime(time.time())[0:2]
elif type(data) in (IntType, LongType, FloatType):
data = time.gmtime(data)[0:2]
elif type(data) in (ListType, TupleType):
if len(data) == 9:
data = data[0:2]
elif len(data) > 2:
raise Exception, "too many values"
data = list(data)
if len(data) < 2:
data += [1, 1][len(data):]
data += [1, 0, 0, 0]
cleanDate(data)
data = data[:2]
else:
raise Exception, "invalid type"
except Exception, e:
raise ValueError, "invalid %s value - %s" % (self._type, e)
return tuple(data)
def _marshalData(self):
if self._cache == None:
d = self._data
s = "%04d-%02dZ" % ((abs(d[0]),) + d[1:])
if d[0] < 0:
s = '-' + s
self._cache = s
return self._cache
class gYearType(anyType):
_validURIs = (NS.XSD3,)
def _checkValueSpace(self, data):
try:
if data == None:
data = time.gmtime(time.time())[0:1]
elif type(data) in (IntType, LongType, FloatType):
data = [data]
if type(data) in (ListType, TupleType):
if len(data) == 9:
data = data[0:1]
elif len(data) < 1:
raise Exception, "too few values"
elif len(data) > 1:
raise Exception, "too many values"
if type(data[0]) == FloatType:
try: s = int(data[0])
except: s = long(data[0])
if s != data[0]:
raise Exception, "not integral"
data = [s]
elif type(data[0]) not in (IntType, LongType):
raise Exception, "bad type"
else:
raise Exception, "invalid type"
except Exception, e:
raise ValueError, "invalid %s value - %s" % (self._type, e)
return data[0]
def _marshalData(self):
if self._cache == None:
d = self._data
s = "%04dZ" % abs(d)
if d < 0:
s = '-' + s
self._cache = s
return self._cache
class centuryType(anyType):
_validURIs = (NS.XSD2, NS.ENC)
def _checkValueSpace(self, data):
try:
if data == None:
data = time.gmtime(time.time())[0:1] / 100
elif type(data) in (IntType, LongType, FloatType):
data = [data]
if type(data) in (ListType, TupleType):
if len(data) == 9:
data = data[0:1] / 100
elif len(data) < 1:
raise Exception, "too few values"
elif len(data) > 1:
raise Exception, "too many values"
if type(data[0]) == FloatType:
try: s = int(data[0])
except: s = long(data[0])
if s != data[0]:
raise Exception, "not integral"
data = [s]
elif type(data[0]) not in (IntType, LongType):
raise Exception, "bad type"
else:
raise Exception, "invalid type"
except Exception, e:
raise ValueError, "invalid %s value - %s" % (self._type, e)
return data[0]
def _marshalData(self):
if self._cache == None:
d = self._data
s = "%02dZ" % abs(d)
if d < 0:
s = '-' + s
self._cache = s
return self._cache
class yearType(gYearType):
_validURIs = (NS.XSD2, NS.ENC)
class gMonthDayType(anyType):
_validURIs = (NS.XSD3,)
def _checkValueSpace(self, data):
try:
if data == None:
data = time.gmtime(time.time())[1:3]
elif type(data) in (IntType, LongType, FloatType):
data = time.gmtime(data)[1:3]
elif type(data) in (ListType, TupleType):
if len(data) == 9:
data = data[0:2]
elif len(data) > 2:
raise Exception, "too many values"
data = list(data)
if len(data) < 2:
data += [1, 1][len(data):]
data = [0] + data + [0, 0, 0]
cleanDate(data, 1)
data = data[1:3]
else:
raise Exception, "invalid type"
except Exception, e:
raise ValueError, "invalid %s value - %s" % (self._type, e)
return tuple(data)
def _marshalData(self):
if self._cache == None:
self._cache = "--%02d-%02dZ" % self._data
return self._cache
class recurringDateType(gMonthDayType):
_validURIs = (NS.XSD2, NS.ENC)
class gMonthType(anyType):
_validURIs = (NS.XSD3,)
def _checkValueSpace(self, data):
try:
if data == None:
data = time.gmtime(time.time())[1:2]
elif type(data) in (IntType, LongType, FloatType):
data = [data]
if type(data) in (ListType, TupleType):
if len(data) == 9:
data = data[1:2]
elif len(data) < 1:
raise Exception, "too few values"
elif len(data) > 1:
raise Exception, "too many values"
if type(data[0]) == FloatType:
try: s = int(data[0])
except: s = long(data[0])
if s != data[0]:
raise Exception, "not integral"
data = [s]
elif type(data[0]) not in (IntType, LongType):
raise Exception, "bad type"
if data[0] < 1 or data[0] > 12:
raise Exception, "bad value"
else:
raise Exception, "invalid type"
except Exception, e:
raise ValueError, "invalid %s value - %s" % (self._type, e)
return data[0]
def _marshalData(self):
if self._cache == None:
self._cache = "--%02d--Z" % self._data
return self._cache
class monthType(gMonthType):
_validURIs = (NS.XSD2, NS.ENC)
class gDayType(anyType):
_validURIs = (NS.XSD3,)
def _checkValueSpace(self, data):
try:
if data == None:
data = time.gmtime(time.time())[2:3]
elif type(data) in (IntType, LongType, FloatType):
data = [data]
if type(data) in (ListType, TupleType):
if len(data) == 9:
data = data[2:3]
elif len(data) < 1:
raise Exception, "too few values"
elif len(data) > 1:
raise Exception, "too many values"
if type(data[0]) == FloatType:
try: s = int(data[0])
except: s = long(data[0])
if s != data[0]:
raise Exception, "not integral"
data = [s]
elif type(data[0]) not in (IntType, LongType):
raise Exception, "bad type"
if data[0] < 1 or data[0] > 31:
raise Exception, "bad value"
else:
raise Exception, "invalid type"
except Exception, e:
raise ValueError, "invalid %s value - %s" % (self._type, e)
return data[0]
def _marshalData(self):
if self._cache == None:
self._cache = "---%02dZ" % self._data
return self._cache
class recurringDayType(gDayType):
_validURIs = (NS.XSD2, NS.ENC)
class hexBinaryType(anyType):
_validURIs = (NS.XSD3,)
def _checkValueSpace(self, data):
if data == None:
raise ValueError, "must supply initial %s value" % self._type
if type(data) not in (StringType, UnicodeType):
raise AttributeError, "invalid %s type" % self._type
return data
def _marshalData(self):
if self._cache == None:
self._cache = encodeHexString(self._data)
return self._cache
class base64BinaryType(anyType):
_validURIs = (NS.XSD3,)
def _checkValueSpace(self, data):
if data == None:
raise ValueError, "must supply initial %s value" % self._type
if type(data) not in (StringType, UnicodeType):
raise AttributeError, "invalid %s type" % self._type
return data
def _marshalData(self):
if self._cache == None:
self._cache = base64.encodestring(self._data)
return self._cache
class base64Type(base64BinaryType):
_validURIs = (NS.ENC,)
class binaryType(anyType):
_validURIs = (NS.XSD, NS.ENC)
def __init__(self, data, name = None, typed = 1, encoding = 'base64',
attrs = None):
anyType.__init__(self, data, name, typed, attrs)
self._setAttr('encoding', encoding)
def _marshalData(self):
if self._cache == None:
if self._getAttr((None, 'encoding')) == 'base64':
self._cache = base64.encodestring(self._data)
else:
self._cache = encodeHexString(self._data)
return self._cache
def _checkValueSpace(self, data):
if data == None:
raise ValueError, "must supply initial %s value" % self._type
if type(data) not in (StringType, UnicodeType):
raise AttributeError, "invalid %s type" % self._type
return data
def _setAttr(self, attr, value):
attr = self._fixAttr(attr)
if attr[1] == 'encoding':
if attr[0] != None or value not in ('base64', 'hex'):
raise AttributeError, "invalid encoding"
self._cache = None
anyType._setAttr(self, attr, value)
class anyURIType(anyType):
_validURIs = (NS.XSD3,)
def _checkValueSpace(self, data):
if data == None:
raise ValueError, "must supply initial %s value" % self._type
if type(data) not in (StringType, UnicodeType):
raise AttributeError, "invalid %s type" % self._type
return data
def _marshalData(self):
if self._cache == None:
self._cache = urllib.quote(self._data)
return self._cache
class uriType(anyURIType):
_validURIs = (NS.XSD,)
class uriReferenceType(anyURIType):
_validURIs = (NS.XSD2,)
class NOTATIONType(anyType):
def __init__(self, data, name = None, typed = 1, attrs = None):
if self.__class__ == NOTATIONType:
raise Error, "a NOTATION can't be instantiated directly"
anyType.__init__(self, data, name, typed, attrs)
class ENTITIESType(anyType):
def _checkValueSpace(self, data):
if data == None:
raise ValueError, "must supply initial %s value" % self._type
if type(data) in (StringType, UnicodeType):
return (data,)
if type(data) not in (ListType, TupleType) or \
filter (lambda x: type(x) not in (StringType, UnicodeType), data):
raise AttributeError, "invalid %s type" % self._type
return data
def _marshalData(self):
return ' '.join(self._data)
class IDREFSType(ENTITIESType): pass
class NMTOKENSType(ENTITIESType): pass
class integerType(anyType):
def _checkValueSpace(self, data):
if data == None:
raise ValueError, "must supply initial %s value" % self._type
if type(data) not in (IntType, LongType):
raise ValueError, "invalid %s value" % self._type
return data
class nonPositiveIntegerType(anyType):
_validURIs = (NS.XSD2, NS.XSD3, NS.ENC)
def _checkValueSpace(self, data):
if data == None:
raise ValueError, "must supply initial %s value" % self._type
if type(data) not in (IntType, LongType) or data > 0:
raise ValueError, "invalid %s value" % self._type
return data
class non_Positive_IntegerType(nonPositiveIntegerType):
_validURIs = (NS.XSD,)
def _typeName(self):
return 'non-positive-integer'
class negativeIntegerType(anyType):
_validURIs = (NS.XSD2, NS.XSD3, NS.ENC)
def _checkValueSpace(self, data):
if data == None:
raise ValueError, "must supply initial %s value" % self._type
if type(data) not in (IntType, LongType) or data >= 0:
raise ValueError, "invalid %s value" % self._type
return data
class negative_IntegerType(negativeIntegerType):
_validURIs = (NS.XSD,)
def _typeName(self):
return 'negative-integer'
class longType(anyType):
_validURIs = (NS.XSD2, NS.XSD3, NS.ENC)
def _checkValueSpace(self, data):
if data == None:
raise ValueError, "must supply initial %s value" % self._type
if type(data) not in (IntType, LongType) or \
data < -9223372036854775808L or \
data > 9223372036854775807L:
raise ValueError, "invalid %s value" % self._type
return data
class intType(anyType):
_validURIs = (NS.XSD2, NS.XSD3, NS.ENC)
def _checkValueSpace(self, data):
if data == None:
raise ValueError, "must supply initial %s value" % self._type
if type(data) not in (IntType, LongType) or \
data < -2147483648L or \
data > 2147483647L:
raise ValueError, "invalid %s value" % self._type
return data
class shortType(anyType):
_validURIs = (NS.XSD2, NS.XSD3, NS.ENC)
def _checkValueSpace(self, data):
if data == None:
raise ValueError, "must supply initial %s value" % self._type
if type(data) not in (IntType, LongType) or \
data < -32768 or \
data > 32767:
raise ValueError, "invalid %s value" % self._type
return data
class byteType(anyType):
_validURIs = (NS.XSD2, NS.XSD3, NS.ENC)
def _checkValueSpace(self, data):
if data == None:
raise ValueError, "must supply initial %s value" % self._type
if type(data) not in (IntType, LongType) or \
data < -128 or \
data > 127:
raise ValueError, "invalid %s value" % self._type
return data
class nonNegativeIntegerType(anyType):
_validURIs = (NS.XSD2, NS.XSD3, NS.ENC)
def _checkValueSpace(self, data):
if data == None:
raise ValueError, "must supply initial %s value" % self._type
if type(data) not in (IntType, LongType) or data < 0:
raise ValueError, "invalid %s value" % self._type
return data
class non_Negative_IntegerType(nonNegativeIntegerType):
_validURIs = (NS.XSD,)
def _typeName(self):
return 'non-negative-integer'
class unsignedLongType(anyType):
_validURIs = (NS.XSD2, NS.XSD3, NS.ENC)
def _checkValueSpace(self, data):
if data == None:
raise ValueError, "must supply initial %s value" % self._type
if type(data) not in (IntType, LongType) or \
data < 0 or \
data > 18446744073709551615L:
raise ValueError, "invalid %s value" % self._type
return data
class unsignedIntType(anyType):
_validURIs = (NS.XSD2, NS.XSD3, NS.ENC)
def _checkValueSpace(self, data):
if data == None:
raise ValueError, "must supply initial %s value" % self._type
if type(data) not in (IntType, LongType) or \
data < 0 or \
data > 4294967295L:
raise ValueError, "invalid %s value" % self._type
return data
class unsignedShortType(anyType):
_validURIs = (NS.XSD2, NS.XSD3, NS.ENC)
def _checkValueSpace(self, data):
if data == None:
raise ValueError, "must supply initial %s value" % self._type
if type(data) not in (IntType, LongType) or \
data < 0 or \
data > 65535:
raise ValueError, "invalid %s value" % self._type
return data
class unsignedByteType(anyType):
_validURIs = (NS.XSD2, NS.XSD3, NS.ENC)
def _checkValueSpace(self, data):
if data == None:
raise ValueError, "must supply initial %s value" % self._type
if type(data) not in (IntType, LongType) or \
data < 0 or \
data > 255:
raise ValueError, "invalid %s value" % self._type
return data
class positiveIntegerType(anyType):
_validURIs = (NS.XSD2, NS.XSD3, NS.ENC)
def _checkValueSpace(self, data):
if data == None:
raise ValueError, "must supply initial %s value" % self._type
if type(data) not in (IntType, LongType) or data <= 0:
raise ValueError, "invalid %s value" % self._type
return data
class positive_IntegerType(positiveIntegerType):
_validURIs = (NS.XSD,)
def _typeName(self):
return 'positive-integer'
# Now compound types
class compoundType(anyType):
def __init__(self, data = None, name = None, typed = 1, attrs = None):
if self.__class__ == compoundType:
raise Error, "a compound can't be instantiated directly"
anyType.__init__(self, data, name, typed, attrs)
self._keyord = []
if type(data) == DictType:
self.__dict__.update(data)
def _aslist(self, item=None):
if item is not None:
return self.__dict__[self._keyord[item]]
else:
return map( lambda x: self.__dict__[x], self._keyord)
def _asdict(self, item=None, encoding=Config.dict_encoding):
if item is not None:
if type(item) in (UnicodeType,StringType):
item = item.encode(encoding)
return self.__dict__[item]
else:
retval = {}
def fun(x): retval[x.encode(encoding)] = self.__dict__[x]
if hasattr(self, '_keyord'):
map( fun, self._keyord)
else:
for name in dir(self):
if isPublic(name):
retval[name] = getattr(self,name)
return retval
def __getitem__(self, item):
if type(item) == IntType:
return self.__dict__[self._keyord[item]]
else:
return getattr(self, item)
def __len__(self):
return len(self._keyord)
def __nonzero__(self):
return 1
def _keys(self):
return filter(lambda x: x[0] != '_', self.__dict__.keys())
def _addItem(self, name, value, attrs = None):
if name in self._keyord:
if type(self.__dict__[name]) != ListType:
self.__dict__[name] = [self.__dict__[name]]
self.__dict__[name].append(value)
else:
self.__dict__[name] = value
self._keyord.append(name)
def _placeItem(self, name, value, pos, subpos = 0, attrs = None):
if subpos == 0 and type(self.__dict__[name]) != ListType:
self.__dict__[name] = value
else:
self.__dict__[name][subpos] = value
# only add to key order list if it does not already
# exist in list
if not (name in self._keyord):
if pos < len(x):
self._keyord[pos] = name
else:
self._keyord.append(name)
def _getItemAsList(self, name, default = []):
try:
d = self.__dict__[name]
except:
return default
if type(d) == ListType:
return d
return [d]
def __str__(self):
return anyType.__str__(self) + ": " + str(self._asdict())
def __repr__(self):
return self.__str__()
class structType(compoundType):
pass
class headerType(structType):
_validURIs = (NS.ENV,)
def __init__(self, data = None, typed = 1, attrs = None):
structType.__init__(self, data, "Header", typed, attrs)
class bodyType(structType):
_validURIs = (NS.ENV,)
def __init__(self, data = None, typed = 1, attrs = None):
structType.__init__(self, data, "Body", typed, attrs)
class arrayType(UserList.UserList, compoundType):
def __init__(self, data = None, name = None, attrs = None,
offset = 0, rank = None, asize = 0, elemsname = None):
if data:
if type(data) not in (ListType, TupleType):
raise Error, "Data must be a sequence"
UserList.UserList.__init__(self, data)
compoundType.__init__(self, data, name, 0, attrs)
self._elemsname = elemsname or "item"
if data == None:
self._rank = rank
# According to 5.4.2.2 in the SOAP spec, each element in a
# sparse array must have a position. _posstate keeps track of
# whether we've seen a position or not. It's possible values
# are:
# -1 No elements have been added, so the state is indeterminate
# 0 An element without a position has been added, so no
# elements can have positions
# 1 An element with a position has been added, so all elements
# must have positions
self._posstate = -1
self._full = 0
if asize in ('', None):
asize = '0'
self._dims = map (lambda x: int(x), str(asize).split(','))
self._dims.reverse() # It's easier to work with this way
self._poss = [0] * len(self._dims) # This will end up
# reversed too
for i in range(len(self._dims)):
if self._dims[i] < 0 or \
self._dims[i] == 0 and len(self._dims) > 1:
raise TypeError, "invalid Array dimensions"
if offset > 0:
self._poss[i] = offset % self._dims[i]
offset = int(offset / self._dims[i])
# Don't break out of the loop if offset is 0 so we test all the
# dimensions for > 0.
if offset:
raise AttributeError, "invalid Array offset"
a = [None] * self._dims[0]
for i in range(1, len(self._dims)):
b = []
for j in range(self._dims[i]):
b.append(copy.deepcopy(a))
a = b
self.data = a
def _aslist(self, item=None):
if item is not None:
return self.data[int(item)]
else:
return self.data
def _asdict(self, item=None, encoding=Config.dict_encoding):
if item is not None:
if type(item) in (UnicodeType,StringType):
item = item.encode(encoding)
return self.data[int(item)]
else:
retval = {}
def fun(x): retval[str(x).encode(encoding)] = self.data[x]
map( fun, range(len(self.data)) )
return retval
def __getitem__(self, item):
try:
return self.data[int(item)]
except ValueError:
return getattr(self, item)
def __len__(self):
return len(self.data)
def __nonzero__(self):
return 1
def __str__(self):
return anyType.__str__(self) + ": " + str(self._aslist())
def _keys(self):
return filter(lambda x: x[0] != '_', self.__dict__.keys())
def _addItem(self, name, value, attrs):
if self._full:
raise ValueError, "Array is full"
pos = attrs.get((NS.ENC, 'position'))
if pos != None:
if self._posstate == 0:
raise AttributeError, \
"all elements in a sparse Array must have a " \
"position attribute"
self._posstate = 1
try:
if pos[0] == '[' and pos[-1] == ']':
pos = map (lambda x: int(x), pos[1:-1].split(','))
pos.reverse()
if len(pos) == 1:
pos = pos[0]
curpos = [0] * len(self._dims)
for i in range(len(self._dims)):
curpos[i] = pos % self._dims[i]
pos = int(pos / self._dims[i])
if pos == 0:
break
if pos:
raise Exception
elif len(pos) != len(self._dims):
raise Exception
else:
for i in range(len(self._dims)):
if pos[i] >= self._dims[i]:
raise Exception
curpos = pos
else:
raise Exception
except:
raise AttributeError, \
"invalid Array element position %s" % str(pos)
else:
if self._posstate == 1:
raise AttributeError, \
"only elements in a sparse Array may have a " \
"position attribute"
self._posstate = 0
curpos = self._poss
a = self.data
for i in range(len(self._dims) - 1, 0, -1):
a = a[curpos[i]]
if curpos[0] >= len(a):
a += [None] * (len(a) - curpos[0] + 1)
a[curpos[0]] = value
if pos == None:
self._poss[0] += 1
for i in range(len(self._dims) - 1):
if self._poss[i] < self._dims[i]:
break
self._poss[i] = 0
self._poss[i + 1] += 1
if self._dims[-1] and self._poss[-1] >= self._dims[-1]:
#self._full = 1
#FIXME: why is this occuring?
pass
def _placeItem(self, name, value, pos, subpos, attrs = None):
curpos = [0] * len(self._dims)
for i in range(len(self._dims)):
if self._dims[i] == 0:
curpos[0] = pos
break
curpos[i] = pos % self._dims[i]
pos = int(pos / self._dims[i])
if pos == 0:
break
if self._dims[i] != 0 and pos:
raise Error, "array index out of range"
a = self.data
for i in range(len(self._dims) - 1, 0, -1):
a = a[curpos[i]]
if curpos[0] >= len(a):
a += [None] * (len(a) - curpos[0] + 1)
a[curpos[0]] = value
class typedArrayType(arrayType):
def __init__(self, data = None, name = None, typed = None, attrs = None,
offset = 0, rank = None, asize = 0, elemsname = None, complexType = 0):
arrayType.__init__(self, data, name, attrs, offset, rank, asize,
elemsname)
self._typed = 1
self._type = typed
self._complexType = complexType
class faultType(structType, Error):
def __init__(self, faultcode = "", faultstring = "", detail = None):
self.faultcode = faultcode
self.faultstring = faultstring
if detail != None:
self.detail = detail
structType.__init__(self, None, 0)
def _setDetail(self, detail = None):
if detail != None:
self.detail = detail
else:
try: del self.detail
except AttributeError: pass
def __repr__(self):
if getattr(self, 'detail', None) != None:
return "<Fault %s: %s: %s>" % (self.faultcode,
self.faultstring,
self.detail)
else:
return "<Fault %s: %s>" % (self.faultcode, self.faultstring)
__str__ = __repr__
def __call__(self):
return (self.faultcode, self.faultstring, self.detail)
class SOAPException(Exception):
def __init__(self, code="", string="", detail=None):
self.value = ("SOAPpy SOAP Exception", code, string, detail)
self.code = code
self.string = string
self.detail = detail
def __str__(self):
return repr(self.value)
class RequiredHeaderMismatch(Exception):
def __init__(self, value):
self.value = value
def __str__(self):
return repr(self.value)
class MethodNotFound(Exception):
def __init__(self, value):
(val, detail) = value.split(":")
self.value = val
self.detail = detail
def __str__(self):
return repr(self.value, self.detail)
class AuthorizationFailed(Exception):
def __init__(self, value):
self.value = value
def __str__(self):
return repr(self.value)
class MethodFailed(Exception):
def __init__(self, value):
self.value = value
def __str__(self):
return repr(self.value)
#######
# Convert complex SOAPpy objects to native python equivalents
#######
def simplify(object, level=0):
"""
Convert the SOAPpy objects and their contents to simple python types.
This function recursively converts the passed 'container' object,
and all public subobjects. (Private subobjects have names that
start with '_'.)
Conversions:
- faultType --> raise python exception
- arrayType --> array
- compoundType --> dictionary
"""
if level > 10:
return object
if isinstance( object, faultType ):
if object.faultstring == "Required Header Misunderstood":
raise RequiredHeaderMismatch(object.detail)
elif object.faultstring == "Method Not Found":
raise MethodNotFound(object.detail)
elif object.faultstring == "Authorization Failed":
raise AuthorizationFailed(object.detail)
elif object.faultstring == "Method Failed":
raise MethodFailed(object.detail)
else:
se = SOAPException(object.faultcode, object.faultstring,
object.detail)
raise se
elif isinstance( object, arrayType ):
data = object._aslist()
for k in range(len(data)):
data[k] = simplify(data[k], level=level+1)
return data
elif isinstance( object, compoundType ) or isinstance(object, structType):
data = object._asdict()
for k in data.keys():
if isPublic(k):
data[k] = simplify(data[k], level=level+1)
return data
elif type(object)==DictType:
for k in object.keys():
if isPublic(k):
object[k] = simplify(object[k])
return object
elif type(object)==list:
for k in range(len(object)):
object[k] = simplify(object[k])
return object
else:
return object
def simplify_contents(object, level=0):
"""
Convert the contents of SOAPpy objects to simple python types.
This function recursively converts the sub-objects contained in a
'container' object to simple python types.
Conversions:
- faultType --> raise python exception
- arrayType --> array
- compoundType --> dictionary
"""
if level>10: return object
if isinstance( object, faultType ):
for k in object._keys():
if isPublic(k):
setattr(object, k, simplify(object[k], level=level+1))
raise object
elif isinstance( object, arrayType ):
data = object._aslist()
for k in range(len(data)):
object[k] = simplify(data[k], level=level+1)
elif isinstance(object, structType):
data = object._asdict()
for k in data.keys():
if isPublic(k):
setattr(object, k, simplify(data[k], level=level+1))
elif isinstance( object, compoundType ) :
data = object._asdict()
for k in data.keys():
if isPublic(k):
object[k] = simplify(data[k], level=level+1)
elif type(object)==DictType:
for k in object.keys():
if isPublic(k):
object[k] = simplify(object[k])
elif type(object)==list:
for k in range(len(object)):
object[k] = simplify(object[k])
return object
|
tcwicklund/django | refs/heads/master | tests/transactions/models.py | 411 | """
Transactions
Django handles transactions in three different ways. The default is to commit
each transaction upon a write, but you can decorate a function to get
commit-on-success behavior. Alternatively, you can manage the transaction
manually.
"""
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()
class Meta:
ordering = ('first_name', 'last_name')
def __str__(self):
return ("%s %s" % (self.first_name, self.last_name)).strip()
|
GeoNode/geonode | refs/heads/master | geonode/tests/bdd/__init__.py | 102 | # -*- coding: utf-8 -*-
#########################################################################
#
# Copyright (C) 2018 OSGeo
#
# 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/>.
#
#########################################################################
|
happycube/ld-decode | refs/heads/master | lddecode/fft8.py | 1 | #! /usr/bin/python
import math
import matplotlib.pyplot as plt
import numpy as np
import scipy as sp
import sys
SAMPLE_RATE = 8 * 315 / 88.0
MAX_SAMPLES = int(1e6)
filename = ""
def load(filename):
if filename.endswith(".ld"):
ttype = np.uint16
max_samples = MAX_SAMPLES * 2
print("Assuming 16 bits per pixel")
else:
ttype = np.uint8
max_samples = MAX_SAMPLES
print("Assuming 8 bits per pixel")
with open(filename, "rb") as binfile:
data = np.fromstring(
binfile.read(max_samples), dtype=ttype
) # Read at most 1e6 samples
print("Loaded %d bytes of file %s" % (max_samples, filename))
return data
def plotfft(data, filename=""):
mean = np.mean(data)
rawmax = max(data)
rawmin = min(data)
sigrange = rawmax - rawmin
data = data - mean
freq = (
np.fft.fftfreq(np.arange(len(data)).shape[-1]) * SAMPLE_RATE
) # Set frequency scale
data = np.fft.fft(data)
data = np.sqrt((data.real * data.real) + (data.imag * data.imag))
data = data / max(data) # Normalize to y to 1.0
peak_to_background = 20 * math.log10(1.0 / np.mean(data))
plt.plot(freq[4:], data[4:])
plt.axis([0, SAMPLE_RATE / 2, 0, 1])
plt.xlabel("Frequency (MHz)")
plt.ylabel("Power (linear)")
fig = plt.figure(1)
fig.canvas.set_window_title(
"FFT8 %s Range:%d(%d - %d) Mean:%.2f PkBG:%.2fdb"
% (filename, sigrange, rawmax, rawmin, mean, peak_to_background)
)
plt.show()
if __name__ == "__main__":
data = load(sys.argv[1])
filename = sys.argv[1]
plotfft(data, filename)
|
stanlyxiang/incubator-hawq | refs/heads/master | tools/bin/pythonSrc/pychecker-0.8.18/pychecker2/File.py | 11 | from pychecker2.util import parents
from compiler import ast
class File:
def __init__(self, name):
self.name = name
self.parseTree = None
self.scopes = {}
self.root_scope = None
self.warnings = []
def __cmp__(self, other):
return cmp(self.name, other.name)
def warning(self, line, warn, *args):
lineno = getattr(line, 'lineno', line)
if not lineno and hasattr(line, 'parent'):
for p in parents(line):
if p.lineno:
lineno = p.lineno
break
self.warnings.append( (lineno, warn, args) )
def scope_filter(self, type):
return [x for x in self.scopes.iteritems() if isinstance(x[0], type)]
def function_scopes(self):
return self.scope_filter(ast.Function)
def class_scopes(self):
return self.scope_filter(ast.Class)
def not_class_scopes(self):
result = []
for n, s in self.scopes.iteritems():
if not isinstance(n, ast.Class):
result.append( (n, s) )
return result
|
SerCeMan/intellij-community | refs/heads/master | python/lib/Lib/distutils/command/bdist_dumb.py | 81 | """distutils.command.bdist_dumb
Implements the Distutils 'bdist_dumb' command (create a "dumb" built
distribution -- i.e., just an archive to be unpacked under $prefix or
$exec_prefix)."""
# This module should be kept compatible with Python 2.1.
__revision__ = "$Id: bdist_dumb.py 38697 2005-03-23 18:54:36Z loewis $"
import os
from distutils.core import Command
from distutils.util import get_platform
from distutils.dir_util import create_tree, remove_tree, ensure_relative
from distutils.errors import *
from distutils.sysconfig import get_python_version
from distutils import log
class bdist_dumb (Command):
description = "create a \"dumb\" built distribution"
user_options = [('bdist-dir=', 'd',
"temporary directory for creating the distribution"),
('plat-name=', 'p',
"platform name to embed in generated filenames "
"(default: %s)" % get_platform()),
('format=', 'f',
"archive format to create (tar, ztar, gztar, zip)"),
('keep-temp', 'k',
"keep the pseudo-installation tree around after " +
"creating the distribution archive"),
('dist-dir=', 'd',
"directory to put final built distributions in"),
('skip-build', None,
"skip rebuilding everything (for testing/debugging)"),
('relative', None,
"build the archive using relative paths"
"(default: false)"),
]
boolean_options = ['keep-temp', 'skip-build', 'relative']
default_format = { 'posix': 'gztar',
'java': 'gztar',
'nt': 'zip',
'os2': 'zip' }
def initialize_options (self):
self.bdist_dir = None
self.plat_name = None
self.format = None
self.keep_temp = 0
self.dist_dir = None
self.skip_build = 0
self.relative = 0
# initialize_options()
def finalize_options (self):
if self.bdist_dir is None:
bdist_base = self.get_finalized_command('bdist').bdist_base
self.bdist_dir = os.path.join(bdist_base, 'dumb')
if self.format is None:
try:
self.format = self.default_format[os.name]
except KeyError:
raise DistutilsPlatformError, \
("don't know how to create dumb built distributions " +
"on platform %s") % os.name
self.set_undefined_options('bdist',
('dist_dir', 'dist_dir'),
('plat_name', 'plat_name'))
# finalize_options()
def run (self):
if not self.skip_build:
self.run_command('build')
install = self.reinitialize_command('install', reinit_subcommands=1)
install.root = self.bdist_dir
install.skip_build = self.skip_build
install.warn_dir = 0
log.info("installing to %s" % self.bdist_dir)
self.run_command('install')
# And make an archive relative to the root of the
# pseudo-installation tree.
archive_basename = "%s.%s" % (self.distribution.get_fullname(),
self.plat_name)
# OS/2 objects to any ":" characters in a filename (such as when
# a timestamp is used in a version) so change them to hyphens.
if os.name == "os2":
archive_basename = archive_basename.replace(":", "-")
pseudoinstall_root = os.path.join(self.dist_dir, archive_basename)
if not self.relative:
archive_root = self.bdist_dir
else:
if (self.distribution.has_ext_modules() and
(install.install_base != install.install_platbase)):
raise DistutilsPlatformError, \
("can't make a dumb built distribution where "
"base and platbase are different (%s, %s)"
% (repr(install.install_base),
repr(install.install_platbase)))
else:
archive_root = os.path.join(self.bdist_dir,
ensure_relative(install.install_base))
# Make the archive
filename = self.make_archive(pseudoinstall_root,
self.format, root_dir=archive_root)
if self.distribution.has_ext_modules():
pyversion = get_python_version()
else:
pyversion = 'any'
self.distribution.dist_files.append(('bdist_dumb', pyversion,
filename))
if not self.keep_temp:
remove_tree(self.bdist_dir, dry_run=self.dry_run)
# run()
# class bdist_dumb
|
varunnaganathan/django | refs/heads/master | django/contrib/admin/helpers.py | 21 | from __future__ import unicode_literals
import json
import warnings
from django import forms
from django.conf import settings
from django.contrib.admin.utils import (
display_for_field, flatten_fieldsets, help_text_for_field, label_for_field,
lookup_field,
)
from django.core.exceptions import ObjectDoesNotExist
from django.db.models.fields.related import ManyToManyRel
from django.forms.utils import flatatt
from django.template.defaultfilters import capfirst, linebreaksbr
from django.utils import six
from django.utils.deprecation import RemovedInDjango20Warning
from django.utils.encoding import force_text, smart_text
from django.utils.html import conditional_escape, format_html
from django.utils.safestring import mark_safe
from django.utils.translation import ugettext, ugettext_lazy as _
ACTION_CHECKBOX_NAME = '_selected_action'
class ActionForm(forms.Form):
action = forms.ChoiceField(label=_('Action:'))
select_across = forms.BooleanField(label='', required=False, initial=0,
widget=forms.HiddenInput({'class': 'select-across'}))
checkbox = forms.CheckboxInput({'class': 'action-select'}, lambda value: False)
class AdminForm(object):
def __init__(self, form, fieldsets, prepopulated_fields, readonly_fields=None, model_admin=None):
self.form, self.fieldsets = form, fieldsets
self.prepopulated_fields = [{
'field': form[field_name],
'dependencies': [form[f] for f in dependencies]
} for field_name, dependencies in prepopulated_fields.items()]
self.model_admin = model_admin
if readonly_fields is None:
readonly_fields = ()
self.readonly_fields = readonly_fields
def __iter__(self):
for name, options in self.fieldsets:
yield Fieldset(
self.form, name,
readonly_fields=self.readonly_fields,
model_admin=self.model_admin,
**options
)
def _media(self):
media = self.form.media
for fs in self:
media = media + fs.media
return media
media = property(_media)
class Fieldset(object):
def __init__(self, form, name=None, readonly_fields=(), fields=(), classes=(),
description=None, model_admin=None):
self.form = form
self.name, self.fields = name, fields
self.classes = ' '.join(classes)
self.description = description
self.model_admin = model_admin
self.readonly_fields = readonly_fields
def _media(self):
if 'collapse' in self.classes:
extra = '' if settings.DEBUG else '.min'
js = ['vendor/jquery/jquery%s.js' % extra,
'jquery.init.js',
'collapse%s.js' % extra]
return forms.Media(js=['admin/js/%s' % url for url in js])
return forms.Media()
media = property(_media)
def __iter__(self):
for field in self.fields:
yield Fieldline(self.form, field, self.readonly_fields, model_admin=self.model_admin)
class Fieldline(object):
def __init__(self, form, field, readonly_fields=None, model_admin=None):
self.form = form # A django.forms.Form instance
if not hasattr(field, "__iter__") or isinstance(field, six.text_type):
self.fields = [field]
else:
self.fields = field
self.has_visible_field = not all(field in self.form.fields and
self.form.fields[field].widget.is_hidden
for field in self.fields)
self.model_admin = model_admin
if readonly_fields is None:
readonly_fields = ()
self.readonly_fields = readonly_fields
def __iter__(self):
for i, field in enumerate(self.fields):
if field in self.readonly_fields:
yield AdminReadonlyField(self.form, field, is_first=(i == 0),
model_admin=self.model_admin)
else:
yield AdminField(self.form, field, is_first=(i == 0))
def errors(self):
return mark_safe(
'\n'.join(self.form[f].errors.as_ul()
for f in self.fields if f not in self.readonly_fields).strip('\n')
)
class AdminField(object):
def __init__(self, form, field, is_first):
self.field = form[field] # A django.forms.BoundField instance
self.is_first = is_first # Whether this field is first on the line
self.is_checkbox = isinstance(self.field.field.widget, forms.CheckboxInput)
self.is_readonly = False
def label_tag(self):
classes = []
contents = conditional_escape(force_text(self.field.label))
if self.is_checkbox:
classes.append('vCheckboxLabel')
if self.field.field.required:
classes.append('required')
if not self.is_first:
classes.append('inline')
attrs = {'class': ' '.join(classes)} if classes else {}
# checkboxes should not have a label suffix as the checkbox appears
# to the left of the label.
return self.field.label_tag(contents=mark_safe(contents), attrs=attrs,
label_suffix='' if self.is_checkbox else None)
def errors(self):
return mark_safe(self.field.errors.as_ul())
class AdminReadonlyField(object):
def __init__(self, form, field, is_first, model_admin=None):
# Make self.field look a little bit like a field. This means that
# {{ field.name }} must be a useful class name to identify the field.
# For convenience, store other field-related data here too.
if callable(field):
class_name = field.__name__ if field.__name__ != '<lambda>' else ''
else:
class_name = field
if form._meta.labels and class_name in form._meta.labels:
label = form._meta.labels[class_name]
else:
label = label_for_field(field, form._meta.model, model_admin)
if form._meta.help_texts and class_name in form._meta.help_texts:
help_text = form._meta.help_texts[class_name]
else:
help_text = help_text_for_field(class_name, form._meta.model)
self.field = {
'name': class_name,
'label': label,
'help_text': help_text,
'field': field,
}
self.form = form
self.model_admin = model_admin
self.is_first = is_first
self.is_checkbox = False
self.is_readonly = True
self.empty_value_display = model_admin.get_empty_value_display()
def label_tag(self):
attrs = {}
if not self.is_first:
attrs["class"] = "inline"
label = self.field['label']
return format_html('<label{}>{}:</label>',
flatatt(attrs),
capfirst(force_text(label)))
def contents(self):
from django.contrib.admin.templatetags.admin_list import _boolean_icon
field, obj, model_admin = self.field['field'], self.form.instance, self.model_admin
try:
f, attr, value = lookup_field(field, obj, model_admin)
except (AttributeError, ValueError, ObjectDoesNotExist):
result_repr = self.empty_value_display
else:
if f is None:
boolean = getattr(attr, "boolean", False)
if boolean:
result_repr = _boolean_icon(value)
else:
if hasattr(value, "__html__"):
result_repr = value
else:
result_repr = smart_text(value)
if getattr(attr, "allow_tags", False):
warnings.warn(
"Deprecated allow_tags attribute used on %s. "
"Use django.utils.safestring.format_html(), "
"format_html_join(), or mark_safe() instead." % attr,
RemovedInDjango20Warning
)
result_repr = mark_safe(value)
else:
result_repr = linebreaksbr(result_repr)
else:
if isinstance(f.remote_field, ManyToManyRel) and value is not None:
result_repr = ", ".join(map(six.text_type, value.all()))
else:
result_repr = display_for_field(value, f, self.empty_value_display)
result_repr = linebreaksbr(result_repr)
return conditional_escape(result_repr)
class InlineAdminFormSet(object):
"""
A wrapper around an inline formset for use in the admin system.
"""
def __init__(self, inline, formset, fieldsets, prepopulated_fields=None,
readonly_fields=None, model_admin=None):
self.opts = inline
self.formset = formset
self.fieldsets = fieldsets
self.model_admin = model_admin
if readonly_fields is None:
readonly_fields = ()
self.readonly_fields = readonly_fields
if prepopulated_fields is None:
prepopulated_fields = {}
self.prepopulated_fields = prepopulated_fields
self.classes = ' '.join(inline.classes) if inline.classes else ''
def __iter__(self):
for form, original in zip(self.formset.initial_forms, self.formset.get_queryset()):
view_on_site_url = self.opts.get_view_on_site_url(original)
yield InlineAdminForm(self.formset, form, self.fieldsets,
self.prepopulated_fields, original, self.readonly_fields,
model_admin=self.opts, view_on_site_url=view_on_site_url)
for form in self.formset.extra_forms:
yield InlineAdminForm(self.formset, form, self.fieldsets,
self.prepopulated_fields, None, self.readonly_fields,
model_admin=self.opts)
yield InlineAdminForm(self.formset, self.formset.empty_form,
self.fieldsets, self.prepopulated_fields, None,
self.readonly_fields, model_admin=self.opts)
def fields(self):
fk = getattr(self.formset, "fk", None)
for i, field_name in enumerate(flatten_fieldsets(self.fieldsets)):
if fk and fk.name == field_name:
continue
if field_name in self.readonly_fields:
yield {
'label': label_for_field(field_name, self.opts.model, self.opts),
'widget': {
'is_hidden': False
},
'required': False,
'help_text': help_text_for_field(field_name, self.opts.model),
}
else:
form_field = self.formset.form.base_fields[field_name]
label = form_field.label
if label is None:
label = label_for_field(field_name, self.opts.model, self.opts)
yield {
'label': label,
'widget': form_field.widget,
'required': form_field.required,
'help_text': form_field.help_text,
}
def inline_formset_data(self):
verbose_name = self.opts.verbose_name
return json.dumps({
'name': '#%s' % self.formset.prefix,
'options': {
'prefix': self.formset.prefix,
'addText': ugettext('Add another %(verbose_name)s') % {
'verbose_name': capfirst(verbose_name),
},
'deleteText': ugettext('Remove'),
}
})
def _media(self):
media = self.opts.media + self.formset.media
for fs in self:
media = media + fs.media
return media
media = property(_media)
class InlineAdminForm(AdminForm):
"""
A wrapper around an inline form for use in the admin system.
"""
def __init__(self, formset, form, fieldsets, prepopulated_fields, original,
readonly_fields=None, model_admin=None, view_on_site_url=None):
self.formset = formset
self.model_admin = model_admin
self.original = original
self.show_url = original and view_on_site_url is not None
self.absolute_url = view_on_site_url
super(InlineAdminForm, self).__init__(form, fieldsets, prepopulated_fields,
readonly_fields, model_admin)
def __iter__(self):
for name, options in self.fieldsets:
yield InlineFieldset(self.formset, self.form, name,
self.readonly_fields, model_admin=self.model_admin, **options)
def needs_explicit_pk_field(self):
# Auto fields are editable (oddly), so need to check for auto or non-editable pk
if self.form._meta.model._meta.has_auto_field or not self.form._meta.model._meta.pk.editable:
return True
# Also search any parents for an auto field. (The pk info is propagated to child
# models so that does not need to be checked in parents.)
for parent in self.form._meta.model._meta.get_parent_list():
if parent._meta.has_auto_field:
return True
return False
def pk_field(self):
return AdminField(self.form, self.formset._pk_field.name, False)
def fk_field(self):
fk = getattr(self.formset, "fk", None)
if fk:
return AdminField(self.form, fk.name, False)
else:
return ""
def deletion_field(self):
from django.forms.formsets import DELETION_FIELD_NAME
return AdminField(self.form, DELETION_FIELD_NAME, False)
def ordering_field(self):
from django.forms.formsets import ORDERING_FIELD_NAME
return AdminField(self.form, ORDERING_FIELD_NAME, False)
class InlineFieldset(Fieldset):
def __init__(self, formset, *args, **kwargs):
self.formset = formset
super(InlineFieldset, self).__init__(*args, **kwargs)
def __iter__(self):
fk = getattr(self.formset, "fk", None)
for field in self.fields:
if fk and fk.name == field:
continue
yield Fieldline(self.form, field, self.readonly_fields,
model_admin=self.model_admin)
class AdminErrorList(forms.utils.ErrorList):
"""
Stores all errors for the form/formsets in an add/change stage view.
"""
def __init__(self, form, inline_formsets):
super(AdminErrorList, self).__init__()
if form.is_bound:
self.extend(form.errors.values())
for inline_formset in inline_formsets:
self.extend(inline_formset.non_form_errors())
for errors_in_inline_form in inline_formset.errors:
self.extend(errors_in_inline_form.values())
|
alephu5/Soundbyte | refs/heads/master | environment/lib/python3.3/site-packages/numpy/random/__init__.py | 16 | """
========================
Random Number Generation
========================
==================== =========================================================
Utility functions
==============================================================================
random Uniformly distributed values of a given shape.
bytes Uniformly distributed random bytes.
random_integers Uniformly distributed integers in a given range.
random_sample Uniformly distributed floats in a given range.
random Alias for random_sample
ranf Alias for random_sample
sample Alias for random_sample
choice Generate a weighted random sample from a given array-like
permutation Randomly permute a sequence / generate a random sequence.
shuffle Randomly permute a sequence in place.
seed Seed the random number generator.
==================== =========================================================
==================== =========================================================
Compatibility functions
==============================================================================
rand Uniformly distributed values.
randn Normally distributed values.
ranf Uniformly distributed floating point numbers.
randint Uniformly distributed integers in a given range.
==================== =========================================================
==================== =========================================================
Univariate distributions
==============================================================================
beta Beta distribution over ``[0, 1]``.
binomial Binomial distribution.
chisquare :math:`\\chi^2` distribution.
exponential Exponential distribution.
f F (Fisher-Snedecor) distribution.
gamma Gamma distribution.
geometric Geometric distribution.
gumbel Gumbel distribution.
hypergeometric Hypergeometric distribution.
laplace Laplace distribution.
logistic Logistic distribution.
lognormal Log-normal distribution.
logseries Logarithmic series distribution.
negative_binomial Negative binomial distribution.
noncentral_chisquare Non-central chi-square distribution.
noncentral_f Non-central F distribution.
normal Normal / Gaussian distribution.
pareto Pareto distribution.
poisson Poisson distribution.
power Power distribution.
rayleigh Rayleigh distribution.
triangular Triangular distribution.
uniform Uniform distribution.
vonmises Von Mises circular distribution.
wald Wald (inverse Gaussian) distribution.
weibull Weibull distribution.
zipf Zipf's distribution over ranked data.
==================== =========================================================
==================== =========================================================
Multivariate distributions
==============================================================================
dirichlet Multivariate generalization of Beta distribution.
multinomial Multivariate generalization of the binomial distribution.
multivariate_normal Multivariate generalization of the normal distribution.
==================== =========================================================
==================== =========================================================
Standard distributions
==============================================================================
standard_cauchy Standard Cauchy-Lorentz distribution.
standard_exponential Standard exponential distribution.
standard_gamma Standard Gamma distribution.
standard_normal Standard normal distribution.
standard_t Standard Student's t-distribution.
==================== =========================================================
==================== =========================================================
Internal functions
==============================================================================
get_state Get tuple representing internal state of generator.
set_state Set state of generator.
==================== =========================================================
"""
from __future__ import division, absolute_import, print_function
import warnings
# To get sub-modules
from .info import __doc__, __all__
with warnings.catch_warnings():
warnings.filterwarnings("ignore", message="numpy.ndarray size changed")
from .mtrand import *
# Some aliases:
ranf = random = sample = random_sample
__all__.extend(['ranf', 'random', 'sample'])
def __RandomState_ctor():
"""Return a RandomState instance.
This function exists solely to assist (un)pickling.
"""
return RandomState()
from numpy.testing import Tester
test = Tester().test
bench = Tester().bench
|
alxgu/ansible | refs/heads/devel | contrib/inventory/stacki.py | 52 | #!/usr/bin/env python
# Copyright (c) 2016, Hugh Ma <hugh.ma@flextronics.com>
#
# This module 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 software 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 software. If not, see <http://www.gnu.org/licenses/>.
# Stacki inventory script
# Configure stacki.yml with proper auth information and place in the following:
# - ../inventory/stacki.yml
# - /etc/stacki/stacki.yml
# - /etc/ansible/stacki.yml
# The stacki.yml file can contain entries for authentication information
# regarding the Stacki front-end node.
#
# use_hostnames uses hostname rather than interface ip as connection
#
#
"""
Example Usage:
List Stacki Nodes
$ ./stack.py --list
Example Configuration:
---
stacki:
auth:
stacki_user: admin
stacki_password: abc12345678910
stacki_endpoint: http://192.168.200.50/stack
use_hostnames: false
"""
import argparse
import os
import sys
import yaml
from distutils.version import StrictVersion
import json
try:
import requests
except Exception:
sys.exit('requests package is required for this inventory script')
CONFIG_FILES = ['/etc/stacki/stacki.yml', '/etc/ansible/stacki.yml']
def stack_auth(params):
endpoint = params['stacki_endpoint']
auth_creds = {'USERNAME': params['stacki_user'],
'PASSWORD': params['stacki_password']}
client = requests.session()
client.get(endpoint)
init_csrf = client.cookies['csrftoken']
header = {'csrftoken': init_csrf, 'X-CSRFToken': init_csrf,
'Content-type': 'application/x-www-form-urlencoded'}
login_endpoint = endpoint + "/login"
login_req = client.post(login_endpoint, data=auth_creds, headers=header)
csrftoken = login_req.cookies['csrftoken']
sessionid = login_req.cookies['sessionid']
auth_creds.update(CSRFTOKEN=csrftoken, SESSIONID=sessionid)
return client, auth_creds
def stack_build_header(auth_creds):
header = {'csrftoken': auth_creds['CSRFTOKEN'],
'X-CSRFToken': auth_creds['CSRFTOKEN'],
'sessionid': auth_creds['SESSIONID'],
'Content-type': 'application/json'}
return header
def stack_host_list(endpoint, header, client):
stack_r = client.post(endpoint, data=json.dumps({"cmd": "list host"}),
headers=header)
return json.loads(stack_r.json())
def stack_net_list(endpoint, header, client):
stack_r = client.post(endpoint, data=json.dumps({"cmd": "list host interface"}),
headers=header)
return json.loads(stack_r.json())
def format_meta(hostdata, intfdata, config):
use_hostnames = config['use_hostnames']
meta = dict(all=dict(hosts=list()),
frontends=dict(hosts=list()),
backends=dict(hosts=list()),
_meta=dict(hostvars=dict()))
# Iterate through list of dicts of hosts and remove
# environment key as it causes conflicts
for host in hostdata:
del host['environment']
meta['_meta']['hostvars'][host['host']] = host
meta['_meta']['hostvars'][host['host']]['interfaces'] = list()
# @bbyhuy to improve readability in next iteration
for intf in intfdata:
if intf['host'] in meta['_meta']['hostvars']:
meta['_meta']['hostvars'][intf['host']]['interfaces'].append(intf)
if intf['default'] is True:
meta['_meta']['hostvars'][intf['host']]['ansible_host'] = intf['ip']
if not use_hostnames:
meta['all']['hosts'].append(intf['ip'])
if meta['_meta']['hostvars'][intf['host']]['appliance'] != 'frontend':
meta['backends']['hosts'].append(intf['ip'])
else:
meta['frontends']['hosts'].append(intf['ip'])
else:
meta['all']['hosts'].append(intf['host'])
if meta['_meta']['hostvars'][intf['host']]['appliance'] != 'frontend':
meta['backends']['hosts'].append(intf['host'])
else:
meta['frontends']['hosts'].append(intf['host'])
return meta
def parse_args():
parser = argparse.ArgumentParser(description='Stacki Inventory Module')
group = parser.add_mutually_exclusive_group(required=True)
group.add_argument('--list', action='store_true',
help='List active hosts')
group.add_argument('--host', help='List details about the specific host')
return parser.parse_args()
def main():
args = parse_args()
if StrictVersion(requests.__version__) < StrictVersion("2.4.3"):
sys.exit('requests>=2.4.3 is required for this inventory script')
try:
config_files = CONFIG_FILES
config_files.append(os.path.dirname(os.path.realpath(__file__)) + '/stacki.yml')
config = None
for cfg_file in config_files:
if os.path.isfile(cfg_file):
stream = open(cfg_file, 'r')
config = yaml.safe_load(stream)
break
if not config:
sys.stderr.write("No config file found at {0}\n".format(config_files))
sys.exit(1)
client, auth_creds = stack_auth(config['stacki']['auth'])
header = stack_build_header(auth_creds)
host_list = stack_host_list(config['stacki']['auth']['stacki_endpoint'], header, client)
intf_list = stack_net_list(config['stacki']['auth']['stacki_endpoint'], header, client)
final_meta = format_meta(host_list, intf_list, config)
print(json.dumps(final_meta, indent=4))
except Exception as e:
sys.stderr.write('%s\n' % e.message)
sys.exit(1)
sys.exit(0)
if __name__ == '__main__':
main()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.