repo_name stringlengths 6 100 | path stringlengths 4 294 | copies stringlengths 1 5 | size stringlengths 4 6 | content stringlengths 606 896k | license stringclasses 15
values |
|---|---|---|---|---|---|
makaaso/aws-lambda-tools | autoscaling-adjust-size/docutils/transforms/writer_aux.py | 116 | 2609 | # $Id: writer_aux.py 7320 2012-01-19 22:33:02Z milde $
# Author: Lea Wiemann <LeWiemann@gmail.com>
# Copyright: This module has been placed in the public domain.
"""
Auxiliary transforms mainly to be used by Writer components.
This module is called "writer_aux" because otherwise there would be
conflicting imports like this one::
from docutils import writers
from docutils.transforms import writers
"""
__docformat__ = 'reStructuredText'
from docutils import nodes, utils, languages
from docutils.transforms import Transform
class Compound(Transform):
"""
Flatten all compound paragraphs. For example, transform ::
<compound>
<paragraph>
<literal_block>
<paragraph>
into ::
<paragraph>
<literal_block classes="continued">
<paragraph classes="continued">
"""
default_priority = 910
def apply(self):
for compound in self.document.traverse(nodes.compound):
first_child = True
for child in compound:
if first_child:
if not isinstance(child, nodes.Invisible):
first_child = False
else:
child['classes'].append('continued')
# Substitute children for compound.
compound.replace_self(compound[:])
class Admonitions(Transform):
"""
Transform specific admonitions, like this:
<note>
<paragraph>
Note contents ...
into generic admonitions, like this::
<admonition classes="note">
<title>
Note
<paragraph>
Note contents ...
The admonition title is localized.
"""
default_priority = 920
def apply(self):
language = languages.get_language(self.document.settings.language_code,
self.document.reporter)
for node in self.document.traverse(nodes.Admonition):
node_name = node.__class__.__name__
# Set class, so that we know what node this admonition came from.
node['classes'].append(node_name)
if not isinstance(node, nodes.admonition):
# Specific admonition. Transform into a generic admonition.
admonition = nodes.admonition(node.rawsource, *node.children,
**node.attributes)
title = nodes.title('', language.labels[node_name])
admonition.insert(0, title)
node.replace_self(admonition)
| mit |
Justin-Yuan/Image2Music-Generator | library/jython2.5.3/Lib/distutils/dir_util.py | 7 | 8084 | """distutils.dir_util
Utility functions for manipulating directories and directory trees."""
# This module should be kept compatible with Python 2.1.
__revision__ = "$Id$"
import os, sys
from types import *
from distutils.errors import DistutilsFileError, DistutilsInternalError
from distutils import log
# cache for by mkpath() -- in addition to cheapening redundant calls,
# eliminates redundant "creating /foo/bar/baz" messages in dry-run mode
_path_created = {}
# I don't use os.makedirs because a) it's new to Python 1.5.2, and
# b) it blows up if the directory already exists (I want to silently
# succeed in that case).
def mkpath (name, mode=0777, verbose=0, dry_run=0):
"""Create a directory and any missing ancestor directories. If the
directory already exists (or if 'name' is the empty string, which
means the current directory, which of course exists), then do
nothing. Raise DistutilsFileError if unable to create some
directory along the way (eg. some sub-path exists, but is a file
rather than a directory). If 'verbose' is true, print a one-line
summary of each mkdir to stdout. Return the list of directories
actually created."""
global _path_created
# Detect a common bug -- name is None
if not isinstance(name, StringTypes):
raise DistutilsInternalError, \
"mkpath: 'name' must be a string (got %r)" % (name,)
# XXX what's the better way to handle verbosity? print as we create
# each directory in the path (the current behaviour), or only announce
# the creation of the whole path? (quite easy to do the latter since
# we're not using a recursive algorithm)
name = os.path.normpath(name)
created_dirs = []
if os.path.isdir(name) or name == '':
return created_dirs
if _path_created.get(os.path.abspath(name)):
return created_dirs
(head, tail) = os.path.split(name)
tails = [tail] # stack of lone dirs to create
while head and tail and not os.path.isdir(head):
#print "splitting '%s': " % head,
(head, tail) = os.path.split(head)
#print "to ('%s','%s')" % (head, tail)
tails.insert(0, tail) # push next higher dir onto stack
#print "stack of tails:", tails
# now 'head' contains the deepest directory that already exists
# (that is, the child of 'head' in 'name' is the highest directory
# that does *not* exist)
for d in tails:
#print "head = %s, d = %s: " % (head, d),
head = os.path.join(head, d)
abs_head = os.path.abspath(head)
if _path_created.get(abs_head):
continue
log.info("creating %s", head)
if not dry_run:
try:
os.mkdir(head)
created_dirs.append(head)
except OSError, exc:
raise DistutilsFileError, \
"could not create '%s': %s" % (head, exc[-1])
_path_created[abs_head] = 1
return created_dirs
# mkpath ()
def create_tree (base_dir, files, mode=0777, verbose=0, dry_run=0):
"""Create all the empty directories under 'base_dir' needed to
put 'files' there. 'base_dir' is just the a name of a directory
which doesn't necessarily exist yet; 'files' is a list of filenames
to be interpreted relative to 'base_dir'. 'base_dir' + the
directory portion of every file in 'files' will be created if it
doesn't already exist. 'mode', 'verbose' and 'dry_run' flags are as
for 'mkpath()'."""
# First get the list of directories to create
need_dir = {}
for file in files:
need_dir[os.path.join(base_dir, os.path.dirname(file))] = 1
need_dirs = need_dir.keys()
need_dirs.sort()
# Now create them
for dir in need_dirs:
mkpath(dir, mode, dry_run=dry_run)
# create_tree ()
def copy_tree (src, dst,
preserve_mode=1,
preserve_times=1,
preserve_symlinks=0,
update=0,
verbose=0,
dry_run=0):
"""Copy an entire directory tree 'src' to a new location 'dst'. Both
'src' and 'dst' must be directory names. If 'src' is not a
directory, raise DistutilsFileError. If 'dst' does not exist, it is
created with 'mkpath()'. The end result of the copy is that every
file in 'src' is copied to 'dst', and directories under 'src' are
recursively copied to 'dst'. Return the list of files that were
copied or might have been copied, using their output name. The
return value is unaffected by 'update' or 'dry_run': it is simply
the list of all files under 'src', with the names changed to be
under 'dst'.
'preserve_mode' and 'preserve_times' are the same as for
'copy_file'; note that they only apply to regular files, not to
directories. If 'preserve_symlinks' is true, symlinks will be
copied as symlinks (on platforms that support them!); otherwise
(the default), the destination of the symlink will be copied.
'update' and 'verbose' are the same as for 'copy_file'."""
from distutils.file_util import copy_file
if not dry_run and not os.path.isdir(src):
raise DistutilsFileError, \
"cannot copy tree '%s': not a directory" % src
try:
names = os.listdir(src)
except os.error, (errno, errstr):
if dry_run:
names = []
else:
raise DistutilsFileError, \
"error listing files in '%s': %s" % (src, errstr)
if not dry_run:
mkpath(dst)
outputs = []
for n in names:
src_name = os.path.join(src, n)
dst_name = os.path.join(dst, n)
if preserve_symlinks and os.path.islink(src_name):
link_dest = os.readlink(src_name)
log.info("linking %s -> %s", dst_name, link_dest)
if not dry_run:
os.symlink(link_dest, dst_name)
outputs.append(dst_name)
elif os.path.isdir(src_name):
outputs.extend(
copy_tree(src_name, dst_name, preserve_mode,
preserve_times, preserve_symlinks, update,
dry_run=dry_run))
else:
copy_file(src_name, dst_name, preserve_mode,
preserve_times, update, dry_run=dry_run)
outputs.append(dst_name)
return outputs
# copy_tree ()
# Helper for remove_tree()
def _build_cmdtuple(path, cmdtuples):
for f in os.listdir(path):
real_f = os.path.join(path,f)
if os.path.isdir(real_f) and not os.path.islink(real_f):
_build_cmdtuple(real_f, cmdtuples)
else:
cmdtuples.append((os.remove, real_f))
cmdtuples.append((os.rmdir, path))
def remove_tree (directory, verbose=0, dry_run=0):
"""Recursively remove an entire directory tree. Any errors are ignored
(apart from being reported to stdout if 'verbose' is true).
"""
from distutils.util import grok_environment_error
global _path_created
log.info("removing '%s' (and everything under it)", directory)
if dry_run:
return
cmdtuples = []
_build_cmdtuple(directory, cmdtuples)
for cmd in cmdtuples:
try:
apply(cmd[0], (cmd[1],))
# remove dir from cache if it's already there
abspath = os.path.abspath(cmd[1])
if _path_created.has_key(abspath):
del _path_created[abspath]
except (IOError, OSError), exc:
log.warn(grok_environment_error(
exc, "error removing %s: " % directory))
def ensure_relative (path):
"""Take the full path 'path', and make it a relative path so
it can be the second argument to os.path.join().
"""
drive, path = os.path.splitdrive(path)
if sys.platform == 'mac':
return os.sep + path
else:
if path[0:1] == os.sep:
path = drive + path[1:]
return path
| gpl-2.0 |
4talesa/rethinkdb | external/v8_3.30.33.16/build/gyp/test/additional-targets/gyptest-additional.py | 139 | 1530 | #!/usr/bin/env python
# Copyright (c) 2012 Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""
Verifies simple actions when using an explicit build target of 'all'.
"""
import TestGyp
test = TestGyp.TestGyp()
test.run_gyp('all.gyp', chdir='src')
test.relocate('src', 'relocate/src')
# Build all.
test.build('all.gyp', chdir='relocate/src')
if test.format=='xcode':
chdir = 'relocate/src/dir1'
else:
chdir = 'relocate/src'
# Output is as expected.
file_content = 'Hello from emit.py\n'
test.built_file_must_match('out2.txt', file_content, chdir=chdir)
test.built_file_must_not_exist('out.txt', chdir='relocate/src')
test.built_file_must_not_exist('foolib1',
type=test.SHARED_LIB,
chdir=chdir)
# TODO(mmoss) Make consistent with msvs, with 'dir1' before 'out/Default'?
if test.format in ('make', 'ninja', 'android', 'cmake'):
chdir='relocate/src'
else:
chdir='relocate/src/dir1'
# Build the action explicitly.
test.build('actions.gyp', 'action1_target', chdir=chdir)
# Check that things got run.
file_content = 'Hello from emit.py\n'
test.built_file_must_exist('out.txt', chdir=chdir)
# Build the shared library explicitly.
test.build('actions.gyp', 'foolib1', chdir=chdir)
test.built_file_must_exist('foolib1',
type=test.SHARED_LIB,
chdir=chdir,
subdir='dir1')
test.pass_test()
| agpl-3.0 |
broxtronix/distributed | distributed/diagnostics/progress.py | 1 | 9766 | from __future__ import print_function, division, absolute_import
from collections import defaultdict
import logging
import sys
import threading
import time
from timeit import default_timer
import dask
from toolz import valmap, groupby, concat
from tornado.ioloop import PeriodicCallback, IOLoop
from tornado import gen
from .plugin import SchedulerPlugin
from ..utils import sync, key_split, tokey
logger = logging.getLogger(__name__)
def dependent_keys(keys, who_has, processing, stacks, dependencies, exceptions,
complete=False):
""" All keys that need to compute for these keys to finish """
out = set()
errors = set()
stack = list(keys)
while stack:
key = stack.pop()
if key in out:
continue
if not complete and (who_has.get(key) or
key in processing or
key in stacks):
continue
if key in exceptions:
errors.add(key)
if not complete:
continue
out.add(key)
stack.extend(dependencies.get(key, []))
return out, errors
class Progress(SchedulerPlugin):
""" Tracks progress of a set of keys or futures
On creation we provide a set of keys or futures that interest us as well as
a scheduler. We traverse through the scheduler's dependencies to find all
relevant keys on which our keys depend. We then plug into the scheduler to
learn when our keys become available in memory at which point we record
their completion.
State
-----
keys: set
Set of keys that are not yet computed
all_keys: set
Set of all keys that we track
This class performs no visualization. However it is used by other classes,
notably TextProgressBar and ProgressWidget, which do perform visualization.
"""
def __init__(self, keys, scheduler, minimum=0, dt=0.1, complete=False):
self.keys = {k.key if hasattr(k, 'key') else k for k in keys}
self.keys = {tokey(k) for k in self.keys}
self.scheduler = scheduler
self.complete = complete
self._minimum = minimum
self._dt = dt
self.last_duration = 0
self._start_time = default_timer()
self._running = False
self.status = None
@gen.coroutine
def setup(self):
keys = self.keys
while not keys.issubset(self.scheduler.task_state):
yield gen.sleep(0.05)
self.keys = None
self.scheduler.add_plugin(self) # subtle race condition here
self.all_keys, errors = dependent_keys(keys, self.scheduler.who_has,
self.scheduler.processing, self.scheduler.stacks,
self.scheduler.dependencies, self.scheduler.exceptions,
complete=self.complete)
if not self.complete:
self.keys = self.all_keys.copy()
else:
self.keys, _ = dependent_keys(keys, self.scheduler.who_has,
self.scheduler.processing, self.scheduler.stacks,
self.scheduler.dependencies, self.scheduler.exceptions,
complete=False)
self.all_keys.update(keys)
self.keys |= errors & self.all_keys
if not self.keys:
self.stop(exception=None, key=None)
logger.debug("Set up Progress keys")
for k in errors:
self.transition(k, None, 'erred', exception=True)
def transition(self, key, start, finish, *args, **kwargs):
if key in self.keys and start == 'processing' and finish == 'memory':
logger.debug("Progress sees key %s", key)
self.keys.remove(key)
if not self.keys:
self.stop()
if key in self.all_keys and finish == 'erred':
logger.debug("Progress sees task erred")
self.stop(exception=kwargs['exception'], key=key)
if key in self.keys and finish == 'forgotten':
logger.debug("A task was cancelled (%s), stopping progress", key)
self.stop(exception=True)
def restart(self, scheduler):
self.stop()
def stop(self, exception=None, key=None):
if self in self.scheduler.plugins:
self.scheduler.plugins.remove(self)
if exception:
self.status = 'error'
else:
self.status = 'finished'
logger.debug("Remove Progress plugin")
class MultiProgress(Progress):
""" Progress variant that keeps track of different groups of keys
See Progress for most details. This only adds a function ``func=``
that splits keys. This defaults to ``key_split`` which aligns with naming
conventions chosen in the dask project (tuples, hyphens, etc..)
State
-----
keys: dict
Maps group name to set of not-yet-complete keys for that group
all_keys: dict
Maps group name to set of all keys for that group
Examples
--------
>>> split = lambda s: s.split('-')[0]
>>> p = MultiProgress(['y-2'], func=split) # doctest: +SKIP
>>> p.keys # doctest: +SKIP
{'x': {'x-1', 'x-2', 'x-3'},
'y': {'y-1', 'y-2'}}
"""
def __init__(self, keys, scheduler=None, func=key_split, minimum=0, dt=0.1,
complete=False):
self.func = func
Progress.__init__(self, keys, scheduler, minimum=minimum, dt=dt,
complete=complete)
@gen.coroutine
def setup(self):
keys = self.keys
while not keys.issubset(self.scheduler.tasks):
yield gen.sleep(0.05)
self.keys = None
self.scheduler.add_plugin(self) # subtle race condition here
self.all_keys, errors = dependent_keys(keys, self.scheduler.who_has,
self.scheduler.processing, self.scheduler.stacks,
self.scheduler.dependencies, self.scheduler.exceptions,
complete=self.complete)
if not self.complete:
self.keys = self.all_keys.copy()
else:
self.keys, _ = dependent_keys(keys, self.scheduler.who_has,
self.scheduler.processing, self.scheduler.stacks,
self.scheduler.dependencies, self.scheduler.exceptions,
complete=False)
self.all_keys.update(keys)
self.keys |= errors & self.all_keys
if not self.keys:
self.stop(exception=None, key=None)
# Group keys by func name
self.keys = valmap(set, groupby(self.func, self.keys))
self.all_keys = valmap(set, groupby(self.func, self.all_keys))
for k in self.all_keys:
if k not in self.keys:
self.keys[k] = set()
for k in errors:
self.transition(k, None, 'erred', exception=True)
logger.debug("Set up Progress keys")
def transition(self, key, start, finish, *args, **kwargs):
if start == 'processing' and finish == 'memory':
s = self.keys.get(self.func(key), None)
if s and key in s:
s.remove(key)
if not self.keys or not any(self.keys.values()):
self.stop()
if finish == 'erred':
logger.debug("Progress sees task erred")
k = self.func(key)
if (k in self.all_keys and key in self.all_keys[k]):
self.stop(exception=kwargs.get('exception'), key=key)
if finish == 'forgotten':
k = self.func(key)
if k in self.all_keys and key in self.all_keys[k]:
logger.debug("A task was cancelled (%s), stopping progress", key)
self.stop(exception=True)
def format_time(t):
"""Format seconds into a human readable form.
>>> format_time(10.4)
'10.4s'
>>> format_time(1000.4)
'16min 40.4s'
>>> format_time(100000.4)
'27hr 46min 40.4s'
"""
m, s = divmod(t, 60)
h, m = divmod(m, 60)
if h:
return '{0:2.0f}hr {1:2.0f}min {2:4.1f}s'.format(h, m, s)
elif m:
return '{0:2.0f}min {1:4.1f}s'.format(m, s)
else:
return '{0:4.1f}s'.format(s)
class AllProgress(SchedulerPlugin):
""" Keep track of all keys, grouped by key_split """
def __init__(self, scheduler):
self.all = defaultdict(set)
self.nbytes = defaultdict(lambda: 0)
self.state = defaultdict(lambda: defaultdict(set))
self.scheduler = scheduler
for key, state in self.scheduler.task_state.items():
k = key_split(key)
self.all[k].add(key)
self.state[state][k].add(key)
if key in self.scheduler.nbytes:
self.nbytes[k] += self.scheduler.nbytes[key]
scheduler.add_plugin(self)
def transition(self, key, start, finish, *args, **kwargs):
k = key_split(key)
self.all[k].add(key)
try:
self.state[start][k].remove(key)
except KeyError: # TODO: remove me once we have a new or clean state
pass
if finish != 'forgotten':
self.state[finish][k].add(key)
else:
self.all[k].remove(key)
if not self.all[k]:
del self.all[k]
try:
del self.nbytes[k]
except KeyError:
pass
for v in self.state.values():
try:
del v[k]
except KeyError:
pass
if start == 'memory':
self.nbytes[k] -= self.scheduler.nbytes[key]
if finish == 'memory':
self.nbytes[k] += self.scheduler.nbytes[key]
def restart(self, scheduler):
self.all.clear()
self.state.clear()
| bsd-3-clause |
woodshop/chainer | tests/functions_tests/test_sigmoid_cross_entropy.py | 7 | 2636 | import math
import unittest
import numpy
import six
import chainer
from chainer import cuda
from chainer import functions
from chainer import gradient_check
from chainer import testing
from chainer.testing import attr
from chainer.testing import condition
if cuda.available:
cuda.init()
class TestSigmoidCrossEntropy(unittest.TestCase):
def setUp(self):
self.x = numpy.random.uniform(-1, 1, (4, 3)).astype(numpy.float32)
self.t = numpy.random.randint(0, 2, (4, 3)).astype(numpy.int32)
def check_forward(self, x_data, t_data, use_cudnn=True):
x_val = chainer.Variable(x_data)
t_val = chainer.Variable(t_data)
loss = functions.sigmoid_cross_entropy(x_val, t_val, use_cudnn)
self.assertEqual(loss.data.shape, ())
self.assertEqual(loss.data.dtype, numpy.float32)
loss_value = float(cuda.to_cpu(loss.data))
# Compute expected value
loss_expect = 0
for i in six.moves.range(self.x.shape[0]):
for j in six.moves.range(self.x.shape[1]):
xd, td = self.x[i, j], self.t[i, j]
loss_expect -= xd * (td - (xd >= 0)) \
- math.log(1 + math.exp(-numpy.abs(xd)))
loss_expect /= self.t.shape[0]
self.assertAlmostEqual(loss_expect, loss_value, places=5)
@condition.retry(3)
def test_forward_cpu(self):
self.check_forward(self.x, self.t)
@attr.cudnn
@condition.retry(3)
def test_forward_gpu(self):
self.check_forward(cuda.to_gpu(self.x), cuda.to_gpu(self.t))
@attr.gpu
@condition.retry(3)
def test_forward_gpu_no_cudnn(self):
self.check_forward(cuda.to_gpu(self.x), cuda.to_gpu(self.t), False)
def check_backward(self, x_data, t_data, use_cudnn=True):
x = chainer.Variable(x_data)
t = chainer.Variable(t_data)
loss = functions.sigmoid_cross_entropy(x, t, use_cudnn)
loss.backward()
self.assertEqual(None, t.grad)
func = loss.creator
f = lambda: func.forward((x.data, t.data))
gx, = gradient_check.numerical_grad(f, (x.data,), (1,), eps=0.01)
gradient_check.assert_allclose(gx, x.grad)
@condition.retry(3)
def test_backward_cpu(self):
self.check_backward(self.x, self.t)
@attr.cudnn
@condition.retry(3)
def test_backward_gpu(self):
self.check_backward(cuda.to_gpu(self.x), cuda.to_gpu(self.t))
@attr.gpu
@condition.retry(3)
def test_backward_gpu_no_cudnn(self):
self.check_backward(cuda.to_gpu(self.x), cuda.to_gpu(self.t), False)
testing.run_module(__name__, __file__)
| mit |
ar7z1/ansible | lib/ansible/module_utils/facts/virtual/netbsd.py | 197 | 1833 | # This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import os
from ansible.module_utils.facts.virtual.base import Virtual, VirtualCollector
from ansible.module_utils.facts.virtual.sysctl import VirtualSysctlDetectionMixin
class NetBSDVirtual(Virtual, VirtualSysctlDetectionMixin):
platform = 'NetBSD'
def get_virtual_facts(self):
virtual_facts = {}
# Set empty values as default
virtual_facts['virtualization_type'] = ''
virtual_facts['virtualization_role'] = ''
virtual_product_facts = self.detect_virt_product('machdep.dmi.system-product')
virtual_facts.update(virtual_product_facts)
if virtual_facts['virtualization_type'] == '':
virtual_vendor_facts = self.detect_virt_vendor('machdep.dmi.system-vendor')
virtual_facts.update(virtual_vendor_facts)
if os.path.exists('/dev/xencons'):
virtual_facts['virtualization_type'] = 'xen'
virtual_facts['virtualization_role'] = 'guest'
return virtual_facts
class NetBSDVirtualCollector(VirtualCollector):
_fact_class = NetBSDVirtual
_platform = 'NetBSD'
| gpl-3.0 |
chrisidefix/devide | snippets/rotateCameraIncreaseIsovalue.py | 7 | 1655 | # this snippet will rotate the camera in the slice3dVWR that you have
# selected whilst slowly increasing the isovalue of the marchingCubes that
# you have selected and dump every frame as a PNG to the temporary directory
# this is ideal for making movies of propagating surfaces in distance fields
# 1. right click on a slice3dVWR in the graphEditor
# 2. select "Mark Module" from the drop-down menu
# 3. accept "slice3dVWR" as suggestion for the mark index name
# 4. do the same for your marchingCubes (select 'marchingCubes' as index name)
# 5. execute this snippet
import os
import tempfile
import vtk
import wx
# get the slice3dVWR marked by the user
sv = devideApp.ModuleManager.getMarkedModule('slice3dVWR')
mc = devideApp.ModuleManager.getMarkedModule('marchingCubes')
if sv and mc:
# bring the window to the front
sv.view()
# make sure it actually happens
wx.Yield()
w2i = vtk.vtkWindowToImageFilter()
w2i.SetInput(sv._threedRenderer.GetRenderWindow())
pngWriter = vtk.vtkPNGWriter()
pngWriter.SetInput(w2i.GetOutput())
tempdir = tempfile.gettempdir()
fprefix = os.path.join(tempdir, 'devideFrame')
camera = sv._threedRenderer.GetActiveCamera()
for i in range(160):
print i
mc._contourFilter.SetValue(0,i / 2.0)
camera.Azimuth(5)
sv.render3D()
# make sure w2i knows it's a new image
w2i.Modified()
pngWriter.SetFileName('%s%03d.png' % (fprefix, i))
pngWriter.Write()
print "The frames have been written as %s*.png." % (fprefix,)
else:
print "You have to mark a slice3dVWR module and a marchingCubes module!"
| bsd-3-clause |
codrut3/tensorflow | tensorflow/python/ops/distributions/bijector_impl.py | 19 | 29676 | # Copyright 2016 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Bijector base."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import abc
import collections
import contextlib
import re
import numpy as np
import six
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import ops
from tensorflow.python.framework import tensor_shape
from tensorflow.python.framework import tensor_util
from tensorflow.python.ops import array_ops
from tensorflow.python.ops import math_ops
__all__ = [
"Bijector",
]
class _Mapping(collections.namedtuple(
"_Mapping", ["x", "y", "ildj", "kwargs"])):
"""Helper class to make it easier to manage caching in `Bijector`."""
def __new__(cls, x=None, y=None, ildj=None, kwargs=None):
"""Custom __new__ so namedtuple items have defaults.
Args:
x: `Tensor`. Forward.
y: `Tensor`. Inverse.
ildj: `Tensor`. Inverse log det Jacobian.
kwargs: Python dictionary. Extra args supplied to
forward/inverse/etc functions.
Returns:
mapping: New instance of _Mapping.
"""
return super(_Mapping, cls).__new__(cls, x, y, ildj, kwargs)
@property
def x_key(self):
"""Returns key used for caching Y=g(X)."""
return (self.x,) + self._deep_tuple(tuple(sorted(self.kwargs.items())))
@property
def y_key(self):
"""Returns key used for caching X=g^{-1}(Y)."""
return (self.y,) + self._deep_tuple(tuple(sorted(self.kwargs.items())))
def merge(self, x=None, y=None, ildj=None, kwargs=None, mapping=None):
"""Returns new _Mapping with args merged with self.
Args:
x: `Tensor`. Forward.
y: `Tensor`. Inverse.
ildj: `Tensor`. Inverse log det Jacobian.
kwargs: Python dictionary. Extra args supplied to
forward/inverse/etc functions.
mapping: Instance of _Mapping to merge. Can only be specified if no other
arg is specified.
Returns:
mapping: New instance of `_Mapping` which has inputs merged with self.
Raises:
ValueError: if mapping and any other arg is not `None`.
"""
if mapping is None:
mapping = _Mapping(x=x, y=y, ildj=ildj, kwargs=kwargs)
elif not all(arg is None for arg in [x, y, ildj, kwargs]):
raise ValueError("Cannot specify mapping and individual args.")
return _Mapping(
x=self._merge(self.x, mapping.x),
y=self._merge(self.y, mapping.y),
ildj=self._merge(self.ildj, mapping.ildj),
kwargs=self._merge(self.kwargs, mapping.kwargs))
def _merge(self, old, new):
"""Helper to merge which handles merging one value."""
if old is None:
return new
elif new is not None and old != new:
raise ValueError("Incompatible values: %s != %s" % (old, new))
return old
def _deep_tuple(self, x):
"""Converts lists of lists to tuples of tuples."""
return (tuple(map(self._deep_tuple, x))
if isinstance(x, (list, tuple)) else x)
@six.add_metaclass(abc.ABCMeta)
class Bijector(object):
"""Interface for transformations of a `Distribution` sample.
Bijectors can be used to represent any differentiable and injective
(one to one) function defined on an open subset of `R^n`. Some non-injective
transformations are also supported (see "Non Injective Transforms" below).
#### Mathematical Details
A `Bijector` implements a
[diffeomorphism](https://en.wikipedia.org/wiki/Diffeomorphism), i.e., a
bijective, differentiable function. A `Bijector` is used by
`TransformedDistribution` but can be generally used for transforming a
`Distribution` generated `Tensor`. A `Bijector` is characterized by three
operations:
1. Forward Evaluation
Useful for turning one random outcome into another random outcome from a
different distribution.
2. Inverse Evaluation
Useful for "reversing" a transformation to compute one probability in
terms of another.
3. (log o det o Jacobian o inverse)(x)
"The log of the determinant of the matrix of all first-order partial
derivatives of the inverse function."
Useful for inverting a transformation to compute one probability in terms
of another. Geometrically, the det(Jacobian) is the volume of the
transformation and is used to scale the probability.
By convention, transformations of random variables are named in terms of the
forward transformation. The forward transformation creates samples, the
inverse is useful for computing probabilities.
#### Example Uses
- Basic properties:
```python
x = ... # A tensor.
# Evaluate forward transformation.
fwd_x = my_bijector.forward(x)
x == my_bijector.inverse(fwd_x)
x != my_bijector.forward(fwd_x) # Not equal because x != g(g(x)).
```
- Computing a log-likelihood:
```python
def transformed_log_prob(bijector, log_prob, x):
return (bijector.inverse_log_det_jacobian(x) +
log_prob(bijector.inverse(x)))
```
- Transforming a random outcome:
```python
def transformed_sample(bijector, x):
return bijector.forward(x)
```
#### Example Bijectors
- "Exponential"
```none
Y = g(X) = exp(X)
X ~ Normal(0, 1) # Univariate.
```
Implies:
```none
g^{-1}(Y) = log(Y)
|Jacobian(g^{-1})(y)| = 1 / y
Y ~ LogNormal(0, 1), i.e.,
prob(Y=y) = |Jacobian(g^{-1})(y)| * prob(X=g^{-1}(y))
= (1 / y) Normal(log(y); 0, 1)
```
Here is an example of how one might implement the `Exp` bijector:
```python
class Exp(Bijector):
def __init__(self, event_ndims=0, validate_args=False, name="exp"):
super(Exp, self).__init__(
event_ndims=event_ndims, validate_args=validate_args, name=name)
def _forward(self, x):
return math_ops.exp(x)
def _inverse(self, y):
return math_ops.log(y)
def _inverse_log_det_jacobian(self, y):
return -self._forward_log_det_jacobian(self._inverse(y))
def _forward_log_det_jacobian(self, x):
if self.event_ndims is None:
raise ValueError("Jacobian requires known event_ndims.")
event_dims = array_ops.shape(x)[-self.event_ndims:]
return math_ops.reduce_sum(x, axis=event_dims)
```
- "Affine"
```none
Y = g(X) = sqrtSigma * X + mu
X ~ MultivariateNormal(0, I_d)
```
Implies:
```none
g^{-1}(Y) = inv(sqrtSigma) * (Y - mu)
|Jacobian(g^{-1})(y)| = det(inv(sqrtSigma))
Y ~ MultivariateNormal(mu, sqrtSigma) , i.e.,
prob(Y=y) = |Jacobian(g^{-1})(y)| * prob(X=g^{-1}(y))
= det(sqrtSigma)^(-d) *
MultivariateNormal(inv(sqrtSigma) * (y - mu); 0, I_d)
```
#### Jacobian
The Jacobian is a reduction over event dims. To see this, consider the `Exp`
`Bijector` applied to a `Tensor` which has sample, batch, and event (S, B, E)
shape semantics. Suppose the `Tensor`'s partitioned-shape is `(S=[4], B=[2],
E=[3, 3])`. The shape of the `Tensor` returned by `forward` and `inverse` is
unchanged, i.e., `[4, 2, 3, 3]`. However the shape returned by
`inverse_log_det_jacobian` is `[4, 2]` because the Jacobian is a reduction
over the event dimensions.
It is sometimes useful to implement the inverse Jacobian as the negative
forward Jacobian. For example,
```python
def _inverse_log_det_jacobian(self, y):
return -self._forward_log_det_jac(self._inverse(y)) # Note negation.
```
The correctness of this approach can be seen from the following claim.
- Claim:
Assume `Y = g(X)` is a bijection whose derivative exists and is nonzero
for its domain, i.e., `dY/dX = d/dX g(X) != 0`. Then:
```none
(log o det o jacobian o g^{-1})(Y) = -(log o det o jacobian o g)(X)
```
- Proof:
From the bijective, nonzero differentiability of `g`, the
[inverse function theorem](
https://en.wikipedia.org/wiki/Inverse_function_theorem)
implies `g^{-1}` is differentiable in the image of `g`.
Applying the chain rule to `y = g(x) = g(g^{-1}(y))` yields
`I = g'(g^{-1}(y))*g^{-1}'(y)`.
The same theorem also implies `g^{-1}'` is non-singular therefore:
`inv[ g'(g^{-1}(y)) ] = g^{-1}'(y)`.
The claim follows from [properties of determinant](
https://en.wikipedia.org/wiki/Determinant#Multiplicativity_and_matrix_groups).
Generally its preferable to directly implement the inverse Jacobian. This
should have superior numerical stability and will often share subgraphs with
the `_inverse` implementation.
#### Subclass Requirements
- Subclasses typically implement:
- `_forward`,
- `_inverse`,
- `_inverse_log_det_jacobian`,
- `_forward_log_det_jacobian` (optional).
The `_forward_log_det_jacobian` is called when the bijector is inverted via
the `Invert` bijector. If undefined, a slightly less efficiently
calculation, `-1 * _inverse_log_det_jacobian`, is used.
If the bijector changes the shape of the input, you must also implement:
- _forward_event_shape_tensor,
- _forward_event_shape (optional),
- _inverse_event_shape_tensor,
- _inverse_event_shape (optional).
By default the event-shape is assumed unchanged from input.
- If the `Bijector`'s use is limited to `TransformedDistribution` (or friends
like `QuantizedDistribution`) then depending on your use, you may not need
to implement all of `_forward` and `_inverse` functions.
Examples:
1. Sampling (e.g., `sample`) only requires `_forward`.
2. Probability functions (e.g., `prob`, `cdf`, `survival`) only require
`_inverse` (and related).
3. Only calling probability functions on the output of `sample` means
`_inverse` can be implemented as a cache lookup.
See "Example Uses" [above] which shows how these functions are used to
transform a distribution. (Note: `_forward` could theoretically be
implemented as a cache lookup but this would require controlling the
underlying sample generation mechanism.)
#### Non Injective Transforms
**WARNING** Handing of non-injective transforms is subject to change.
Non injective maps `g` are supported, provided their domain `D` can be
partitioned into `k` disjoint subsets, `Union{D1, ..., Dk}`, such that,
ignoring sets of measure zero, the restriction of `g` to each subset is a
differentiable bijection onto `g(D)`. In particular, this imples that for
`y in g(D)`, the set inverse, i.e. `g^{-1}(y) = {x in D : g(x) = y}`, always
contains exactly `k` distinct points.
The property, `_is_injective` is set to `False` to indicate that the bijector
is not injective, yet satisfies the above condition.
The usual bijector API is modified in the case `_is_injective is False` (see
method docstrings for specifics). Here we show by example the `AbsoluteValue`
bijector. In this case, the domain `D = (-inf, inf)`, can be partitioned
into `D1 = (-inf, 0)`, `D2 = {0}`, and `D3 = (0, inf)`. Let `gi` be the
restriction of `g` to `Di`, then both `g1` and `g3` are bijections onto
`(0, inf)`, with `g1^{-1}(y) = -y`, and `g3^{-1}(y) = y`. We will use
`g1` and `g3` to define bijector methods over `D1` and `D3`. `D2 = {0}` is
an oddball in that `g2` is one to one, and the derivative is not well defined.
Fortunately, when considering transformations of probability densities
(e.g. in `TransformedDistribution`), sets of measure zero have no effect in
theory, and only a small effect in 32 or 64 bit precision. For that reason,
we define `inverse(0)` and `inverse_log_det_jacobian(0)` both as `[0, 0]`,
which is convenient and results in a left-semicontinuous pdf.
```python
abs = tf.contrib.distributions.bijectors.AbsoluteValue()
abs.forward(-1.)
==> 1.
abs.forward(1.)
==> 1.
abs.inverse(1.)
==> (-1., 1.)
# The |dX/dY| is constant, == 1. So Log|dX/dY| == 0.
abs.inverse_log_det_jacobian(1.)
==> (0., 0.)
# Special case handling of 0.
abs.inverse(0.)
==> (0., 0.)
abs.inverse_log_det_jacobian(0.)
==> (0., 0.)
```
"""
@abc.abstractmethod
def __init__(self,
event_ndims=None,
graph_parents=None,
is_constant_jacobian=False,
validate_args=False,
dtype=None,
name=None):
"""Constructs Bijector.
A `Bijector` transforms random variables into new random variables.
Examples:
```python
# Create the Y = g(X) = X transform which operates on vector events.
identity = Identity(event_ndims=1)
# Create the Y = g(X) = exp(X) transform which operates on matrices.
exp = Exp(event_ndims=2)
```
See `Bijector` subclass docstring for more details and specific examples.
Args:
event_ndims: number of dimensions associated with event coordinates.
graph_parents: Python list of graph prerequisites of this `Bijector`.
is_constant_jacobian: Python `bool` indicating that the Jacobian is not a
function of the input.
validate_args: Python `bool`, default `False`. Whether to validate input
with asserts. If `validate_args` is `False`, and the inputs are invalid,
correct behavior is not guaranteed.
dtype: `tf.dtype` supported by this `Bijector`. `None` means dtype is not
enforced.
name: The name to give Ops created by the initializer.
Raises:
ValueError: If a member of `graph_parents` is not a `Tensor`.
"""
self._event_ndims = (
ops.convert_to_tensor(event_ndims, dtype=dtypes.int32)
if event_ndims is not None else None)
self._graph_parents = graph_parents or []
self._is_constant_jacobian = is_constant_jacobian
self._validate_args = validate_args
self._dtype = dtype
self._from_y = {}
self._from_x = {}
# Using abbreviation ildj for "inverse log det Jacobian."
# This variable is not `None` iff is_constant_jacobian is `True`.
self._constant_ildj = None
if name:
self._name = name
else:
# We want the default convention to be snake_case rather than CamelCase
# since `Chain` uses bijector.name as the kwargs dictionary key.
def camel_to_snake(name):
s1 = re.sub("(.)([A-Z][a-z]+)", r"\1_\2", name)
return re.sub("([a-z0-9])([A-Z])", r"\1_\2", s1).lower()
self._name = camel_to_snake(type(self).__name__.lstrip("_"))
for i, t in enumerate(self._graph_parents):
if t is None or not tensor_util.is_tensor(t):
raise ValueError("Graph parent item %d is not a Tensor; %s." % (i, t))
@property
def event_ndims(self):
"""Returns then number of event dimensions this bijector operates on."""
return self._event_ndims
@property
def graph_parents(self):
"""Returns this `Bijector`'s graph_parents as a Python list."""
return self._graph_parents
@property
def is_constant_jacobian(self):
"""Returns true iff the Jacobian is not a function of x.
Note: Jacobian is either constant for both forward and inverse or neither.
Returns:
is_constant_jacobian: Python `bool`.
"""
return self._is_constant_jacobian
@property
def _is_injective(self):
"""Returns true iff the forward map `g` is injective (one-to-one function).
**WARNING** This hidden property and its behavior are subject to change.
Note: Non-injective maps `g` are supported, provided their domain `D` can
be partitioned into `k` disjoint subsets, `Union{D1, ..., Dk}`, such that,
ignoring sets of measure zero, the restriction of `g` to each subset is a
differentiable bijection onto `g(D)`.
Returns:
is_injective: Python `bool`.
"""
return True
@property
def validate_args(self):
"""Returns True if Tensor arguments will be validated."""
return self._validate_args
@property
def dtype(self):
"""dtype of `Tensor`s transformable by this distribution."""
return self._dtype
@property
def name(self):
"""Returns the string name of this `Bijector`."""
return self._name
def _forward_event_shape_tensor(self, input_shape):
"""Subclass implementation for `forward_event_shape_tensor` function."""
# By default, we assume event_shape is unchanged.
return input_shape
def forward_event_shape_tensor(self,
input_shape,
name="forward_event_shape_tensor"):
"""Shape of a single sample from a single batch as an `int32` 1D `Tensor`.
Args:
input_shape: `Tensor`, `int32` vector indicating event-portion shape
passed into `forward` function.
name: name to give to the op
Returns:
forward_event_shape_tensor: `Tensor`, `int32` vector indicating
event-portion shape after applying `forward`.
"""
with self._name_scope(name, [input_shape]):
input_shape = ops.convert_to_tensor(input_shape, dtype=dtypes.int32,
name="input_shape")
return self._forward_event_shape_tensor(input_shape)
def _forward_event_shape(self, input_shape):
"""Subclass implementation for `forward_event_shape` public function."""
# By default, we assume event_shape is unchanged.
return input_shape
def forward_event_shape(self, input_shape):
"""Shape of a single sample from a single batch as a `TensorShape`.
Same meaning as `forward_event_shape_tensor`. May be only partially defined.
Args:
input_shape: `TensorShape` indicating event-portion shape passed into
`forward` function.
Returns:
forward_event_shape_tensor: `TensorShape` indicating event-portion shape
after applying `forward`. Possibly unknown.
"""
return self._forward_event_shape(tensor_shape.TensorShape(input_shape))
def _inverse_event_shape_tensor(self, output_shape):
"""Subclass implementation for `inverse_event_shape_tensor` function."""
# By default, we assume event_shape is unchanged.
return output_shape
def inverse_event_shape_tensor(self,
output_shape,
name="inverse_event_shape_tensor"):
"""Shape of a single sample from a single batch as an `int32` 1D `Tensor`.
Args:
output_shape: `Tensor`, `int32` vector indicating event-portion shape
passed into `inverse` function.
name: name to give to the op
Returns:
inverse_event_shape_tensor: `Tensor`, `int32` vector indicating
event-portion shape after applying `inverse`.
"""
with self._name_scope(name, [output_shape]):
output_shape = ops.convert_to_tensor(output_shape, dtype=dtypes.int32,
name="output_shape")
return self._inverse_event_shape_tensor(output_shape)
def _inverse_event_shape(self, output_shape):
"""Subclass implementation for `inverse_event_shape` public function."""
# By default, we assume event_shape is unchanged.
return tensor_shape.TensorShape(output_shape)
def inverse_event_shape(self, output_shape):
"""Shape of a single sample from a single batch as a `TensorShape`.
Same meaning as `inverse_event_shape_tensor`. May be only partially defined.
Args:
output_shape: `TensorShape` indicating event-portion shape passed into
`inverse` function.
Returns:
inverse_event_shape_tensor: `TensorShape` indicating event-portion shape
after applying `inverse`. Possibly unknown.
"""
return self._inverse_event_shape(output_shape)
def _forward(self, x):
"""Subclass implementation for `forward` public function."""
raise NotImplementedError("forward not implemented.")
def _call_forward(self, x, name, **kwargs):
with self._name_scope(name, [x]):
x = ops.convert_to_tensor(x, name="x")
self._maybe_assert_dtype(x)
if not self._is_injective: # No caching for non-injective
return self._forward(x, **kwargs)
mapping = self._lookup(x=x, kwargs=kwargs)
if mapping.y is not None:
return mapping.y
mapping = mapping.merge(y=self._forward(x, **kwargs))
self._cache(mapping)
return mapping.y
def forward(self, x, name="forward"):
"""Returns the forward `Bijector` evaluation, i.e., X = g(Y).
Args:
x: `Tensor`. The input to the "forward" evaluation.
name: The name to give this op.
Returns:
`Tensor`.
Raises:
TypeError: if `self.dtype` is specified and `x.dtype` is not
`self.dtype`.
NotImplementedError: if `_forward` is not implemented.
"""
return self._call_forward(x, name)
def _inverse(self, y):
"""Subclass implementation for `inverse` public function."""
raise NotImplementedError("inverse not implemented")
def _call_inverse(self, y, name, **kwargs):
with self._name_scope(name, [y]):
y = ops.convert_to_tensor(y, name="y")
self._maybe_assert_dtype(y)
if not self._is_injective: # No caching for non-injective
return self._inverse(y, **kwargs)
mapping = self._lookup(y=y, kwargs=kwargs)
if mapping.x is not None:
return mapping.x
mapping = mapping.merge(x=self._inverse(y, **kwargs))
self._cache(mapping)
return mapping.x
def inverse(self, y, name="inverse"):
"""Returns the inverse `Bijector` evaluation, i.e., X = g^{-1}(Y).
Args:
y: `Tensor`. The input to the "inverse" evaluation.
name: The name to give this op.
Returns:
`Tensor`, if this bijector is injective.
If not injective, returns the k-tuple containing the unique
`k` points `(x1, ..., xk)` such that `g(xi) = y`.
Raises:
TypeError: if `self.dtype` is specified and `y.dtype` is not
`self.dtype`.
NotImplementedError: if `_inverse` is not implemented.
"""
return self._call_inverse(y, name)
def _inverse_log_det_jacobian(self, y):
"""Subclass implementation of `inverse_log_det_jacobian` public function."""
raise NotImplementedError("inverse_log_det_jacobian not implemented.")
def _call_inverse_log_det_jacobian(self, y, name, **kwargs):
with self._name_scope(name, [y]):
if self._constant_ildj is not None:
return self._constant_ildj
y = ops.convert_to_tensor(y, name="y")
self._maybe_assert_dtype(y)
if not self._is_injective: # No caching for non-injective
return self._inverse_log_det_jacobian(y, **kwargs)
mapping = self._lookup(y=y, kwargs=kwargs)
if mapping.ildj is not None:
return mapping.ildj
try:
x = None # Not needed; leave cache as is.
ildj = self._inverse_log_det_jacobian(y, **kwargs)
except NotImplementedError as original_exception:
try:
x = mapping.x if mapping.x is not None else self._inverse(y, **kwargs)
ildj = -self._forward_log_det_jacobian(x, **kwargs)
except NotImplementedError:
raise original_exception
mapping = mapping.merge(x=x, ildj=ildj)
self._cache(mapping)
if self.is_constant_jacobian:
self._constant_ildj = mapping.ildj
return mapping.ildj
def inverse_log_det_jacobian(self, y, name="inverse_log_det_jacobian"):
"""Returns the (log o det o Jacobian o inverse)(y).
Mathematically, returns: `log(det(dX/dY))(Y)`. (Recall that: `X=g^{-1}(Y)`.)
Note that `forward_log_det_jacobian` is the negative of this function,
evaluated at `g^{-1}(y)`.
Args:
y: `Tensor`. The input to the "inverse" Jacobian evaluation.
name: The name to give this op.
Returns:
`Tensor`, if this bijector is injective.
If not injective, returns the tuple of local log det
Jacobians, `log(det(Dg_i^{-1}(y)))`, where `g_i` is the restriction
of `g` to the `ith` partition `Di`.
Raises:
TypeError: if `self.dtype` is specified and `y.dtype` is not
`self.dtype`.
NotImplementedError: if `_inverse_log_det_jacobian` is not implemented.
"""
return self._call_inverse_log_det_jacobian(y, name)
def _forward_log_det_jacobian(self, x):
"""Subclass implementation of `forward_log_det_jacobian`."""
raise NotImplementedError(
"forward_log_det_jacobian not implemented.")
def _call_forward_log_det_jacobian(self, x, name, **kwargs):
with self._name_scope(name, [x]):
if self._constant_ildj is not None:
# Need "-1. *" to avoid invalid-unary-operand-type linter warning.
return -1. * self._constant_ildj
x = ops.convert_to_tensor(x, name="x")
self._maybe_assert_dtype(x)
if not self._is_injective:
return self._forward_log_det_jacobian(x, **kwargs) # No caching.
mapping = self._lookup(x=x, kwargs=kwargs)
if mapping.ildj is not None:
return -mapping.ildj
try:
y = None # Not needed; leave cache as is.
ildj = -self._forward_log_det_jacobian(x, **kwargs)
except NotImplementedError as original_exception:
try:
y = mapping.y if mapping.y is not None else self._forward(x, **kwargs)
ildj = self._inverse_log_det_jacobian(y, **kwargs)
except NotImplementedError:
raise original_exception
mapping = mapping.merge(y=y, ildj=ildj)
self._cache(mapping)
if self.is_constant_jacobian:
self._constant_ildj = mapping.ildj
return -mapping.ildj
def forward_log_det_jacobian(self, x, name="forward_log_det_jacobian"):
"""Returns both the forward_log_det_jacobian.
Args:
x: `Tensor`. The input to the "forward" Jacobian evaluation.
name: The name to give this op.
Returns:
`Tensor`, if this bijector is injective.
If not injective this is not implemented.
Raises:
TypeError: if `self.dtype` is specified and `y.dtype` is not
`self.dtype`.
NotImplementedError: if neither `_forward_log_det_jacobian`
nor {`_inverse`, `_inverse_log_det_jacobian`} are implemented, or
this is a non-injective bijector.
"""
if not self._is_injective:
raise NotImplementedError(
"forward_log_det_jacobian cannot be implemented for non-injective "
"transforms.")
return self._call_forward_log_det_jacobian(x, name)
@contextlib.contextmanager
def _name_scope(self, name=None, values=None):
"""Helper function to standardize op scope."""
with ops.name_scope(self.name):
with ops.name_scope(
name, values=(values or []) + self.graph_parents) as scope:
yield scope
def _maybe_assert_dtype(self, x):
"""Helper to check dtype when self.dtype is known."""
if self.dtype is not None and self.dtype.base_dtype != x.dtype.base_dtype:
raise TypeError("Input had dtype %s but expected %s." %
(self.dtype, x.dtype))
def _cache(self, mapping):
"""Helper which stores mapping info in forward/inverse dicts."""
if self._constant_ildj is not None:
# Fold in ildj if known constant Jacobian.
mapping = mapping.merge(ildj=self._constant_ildj)
# Merging from lookup is an added check that we're not overwriting anything
# which is not None.
mapping = mapping.merge(mapping=self._lookup(
mapping.x, mapping.y, mapping.kwargs))
if mapping.x is None and mapping.y is None:
raise ValueError("Caching expects at least one of (x,y) to be known, "
"i.e., not None.")
self._from_x[mapping.x_key] = mapping
self._from_y[mapping.y_key] = mapping
def _lookup(self, x=None, y=None, kwargs=None):
"""Helper which retrieves mapping info from forward/inverse dicts."""
mapping = _Mapping(x=x, y=y, kwargs=kwargs)
# Since _cache requires both x,y to be set, we only need to do one cache
# lookup since the mapping is always in both or neither.
if mapping.x is not None:
return self._from_x.get(mapping.x_key, mapping)
if mapping.y is not None:
return self._from_y.get(mapping.y_key, mapping)
return mapping
def _event_dims_tensor(self, sample):
"""Return a 1D `int32` tensor: `range(rank(sample))[-event_ndims:]`."""
if self.event_ndims is None:
raise ValueError("Jacobian cannot be computed with unknown event_ndims")
static_event_ndims = tensor_util.constant_value(self.event_ndims)
static_rank = sample.get_shape().ndims
if static_event_ndims is not None and static_rank is not None:
return ops.convert_to_tensor(
static_rank + np.arange(-static_event_ndims, 0).astype(np.int32))
if static_event_ndims is not None:
event_range = np.arange(-static_event_ndims, 0).astype(np.int32)
else:
event_range = math_ops.range(-self.event_ndims, 0, dtype=dtypes.int32)
if static_rank is not None:
return event_range + static_rank
else:
return event_range + array_ops.rank(sample)
| apache-2.0 |
iojancode/botija | plug.livolo.py | 1 | 1887 | import time
import sys
import RPi.GPIO as GPIO
off = '1242424352424342424242424242425342524342'
b0 = '12424243524243424242424242424242424242424242'
b1 = '124242435242434242424242424242534242424242'
b2 = '1242424352424342424242424242425353424242'
b3 = '124242435242434242424242424242424253424242'
b4 = '124242435242434242424242424242524342424242'
b5 = '124242435242434242424242424242425342424242'
b6 = '1242424352424342424242424242425342534242'
b7 = '124242435242434242424242424242424242534242'
b8 = '124242435242434242424242424242524243424242'
b9 = '124242435242434242424242424242425243424242'
if sys.argv[1:] == 'off':
NUM_ATTEMPTS = 1300
else:
NUM_ATTEMPTS = 170
TRANSMIT_PIN = 17
def transmit_code(code):
'''Transmit a chosen code string using the GPIO transmitter'''
GPIO.setmode(GPIO.BCM)
GPIO.setup(TRANSMIT_PIN, GPIO.OUT)
for t in range(NUM_ATTEMPTS):
for i in code:
if i == '1':
GPIO.output(TRANSMIT_PIN, 1)
time.sleep(.00055);
GPIO.output(TRANSMIT_PIN, 0)
elif i == '2':
GPIO.output(TRANSMIT_PIN, 0)
time.sleep(.00011);
GPIO.output(TRANSMIT_PIN, 1)
elif i == '3':
GPIO.output(TRANSMIT_PIN, 0)
time.sleep(.000303);
GPIO.output(TRANSMIT_PIN, 1)
elif i == '4':
GPIO.output(TRANSMIT_PIN, 1)
time.sleep(.00011);
GPIO.output(TRANSMIT_PIN, 0)
elif i == '5':
GPIO.output(TRANSMIT_PIN, 1)
time.sleep(.00029);
GPIO.output(TRANSMIT_PIN, 0)
else:
continue
GPIO.output(TRANSMIT_PIN, 0)
GPIO.cleanup()
if __name__ == '__main__':
for argument in sys.argv[1:]:
exec('transmit_code(' + str(argument) + ')') | gpl-3.0 |
batermj/algorithm-challenger | code-analysis/programming_anguage/python/source_codes/Python3.5.9/Python-3.5.9/Lib/test/test_copyreg.py | 12 | 4135 | import copyreg
import unittest
from test.pickletester import ExtensionSaver
class C:
pass
class WithoutSlots(object):
pass
class WithWeakref(object):
__slots__ = ('__weakref__',)
class WithPrivate(object):
__slots__ = ('__spam',)
class WithSingleString(object):
__slots__ = 'spam'
class WithInherited(WithSingleString):
__slots__ = ('eggs',)
class CopyRegTestCase(unittest.TestCase):
def test_class(self):
self.assertRaises(TypeError, copyreg.pickle,
C, None, None)
def test_noncallable_reduce(self):
self.assertRaises(TypeError, copyreg.pickle,
type(1), "not a callable")
def test_noncallable_constructor(self):
self.assertRaises(TypeError, copyreg.pickle,
type(1), int, "not a callable")
def test_bool(self):
import copy
self.assertEqual(True, copy.copy(True))
def test_extension_registry(self):
mod, func, code = 'junk1 ', ' junk2', 0xabcd
e = ExtensionSaver(code)
try:
# Shouldn't be in registry now.
self.assertRaises(ValueError, copyreg.remove_extension,
mod, func, code)
copyreg.add_extension(mod, func, code)
# Should be in the registry.
self.assertTrue(copyreg._extension_registry[mod, func] == code)
self.assertTrue(copyreg._inverted_registry[code] == (mod, func))
# Shouldn't be in the cache.
self.assertNotIn(code, copyreg._extension_cache)
# Redundant registration should be OK.
copyreg.add_extension(mod, func, code) # shouldn't blow up
# Conflicting code.
self.assertRaises(ValueError, copyreg.add_extension,
mod, func, code + 1)
self.assertRaises(ValueError, copyreg.remove_extension,
mod, func, code + 1)
# Conflicting module name.
self.assertRaises(ValueError, copyreg.add_extension,
mod[1:], func, code )
self.assertRaises(ValueError, copyreg.remove_extension,
mod[1:], func, code )
# Conflicting function name.
self.assertRaises(ValueError, copyreg.add_extension,
mod, func[1:], code)
self.assertRaises(ValueError, copyreg.remove_extension,
mod, func[1:], code)
# Can't remove one that isn't registered at all.
if code + 1 not in copyreg._inverted_registry:
self.assertRaises(ValueError, copyreg.remove_extension,
mod[1:], func[1:], code + 1)
finally:
e.restore()
# Shouldn't be there anymore.
self.assertNotIn((mod, func), copyreg._extension_registry)
# The code *may* be in copyreg._extension_registry, though, if
# we happened to pick on a registered code. So don't check for
# that.
# Check valid codes at the limits.
for code in 1, 0x7fffffff:
e = ExtensionSaver(code)
try:
copyreg.add_extension(mod, func, code)
copyreg.remove_extension(mod, func, code)
finally:
e.restore()
# Ensure invalid codes blow up.
for code in -1, 0, 0x80000000:
self.assertRaises(ValueError, copyreg.add_extension,
mod, func, code)
def test_slotnames(self):
self.assertEqual(copyreg._slotnames(WithoutSlots), [])
self.assertEqual(copyreg._slotnames(WithWeakref), [])
expected = ['_WithPrivate__spam']
self.assertEqual(copyreg._slotnames(WithPrivate), expected)
self.assertEqual(copyreg._slotnames(WithSingleString), ['spam'])
expected = ['eggs', 'spam']
expected.sort()
result = copyreg._slotnames(WithInherited)
result.sort()
self.assertEqual(result, expected)
if __name__ == "__main__":
unittest.main()
| apache-2.0 |
dawnpower/nova | nova/tests/unit/objects/test_floating_ip.py | 65 | 11358 | # Copyright 2014 Red Hat, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import mock
import netaddr
from nova import exception
from nova import objects
from nova.objects import floating_ip
from nova.tests.unit.objects import test_fixed_ip
from nova.tests.unit.objects import test_network
from nova.tests.unit.objects import test_objects
fake_floating_ip = {
'created_at': None,
'updated_at': None,
'deleted_at': None,
'deleted': False,
'id': 123,
'address': '172.17.0.1',
'fixed_ip_id': None,
'project_id': None,
'host': None,
'auto_assigned': False,
'pool': None,
'interface': None,
'fixed_ip': None,
}
class _TestFloatingIPObject(object):
def _compare(self, obj, db_obj):
for field in obj.fields:
if field in floating_ip.FLOATING_IP_OPTIONAL_ATTRS:
if obj.obj_attr_is_set(field):
obj_val = obj[field].id
db_val = db_obj[field]['id']
else:
continue
else:
obj_val = obj[field]
db_val = db_obj[field]
if isinstance(obj_val, netaddr.IPAddress):
obj_val = str(obj_val)
self.assertEqual(db_val, obj_val)
@mock.patch('nova.db.floating_ip_get')
def test_get_by_id(self, get):
db_floatingip = dict(fake_floating_ip,
fixed_ip=test_fixed_ip.fake_fixed_ip)
get.return_value = db_floatingip
floatingip = floating_ip.FloatingIP.get_by_id(self.context, 123)
get.assert_called_once_with(self.context, 123)
self._compare(floatingip, db_floatingip)
@mock.patch('nova.db.floating_ip_get_by_address')
def test_get_by_address(self, get):
get.return_value = fake_floating_ip
floatingip = floating_ip.FloatingIP.get_by_address(self.context,
'1.2.3.4')
get.assert_called_once_with(self.context, '1.2.3.4')
self._compare(floatingip, fake_floating_ip)
@mock.patch('nova.db.floating_ip_get_pools')
def test_get_pool_names(self, get):
get.return_value = [{'name': 'a'}, {'name': 'b'}]
self.assertEqual(['a', 'b'],
floating_ip.FloatingIP.get_pool_names(self.context))
@mock.patch('nova.db.floating_ip_allocate_address')
def test_allocate_address(self, allocate):
allocate.return_value = '1.2.3.4'
self.assertEqual('1.2.3.4',
floating_ip.FloatingIP.allocate_address(self.context,
'project',
'pool'))
allocate.assert_called_with(self.context, 'project', 'pool',
auto_assigned=False)
@mock.patch('nova.db.floating_ip_fixed_ip_associate')
def test_associate(self, associate):
db_fixed = dict(test_fixed_ip.fake_fixed_ip,
network=test_network.fake_network)
associate.return_value = db_fixed
floatingip = floating_ip.FloatingIP.associate(self.context,
'172.17.0.1',
'192.168.1.1',
'host')
associate.assert_called_with(self.context, '172.17.0.1',
'192.168.1.1', 'host')
self.assertEqual(db_fixed['id'], floatingip.fixed_ip.id)
self.assertEqual('172.17.0.1', str(floatingip.address))
self.assertEqual('host', floatingip.host)
@mock.patch('nova.db.floating_ip_deallocate')
def test_deallocate(self, deallocate):
floating_ip.FloatingIP.deallocate(self.context, '1.2.3.4')
deallocate.assert_called_with(self.context, '1.2.3.4')
@mock.patch('nova.db.floating_ip_destroy')
def test_destroy(self, destroy):
floating_ip.FloatingIP.destroy(self.context, '1.2.3.4')
destroy.assert_called_with(self.context, '1.2.3.4')
@mock.patch('nova.db.floating_ip_disassociate')
def test_disassociate(self, disassociate):
db_fixed = dict(test_fixed_ip.fake_fixed_ip,
network=test_network.fake_network)
disassociate.return_value = db_fixed
floatingip = floating_ip.FloatingIP.disassociate(self.context,
'1.2.3.4')
disassociate.assert_called_with(self.context, '1.2.3.4')
self.assertEqual(db_fixed['id'], floatingip.fixed_ip.id)
self.assertEqual('1.2.3.4', str(floatingip.address))
@mock.patch('nova.db.floating_ip_update')
def test_save(self, update):
update.return_value = fake_floating_ip
floatingip = floating_ip.FloatingIP(context=self.context,
id=123, address='1.2.3.4',
host='foo')
floatingip.obj_reset_changes(['address', 'id'])
floatingip.save()
self.assertEqual(set(), floatingip.obj_what_changed())
update.assert_called_with(self.context, '1.2.3.4',
{'host': 'foo'})
def test_save_errors(self):
floatingip = floating_ip.FloatingIP(context=self.context,
id=123, host='foo')
floatingip.obj_reset_changes()
floating_ip.address = '1.2.3.4'
self.assertRaises(exception.ObjectActionError, floatingip.save)
floatingip.obj_reset_changes()
floatingip.fixed_ip_id = 1
self.assertRaises(exception.ObjectActionError, floatingip.save)
@mock.patch('nova.db.floating_ip_update')
def test_save_no_fixedip(self, update):
update.return_value = fake_floating_ip
floatingip = floating_ip.FloatingIP(context=self.context,
id=123)
floatingip.fixed_ip = objects.FixedIP(context=self.context,
id=456)
self.assertNotIn('fixed_ip', update.calls[1])
@mock.patch('nova.db.floating_ip_get_all')
def test_get_all(self, get):
get.return_value = [fake_floating_ip]
floatingips = floating_ip.FloatingIPList.get_all(self.context)
self.assertEqual(1, len(floatingips))
self._compare(floatingips[0], fake_floating_ip)
get.assert_called_with(self.context)
@mock.patch('nova.db.floating_ip_get_all_by_host')
def test_get_by_host(self, get):
get.return_value = [fake_floating_ip]
floatingips = floating_ip.FloatingIPList.get_by_host(self.context,
'host')
self.assertEqual(1, len(floatingips))
self._compare(floatingips[0], fake_floating_ip)
get.assert_called_with(self.context, 'host')
@mock.patch('nova.db.floating_ip_get_all_by_project')
def test_get_by_project(self, get):
get.return_value = [fake_floating_ip]
floatingips = floating_ip.FloatingIPList.get_by_project(self.context,
'project')
self.assertEqual(1, len(floatingips))
self._compare(floatingips[0], fake_floating_ip)
get.assert_called_with(self.context, 'project')
@mock.patch('nova.db.floating_ip_get_by_fixed_address')
def test_get_by_fixed_address(self, get):
get.return_value = [fake_floating_ip]
floatingips = floating_ip.FloatingIPList.get_by_fixed_address(
self.context, '1.2.3.4')
self.assertEqual(1, len(floatingips))
self._compare(floatingips[0], fake_floating_ip)
get.assert_called_with(self.context, '1.2.3.4')
@mock.patch('nova.db.floating_ip_get_by_fixed_ip_id')
def test_get_by_fixed_ip_id(self, get):
get.return_value = [fake_floating_ip]
floatingips = floating_ip.FloatingIPList.get_by_fixed_ip_id(
self.context, 123)
self.assertEqual(1, len(floatingips))
self._compare(floatingips[0], fake_floating_ip)
get.assert_called_with(self.context, 123)
@mock.patch('nova.db.instance_floating_address_get_all')
def test_get_addresses_by_instance(self, get_all):
expected = ['1.2.3.4', '4.5.6.7']
get_all.return_value = list(expected)
ips = floating_ip.FloatingIP.get_addresses_by_instance(
self.context, {'uuid': '1234'})
self.assertEqual(expected, ips)
get_all.assert_called_once_with(self.context, '1234')
def test_make_ip_info(self):
result = objects.FloatingIPList.make_ip_info('1.2.3.4', 'pool', 'eth0')
self.assertEqual({'address': '1.2.3.4', 'pool': 'pool',
'interface': 'eth0'},
result)
@mock.patch('nova.db.floating_ip_bulk_create')
def test_bulk_create(self, create_mock):
def fake_create(ctxt, ip_info, want_result=False):
return [{'id': 1, 'address': ip['address'], 'fixed_ip_id': 1,
'project_id': 'foo', 'host': 'host',
'auto_assigned': False, 'pool': ip['pool'],
'interface': ip['interface'], 'fixed_ip': None,
'created_at': None, 'updated_at': None,
'deleted_at': None, 'deleted': False}
for ip in ip_info]
create_mock.side_effect = fake_create
ips = [objects.FloatingIPList.make_ip_info('1.1.1.1', 'pool', 'eth0'),
objects.FloatingIPList.make_ip_info('1.1.1.2', 'loop', 'eth1')]
result = objects.FloatingIPList.create(None, ips)
self.assertIs(result, None)
result = objects.FloatingIPList.create(None, ips, want_result=True)
self.assertEqual('1.1.1.1', str(result[0].address))
self.assertEqual('1.1.1.2', str(result[1].address))
@mock.patch('nova.db.floating_ip_bulk_destroy')
def test_bulk_destroy(self, destroy_mock):
ips = [{'address': '1.2.3.4'}, {'address': '4.5.6.7'}]
objects.FloatingIPList.destroy(None, ips)
destroy_mock.assert_called_once_with(None, ips)
def test_backport_fixedip_1_1(self):
floating = objects.FloatingIP()
fixed = objects.FixedIP()
floating.fixed_ip = fixed
primitive = floating.obj_to_primitive(target_version='1.1')
self.assertEqual('1.1',
primitive['nova_object.data']['fixed_ip']['nova_object.version'])
class TestFloatingIPObject(test_objects._LocalTest,
_TestFloatingIPObject):
pass
class TestRemoteFloatingIPObject(test_objects._RemoteTest,
_TestFloatingIPObject):
pass
| apache-2.0 |
chintak/scikit-image | skimage/segmentation/_clear_border.py | 22 | 2072 | import numpy as np
from scipy.ndimage import label
def clear_border(image, buffer_size=0, bgval=0):
"""Clear objects connected to image border.
The changes will be applied to the input image.
Parameters
----------
image : (N, M) array
Binary image.
buffer_size : int, optional
Define additional buffer around image border.
bgval : float or int, optional
Value for cleared objects.
Returns
-------
image : (N, M) array
Cleared binary image.
Examples
--------
>>> import numpy as np
>>> from skimage.segmentation import clear_border
>>> image = np.array([[0, 0, 0, 0, 0, 0, 0, 1, 0],
... [0, 0, 0, 0, 1, 0, 0, 0, 0],
... [1, 0, 0, 1, 0, 1, 0, 0, 0],
... [0, 0, 1, 1, 1, 1, 1, 0, 0],
... [0, 1, 1, 1, 1, 1, 1, 1, 0],
... [0, 0, 0, 0, 0, 0, 0, 0, 0]])
>>> clear_border(image)
array([[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 1, 0, 0, 0, 0],
[0, 0, 0, 1, 0, 1, 0, 0, 0],
[0, 0, 1, 1, 1, 1, 1, 0, 0],
[0, 1, 1, 1, 1, 1, 1, 1, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0]])
"""
rows, cols = image.shape
if buffer_size >= rows or buffer_size >= cols:
raise ValueError("buffer size may not be greater than image size")
# create borders with buffer_size
borders = np.zeros_like(image, dtype=np.bool_)
ext = buffer_size + 1
borders[:ext] = True
borders[- ext:] = True
borders[:, :ext] = True
borders[:, - ext:] = True
labels, number = label(image)
# determine all objects that are connected to borders
borders_indices = np.unique(labels[borders])
indices = np.arange(number + 1)
# mask all label indices that are connected to borders
label_mask = np.in1d(indices, borders_indices)
# create mask for pixels to clear
mask = label_mask[labels.ravel()].reshape(labels.shape)
# clear border pixels
image[mask] = bgval
return image
| bsd-3-clause |
KunihikoKido/sublime-elasticsearch-client | lib/requests/cookies.py | 413 | 17191 | # -*- coding: utf-8 -*-
"""
Compatibility code to be able to use `cookielib.CookieJar` with requests.
requests.utils imports from here, so be careful with imports.
"""
import copy
import time
import collections
from .compat import cookielib, urlparse, urlunparse, Morsel
try:
import threading
# grr, pyflakes: this fixes "redefinition of unused 'threading'"
threading
except ImportError:
import dummy_threading as threading
class MockRequest(object):
"""Wraps a `requests.Request` to mimic a `urllib2.Request`.
The code in `cookielib.CookieJar` expects this interface in order to correctly
manage cookie policies, i.e., determine whether a cookie can be set, given the
domains of the request and the cookie.
The original request object is read-only. The client is responsible for collecting
the new headers via `get_new_headers()` and interpreting them appropriately. You
probably want `get_cookie_header`, defined below.
"""
def __init__(self, request):
self._r = request
self._new_headers = {}
self.type = urlparse(self._r.url).scheme
def get_type(self):
return self.type
def get_host(self):
return urlparse(self._r.url).netloc
def get_origin_req_host(self):
return self.get_host()
def get_full_url(self):
# Only return the response's URL if the user hadn't set the Host
# header
if not self._r.headers.get('Host'):
return self._r.url
# If they did set it, retrieve it and reconstruct the expected domain
host = self._r.headers['Host']
parsed = urlparse(self._r.url)
# Reconstruct the URL as we expect it
return urlunparse([
parsed.scheme, host, parsed.path, parsed.params, parsed.query,
parsed.fragment
])
def is_unverifiable(self):
return True
def has_header(self, name):
return name in self._r.headers or name in self._new_headers
def get_header(self, name, default=None):
return self._r.headers.get(name, self._new_headers.get(name, default))
def add_header(self, key, val):
"""cookielib has no legitimate use for this method; add it back if you find one."""
raise NotImplementedError("Cookie headers should be added with add_unredirected_header()")
def add_unredirected_header(self, name, value):
self._new_headers[name] = value
def get_new_headers(self):
return self._new_headers
@property
def unverifiable(self):
return self.is_unverifiable()
@property
def origin_req_host(self):
return self.get_origin_req_host()
@property
def host(self):
return self.get_host()
class MockResponse(object):
"""Wraps a `httplib.HTTPMessage` to mimic a `urllib.addinfourl`.
...what? Basically, expose the parsed HTTP headers from the server response
the way `cookielib` expects to see them.
"""
def __init__(self, headers):
"""Make a MockResponse for `cookielib` to read.
:param headers: a httplib.HTTPMessage or analogous carrying the headers
"""
self._headers = headers
def info(self):
return self._headers
def getheaders(self, name):
self._headers.getheaders(name)
def extract_cookies_to_jar(jar, request, response):
"""Extract the cookies from the response into a CookieJar.
:param jar: cookielib.CookieJar (not necessarily a RequestsCookieJar)
:param request: our own requests.Request object
:param response: urllib3.HTTPResponse object
"""
if not (hasattr(response, '_original_response') and
response._original_response):
return
# the _original_response field is the wrapped httplib.HTTPResponse object,
req = MockRequest(request)
# pull out the HTTPMessage with the headers and put it in the mock:
res = MockResponse(response._original_response.msg)
jar.extract_cookies(res, req)
def get_cookie_header(jar, request):
"""Produce an appropriate Cookie header string to be sent with `request`, or None."""
r = MockRequest(request)
jar.add_cookie_header(r)
return r.get_new_headers().get('Cookie')
def remove_cookie_by_name(cookiejar, name, domain=None, path=None):
"""Unsets a cookie by name, by default over all domains and paths.
Wraps CookieJar.clear(), is O(n).
"""
clearables = []
for cookie in cookiejar:
if cookie.name == name:
if domain is None or domain == cookie.domain:
if path is None or path == cookie.path:
clearables.append((cookie.domain, cookie.path, cookie.name))
for domain, path, name in clearables:
cookiejar.clear(domain, path, name)
class CookieConflictError(RuntimeError):
"""There are two cookies that meet the criteria specified in the cookie jar.
Use .get and .set and include domain and path args in order to be more specific."""
class RequestsCookieJar(cookielib.CookieJar, collections.MutableMapping):
"""Compatibility class; is a cookielib.CookieJar, but exposes a dict
interface.
This is the CookieJar we create by default for requests and sessions that
don't specify one, since some clients may expect response.cookies and
session.cookies to support dict operations.
Requests does not use the dict interface internally; it's just for
compatibility with external client code. All requests code should work
out of the box with externally provided instances of ``CookieJar``, e.g.
``LWPCookieJar`` and ``FileCookieJar``.
Unlike a regular CookieJar, this class is pickleable.
.. warning:: dictionary operations that are normally O(1) may be O(n).
"""
def get(self, name, default=None, domain=None, path=None):
"""Dict-like get() that also supports optional domain and path args in
order to resolve naming collisions from using one cookie jar over
multiple domains.
.. warning:: operation is O(n), not O(1)."""
try:
return self._find_no_duplicates(name, domain, path)
except KeyError:
return default
def set(self, name, value, **kwargs):
"""Dict-like set() that also supports optional domain and path args in
order to resolve naming collisions from using one cookie jar over
multiple domains."""
# support client code that unsets cookies by assignment of a None value:
if value is None:
remove_cookie_by_name(self, name, domain=kwargs.get('domain'), path=kwargs.get('path'))
return
if isinstance(value, Morsel):
c = morsel_to_cookie(value)
else:
c = create_cookie(name, value, **kwargs)
self.set_cookie(c)
return c
def iterkeys(self):
"""Dict-like iterkeys() that returns an iterator of names of cookies
from the jar. See itervalues() and iteritems()."""
for cookie in iter(self):
yield cookie.name
def keys(self):
"""Dict-like keys() that returns a list of names of cookies from the
jar. See values() and items()."""
return list(self.iterkeys())
def itervalues(self):
"""Dict-like itervalues() that returns an iterator of values of cookies
from the jar. See iterkeys() and iteritems()."""
for cookie in iter(self):
yield cookie.value
def values(self):
"""Dict-like values() that returns a list of values of cookies from the
jar. See keys() and items()."""
return list(self.itervalues())
def iteritems(self):
"""Dict-like iteritems() that returns an iterator of name-value tuples
from the jar. See iterkeys() and itervalues()."""
for cookie in iter(self):
yield cookie.name, cookie.value
def items(self):
"""Dict-like items() that returns a list of name-value tuples from the
jar. See keys() and values(). Allows client-code to call
``dict(RequestsCookieJar)`` and get a vanilla python dict of key value
pairs."""
return list(self.iteritems())
def list_domains(self):
"""Utility method to list all the domains in the jar."""
domains = []
for cookie in iter(self):
if cookie.domain not in domains:
domains.append(cookie.domain)
return domains
def list_paths(self):
"""Utility method to list all the paths in the jar."""
paths = []
for cookie in iter(self):
if cookie.path not in paths:
paths.append(cookie.path)
return paths
def multiple_domains(self):
"""Returns True if there are multiple domains in the jar.
Returns False otherwise."""
domains = []
for cookie in iter(self):
if cookie.domain is not None and cookie.domain in domains:
return True
domains.append(cookie.domain)
return False # there is only one domain in jar
def get_dict(self, domain=None, path=None):
"""Takes as an argument an optional domain and path and returns a plain
old Python dict of name-value pairs of cookies that meet the
requirements."""
dictionary = {}
for cookie in iter(self):
if (domain is None or cookie.domain == domain) and (path is None
or cookie.path == path):
dictionary[cookie.name] = cookie.value
return dictionary
def __getitem__(self, name):
"""Dict-like __getitem__() for compatibility with client code. Throws
exception if there are more than one cookie with name. In that case,
use the more explicit get() method instead.
.. warning:: operation is O(n), not O(1)."""
return self._find_no_duplicates(name)
def __setitem__(self, name, value):
"""Dict-like __setitem__ for compatibility with client code. Throws
exception if there is already a cookie of that name in the jar. In that
case, use the more explicit set() method instead."""
self.set(name, value)
def __delitem__(self, name):
"""Deletes a cookie given a name. Wraps ``cookielib.CookieJar``'s
``remove_cookie_by_name()``."""
remove_cookie_by_name(self, name)
def set_cookie(self, cookie, *args, **kwargs):
if hasattr(cookie.value, 'startswith') and cookie.value.startswith('"') and cookie.value.endswith('"'):
cookie.value = cookie.value.replace('\\"', '')
return super(RequestsCookieJar, self).set_cookie(cookie, *args, **kwargs)
def update(self, other):
"""Updates this jar with cookies from another CookieJar or dict-like"""
if isinstance(other, cookielib.CookieJar):
for cookie in other:
self.set_cookie(copy.copy(cookie))
else:
super(RequestsCookieJar, self).update(other)
def _find(self, name, domain=None, path=None):
"""Requests uses this method internally to get cookie values. Takes as
args name and optional domain and path. Returns a cookie.value. If
there are conflicting cookies, _find arbitrarily chooses one. See
_find_no_duplicates if you want an exception thrown if there are
conflicting cookies."""
for cookie in iter(self):
if cookie.name == name:
if domain is None or cookie.domain == domain:
if path is None or cookie.path == path:
return cookie.value
raise KeyError('name=%r, domain=%r, path=%r' % (name, domain, path))
def _find_no_duplicates(self, name, domain=None, path=None):
"""Both ``__get_item__`` and ``get`` call this function: it's never
used elsewhere in Requests. Takes as args name and optional domain and
path. Returns a cookie.value. Throws KeyError if cookie is not found
and CookieConflictError if there are multiple cookies that match name
and optionally domain and path."""
toReturn = None
for cookie in iter(self):
if cookie.name == name:
if domain is None or cookie.domain == domain:
if path is None or cookie.path == path:
if toReturn is not None: # if there are multiple cookies that meet passed in criteria
raise CookieConflictError('There are multiple cookies with name, %r' % (name))
toReturn = cookie.value # we will eventually return this as long as no cookie conflict
if toReturn:
return toReturn
raise KeyError('name=%r, domain=%r, path=%r' % (name, domain, path))
def __getstate__(self):
"""Unlike a normal CookieJar, this class is pickleable."""
state = self.__dict__.copy()
# remove the unpickleable RLock object
state.pop('_cookies_lock')
return state
def __setstate__(self, state):
"""Unlike a normal CookieJar, this class is pickleable."""
self.__dict__.update(state)
if '_cookies_lock' not in self.__dict__:
self._cookies_lock = threading.RLock()
def copy(self):
"""Return a copy of this RequestsCookieJar."""
new_cj = RequestsCookieJar()
new_cj.update(self)
return new_cj
def _copy_cookie_jar(jar):
if jar is None:
return None
if hasattr(jar, 'copy'):
# We're dealing with an instane of RequestsCookieJar
return jar.copy()
# We're dealing with a generic CookieJar instance
new_jar = copy.copy(jar)
new_jar.clear()
for cookie in jar:
new_jar.set_cookie(copy.copy(cookie))
return new_jar
def create_cookie(name, value, **kwargs):
"""Make a cookie from underspecified parameters.
By default, the pair of `name` and `value` will be set for the domain ''
and sent on every request (this is sometimes called a "supercookie").
"""
result = dict(
version=0,
name=name,
value=value,
port=None,
domain='',
path='/',
secure=False,
expires=None,
discard=True,
comment=None,
comment_url=None,
rest={'HttpOnly': None},
rfc2109=False,)
badargs = set(kwargs) - set(result)
if badargs:
err = 'create_cookie() got unexpected keyword arguments: %s'
raise TypeError(err % list(badargs))
result.update(kwargs)
result['port_specified'] = bool(result['port'])
result['domain_specified'] = bool(result['domain'])
result['domain_initial_dot'] = result['domain'].startswith('.')
result['path_specified'] = bool(result['path'])
return cookielib.Cookie(**result)
def morsel_to_cookie(morsel):
"""Convert a Morsel object into a Cookie containing the one k/v pair."""
expires = None
if morsel['max-age']:
expires = time.time() + morsel['max-age']
elif morsel['expires']:
time_template = '%a, %d-%b-%Y %H:%M:%S GMT'
expires = time.mktime(
time.strptime(morsel['expires'], time_template)) - time.timezone
return create_cookie(
comment=morsel['comment'],
comment_url=bool(morsel['comment']),
discard=False,
domain=morsel['domain'],
expires=expires,
name=morsel.key,
path=morsel['path'],
port=None,
rest={'HttpOnly': morsel['httponly']},
rfc2109=False,
secure=bool(morsel['secure']),
value=morsel.value,
version=morsel['version'] or 0,
)
def cookiejar_from_dict(cookie_dict, cookiejar=None, overwrite=True):
"""Returns a CookieJar from a key/value dictionary.
:param cookie_dict: Dict of key/values to insert into CookieJar.
:param cookiejar: (optional) A cookiejar to add the cookies to.
:param overwrite: (optional) If False, will not replace cookies
already in the jar with new ones.
"""
if cookiejar is None:
cookiejar = RequestsCookieJar()
if cookie_dict is not None:
names_from_jar = [cookie.name for cookie in cookiejar]
for name in cookie_dict:
if overwrite or (name not in names_from_jar):
cookiejar.set_cookie(create_cookie(name, cookie_dict[name]))
return cookiejar
def merge_cookies(cookiejar, cookies):
"""Add cookies to cookiejar and returns a merged CookieJar.
:param cookiejar: CookieJar object to add the cookies to.
:param cookies: Dictionary or CookieJar object to be added.
"""
if not isinstance(cookiejar, cookielib.CookieJar):
raise ValueError('You can only merge into CookieJar')
if isinstance(cookies, dict):
cookiejar = cookiejar_from_dict(
cookies, cookiejar=cookiejar, overwrite=False)
elif isinstance(cookies, cookielib.CookieJar):
try:
cookiejar.update(cookies)
except AttributeError:
for cookie_in_jar in cookies:
cookiejar.set_cookie(cookie_in_jar)
return cookiejar
| mit |
flipdazed/SoftwareDevelopment | common.py | 1 | 10121 | #!/usr/bin/env python
# encoding: utf-8
# contains the common actions
import random
from logs import *
class Card(object):
"""Creates the card objects used in game"""
def __init__(self, name, attack, money, cost, name_padding=15, num_padding=2):
self.name = name
self.cost = cost
self.attack = attack
self.money = money
self.name_padding = name_padding
self.num_padding = num_padding
self.padded_vals = (
str(self.cost).ljust(self.num_padding),
self.name.ljust(self.name_padding),
str(self.attack).ljust(self.num_padding),
str(self.money).ljust(self.num_padding),
)
def __str__(self):
"""outputs string of the card details when called as print Card()"""
s_out = "Cost: {0} ~ {1} ~ Stats ... Attack: {2}, Money: {3}".format(
*self.padded_vals)
return s_out
def get_attack(self):
return self.attack
def get_money(self):
return self.money
@wrap_all(log_me)
class CommonActions(object):
"""Contains the common actions
used by all game classes
"""
def __init__(self):
# self.art = Art()
pass
def deck_to_hand(self):
"""
Move cards from central.central deck
to active central.central deck
Container is the dictionary within the
class that need to be called with the
getattr()
"""
# For each index in player hand
# Refills player hand from player deck.
# If deck is empty, discard pile is shuffled
# and becomes deck
for i in xrange(0, self.hand_size):
# Shuffle deck computer.pC['hand_size times
# if length of deck = 0
# Will only be done once
if len(self.deck) == 0:
self.logger.debug("Deck length is zero!")
if len(self.discard) == 0:
self.logger.debug("Discard length is also zero!")
self.logger.debug("Exiting the deck_to_hand routine as no more cards.")
return
random.shuffle(self.discard) # Shuffle discard pile
self.logger.debug("shuffled deck")
self.deck = self.discard # Make deck the discard
self.discard = [] # empty the discard pile
self.logger.debug("Moved discard pile to deck. Discard pile set to empty.")
card = self.deck.pop()
self.hand.append(card)
self.logger.debug("Iteration #{}: Drawn {} from deck and added to hand".format(i,card.name))
pass
def print_active_cards(self, title=None, index=False):
"""Display cards in active"""
if title is None: title = "Your Played Cards"
# switch depending on player type
self.logger.debug("Actor is: {}".format(type(self).__name__))
title = self.art.make_title(title)
self.player_logger(title)
self._print_cards(self.active, index=index)
self.player_logger(self.art.underline)
pass
def deck_creator(self, deck_list):
"""Creates the deck from a list of dictionaries
_Input_
list of dicts.
dict contents:
"card" : dict containing all **kwargs for Card()
"count" : number of cards with these settings to create
_Output_
list of Card() types
Expected input example:
[{"count":1, "card":{"name":'Archer', "attack":3, "money":0, "cost":2}},
{"count":2, "card":{"name":'Baker', "attack":0, "money":0, "cost":2}}]
Expected Output example:
[Card('Archer', 3,0,2), Card('Baker', 0,0,2), Card('Baker', 0,0,2)]
"""
deck = [] # get deck ready
for card in deck_list:
for _ in xrange(card["count"]):
# passes the dictionary as a keyword arg (**kwarg)
deck.append(Card(
name_padding=self.parent.max_card_name_len,
num_padding=2,
**card["params"]
))
self.logger.debug("Created {}x{}".format(card["count"], card["params"]["name"]))
return deck
def _print_cards(self, cards, index=False):
"""Prints out the cards provided"""
# max card name length
if len(cards) == 0:
self.logger.game(self.art.index_buffer+ \
"Nothing interesting to see here...")
else:
for i, card in enumerate(cards):
num_str = "[{}] ".format(i) if index else self.art.index_buffer
self.logger.game(num_str + "{}".format(card))
pass
@wrap_all(log_me)
class CommonUserActions(object):
"""Contains actions for user and computer"""
def __init__(self):
pass
def newgame(self):
# revert to initial state
for attr, val in self.init.iteritems():
setattr(self, attr, val)
self.active = []
self.hand = []
self.discard = []
self.deck = self.deck_creator(self.deck_settings)
pass
def end_turn(self):
"""Ends the turn of the user"""
self.logger.debug("Ending Turn: {}".format(self.name))
# If player has cards in the hand add to discard pile
self.discard_hand()
# If there cards in active deck
# then move all cards from active to discard
self.discard_active_cards()
# Move cards from deck to hand
self.deck_to_hand()
pass
def play_all_cards(self):
"""transfer all cards from hand to active
add values in hand to current totals
should only be used by User and Computer
"""
for i in xrange(0, len(self.hand)):
card = self.hand.pop()
self.active.append(card)
self.logger.debug("Iteration #{}: Drawn {} from deck and added to active deck".format(i,card.name))
self.__add_values_to_total(card)
pass
def play_a_card(self, card_number):
"""plays a specific card...
Transfer card to active
add values in hand to current totals
"""
i=0
card_number = int(card_number)
# Transfer card to active
# add values in hand to current totals
card = self.hand.pop(card_number)
self.active.append(card)
self.logger.debug("Iteration #{}: Drawn {} from deck and added to active deck".format(i,card.name))
self.__add_values_to_total(card)
pass
def __add_values_to_total(self, card):
"""Adds money and attack to total"""
money_i = card.get_money()
attack_i = card.get_attack()
self.logger.debug("Money:{}+{} Attack:{}+{}".format(self.money, money_i, self.attack, attack_i))
self.money += money_i
self.attack += attack_i
pass
def discard_hand(self):
"""If there are cards in the hand add to discard pile"""
if (len(self.hand) > 0 ):
# Iterate through all cards in player hand
for i in xrange(0, len(self.hand)):
card = self.hand.pop()
self.logger.debug("Iteration #{}: Moving {} from hand and added to discard pile".format(i, card.name))
self.discard.append(card)
else:
self.logger.debug("Hand length is zero. No cards to discard.")
pass
def discard_active_cards(self):
"""If there cards in PC active deck
then move all cards from active to discard"""
if (len(self.active) > 0 ):
for i in xrange(0, len(self.active)):
card = self.active.pop()
self.logger.debug("Iteration #{}: Moving {} from hand and added to discard pile".format(i, card.name))
self.discard.append(card)
else:
self.logger.debug("Active Deck length is zero. No cards to discard.")
pass
def display_values(self, attack=None, money=None):
""" Display player values"""
# allows forced values
if attack is None: attack = self.attack
if money is None: money = self.money
padded_name = self.name.ljust(self.parent.max_player_name_len)
out_str = "{} Values :: ".format(padded_name)
out_str += " Attack: {} Money: {}".format(
attack, money)
self.player_logger("")
self.player_logger(out_str)
self.player_logger("")
pass
def show_health(self):
"""Shows players' health"""
# creates an attribute based on the class
padded_name = self.name.ljust(self.parent.max_player_name_len)
out_str = "{} Health : ".format(padded_name)
out_str += "{}".format(self.health)
self.player_logger(out_str)
pass
def attack_player(self, other_player):
""" Attack another player
other_player expected input is a class
that corresponds to another sibling player
an example of this from self = game.User() would be:
self.attack(self.parent.computer)
which would attack the computer form the player
"""
self.logger.debug("{0} Attacking {1} with strength {2}".format(self.name, other_player.name, self.attack))
self.logger.debug("{0} Health before attack: {1}".format(other_player.name, other_player.health))
other_player.health -= self.attack
self.attack = 0
self.logger.debug("{0} Attack: {1}".format(self.name, self.attack))
pass
def reset_vals(self):
"""resets money and attack"""
self.logger.debug("Money and Attack set to 0 for {}".format(self.name))
self.money = 0
self.attack = 0
pass | gpl-3.0 |
DirectXMan12/nova-hacking | nova/weights.py | 22 | 2385 | # Copyright (c) 2011-2012 OpenStack Foundation
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
"""
Pluggable Weighing support
"""
from nova import loadables
class WeighedObject(object):
"""Object with weight information."""
def __init__(self, obj, weight):
self.obj = obj
self.weight = weight
def __repr__(self):
return "<WeighedObject '%s': %s>" % (self.obj, self.weight)
class BaseWeigher(object):
"""Base class for pluggable weighers."""
def _weight_multiplier(self):
"""How weighted this weigher should be. Normally this would
be overriden in a subclass based on a config value.
"""
return 1.0
def _weigh_object(self, obj, weight_properties):
"""Override in a subclass to specify a weight for a specific
object.
"""
return 0.0
def weigh_objects(self, weighed_obj_list, weight_properties):
"""Weigh multiple objects. Override in a subclass if you need
need access to all objects in order to manipulate weights.
"""
for obj in weighed_obj_list:
obj.weight += (self._weight_multiplier() *
self._weigh_object(obj.obj, weight_properties))
class BaseWeightHandler(loadables.BaseLoader):
object_class = WeighedObject
def get_weighed_objects(self, weigher_classes, obj_list,
weighing_properties):
"""Return a sorted (highest score first) list of WeighedObjects."""
if not obj_list:
return []
weighed_objs = [self.object_class(obj, 0.0) for obj in obj_list]
for weigher_cls in weigher_classes:
weigher = weigher_cls()
weigher.weigh_objects(weighed_objs, weighing_properties)
return sorted(weighed_objs, key=lambda x: x.weight, reverse=True)
| apache-2.0 |
tnagorra/nspell | lib/misc.py | 1 | 2396 | # cython: language_level=3
import re
class Mreplace:
def __init__(self, mydict):
self._mydict = mydict
self._rx = re.compile('|'.join(map(re.escape, self._mydict)))
def replace(self, text):
return self._rx.sub(lambda x: self._mydict[x.group(0)], text)
class Mmatch:
def __init__(self, mylist):
self._rx = re.compile('|'.join(mylist))
def match(self, text):
return self._rx.match(text)
_matches = {
'.*[?{}(),/\\"\';+=_*&^$#@!~`|\[\]]+.*',
'.*[a-zA-Z0-9]+.*',
'[-+]?[०-९]+(\.[०-९]+)?'
}
_validator = Mmatch(_matches)
def valid(mystr):
return not _validator.match(mystr)
_replacements = {
'':'',
'-':'-',
'—':'-',
'–':'-',
' :':' : ',
'।':' । ',
'’':' " ',
'‘':' " ',
'“':' " ',
'”':' " ',
'"':' " ',
"'":' " ',
'?':' ? ',
'!':' ! ',
',':' , ',
'/':' / ',
'÷':' ÷ ',
'…':' … ',
'{':' { ',
'}':' } ',
'[':' [ ',
']':' ] ',
'(':' ( ',
')':' ) ',
'=': ' = ',
'***': ' ',
'**':' ',
'*':' ',
'~': ' ',
'`': ' ',
'#': ' ',
'...': ' ... ',
'..': ' ... ',
'.': ' . '
}
_tokenizer = Mreplace(_replacements)
def tokenize(mystr):
return _tokenizer.replace(mystr).split()
# FIXME tokenizer to split the non-valid words
# TODO Use regex to match for 'ं'
# Dictionary of characters that have similar phonics, normalized words
# will have zero edit distance if they differ in only _phonics
_phonics = {
'ा':'आ',
'ो':'ओ',
'ी':'इ',
'ि':'इ',
'ई':'इ',
'ू':'उ',
'ु':'उ',
'ऊ':'उ',
'े':'ए',
'्':'',
'श':'स',
'ष':'स',
'व':'ब',
'':'', # Contains a non-joiner
}
_normalizer = Mreplace(_phonics)
# Normalize word (
def normalize(word):
return _normalizer.replace(word)
_dependent = {
'ँ':'',
'ं':'',
'ः':'',
'ा':'',
'ि':'',
'ी':'',
'ु':'',
'ू':'',
'ृ':'',
'े':'',
'ै':'',
'ो':'',
'ौ':'',
'्':'',
'':'',
}
_len = Mreplace(_dependent)
def length(mystr):
x = _len.replace(mystr)
return (len(x),x)
| gpl-3.0 |
simonwydooghe/ansible | lib/ansible/modules/network/fortios/fortios_wireless_controller_bonjour_profile.py | 7 | 12583 | #!/usr/bin/python
from __future__ import (absolute_import, division, print_function)
# Copyright 2019 Fortinet, Inc.
#
# 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 <https://www.gnu.org/licenses/>.
__metaclass__ = type
ANSIBLE_METADATA = {'status': ['preview'],
'supported_by': 'community',
'metadata_version': '1.1'}
DOCUMENTATION = '''
---
module: fortios_wireless_controller_bonjour_profile
short_description: Configure Bonjour profiles. Bonjour is Apple's zero configuration networking protocol. Bonjour profiles allow APs and FortiAPs to connect
to networks using Bonjour in Fortinet's FortiOS and FortiGate.
description:
- This module is able to configure a FortiGate or FortiOS (FOS) device by allowing the
user to set and modify wireless_controller feature and bonjour_profile category.
Examples include all parameters and values need to be adjusted to datasources before usage.
Tested with FOS v6.0.5
version_added: "2.9"
author:
- Miguel Angel Munoz (@mamunozgonzalez)
- Nicolas Thomas (@thomnico)
notes:
- Requires fortiosapi library developed by Fortinet
- Run as a local_action in your playbook
requirements:
- fortiosapi>=0.9.8
options:
host:
description:
- FortiOS or FortiGate IP address.
type: str
required: false
username:
description:
- FortiOS or FortiGate username.
type: str
required: false
password:
description:
- FortiOS or FortiGate password.
type: str
default: ""
vdom:
description:
- Virtual domain, among those defined previously. A vdom is a
virtual instance of the FortiGate that can be configured and
used as a different unit.
type: str
default: root
https:
description:
- Indicates if the requests towards FortiGate must use HTTPS protocol.
type: bool
default: true
ssl_verify:
description:
- Ensures FortiGate certificate must be verified by a proper CA.
type: bool
default: true
state:
description:
- Indicates whether to create or remove the object.
type: str
required: true
choices:
- present
- absent
wireless_controller_bonjour_profile:
description:
- Configure Bonjour profiles. Bonjour is Apple's zero configuration networking protocol. Bonjour profiles allow APs and FortiAPs to connect to
networks using Bonjour.
default: null
type: dict
suboptions:
comment:
description:
- Comment.
type: str
name:
description:
- Bonjour profile name.
required: true
type: str
policy_list:
description:
- Bonjour policy list.
type: list
suboptions:
description:
description:
- Description.
type: str
from_vlan:
description:
- VLAN ID from which the Bonjour service is advertised (0 - 4094).
type: str
policy_id:
description:
- Policy ID.
type: int
services:
description:
- Bonjour services for the VLAN connecting to the Bonjour network.
type: str
choices:
- all
- airplay
- afp
- bit-torrent
- ftp
- ichat
- itunes
- printers
- samba
- scanners
- ssh
- chromecast
to_vlan:
description:
- VLAN ID to which the Bonjour service is made available (0 - 4094).
type: str
'''
EXAMPLES = '''
- hosts: localhost
vars:
host: "192.168.122.40"
username: "admin"
password: ""
vdom: "root"
ssl_verify: "False"
tasks:
- name: Configure Bonjour profiles. Bonjour is Apple's zero configuration networking protocol. Bonjour profiles allow APs and FortiAPs to connect to
networks using Bonjour.
fortios_wireless_controller_bonjour_profile:
host: "{{ host }}"
username: "{{ username }}"
password: "{{ password }}"
vdom: "{{ vdom }}"
https: "False"
state: "present"
wireless_controller_bonjour_profile:
comment: "Comment."
name: "default_name_4"
policy_list:
-
description: "<your_own_value>"
from_vlan: "<your_own_value>"
policy_id: "8"
services: "all"
to_vlan: "<your_own_value>"
'''
RETURN = '''
build:
description: Build number of the fortigate image
returned: always
type: str
sample: '1547'
http_method:
description: Last method used to provision the content into FortiGate
returned: always
type: str
sample: 'PUT'
http_status:
description: Last result given by FortiGate on last operation applied
returned: always
type: str
sample: "200"
mkey:
description: Master key (id) used in the last call to FortiGate
returned: success
type: str
sample: "id"
name:
description: Name of the table used to fulfill the request
returned: always
type: str
sample: "urlfilter"
path:
description: Path of the table used to fulfill the request
returned: always
type: str
sample: "webfilter"
revision:
description: Internal revision number
returned: always
type: str
sample: "17.0.2.10658"
serial:
description: Serial number of the unit
returned: always
type: str
sample: "FGVMEVYYQT3AB5352"
status:
description: Indication of the operation's result
returned: always
type: str
sample: "success"
vdom:
description: Virtual domain used
returned: always
type: str
sample: "root"
version:
description: Version of the FortiGate
returned: always
type: str
sample: "v5.6.3"
'''
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.connection import Connection
from ansible.module_utils.network.fortios.fortios import FortiOSHandler
from ansible.module_utils.network.fortimanager.common import FAIL_SOCKET_MSG
def login(data, fos):
host = data['host']
username = data['username']
password = data['password']
ssl_verify = data['ssl_verify']
fos.debug('on')
if 'https' in data and not data['https']:
fos.https('off')
else:
fos.https('on')
fos.login(host, username, password, verify=ssl_verify)
def filter_wireless_controller_bonjour_profile_data(json):
option_list = ['comment', 'name', 'policy_list']
dictionary = {}
for attribute in option_list:
if attribute in json and json[attribute] is not None:
dictionary[attribute] = json[attribute]
return dictionary
def underscore_to_hyphen(data):
if isinstance(data, list):
for i, elem in enumerate(data):
data[i] = underscore_to_hyphen(elem)
elif isinstance(data, dict):
new_data = {}
for k, v in data.items():
new_data[k.replace('_', '-')] = underscore_to_hyphen(v)
data = new_data
return data
def wireless_controller_bonjour_profile(data, fos):
vdom = data['vdom']
state = data['state']
wireless_controller_bonjour_profile_data = data['wireless_controller_bonjour_profile']
filtered_data = underscore_to_hyphen(filter_wireless_controller_bonjour_profile_data(wireless_controller_bonjour_profile_data))
if state == "present":
return fos.set('wireless-controller',
'bonjour-profile',
data=filtered_data,
vdom=vdom)
elif state == "absent":
return fos.delete('wireless-controller',
'bonjour-profile',
mkey=filtered_data['name'],
vdom=vdom)
def is_successful_status(status):
return status['status'] == "success" or \
status['http_method'] == "DELETE" and status['http_status'] == 404
def fortios_wireless_controller(data, fos):
if data['wireless_controller_bonjour_profile']:
resp = wireless_controller_bonjour_profile(data, fos)
return not is_successful_status(resp), \
resp['status'] == "success", \
resp
def main():
fields = {
"host": {"required": False, "type": "str"},
"username": {"required": False, "type": "str"},
"password": {"required": False, "type": "str", "default": "", "no_log": True},
"vdom": {"required": False, "type": "str", "default": "root"},
"https": {"required": False, "type": "bool", "default": True},
"ssl_verify": {"required": False, "type": "bool", "default": True},
"state": {"required": True, "type": "str",
"choices": ["present", "absent"]},
"wireless_controller_bonjour_profile": {
"required": False, "type": "dict", "default": None,
"options": {
"comment": {"required": False, "type": "str"},
"name": {"required": True, "type": "str"},
"policy_list": {"required": False, "type": "list",
"options": {
"description": {"required": False, "type": "str"},
"from_vlan": {"required": False, "type": "str"},
"policy_id": {"required": False, "type": "int"},
"services": {"required": False, "type": "str",
"choices": ["all", "airplay", "afp",
"bit-torrent", "ftp", "ichat",
"itunes", "printers", "samba",
"scanners", "ssh", "chromecast"]},
"to_vlan": {"required": False, "type": "str"}
}}
}
}
}
module = AnsibleModule(argument_spec=fields,
supports_check_mode=False)
# legacy_mode refers to using fortiosapi instead of HTTPAPI
legacy_mode = 'host' in module.params and module.params['host'] is not None and \
'username' in module.params and module.params['username'] is not None and \
'password' in module.params and module.params['password'] is not None
if not legacy_mode:
if module._socket_path:
connection = Connection(module._socket_path)
fos = FortiOSHandler(connection)
is_error, has_changed, result = fortios_wireless_controller(module.params, fos)
else:
module.fail_json(**FAIL_SOCKET_MSG)
else:
try:
from fortiosapi import FortiOSAPI
except ImportError:
module.fail_json(msg="fortiosapi module is required")
fos = FortiOSAPI()
login(module.params, fos)
is_error, has_changed, result = fortios_wireless_controller(module.params, fos)
fos.logout()
if not is_error:
module.exit_json(changed=has_changed, meta=result)
else:
module.fail_json(msg="Error in repo", meta=result)
if __name__ == '__main__':
main()
| gpl-3.0 |
ChristinaZografou/sympy | sympy/parsing/sympy_parser.py | 29 | 32979 | """Transform a string with Python-like source code into SymPy expression. """
from __future__ import print_function, division
from .sympy_tokenize import \
generate_tokens, untokenize, TokenError, \
NUMBER, STRING, NAME, OP, ENDMARKER
from keyword import iskeyword
import ast
import re
import unicodedata
import sympy
from sympy.core.compatibility import exec_, StringIO
from sympy.core.basic import Basic
_re_repeated = re.compile(r"^(\d*)\.(\d*)\[(\d+)\]$")
def _token_splittable(token):
"""
Predicate for whether a token name can be split into multiple tokens.
A token is splittable if it does not contain an underscore character and
it is not the name of a Greek letter. This is used to implicitly convert
expressions like 'xyz' into 'x*y*z'.
"""
if '_' in token:
return False
else:
try:
return not unicodedata.lookup('GREEK SMALL LETTER ' + token)
except KeyError:
pass
if len(token) > 1:
return True
return False
def _token_callable(token, local_dict, global_dict, nextToken=None):
"""
Predicate for whether a token name represents a callable function.
Essentially wraps ``callable``, but looks up the token name in the
locals and globals.
"""
func = local_dict.get(token[1])
if not func:
func = global_dict.get(token[1])
return callable(func) and not isinstance(func, sympy.Symbol)
def _add_factorial_tokens(name, result):
if result == [] or result[-1][1] == '(':
raise TokenError()
beginning = [(NAME, name), (OP, '(')]
end = [(OP, ')')]
diff = 0
length = len(result)
for index, token in enumerate(result[::-1]):
toknum, tokval = token
i = length - index - 1
if tokval == ')':
diff += 1
elif tokval == '(':
diff -= 1
if diff == 0:
if i - 1 >= 0 and result[i - 1][0] == NAME:
return result[:i - 1] + beginning + result[i - 1:] + end
else:
return result[:i] + beginning + result[i:] + end
return result
class AppliedFunction(object):
"""
A group of tokens representing a function and its arguments.
`exponent` is for handling the shorthand sin^2, ln^2, etc.
"""
def __init__(self, function, args, exponent=None):
if exponent is None:
exponent = []
self.function = function
self.args = args
self.exponent = exponent
self.items = ['function', 'args', 'exponent']
def expand(self):
"""Return a list of tokens representing the function"""
result = []
result.append(self.function)
result.extend(self.args)
return result
def __getitem__(self, index):
return getattr(self, self.items[index])
def __repr__(self):
return "AppliedFunction(%s, %s, %s)" % (self.function, self.args,
self.exponent)
class ParenthesisGroup(list):
"""List of tokens representing an expression in parentheses."""
pass
def _flatten(result):
result2 = []
for tok in result:
if isinstance(tok, AppliedFunction):
result2.extend(tok.expand())
else:
result2.append(tok)
return result2
def _group_parentheses(recursor):
def _inner(tokens, local_dict, global_dict):
"""Group tokens between parentheses with ParenthesisGroup.
Also processes those tokens recursively.
"""
result = []
stacks = []
stacklevel = 0
for token in tokens:
if token[0] == OP:
if token[1] == '(':
stacks.append(ParenthesisGroup([]))
stacklevel += 1
elif token[1] == ')':
stacks[-1].append(token)
stack = stacks.pop()
if len(stacks) > 0:
# We don't recurse here since the upper-level stack
# would reprocess these tokens
stacks[-1].extend(stack)
else:
# Recurse here to handle nested parentheses
# Strip off the outer parentheses to avoid an infinite loop
inner = stack[1:-1]
inner = recursor(inner,
local_dict,
global_dict)
parenGroup = [stack[0]] + inner + [stack[-1]]
result.append(ParenthesisGroup(parenGroup))
stacklevel -= 1
continue
if stacklevel:
stacks[-1].append(token)
else:
result.append(token)
if stacklevel:
raise TokenError("Mismatched parentheses")
return result
return _inner
def _apply_functions(tokens, local_dict, global_dict):
"""Convert a NAME token + ParenthesisGroup into an AppliedFunction.
Note that ParenthesisGroups, if not applied to any function, are
converted back into lists of tokens.
"""
result = []
symbol = None
for tok in tokens:
if tok[0] == NAME:
symbol = tok
result.append(tok)
elif isinstance(tok, ParenthesisGroup):
if symbol and _token_callable(symbol, local_dict, global_dict):
result[-1] = AppliedFunction(symbol, tok)
symbol = None
else:
result.extend(tok)
else:
symbol = None
result.append(tok)
return result
def _implicit_multiplication(tokens, local_dict, global_dict):
"""Implicitly adds '*' tokens.
Cases:
- Two AppliedFunctions next to each other ("sin(x)cos(x)")
- AppliedFunction next to an open parenthesis ("sin x (cos x + 1)")
- A close parenthesis next to an AppliedFunction ("(x+2)sin x")\
- A close parenthesis next to an open parenthesis ("(x+2)(x+3)")
- AppliedFunction next to an implicitly applied function ("sin(x)cos x")
"""
result = []
for tok, nextTok in zip(tokens, tokens[1:]):
result.append(tok)
if (isinstance(tok, AppliedFunction) and
isinstance(nextTok, AppliedFunction)):
result.append((OP, '*'))
elif (isinstance(tok, AppliedFunction) and
nextTok[0] == OP and nextTok[1] == '('):
# Applied function followed by an open parenthesis
result.append((OP, '*'))
elif (tok[0] == OP and tok[1] == ')' and
isinstance(nextTok, AppliedFunction)):
# Close parenthesis followed by an applied function
result.append((OP, '*'))
elif (tok[0] == OP and tok[1] == ')' and
nextTok[0] == NAME):
# Close parenthesis followed by an implicitly applied function
result.append((OP, '*'))
elif (tok[0] == nextTok[0] == OP
and tok[1] == ')' and nextTok[1] == '('):
# Close parenthesis followed by an open parenthesis
result.append((OP, '*'))
elif (isinstance(tok, AppliedFunction) and nextTok[0] == NAME):
# Applied function followed by implicitly applied function
result.append((OP, '*'))
elif (tok[0] == NAME and
not _token_callable(tok, local_dict, global_dict) and
nextTok[0] == OP and nextTok[1] == '('):
# Constant followed by parenthesis
result.append((OP, '*'))
elif (tok[0] == NAME and
not _token_callable(tok, local_dict, global_dict) and
nextTok[0] == NAME and
not _token_callable(nextTok, local_dict, global_dict)):
# Constant followed by constant
result.append((OP, '*'))
elif (tok[0] == NAME and
not _token_callable(tok, local_dict, global_dict) and
(isinstance(nextTok, AppliedFunction) or nextTok[0] == NAME)):
# Constant followed by (implicitly applied) function
result.append((OP, '*'))
if tokens:
result.append(tokens[-1])
return result
def _implicit_application(tokens, local_dict, global_dict):
"""Adds parentheses as needed after functions."""
result = []
appendParen = 0 # number of closing parentheses to add
skip = 0 # number of tokens to delay before adding a ')' (to
# capture **, ^, etc.)
exponentSkip = False # skipping tokens before inserting parentheses to
# work with function exponentiation
for tok, nextTok in zip(tokens, tokens[1:]):
result.append(tok)
if (tok[0] == NAME and
nextTok[0] != OP and
nextTok[0] != ENDMARKER):
if _token_callable(tok, local_dict, global_dict, nextTok):
result.append((OP, '('))
appendParen += 1
# name followed by exponent - function exponentiation
elif (tok[0] == NAME and nextTok[0] == OP and nextTok[1] == '**'):
if _token_callable(tok, local_dict, global_dict):
exponentSkip = True
elif exponentSkip:
# if the last token added was an applied function (i.e. the
# power of the function exponent) OR a multiplication (as
# implicit multiplication would have added an extraneous
# multiplication)
if (isinstance(tok, AppliedFunction)
or (tok[0] == OP and tok[1] == '*')):
# don't add anything if the next token is a multiplication
# or if there's already a parenthesis (if parenthesis, still
# stop skipping tokens)
if not (nextTok[0] == OP and nextTok[1] == '*'):
if not(nextTok[0] == OP and nextTok[1] == '('):
result.append((OP, '('))
appendParen += 1
exponentSkip = False
elif appendParen:
if nextTok[0] == OP and nextTok[1] in ('^', '**', '*'):
skip = 1
continue
if skip:
skip -= 1
continue
result.append((OP, ')'))
appendParen -= 1
if tokens:
result.append(tokens[-1])
if appendParen:
result.extend([(OP, ')')] * appendParen)
return result
def function_exponentiation(tokens, local_dict, global_dict):
"""Allows functions to be exponentiated, e.g. ``cos**2(x)``.
Examples
========
>>> from sympy.parsing.sympy_parser import (parse_expr,
... standard_transformations, function_exponentiation)
>>> transformations = standard_transformations + (function_exponentiation,)
>>> parse_expr('sin**4(x)', transformations=transformations)
sin(x)**4
"""
result = []
exponent = []
consuming_exponent = False
level = 0
for tok, nextTok in zip(tokens, tokens[1:]):
if tok[0] == NAME and nextTok[0] == OP and nextTok[1] == '**':
if _token_callable(tok, local_dict, global_dict):
consuming_exponent = True
elif consuming_exponent:
exponent.append(tok)
# only want to stop after hitting )
if tok[0] == nextTok[0] == OP and tok[1] == ')' and nextTok[1] == '(':
consuming_exponent = False
# if implicit multiplication was used, we may have )*( instead
if tok[0] == nextTok[0] == OP and tok[1] == '*' and nextTok[1] == '(':
consuming_exponent = False
del exponent[-1]
continue
elif exponent and not consuming_exponent:
if tok[0] == OP:
if tok[1] == '(':
level += 1
elif tok[1] == ')':
level -= 1
if level == 0:
result.append(tok)
result.extend(exponent)
exponent = []
continue
result.append(tok)
if tokens:
result.append(tokens[-1])
if exponent:
result.extend(exponent)
return result
def split_symbols_custom(predicate):
"""Creates a transformation that splits symbol names.
``predicate`` should return True if the symbol name is to be split.
For instance, to retain the default behavior but avoid splitting certain
symbol names, a predicate like this would work:
>>> from sympy.parsing.sympy_parser import (parse_expr, _token_splittable,
... standard_transformations, implicit_multiplication,
... split_symbols_custom)
>>> def can_split(symbol):
... if symbol not in ('list', 'of', 'unsplittable', 'names'):
... return _token_splittable(symbol)
... return False
...
>>> transformation = split_symbols_custom(can_split)
>>> parse_expr('unsplittable', transformations=standard_transformations +
... (transformation, implicit_multiplication))
unsplittable
"""
def _split_symbols(tokens, local_dict, global_dict):
result = []
split = False
split_previous=False
for tok in tokens:
if split_previous:
# throw out closing parenthesis of Symbol that was split
split_previous=False
continue
split_previous=False
if tok[0] == NAME and tok[1] == 'Symbol':
split = True
elif split and tok[0] == NAME:
symbol = tok[1][1:-1]
if predicate(symbol):
for char in symbol:
if char in local_dict or char in global_dict:
# Get rid of the call to Symbol
del result[-2:]
result.extend([(NAME, "%s" % char),
(NAME, 'Symbol'), (OP, '(')])
else:
result.extend([(NAME, "'%s'" % char), (OP, ')'),
(NAME, 'Symbol'), (OP, '(')])
# Delete the last two tokens: get rid of the extraneous
# Symbol( we just added
# Also, set split_previous=True so will skip
# the closing parenthesis of the original Symbol
del result[-2:]
split = False
split_previous = True
continue
else:
split = False
result.append(tok)
return result
return _split_symbols
#: Splits symbol names for implicit multiplication.
#:
#: Intended to let expressions like ``xyz`` be parsed as ``x*y*z``. Does not
#: split Greek character names, so ``theta`` will *not* become
#: ``t*h*e*t*a``. Generally this should be used with
#: ``implicit_multiplication``.
split_symbols = split_symbols_custom(_token_splittable)
def implicit_multiplication(result, local_dict, global_dict):
"""Makes the multiplication operator optional in most cases.
Use this before :func:`implicit_application`, otherwise expressions like
``sin 2x`` will be parsed as ``x * sin(2)`` rather than ``sin(2*x)``.
Examples
========
>>> from sympy.parsing.sympy_parser import (parse_expr,
... standard_transformations, implicit_multiplication)
>>> transformations = standard_transformations + (implicit_multiplication,)
>>> parse_expr('3 x y', transformations=transformations)
3*x*y
"""
# These are interdependent steps, so we don't expose them separately
for step in (_group_parentheses(implicit_multiplication),
_apply_functions,
_implicit_multiplication):
result = step(result, local_dict, global_dict)
result = _flatten(result)
return result
def implicit_application(result, local_dict, global_dict):
"""Makes parentheses optional in some cases for function calls.
Use this after :func:`implicit_multiplication`, otherwise expressions
like ``sin 2x`` will be parsed as ``x * sin(2)`` rather than
``sin(2*x)``.
Examples
========
>>> from sympy.parsing.sympy_parser import (parse_expr,
... standard_transformations, implicit_application)
>>> transformations = standard_transformations + (implicit_application,)
>>> parse_expr('cot z + csc z', transformations=transformations)
cot(z) + csc(z)
"""
for step in (_group_parentheses(implicit_application),
_apply_functions,
_implicit_application,):
result = step(result, local_dict, global_dict)
result = _flatten(result)
return result
def implicit_multiplication_application(result, local_dict, global_dict):
"""Allows a slightly relaxed syntax.
- Parentheses for single-argument method calls are optional.
- Multiplication is implicit.
- Symbol names can be split (i.e. spaces are not needed between
symbols).
- Functions can be exponentiated.
Examples
========
>>> from sympy.parsing.sympy_parser import (parse_expr,
... standard_transformations, implicit_multiplication_application)
>>> parse_expr("10sin**2 x**2 + 3xyz + tan theta",
... transformations=(standard_transformations +
... (implicit_multiplication_application,)))
3*x*y*z + 10*sin(x**2)**2 + tan(theta)
"""
for step in (split_symbols, implicit_multiplication,
implicit_application, function_exponentiation):
result = step(result, local_dict, global_dict)
return result
def auto_symbol(tokens, local_dict, global_dict):
"""Inserts calls to ``Symbol`` for undefined variables."""
result = []
prevTok = (None, None)
tokens.append((None, None)) # so zip traverses all tokens
for tok, nextTok in zip(tokens, tokens[1:]):
tokNum, tokVal = tok
nextTokNum, nextTokVal = nextTok
if tokNum == NAME:
name = tokVal
if (name in ['True', 'False', 'None']
or iskeyword(name)
or name in local_dict
# Don't convert attribute access
or (prevTok[0] == OP and prevTok[1] == '.')
# Don't convert keyword arguments
or (prevTok[0] == OP and prevTok[1] in ('(', ',')
and nextTokNum == OP and nextTokVal == '=')):
result.append((NAME, name))
continue
elif name in global_dict:
obj = global_dict[name]
if isinstance(obj, (Basic, type)) or callable(obj):
result.append((NAME, name))
continue
result.extend([
(NAME, 'Symbol'),
(OP, '('),
(NAME, repr(str(name))),
(OP, ')'),
])
else:
result.append((tokNum, tokVal))
prevTok = (tokNum, tokVal)
return result
def lambda_notation(tokens, local_dict, global_dict):
"""Substitutes "lambda" with its Sympy equivalent Lambda().
However, the conversion doesn't take place if only "lambda"
is passed because that is a syntax error.
"""
result = []
flag = False
toknum, tokval = tokens[0]
tokLen = len(tokens)
if toknum == NAME and tokval == 'lambda':
if tokLen == 2:
result.extend(tokens)
elif tokLen > 2:
result.extend([
(NAME, 'Lambda'),
(OP, '('),
(OP, '('),
(OP, ')'),
(OP, ')'),
])
for tokNum, tokVal in tokens[1:]:
if tokNum == OP and tokVal == ':':
tokVal = ','
flag = True
if not flag and tokNum == OP and tokVal in ['*', '**']:
raise TokenError("Starred arguments in lambda not supported")
if flag:
result.insert(-1, (tokNum, tokVal))
else:
result.insert(-2, (tokNum, tokVal))
else:
result.extend(tokens)
return result
def factorial_notation(tokens, local_dict, global_dict):
"""Allows standard notation for factorial."""
result = []
prevtoken = ''
for toknum, tokval in tokens:
if toknum == OP:
op = tokval
if op == '!!':
if prevtoken == '!' or prevtoken == '!!':
raise TokenError
result = _add_factorial_tokens('factorial2', result)
elif op == '!':
if prevtoken == '!' or prevtoken == '!!':
raise TokenError
result = _add_factorial_tokens('factorial', result)
else:
result.append((OP, op))
else:
result.append((toknum, tokval))
prevtoken = tokval
return result
def convert_xor(tokens, local_dict, global_dict):
"""Treats XOR, ``^``, as exponentiation, ``**``."""
result = []
for toknum, tokval in tokens:
if toknum == OP:
if tokval == '^':
result.append((OP, '**'))
else:
result.append((toknum, tokval))
else:
result.append((toknum, tokval))
return result
def auto_number(tokens, local_dict, global_dict):
"""Converts numeric literals to use SymPy equivalents.
Complex numbers use ``I``; integer literals use ``Integer``, float
literals use ``Float``, and repeating decimals use ``Rational``.
"""
result = []
prevtoken = ''
for toknum, tokval in tokens:
if toknum == NUMBER:
number = tokval
postfix = []
if number.endswith('j') or number.endswith('J'):
number = number[:-1]
postfix = [(OP, '*'), (NAME, 'I')]
if '.' in number or (('e' in number or 'E' in number) and
not (number.startswith('0x') or number.startswith('0X'))):
match = _re_repeated.match(number)
if match is not None:
# Clear repeating decimals, e.g. 3.4[31] -> (3 + 4/10 + 31/990)
pre, post, repetend = match.groups()
zeros = '0'*len(post)
post, repetends = [w.lstrip('0') for w in [post, repetend]]
# or else interpreted as octal
a = pre or '0'
b, c = post or '0', '1' + zeros
d, e = repetends, ('9'*len(repetend)) + zeros
seq = [
(OP, '('),
(NAME,
'Integer'), (OP, '('), (NUMBER, a), (OP, ')'),
(OP, '+'),
(NAME, 'Rational'), (OP, '('), (
NUMBER, b), (OP, ','), (NUMBER, c), (OP, ')'),
(OP, '+'),
(NAME, 'Rational'), (OP, '('), (
NUMBER, d), (OP, ','), (NUMBER, e), (OP, ')'),
(OP, ')'),
]
else:
seq = [(NAME, 'Float'), (OP, '('),
(NUMBER, repr(str(number))), (OP, ')')]
else:
seq = [(NAME, 'Integer'), (OP, '('), (
NUMBER, number), (OP, ')')]
result.extend(seq + postfix)
else:
result.append((toknum, tokval))
return result
def rationalize(tokens, local_dict, global_dict):
"""Converts floats into ``Rational``. Run AFTER ``auto_number``."""
result = []
passed_float = False
for toknum, tokval in tokens:
if toknum == NAME:
if tokval == 'Float':
passed_float = True
tokval = 'Rational'
result.append((toknum, tokval))
elif passed_float == True and toknum == NUMBER:
passed_float = False
result.append((STRING, tokval))
else:
result.append((toknum, tokval))
return result
def _transform_equals_sign(tokens, local_dict, global_dict):
"""Transforms the equals sign ``=`` to instances of Eq.
This is a helper function for `convert_equals_signs`.
Works with expressions containing one equals sign and no
nesting. Expressions like `(1=2)=False` won't work with this
and should be used with `convert_equals_signs`.
Examples: 1=2 to Eq(1,2)
1*2=x to Eq(1*2, x)
This does not deal with function arguments yet.
"""
result = []
if (OP, "=") in tokens:
result.append((NAME, "Eq"))
result.append((OP, "("))
for index, token in enumerate(tokens):
if token == (OP, "="):
result.append((OP, ","))
continue
result.append(token)
result.append((OP, ")"))
else:
result = tokens
return result
def convert_equals_signs(result, local_dict, global_dict):
""" Transforms all the equals signs ``=`` to instances of Eq.
Parses the equals signs in the expression and replaces them with
appropriate Eq instances.Also works with nested equals signs.
Does not yet play well with function arguments.
For example, the expression `(x=y)` is ambiguous and can be interpreted
as x being an argument to a function and `convert_equals_signs` won't
work for this.
See also
========
convert_equality_operators
Examples:
=========
>>> from sympy.parsing.sympy_parser import (parse_expr,
... standard_transformations, convert_equals_signs)
>>> parse_expr("1*2=x", transformations=(
... standard_transformations + (convert_equals_signs,)))
Eq(2, x)
>>> parse_expr("(1*2=x)=False", transformations=(
... standard_transformations + (convert_equals_signs,)))
Eq(Eq(2, x), False)
"""
for step in (_group_parentheses(convert_equals_signs),
_apply_functions,
_transform_equals_sign):
result = step(result, local_dict, global_dict)
result = _flatten(result)
return result
#: Standard transformations for :func:`parse_expr`.
#: Inserts calls to :class:`Symbol`, :class:`Integer`, and other SymPy
#: datatypes and allows the use of standard factorial notation (e.g. ``x!``).
standard_transformations = (lambda_notation, auto_symbol, auto_number, factorial_notation)
def stringify_expr(s, local_dict, global_dict, transformations):
"""
Converts the string ``s`` to Python code, in ``local_dict``
Generally, ``parse_expr`` should be used.
"""
tokens = []
input_code = StringIO(s.strip())
for toknum, tokval, _, _, _ in generate_tokens(input_code.readline):
tokens.append((toknum, tokval))
for transform in transformations:
tokens = transform(tokens, local_dict, global_dict)
return untokenize(tokens)
def eval_expr(code, local_dict, global_dict):
"""
Evaluate Python code generated by ``stringify_expr``.
Generally, ``parse_expr`` should be used.
"""
expr = eval(
code, global_dict, local_dict) # take local objects in preference
return expr
def parse_expr(s, local_dict=None, transformations=standard_transformations,
global_dict=None, evaluate=True):
"""Converts the string ``s`` to a SymPy expression, in ``local_dict``
Parameters
==========
s : str
The string to parse.
local_dict : dict, optional
A dictionary of local variables to use when parsing.
global_dict : dict, optional
A dictionary of global variables. By default, this is initialized
with ``from sympy import *``; provide this parameter to override
this behavior (for instance, to parse ``"Q & S"``).
transformations : tuple, optional
A tuple of transformation functions used to modify the tokens of the
parsed expression before evaluation. The default transformations
convert numeric literals into their SymPy equivalents, convert
undefined variables into SymPy symbols, and allow the use of standard
mathematical factorial notation (e.g. ``x!``).
evaluate : bool, optional
When False, the order of the arguments will remain as they were in the
string and automatic simplification that would normally occur is
suppressed. (see examples)
Examples
========
>>> from sympy.parsing.sympy_parser import parse_expr
>>> parse_expr("1/2")
1/2
>>> type(_)
<class 'sympy.core.numbers.Half'>
>>> from sympy.parsing.sympy_parser import standard_transformations,\\
... implicit_multiplication_application
>>> transformations = (standard_transformations +
... (implicit_multiplication_application,))
>>> parse_expr("2x", transformations=transformations)
2*x
When evaluate=False, some automatic simplifications will not occur:
>>> parse_expr("2**3"), parse_expr("2**3", evaluate=False)
(8, 2**3)
In addition the order of the arguments will not be made canonical.
This feature allows one to tell exactly how the expression was entered:
>>> a = parse_expr('1 + x', evaluate=False)
>>> b = parse_expr('x + 1', evaluate=0)
>>> a == b
False
>>> a.args
(1, x)
>>> b.args
(x, 1)
See Also
========
stringify_expr, eval_expr, standard_transformations,
implicit_multiplication_application
"""
if local_dict is None:
local_dict = {}
if global_dict is None:
global_dict = {}
exec_('from sympy import *', global_dict)
code = stringify_expr(s, local_dict, global_dict, transformations)
if not evaluate:
code = compile(evaluateFalse(code), '<string>', 'eval')
return eval_expr(code, local_dict, global_dict)
def evaluateFalse(s):
"""
Replaces operators with the SymPy equivalent and sets evaluate=False.
"""
node = ast.parse(s)
node = EvaluateFalseTransformer().visit(node)
# node is a Module, we want an Expression
node = ast.Expression(node.body[0].value)
return ast.fix_missing_locations(node)
class EvaluateFalseTransformer(ast.NodeTransformer):
operators = {
ast.Add: 'Add',
ast.Mult: 'Mul',
ast.Pow: 'Pow',
ast.Sub: 'Add',
ast.Div: 'Mul',
ast.BitOr: 'Or',
ast.BitAnd: 'And',
ast.BitXor: 'Not',
}
def flatten(self, args, func):
result = []
for arg in args:
if isinstance(arg, ast.Call) and arg.func.id == func:
result.extend(self.flatten(arg.args, func))
else:
result.append(arg)
return result
def visit_BinOp(self, node):
if node.op.__class__ in self.operators:
sympy_class = self.operators[node.op.__class__]
right = self.visit(node.right)
left = self.visit(node.left)
if isinstance(node.left, ast.UnaryOp) and (isinstance(node.right, ast.UnaryOp) == 0) and sympy_class in ('Mul',):
left, right = right, left
if isinstance(node.op, ast.Sub):
right = ast.UnaryOp(op=ast.USub(), operand=right)
if isinstance(node.op, ast.Div):
if isinstance(node.left, ast.UnaryOp):
if isinstance(node.right,ast.UnaryOp):
left, right = right, left
left = ast.Call(
func=ast.Name(id='Pow', ctx=ast.Load()),
args=[left, ast.UnaryOp(op=ast.USub(), operand=ast.Num(1))],
keywords=[ast.keyword(arg='evaluate', value=ast.Name(id='False', ctx=ast.Load()))],
starargs=None,
kwargs=None
)
else:
right = ast.Call(
func=ast.Name(id='Pow', ctx=ast.Load()),
args=[right, ast.UnaryOp(op=ast.USub(), operand=ast.Num(1))],
keywords=[ast.keyword(arg='evaluate', value=ast.Name(id='False', ctx=ast.Load()))],
starargs=None,
kwargs=None
)
new_node = ast.Call(
func=ast.Name(id=sympy_class, ctx=ast.Load()),
args=[left, right],
keywords=[ast.keyword(arg='evaluate', value=ast.Name(id='False', ctx=ast.Load()))],
starargs=None,
kwargs=None
)
if sympy_class in ('Add', 'Mul'):
# Denest Add or Mul as appropriate
new_node.args = self.flatten(new_node.args, sympy_class)
return new_node
return node
| bsd-3-clause |
diegoguimaraes/django | tests/admin_widgets/tests.py | 8 | 53006 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from datetime import datetime, timedelta
import gettext
from importlib import import_module
import os
from unittest import TestCase, skipIf
try:
import pytz
except ImportError:
pytz = None
from django import forms
from django.conf import settings
from django.contrib import admin
from django.contrib.admin import widgets
from django.contrib.admin.tests import AdminSeleniumWebDriverTestCase
from django.core.files.storage import default_storage
from django.core.files.uploadedfile import SimpleUploadedFile
from django.db.models import CharField, DateField
from django.test import TestCase as DjangoTestCase
from django.test import override_settings
from django.utils import six
from django.utils import translation
from . import models
from .widgetadmin import site as widget_admin_site
admin_static_prefix = lambda: {
'ADMIN_STATIC_PREFIX': "%sadmin/" % settings.STATIC_URL,
}
class AdminFormfieldForDBFieldTests(TestCase):
"""
Tests for correct behavior of ModelAdmin.formfield_for_dbfield
"""
def assertFormfield(self, model, fieldname, widgetclass, **admin_overrides):
"""
Helper to call formfield_for_dbfield for a given model and field name
and verify that the returned formfield is appropriate.
"""
# Override any settings on the model admin
class MyModelAdmin(admin.ModelAdmin):
pass
for k in admin_overrides:
setattr(MyModelAdmin, k, admin_overrides[k])
# Construct the admin, and ask it for a formfield
ma = MyModelAdmin(model, admin.site)
ff = ma.formfield_for_dbfield(model._meta.get_field(fieldname), request=None)
# "unwrap" the widget wrapper, if needed
if isinstance(ff.widget, widgets.RelatedFieldWidgetWrapper):
widget = ff.widget.widget
else:
widget = ff.widget
# Check that we got a field of the right type
self.assertTrue(
isinstance(widget, widgetclass),
"Wrong widget for %s.%s: expected %s, got %s" % (
model.__class__.__name__,
fieldname,
widgetclass,
type(widget),
)
)
# Return the formfield so that other tests can continue
return ff
def test_DateField(self):
self.assertFormfield(models.Event, 'start_date', widgets.AdminDateWidget)
def test_DateTimeField(self):
self.assertFormfield(models.Member, 'birthdate', widgets.AdminSplitDateTime)
def test_TimeField(self):
self.assertFormfield(models.Event, 'start_time', widgets.AdminTimeWidget)
def test_TextField(self):
self.assertFormfield(models.Event, 'description', widgets.AdminTextareaWidget)
def test_URLField(self):
self.assertFormfield(models.Event, 'link', widgets.AdminURLFieldWidget)
def test_IntegerField(self):
self.assertFormfield(models.Event, 'min_age', widgets.AdminIntegerFieldWidget)
def test_CharField(self):
self.assertFormfield(models.Member, 'name', widgets.AdminTextInputWidget)
def test_EmailField(self):
self.assertFormfield(models.Member, 'email', widgets.AdminEmailInputWidget)
def test_FileField(self):
self.assertFormfield(models.Album, 'cover_art', widgets.AdminFileWidget)
def test_ForeignKey(self):
self.assertFormfield(models.Event, 'main_band', forms.Select)
def test_raw_id_ForeignKey(self):
self.assertFormfield(models.Event, 'main_band', widgets.ForeignKeyRawIdWidget,
raw_id_fields=['main_band'])
def test_radio_fields_ForeignKey(self):
ff = self.assertFormfield(models.Event, 'main_band', widgets.AdminRadioSelect,
radio_fields={'main_band': admin.VERTICAL})
self.assertEqual(ff.empty_label, None)
def test_many_to_many(self):
self.assertFormfield(models.Band, 'members', forms.SelectMultiple)
def test_raw_id_many_to_many(self):
self.assertFormfield(models.Band, 'members', widgets.ManyToManyRawIdWidget,
raw_id_fields=['members'])
def test_filtered_many_to_many(self):
self.assertFormfield(models.Band, 'members', widgets.FilteredSelectMultiple,
filter_vertical=['members'])
def test_formfield_overrides(self):
self.assertFormfield(models.Event, 'start_date', forms.TextInput,
formfield_overrides={DateField: {'widget': forms.TextInput}})
def test_formfield_overrides_widget_instances(self):
"""
Test that widget instances in formfield_overrides are not shared between
different fields. (#19423)
"""
class BandAdmin(admin.ModelAdmin):
formfield_overrides = {
CharField: {'widget': forms.TextInput(attrs={'size': '10'})}
}
ma = BandAdmin(models.Band, admin.site)
f1 = ma.formfield_for_dbfield(models.Band._meta.get_field('name'), request=None)
f2 = ma.formfield_for_dbfield(models.Band._meta.get_field('style'), request=None)
self.assertNotEqual(f1.widget, f2.widget)
self.assertEqual(f1.widget.attrs['maxlength'], '100')
self.assertEqual(f2.widget.attrs['maxlength'], '20')
self.assertEqual(f2.widget.attrs['size'], '10')
def test_field_with_choices(self):
self.assertFormfield(models.Member, 'gender', forms.Select)
def test_choices_with_radio_fields(self):
self.assertFormfield(models.Member, 'gender', widgets.AdminRadioSelect,
radio_fields={'gender': admin.VERTICAL})
def test_inheritance(self):
self.assertFormfield(models.Album, 'backside_art', widgets.AdminFileWidget)
def test_m2m_widgets(self):
"""m2m fields help text as it applies to admin app (#9321)."""
class AdvisorAdmin(admin.ModelAdmin):
filter_vertical = ['companies']
self.assertFormfield(models.Advisor, 'companies', widgets.FilteredSelectMultiple,
filter_vertical=['companies'])
ma = AdvisorAdmin(models.Advisor, admin.site)
f = ma.formfield_for_dbfield(models.Advisor._meta.get_field('companies'), request=None)
self.assertEqual(six.text_type(f.help_text), 'Hold down "Control", or "Command" on a Mac, to select more than one.')
@override_settings(PASSWORD_HASHERS=('django.contrib.auth.hashers.SHA1PasswordHasher',),
ROOT_URLCONF='admin_widgets.urls')
class AdminFormfieldForDBFieldWithRequestTests(DjangoTestCase):
fixtures = ["admin-widgets-users.xml"]
def test_filter_choices_by_request_user(self):
"""
Ensure the user can only see their own cars in the foreign key dropdown.
"""
self.client.login(username="super", password="secret")
response = self.client.get("/admin_widgets/cartire/add/")
self.assertNotContains(response, "BMW M3")
self.assertContains(response, "Volkswagon Passat")
@override_settings(PASSWORD_HASHERS=('django.contrib.auth.hashers.SHA1PasswordHasher',),
ROOT_URLCONF='admin_widgets.urls')
class AdminForeignKeyWidgetChangeList(DjangoTestCase):
fixtures = ["admin-widgets-users.xml"]
def setUp(self):
self.client.login(username="super", password="secret")
def tearDown(self):
self.client.logout()
def test_changelist_ForeignKey(self):
response = self.client.get('/admin_widgets/car/')
self.assertContains(response, '/auth/user/add/')
@override_settings(PASSWORD_HASHERS=('django.contrib.auth.hashers.SHA1PasswordHasher',),
ROOT_URLCONF='admin_widgets.urls')
class AdminForeignKeyRawIdWidget(DjangoTestCase):
fixtures = ["admin-widgets-users.xml"]
def setUp(self):
self.client.login(username="super", password="secret")
def tearDown(self):
self.client.logout()
def test_nonexistent_target_id(self):
band = models.Band.objects.create(name='Bogey Blues')
pk = band.pk
band.delete()
post_data = {
"main_band": '%s' % pk,
}
# Try posting with a non-existent pk in a raw id field: this
# should result in an error message, not a server exception.
response = self.client.post('/admin_widgets/event/add/', post_data)
self.assertContains(response,
'Select a valid choice. That choice is not one of the available choices.')
def test_invalid_target_id(self):
for test_str in ('Iñtërnâtiônàlizætiøn', "1234'", -1234):
# This should result in an error message, not a server exception.
response = self.client.post('/admin_widgets/event/add/',
{"main_band": test_str})
self.assertContains(response,
'Select a valid choice. That choice is not one of the available choices.')
def test_url_params_from_lookup_dict_any_iterable(self):
lookup1 = widgets.url_params_from_lookup_dict({'color__in': ('red', 'blue')})
lookup2 = widgets.url_params_from_lookup_dict({'color__in': ['red', 'blue']})
self.assertEqual(lookup1, {'color__in': 'red,blue'})
self.assertEqual(lookup1, lookup2)
def test_url_params_from_lookup_dict_callable(self):
def my_callable():
return 'works'
lookup1 = widgets.url_params_from_lookup_dict({'myfield': my_callable})
lookup2 = widgets.url_params_from_lookup_dict({'myfield': my_callable()})
self.assertEqual(lookup1, lookup2)
class FilteredSelectMultipleWidgetTest(DjangoTestCase):
def test_render(self):
w = widgets.FilteredSelectMultiple('test', False)
self.assertHTMLEqual(
w.render('test', 'test'),
'<select multiple="multiple" name="test" class="selectfilter">\n</select><script type="text/javascript">addEvent(window, "load", function(e) {SelectFilter.init("id_test", "test", 0, "%(ADMIN_STATIC_PREFIX)s"); });</script>\n' % admin_static_prefix()
)
def test_stacked_render(self):
w = widgets.FilteredSelectMultiple('test', True)
self.assertHTMLEqual(
w.render('test', 'test'),
'<select multiple="multiple" name="test" class="selectfilterstacked">\n</select><script type="text/javascript">addEvent(window, "load", function(e) {SelectFilter.init("id_test", "test", 1, "%(ADMIN_STATIC_PREFIX)s"); });</script>\n' % admin_static_prefix()
)
class AdminDateWidgetTest(DjangoTestCase):
def test_attrs(self):
"""
Ensure that user-supplied attrs are used.
Refs #12073.
"""
w = widgets.AdminDateWidget()
self.assertHTMLEqual(
w.render('test', datetime(2007, 12, 1, 9, 30)),
'<input value="2007-12-01" type="text" class="vDateField" name="test" size="10" />',
)
# pass attrs to widget
w = widgets.AdminDateWidget(attrs={'size': 20, 'class': 'myDateField'})
self.assertHTMLEqual(
w.render('test', datetime(2007, 12, 1, 9, 30)),
'<input value="2007-12-01" type="text" class="myDateField" name="test" size="20" />',
)
class AdminTimeWidgetTest(DjangoTestCase):
def test_attrs(self):
"""
Ensure that user-supplied attrs are used.
Refs #12073.
"""
w = widgets.AdminTimeWidget()
self.assertHTMLEqual(
w.render('test', datetime(2007, 12, 1, 9, 30)),
'<input value="09:30:00" type="text" class="vTimeField" name="test" size="8" />',
)
# pass attrs to widget
w = widgets.AdminTimeWidget(attrs={'size': 20, 'class': 'myTimeField'})
self.assertHTMLEqual(
w.render('test', datetime(2007, 12, 1, 9, 30)),
'<input value="09:30:00" type="text" class="myTimeField" name="test" size="20" />',
)
class AdminSplitDateTimeWidgetTest(DjangoTestCase):
def test_render(self):
w = widgets.AdminSplitDateTime()
self.assertHTMLEqual(
w.render('test', datetime(2007, 12, 1, 9, 30)),
'<p class="datetime">Date: <input value="2007-12-01" type="text" class="vDateField" name="test_0" size="10" /><br />Time: <input value="09:30:00" type="text" class="vTimeField" name="test_1" size="8" /></p>',
)
def test_localization(self):
w = widgets.AdminSplitDateTime()
with self.settings(USE_L10N=True), translation.override('de-at'):
w.is_localized = True
self.assertHTMLEqual(
w.render('test', datetime(2007, 12, 1, 9, 30)),
'<p class="datetime">Datum: <input value="01.12.2007" type="text" class="vDateField" name="test_0" size="10" /><br />Zeit: <input value="09:30:00" type="text" class="vTimeField" name="test_1" size="8" /></p>',
)
class AdminURLWidgetTest(DjangoTestCase):
def test_render(self):
w = widgets.AdminURLFieldWidget()
self.assertHTMLEqual(
w.render('test', ''),
'<input class="vURLField" name="test" type="url" />'
)
self.assertHTMLEqual(
w.render('test', 'http://example.com'),
'<p class="url">Currently:<a href="http://example.com">http://example.com</a><br />Change:<input class="vURLField" name="test" type="url" value="http://example.com" /></p>'
)
def test_render_idn(self):
w = widgets.AdminURLFieldWidget()
self.assertHTMLEqual(
w.render('test', 'http://example-äüö.com'),
'<p class="url">Currently: <a href="http://xn--example--7za4pnc.com">http://example-äüö.com</a><br />Change:<input class="vURLField" name="test" type="url" value="http://example-äüö.com" /></p>'
)
def test_render_quoting(self):
# WARNING: Don't use assertHTMLEqual in that testcase!
# assertHTMLEqual will get rid of some escapes which are tested here!
w = widgets.AdminURLFieldWidget()
self.assertEqual(
w.render('test', 'http://example.com/<sometag>some text</sometag>'),
'<p class="url">Currently: <a href="http://example.com/%3Csometag%3Esome%20text%3C/sometag%3E">http://example.com/<sometag>some text</sometag></a><br />Change: <input class="vURLField" name="test" type="url" value="http://example.com/<sometag>some text</sometag>" /></p>'
)
self.assertEqual(
w.render('test', 'http://example-äüö.com/<sometag>some text</sometag>'),
'<p class="url">Currently: <a href="http://xn--example--7za4pnc.com/%3Csometag%3Esome%20text%3C/sometag%3E">http://example-äüö.com/<sometag>some text</sometag></a><br />Change: <input class="vURLField" name="test" type="url" value="http://example-äüö.com/<sometag>some text</sometag>" /></p>'
)
self.assertEqual(
w.render('test', 'http://www.example.com/%C3%A4"><script>alert("XSS!")</script>"'),
'<p class="url">Currently: <a href="http://www.example.com/%C3%A4%22%3E%3Cscript%3Ealert(%22XSS!%22)%3C/script%3E%22">http://www.example.com/%C3%A4"><script>alert("XSS!")</script>"</a><br />Change: <input class="vURLField" name="test" type="url" value="http://www.example.com/%C3%A4"><script>alert("XSS!")</script>"" /></p>'
)
class AdminFileWidgetTest(DjangoTestCase):
def test_render(self):
band = models.Band.objects.create(name='Linkin Park')
album = band.album_set.create(
name='Hybrid Theory', cover_art=r'albums\hybrid_theory.jpg'
)
w = widgets.AdminFileWidget()
self.assertHTMLEqual(
w.render('test', album.cover_art),
'<p class="file-upload">Currently: <a href="%(STORAGE_URL)salbums/hybrid_theory.jpg">albums\hybrid_theory.jpg</a> <span class="clearable-file-input"><input type="checkbox" name="test-clear" id="test-clear_id" /> <label for="test-clear_id">Clear</label></span><br />Change: <input type="file" name="test" /></p>' % {
'STORAGE_URL': default_storage.url('')
},
)
self.assertHTMLEqual(
w.render('test', SimpleUploadedFile('test', b'content')),
'<input type="file" name="test" />',
)
@override_settings(ROOT_URLCONF='admin_widgets.urls')
class ForeignKeyRawIdWidgetTest(DjangoTestCase):
def test_render(self):
band = models.Band.objects.create(name='Linkin Park')
band.album_set.create(
name='Hybrid Theory', cover_art=r'albums\hybrid_theory.jpg'
)
rel = models.Album._meta.get_field('band').rel
w = widgets.ForeignKeyRawIdWidget(rel, widget_admin_site)
self.assertHTMLEqual(
w.render('test', band.pk, attrs={}), (
'<input type="text" name="test" value="%(bandpk)s" class="vForeignKeyRawIdAdminField" />'
'<a href="/admin_widgets/band/?_to_field=id" class="related-lookup" id="lookup_id_test" title="Lookup"></a>'
' <strong>Linkin Park</strong>'
) % {'bandpk': band.pk}
)
def test_relations_to_non_primary_key(self):
# Check that ForeignKeyRawIdWidget works with fields which aren't
# related to the model's primary key.
apple = models.Inventory.objects.create(barcode=86, name='Apple')
models.Inventory.objects.create(barcode=22, name='Pear')
core = models.Inventory.objects.create(
barcode=87, name='Core', parent=apple
)
rel = models.Inventory._meta.get_field('parent').rel
w = widgets.ForeignKeyRawIdWidget(rel, widget_admin_site)
self.assertHTMLEqual(
w.render('test', core.parent_id, attrs={}), (
'<input type="text" name="test" value="86" class="vForeignKeyRawIdAdminField" />'
'<a href="/admin_widgets/inventory/?_to_field=barcode" class="related-lookup" id="lookup_id_test" title="Lookup">'
'</a> <strong>Apple</strong>'
)
)
def test_fk_related_model_not_in_admin(self):
# FK to a model not registered with admin site. Raw ID widget should
# have no magnifying glass link. See #16542
big_honeycomb = models.Honeycomb.objects.create(location='Old tree')
big_honeycomb.bee_set.create()
rel = models.Bee._meta.get_field('honeycomb').rel
w = widgets.ForeignKeyRawIdWidget(rel, widget_admin_site)
self.assertHTMLEqual(
w.render('honeycomb_widget', big_honeycomb.pk, attrs={}),
'<input type="text" name="honeycomb_widget" value="%(hcombpk)s" /> <strong>Honeycomb object</strong>' % {'hcombpk': big_honeycomb.pk}
)
def test_fk_to_self_model_not_in_admin(self):
# FK to self, not registered with admin site. Raw ID widget should have
# no magnifying glass link. See #16542
subject1 = models.Individual.objects.create(name='Subject #1')
models.Individual.objects.create(name='Child', parent=subject1)
rel = models.Individual._meta.get_field('parent').rel
w = widgets.ForeignKeyRawIdWidget(rel, widget_admin_site)
self.assertHTMLEqual(
w.render('individual_widget', subject1.pk, attrs={}),
'<input type="text" name="individual_widget" value="%(subj1pk)s" /> <strong>Individual object</strong>' % {'subj1pk': subject1.pk}
)
def test_proper_manager_for_label_lookup(self):
# see #9258
rel = models.Inventory._meta.get_field('parent').rel
w = widgets.ForeignKeyRawIdWidget(rel, widget_admin_site)
hidden = models.Inventory.objects.create(
barcode=93, name='Hidden', hidden=True
)
child_of_hidden = models.Inventory.objects.create(
barcode=94, name='Child of hidden', parent=hidden
)
self.assertHTMLEqual(
w.render('test', child_of_hidden.parent_id, attrs={}), (
'<input type="text" name="test" value="93" class="vForeignKeyRawIdAdminField" />'
'<a href="/admin_widgets/inventory/?_to_field=barcode" class="related-lookup" id="lookup_id_test" title="Lookup">'
'</a> <strong>Hidden</strong>'
)
)
@override_settings(ROOT_URLCONF='admin_widgets.urls')
class ManyToManyRawIdWidgetTest(DjangoTestCase):
def test_render(self):
band = models.Band.objects.create(name='Linkin Park')
m1 = models.Member.objects.create(name='Chester')
m2 = models.Member.objects.create(name='Mike')
band.members.add(m1, m2)
rel = models.Band._meta.get_field('members').rel
w = widgets.ManyToManyRawIdWidget(rel, widget_admin_site)
self.assertHTMLEqual(
w.render('test', [m1.pk, m2.pk], attrs={}), (
'<input type="text" name="test" value="%(m1pk)s,%(m2pk)s" class="vManyToManyRawIdAdminField" />'
'<a href="/admin_widgets/member/" class="related-lookup" id="lookup_id_test" title="Lookup"></a>'
) % dict(m1pk=m1.pk, m2pk=m2.pk)
)
self.assertHTMLEqual(
w.render('test', [m1.pk]), (
'<input type="text" name="test" value="%(m1pk)s" class="vManyToManyRawIdAdminField">'
'<a href="/admin_widgets/member/" class="related-lookup" id="lookup_id_test" title="Lookup"></a>'
) % dict(m1pk=m1.pk)
)
def test_m2m_related_model_not_in_admin(self):
# M2M relationship with model not registered with admin site. Raw ID
# widget should have no magnifying glass link. See #16542
consultor1 = models.Advisor.objects.create(name='Rockstar Techie')
c1 = models.Company.objects.create(name='Doodle')
c2 = models.Company.objects.create(name='Pear')
consultor1.companies.add(c1, c2)
rel = models.Advisor._meta.get_field('companies').rel
w = widgets.ManyToManyRawIdWidget(rel, widget_admin_site)
self.assertHTMLEqual(
w.render('company_widget1', [c1.pk, c2.pk], attrs={}),
'<input type="text" name="company_widget1" value="%(c1pk)s,%(c2pk)s" />' % {'c1pk': c1.pk, 'c2pk': c2.pk}
)
self.assertHTMLEqual(
w.render('company_widget2', [c1.pk]),
'<input type="text" name="company_widget2" value="%(c1pk)s" />' % {'c1pk': c1.pk}
)
class RelatedFieldWidgetWrapperTests(DjangoTestCase):
def test_no_can_add_related(self):
rel = models.Individual._meta.get_field('parent').rel
w = widgets.AdminRadioSelect()
# Used to fail with a name error.
w = widgets.RelatedFieldWidgetWrapper(w, rel, widget_admin_site)
self.assertFalse(w.can_add_related)
@override_settings(PASSWORD_HASHERS=('django.contrib.auth.hashers.SHA1PasswordHasher',),
ROOT_URLCONF='admin_widgets.urls')
class DateTimePickerSeleniumFirefoxTests(AdminSeleniumWebDriverTestCase):
available_apps = ['admin_widgets'] + AdminSeleniumWebDriverTestCase.available_apps
fixtures = ['admin-widgets-users.xml']
webdriver_class = 'selenium.webdriver.firefox.webdriver.WebDriver'
def test_show_hide_date_time_picker_widgets(self):
"""
Ensure that pressing the ESC key closes the date and time picker
widgets.
Refs #17064.
"""
from selenium.webdriver.common.keys import Keys
self.admin_login(username='super', password='secret', login_url='/')
# Open a page that has a date and time picker widgets
self.selenium.get('%s%s' % (self.live_server_url,
'/admin_widgets/member/add/'))
# First, with the date picker widget ---------------------------------
# Check that the date picker is hidden
self.assertEqual(
self.get_css_value('#calendarbox0', 'display'), 'none')
# Click the calendar icon
self.selenium.find_element_by_id('calendarlink0').click()
# Check that the date picker is visible
self.assertEqual(
self.get_css_value('#calendarbox0', 'display'), 'block')
# Press the ESC key
self.selenium.find_element_by_tag_name('body').send_keys([Keys.ESCAPE])
# Check that the date picker is hidden again
self.assertEqual(
self.get_css_value('#calendarbox0', 'display'), 'none')
# Then, with the time picker widget ----------------------------------
# Check that the time picker is hidden
self.assertEqual(
self.get_css_value('#clockbox0', 'display'), 'none')
# Click the time icon
self.selenium.find_element_by_id('clocklink0').click()
# Check that the time picker is visible
self.assertEqual(
self.get_css_value('#clockbox0', 'display'), 'block')
# Press the ESC key
self.selenium.find_element_by_tag_name('body').send_keys([Keys.ESCAPE])
# Check that the time picker is hidden again
self.assertEqual(
self.get_css_value('#clockbox0', 'display'), 'none')
def test_calendar_nonday_class(self):
"""
Ensure cells that are not days of the month have the `nonday` CSS class.
Refs #4574.
"""
self.admin_login(username='super', password='secret', login_url='/')
# Open a page that has a date and time picker widgets
self.selenium.get('%s%s' % (self.live_server_url,
'/admin_widgets/member/add/'))
# fill in the birth date.
self.selenium.find_element_by_id('id_birthdate_0').send_keys('2013-06-01')
# Click the calendar icon
self.selenium.find_element_by_id('calendarlink0').click()
# get all the tds within the calendar
calendar0 = self.selenium.find_element_by_id('calendarin0')
tds = calendar0.find_elements_by_tag_name('td')
# make sure the first and last 6 cells have class nonday
for td in tds[:6] + tds[-6:]:
self.assertEqual(td.get_attribute('class'), 'nonday')
def test_calendar_selected_class(self):
"""
Ensure cell for the day in the input has the `selected` CSS class.
Refs #4574.
"""
self.admin_login(username='super', password='secret', login_url='/')
# Open a page that has a date and time picker widgets
self.selenium.get('%s%s' % (self.live_server_url,
'/admin_widgets/member/add/'))
# fill in the birth date.
self.selenium.find_element_by_id('id_birthdate_0').send_keys('2013-06-01')
# Click the calendar icon
self.selenium.find_element_by_id('calendarlink0').click()
# get all the tds within the calendar
calendar0 = self.selenium.find_element_by_id('calendarin0')
tds = calendar0.find_elements_by_tag_name('td')
# verify the selected cell
selected = tds[6]
self.assertEqual(selected.get_attribute('class'), 'selected')
self.assertEqual(selected.text, '1')
def test_calendar_no_selected_class(self):
"""
Ensure no cells are given the selected class when the field is empty.
Refs #4574.
"""
self.admin_login(username='super', password='secret', login_url='/')
# Open a page that has a date and time picker widgets
self.selenium.get('%s%s' % (self.live_server_url,
'/admin_widgets/member/add/'))
# Click the calendar icon
self.selenium.find_element_by_id('calendarlink0').click()
# get all the tds within the calendar
calendar0 = self.selenium.find_element_by_id('calendarin0')
tds = calendar0.find_elements_by_tag_name('td')
# verify there are no cells with the selected class
selected = [td for td in tds if td.get_attribute('class') == 'selected']
self.assertEqual(len(selected), 0)
def test_calendar_show_date_from_input(self):
"""
Ensure that the calendar show the date from the input field for every
locale supported by django.
"""
self.admin_login(username='super', password='secret', login_url='/')
# Enter test data
member = models.Member.objects.create(name='Bob', birthdate=datetime(1984, 5, 15), gender='M')
# Get month names translations for every locales
month_string = 'January February March April May June July August September October November December'
path = os.path.join(os.path.dirname(import_module('django.contrib.admin').__file__), 'locale')
for language_code, language_name in settings.LANGUAGES:
try:
catalog = gettext.translation('djangojs', path, [language_code])
except IOError:
continue
if month_string in catalog._catalog:
month_names = catalog._catalog[month_string]
else:
month_names = month_string
# Get the expected caption
may_translation = month_names.split(' ')[4]
expected_caption = '{0:s} {1:d}'.format(may_translation, 1984)
# Test with every locale
with override_settings(LANGUAGE_CODE=language_code, USE_L10N=True):
# Open a page that has a date picker widget
self.selenium.get('{}{}'.format(self.live_server_url,
'/admin_widgets/member/{}/'.format(member.pk)))
# Click on the calendar icon
self.selenium.find_element_by_id('calendarlink0').click()
# Get the calendar caption
calendar0 = self.selenium.find_element_by_id('calendarin0')
caption = calendar0.find_element_by_tag_name('caption')
# Make sure that the right month and year are displayed
self.assertEqual(caption.text, expected_caption)
class DateTimePickerSeleniumChromeTests(DateTimePickerSeleniumFirefoxTests):
webdriver_class = 'selenium.webdriver.chrome.webdriver.WebDriver'
class DateTimePickerSeleniumIETests(DateTimePickerSeleniumFirefoxTests):
webdriver_class = 'selenium.webdriver.ie.webdriver.WebDriver'
@skipIf(pytz is None, "this test requires pytz")
@override_settings(TIME_ZONE='Asia/Singapore')
@override_settings(PASSWORD_HASHERS=('django.contrib.auth.hashers.SHA1PasswordHasher',),
ROOT_URLCONF='admin_widgets.urls')
class DateTimePickerShortcutsSeleniumFirefoxTests(AdminSeleniumWebDriverTestCase):
available_apps = ['admin_widgets'] + AdminSeleniumWebDriverTestCase.available_apps
fixtures = ['admin-widgets-users.xml']
webdriver_class = 'selenium.webdriver.firefox.webdriver.WebDriver'
def test_date_time_picker_shortcuts(self):
"""
Ensure that date/time/datetime picker shortcuts work in the current time zone.
Refs #20663.
This test case is fairly tricky, it relies on selenium still running the browser
in the default time zone "America/Chicago" despite `override_settings` changing
the time zone to "Asia/Singapore".
"""
self.admin_login(username='super', password='secret', login_url='/')
error_margin = timedelta(seconds=10)
# If we are neighbouring a DST, we add an hour of error margin.
tz = pytz.timezone('America/Chicago')
utc_now = datetime.now(pytz.utc)
tz_yesterday = (utc_now - timedelta(days=1)).astimezone(tz).tzname()
tz_tomorrow = (utc_now + timedelta(days=1)).astimezone(tz).tzname()
if tz_yesterday != tz_tomorrow:
error_margin += timedelta(hours=1)
now = datetime.now()
self.selenium.get('%s%s' % (self.live_server_url,
'/admin_widgets/member/add/'))
self.selenium.find_element_by_id('id_name').send_keys('test')
# Click on the "today" and "now" shortcuts.
shortcuts = self.selenium.find_elements_by_css_selector(
'.field-birthdate .datetimeshortcuts')
for shortcut in shortcuts:
shortcut.find_element_by_tag_name('a').click()
# Check that there is a time zone mismatch warning.
# Warning: This would effectively fail if the TIME_ZONE defined in the
# settings has the same UTC offset as "Asia/Singapore" because the
# mismatch warning would be rightfully missing from the page.
self.selenium.find_elements_by_css_selector(
'.field-birthdate .timezonewarning')
# Submit the form.
self.selenium.find_element_by_tag_name('form').submit()
self.wait_page_loaded()
# Make sure that "now" in javascript is within 10 seconds
# from "now" on the server side.
member = models.Member.objects.get(name='test')
self.assertGreater(member.birthdate, now - error_margin)
self.assertLess(member.birthdate, now + error_margin)
class DateTimePickerShortcutsSeleniumChromeTests(DateTimePickerShortcutsSeleniumFirefoxTests):
webdriver_class = 'selenium.webdriver.chrome.webdriver.WebDriver'
class DateTimePickerShortcutsSeleniumIETests(DateTimePickerShortcutsSeleniumFirefoxTests):
webdriver_class = 'selenium.webdriver.ie.webdriver.WebDriver'
@override_settings(PASSWORD_HASHERS=('django.contrib.auth.hashers.SHA1PasswordHasher',),
ROOT_URLCONF='admin_widgets.urls')
class HorizontalVerticalFilterSeleniumFirefoxTests(AdminSeleniumWebDriverTestCase):
available_apps = ['admin_widgets'] + AdminSeleniumWebDriverTestCase.available_apps
fixtures = ['admin-widgets-users.xml']
webdriver_class = 'selenium.webdriver.firefox.webdriver.WebDriver'
def setUp(self):
self.lisa = models.Student.objects.create(name='Lisa')
self.john = models.Student.objects.create(name='John')
self.bob = models.Student.objects.create(name='Bob')
self.peter = models.Student.objects.create(name='Peter')
self.jenny = models.Student.objects.create(name='Jenny')
self.jason = models.Student.objects.create(name='Jason')
self.cliff = models.Student.objects.create(name='Cliff')
self.arthur = models.Student.objects.create(name='Arthur')
self.school = models.School.objects.create(name='School of Awesome')
super(HorizontalVerticalFilterSeleniumFirefoxTests, self).setUp()
def assertActiveButtons(self, mode, field_name, choose, remove,
choose_all=None, remove_all=None):
choose_link = '#id_%s_add_link' % field_name
choose_all_link = '#id_%s_add_all_link' % field_name
remove_link = '#id_%s_remove_link' % field_name
remove_all_link = '#id_%s_remove_all_link' % field_name
self.assertEqual(self.has_css_class(choose_link, 'active'), choose)
self.assertEqual(self.has_css_class(remove_link, 'active'), remove)
if mode == 'horizontal':
self.assertEqual(self.has_css_class(choose_all_link, 'active'), choose_all)
self.assertEqual(self.has_css_class(remove_all_link, 'active'), remove_all)
def execute_basic_operations(self, mode, field_name):
from_box = '#id_%s_from' % field_name
to_box = '#id_%s_to' % field_name
choose_link = 'id_%s_add_link' % field_name
choose_all_link = 'id_%s_add_all_link' % field_name
remove_link = 'id_%s_remove_link' % field_name
remove_all_link = 'id_%s_remove_all_link' % field_name
# Initial positions ---------------------------------------------------
self.assertSelectOptions(from_box,
[str(self.arthur.id), str(self.bob.id),
str(self.cliff.id), str(self.jason.id),
str(self.jenny.id), str(self.john.id)])
self.assertSelectOptions(to_box,
[str(self.lisa.id), str(self.peter.id)])
self.assertActiveButtons(mode, field_name, False, False, True, True)
# Click 'Choose all' --------------------------------------------------
if mode == 'horizontal':
self.selenium.find_element_by_id(choose_all_link).click()
elif mode == 'vertical':
# There 's no 'Choose all' button in vertical mode, so individually
# select all options and click 'Choose'.
for option in self.selenium.find_elements_by_css_selector(from_box + ' > option'):
option.click()
self.selenium.find_element_by_id(choose_link).click()
self.assertSelectOptions(from_box, [])
self.assertSelectOptions(to_box,
[str(self.lisa.id), str(self.peter.id),
str(self.arthur.id), str(self.bob.id),
str(self.cliff.id), str(self.jason.id),
str(self.jenny.id), str(self.john.id)])
self.assertActiveButtons(mode, field_name, False, False, False, True)
# Click 'Remove all' --------------------------------------------------
if mode == 'horizontal':
self.selenium.find_element_by_id(remove_all_link).click()
elif mode == 'vertical':
# There 's no 'Remove all' button in vertical mode, so individually
# select all options and click 'Remove'.
for option in self.selenium.find_elements_by_css_selector(to_box + ' > option'):
option.click()
self.selenium.find_element_by_id(remove_link).click()
self.assertSelectOptions(from_box,
[str(self.lisa.id), str(self.peter.id),
str(self.arthur.id), str(self.bob.id),
str(self.cliff.id), str(self.jason.id),
str(self.jenny.id), str(self.john.id)])
self.assertSelectOptions(to_box, [])
self.assertActiveButtons(mode, field_name, False, False, True, False)
# Choose some options ------------------------------------------------
from_lisa_select_option = self.get_select_option(from_box, str(self.lisa.id))
# Check the title attribute is there for tool tips: ticket #20821
self.assertEqual(from_lisa_select_option.get_attribute('title'), from_lisa_select_option.get_attribute('text'))
from_lisa_select_option.click()
self.get_select_option(from_box, str(self.jason.id)).click()
self.get_select_option(from_box, str(self.bob.id)).click()
self.get_select_option(from_box, str(self.john.id)).click()
self.assertActiveButtons(mode, field_name, True, False, True, False)
self.selenium.find_element_by_id(choose_link).click()
self.assertActiveButtons(mode, field_name, False, False, True, True)
self.assertSelectOptions(from_box,
[str(self.peter.id), str(self.arthur.id),
str(self.cliff.id), str(self.jenny.id)])
self.assertSelectOptions(to_box,
[str(self.lisa.id), str(self.bob.id),
str(self.jason.id), str(self.john.id)])
# Check the tooltip is still there after moving: ticket #20821
to_lisa_select_option = self.get_select_option(to_box, str(self.lisa.id))
self.assertEqual(to_lisa_select_option.get_attribute('title'), to_lisa_select_option.get_attribute('text'))
# Remove some options -------------------------------------------------
self.get_select_option(to_box, str(self.lisa.id)).click()
self.get_select_option(to_box, str(self.bob.id)).click()
self.assertActiveButtons(mode, field_name, False, True, True, True)
self.selenium.find_element_by_id(remove_link).click()
self.assertActiveButtons(mode, field_name, False, False, True, True)
self.assertSelectOptions(from_box,
[str(self.peter.id), str(self.arthur.id),
str(self.cliff.id), str(self.jenny.id),
str(self.lisa.id), str(self.bob.id)])
self.assertSelectOptions(to_box,
[str(self.jason.id), str(self.john.id)])
# Choose some more options --------------------------------------------
self.get_select_option(from_box, str(self.arthur.id)).click()
self.get_select_option(from_box, str(self.cliff.id)).click()
self.selenium.find_element_by_id(choose_link).click()
self.assertSelectOptions(from_box,
[str(self.peter.id), str(self.jenny.id),
str(self.lisa.id), str(self.bob.id)])
self.assertSelectOptions(to_box,
[str(self.jason.id), str(self.john.id),
str(self.arthur.id), str(self.cliff.id)])
def test_basic(self):
self.school.students = [self.lisa, self.peter]
self.school.alumni = [self.lisa, self.peter]
self.school.save()
self.admin_login(username='super', password='secret', login_url='/')
self.selenium.get(
'%s%s' % (self.live_server_url, '/admin_widgets/school/%s/' % self.school.id))
self.wait_page_loaded()
self.execute_basic_operations('vertical', 'students')
self.execute_basic_operations('horizontal', 'alumni')
# Save and check that everything is properly stored in the database ---
self.selenium.find_element_by_xpath('//input[@value="Save"]').click()
self.wait_page_loaded()
self.school = models.School.objects.get(id=self.school.id) # Reload from database
self.assertEqual(list(self.school.students.all()),
[self.arthur, self.cliff, self.jason, self.john])
self.assertEqual(list(self.school.alumni.all()),
[self.arthur, self.cliff, self.jason, self.john])
def test_filter(self):
"""
Ensure that typing in the search box filters out options displayed in
the 'from' box.
"""
from selenium.webdriver.common.keys import Keys
self.school.students = [self.lisa, self.peter]
self.school.alumni = [self.lisa, self.peter]
self.school.save()
self.admin_login(username='super', password='secret', login_url='/')
self.selenium.get(
'%s%s' % (self.live_server_url, '/admin_widgets/school/%s/' % self.school.id))
for field_name in ['students', 'alumni']:
from_box = '#id_%s_from' % field_name
to_box = '#id_%s_to' % field_name
choose_link = '#id_%s_add_link' % field_name
remove_link = '#id_%s_remove_link' % field_name
input = self.selenium.find_element_by_css_selector('#id_%s_input' % field_name)
# Initial values
self.assertSelectOptions(from_box,
[str(self.arthur.id), str(self.bob.id),
str(self.cliff.id), str(self.jason.id),
str(self.jenny.id), str(self.john.id)])
# Typing in some characters filters out non-matching options
input.send_keys('a')
self.assertSelectOptions(from_box, [str(self.arthur.id), str(self.jason.id)])
input.send_keys('R')
self.assertSelectOptions(from_box, [str(self.arthur.id)])
# Clearing the text box makes the other options reappear
input.send_keys([Keys.BACK_SPACE])
self.assertSelectOptions(from_box, [str(self.arthur.id), str(self.jason.id)])
input.send_keys([Keys.BACK_SPACE])
self.assertSelectOptions(from_box,
[str(self.arthur.id), str(self.bob.id),
str(self.cliff.id), str(self.jason.id),
str(self.jenny.id), str(self.john.id)])
# -----------------------------------------------------------------
# Check that chosing a filtered option sends it properly to the
# 'to' box.
input.send_keys('a')
self.assertSelectOptions(from_box, [str(self.arthur.id), str(self.jason.id)])
self.get_select_option(from_box, str(self.jason.id)).click()
self.selenium.find_element_by_css_selector(choose_link).click()
self.assertSelectOptions(from_box, [str(self.arthur.id)])
self.assertSelectOptions(to_box,
[str(self.lisa.id), str(self.peter.id),
str(self.jason.id)])
self.get_select_option(to_box, str(self.lisa.id)).click()
self.selenium.find_element_by_css_selector(remove_link).click()
self.assertSelectOptions(from_box,
[str(self.arthur.id), str(self.lisa.id)])
self.assertSelectOptions(to_box,
[str(self.peter.id), str(self.jason.id)])
input.send_keys([Keys.BACK_SPACE]) # Clear text box
self.assertSelectOptions(from_box,
[str(self.arthur.id), str(self.bob.id),
str(self.cliff.id), str(self.jenny.id),
str(self.john.id), str(self.lisa.id)])
self.assertSelectOptions(to_box,
[str(self.peter.id), str(self.jason.id)])
# -----------------------------------------------------------------
# Check that pressing enter on a filtered option sends it properly
# to the 'to' box.
self.get_select_option(to_box, str(self.jason.id)).click()
self.selenium.find_element_by_css_selector(remove_link).click()
input.send_keys('ja')
self.assertSelectOptions(from_box, [str(self.jason.id)])
input.send_keys([Keys.ENTER])
self.assertSelectOptions(to_box, [str(self.peter.id), str(self.jason.id)])
input.send_keys([Keys.BACK_SPACE, Keys.BACK_SPACE])
# Save and check that everything is properly stored in the database ---
self.selenium.find_element_by_xpath('//input[@value="Save"]').click()
self.wait_page_loaded()
self.school = models.School.objects.get(id=self.school.id) # Reload from database
self.assertEqual(list(self.school.students.all()),
[self.jason, self.peter])
self.assertEqual(list(self.school.alumni.all()),
[self.jason, self.peter])
class HorizontalVerticalFilterSeleniumChromeTests(HorizontalVerticalFilterSeleniumFirefoxTests):
webdriver_class = 'selenium.webdriver.chrome.webdriver.WebDriver'
class HorizontalVerticalFilterSeleniumIETests(HorizontalVerticalFilterSeleniumFirefoxTests):
webdriver_class = 'selenium.webdriver.ie.webdriver.WebDriver'
@override_settings(PASSWORD_HASHERS=('django.contrib.auth.hashers.SHA1PasswordHasher',),
ROOT_URLCONF='admin_widgets.urls')
class AdminRawIdWidgetSeleniumFirefoxTests(AdminSeleniumWebDriverTestCase):
available_apps = ['admin_widgets'] + AdminSeleniumWebDriverTestCase.available_apps
fixtures = ['admin-widgets-users.xml']
webdriver_class = 'selenium.webdriver.firefox.webdriver.WebDriver'
def setUp(self):
models.Band.objects.create(id=42, name='Bogey Blues')
models.Band.objects.create(id=98, name='Green Potatoes')
super(AdminRawIdWidgetSeleniumFirefoxTests, self).setUp()
def test_ForeignKey(self):
self.admin_login(username='super', password='secret', login_url='/')
self.selenium.get(
'%s%s' % (self.live_server_url, '/admin_widgets/event/add/'))
main_window = self.selenium.current_window_handle
# No value has been selected yet
self.assertEqual(
self.selenium.find_element_by_id('id_main_band').get_attribute('value'),
'')
# Open the popup window and click on a band
self.selenium.find_element_by_id('lookup_id_main_band').click()
self.selenium.switch_to.window('id_main_band')
self.wait_page_loaded()
link = self.selenium.find_element_by_link_text('Bogey Blues')
self.assertTrue('/band/42/' in link.get_attribute('href'))
link.click()
# The field now contains the selected band's id
self.selenium.switch_to.window(main_window)
self.wait_for_value('#id_main_band', '42')
# Reopen the popup window and click on another band
self.selenium.find_element_by_id('lookup_id_main_band').click()
self.selenium.switch_to.window('id_main_band')
self.wait_page_loaded()
link = self.selenium.find_element_by_link_text('Green Potatoes')
self.assertTrue('/band/98/' in link.get_attribute('href'))
link.click()
# The field now contains the other selected band's id
self.selenium.switch_to.window(main_window)
self.wait_for_value('#id_main_band', '98')
def test_many_to_many(self):
self.admin_login(username='super', password='secret', login_url='/')
self.selenium.get(
'%s%s' % (self.live_server_url, '/admin_widgets/event/add/'))
main_window = self.selenium.current_window_handle
# No value has been selected yet
self.assertEqual(
self.selenium.find_element_by_id('id_supporting_bands').get_attribute('value'),
'')
# Open the popup window and click on a band
self.selenium.find_element_by_id('lookup_id_supporting_bands').click()
self.selenium.switch_to.window('id_supporting_bands')
self.wait_page_loaded()
link = self.selenium.find_element_by_link_text('Bogey Blues')
self.assertTrue('/band/42/' in link.get_attribute('href'))
link.click()
# The field now contains the selected band's id
self.selenium.switch_to.window(main_window)
self.wait_for_value('#id_supporting_bands', '42')
# Reopen the popup window and click on another band
self.selenium.find_element_by_id('lookup_id_supporting_bands').click()
self.selenium.switch_to.window('id_supporting_bands')
self.wait_page_loaded()
link = self.selenium.find_element_by_link_text('Green Potatoes')
self.assertTrue('/band/98/' in link.get_attribute('href'))
link.click()
# The field now contains the two selected bands' ids
self.selenium.switch_to.window(main_window)
self.wait_for_value('#id_supporting_bands', '42,98')
class AdminRawIdWidgetSeleniumChromeTests(AdminRawIdWidgetSeleniumFirefoxTests):
webdriver_class = 'selenium.webdriver.chrome.webdriver.WebDriver'
class AdminRawIdWidgetSeleniumIETests(AdminRawIdWidgetSeleniumFirefoxTests):
webdriver_class = 'selenium.webdriver.ie.webdriver.WebDriver'
@override_settings(PASSWORD_HASHERS=('django.contrib.auth.hashers.SHA1PasswordHasher',),
ROOT_URLCONF='admin_widgets.urls')
class RelatedFieldWidgetSeleniumFirefoxTests(AdminSeleniumWebDriverTestCase):
available_apps = ['admin_widgets'] + AdminSeleniumWebDriverTestCase.available_apps
fixtures = ['admin-widgets-users.xml']
webdriver_class = 'selenium.webdriver.firefox.webdriver.WebDriver'
def test_ForeignKey_using_to_field(self):
self.admin_login(username='super', password='secret', login_url='/')
self.selenium.get('%s%s' % (
self.live_server_url,
'/admin_widgets/profile/add/'))
main_window = self.selenium.current_window_handle
# Click the Add User button to add new
self.selenium.find_element_by_id('add_id_user').click()
self.selenium.switch_to.window('id_user')
self.wait_for('#id_password')
password_field = self.selenium.find_element_by_id('id_password')
password_field.send_keys('password')
username_field = self.selenium.find_element_by_id('id_username')
username_value = 'newuser'
username_field.send_keys(username_value)
save_button_css_selector = '.submit-row > input[type=submit]'
self.selenium.find_element_by_css_selector(save_button_css_selector).click()
self.selenium.switch_to.window(main_window)
# The field now contains the new user
self.wait_for('#id_user option[value="newuser"]')
# Go ahead and submit the form to make sure it works
self.selenium.find_element_by_css_selector(save_button_css_selector).click()
self.wait_for_text('li.success', 'The profile "newuser" was added successfully.')
profiles = models.Profile.objects.all()
self.assertEqual(len(profiles), 1)
self.assertEqual(profiles[0].user.username, username_value)
class RelatedFieldWidgetSeleniumChromeTests(RelatedFieldWidgetSeleniumFirefoxTests):
webdriver_class = 'selenium.webdriver.chrome.webdriver.WebDriver'
class RelatedFieldWidgetSeleniumIETests(RelatedFieldWidgetSeleniumFirefoxTests):
webdriver_class = 'selenium.webdriver.ie.webdriver.WebDriver'
| bsd-3-clause |
MartinHjelmare/home-assistant | homeassistant/components/tellstick/sensor.py | 7 | 4038 | """Support for Tellstick sensors."""
import logging
from collections import namedtuple
import voluptuous as vol
from homeassistant.components.sensor import PLATFORM_SCHEMA
from homeassistant.const import TEMP_CELSIUS, CONF_ID, CONF_NAME
from homeassistant.helpers.entity import Entity
import homeassistant.helpers.config_validation as cv
_LOGGER = logging.getLogger(__name__)
DatatypeDescription = namedtuple('DatatypeDescription', ['name', 'unit'])
CONF_DATATYPE_MASK = 'datatype_mask'
CONF_ONLY_NAMED = 'only_named'
CONF_TEMPERATURE_SCALE = 'temperature_scale'
DEFAULT_DATATYPE_MASK = 127
DEFAULT_TEMPERATURE_SCALE = TEMP_CELSIUS
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
vol.Optional(CONF_TEMPERATURE_SCALE, default=DEFAULT_TEMPERATURE_SCALE):
cv.string,
vol.Optional(CONF_DATATYPE_MASK, default=DEFAULT_DATATYPE_MASK):
cv.positive_int,
vol.Optional(CONF_ONLY_NAMED, default=[]):
vol.All(cv.ensure_list, [vol.Schema({
vol.Required(CONF_ID): cv.positive_int,
vol.Required(CONF_NAME): cv.string,
})])
})
def setup_platform(hass, config, add_entities, discovery_info=None):
"""Set up the Tellstick sensors."""
from tellcore import telldus
import tellcore.constants as tellcore_constants
sensor_value_descriptions = {
tellcore_constants.TELLSTICK_TEMPERATURE:
DatatypeDescription('temperature', config.get(CONF_TEMPERATURE_SCALE)),
tellcore_constants.TELLSTICK_HUMIDITY:
DatatypeDescription('humidity', '%'),
tellcore_constants.TELLSTICK_RAINRATE:
DatatypeDescription('rain rate', ''),
tellcore_constants.TELLSTICK_RAINTOTAL:
DatatypeDescription('rain total', ''),
tellcore_constants.TELLSTICK_WINDDIRECTION:
DatatypeDescription('wind direction', ''),
tellcore_constants.TELLSTICK_WINDAVERAGE:
DatatypeDescription('wind average', ''),
tellcore_constants.TELLSTICK_WINDGUST:
DatatypeDescription('wind gust', '')
}
try:
tellcore_lib = telldus.TelldusCore()
except OSError:
_LOGGER.exception('Could not initialize Tellstick')
return
sensors = []
datatype_mask = config.get(CONF_DATATYPE_MASK)
if config[CONF_ONLY_NAMED]:
named_sensors = {
named_sensor[CONF_ID]: named_sensor[CONF_NAME]
for named_sensor in config[CONF_ONLY_NAMED]}
for tellcore_sensor in tellcore_lib.sensors():
if not config[CONF_ONLY_NAMED]:
sensor_name = str(tellcore_sensor.id)
else:
if tellcore_sensor.id not in named_sensors:
continue
sensor_name = named_sensors[tellcore_sensor.id]
for datatype in sensor_value_descriptions:
if datatype & datatype_mask and \
tellcore_sensor.has_value(datatype):
sensor_info = sensor_value_descriptions[datatype]
sensors.append(TellstickSensor(
sensor_name, tellcore_sensor,
datatype, sensor_info))
add_entities(sensors)
class TellstickSensor(Entity):
"""Representation of a Tellstick sensor."""
def __init__(self, name, tellcore_sensor, datatype, sensor_info):
"""Initialize the sensor."""
self._datatype = datatype
self._tellcore_sensor = tellcore_sensor
self._unit_of_measurement = sensor_info.unit or None
self._value = None
self._name = '{} {}'.format(name, sensor_info.name)
@property
def name(self):
"""Return the name of the sensor."""
return self._name
@property
def state(self):
"""Return the state of the sensor."""
return self._value
@property
def unit_of_measurement(self):
"""Return the unit of measurement of this entity, if any."""
return self._unit_of_measurement
def update(self):
"""Update tellstick sensor."""
self._value = self._tellcore_sensor.value(self._datatype).value
| apache-2.0 |
Dave667/service | script.video.F4mProxy/lib/utils/openssl_tripledes.py | 202 | 1788 | # Author: Trevor Perrin
# See the LICENSE file for legal information regarding use of this file.
"""OpenSSL/M2Crypto 3DES implementation."""
from .cryptomath import *
from .tripledes import *
if m2cryptoLoaded:
def new(key, mode, IV):
return OpenSSL_TripleDES(key, mode, IV)
class OpenSSL_TripleDES(TripleDES):
def __init__(self, key, mode, IV):
TripleDES.__init__(self, key, mode, IV, "openssl")
self.key = key
self.IV = IV
def _createContext(self, encrypt):
context = m2.cipher_ctx_new()
cipherType = m2.des_ede3_cbc()
m2.cipher_init(context, cipherType, self.key, self.IV, encrypt)
return context
def encrypt(self, plaintext):
TripleDES.encrypt(self, plaintext)
context = self._createContext(1)
ciphertext = m2.cipher_update(context, plaintext)
m2.cipher_ctx_free(context)
self.IV = ciphertext[-self.block_size:]
return bytearray(ciphertext)
def decrypt(self, ciphertext):
TripleDES.decrypt(self, ciphertext)
context = self._createContext(0)
#I think M2Crypto has a bug - it fails to decrypt and return the last block passed in.
#To work around this, we append sixteen zeros to the string, below:
plaintext = m2.cipher_update(context, ciphertext+('\0'*16))
#If this bug is ever fixed, then plaintext will end up having a garbage
#plaintext block on the end. That's okay - the below code will ignore it.
plaintext = plaintext[:len(ciphertext)]
m2.cipher_ctx_free(context)
self.IV = ciphertext[-self.block_size:]
return bytearray(plaintext) | gpl-2.0 |
bordeltabernacle/python_koans | python2/libs/mock.py | 249 | 8036 | # mock.py
# Test tools for mocking and patching.
# Copyright (C) 2007-2009 Michael Foord
# E-mail: fuzzyman AT voidspace DOT org DOT uk
# mock 0.6.0
# http://www.voidspace.org.uk/python/mock/
# Released subject to the BSD License
# Please see http://www.voidspace.org.uk/python/license.shtml
# Scripts maintained at http://www.voidspace.org.uk/python/index.shtml
# Comments, suggestions and bug reports welcome.
__all__ = (
'Mock',
'patch',
'patch_object',
'sentinel',
'DEFAULT'
)
__version__ = '0.6.0 modified by Greg Malcolm'
class SentinelObject(object):
def __init__(self, name):
self.name = name
def __repr__(self):
return '<SentinelObject "{0!s}">'.format(self.name)
class Sentinel(object):
def __init__(self):
self._sentinels = {}
def __getattr__(self, name):
return self._sentinels.setdefault(name, SentinelObject(name))
sentinel = Sentinel()
DEFAULT = sentinel.DEFAULT
class OldStyleClass:
pass
ClassType = type(OldStyleClass)
def _is_magic(name):
return '__{0!s}__'.format(name[2:-2]) == name
def _copy(value):
if type(value) in (dict, list, tuple, set):
return type(value)(value)
return value
class Mock(object):
def __init__(self, spec=None, side_effect=None, return_value=DEFAULT,
name=None, parent=None, wraps=None):
self._parent = parent
self._name = name
if spec is not None and not isinstance(spec, list):
spec = [member for member in dir(spec) if not _is_magic(member)]
self._methods = spec
self._children = {}
self._return_value = return_value
self.side_effect = side_effect
self._wraps = wraps
self.reset_mock()
def reset_mock(self):
self.called = False
self.call_args = None
self.call_count = 0
self.call_args_list = []
self.method_calls = []
for child in self._children.values():
child.reset_mock()
if isinstance(self._return_value, Mock):
self._return_value.reset_mock()
def __get_return_value(self):
if self._return_value is DEFAULT:
self._return_value = Mock()
return self._return_value
def __set_return_value(self, value):
self._return_value = value
return_value = property(__get_return_value, __set_return_value)
def __call__(self, *args, **kwargs):
self.called = True
self.call_count += 1
self.call_args = (args, kwargs)
self.call_args_list.append((args, kwargs))
parent = self._parent
name = self._name
while parent is not None:
parent.method_calls.append((name, args, kwargs))
if parent._parent is None:
break
name = parent._name + '.' + name
parent = parent._parent
ret_val = DEFAULT
if self.side_effect is not None:
if (isinstance(self.side_effect, Exception) or
isinstance(self.side_effect, (type, ClassType)) and
issubclass(self.side_effect, Exception)):
raise self.side_effect
ret_val = self.side_effect(*args, **kwargs)
if ret_val is DEFAULT:
ret_val = self.return_value
if self._wraps is not None and self._return_value is DEFAULT:
return self._wraps(*args, **kwargs)
if ret_val is DEFAULT:
ret_val = self.return_value
return ret_val
def __getattr__(self, name):
if self._methods is not None:
if name not in self._methods:
raise AttributeError("Mock object has no attribute '{0!s}'".format(name))
elif _is_magic(name):
raise AttributeError(name)
if name not in self._children:
wraps = None
if self._wraps is not None:
wraps = getattr(self._wraps, name)
self._children[name] = Mock(parent=self, name=name, wraps=wraps)
return self._children[name]
def assert_called_with(self, *args, **kwargs):
assert self.call_args == (args, kwargs), 'Expected: {0!s}\nCalled with: {1!s}'.format((args, kwargs), self.call_args)
def _dot_lookup(thing, comp, import_path):
try:
return getattr(thing, comp)
except AttributeError:
__import__(import_path)
return getattr(thing, comp)
def _importer(target):
components = target.split('.')
import_path = components.pop(0)
thing = __import__(import_path)
for comp in components:
import_path += ".{0!s}".format(comp)
thing = _dot_lookup(thing, comp, import_path)
return thing
class _patch(object):
def __init__(self, target, attribute, new, spec, create):
self.target = target
self.attribute = attribute
self.new = new
self.spec = spec
self.create = create
self.has_local = False
def __call__(self, func):
if hasattr(func, 'patchings'):
func.patchings.append(self)
return func
def patched(*args, **keywargs):
# don't use a with here (backwards compatability with 2.5)
extra_args = []
for patching in patched.patchings:
arg = patching.__enter__()
if patching.new is DEFAULT:
extra_args.append(arg)
args += tuple(extra_args)
try:
return func(*args, **keywargs)
finally:
for patching in getattr(patched, 'patchings', []):
patching.__exit__()
patched.patchings = [self]
patched.__name__ = func.__name__
patched.compat_co_firstlineno = getattr(func, "compat_co_firstlineno",
func.func_code.co_firstlineno)
return patched
def get_original(self):
target = self.target
name = self.attribute
create = self.create
original = DEFAULT
if _has_local_attr(target, name):
try:
original = target.__dict__[name]
except AttributeError:
# for instances of classes with slots, they have no __dict__
original = getattr(target, name)
elif not create and not hasattr(target, name):
raise AttributeError("{0!s} does not have the attribute {1!r}".format(target, name))
return original
def __enter__(self):
new, spec, = self.new, self.spec
original = self.get_original()
if new is DEFAULT:
# XXXX what if original is DEFAULT - shouldn't use it as a spec
inherit = False
if spec == True:
# set spec to the object we are replacing
spec = original
if isinstance(spec, (type, ClassType)):
inherit = True
new = Mock(spec=spec)
if inherit:
new.return_value = Mock(spec=spec)
self.temp_original = original
setattr(self.target, self.attribute, new)
return new
def __exit__(self, *_):
if self.temp_original is not DEFAULT:
setattr(self.target, self.attribute, self.temp_original)
else:
delattr(self.target, self.attribute)
del self.temp_original
def patch_object(target, attribute, new=DEFAULT, spec=None, create=False):
return _patch(target, attribute, new, spec, create)
def patch(target, new=DEFAULT, spec=None, create=False):
try:
target, attribute = target.rsplit('.', 1)
except (TypeError, ValueError):
raise TypeError("Need a valid target to patch. You supplied: {0!r}".format(target,))
target = _importer(target)
return _patch(target, attribute, new, spec, create)
def _has_local_attr(obj, name):
try:
return name in vars(obj)
except TypeError:
# objects without a __dict__
return hasattr(obj, name)
| mit |
controlzee/three.js | utils/exporters/blender/addons/io_three/exporter/api/animation.py | 177 | 16103 | """
Module for handling the parsing of skeletal animation data.
"""
import math
import mathutils
from bpy import data, context
from .. import constants, logger
def pose_animation(armature, options):
"""Query armature animation using pose bones
:param armature:
:param options:
:returns: list dictionaries containing animationdata
:rtype: [{}, {}, ...]
"""
logger.debug("animation.pose_animation(%s)", armature)
func = _parse_pose_action
return _parse_action(func, armature, options)
def rest_animation(armature, options):
"""Query armature animation (REST position)
:param armature:
:param options:
:returns: list dictionaries containing animationdata
:rtype: [{}, {}, ...]
"""
logger.debug("animation.rest_animation(%s)", armature)
func = _parse_rest_action
return _parse_action(func, armature, options)
def _parse_action(func, armature, options):
"""
:param func:
:param armature:
:param options:
"""
animations = []
logger.info("Parsing %d actions", len(data.actions))
for action in data.actions:
logger.info("Parsing action %s", action.name)
animation = func(action, armature, options)
animations.append(animation)
return animations
def _parse_rest_action(action, armature, options):
"""
:param action:
:param armature:
:param options:
"""
end_frame = action.frame_range[1]
start_frame = action.frame_range[0]
frame_length = end_frame - start_frame
rot = armature.matrix_world.decompose()[1]
rotation_matrix = rot.to_matrix()
hierarchy = []
parent_index = -1
frame_step = options.get(constants.FRAME_STEP, 1)
fps = context.scene.render.fps
start = int(start_frame)
end = int(end_frame / frame_step) + 1
for bone in armature.data.bones:
# I believe this was meant to skip control bones, may
# not be useful. needs more testing
if bone.use_deform is False:
logger.info("Skipping animation data for bone %s", bone.name)
continue
logger.info("Parsing animation data for bone %s", bone.name)
keys = []
for frame in range(start, end):
computed_frame = frame * frame_step
pos, pchange = _position(bone, computed_frame,
action, armature.matrix_world)
rot, rchange = _rotation(bone, computed_frame,
action, rotation_matrix)
rot = _normalize_quaternion(rot)
pos_x, pos_y, pos_z = pos.x, pos.z, -pos.y
rot_x, rot_y, rot_z, rot_w = rot.x, rot.z, -rot.y, rot.w
if frame == start_frame:
time = (frame * frame_step - start_frame) / fps
# @TODO: missing scale values
keyframe = {
constants.TIME: time,
constants.POS: [pos_x, pos_y, pos_z],
constants.ROT: [rot_x, rot_y, rot_z, rot_w],
constants.SCL: [1, 1, 1]
}
keys.append(keyframe)
# END-FRAME: needs pos, rot and scl attributes
# with animation length (required frame)
elif frame == end_frame / frame_step:
time = frame_length / fps
keyframe = {
constants.TIME: time,
constants.POS: [pos_x, pos_y, pos_z],
constants.ROT: [rot_x, rot_y, rot_z, rot_w],
constants.SCL: [1, 1, 1]
}
keys.append(keyframe)
# MIDDLE-FRAME: needs only one of the attributes,
# can be an empty frame (optional frame)
elif pchange is True or rchange is True:
time = (frame * frame_step - start_frame) / fps
if pchange is True and rchange is True:
keyframe = {
constants.TIME: time,
constants.POS: [pos_x, pos_y, pos_z],
constants.ROT: [rot_x, rot_y, rot_z, rot_w]
}
elif pchange is True:
keyframe = {
constants.TIME: time,
constants.POS: [pos_x, pos_y, pos_z]
}
elif rchange is True:
keyframe = {
constants.TIME: time,
constants.ROT: [rot_x, rot_y, rot_z, rot_w]
}
keys.append(keyframe)
hierarchy.append({
constants.KEYS: keys,
constants.PARENT: parent_index
})
parent_index += 1
animation = {
constants.HIERARCHY: hierarchy,
constants.LENGTH: frame_length / fps,
constants.FPS: fps,
constants.NAME: action.name
}
return animation
def _parse_pose_action(action, armature, options):
"""
:param action:
:param armature:
:param options:
"""
# @TODO: this seems to fail in batch mode meaning the
# user has to have th GUI open. need to improve
# this logic to allow batch processing, if Blender
# chooses to behave....
current_context = context.area.type
context.area.type = 'DOPESHEET_EDITOR'
context.space_data.mode = 'ACTION'
context.area.spaces.active.action = action
armature_matrix = armature.matrix_world
fps = context.scene.render.fps
end_frame = action.frame_range[1]
start_frame = action.frame_range[0]
frame_length = end_frame - start_frame
frame_step = options.get(constants.FRAME_STEP, 1)
used_frames = int(frame_length / frame_step) + 1
keys = []
channels_location = []
channels_rotation = []
channels_scale = []
for pose_bone in armature.pose.bones:
logger.info("Processing channels for %s",
pose_bone.bone.name)
keys.append([])
channels_location.append(
_find_channels(action,
pose_bone.bone,
'location'))
channels_rotation.append(
_find_channels(action,
pose_bone.bone,
'rotation_quaternion'))
channels_rotation.append(
_find_channels(action,
pose_bone.bone,
'rotation_euler'))
channels_scale.append(
_find_channels(action,
pose_bone.bone,
'scale'))
frame_step = options[constants.FRAME_STEP]
frame_index_as_time = options[constants.FRAME_INDEX_AS_TIME]
for frame_index in range(0, used_frames):
if frame_index == used_frames - 1:
frame = end_frame
else:
frame = start_frame + frame_index * frame_step
logger.info("Processing frame %d", frame)
time = frame - start_frame
if frame_index_as_time is False:
time = time / fps
context.scene.frame_set(frame)
bone_index = 0
def has_keyframe_at(channels, frame):
"""
:param channels:
:param frame:
"""
def find_keyframe_at(channel, frame):
"""
:param channel:
:param frame:
"""
for keyframe in channel.keyframe_points:
if keyframe.co[0] == frame:
return keyframe
return None
for channel in channels:
if not find_keyframe_at(channel, frame) is None:
return True
return False
for pose_bone in armature.pose.bones:
logger.info("Processing bone %s", pose_bone.bone.name)
if pose_bone.parent is None:
bone_matrix = armature_matrix * pose_bone.matrix
else:
parent_matrix = armature_matrix * pose_bone.parent.matrix
bone_matrix = armature_matrix * pose_bone.matrix
bone_matrix = parent_matrix.inverted() * bone_matrix
pos, rot, scl = bone_matrix.decompose()
rot = _normalize_quaternion(rot)
pchange = True or has_keyframe_at(
channels_location[bone_index], frame)
rchange = True or has_keyframe_at(
channels_rotation[bone_index], frame)
schange = True or has_keyframe_at(
channels_scale[bone_index], frame)
pos = (pos.x, pos.z, -pos.y)
rot = (rot.x, rot.z, -rot.y, rot.w)
scl = (scl.x, scl.z, scl.y)
keyframe = {constants.TIME: time}
if frame == start_frame or frame == end_frame:
keyframe.update({
constants.POS: pos,
constants.ROT: rot,
constants.SCL: scl
})
elif any([pchange, rchange, schange]):
if pchange is True:
keyframe[constants.POS] = pos
if rchange is True:
keyframe[constants.ROT] = rot
if schange is True:
keyframe[constants.SCL] = scl
if len(keyframe.keys()) > 1:
logger.info("Recording keyframe data for %s %s",
pose_bone.bone.name, str(keyframe))
keys[bone_index].append(keyframe)
else:
logger.info("No anim data to record for %s",
pose_bone.bone.name)
bone_index += 1
hierarchy = []
bone_index = 0
for pose_bone in armature.pose.bones:
hierarchy.append({
constants.PARENT: bone_index - 1,
constants.KEYS: keys[bone_index]
})
bone_index += 1
if frame_index_as_time is False:
frame_length = frame_length / fps
context.scene.frame_set(start_frame)
context.area.type = current_context
animation = {
constants.HIERARCHY: hierarchy,
constants.LENGTH: frame_length,
constants.FPS: fps,
constants.NAME: action.name
}
return animation
def _find_channels(action, bone, channel_type):
"""
:param action:
:param bone:
:param channel_type:
"""
result = []
if len(action.groups):
group_index = -1
for index, group in enumerate(action.groups):
if group.name == bone.name:
group_index = index
# @TODO: break?
if group_index > -1:
for channel in action.groups[group_index].channels:
if channel_type in channel.data_path:
result.append(channel)
else:
bone_label = '"%s"' % bone.name
for channel in action.fcurves:
data_path = [bone_label in channel.data_path,
channel_type in channel.data_path]
if all(data_path):
result.append(channel)
return result
def _position(bone, frame, action, armature_matrix):
"""
:param bone:
:param frame:
:param action:
:param armature_matrix:
"""
position = mathutils.Vector((0, 0, 0))
change = False
ngroups = len(action.groups)
if ngroups > 0:
index = 0
for i in range(ngroups):
if action.groups[i].name == bone.name:
index = i
for channel in action.groups[index].channels:
if "location" in channel.data_path:
has_changed = _handle_position_channel(
channel, frame, position)
change = change or has_changed
else:
bone_label = '"%s"' % bone.name
for channel in action.fcurves:
data_path = channel.data_path
if bone_label in data_path and "location" in data_path:
has_changed = _handle_position_channel(
channel, frame, position)
change = change or has_changed
position = position * bone.matrix_local.inverted()
if bone.parent is None:
position.x += bone.head.x
position.y += bone.head.y
position.z += bone.head.z
else:
parent = bone.parent
parent_matrix = parent.matrix_local.inverted()
diff = parent.tail_local - parent.head_local
position.x += (bone.head * parent_matrix).x + diff.x
position.y += (bone.head * parent_matrix).y + diff.y
position.z += (bone.head * parent_matrix).z + diff.z
return armature_matrix*position, change
def _rotation(bone, frame, action, armature_matrix):
"""
:param bone:
:param frame:
:param action:
:param armature_matrix:
"""
# TODO: calculate rotation also from rotation_euler channels
rotation = mathutils.Vector((0, 0, 0, 1))
change = False
ngroups = len(action.groups)
# animation grouped by bones
if ngroups > 0:
index = -1
for i in range(ngroups):
if action.groups[i].name == bone.name:
index = i
if index > -1:
for channel in action.groups[index].channels:
if "quaternion" in channel.data_path:
has_changed = _handle_rotation_channel(
channel, frame, rotation)
change = change or has_changed
# animation in raw fcurves
else:
bone_label = '"%s"' % bone.name
for channel in action.fcurves:
data_path = channel.data_path
if bone_label in data_path and "quaternion" in data_path:
has_changed = _handle_rotation_channel(
channel, frame, rotation)
change = change or has_changed
rot3 = rotation.to_3d()
rotation.xyz = rot3 * bone.matrix_local.inverted()
rotation.xyz = armature_matrix * rotation.xyz
return rotation, change
def _handle_rotation_channel(channel, frame, rotation):
"""
:param channel:
:param frame:
:param rotation:
"""
change = False
if channel.array_index in [0, 1, 2, 3]:
for keyframe in channel.keyframe_points:
if keyframe.co[0] == frame:
change = True
value = channel.evaluate(frame)
if channel.array_index == 1:
rotation.x = value
elif channel.array_index == 2:
rotation.y = value
elif channel.array_index == 3:
rotation.z = value
elif channel.array_index == 0:
rotation.w = value
return change
def _handle_position_channel(channel, frame, position):
"""
:param channel:
:param frame:
:param position:
"""
change = False
if channel.array_index in [0, 1, 2]:
for keyframe in channel.keyframe_points:
if keyframe.co[0] == frame:
change = True
value = channel.evaluate(frame)
if channel.array_index == 0:
position.x = value
if channel.array_index == 1:
position.y = value
if channel.array_index == 2:
position.z = value
return change
def _quaternion_length(quat):
"""Calculate the length of a quaternion
:param quat: Blender quaternion object
:rtype: float
"""
return math.sqrt(quat.x * quat.x + quat.y * quat.y +
quat.z * quat.z + quat.w * quat.w)
def _normalize_quaternion(quat):
"""Normalize a quaternion
:param quat: Blender quaternion object
:returns: generic quaternion enum object with normalized values
:rtype: object
"""
enum = type('Enum', (), {'x': 0, 'y': 0, 'z': 0, 'w': 1})
length = _quaternion_length(quat)
if length is not 0:
length = 1 / length
enum.x = quat.x * length
enum.y = quat.y * length
enum.z = quat.z * length
enum.w = quat.w * length
return enum
| mit |
dkkline/CanSat14-15 | feeder/feeder.py | 1 | 3082 | """
Contains a tornado-based WebSocket server in charge of supplying
connected clients with live or replay data.
"""
import tornado.ioloop
import tornado.web
import tornado.websocket
from collections import deque
from pprint import pprint
import json
from .config import CACHE_SIZE, PORT, FREQUENCY
from groundstation.config import COM_FILE, BIND_ADDRESS
from groundstation.parse import parse_line
from groundstation.exceptions import InvalidLine
from groundstation.utilities import Buffer
com_handle = open(COM_FILE, "r")
buf = Buffer(com_handle)
clients = []
cache = deque(maxlen=CACHE_SIZE)
class BaseWebSocket(tornado.websocket.WebSocketHandler):
"""
A base class for all WebSocket interfaces.
"""
def check_origin(self, origin):
return True # All clients are welcome
class LiveDataWebSocket(BaseWebSocket):
"""
Serves clients connected to the live endpoint with live data.
"""
def open(self):
"""
Called when a client opens the connection.
"""
clients.append(self)
print("A client has opened a connection.")
for data_point in cache:
self.write_message(data_point)
def on_close(self):
"""
Called when a client closes the connection.
"""
clients.remove(self)
print("A client closed its connection.")
def on_message(self, message):
"""
Called when a client sends a message.
"""
print("[WARNNING] Got message: {}".format(message))
class ReplayWebSocket(BaseWebSocket):
"""
Serves clients connected to the replay endpoint.
"""
def broadcast(message):
"""
Broadcasts a message to all the connected clients.
"""
for client in clients:
client.write_message(message)
def get_data():
"""
Called by the ioloop to get data from the listener.
"""
try:
data = parse_line(buf)
except InvalidLine:
return
rel_data = {
"NTC": data["Temp_NTC"],
"Pressure": data["Press"],
"Height": data["Height"],
"Gyroscope": data["GyrZ"] / 360 * 60, # RPM
"Latitude": data["Lat"],
"Longitude": data["Long"]
}
# import random
# if random.randint(0, 10) == 5:
# rel_data["Latitude"] = float(random.randint(0, 10))
# rel_data["Longitude"] = float(random.randint(0, 10))
# rel_data["Height"] = float(random.randint(0, 1500))
pprint(rel_data)
post_data(rel_data)
# print(line, end="")
def post_data(data):
"""
Called by ``get_data``.
Sends ``data`` to the connected clients.
"""
json_data = json.dumps(data)
broadcast(json_data)
app = tornado.web.Application([
(r"/live", LiveDataWebSocket),
(r"/replay", ReplayWebSocket)
])
if __name__ == '__main__':
app.listen(PORT, BIND_ADDRESS)
loop = tornado.ioloop.IOLoop.instance()
getter = tornado.ioloop.PeriodicCallback(get_data, FREQUENCY,
io_loop=loop)
getter.start()
loop.start()
| mit |
panthorstudios/Gold-Rush | oldgame.py | 1 | 10225 | from random import random
from random import randint
import pygame
from pygame.locals import *
from miner import Miner
from explosion import Explosion
class Game(object):
TITLE = "Gold Rush!"
BOARD_LEFT = 20
BOARD_TOP = 130
SQUARE_SIZE = 32
BLACK = (0,0,0)
GREEN=(128,255,128)
YELLOW=(255,255,128)
RED=(255,128,128)
FRAMES_PER_SECOND = 30
ASSAY_X = 540
ASSAY_Y = 84
CHARGES_X = 180
CASH_X = 20
CASH_OFFSET = 30
GOLD_X = 16
CHARGES_OFFSET = 32
HEALTH_X =CHARGES_X + 40
TITLE_X = 340
def display_gold(self):
scoretext='%03d' % self.gold
for i in range(len(scoretext)):
num=int(scoretext[i])*24
pos=i*24
self.screen.blit(self.digits,(self.CASH_X+self.CASH_OFFSET+(i*24),20),(num,0,24,35))
def display_charges(self):
scoretext='%02d' % self.charges
for i in range(len(scoretext)):
num=int(scoretext[i])*24
pos=i*24
self.screen.blit(self.digits,(self.CHARGES_X+self.CHARGES_OFFSET+(i*24),20),(num,0,24,35))
def display_cash(self):
scoretext='%05d' % self.cash
for i in range(len(scoretext)):
num=int(scoretext[i])*24
pos=i*24
self.screen.blit(self.digits,(self.CASH_X+self.CASH_OFFSET+(i*24),66),(num,0,24,35))
def display_health(self):
h=int(84*(self.health/100.0))
b=84-h
c=self.GREEN
if self.health<20:
c=self.RED
elif self.health<40:
c=self.YELLOW
self.screen.fill(c,(self.HEALTH_X,70,h,32))
self.screen.fill(self.BLACK,(self.HEALTH_X+h,70,b,32))
# num=int(scoretext[i])*24
# pos=i*24
# self.screen.blit(self.digits,(self.CASH_X+self.CASH_OFFSET+(i*24),66),(num,0,24,35))
def __init__(self):
pygame.mixer.pre_init(44100,-16,2,2048)
pygame.init()
self.screen=pygame.display.set_mode((680,600))
pygame.display.set_caption(self.TITLE)
self.pressedkey=None
self.bellsound=pygame.mixer.Sound('assets/sounds/bell.ogg')
self.chargesound=pygame.mixer.Sound('assets/sounds/bomb.ogg')
self.yeehawsound=pygame.mixer.Sound('assets/sounds/yeehaw.ogg')
self.kachingsound=pygame.mixer.Sound('assets/sounds/kaching.ogg')
self.board=[]
self.bgbase=pygame.image.load('assets/images/background.png')
self.bg=pygame.image.load('assets/images/background.png')
self.digits=pygame.image.load('assets/images/digits.png')
self.gamearea=pygame.Surface(self.bg.get_size())
self.is_playing=False
# currently 2 nugget images
self.nuggets=[]
self.nuggets.append(pygame.image.load('assets/images/gold01-%dpx.png' % self.SQUARE_SIZE))
self.nuggets.append(pygame.image.load('assets/images/gold02-%dpx.png' % self.SQUARE_SIZE))
self.explosion=Explosion(0,0,self.SQUARE_SIZE)
self.explosion_group=pygame.sprite.RenderPlain(self.explosion)
self.miner=Miner(0,0)
self.clock=pygame.time.Clock()
# add title
text=pygame.image.load('assets/images/text_title.png')
self.screen.blit(text,(self.TITLE_X,self.BOARD_LEFT))
# add assay office
self.office=pygame.image.load('assets/images/assayoffice.png')
self.screen.blit(self.office,(self.ASSAY_X+self.BOARD_LEFT,self.ASSAY_Y))
self.cash=0
self.gold=0
self.charges=10
self.health=100
# add "Gold"
text=pygame.image.load('assets/images/nugget.png')
self.screen.blit(text,(self.GOLD_X,self.BOARD_LEFT))
self.display_gold()
# add "Cash"
text=pygame.image.load('assets/images/text_cash.png')
self.screen.blit(text,(self.CASH_X,66))
self.display_cash()
# add "Charges"
text=pygame.image.load('assets/images/dynamite.png')
self.screen.blit(text,(self.CHARGES_X,16))
self.display_charges()
# add "Miner head"
text=pygame.image.load('assets/images/miner_head.png')
self.screen.blit(text,(self.CHARGES_X,66))
self.display_health()
self.setup()
def setup(self):
# initialize score items
self.cash=0
self.gold=0
self.charges=10
# load background image every time
self.bg=pygame.image.load('assets/images/background.png')
#redraw assay office
self.bg.blit(self.office,(self.ASSAY_X,self.ASSAY_Y-self.BOARD_TOP))
self.board=[]
# top row of empty spaces
pathsup=2
self.board.append([' ']*20)
self.board.append(['*']*20)
for y in range(2,14):
row=[]
for x in range(20):
c='*'
if random()<0.4:
# make a hole
self.bg.fill(self.BLACK,(x*self.SQUARE_SIZE,y*self.SQUARE_SIZE,self.SQUARE_SIZE,self.SQUARE_SIZE))
c=' '
if y>1:
c='G'
nugg=self.nuggets[0 if random()<0.5 else 1]
self.bg.blit(nugg,(x*self.SQUARE_SIZE,y*self.SQUARE_SIZE))
row.append(c)
self.board.append(row)
# add soil
self.gamearea.blit(self.bg,(0,0))
pygame.display.flip()
def print_board(self):
for row in self.board:
print ' '.join(row)
def mainloop(self):
deltat=self.clock.tick(self.FRAMES_PER_SECOND)
tx=self.miner.x
ty=self.miner.y
self.miner_group.clear(self.gamearea,self.bg)
self.explosion_group.clear(self.gamearea,self.bg)
pressedspace=False
for event in pygame.event.get():
#print event
if event.type == KEYDOWN:
if event.key == K_ESCAPE:
exit(0)
elif event.key in (K_RIGHT,K_LEFT,K_UP,K_DOWN):
self.pressedkey= event.key
elif event.key == K_SPACE:
pressedspace = True
elif event.type == KEYUP:
if event.key in (K_RIGHT,K_LEFT,K_UP,K_DOWN):
if self.pressedkey == event.key:
self.pressedkey = None
#elif event.key == K_SPACE:
#pressedspace = False
# only draw explosion if necessary
if self.explosion.update(deltat):
self.explosion_group.update(deltat)
self.explosion_group.draw(self.gamearea)
else:
if pressedspace and self.pressedkey:
# Do explosion
pressedspace=False
bx=self.miner.x
by=self.miner.y
if self.pressedkey == K_LEFT:
bx-=1
if self.pressedkey == K_RIGHT:
bx+=1
if self.pressedkey == K_UP:
by-=1
if self.pressedkey == K_DOWN:
by+=1
if bx>=0 and bx<20 and (by>0 or (by==0 and self.pressedkey == K_DOWN)) and by<20 and self.charges>0:
self.explosion.explode(bx,by)
self.charges-=1
# print "(%d,%d)->(%d,%d) Boom! %d charges left." % (self.miner.x,self.miner.y,bx,by,self.charges)
self.board[by][bx]=' '
self.bg.fill(self.BLACK,(bx*self.SQUARE_SIZE,by*self.SQUARE_SIZE,self.SQUARE_SIZE,self.SQUARE_SIZE))
self.gamearea.blit(self.bg,(0,0))
self.display_charges()
#self.screen.blit(self.digits,(460+(i*24),20),(num,0,24,35))
self.chargesound.play()
for j in range(20):
x=randint(0,19)
y=randint(2,11)
o=self.board[y][x]
a=self.board[y-1][x]
if o==' ' and a=='*':
self.board[y][x]='*'
xpos=x*self.SQUARE_SIZE
ypos=y*self.SQUARE_SIZE
self.bg.blit(self.bgbase,(x*self.SQUARE_SIZE,y*self.SQUARE_SIZE),(xpos,ypos,self.SQUARE_SIZE,self.SQUARE_SIZE))
if self.pressedkey == K_RIGHT and self.miner.can_move():
if tx<19:
tx += 1
if self.pressedkey == K_LEFT and self.miner.can_move():
if tx>0:
tx -= 1
if self.pressedkey == K_UP and self.miner.can_move():
if ty>0:
ty -= 1
else:
if tx==17:
if self.gold!=0:
self.cash+=self.gold*self.charges
self.gold=0
self.kachingsound.play()
self.display_gold()
self.display_cash()
self.yeehawsound.play()
if self.pressedkey == K_DOWN and self.miner.can_move():
if ty<13:
ty += 1
o=self.board[ty][tx]
if (tx!=self.miner.x or ty!=self.miner.y) and o in ' G':
self.miner.set_location(tx,ty)
if o=='G':
self.board[ty][tx]=' '
self.gold += 1
self.bellsound.play()
self.bg.fill(self.BLACK,(self.miner.x*self.SQUARE_SIZE,self.miner.y*self.SQUARE_SIZE,self.SQUARE_SIZE,self.SQUARE_SIZE))
self.gamearea.blit(self.bg,(0,0))
self.display_gold()
self.miner.update_move()
self.miner_group.update(deltat)
self.miner_group.draw(self.gamearea)
if self.miner.y>0:
self.health-=0.25
if self.health<0:
self.health=0
pass
self.display_health()
else:
self.health+=1
if self.health>100:
self.health=100
self.display_health()
self.screen.blit(self.gamearea,(self.BOARD_LEFT,self.BOARD_TOP))
pygame.display.flip()
| mit |
cwilson1031/omaha | site_scons/site_tools/wix.py | 63 | 5679 | """SCons.Tool.wix
Tool-specific initialization for wix, the Windows Installer XML Tool.
There normally shouldn't be any need to import this module directly.
It will usually be imported through the generic SCons.Tool.Tool()
selection method.
"""
#
# Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009 The SCons Foundation
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
# KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#
__revision__ = "src/engine/SCons/Tool/wix.py 3897 2009/01/13 06:45:54 scons"
import SCons.Builder
import SCons.Action
import os
import string
def generate(env):
"""Add Builders and construction variables for WiX to an Environment."""
if not exists(env):
return
env['WIXCANDLEFLAGS'] = ['-nologo']
env['WIXCANDLEINCLUDE'] = []
env['WIXCANDLECOM'] = '$WIXCANDLE $WIXCANDLEFLAGS -I $WIXCANDLEINCLUDE -o ${TARGET} ${SOURCE}'
env['WIXLIGHTFLAGS'].append( '-nologo' )
env['WIXLIGHTCOM'] = "$WIXLIGHT $WIXLIGHTFLAGS -out ${TARGET} ${SOURCES}"
#BEGIN_OMAHA_ADDITION
# Necessary to build multiple MSIs from a single .wxs without explicitly
# building the .wixobj.
# Follows the convention of obj file prefixes in other tools, such as
# OBJPREFIX in msvc.py.
env['WIXOBJPREFIX'] = ''
#END_OMAHA_ADDITION
object_builder = SCons.Builder.Builder(
action = '$WIXCANDLECOM',
#BEGIN_OMAHA_ADDITION
prefix = '$WIXOBJPREFIX',
#END_OMAHA_ADDITION
#BEGIN_OMAHA_CHANGE
# The correct/default suffix is .wixobj, not .wxiobj.
# suffix = '.wxiobj',
suffix = '.wixobj',
#END_OMAHA_CHANGE
src_suffix = '.wxs')
linker_builder = SCons.Builder.Builder(
action = '$WIXLIGHTCOM',
#BEGIN_OMAHA_CHANGE
# The correct/default suffix is .wixobj, not .wxiobj.
# src_suffix = '.wxiobj',
src_suffix = '.wixobj',
#END_OMAHA_CHANGE
src_builder = object_builder)
env['BUILDERS']['WiX'] = linker_builder
def exists(env):
env['WIXCANDLE'] = 'candle.exe'
env['WIXLIGHT'] = 'light.exe'
#BEGIN_OMAHA_CHANGE
# # try to find the candle.exe and light.exe tools and
# try to find the candle.exe and light.exe tools and
#END_OMAHA_CHANGE
# add the install directory to light libpath.
#BEGIN_OMAHA_CHANGE
# For backwards compatibility, search PATH environment variable for tools.
# #for path in os.environ['PATH'].split(os.pathsep):
# for path in string.split(os.environ['PATH'], os.pathsep):
for path in os.environ['PATH'].split(os.pathsep):
#END_OMAHA_CHANGE
if not path:
continue
# workaround for some weird python win32 bug.
if path[0] == '"' and path[-1:]=='"':
path = path[1:-1]
# normalize the path
path = os.path.normpath(path)
# search for the tools in the PATH environment variable
try:
#BEGIN_OMAHA_CHANGE
# if env['WIXCANDLE'] in os.listdir(path) and\
# env['WIXLIGHT'] in os.listdir(path):
files = os.listdir(path)
if (env['WIXCANDLE'] in files and
env['WIXLIGHT'] in files):
# env.PrependENVPath('PATH', path)
env.PrependENVPath('PATH', path)
# env['WIXLIGHTFLAGS'] = [ os.path.join( path, 'wixui.wixlib' ),
# '-loc',
# os.path.join( path, 'WixUI_en-us.wxl' ) ]
# return 1
break
#END_OMAHA_CHANGE
except OSError:
pass # ignore this, could be a stale PATH entry.
#BEGIN_OMAHA_ADDITION
# Search for the tools in the SCons paths.
for path in env['ENV'].get('PATH', '').split(os.pathsep):
try:
files = os.listdir(path)
if (env['WIXCANDLE'] in files and
env['WIXLIGHT'] in files):
# The following is for compatibility with versions prior to 3.
# Version 3 no longer has these files.
extra_files = [os.path.join(i) for i in ['wixui.wixlib',
'WixUI_en-us.wxl']]
if (os.path.exists(extra_files[0]) and
os.path.exists(extra_files[1])):
env.Append(WIXLIGHTFLAGS=[
extra_files[0],
'-loc', extra_files[1]])
else:
# Create empty variable so the append in generate() works.
env.Append(WIXLIGHTFLAGS=[])
# WiX was found.
return 1
except OSError:
pass # ignore this, could be a stale PATH entry.
#END_OMAHA_ADDITION
return None
| apache-2.0 |
mpatacchiola/dissecting-reinforcement-learning | src/6/multi-armed-bandit/boltzman_agent_bandit.py | 1 | 4551 | #!/usr/bin/env python
# MIT License
# Copyright (c) 2017 Massimiliano Patacchiola
# https://mpatacchiola.github.io/blog/
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
#Average cumulated reward: 648.0975
#Std Cumulated Reward: 16.1566083616
#Average utility distribution: [ 0.29889418 0.49732589 0.79993241]
#Average utility RMSE: 0.0016711564118
from multi_armed_bandit import MultiArmedBandit
import numpy as np
import random
def return_rmse(predictions, targets):
"""Return the Root Mean Square error between two arrays
@param predictions an array of prediction values
@param targets an array of target values
@return the RMSE
"""
return np.sqrt(((predictions - targets)**2).mean())
def boltzmann(x, temperature):
"""Compute boltzmann distribution of array x.
@param x the input array
@param temperature
@return the boltzmann array
"""
exponent = np.true_divide(x - np.max(x), temperature)
return np.exp(exponent) / np.sum(np.exp(exponent))
def return_boltzmann_action(temperature, reward_counter_array):
"""Return an action using an epsilon greedy strategy
@return the action selected
"""
tot_arms = reward_counter_array.shape[0]
boltzmann_distribution = boltzmann(reward_counter_array, temperature)
return np.random.choice(tot_arms, p=boltzmann_distribution)
def main():
reward_distribution = [0.3, 0.5, 0.8]
my_bandit = MultiArmedBandit(reward_probability_list=reward_distribution)
temperature_start = 0.1
temperature_stop = 0.0001
epsilon = 0.1
tot_arms = 3
tot_episodes = 2000
tot_steps = 1000
print_every_episodes = 100
cumulated_reward_list = list()
average_utility_array = np.zeros(tot_arms)
temperature_array = np.linspace(temperature_start, temperature_stop, num=tot_steps)
print("Starting Boltzmann agent...")
for episode in range(tot_episodes):
cumulated_reward = 0
reward_counter_array = np.zeros(tot_arms)
action_counter_array = np.full(tot_arms, 1.0e-5)
for step in range(tot_steps):
temperature = temperature_array[step]
action = return_boltzmann_action(temperature, np.true_divide(reward_counter_array, action_counter_array))
reward = my_bandit.step(action)
reward_counter_array[action] += reward
action_counter_array[action] += 1
cumulated_reward += reward
# Append the cumulated reward for this episode in a list
cumulated_reward_list.append(cumulated_reward)
utility_array = np.true_divide(reward_counter_array, action_counter_array)
average_utility_array += utility_array
if episode % print_every_episodes == 0:
print("Episode: " + str(episode))
print("Cumulated Reward: " + str(cumulated_reward))
print("Reward counter: " + str(reward_counter_array))
print("Utility distribution: " + str(utility_array))
print("Utility RMSE: " + str(return_rmse(utility_array, reward_distribution)))
print("")
# Print the average cumulated reward for all the episodes
print("Average cumulated reward: " + str(np.mean(cumulated_reward_list)))
print("Std Cumulated Reward: " + str(np.std(cumulated_reward_list)))
print("Average utility distribution: " + str(average_utility_array / tot_episodes))
print("Average utility RMSE: " + str(return_rmse(average_utility_array/tot_episodes, reward_distribution)))
if __name__ == "__main__":
main()
| mit |
BehavioralInsightsTeam/edx-platform | openedx/core/djangoapps/site_configuration/tests/test_middleware.py | 22 | 5267 | # -*- coding: utf-8 -*-
"""
Test site_configuration middleware.
"""
import ddt
from mock import patch
from django.conf import settings
from django.test import TestCase
from django.test.client import Client
from django.test.utils import override_settings
from student.tests.factories import UserFactory
from microsite_configuration.microsite import (
get_backend,
)
from microsite_configuration.backends.base import BaseMicrositeBackend
from microsite_configuration.tests.tests import (
DatabaseMicrositeTestCase,
side_effect_for_get_value,
MICROSITE_BACKENDS,
)
from openedx.core.djangoapps.site_configuration.tests.factories import SiteConfigurationFactory, SiteFactory
from openedx.core.djangolib.testing.utils import skip_unless_lms
# NOTE: We set SESSION_SAVE_EVERY_REQUEST to True in order to make sure
# Sessions are always started on every request
# pylint: disable=no-member, protected-access
@ddt.ddt
@override_settings(SESSION_SAVE_EVERY_REQUEST=True)
@skip_unless_lms
class SessionCookieDomainMicrositeOverrideTests(DatabaseMicrositeTestCase):
"""
Tests regarding the session cookie management in the middlware for Microsites
"""
def setUp(self):
super(SessionCookieDomainMicrositeOverrideTests, self).setUp()
# Create a test client, and log it in so that it will save some session
# data.
self.user = UserFactory.create()
self.user.set_password('password')
self.user.save()
self.client = Client()
self.client.login(username=self.user.username, password="password")
self.site = SiteFactory.create(
domain='testserver.fake',
name='testserver.fake'
)
self.site_configuration = SiteConfigurationFactory.create(
site=self.site,
values={
"SESSION_COOKIE_DOMAIN": self.site.domain,
}
)
@ddt.data(*MICROSITE_BACKENDS)
def test_session_cookie_domain_no_override(self, site_backend):
"""
Test sessionid cookie when no override is set
"""
with patch('microsite_configuration.microsite.BACKEND',
get_backend(site_backend, BaseMicrositeBackend)):
response = self.client.get('/')
self.assertNotIn('test_site.localhost', str(response.cookies['sessionid']))
self.assertNotIn('Domain', str(response.cookies['sessionid']))
@ddt.data(*MICROSITE_BACKENDS)
def test_session_cookie_domain_with_microsite_override(self, site_backend):
"""
Makes sure that the cookie being set in a Microsite
is the one specially overridden in configuration
"""
with patch('microsite_configuration.microsite.BACKEND',
get_backend(site_backend, BaseMicrositeBackend)):
response = self.client.get('/', HTTP_HOST=settings.MICROSITE_TEST_HOSTNAME)
self.assertIn('test_site.localhost', str(response.cookies['sessionid']))
@ddt.data(*MICROSITE_BACKENDS)
def test_microsite_none_cookie_domain(self, site_backend):
"""
Tests to make sure that a Microsite that specifies None for 'SESSION_COOKIE_DOMAIN' does not
set a domain on the session cookie
"""
with patch('microsite_configuration.microsite.get_value') as mock_get_value:
mock_get_value.side_effect = side_effect_for_get_value('SESSION_COOKIE_DOMAIN', None)
with patch('microsite_configuration.microsite.BACKEND',
get_backend(site_backend, BaseMicrositeBackend)):
response = self.client.get('/', HTTP_HOST=settings.MICROSITE_TEST_HOSTNAME)
self.assertNotIn('test_site.localhost', str(response.cookies['sessionid']))
self.assertNotIn('Domain', str(response.cookies['sessionid']))
# NOTE: We set SESSION_SAVE_EVERY_REQUEST to True in order to make sure
# Sessions are always started on every request
# pylint: disable=no-member, protected-access
@override_settings(SESSION_SAVE_EVERY_REQUEST=True)
class SessionCookieDomainSiteConfigurationOverrideTests(TestCase):
"""
Tests regarding the session cookie management in the middlware for Microsites
"""
def setUp(self):
super(SessionCookieDomainSiteConfigurationOverrideTests, self).setUp()
# Create a test client, and log it in so that it will save some session data.
self.user = UserFactory.create()
self.user.set_password('password')
self.user.save()
self.site = SiteFactory.create(
domain='testserver.fake',
name='testserver.fake'
)
self.site_configuration = SiteConfigurationFactory.create(
site=self.site,
values={
"SESSION_COOKIE_DOMAIN": self.site.domain,
}
)
self.client = Client()
self.client.login(username=self.user.username, password="password")
def test_session_cookie_domain_with_site_configuration_override(self):
"""
Makes sure that the cookie being set is for the overridden domain
"""
response = self.client.get('/', HTTP_HOST=self.site.domain)
self.assertIn(self.site.domain, str(response.cookies['sessionid']))
| agpl-3.0 |
oesteban/phantomas | phantomas/utils/shm.py | 1 | 6453 | """
This module contains an implementation of the real, antipodally symmetric
Spherical Harmonics basis as defined in [1]_.
References
----------
.. [1] Descoteaux, Maxime, Elaine Angelino, Shaun Fitzgibbons, and Rachid
Deriche. "Regularized, fast, and robust analytical Q-ball imaging"
Magnetic Resonance in Medicine 58, no. 3 (2007): 497-510
"""
import numpy as np
from scipy.misc import factorial
from scipy.special import lpmv, legendre, sph_harm
import hashlib
def angular_function(j, theta, phi):
"""
Returns the values of the spherical harmonics function at given
positions specified by colatitude and aximuthal angles.
Parameters
----------
j : int
The spherical harmonic index.
theta : array-like, shape (K, )
The colatitude angles.
phi : array-like, shape (K, )
The azimuth angles.
Returns
-------
f : array-like, shape (K, )
The value of the function at given positions.
"""
l = sh_degree(j)
m = sh_order(j)
# We follow here reverse convention about theta and phi w.r.t scipy.
sh = sph_harm(np.abs(m), l, phi, theta)
if m < 0:
return np.sqrt(2) * sh.real
if m == 0:
return sh.real
if m > 0:
return np.sqrt(2) * sh.imag
def spherical_function(j, x, y, z):
"""
Returns the values of the spherical harmonics function at given
positions specified by Cartesian coordinates.
Parameters
----------
x, y, z : array-like, shape (K, )
Cartesian coordinates.
Returns
-------
f : array-like, shape (K, )
The value of the function at given positions.
"""
theta = np.arccos(z)
phi = np.arctan2(y, x)
return angular_function(j, theta, phi)
def dimension(order):
r"""
Returns the dimension, :math:`R`, of the real, antipodally symmetric
spherical harmonics basis for a given truncation order.
Parameters
----------
order : int
The trunction order.
Returns
-------
R : int
The dimension of the truncated spherical harmonics basis.
"""
return (order + 1) * (order + 2) / 2
def j(l, m):
r"""
Returns the flattened spherical harmonics index corresponding to degree
``l`` and order ``m``.
Parameters
----------
l : int
Degree of the spherical harmonics. Should be even.
m : int
Order of the spherical harmonics, should verify :math:`-l \leq m \leq l`
Returns
-------
j : int
The associated index of the spherical harmonic.
"""
if np.abs(m) > l:
raise NameError('SphericalHarmonics.j: m must lie in [-l, l]')
return int(l + m + (2 * np.array(range(0, l, 2)) + 1).sum())
def sh_degree(j):
"""
Returns the degree, ``l``, of the spherical harmonic associated to index
``j``.
Parameters
----------
j : int
The flattened index of the spherical harmonic.
Returns
-------
l : int
The associated even degree.
"""
l = 0
while dimension(l) - 1 < j:
l += 2
return l
def sh_order(j):
"""
Returns the order, ``m``, of the spherical harmonic associated to index
``j``.
Parameters
----------
j : int
The flattened index of the spherical harmonic.
Returns
-------
m : int
The associated order.
"""
l = sh_degree(j)
return j + l + 1 - dimension(l)
class _CachedMatrix():
"""
Returns the spherical harmonics observation matrix.
Parameters
----------
theta : array-like, shape (K, )
The colatitude angles.
phi : array-like, shape (K, )
The azimuth angles.
order : int
The spherical harmonics truncation order.
cache : bool
Whether the result should be cached or not.
Returns
-------
H : array-like, shape (K, R)
The spherical harmonics observation matrix.
"""
def __init__(self):
self._cache = {}
def __call__(self, theta, phi, order=4, cache=True):
if not cache:
return self._eval_matrix(theta, phi, order)
key1 = self._hash(theta)
key2 = self._hash(phi)
if (key1, key2, order) in self._cache:
return self._cache[(key1, key2, order)]
else:
val = self._eval_matrix(theta, phi, order)
self._cache[(key1, key2, order)] = val
return val
def _hash(self, np_array):
return hashlib.sha1(np_array).hexdigest()
def _eval_matrix(self, theta, phi, order):
N = theta.shape[0]
dim_sh = dimension(order)
ls = [l for L in range(0, order + 1, 2) for l in [L] * (2*L + 1)]
ms = [m for L in range(0, order + 1, 2) for m in range(-L, L+1)]
ls = np.asarray(ls, dtype=np.int)[np.newaxis, :]
ms = np.asarray(ms, dtype=np.int)[np.newaxis, :]
sh = sph_harm(np.abs(ms), ls,
phi[:, np.newaxis], theta[:, np.newaxis])
H = np.where(ms > 0, sh.imag, sh.real)
H[:, (ms != 0)[0]] *= np.sqrt(2)
return H
matrix = _CachedMatrix()
def L(order=4):
"""Computees the Laplace-Beltrami operator matrix.
Parameters
----------
order : int
The truncation order (should be an even number).
"""
dim_sh = dimension(order)
L = np.zeros((dim_sh, dim_sh))
for j in range(dim_sh):
l = sh_degree(j)
L[j, j] = - (l * (l + 1))
return L
def P(order=4):
"""Returns the Funk-Radon operator matrix.
Parameters
----------
order : int
The truncation order (should be an even number).
"""
dim_sh = dimension(order)
P = zeros((dim_sh, dim_sh))
for j in range(dim_sh):
l = sh_degree(j)
P[j, j] = 2 * pi * legendre(l)(0)
return P
def convert_to_mrtrix(order):
"""
Returns the linear matrix used to convert coefficients into the mrtrix
convention for spherical harmonics.
Parameters
----------
order : int
Returns
-------
conversion_matrix : array-like, shape (dim_sh, dim_sh)
"""
dim_sh = dimension(order)
conversion_matrix = np.zeros((dim_sh, dim_sh))
for j in range(dim_sh):
l = sh_degree(j)
m = sh_order(j)
if m == 0:
conversion_matrix[j, j] = 1
else:
conversion_matrix[j, j - 2*m] = np.sqrt(2)
return conversion_matrix
| bsd-3-clause |
ropik/chromium | chrome/test/functional/chromeos_ephemeral.py | 6 | 9687 | # Copyright (c) 2012 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import logging
import os
import sys
import pyauto_functional # Must come before pyauto (and thus, policy_base).
import policy_base
sys.path.append('/usr/local') # Required to import autotest libs.
from autotest.cros import constants
from autotest.cros import cryptohome
class ChromeosEphemeral(policy_base.PolicyTestBase):
"""Tests a policy that makes all users except the owner ephemeral.
When this policy is enabled, no persistent information in the form of
cryptohome shadow directories or local state prefs should be created for
users. Additionally, any persistent information previously accumulated should
be cleared when a user first logs in after enabling the policy."""
def _SetDevicePolicyAndOwner(self, ephemeral_users_enabled, owner_index):
"""Sets device policy and owner.
TODO(bartfab): Ensure Login still works after crosbug.com/20709 is fixed.
The show_user_names policy is set to False to ensure that even if the local
state is not being automatically cleared, the login screen never shows user
pods. This is required by the Login browser automation call.
"""
self.SetDevicePolicy(
device_policy={'ephemeral_users_enabled': ephemeral_users_enabled,
'show_user_names': False},
owner=self._usernames[owner_index])
def _DoesVaultDirectoryExist(self, user_index):
user_hash = cryptohome.get_user_hash(self._usernames[user_index])
return os.path.exists(os.path.join(constants.SHADOW_ROOT, user_hash))
def _AssertLocalStatePrefsSet(self, user_indexes):
expected = sorted([self._usernames[index] for index in user_indexes])
# The OAuthTokenStatus pref is populated asynchronously. Checking whether it
# is set would lead to an ugly race.
for pref in ['LoggedInUsers', 'UserImages', 'UserDisplayEmail', ]:
actual = sorted(self.GetLocalStatePrefsInfo().Prefs(pref))
self.assertEqual(actual, expected,
msg='Expected to find prefs in local state for users.')
def _AssertLocalStatePrefsEmpty(self):
for pref in ['LoggedInUsers',
'UserImages',
'UserDisplayEmail',
'OAuthTokenStatus']:
self.assertFalse(self.GetLocalStatePrefsInfo().Prefs(pref),
msg='Expected to not find prefs in local state for any user.')
def _AssertVaultDirectoryExists(self, user_index):
self.assertTrue(self._DoesVaultDirectoryExist(user_index=user_index),
msg='Expected vault shadow directory to exist.')
def _AssertVaultDirectoryDoesNotExist(self, user_index):
self.assertFalse(self._DoesVaultDirectoryExist(user_index=user_index),
msg='Expected vault shadow directory to not exist.')
def _AssertVaultMounted(self, user_index, ephemeral):
if ephemeral:
device_regex = constants.CRYPTOHOME_DEV_REGEX_REGULAR_USER_EPHEMERAL
fs_regex = constants.CRYPTOHOME_FS_REGEX_TMPFS
else:
device_regex = constants.CRYPTOHOME_DEV_REGEX_REGULAR_USER_SHADOW
fs_regex = constants.CRYPTOHOME_FS_REGEX_ANY
self.assertTrue(
cryptohome.is_vault_mounted(device_regex=device_regex,
fs_regex=fs_regex,
user=self._usernames[user_index],
allow_fail=True),
msg='Expected vault backed by %s to be mounted.' %
'tmpfs' if ephemeral else 'shadow directory')
def _AssertNoVaultMounted(self):
self.assertFalse(cryptohome.is_vault_mounted(allow_fail=True),
msg='Did not expect any vault to be mounted.')
def Login(self, user_index):
self.assertFalse(self.GetLoginInfo()['is_logged_in'],
msg='Expected to be logged out.')
policy_base.PolicyTestBase.Login(self,
self._usernames[user_index],
self._passwords[user_index])
self.assertTrue(self.GetLoginInfo()['is_logged_in'],
msg='Expected to be logged in.')
def ExtraChromeFlags(self):
"""Sets up Chrome to skip OOBE.
TODO(bartfab): Ensure OOBE is still skipped when crosbug.com/20709 is fixed.
Disabling automatic clearing of the local state has the curious side effect
of removing a flag that disables OOBE. This method adds back the flag.
"""
flags = policy_base.PolicyTestBase.ExtraChromeFlags(self)
flags.append('--login-screen=login')
return flags
def setUp(self):
policy_base.PolicyTestBase.setUp(self)
# TODO(bartfab): Remove this after crosbug.com/20709 is fixed.
# Try to disable automatic clearing of the local state.
self.TryToDisableLocalStateAutoClearingOnChromeOS()
self._local_state_auto_clearing = \
self.IsLocalStateAutoClearingEnabledOnChromeOS()
if not self._local_state_auto_clearing:
# Prevent the inherited Logout() method from cleaning up /home/chronos
# as this also clears the local state.
self.set_clear_profile(False)
credentials = (self.GetPrivateInfo()['prod_enterprise_test_user'],
self.GetPrivateInfo()['prod_enterprise_executive_user'],
self.GetPrivateInfo()['prod_enterprise_sales_user'])
self._usernames = [credential['username'] for credential in credentials]
self._passwords = [credential['password'] for credential in credentials]
def tearDown(self):
# TODO(bartfab): Remove this after crosbug.com/20709 is fixed.
# Try to re-enable automatic clearing of the local state and /home/chronos.
if not self._local_state_auto_clearing:
self.TryToEnableLocalStateAutoClearingOnChromeOS()
self.set_clear_profile(True)
policy_base.PolicyTestBase.tearDown(self)
def testLoginAsOwnerIsNotEphemeral(self):
"""Checks that the owner does not become ephemeral."""
self._SetDevicePolicyAndOwner(ephemeral_users_enabled=True, owner_index=0)
self.Login(user_index=0)
# TODO(bartfab): Remove this when crosbug.com/20709 is fixed.
if self._local_state_auto_clearing:
self._AssertLocalStatePrefsSet(user_indexes=[0])
self._AssertVaultDirectoryExists(user_index=0)
self._AssertVaultMounted(user_index=0, ephemeral=False)
self.Logout()
# TODO(bartfab): Make this unconditional when crosbug.com/20709 is fixed.
if not self._local_state_auto_clearing:
self._AssertLocalStatePrefsSet(user_indexes=[0])
self._AssertVaultDirectoryExists(user_index=0)
self._AssertNoVaultMounted()
def testLoginAsNonOwnerIsEphemeral(self):
"""Checks that a non-owner user does become ephemeral."""
self._SetDevicePolicyAndOwner(ephemeral_users_enabled=True, owner_index=0)
self.Login(user_index=1)
# TODO(bartfab): Remove this when crosbug.com/20709 is fixed.
if self._local_state_auto_clearing:
self._AssertLocalStatePrefsEmpty()
self._AssertVaultDirectoryDoesNotExist(user_index=1)
self._AssertVaultMounted(user_index=1, ephemeral=True)
self.Logout()
# TODO(bartfab): Make this unconditional when crosbug.com/20709 is fixed.
if not self._local_state_auto_clearing:
self._AssertLocalStatePrefsEmpty()
self._AssertVaultDirectoryDoesNotExist(user_index=1)
self._AssertNoVaultMounted()
def testEnablingEphemeralUsersCleansUp(self):
"""Checks that persistent information is cleared."""
self._SetDevicePolicyAndOwner(ephemeral_users_enabled=False, owner_index=0)
self.Login(user_index=0)
# TODO(bartfab): Remove this when crosbug.com/20709 is fixed.
if self._local_state_auto_clearing:
self._AssertLocalStatePrefsSet(user_indexes=[0])
self.Logout()
# TODO(bartfab): Make this unconditional when crosbug.com/20709 is fixed.
if not self._local_state_auto_clearing:
self._AssertLocalStatePrefsSet(user_indexes=[0])
self.Login(user_index=1)
# TODO(bartfab): Remove this when crosbug.com/20709 is fixed.
if self._local_state_auto_clearing:
self._AssertLocalStatePrefsSet(user_indexes=[1])
self.Logout()
# TODO(bartfab): Make this unconditional when crosbug.com/20709 is fixed.
if not self._local_state_auto_clearing:
self._AssertLocalStatePrefsSet(user_indexes=[0, 1])
self.Login(user_index=2)
# TODO(bartfab): Remove this when crosbug.com/20709 is fixed.
if self._local_state_auto_clearing:
self._AssertLocalStatePrefsSet(user_indexes=[2])
self.Logout()
# TODO(bartfab): Make this unconditional when crosbug.com/20709 is fixed.
if not self._local_state_auto_clearing:
self._AssertLocalStatePrefsSet(user_indexes=[0, 1, 2])
self._AssertVaultDirectoryExists(user_index=0)
self._AssertVaultDirectoryExists(user_index=1)
self._AssertVaultDirectoryExists(user_index=2)
self._SetDevicePolicyAndOwner(ephemeral_users_enabled=True, owner_index=0)
self.Login(user_index=1)
# TODO(bartfab): Remove this when crosbug.com/20709 is fixed.
if self._local_state_auto_clearing:
self._AssertLocalStatePrefsEmpty()
self._AssertVaultMounted(user_index=1, ephemeral=True)
self.Logout()
# TODO(bartfab): Make this unconditional when crosbug.com/20709 is fixed.
if not self._local_state_auto_clearing:
self._AssertLocalStatePrefsSet(user_indexes=[0])
self._AssertVaultDirectoryExists(user_index=0)
self._AssertVaultDirectoryDoesNotExist(user_index=1)
self._AssertVaultDirectoryDoesNotExist(user_index=2)
if __name__ == '__main__':
pyauto_functional.Main()
| bsd-3-clause |
ojengwa/oh-mainline | vendor/packages/python-social-auth/social/backends/xing.py | 83 | 1519 | """
XING OAuth1 backend, docs at:
http://psa.matiasaguirre.net/docs/backends/xing.html
"""
from social.backends.oauth import BaseOAuth1
class XingOAuth(BaseOAuth1):
"""Xing OAuth authentication backend"""
name = 'xing'
AUTHORIZATION_URL = 'https://api.xing.com/v1/authorize'
REQUEST_TOKEN_URL = 'https://api.xing.com/v1/request_token'
ACCESS_TOKEN_URL = 'https://api.xing.com/v1/access_token'
SCOPE_SEPARATOR = '+'
EXTRA_DATA = [
('id', 'id'),
('user_id', 'user_id')
]
def get_user_details(self, response):
"""Return user details from Xing account"""
email = response.get('email', '')
fullname, first_name, last_name = self.get_user_names(
first_name=response['first_name'],
last_name=response['last_name']
)
return {'username': first_name + last_name,
'fullname': fullname,
'first_name': first_name,
'last_name': last_name,
'email': email}
def user_data(self, access_token, *args, **kwargs):
"""Return user data provided"""
profile = self.get_json(
'https://api.xing.com/v1/users/me.json',
auth=self.oauth_auth(access_token)
)['users'][0]
return {
'user_id': profile['id'],
'id': profile['id'],
'first_name': profile['first_name'],
'last_name': profile['last_name'],
'email': profile['active_email']
}
| agpl-3.0 |
sinisterrook/arduinojavatomaven | arduino-core/src/processing/app/i18n/python/requests/packages/urllib3/poolmanager.py | 168 | 6142 | # urllib3/poolmanager.py
# Copyright 2008-2012 Andrey Petrov and contributors (see CONTRIBUTORS.txt)
#
# This module is part of urllib3 and is released under
# the MIT License: http://www.opensource.org/licenses/mit-license.php
import logging
from ._collections import RecentlyUsedContainer
from .connectionpool import HTTPConnectionPool, HTTPSConnectionPool
from .connectionpool import connection_from_url, port_by_scheme
from .request import RequestMethods
from .util import parse_url
__all__ = ['PoolManager', 'ProxyManager', 'proxy_from_url']
pool_classes_by_scheme = {
'http': HTTPConnectionPool,
'https': HTTPSConnectionPool,
}
log = logging.getLogger(__name__)
class PoolManager(RequestMethods):
"""
Allows for arbitrary requests while transparently keeping track of
necessary connection pools for you.
:param num_pools:
Number of connection pools to cache before discarding the least
recently used pool.
:param headers:
Headers to include with all requests, unless other headers are given
explicitly.
:param \**connection_pool_kw:
Additional parameters are used to create fresh
:class:`urllib3.connectionpool.ConnectionPool` instances.
Example: ::
>>> manager = PoolManager(num_pools=2)
>>> r = manager.request('GET', 'http://google.com/')
>>> r = manager.request('GET', 'http://google.com/mail')
>>> r = manager.request('GET', 'http://yahoo.com/')
>>> len(manager.pools)
2
"""
def __init__(self, num_pools=10, headers=None, **connection_pool_kw):
RequestMethods.__init__(self, headers)
self.connection_pool_kw = connection_pool_kw
self.pools = RecentlyUsedContainer(num_pools,
dispose_func=lambda p: p.close())
def _new_pool(self, scheme, host, port):
"""
Create a new :class:`ConnectionPool` based on host, port and scheme.
This method is used to actually create the connection pools handed out
by :meth:`connection_from_url` and companion methods. It is intended
to be overridden for customization.
"""
pool_cls = pool_classes_by_scheme[scheme]
return pool_cls(host, port, **self.connection_pool_kw)
def clear(self):
"""
Empty our store of pools and direct them all to close.
This will not affect in-flight connections, but they will not be
re-used after completion.
"""
self.pools.clear()
def connection_from_host(self, host, port=None, scheme='http'):
"""
Get a :class:`ConnectionPool` based on the host, port, and scheme.
If ``port`` isn't given, it will be derived from the ``scheme`` using
``urllib3.connectionpool.port_by_scheme``.
"""
scheme = scheme or 'http'
port = port or port_by_scheme.get(scheme, 80)
pool_key = (scheme, host, port)
# If the scheme, host, or port doesn't match existing open connections,
# open a new ConnectionPool.
pool = self.pools.get(pool_key)
if pool:
return pool
# Make a fresh ConnectionPool of the desired type
pool = self._new_pool(scheme, host, port)
self.pools[pool_key] = pool
return pool
def connection_from_url(self, url):
"""
Similar to :func:`urllib3.connectionpool.connection_from_url` but
doesn't pass any additional parameters to the
:class:`urllib3.connectionpool.ConnectionPool` constructor.
Additional parameters are taken from the :class:`.PoolManager`
constructor.
"""
u = parse_url(url)
return self.connection_from_host(u.host, port=u.port, scheme=u.scheme)
def urlopen(self, method, url, redirect=True, **kw):
"""
Same as :meth:`urllib3.connectionpool.HTTPConnectionPool.urlopen`
with custom cross-host redirect logic and only sends the request-uri
portion of the ``url``.
The given ``url`` parameter must be absolute, such that an appropriate
:class:`urllib3.connectionpool.ConnectionPool` can be chosen for it.
"""
u = parse_url(url)
conn = self.connection_from_host(u.host, port=u.port, scheme=u.scheme)
kw['assert_same_host'] = False
kw['redirect'] = False
if 'headers' not in kw:
kw['headers'] = self.headers
response = conn.urlopen(method, u.request_uri, **kw)
redirect_location = redirect and response.get_redirect_location()
if not redirect_location:
return response
if response.status == 303:
method = 'GET'
log.info("Redirecting %s -> %s" % (url, redirect_location))
kw['retries'] = kw.get('retries', 3) - 1 # Persist retries countdown
return self.urlopen(method, redirect_location, **kw)
class ProxyManager(RequestMethods):
"""
Given a ConnectionPool to a proxy, the ProxyManager's ``urlopen`` method
will make requests to any url through the defined proxy. The ProxyManager
class will automatically set the 'Host' header if it is not provided.
"""
def __init__(self, proxy_pool):
self.proxy_pool = proxy_pool
def _set_proxy_headers(self, url, headers=None):
"""
Sets headers needed by proxies: specifically, the Accept and Host
headers. Only sets headers not provided by the user.
"""
headers_ = {'Accept': '*/*'}
host = parse_url(url).host
if host:
headers_['Host'] = host
if headers:
headers_.update(headers)
return headers_
def urlopen(self, method, url, **kw):
"Same as HTTP(S)ConnectionPool.urlopen, ``url`` must be absolute."
kw['assert_same_host'] = False
kw['headers'] = self._set_proxy_headers(url, headers=kw.get('headers'))
return self.proxy_pool.urlopen(method, url, **kw)
def proxy_from_url(url, **pool_kw):
proxy_pool = connection_from_url(url, **pool_kw)
return ProxyManager(proxy_pool)
| gpl-2.0 |
richo/rust | src/etc/snapshot.py | 4 | 7922 | # Copyright 2011-2015 The Rust Project Developers. See the COPYRIGHT
# file at the top-level directory of this distribution and at
# http://rust-lang.org/COPYRIGHT.
#
# Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
# http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
# <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
# option. This file may not be copied, modified, or distributed
# except according to those terms.
import re
import os
import sys
import glob
import tarfile
import shutil
import subprocess
import distutils.spawn
try:
import hashlib
sha_func = hashlib.sha1
except ImportError:
import sha
sha_func = sha.new
def scrub(b):
if sys.version_info >= (3,) and type(b) == bytes:
return b.decode('ascii')
else:
return b
src_dir = scrub(os.getenv("CFG_SRC_DIR"))
if not src_dir:
raise Exception("missing env var CFG_SRC_DIR")
snapshotfile = os.path.join(src_dir, "src", "snapshots.txt")
download_url_base = "https://static.rust-lang.org/stage0-snapshots"
download_dir_base = "dl"
download_unpack_base = os.path.join(download_dir_base, "unpack")
snapshot_files = {
"linux": ["bin/rustc"],
"macos": ["bin/rustc"],
"winnt": ["bin/rustc.exe"],
"freebsd": ["bin/rustc"],
"dragonfly": ["bin/rustc"],
"openbsd": ["bin/rustc"],
}
winnt_runtime_deps_32 = ["libgcc_s_dw2-1.dll", "libstdc++-6.dll"]
winnt_runtime_deps_64 = ["libgcc_s_seh-1.dll", "libstdc++-6.dll"]
def parse_line(n, line):
global snapshotfile
if re.match(r"\s*$", line):
return None
if re.match(r"^T\s*$", line):
return None
match = re.match(r"\s+([\w_-]+) ([a-fA-F\d]{40})\s*$", line)
if match:
return {"type": "file",
"platform": match.group(1),
"hash": match.group(2).lower()}
match = re.match(r"([ST]) (\d{4}-\d{2}-\d{2}) ([a-fA-F\d]+)\s*$", line)
if not match:
raise Exception("%s:%d:E syntax error: " % (snapshotfile, n))
return {"type": "snapshot",
"date": match.group(2),
"rev": match.group(3)}
def partial_snapshot_name(date, rev, platform):
return ("rust-stage0-%s-%s-%s.tar.bz2" %
(date, rev, platform))
def full_snapshot_name(date, rev, platform, hsh):
return ("rust-stage0-%s-%s-%s-%s.tar.bz2" %
(date, rev, platform, hsh))
def get_kernel(triple):
t = triple.split('-')
if len(t) == 2:
os_name = t[1]
else:
os_name = t[2]
if os_name == "windows":
return "winnt"
if os_name == "darwin":
return "macos"
if os_name == "freebsd":
return "freebsd"
if os_name == "dragonfly":
return "dragonfly"
if os_name == "openbsd":
return "openbsd"
return "linux"
def get_cpu(triple):
arch = triple.split('-')[0]
if arch == "i686":
return "i386"
return arch
def get_platform(triple):
return "%s-%s" % (get_kernel(triple), get_cpu(triple))
def cmd_out(cmdline):
p = subprocess.Popen(cmdline, stdout=subprocess.PIPE)
return scrub(p.communicate()[0].strip())
def local_rev_info(field):
return cmd_out(["git", "--git-dir=" + os.path.join(src_dir, ".git"),
"log", "-n", "1",
"--format=%%%s" % field, "HEAD"])
def local_rev_full_sha():
return local_rev_info("H").split()[0]
def local_rev_short_sha():
return local_rev_info("h").split()[0]
def local_rev_committer_date():
return local_rev_info("ci")
def get_url_to_file(u, f):
# no security issue, just to stop partial download leaving a stale file
tmpf = f + '.tmp'
returncode = -1
if distutils.spawn.find_executable("curl"):
returncode = subprocess.call(["curl", "-o", tmpf, u])
elif distutils.spawn.find_executable("wget"):
returncode = subprocess.call(["wget", "-O", tmpf, u])
if returncode != 0:
try:
os.unlink(tmpf)
except OSError:
pass
raise Exception("failed to fetch url")
os.rename(tmpf, f)
def snap_filename_hash_part(snap):
match = re.match(r".*([a-fA-F\d]{40}).tar.bz2$", snap)
if not match:
raise Exception("unable to find hash in filename: " + snap)
return match.group(1)
def hash_file(x):
h = sha_func()
h.update(open(x, "rb").read())
return scrub(h.hexdigest())
def get_winnt_runtime_deps(platform):
"""Returns a list of paths of Rust's system runtime dependencies"""
if platform == "winnt-x86_64":
deps = winnt_runtime_deps_64
else:
deps = winnt_runtime_deps_32
runtime_deps = []
path_dirs = os.environ["PATH"].split(os.pathsep)
for name in deps:
for dir in path_dirs:
filepath = os.path.join(dir, name)
if os.path.isfile(filepath):
runtime_deps.append(filepath)
break
else:
raise Exception("Could not find runtime dependency: %s" % name)
return runtime_deps
def make_snapshot(stage, triple):
kernel = get_kernel(triple)
platform = get_platform(triple)
rev = local_rev_short_sha()
date = local_rev_committer_date().split()[0]
file0 = partial_snapshot_name(date, rev, platform)
def in_tar_name(fn):
cs = re.split(r"[\\/]", fn)
if len(cs) >= 2:
return os.sep.join(cs[-2:])
tar = tarfile.open(file0, "w:bz2")
for name in snapshot_files[kernel]:
dir = stage
if stage == "stage1" and re.match(r"^lib/(lib)?std.*", name):
dir = "stage0"
fn_glob = os.path.join(triple, dir, name)
matches = glob.glob(fn_glob)
if not matches:
raise Exception("Not found file with name like " + fn_glob)
if len(matches) == 1:
tar.add(matches[0], "rust-stage0/" + in_tar_name(matches[0]))
else:
raise Exception("Found stale files: \n %s\n"
"Please make a clean build." % "\n ".join(matches))
if kernel == "winnt":
for path in get_winnt_runtime_deps(platform):
tar.add(path, "rust-stage0/bin/" + os.path.basename(path))
tar.add(os.path.join(os.path.dirname(__file__), "third-party"),
"rust-stage0/bin/third-party")
tar.close()
h = hash_file(file0)
file1 = full_snapshot_name(date, rev, platform, h)
shutil.move(file0, file1)
return file1
def curr_snapshot_rev():
i = 0
found_snap = False
date = None
rev = None
f = open(snapshotfile)
for line in f.readlines():
i += 1
parsed = parse_line(i, line)
if not parsed:
continue
if parsed["type"] == "snapshot":
date = parsed["date"]
rev = parsed["rev"]
found_snap = True
break
if not found_snap:
raise Exception("no snapshot entries in file")
return (date, rev)
def determine_curr_snapshot(triple):
i = 0
platform = get_platform(triple)
found_file = False
found_snap = False
hsh = None
date = None
rev = None
f = open(snapshotfile)
for line in f.readlines():
i += 1
parsed = parse_line(i, line)
if not parsed:
continue
if found_snap and parsed["type"] == "file":
if parsed["platform"] == platform:
hsh = parsed["hash"]
found_file = True
break
elif parsed["type"] == "snapshot":
date = parsed["date"]
rev = parsed["rev"]
found_snap = True
if not found_snap:
raise Exception("no snapshot entries in file")
if not found_file:
raise Exception("no snapshot file found for platform %s, rev %s" %
(platform, rev))
return full_snapshot_name(date, rev, platform, hsh)
| apache-2.0 |
sassoftware/mint | mint/db/mirror.py | 1 | 5677 | #
# Copyright (c) SAS Institute Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
from mint.lib import database
class InboundMirrorsTable(database.KeyedTable):
name = 'InboundMirrors'
key = 'inboundMirrorId'
fields = ['inboundMirrorId', 'targetProjectId', 'sourceLabels',
'sourceUrl', 'sourceAuthType', 'sourceUsername',
'sourcePassword', 'sourceEntitlement',
'mirrorOrder', 'allLabels']
def getIdByHostname(self, hostname):
cu = self.db.cursor()
cu.execute("""
SELECT MIN(inboundMirrorId) FROM InboundMirrors
JOIN Projects ON Projects.projectId = InboundMirrors.targetProjectId
WHERE Projects.fqdn = ?
""", hostname)
return cu.fetchone()[0]
class OutboundMirrorsTable(database.KeyedTable):
name = 'OutboundMirrors'
key = 'outboundMirrorId'
fields = ['outboundMirrorId', 'sourceProjectId', 'targetLabels',
'allLabels', 'recurse', 'matchStrings', 'mirrorOrder',
'useReleases',
]
def __init__(self, db, cfg):
self.cfg = cfg
database.KeyedTable.__init__(self, db)
def get(self, *args, **kwargs):
res = database.KeyedTable.get(self, *args, **kwargs)
if 'allLabels' in res:
res['allLabels'] = bool(res['allLabels'])
if 'recurse' in res:
res['recurse'] = bool(res['recurse'])
return res
def delete(self, id):
cu = self.db.transaction()
try:
cu.execute("""DELETE FROM OutboundMirrors WHERE
outboundMirrorId = ?""", id)
# Cleanup mapping table ourselves if we are using SQLite,
# as it doesn't know about contraints.
if self.cfg.dbDriver == 'sqlite':
cu.execute("""DELETE FROM OutboundMirrorsUpdateServices WHERE
outboundMirrorId = ?""", id)
except:
self.db.rollback()
raise
else:
self.db.commit()
return True
def getOutboundMirrors(self):
cu = self.db.cursor()
cu.execute("""SELECT outboundMirrorId, sourceProjectId,
targetLabels, allLabels, recurse,
matchStrings, mirrorOrder, fullSync,
useReleases
FROM OutboundMirrors
ORDER by mirrorOrder""")
return [list(x[:3]) + [bool(x[3]), bool(x[4]), x[5].split(), \
x[6], bool(x[7]), bool(x[8])] \
for x in cu.fetchall()]
class OutboundMirrorsUpdateServicesTable(database.DatabaseTable):
name = "OutboundMirrorsUpdateServices"
fields = [ 'updateServiceId', 'outboundMirrorId' ]
def getOutboundMirrorTargets(self, outboundMirrorId):
cu = self.db.cursor()
cu.execute("""SELECT obus.updateServiceId, us.hostname,
us.mirrorUser, us.mirrorPassword, us.description
FROM OutboundMirrorsUpdateServices obus
JOIN
UpdateServices us
USING(updateServiceId)
WHERE outboundMirrorId = ?""", outboundMirrorId)
return [ list(x[:4]) + [x[4] and x[4] or ''] \
for x in cu.fetchall() ]
def setTargets(self, outboundMirrorId, updateServiceIds):
cu = self.db.transaction()
updates = [ (outboundMirrorId, x) for x in updateServiceIds ]
try:
cu.execute("""DELETE FROM OutboundMirrorsUpdateServices
WHERE outboundMirrorId = ?""", outboundMirrorId)
except:
pass # don't worry if there is nothing to do here
try:
cu.executemany("INSERT INTO OutboundMirrorsUpdateServices VALUES(?,?)",
updates)
except:
self.db.rollback()
raise
else:
self.db.commit()
return updateServiceIds
class UpdateServicesTable(database.KeyedTable):
name = 'UpdateServices'
key = 'updateServiceId'
fields = [ 'updateServiceId', 'hostname',
'mirrorUser', 'mirrorPassword', 'description' ]
def __init__(self, db, cfg):
self.cfg = cfg
database.KeyedTable.__init__(self, db)
def getUpdateServiceList(self):
cu = self.db.cursor()
cu.execute("""SELECT %s FROM UpdateServices""" % ', '.join(self.fields))
return [ list(x) for x in cu.fetchall() ]
def delete(self, id):
cu = self.db.transaction()
try:
cu.execute("""DELETE FROM UpdateServices WHERE
updateServiceId = ?""", id)
# Cleanup mapping table ourselves if we are using SQLite,
# as it doesn't know about contraints.
if self.cfg.dbDriver == 'sqlite':
cu.execute("""DELETE FROM OutboundMirrorsUpdateServices WHERE
updateServiceId = ?""", id)
except:
self.db.rollback()
raise
else:
self.db.commit()
return True
| apache-2.0 |
epic-math/sfvue3 | registration-should-be-restored/tests/urls.py | 138 | 4645 | """
URLs used in the unit tests for django-registration.
You should not attempt to use these URLs in any sort of real or
development environment; instead, use
``registration/backends/default/urls.py``. This URLconf includes those
URLs, and also adds several additional URLs which serve no purpose
other than to test that optional keyword arguments are properly
handled.
"""
from django.conf.urls.defaults import *
from django.views.generic.simple import direct_to_template
from registration.views import activate
from registration.views import register
urlpatterns = patterns('',
# Test the 'activate' view with custom template
# name.
url(r'^activate-with-template-name/(?P<activation_key>\w+)/$',
activate,
{'template_name': 'registration/test_template_name.html',
'backend': 'registration.backends.default.DefaultBackend'},
name='registration_test_activate_template_name'),
# Test the 'activate' view with
# extra_context_argument.
url(r'^activate-extra-context/(?P<activation_key>\w+)/$',
activate,
{'extra_context': {'foo': 'bar', 'callable': lambda: 'called'},
'backend': 'registration.backends.default.DefaultBackend'},
name='registration_test_activate_extra_context'),
# Test the 'activate' view with success_url argument.
url(r'^activate-with-success-url/(?P<activation_key>\w+)/$',
activate,
{'success_url': 'registration_test_custom_success_url',
'backend': 'registration.backends.default.DefaultBackend'},
name='registration_test_activate_success_url'),
# Test the 'register' view with custom template
# name.
url(r'^register-with-template-name/$',
register,
{'template_name': 'registration/test_template_name.html',
'backend': 'registration.backends.default.DefaultBackend'},
name='registration_test_register_template_name'),
# Test the'register' view with extra_context
# argument.
url(r'^register-extra-context/$',
register,
{'extra_context': {'foo': 'bar', 'callable': lambda: 'called'},
'backend': 'registration.backends.default.DefaultBackend'},
name='registration_test_register_extra_context'),
# Test the 'register' view with custom URL for
# closed registration.
url(r'^register-with-disallowed-url/$',
register,
{'disallowed_url': 'registration_test_custom_disallowed',
'backend': 'registration.backends.default.DefaultBackend'},
name='registration_test_register_disallowed_url'),
# Set up a pattern which will correspond to the
# custom 'disallowed_url' above.
url(r'^custom-disallowed/$',
direct_to_template,
{'template': 'registration/registration_closed.html'},
name='registration_test_custom_disallowed'),
# Test the 'register' view with custom redirect
# on successful registration.
url(r'^register-with-success_url/$',
register,
{'success_url': 'registration_test_custom_success_url',
'backend': 'registration.backends.default.DefaultBackend'},
name='registration_test_register_success_url'
),
# Pattern for custom redirect set above.
url(r'^custom-success/$',
direct_to_template,
{'template': 'registration/test_template_name.html'},
name='registration_test_custom_success_url'),
(r'', include('registration.backends.default.urls')),
)
| mit |
gechong/XlsxWriter | xlsxwriter/test/comparison/test_table07.py | 8 | 1123 | ###############################################################################
#
# Tests for XlsxWriter.
#
# Copyright (c), 2013-2015, John McNamara, jmcnamara@cpan.org
#
from ..excel_comparsion_test import ExcelComparisonTest
from ...workbook import Workbook
class TestCompareXLSXFiles(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.maxDiff = None
filename = 'table07.xlsx'
test_dir = 'xlsxwriter/test/comparison/'
self.got_filename = test_dir + '_test_' + filename
self.exp_filename = test_dir + 'xlsx_files/' + filename
self.ignore_files = []
self.ignore_elements = {}
def test_create_file(self):
"""Test the creation of a simple XlsxWriter file with tables."""
workbook = Workbook(self.got_filename)
worksheet = workbook.add_worksheet()
worksheet.set_column('C:F', 10.288)
worksheet.add_table('C3:F13', {'header_row': 0})
worksheet.write('A1', 'Foo')
workbook.close()
self.assertExcelEqual()
| bsd-2-clause |
Jerry-X-Meng/AlphaBoxPlus | u-boot/tools/patman/get_maintainer.py | 57 | 1238 | # Copyright (c) 2012 The Chromium OS Authors.
#
# SPDX-License-Identifier: GPL-2.0+
#
import command
import gitutil
import os
def FindGetMaintainer():
"""Look for the get_maintainer.pl script.
Returns:
If the script is found we'll return a path to it; else None.
"""
try_list = [
os.path.join(gitutil.GetTopLevel(), 'scripts'),
]
# Look in the list
for path in try_list:
fname = os.path.join(path, 'get_maintainer.pl')
if os.path.isfile(fname):
return fname
return None
def GetMaintainer(fname, verbose=False):
"""Run get_maintainer.pl on a file if we find it.
We look for get_maintainer.pl in the 'scripts' directory at the top of
git. If we find it we'll run it. If we don't find get_maintainer.pl
then we fail silently.
Args:
fname: Path to the patch file to run get_maintainer.pl on.
Returns:
A list of email addresses to CC to.
"""
get_maintainer = FindGetMaintainer()
if not get_maintainer:
if verbose:
print "WARNING: Couldn't find get_maintainer.pl"
return []
stdout = command.Output(get_maintainer, '--norolestats', fname)
return stdout.splitlines()
| gpl-3.0 |
Lujeni/ansible | lib/ansible/modules/cloud/memset/memset_dns_reload.py | 44 | 5850 | #!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright (c) 2018, Simon Weald <ansible@simonweald.com>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
ANSIBLE_METADATA = {
'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'
}
DOCUMENTATION = '''
---
module: memset_dns_reload
author: "Simon Weald (@glitchcrab)"
version_added: "2.6"
short_description: Request reload of Memset's DNS infrastructure,
notes:
- DNS reload requests are a best-effort service provided by Memset; these generally
happen every 15 minutes by default, however you can request an immediate reload if
later tasks rely on the records being created. An API key generated via the
Memset customer control panel is required with the following minimum scope -
I(dns.reload). If you wish to poll the job status to wait until the reload has
completed, then I(job.status) is also required.
description:
- Request a reload of Memset's DNS infrastructure, and optionally poll until it finishes.
options:
api_key:
required: true
description:
- The API key obtained from the Memset control panel.
poll:
default: false
type: bool
description:
- Boolean value, if set will poll the reload job's status and return
when the job has completed (unless the 30 second timeout is reached first).
If the timeout is reached then the task will not be marked as failed, but
stderr will indicate that the polling failed.
'''
EXAMPLES = '''
- name: submit DNS reload and poll.
memset_dns_reload:
api_key: 5eb86c9196ab03919abcf03857163741
poll: True
delegate_to: localhost
'''
RETURN = '''
---
memset_api:
description: Raw response from the Memset API.
returned: always
type: complex
contains:
error:
description: Whether the job ended in error state.
returned: always
type: bool
sample: true
finished:
description: Whether the job completed before the result was returned.
returned: always
type: bool
sample: true
id:
description: Job ID.
returned: always
type: str
sample: "c9cc8ad2a3e3fb8c63ed83c424928ef8"
status:
description: Job status.
returned: always
type: str
sample: "DONE"
type:
description: Job type.
returned: always
type: str
sample: "dns"
'''
from time import sleep
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.memset import memset_api_call
def poll_reload_status(api_key=None, job_id=None, payload=None):
'''
We poll the `job.status` endpoint every 5 seconds up to a
maximum of 6 times. This is a relatively arbitrary choice of
timeout, however requests rarely take longer than 15 seconds
to complete.
'''
memset_api, stderr, msg = None, None, None
payload['id'] = job_id
api_method = 'job.status'
_has_failed, _msg, response = memset_api_call(api_key=api_key, api_method=api_method, payload=payload)
while not response.json()['finished']:
counter = 0
while counter < 6:
sleep(5)
_has_failed, msg, response = memset_api_call(api_key=api_key, api_method=api_method, payload=payload)
counter += 1
if response.json()['error']:
# the reload job was submitted but polling failed. Don't return this as an overall task failure.
stderr = "Reload submitted successfully, but the Memset API returned a job error when attempting to poll the reload status."
else:
memset_api = response.json()
msg = None
return(memset_api, msg, stderr)
def reload_dns(args=None):
'''
DNS reloads are a single API call and therefore there's not much
which can go wrong outside of auth errors.
'''
retvals, payload = dict(), dict()
has_changed, has_failed = False, False
memset_api, msg, stderr = None, None, None
api_method = 'dns.reload'
has_failed, msg, response = memset_api_call(api_key=args['api_key'], api_method=api_method)
if has_failed:
# this is the first time the API is called; incorrect credentials will
# manifest themselves at this point so we need to ensure the user is
# informed of the reason.
retvals['failed'] = has_failed
retvals['memset_api'] = response.json()
retvals['msg'] = msg
return(retvals)
# set changed to true if the reload request was accepted.
has_changed = True
memset_api = msg
# empty msg var as we don't want to return the API's json response twice.
msg = None
if args['poll']:
# hand off to the poll function.
job_id = response.json()['id']
memset_api, msg, stderr = poll_reload_status(api_key=args['api_key'], job_id=job_id, payload=payload)
# assemble return variables.
retvals['failed'] = has_failed
retvals['changed'] = has_changed
for val in ['msg', 'stderr', 'memset_api']:
if val is not None:
retvals[val] = eval(val)
return(retvals)
def main():
global module
module = AnsibleModule(
argument_spec=dict(
api_key=dict(required=True, type='str', no_log=True),
poll=dict(required=False, default=False, type='bool')
),
supports_check_mode=False
)
# populate the dict with the user-provided vars.
args = dict()
for key, arg in module.params.items():
args[key] = arg
retvals = reload_dns(args)
if retvals['failed']:
module.fail_json(**retvals)
else:
module.exit_json(**retvals)
if __name__ == '__main__':
main()
| gpl-3.0 |
romain-dartigues/ansible | lib/ansible/module_utils/network/voss/voss.py | 63 | 7726 | # This code is part of Ansible, but is an independent component.
# This particular file snippet, and this file snippet only, is BSD licensed.
# Modules you write using this snippet, which is embedded dynamically by Ansible
# still belong to the author of the module, and may assign their own license
# to the complete work.
#
# (c) 2018 Extreme Networks Inc.
#
# Redistribution and use in source and binary forms, with or without modification,
# are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
# IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
# USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
import json
import re
from ansible.module_utils._text import to_native, to_text
from ansible.module_utils.network.common.utils import to_list, ComplexList
from ansible.module_utils.connection import Connection, ConnectionError
from ansible.module_utils.network.common.config import NetworkConfig, ConfigLine
_DEVICE_CONFIGS = {}
DEFAULT_COMMENT_TOKENS = ['#', '!', '/*', '*/', 'echo']
DEFAULT_IGNORE_LINES_RE = set([
re.compile(r"Preparing to Display Configuration\.\.\.")
])
def get_connection(module):
if hasattr(module, '_voss_connection'):
return module._voss_connection
capabilities = get_capabilities(module)
network_api = capabilities.get('network_api')
if network_api == 'cliconf':
module._voss_connection = Connection(module._socket_path)
else:
module.fail_json(msg='Invalid connection type %s' % network_api)
return module._voss_connection
def get_capabilities(module):
if hasattr(module, '_voss_capabilities'):
return module._voss_capabilities
try:
capabilities = Connection(module._socket_path).get_capabilities()
except ConnectionError as exc:
module.fail_json(msg=to_text(exc, errors='surrogate_then_replace'))
module._voss_capabilities = json.loads(capabilities)
return module._voss_capabilities
def get_defaults_flag(module):
connection = get_connection(module)
try:
out = connection.get_defaults_flag()
except ConnectionError as exc:
module.fail_json(msg=to_text(exc, errors='surrogate_then_replace'))
return to_text(out, errors='surrogate_then_replace').strip()
def get_config(module, source='running', flags=None):
flag_str = ' '.join(to_list(flags))
try:
return _DEVICE_CONFIGS[flag_str]
except KeyError:
connection = get_connection(module)
try:
out = connection.get_config(source=source, flags=flags)
except ConnectionError as exc:
module.fail_json(msg=to_text(exc, errors='surrogate_then_replace'))
cfg = to_text(out, errors='surrogate_then_replace').strip()
_DEVICE_CONFIGS[flag_str] = cfg
return cfg
def to_commands(module, commands):
spec = {
'command': dict(key=True),
'prompt': dict(),
'answer': dict()
}
transform = ComplexList(spec, module)
return transform(commands)
def run_commands(module, commands, check_rc=True):
connection = get_connection(module)
try:
out = connection.run_commands(commands=commands, check_rc=check_rc)
return out
except ConnectionError as exc:
module.fail_json(msg=to_text(exc))
def load_config(module, commands):
connection = get_connection(module)
try:
resp = connection.edit_config(commands)
return resp.get('response')
except ConnectionError as exc:
module.fail_json(msg=to_text(exc))
def get_sublevel_config(running_config, module):
contents = list()
current_config_contents = list()
sublevel_config = VossNetworkConfig(indent=0)
obj = running_config.get_object(module.params['parents'])
if obj:
contents = obj._children
for c in contents:
if isinstance(c, ConfigLine):
current_config_contents.append(c.raw)
sublevel_config.add(current_config_contents, module.params['parents'])
return sublevel_config
def ignore_line(text, tokens=None):
for item in (tokens or DEFAULT_COMMENT_TOKENS):
if text.startswith(item):
return True
for regex in DEFAULT_IGNORE_LINES_RE:
if regex.match(text):
return True
def voss_parse(lines, indent=None, comment_tokens=None):
toplevel = re.compile(r'(^interface.*$)|(^router \w+$)|(^router vrf \w+$)')
exitline = re.compile(r'^exit$')
entry_reg = re.compile(r'([{};])')
ancestors = list()
config = list()
dup_parent_index = None
for line in to_native(lines, errors='surrogate_or_strict').split('\n'):
text = entry_reg.sub('', line).strip()
cfg = ConfigLine(text)
if not text or ignore_line(text, comment_tokens):
continue
# Handle top level commands
if toplevel.match(text):
# Looking to see if we have existing parent
for index, item in enumerate(config):
if item.text == text:
# This means we have an existing parent with same label
dup_parent_index = index
break
ancestors = [cfg]
config.append(cfg)
# Handle 'exit' line
elif exitline.match(text):
ancestors = list()
if dup_parent_index is not None:
# We're working with a duplicate parent
# Don't need to store exit, just go to next line in config
dup_parent_index = None
else:
cfg._parents = ancestors[:1]
config.append(cfg)
# Handle sub-level commands. Only have single sub-level
elif ancestors:
cfg._parents = ancestors[:1]
if dup_parent_index is not None:
# Update existing entry, since this already exists in config
config[int(dup_parent_index)].add_child(cfg)
new_index = dup_parent_index + 1
config.insert(new_index, cfg)
else:
ancestors[0].add_child(cfg)
config.append(cfg)
else:
# Global command, no further special handling needed
config.append(cfg)
return config
class VossNetworkConfig(NetworkConfig):
def load(self, s):
self._config_text = s
self._items = voss_parse(s, self._indent)
def _diff_line(self, other):
updates = list()
for item in self.items:
if str(item) == "exit":
if updates and updates[-1]._parents:
updates.append(item)
elif item not in other:
updates.append(item)
return updates
| gpl-3.0 |
kouaw/CouchPotatoServer | couchpotato/core/media/movie/providers/trailer/youtube_dl/extractor/clipfish.py | 17 | 1626 | from __future__ import unicode_literals
import re
import time
import xml.etree.ElementTree
from .common import InfoExtractor
from ..utils import (
ExtractorError,
parse_duration,
)
class ClipfishIE(InfoExtractor):
IE_NAME = 'clipfish'
_VALID_URL = r'^https?://(?:www\.)?clipfish\.de/.*?/video/(?P<id>[0-9]+)/'
_TEST = {
'url': 'http://www.clipfish.de/special/game-trailer/video/3966754/fifa-14-e3-2013-trailer/',
'md5': '2521cd644e862936cf2e698206e47385',
'info_dict': {
'id': '3966754',
'ext': 'mp4',
'title': 'FIFA 14 - E3 2013 Trailer',
'duration': 82,
},
u'skip': 'Blocked in the US'
}
def _real_extract(self, url):
mobj = re.match(self._VALID_URL, url)
video_id = mobj.group(1)
info_url = ('http://www.clipfish.de/devxml/videoinfo/%s?ts=%d' %
(video_id, int(time.time())))
doc = self._download_xml(
info_url, video_id, note=u'Downloading info page')
title = doc.find('title').text
video_url = doc.find('filename').text
if video_url is None:
xml_bytes = xml.etree.ElementTree.tostring(doc)
raise ExtractorError('Cannot find video URL in document %r' %
xml_bytes)
thumbnail = doc.find('imageurl').text
duration = parse_duration(doc.find('duration').text)
return {
'id': video_id,
'title': title,
'url': video_url,
'thumbnail': thumbnail,
'duration': duration,
}
| gpl-3.0 |
xtmhm2000/scrapy-0.22 | scrapy/contrib/pipeline/files.py | 4 | 11536 | """
Files Pipeline
"""
import hashlib
import os
import os.path
import rfc822
import time
import urlparse
from collections import defaultdict
from cStringIO import StringIO
from twisted.internet import defer, threads
from scrapy import log
from scrapy.contrib.pipeline.media import MediaPipeline
from scrapy.exceptions import NotConfigured, IgnoreRequest
from scrapy.http import Request
from scrapy.utils.misc import md5sum
class FileException(Exception):
"""General media error exception"""
class FSFilesStore(object):
def __init__(self, basedir):
if '://' in basedir:
basedir = basedir.split('://', 1)[1]
self.basedir = basedir
self._mkdir(self.basedir)
self.created_directories = defaultdict(set)
def persist_file(self, path, buf, info, meta=None, headers=None):
absolute_path = self._get_filesystem_path(path)
self._mkdir(os.path.dirname(absolute_path), info)
with open(absolute_path, 'wb') as f:
f.write(buf.getvalue())
def stat_file(self, path, info):
absolute_path = self._get_filesystem_path(path)
try:
last_modified = os.path.getmtime(absolute_path)
except: # FIXME: catching everything!
return {}
with open(absolute_path, 'rb') as f:
checksum = md5sum(f)
return {'last_modified': last_modified, 'checksum': checksum}
def _get_filesystem_path(self, path):
path_comps = path.split('/')
return os.path.join(self.basedir, *path_comps)
def _mkdir(self, dirname, domain=None):
seen = self.created_directories[domain] if domain else set()
if dirname not in seen:
if not os.path.exists(dirname):
os.makedirs(dirname)
seen.add(dirname)
class S3FilesStore(object):
AWS_ACCESS_KEY_ID = None
AWS_SECRET_ACCESS_KEY = None
POLICY = 'public-read'
HEADERS = {
'Cache-Control': 'max-age=172800',
}
def __init__(self, uri):
assert uri.startswith('s3://')
self.bucket, self.prefix = uri[5:].split('/', 1)
def stat_file(self, path, info):
def _onsuccess(boto_key):
checksum = boto_key.etag.strip('"')
last_modified = boto_key.last_modified
modified_tuple = rfc822.parsedate_tz(last_modified)
modified_stamp = int(rfc822.mktime_tz(modified_tuple))
return {'checksum': checksum, 'last_modified': modified_stamp}
return self._get_boto_key(path).addCallback(_onsuccess)
def _get_boto_bucket(self):
from boto.s3.connection import S3Connection
# disable ssl (is_secure=False) because of this python bug:
# http://bugs.python.org/issue5103
c = S3Connection(self.AWS_ACCESS_KEY_ID, self.AWS_SECRET_ACCESS_KEY, is_secure=False)
return c.get_bucket(self.bucket, validate=False)
def _get_boto_key(self, path):
b = self._get_boto_bucket()
key_name = '%s%s' % (self.prefix, path)
return threads.deferToThread(b.get_key, key_name)
def persist_file(self, path, buf, info, meta=None, headers=None):
"""Upload file to S3 storage"""
b = self._get_boto_bucket()
key_name = '%s%s' % (self.prefix, path)
k = b.new_key(key_name)
if meta:
for metakey, metavalue in meta.iteritems():
k.set_metadata(metakey, str(metavalue))
h = self.HEADERS.copy()
if headers:
h.update(headers)
buf.seek(0)
return threads.deferToThread(k.set_contents_from_string, buf.getvalue(),
headers=h, policy=self.POLICY)
class FilesPipeline(MediaPipeline):
"""Abstract pipeline that implement the file downloading
This pipeline tries to minimize network transfers and file processing,
doing stat of the files and determining if file is new, uptodate or
expired.
`new` files are those that pipeline never processed and needs to be
downloaded from supplier site the first time.
`uptodate` files are the ones that the pipeline processed and are still
valid files.
`expired` files are those that pipeline already processed but the last
modification was made long time ago, so a reprocessing is recommended to
refresh it in case of change.
"""
MEDIA_NAME = "file"
EXPIRES = 90
STORE_SCHEMES = {
'': FSFilesStore,
'file': FSFilesStore,
's3': S3FilesStore,
}
DEFAULT_FILES_URLS_FIELD = 'file_urls'
DEFAULT_FILES_RESULT_FIELD = 'files'
def __init__(self, store_uri, download_func=None):
if not store_uri:
raise NotConfigured
self.store = self._get_store(store_uri)
super(FilesPipeline, self).__init__(download_func=download_func)
@classmethod
def from_settings(cls, settings):
s3store = cls.STORE_SCHEMES['s3']
s3store.AWS_ACCESS_KEY_ID = settings['AWS_ACCESS_KEY_ID']
s3store.AWS_SECRET_ACCESS_KEY = settings['AWS_SECRET_ACCESS_KEY']
cls.FILES_URLS_FIELD = settings.get('FILES_URLS_FIELD', cls.DEFAULT_FILES_URLS_FIELD)
cls.FILES_RESULT_FIELD = settings.get('FILES_RESULT_FIELD', cls.DEFAULT_FILES_RESULT_FIELD)
cls.EXPIRES = settings.getint('FILES_EXPIRES', 90)
store_uri = settings['FILES_STORE']
return cls(store_uri)
def _get_store(self, uri):
if os.path.isabs(uri): # to support win32 paths like: C:\\some\dir
scheme = 'file'
else:
scheme = urlparse.urlparse(uri).scheme
store_cls = self.STORE_SCHEMES[scheme]
return store_cls(uri)
def media_to_download(self, request, info):
def _onsuccess(result):
if not result:
return # returning None force download
last_modified = result.get('last_modified', None)
if not last_modified:
return # returning None force download
age_seconds = time.time() - last_modified
age_days = age_seconds / 60 / 60 / 24
if age_days > self.EXPIRES:
return # returning None force download
referer = request.headers.get('Referer')
log.msg(format='File (uptodate): Downloaded %(medianame)s from %(request)s referred in <%(referer)s>',
level=log.DEBUG, spider=info.spider,
medianame=self.MEDIA_NAME, request=request, referer=referer)
self.inc_stats(info.spider, 'uptodate')
checksum = result.get('checksum', None)
return {'url': request.url, 'path': path, 'checksum': checksum}
path = self.file_path(request, info=info)
dfd = defer.maybeDeferred(self.store.stat_file, path, info)
dfd.addCallbacks(_onsuccess, lambda _: None)
dfd.addErrback(log.err, self.__class__.__name__ + '.store.stat_file')
return dfd
def media_failed(self, failure, request, info):
if not isinstance(failure.value, IgnoreRequest):
referer = request.headers.get('Referer')
log.msg(format='File (unknown-error): Error downloading '
'%(medianame)s from %(request)s referred in '
'<%(referer)s>: %(exception)s',
level=log.WARNING, spider=info.spider, exception=failure.value,
medianame=self.MEDIA_NAME, request=request, referer=referer)
raise FileException
def media_downloaded(self, response, request, info):
referer = request.headers.get('Referer')
if response.status != 200:
log.msg(format='File (code: %(status)s): Error downloading image from %(request)s referred in <%(referer)s>',
level=log.WARNING, spider=info.spider,
status=response.status, request=request, referer=referer)
raise FileException('download-error')
if not response.body:
log.msg(format='File (empty-content): Empty image from %(request)s referred in <%(referer)s>: no-content',
level=log.WARNING, spider=info.spider,
request=request, referer=referer)
raise FileException('empty-content')
status = 'cached' if 'cached' in response.flags else 'downloaded'
log.msg(format='File (%(status)s): Downloaded image from %(request)s referred in <%(referer)s>',
level=log.DEBUG, spider=info.spider,
status=status, request=request, referer=referer)
self.inc_stats(info.spider, status)
try:
path = self.file_path(request, response=response, info=info)
checksum = self.file_downloaded(response, request, info)
except FileException as exc:
whyfmt = 'File (error): Error processing image from %(request)s referred in <%(referer)s>: %(errormsg)s'
log.msg(format=whyfmt, level=log.WARNING, spider=info.spider,
request=request, referer=referer, errormsg=str(exc))
raise
except Exception as exc:
whyfmt = 'File (unknown-error): Error processing image from %(request)s referred in <%(referer)s>'
log.err(None, whyfmt % {'request': request, 'referer': referer}, spider=info.spider)
raise FileException(str(exc))
return {'url': request.url, 'path': path, 'checksum': checksum}
def inc_stats(self, spider, status):
spider.crawler.stats.inc_value('file_count', spider=spider)
spider.crawler.stats.inc_value('file_status_count/%s' % status, spider=spider)
### Overridable Interface
def get_media_requests(self, item, info):
return [Request(x) for x in item.get(self.FILES_URLS_FIELD, [])]
def file_downloaded(self, response, request, info):
path = self.file_path(request, response=response, info=info)
buf = StringIO(response.body)
self.store.persist_file(path, buf, info)
checksum = md5sum(buf)
return checksum
def item_completed(self, results, item, info):
if self.FILES_RESULT_FIELD in item.fields:
item[self.FILES_RESULT_FIELD] = [x for ok, x in results if ok]
return item
def file_path(self, request, response=None, info=None):
## start of deprecation warning block (can be removed in the future)
def _warn():
from scrapy.exceptions import ScrapyDeprecationWarning
import warnings
warnings.warn('FilesPipeline.file_key(url) method is deprecated, please use '
'file_path(request, response=None, info=None) instead',
category=ScrapyDeprecationWarning, stacklevel=1)
# check if called from file_key with url as first argument
if not isinstance(request, Request):
_warn()
url = request
else:
url = request.url
# detect if file_key() method has been overridden
if not hasattr(self.file_key, '_base'):
_warn()
return self.file_key(url)
## end of deprecation warning block
media_guid = hashlib.sha1(url).hexdigest() # change to request.url after deprecation
media_ext = os.path.splitext(url)[1] # change to request.url after deprecation
return 'full/%s%s' % (media_guid, media_ext)
# deprecated
def file_key(self, url):
return self.file_path(url)
file_key._base = True
| bsd-3-clause |
ikben/troposphere | examples/Route53_RoundRobin.py | 1 | 1994 | # Converted from Route53_RoundRobin.template located at:
# http://aws.amazon.com/cloudformation/aws-cloudformation-templates/
from troposphere import Join
from troposphere import Parameter, Ref, Template
from troposphere.route53 import RecordSet, RecordSetGroup
t = Template()
t.set_description(
"AWS CloudFormation Sample Template Route53_RoundRobin: Sample template "
"showing how to use weighted round robin (WRR) DNS entried via Amazon "
"Route 53. This contrived sample uses weighted CNAME records to "
"illustrate that the weighting influences the return records. It assumes "
" that you already have a Hosted Zone registered with Amazon Route 53. "
"**WARNING** This template creates an Amazon EC2 instance. "
"You will be billed for the AWS resources used if you create "
"a stack from this template.")
hostedzone = t.add_parameter(Parameter(
"HostedZone",
Description="The DNS name of an existing Amazon Route 53 hosted zone",
Type="String",
))
myDNSRecord = t.add_resource(RecordSetGroup(
"myDNSRecord",
HostedZoneName=Join("", [Ref(hostedzone), "."]),
Comment="Contrived example to redirect to aws.amazon.com 75% of the time "
"and www.amazon.com 25% of the time.",
RecordSets=[
RecordSet(
SetIdentifier=Join(" ", [Ref("AWS::StackName"), "AWS"]),
Name=Join("", [Ref("AWS::StackName"), ".", Ref("AWS::Region"), ".",
Ref(hostedzone), "."]),
Type="CNAME",
TTL="900",
ResourceRecords=["aws.amazon.com"],
Weight="3",
),
RecordSet(
SetIdentifier=Join(" ", [Ref("AWS::StackName"), "Amazon"]),
Name=Join("", [Ref("AWS::StackName"), ".", Ref("AWS::Region"), ".",
Ref(hostedzone), "."]),
Type="CNAME",
TTL="900",
ResourceRecords=["www.amazon.com"],
Weight="1",
),
],
))
print(t.to_json())
| bsd-2-clause |
cloudtools/troposphere | troposphere/applicationautoscaling.py | 1 | 3322 | from . import AWSObject, AWSProperty
from .validators import boolean, double, integer, positive_integer
class ScalableTargetAction(AWSProperty):
props = {
"MaxCapacity": (integer, False),
"MinCapacity": (integer, False),
}
class ScheduledAction(AWSProperty):
props = {
"EndTime": (str, False),
"ScalableTargetAction": (ScalableTargetAction, False),
"Schedule": (str, True),
"ScheduledActionName": (str, True),
"StartTime": (str, False),
"Timezone": (str, False),
}
class SuspendedState(AWSProperty):
props = {
"DynamicScalingInSuspended": (boolean, False),
"DynamicScalingOutSuspended": (boolean, False),
"ScheduledScalingSuspended": (boolean, False),
}
class ScalableTarget(AWSObject):
resource_type = "AWS::ApplicationAutoScaling::ScalableTarget"
props = {
"MaxCapacity": (integer, True),
"MinCapacity": (integer, True),
"ResourceId": (str, True),
"RoleARN": (str, True),
"ScalableDimension": (str, True),
"ScheduledActions": ([ScheduledAction], False),
"ServiceNamespace": (str, True),
"SuspendedState": (SuspendedState, False),
}
class StepAdjustment(AWSProperty):
props = {
"MetricIntervalLowerBound": (integer, False),
"MetricIntervalUpperBound": (integer, False),
"ScalingAdjustment": (integer, True),
}
class StepScalingPolicyConfiguration(AWSProperty):
props = {
"AdjustmentType": (str, False),
"Cooldown": (integer, False),
"MetricAggregationType": (str, False),
"MinAdjustmentMagnitude": (integer, False),
"StepAdjustments": ([StepAdjustment], False),
}
class MetricDimension(AWSProperty):
props = {
"Name": (str, True),
"Value": (str, True),
}
class CustomizedMetricSpecification(AWSProperty):
props = {
"Dimensions": ([MetricDimension], False),
"MetricName": (str, False),
"Namespace": (str, False),
"Statistic": (str, False),
"Unit": (str, True),
}
class PredefinedMetricSpecification(AWSProperty):
props = {
"PredefinedMetricType": (str, True),
"ResourceLabel": (str, False),
}
class TargetTrackingScalingPolicyConfiguration(AWSProperty):
props = {
"CustomizedMetricSpecification": (CustomizedMetricSpecification, False),
"DisableScaleIn": (boolean, False),
"PredefinedMetricSpecification": (PredefinedMetricSpecification, False),
"ScaleInCooldown": (positive_integer, False),
"ScaleOutCooldown": (positive_integer, False),
"TargetValue": (double, True),
}
class ScalingPolicy(AWSObject):
resource_type = "AWS::ApplicationAutoScaling::ScalingPolicy"
props = {
"PolicyName": (str, True),
"PolicyType": (str, False),
"ResourceId": (str, False),
"ScalableDimension": (str, False),
"ServiceNamespace": (str, False),
"ScalingTargetId": (str, False),
"StepScalingPolicyConfiguration": (
StepScalingPolicyConfiguration,
False,
),
"TargetTrackingScalingPolicyConfiguration": (
TargetTrackingScalingPolicyConfiguration,
False,
),
}
| bsd-2-clause |
eayunstack/neutron | neutron/tests/functional/agent/linux/test_keepalived.py | 3 | 4049 | # Copyright (c) 2014 Red Hat, 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.
from oslo_config import cfg
from neutron._i18n import _
from neutron.agent.linux import external_process
from neutron.agent.linux import keepalived
from neutron.agent.linux import utils
from neutron.common import utils as common_utils
from neutron.tests.functional.agent.linux import helpers
from neutron.tests.functional import base
from neutron.tests.unit.agent.linux import test_keepalived
class KeepalivedManagerTestCase(base.BaseLoggingTestCase,
test_keepalived.KeepalivedConfBaseMixin):
def setUp(self):
super(KeepalivedManagerTestCase, self).setUp()
cfg.CONF.set_override('check_child_processes_interval', 1, 'AGENT')
self.expected_config = self._get_config()
self.process_monitor = external_process.ProcessMonitor(cfg.CONF,
'router')
self.manager = keepalived.KeepalivedManager(
'router1', self.expected_config, self.process_monitor,
conf_path=cfg.CONF.state_path)
self.addCleanup(self.manager.disable)
def _spawn_keepalived(self, keepalived_manager):
keepalived_manager.spawn()
process = keepalived_manager.get_process()
common_utils.wait_until_true(
lambda: process.active,
timeout=5,
sleep=0.01,
exception=RuntimeError(_("Keepalived didn't spawn")))
return process
def test_keepalived_spawn(self):
self._spawn_keepalived(self.manager)
self.assertEqual(self.expected_config.get_config_str(),
self.manager.get_conf_on_disk())
def _test_keepalived_respawns(self, normal_exit=True):
process = self._spawn_keepalived(self.manager)
pid = process.pid
exit_code = '-15' if normal_exit else '-9'
# Exit the process, and see that when it comes back
# It's indeed a different process
utils.execute(['kill', exit_code, pid])
common_utils.wait_until_true(
lambda: process.active and pid != process.pid,
timeout=5,
sleep=0.01,
exception=RuntimeError(_("Keepalived didn't respawn")))
def test_keepalived_respawns(self):
self._test_keepalived_respawns()
def test_keepalived_respawn_with_unexpected_exit(self):
self._test_keepalived_respawns(False)
def _test_keepalived_spawns_conflicting_pid(self, process, pid_file):
# Test the situation when keepalived PID file contains PID of an
# existing non-keepalived process. This situation can happen e.g.
# after hard node reset.
spawn_process = helpers.SleepyProcessFixture()
self.useFixture(spawn_process)
with open(pid_file, "w") as f_pid_file:
f_pid_file.write("%s" % spawn_process.pid)
self._spawn_keepalived(self.manager)
def test_keepalived_spawns_conflicting_pid_base_process(self):
process = self.manager.get_process()
pid_file = process.get_pid_file_name()
self._test_keepalived_spawns_conflicting_pid(process, pid_file)
def test_keepalived_spawns_conflicting_pid_vrrp_subprocess(self):
process = self.manager.get_process()
pid_file = process.get_pid_file_name()
self._test_keepalived_spawns_conflicting_pid(
process,
self.manager.get_vrrp_pid_file_name(pid_file))
| apache-2.0 |
ShassAro/ShassAro | Bl_project/blVirtualEnv/lib/python2.7/site-packages/pip/_vendor/requests/packages/urllib3/util/connection.py | 319 | 1348 | from socket import error as SocketError
try:
from select import poll, POLLIN
except ImportError: # `poll` doesn't exist on OSX and other platforms
poll = False
try:
from select import select
except ImportError: # `select` doesn't exist on AppEngine.
select = False
def is_connection_dropped(conn): # Platform-specific
"""
Returns True if the connection is dropped and should be closed.
:param conn:
:class:`httplib.HTTPConnection` object.
Note: For platforms like AppEngine, this will always return ``False`` to
let the platform handle connection recycling transparently for us.
"""
sock = getattr(conn, 'sock', False)
if sock is False: # Platform-specific: AppEngine
return False
if sock is None: # Connection already closed (such as by httplib).
return False
if not poll:
if not select: # Platform-specific: AppEngine
return False
try:
return select([sock], [], [], 0.0)[0]
except SocketError:
return True
# This version is better on platforms that support it.
p = poll()
p.register(sock, POLLIN)
for (fno, ev) in p.poll(0.0):
if fno == sock.fileno():
# Either data is buffered (bad), or the connection is dropped.
return True
| gpl-2.0 |
wanghao-xznu/uboot-imx | tools/patman/checkpatch.py | 31 | 6898 | # Copyright (c) 2011 The Chromium OS Authors.
#
# See file CREDITS for list of people who contributed to this
# project.
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 2 of
# the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston,
# MA 02111-1307 USA
#
import collections
import command
import gitutil
import os
import re
import sys
import terminal
def FindCheckPatch():
top_level = gitutil.GetTopLevel()
try_list = [
os.getcwd(),
os.path.join(os.getcwd(), '..', '..'),
os.path.join(top_level, 'tools'),
os.path.join(top_level, 'scripts'),
'%s/bin' % os.getenv('HOME'),
]
# Look in current dir
for path in try_list:
fname = os.path.join(path, 'checkpatch.pl')
if os.path.isfile(fname):
return fname
# Look upwwards for a Chrome OS tree
while not os.path.ismount(path):
fname = os.path.join(path, 'src', 'third_party', 'kernel', 'files',
'scripts', 'checkpatch.pl')
if os.path.isfile(fname):
return fname
path = os.path.dirname(path)
print >> sys.stderr, ('Cannot find checkpatch.pl - please put it in your ' +
'~/bin directory or use --no-check')
sys.exit(1)
def CheckPatch(fname, verbose=False):
"""Run checkpatch.pl on a file.
Returns:
namedtuple containing:
ok: False=failure, True=ok
problems: List of problems, each a dict:
'type'; error or warning
'msg': text message
'file' : filename
'line': line number
errors: Number of errors
warnings: Number of warnings
checks: Number of checks
lines: Number of lines
stdout: Full output of checkpatch
"""
fields = ['ok', 'problems', 'errors', 'warnings', 'checks', 'lines',
'stdout']
result = collections.namedtuple('CheckPatchResult', fields)
result.ok = False
result.errors, result.warning, result.checks = 0, 0, 0
result.lines = 0
result.problems = []
chk = FindCheckPatch()
item = {}
result.stdout = command.Output(chk, '--no-tree', fname)
#pipe = subprocess.Popen(cmd, stdout=subprocess.PIPE)
#stdout, stderr = pipe.communicate()
# total: 0 errors, 0 warnings, 159 lines checked
# or:
# total: 0 errors, 2 warnings, 7 checks, 473 lines checked
re_stats = re.compile('total: (\\d+) errors, (\d+) warnings, (\d+)')
re_stats_full = re.compile('total: (\\d+) errors, (\d+) warnings, (\d+)'
' checks, (\d+)')
re_ok = re.compile('.*has no obvious style problems')
re_bad = re.compile('.*has style problems, please review')
re_error = re.compile('ERROR: (.*)')
re_warning = re.compile('WARNING: (.*)')
re_check = re.compile('CHECK: (.*)')
re_file = re.compile('#\d+: FILE: ([^:]*):(\d+):')
for line in result.stdout.splitlines():
if verbose:
print line
# A blank line indicates the end of a message
if not line and item:
result.problems.append(item)
item = {}
match = re_stats_full.match(line)
if not match:
match = re_stats.match(line)
if match:
result.errors = int(match.group(1))
result.warnings = int(match.group(2))
if len(match.groups()) == 4:
result.checks = int(match.group(3))
result.lines = int(match.group(4))
else:
result.lines = int(match.group(3))
elif re_ok.match(line):
result.ok = True
elif re_bad.match(line):
result.ok = False
err_match = re_error.match(line)
warn_match = re_warning.match(line)
file_match = re_file.match(line)
check_match = re_check.match(line)
if err_match:
item['msg'] = err_match.group(1)
item['type'] = 'error'
elif warn_match:
item['msg'] = warn_match.group(1)
item['type'] = 'warning'
elif check_match:
item['msg'] = check_match.group(1)
item['type'] = 'check'
elif file_match:
item['file'] = file_match.group(1)
item['line'] = int(file_match.group(2))
return result
def GetWarningMsg(col, msg_type, fname, line, msg):
'''Create a message for a given file/line
Args:
msg_type: Message type ('error' or 'warning')
fname: Filename which reports the problem
line: Line number where it was noticed
msg: Message to report
'''
if msg_type == 'warning':
msg_type = col.Color(col.YELLOW, msg_type)
elif msg_type == 'error':
msg_type = col.Color(col.RED, msg_type)
elif msg_type == 'check':
msg_type = col.Color(col.MAGENTA, msg_type)
return '%s: %s,%d: %s' % (msg_type, fname, line, msg)
def CheckPatches(verbose, args):
'''Run the checkpatch.pl script on each patch'''
error_count, warning_count, check_count = 0, 0, 0
col = terminal.Color()
for fname in args:
result = CheckPatch(fname, verbose)
if not result.ok:
error_count += result.errors
warning_count += result.warnings
check_count += result.checks
print '%d errors, %d warnings, %d checks for %s:' % (result.errors,
result.warnings, result.checks, col.Color(col.BLUE, fname))
if (len(result.problems) != result.errors + result.warnings +
result.checks):
print "Internal error: some problems lost"
for item in result.problems:
print GetWarningMsg(col, item.get('type', '<unknown>'),
item.get('file', '<unknown>'),
item.get('line', 0), item.get('msg', 'message'))
print
#print stdout
if error_count or warning_count or check_count:
str = 'checkpatch.pl found %d error(s), %d warning(s), %d checks(s)'
color = col.GREEN
if warning_count:
color = col.YELLOW
if error_count:
color = col.RED
print col.Color(color, str % (error_count, warning_count, check_count))
return False
return True
| gpl-2.0 |
Teagan42/home-assistant | homeassistant/components/demo/lock.py | 3 | 1862 | """Demo lock platform that has two fake locks."""
from homeassistant.components.lock import SUPPORT_OPEN, LockDevice
from homeassistant.const import STATE_LOCKED, STATE_UNLOCKED
async def async_setup_platform(hass, config, async_add_entities, discovery_info=None):
"""Set up the Demo lock platform."""
async_add_entities(
[
DemoLock("Front Door", STATE_LOCKED),
DemoLock("Kitchen Door", STATE_UNLOCKED),
DemoLock("Openable Lock", STATE_LOCKED, True),
]
)
async def async_setup_entry(hass, config_entry, async_add_entities):
"""Set up the Demo config entry."""
await async_setup_platform(hass, {}, async_add_entities)
class DemoLock(LockDevice):
"""Representation of a Demo lock."""
def __init__(self, name, state, openable=False):
"""Initialize the lock."""
self._name = name
self._state = state
self._openable = openable
@property
def should_poll(self):
"""No polling needed for a demo lock."""
return False
@property
def name(self):
"""Return the name of the lock if any."""
return self._name
@property
def is_locked(self):
"""Return true if lock is locked."""
return self._state == STATE_LOCKED
def lock(self, **kwargs):
"""Lock the device."""
self._state = STATE_LOCKED
self.schedule_update_ha_state()
def unlock(self, **kwargs):
"""Unlock the device."""
self._state = STATE_UNLOCKED
self.schedule_update_ha_state()
def open(self, **kwargs):
"""Open the door latch."""
self._state = STATE_UNLOCKED
self.schedule_update_ha_state()
@property
def supported_features(self):
"""Flag supported features."""
if self._openable:
return SUPPORT_OPEN
| apache-2.0 |
SUSE-Cloud/nova | plugins/xenserver/xenapi/etc/xapi.d/plugins/utils.py | 14 | 14138 | # Copyright (c) 2012 OpenStack Foundation
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
"""Various utilities used by XenServer plugins."""
import cPickle as pickle
import errno
import logging
import os
import shutil
import subprocess
import tempfile
import XenAPIPlugin
LOG = logging.getLogger(__name__)
CHUNK_SIZE = 8192
class CommandNotFound(Exception):
pass
def delete_if_exists(path):
try:
os.unlink(path)
except OSError, e: # noqa
if e.errno == errno.ENOENT:
LOG.warning("'%s' was already deleted, skipping delete" % path)
else:
raise
def _link(src, dst):
LOG.info("Hard-linking file '%s' -> '%s'" % (src, dst))
os.link(src, dst)
def _rename(src, dst):
LOG.info("Renaming file '%s' -> '%s'" % (src, dst))
try:
os.rename(src, dst)
except OSError, e: # noqa
if e.errno == errno.EXDEV:
LOG.error("Invalid cross-device link. Perhaps %s and %s should "
"be symlinked on the same filesystem?" % (src, dst))
raise
def make_subprocess(cmdline, stdout=False, stderr=False, stdin=False,
universal_newlines=False, close_fds=True, env=None):
"""Make a subprocess according to the given command-line string
"""
LOG.info("Running cmd '%s'" % " ".join(cmdline))
kwargs = {}
kwargs['stdout'] = stdout and subprocess.PIPE or None
kwargs['stderr'] = stderr and subprocess.PIPE or None
kwargs['stdin'] = stdin and subprocess.PIPE or None
kwargs['universal_newlines'] = universal_newlines
kwargs['close_fds'] = close_fds
kwargs['env'] = env
try:
proc = subprocess.Popen(cmdline, **kwargs)
except OSError, e: # noqa
if e.errno == errno.ENOENT:
raise CommandNotFound
else:
raise
return proc
class SubprocessException(Exception):
def __init__(self, cmdline, ret, out, err):
Exception.__init__(self, "'%s' returned non-zero exit code: "
"retcode=%i, out='%s', stderr='%s'"
% (cmdline, ret, out, err))
self.cmdline = cmdline
self.ret = ret
self.out = out
self.err = err
def finish_subprocess(proc, cmdline, cmd_input=None, ok_exit_codes=None):
"""Ensure that the process returned a zero exit code indicating success
"""
if ok_exit_codes is None:
ok_exit_codes = [0]
out, err = proc.communicate(cmd_input)
ret = proc.returncode
if ret not in ok_exit_codes:
raise SubprocessException(' '.join(cmdline), ret, out, err)
return out
def run_command(cmd, cmd_input=None, ok_exit_codes=None):
"""Abstracts out the basics of issuing system commands. If the command
returns anything in stderr, an exception is raised with that information.
Otherwise, the output from stdout is returned.
cmd_input is passed to the process on standard input.
"""
proc = make_subprocess(cmd, stdout=True, stderr=True, stdin=True,
close_fds=True)
return finish_subprocess(proc, cmd, cmd_input=cmd_input,
ok_exit_codes=ok_exit_codes)
def make_staging_area(sr_path):
"""
The staging area is a place where we can temporarily store and
manipulate VHDs. The use of the staging area is different for upload and
download:
Download
========
When we download the tarball, the VHDs contained within will have names
like "snap.vhd" and "image.vhd". We need to assign UUIDs to them before
moving them into the SR. However, since 'image.vhd' may be a base_copy, we
need to link it to 'snap.vhd' (using vhd-util modify) before moving both
into the SR (otherwise the SR.scan will cause 'image.vhd' to be deleted).
The staging area gives us a place to perform these operations before they
are moved to the SR, scanned, and then registered with XenServer.
Upload
======
On upload, we want to rename the VHDs to reflect what they are, 'snap.vhd'
in the case of the snapshot VHD, and 'image.vhd' in the case of the
base_copy. The staging area provides a directory in which we can create
hard-links to rename the VHDs without affecting what's in the SR.
NOTE
====
The staging area is created as a subdirectory within the SR in order to
guarantee that it resides within the same filesystem and therefore permit
hard-linking and cheap file moves.
"""
staging_path = tempfile.mkdtemp(dir=sr_path)
return staging_path
def cleanup_staging_area(staging_path):
"""Remove staging area directory
On upload, the staging area contains hard-links to the VHDs in the SR;
it's safe to remove the staging-area because the SR will keep the link
count > 0 (so the VHDs in the SR will not be deleted).
"""
if os.path.exists(staging_path):
shutil.rmtree(staging_path)
def _handle_old_style_images(staging_path):
"""Rename files to conform to new image format, if needed.
Old-Style:
snap.vhd -> image.vhd -> base.vhd
New-Style:
0.vhd -> 1.vhd -> ... (n-1).vhd
The New-Style format has the benefit of being able to support a VDI chain
of arbitrary length.
"""
file_num = 0
for filename in ('snap.vhd', 'image.vhd', 'base.vhd'):
path = os.path.join(staging_path, filename)
if os.path.exists(path):
_rename(path, os.path.join(staging_path, "%d.vhd" % file_num))
file_num += 1
def _assert_vhd_not_hidden(path):
"""Sanity check to ensure that only appropriate VHDs are marked as hidden.
If this flag is incorrectly set, then when we move the VHD into the SR, it
will be deleted out from under us.
"""
query_cmd = ["vhd-util", "query", "-n", path, "-f"]
out = run_command(query_cmd)
for line in out.splitlines():
if line.lower().startswith('hidden'):
value = line.split(':')[1].strip()
if value == "1":
raise Exception(
"VHD %s is marked as hidden without child" % path)
def _validate_vhd(vdi_path):
"""
This checks for several errors in the VHD structure.
Most notably, it checks that the timestamp in the footer is correct, but
may pick up other errors also.
This check ensures that the timestamps listed in the VHD footer aren't in
the future. This can occur during a migration if the clocks on the the two
Dom0's are out-of-sync. This would corrupt the SR if it were imported, so
generate an exception to bail.
"""
check_cmd = ["vhd-util", "check", "-n", vdi_path, "-p"]
out = run_command(check_cmd, ok_exit_codes=[0, 22])
first_line = out.splitlines()[0].strip()
if 'invalid' in first_line:
if 'footer' in first_line:
part = 'footer'
elif 'header' in first_line:
part = 'header'
else:
part = 'setting'
details = first_line.split(':', 1)
if len(details) == 2:
details = details[1]
else:
details = first_line
extra = ''
if 'timestamp' in first_line:
extra = (" ensure source and destination host machines have "
"time set correctly")
LOG.info("VDI Error details: %s" % out)
raise Exception(
"VDI '%(vdi_path)s' has an invalid %(part)s: '%(details)s'"
"%(extra)s" % {'vdi_path': vdi_path, 'part': part,
'details': details, 'extra': extra})
def _validate_vdi_chain(vdi_path):
"""
This check ensures that the parent pointers on the VHDs are valid
before we move the VDI chain to the SR. This is *very* important
because a bad parent pointer will corrupt the SR causing a cascade of
failures.
"""
def get_parent_path(path):
query_cmd = ["vhd-util", "query", "-n", path, "-p"]
out = run_command(query_cmd, ok_exit_codes=[0, 22])
first_line = out.splitlines()[0].strip()
if first_line.endswith(".vhd"):
return first_line
elif 'has no parent' in first_line:
return None
elif 'query failed' in first_line:
raise Exception("VDI '%s' not present which breaks"
" the VDI chain, bailing out" % path)
else:
raise Exception("Unexpected output '%s' from vhd-util" % out)
cur_path = vdi_path
while cur_path:
_validate_vhd(cur_path)
cur_path = get_parent_path(cur_path)
def _validate_sequenced_vhds(staging_path):
"""This check ensures that the VHDs in the staging area are sequenced
properly from 0 to n-1 with no gaps.
"""
seq_num = 0
filenames = os.listdir(staging_path)
for filename in filenames:
if not filename.endswith('.vhd'):
continue
# Ignore legacy swap embedded in the image, generated on-the-fly now
if filename == "swap.vhd":
continue
vhd_path = os.path.join(staging_path, "%d.vhd" % seq_num)
if not os.path.exists(vhd_path):
raise Exception("Corrupt image. Expected seq number: %d. Files: %s"
% (seq_num, filenames))
seq_num += 1
def import_vhds(sr_path, staging_path, uuid_stack):
"""Move VHDs from staging area into the SR.
The staging area is necessary because we need to perform some fixups
(assigning UUIDs, relinking the VHD chain) before moving into the SR,
otherwise the SR manager process could potentially delete the VHDs out from
under us.
Returns: A dict of imported VHDs:
{'root': {'uuid': 'ffff-aaaa'}}
"""
_handle_old_style_images(staging_path)
_validate_sequenced_vhds(staging_path)
files_to_move = []
# Collect sequenced VHDs and assign UUIDs to them
seq_num = 0
while True:
orig_vhd_path = os.path.join(staging_path, "%d.vhd" % seq_num)
if not os.path.exists(orig_vhd_path):
break
# Rename (0, 1 .. N).vhd -> aaaa-bbbb-cccc-dddd.vhd
vhd_uuid = uuid_stack.pop()
vhd_path = os.path.join(staging_path, "%s.vhd" % vhd_uuid)
_rename(orig_vhd_path, vhd_path)
if seq_num == 0:
leaf_vhd_path = vhd_path
leaf_vhd_uuid = vhd_uuid
files_to_move.append(vhd_path)
seq_num += 1
# Re-link VHDs, in reverse order, from base-copy -> leaf
parent_path = None
for vhd_path in reversed(files_to_move):
if parent_path:
# Link to parent
modify_cmd = ["vhd-util", "modify", "-n", vhd_path,
"-p", parent_path]
run_command(modify_cmd)
parent_path = vhd_path
# Sanity check the leaf VHD
_assert_vhd_not_hidden(leaf_vhd_path)
_validate_vdi_chain(leaf_vhd_path)
# Move files into SR
for orig_path in files_to_move:
new_path = os.path.join(sr_path, os.path.basename(orig_path))
_rename(orig_path, new_path)
imported_vhds = dict(root=dict(uuid=leaf_vhd_uuid))
return imported_vhds
def prepare_staging_area(sr_path, staging_path, vdi_uuids, seq_num=0):
"""Hard-link VHDs into staging area."""
for vdi_uuid in vdi_uuids:
source = os.path.join(sr_path, "%s.vhd" % vdi_uuid)
link_name = os.path.join(staging_path, "%d.vhd" % seq_num)
_link(source, link_name)
seq_num += 1
def create_tarball(fileobj, path, callback=None, compression_level=None):
"""Create a tarball from a given path.
:param fileobj: a file-like object holding the tarball byte-stream.
If None, then only the callback will be used.
:param path: path to create tarball from
:param callback: optional callback to call on each chunk written
:param compression_level: compression level, e.g., 9 for gzip -9.
"""
tar_cmd = ["tar", "-zc", "--directory=%s" % path, "."]
env = os.environ.copy()
if compression_level and 1 <= compression_level <= 9:
env["GZIP"] = "-%d" % compression_level
tar_proc = make_subprocess(tar_cmd, stdout=True, stderr=True, env=env)
while True:
chunk = tar_proc.stdout.read(CHUNK_SIZE)
if chunk == '':
break
if callback:
callback(chunk)
if fileobj:
fileobj.write(chunk)
finish_subprocess(tar_proc, tar_cmd)
def extract_tarball(fileobj, path, callback=None):
"""Extract a tarball to a given path.
:param fileobj: a file-like object holding the tarball byte-stream
:param path: path to extract tarball into
:param callback: optional callback to call on each chunk read
"""
tar_cmd = ["tar", "-zx", "--directory=%s" % path]
tar_proc = make_subprocess(tar_cmd, stderr=True, stdin=True)
while True:
chunk = fileobj.read(CHUNK_SIZE)
if chunk == '':
break
if callback:
callback(chunk)
tar_proc.stdin.write(chunk)
finish_subprocess(tar_proc, tar_cmd)
def _handle_serialization(func):
def wrapped(session, params):
params = pickle.loads(params['params'])
rv = func(session, *params['args'], **params['kwargs'])
return pickle.dumps(rv)
return wrapped
def register_plugin_calls(*funcs):
"""Wrapper around XenAPIPlugin.dispatch which handles pickle
serialization.
"""
wrapped_dict = {}
for func in funcs:
wrapped_dict[func.__name__] = _handle_serialization(func)
XenAPIPlugin.dispatch(wrapped_dict)
| apache-2.0 |
jorsea/odoo-addons | sale_add_products_wizard/wizard/sale_order_wizard.py | 3 | 1526 | # -*- coding: utf-8 -*-
##############################################################################
# For copyright and license notices, see __openerp__.py file in module root
# directory
##############################################################################
from openerp import models, fields, api
class sale_order_add_multiple(models.TransientModel):
_name = 'sale.order.add_multiple'
_description = 'Sale order add multiple'
quantity = fields.Float('Quantity',
default='1.0')
products_ids = fields.Many2many(
'product.product',
string='Products',
domain=[('sale_ok', '=', True)],
)
@api.one
def add_multiple(self):
active_id = self._context['active_id']
sale = self.env['sale.order'].browse(active_id)
for product_id in self.products_ids:
product = self.env['sale.order.line'].product_id_change(
sale.pricelist_id.id,
product_id.id,
qty=self.quantity,
uom=product_id.uom_id.id,
partner_id=sale.partner_id.id)
val = {
'name': product['value'].get('name'),
'product_uom_qty': self.quantity,
'order_id': active_id,
'product_id': product_id.id or False,
'product_uom': product_id.uom_id.id,
'price_unit': product['value'].get('price_unit'),
}
self.env['sale.order.line'].create(val)
| agpl-3.0 |
eddiejessup/nex | tests/test_lexer.py | 1 | 4285 | from nex.constants.codes import CatCode
from nex.accessors import Codes
from nex.lexer import Lexer
class DummyCatCodeGetter:
def __init__(self):
self.char_to_cat = Codes.default_initial_cat_codes()
def get(self, char):
return self.char_to_cat[char]
def lex_string_to_tokens(s):
cat_code_getter = DummyCatCodeGetter()
lex = Lexer.from_string(s, get_cat_code_func=cat_code_getter.get)
return list(lex.advance_to_end())
def test_trioing():
"""Check trioing (escaping characters to obtain exotic character codes)."""
test_input = 'abc^^I^^K^^>'
# The code numbers we should return if all is well.
correct_code_nrs = [ord('a'), ord('b'), ord('c'),
ord('\t'), ord('K') - 64, ord('>') + 64]
# Check with various characters, including the usual '^'.
for trio_char in ['^', '1', '@']:
cat_code_getter = DummyCatCodeGetter()
# Set our chosen trioing character to have superscript CatCode, so we
# can use it for trioing (this is a necessary condition to trigger it).
cat_code_getter.char_to_cat[trio_char] = CatCode.superscript
# Input the test string, substituted with the chosen trioing character.
lex = Lexer.from_string(test_input.replace('^', trio_char),
cat_code_getter.get)
tokens = list(lex.advance_to_end())
# Check correct number of tokens were returned
assert len(tokens) == 6
# Check the correct code numbers were returned.
assert [ord(t.value['char']) for t in tokens] == correct_code_nrs
def test_comments():
"""Check comment characters."""
tokens = lex_string_to_tokens(r'hello% say hello')
assert [t.value['char'] for t in tokens] == list('hello')
def test_skipping_blanks():
"""Check multiple spaces are ignored."""
toks_single = lex_string_to_tokens(r'hello m')
toks_triple = lex_string_to_tokens(r'hello m')
# Check same char-cat pairs are returned.
assert ([t.value['char'] for t in toks_single] ==
[t.value['char'] for t in toks_triple])
assert ([t.value['cat'] for t in toks_single] ==
[t.value['cat'] for t in toks_triple])
def test_control_sequence():
"""Check multiple spaces are ignored."""
tokens = lex_string_to_tokens(r'a\howdy\world')
assert len(tokens) == 3
assert tokens[0].value['char'] == 'a'
assert tokens[1].value == 'howdy'
assert tokens[2].value == 'world'
# Check control sequences starting with a non-letter, make single-letter
# control sequences.
tokens_single = lex_string_to_tokens(r'\@a')
assert tokens_single[0].value == '@' and len(tokens_single) == 2
def test_control_sequence_spacing():
"""Check multiple spaces are ignored."""
tokens_close = lex_string_to_tokens(r'\howdy\world')
tokens_spaced = lex_string_to_tokens(r'\howdy \world')
tokens_super_spaced = lex_string_to_tokens(r'\howdy \world')
assert len(tokens_close) == len(tokens_spaced) == len(tokens_super_spaced)
def test_new_lines():
"""Check what happens when entering new-lines."""
# Note that I'm not even sure what the specification says *should* happen
# here.
# Check entering once in the middle of a line makes a space.
tokens = lex_string_to_tokens('a\n')
assert len(tokens) == 2 and tokens[1].value['char'] == ' '
# Check entering a new-line at a line beginning gives a \par.
tokens = lex_string_to_tokens('a\n\n')
assert (len(tokens) == 3 and tokens[1].value['char'] == ' ' and
tokens[2].value == 'par')
# Check entering a new-line when skipping spaces does nothing. Note that a
# space *is* returned, but from the first space after the 'a'.
tokens = lex_string_to_tokens('a \n')
assert len(tokens) == 2 and tokens[1].value['char'] == ' '
def test_tokenise():
"""Check what happens when entering non-lexical tokens."""
s = '@${'
tokens = lex_string_to_tokens(s)
assert len(tokens) == 3
# Tokens should just be wrapped as a lexical token, with the character
# returned by the reader, and category assigned by the state.
for c, t in zip(s, tokens):
assert t.value['char'] == c
assert t.value['cat'] == CatCode.other
| mit |
Shaun-duplessis79/mongoose | bindings/python/mongoose.py | 106 | 5281 | # Copyright (c) 2004-2009 Sergey Lyubka
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#
# $Id: mongoose.py 471 2009-08-30 14:30:21Z valenok $
"""
This module provides python binding for the Mongoose web server.
There are two classes defined:
Connection: - wraps all functions that accept struct mg_connection pointer
as first argument.
Mongoose: wraps all functions that accept struct mg_context pointer as
first argument.
Creating Mongoose object automatically starts server, deleting object
automatically stops it. There is no need to call mg_start() or mg_stop().
"""
import ctypes
import os
NEW_REQUEST = 0
HTTP_ERROR = 1
EVENT_LOG = 2
INIT_SSL = 3
class mg_header(ctypes.Structure):
"""A wrapper for struct mg_header."""
_fields_ = [
('name', ctypes.c_char_p),
('value', ctypes.c_char_p),
]
class mg_request_info(ctypes.Structure):
"""A wrapper for struct mg_request_info."""
_fields_ = [
('user_data', ctypes.c_char_p),
('request_method', ctypes.c_char_p),
('uri', ctypes.c_char_p),
('http_version', ctypes.c_char_p),
('query_string', ctypes.c_char_p),
('remote_user', ctypes.c_char_p),
('log_message', ctypes.c_char_p),
('remote_ip', ctypes.c_long),
('remote_port', ctypes.c_int),
('status_code', ctypes.c_int),
('is_ssl', ctypes.c_int),
('num_headers', ctypes.c_int),
('http_headers', mg_header * 64),
]
mg_callback_t = ctypes.CFUNCTYPE(ctypes.c_void_p, ctypes.c_int, ctypes.c_void_p)
class Connection(object):
"""A wrapper class for all functions that take
struct mg_connection * as the first argument."""
def __init__(self, mongoose, connection):
self.m = mongoose
self.conn = ctypes.c_void_p(connection)
self.info = self.m.dll.mg_get_request_info(self.conn).contents
def get_header(self, name):
val = self.m.dll.mg_get_header(self.conn, name)
return ctypes.c_char_p(val).value
def get_var(self, data, name):
size = data and len(data) or 0
buf = ctypes.create_string_buffer(size)
n = self.m.dll.mg_get_var(data, size, name, buf, size)
return n >= 0 and buf or None
def printf(self, fmt, *args):
val = self.m.dll.mg_printf(self.conn, fmt, *args)
return ctypes.c_int(val).value
def write(self, data):
val = self.m.dll.mg_write(self.conn, data, len(data))
return ctypes.c_int(val).value
def read(self, size):
buf = ctypes.create_string_buffer(size)
n = self.m.dll.mg_read(self.conn, buf, size)
return n <= 0 and None or buf[:n]
def send_file(self, path):
self.m.dll.mg_send_file(self.conn, path)
class Mongoose(object):
"""A wrapper class for Mongoose shared library."""
def __init__(self, callback, **kwargs):
if os.name == 'nt':
self.dll = ctypes.WinDLL('_mongoose.dll')
else:
self.dll = ctypes.CDLL('_mongoose.so')
self.dll.mg_start.restype = ctypes.c_void_p
self.dll.mg_modify_passwords_file.restype = ctypes.c_int
self.dll.mg_read.restype = ctypes.c_int
self.dll.mg_write.restype = ctypes.c_int
self.dll.mg_printf.restype = ctypes.c_int
self.dll.mg_get_header.restype = ctypes.c_char_p
self.dll.mg_get_var.restype = ctypes.c_int
self.dll.mg_get_cookie.restype = ctypes.c_int
self.dll.mg_get_option.restype = ctypes.c_char_p
self.dll.mg_get_request_info.restype = ctypes.POINTER(mg_request_info)
if callback:
# Create a closure that will be called by the shared library.
def func(event, connection):
# Wrap connection pointer into the connection
# object and call Python callback
conn = Connection(self, connection)
return callback(event, conn) and 1 or 0
# Convert the closure into C callable object
self.callback = mg_callback_t(func)
self.callback.restype = ctypes.c_char_p
else:
self.callback = ctypes.c_void_p(0)
args = [y for x in kwargs.items() for y in x] + [None]
options = (ctypes.c_char_p * len(args))(*args)
ret = self.dll.mg_start(self.callback, 0, options)
self.ctx = ctypes.c_void_p(ret)
def __del__(self):
"""Destructor, stop Mongoose instance."""
self.dll.mg_stop(self.ctx)
def get_option(self, name):
return self.dll.mg_get_option(self.ctx, name)
| mit |
sysbot/CouchPotatoServer | libs/tornado/platform/asyncio.py | 10 | 4943 | """Bridges between the `asyncio` module and Tornado IOLoop.
This is a work in progress and interfaces are subject to change.
To test:
python3.4 -m tornado.test.runtests --ioloop=tornado.platform.asyncio.AsyncIOLoop
python3.4 -m tornado.test.runtests --ioloop=tornado.platform.asyncio.AsyncIOMainLoop
(the tests log a few warnings with AsyncIOMainLoop because they leave some
unfinished callbacks on the event loop that fail when it resumes)
"""
from __future__ import absolute_import, division, print_function, with_statement
import asyncio
import datetime
import functools
import os
from tornado.ioloop import IOLoop
from tornado import stack_context
class BaseAsyncIOLoop(IOLoop):
def initialize(self, asyncio_loop, close_loop=False):
self.asyncio_loop = asyncio_loop
self.close_loop = close_loop
self.asyncio_loop.call_soon(self.make_current)
# Maps fd to handler function (as in IOLoop.add_handler)
self.handlers = {}
# Set of fds listening for reads/writes
self.readers = set()
self.writers = set()
self.closing = False
def close(self, all_fds=False):
self.closing = True
for fd in list(self.handlers):
self.remove_handler(fd)
if all_fds:
try:
os.close(fd)
except OSError:
pass
if self.close_loop:
self.asyncio_loop.close()
def add_handler(self, fd, handler, events):
if fd in self.handlers:
raise ValueError("fd %d added twice" % fd)
self.handlers[fd] = stack_context.wrap(handler)
if events & IOLoop.READ:
self.asyncio_loop.add_reader(
fd, self._handle_events, fd, IOLoop.READ)
self.readers.add(fd)
if events & IOLoop.WRITE:
self.asyncio_loop.add_writer(
fd, self._handle_events, fd, IOLoop.WRITE)
self.writers.add(fd)
def update_handler(self, fd, events):
if events & IOLoop.READ:
if fd not in self.readers:
self.asyncio_loop.add_reader(
fd, self._handle_events, fd, IOLoop.READ)
self.readers.add(fd)
else:
if fd in self.readers:
self.asyncio_loop.remove_reader(fd)
self.readers.remove(fd)
if events & IOLoop.WRITE:
if fd not in self.writers:
self.asyncio_loop.add_writer(
fd, self._handle_events, fd, IOLoop.WRITE)
self.writers.add(fd)
else:
if fd in self.writers:
self.asyncio_loop.remove_writer(fd)
self.writers.remove(fd)
def remove_handler(self, fd):
if fd not in self.handlers:
return
if fd in self.readers:
self.asyncio_loop.remove_reader(fd)
self.readers.remove(fd)
if fd in self.writers:
self.asyncio_loop.remove_writer(fd)
self.writers.remove(fd)
del self.handlers[fd]
def _handle_events(self, fd, events):
self.handlers[fd](fd, events)
def start(self):
self._setup_logging()
self.asyncio_loop.run_forever()
def stop(self):
self.asyncio_loop.stop()
def _run_callback(self, callback, *args, **kwargs):
try:
callback(*args, **kwargs)
except Exception:
self.handle_callback_exception(callback)
def add_timeout(self, deadline, callback):
if isinstance(deadline, (int, float)):
delay = max(deadline - self.time(), 0)
elif isinstance(deadline, datetime.timedelta):
delay = deadline.total_seconds()
else:
raise TypeError("Unsupported deadline %r", deadline)
return self.asyncio_loop.call_later(delay, self._run_callback,
stack_context.wrap(callback))
def remove_timeout(self, timeout):
timeout.cancel()
def add_callback(self, callback, *args, **kwargs):
if self.closing:
raise RuntimeError("IOLoop is closing")
if kwargs:
self.asyncio_loop.call_soon_threadsafe(functools.partial(
self._run_callback, stack_context.wrap(callback),
*args, **kwargs))
else:
self.asyncio_loop.call_soon_threadsafe(
self._run_callback, stack_context.wrap(callback), *args)
add_callback_from_signal = add_callback
class AsyncIOMainLoop(BaseAsyncIOLoop):
def initialize(self):
super(AsyncIOMainLoop, self).initialize(asyncio.get_event_loop(),
close_loop=False)
class AsyncIOLoop(BaseAsyncIOLoop):
def initialize(self):
super(AsyncIOLoop, self).initialize(asyncio.new_event_loop(),
close_loop=True)
| gpl-3.0 |
sportorg/pysport | sportorg/modules/winorient/winorient_server.py | 1 | 2292 | import datetime
from socket import *
from sportorg.utils.time import time_to_hhmmss
"""
Format of WDB data package
- length is 1772 bytes
1) 36b text block at the beginning
2 4132500 0 0 3974600\n
bib - finish_time - disqual_status - 0 - start_time
2) binary part
bytes 128-131 - card number
bytes 136-139 - qty of punches
bytes 144-147 - start in card
bytes 152-155 - finish in card
starting from b172: 8b blocks * 200
- byte 1 control number
- bytes 4-7 punch time
"""
def int_to_time(value):
""" convert value from 1/100 s to time """
today = datetime.datetime.now()
ret = datetime.datetime(
today.year,
today.month,
today.day,
value // 360000 % 24,
(value % 360000) // 6000,
(value % 6000) // 100,
(value % 100) * 10000,
)
return ret
host = 'localhost'
port = 1212
addr = (host, port)
udp_socket = socket(AF_INET, SOCK_DGRAM)
udp_socket.bind(addr)
# main loop
while True:
print('wait data...')
# recvfrom - receiving of data
conn, addr = udp_socket.recvfrom(1772)
print('client addr: ', addr)
print('data: ', conn)
# string = ''
# for i in conn:
# string += str( hex(i)) + '-'
# print(string)
text_array = bytes(conn[0:34]).decode().split()
bib = text_array[0]
result = int_to_time(int(text_array[1]))
status = text_array[2]
start = int_to_time(int(text_array[4]))
byteorder = 'little'
punch_qty = int.from_bytes(conn[136:140], byteorder)
card_start = int_to_time(int.from_bytes(conn[144:148], byteorder))
card_finish = int_to_time(int.from_bytes(conn[152:156], byteorder))
init_offset = 172
punches = []
for i in range(punch_qty):
cp = int.from_bytes(
conn[init_offset + i * 8 : init_offset + i * 8 + 1], byteorder
)
time = int_to_time(
int.from_bytes(
conn[init_offset + i * 8 + 4 : init_offset + i * 8 + 8], byteorder
)
)
punches.append((cp, time_to_hhmmss(time)))
print('bib=' + bib + ' result=' + time_to_hhmmss(result) + ' punches=')
print(punches)
# sendto - responce
udp_socket.sendto(b'message received by the server', addr)
# udp_socket.close()
| gpl-3.0 |
agiliq/django | django/template/loaders/app_directories.py | 89 | 2231 | """
Wrapper for loading templates from "templates" directories in INSTALLED_APPS
packages.
"""
import os
import sys
from django.apps import apps
from django.conf import settings
from django.template.base import TemplateDoesNotExist
from django.template.loader import BaseLoader
from django.utils._os import safe_join
from django.utils import six
def calculate_app_template_dirs():
if six.PY2:
fs_encoding = sys.getfilesystemencoding() or sys.getdefaultencoding()
app_template_dirs = []
for app_config in apps.get_app_configs():
if not app_config.path:
continue
template_dir = os.path.join(app_config.path, 'templates')
if os.path.isdir(template_dir):
if six.PY2:
template_dir = template_dir.decode(fs_encoding)
app_template_dirs.append(template_dir)
return tuple(app_template_dirs)
# At compile time, cache the directories to search.
app_template_dirs = calculate_app_template_dirs()
class Loader(BaseLoader):
is_usable = True
def get_template_sources(self, template_name, template_dirs=None):
"""
Returns the absolute paths to "template_name", when appended to each
directory in "template_dirs". Any paths that don't lie inside one of the
template dirs are excluded from the result set, for security reasons.
"""
if not template_dirs:
template_dirs = app_template_dirs
for template_dir in template_dirs:
try:
yield safe_join(template_dir, template_name)
except UnicodeDecodeError:
# The template dir name was a bytestring that wasn't valid UTF-8.
raise
except ValueError:
# The joined path was located outside of template_dir.
pass
def load_template_source(self, template_name, template_dirs=None):
for filepath in self.get_template_sources(template_name, template_dirs):
try:
with open(filepath, 'rb') as fp:
return (fp.read().decode(settings.FILE_CHARSET), filepath)
except IOError:
pass
raise TemplateDoesNotExist(template_name)
| bsd-3-clause |
kontais/EFI-MIPS | ToolKit/cmds/python/Lib/Queue.py | 13 | 5880 | """A multi-producer, multi-consumer queue."""
from time import time as _time
from collections import deque
__all__ = ['Empty', 'Full', 'Queue']
class Empty(Exception):
"Exception raised by Queue.get(block=0)/get_nowait()."
pass
class Full(Exception):
"Exception raised by Queue.put(block=0)/put_nowait()."
pass
class Queue:
def __init__(self, maxsize=0):
"""Initialize a queue object with a given maximum size.
If maxsize is <= 0, the queue size is infinite.
"""
try:
import threading
except ImportError:
import dummy_threading as threading
self._init(maxsize)
# mutex must be held whenever the queue is mutating. All methods
# that acquire mutex must release it before returning. mutex
# is shared between the two conditions, so acquiring and
# releasing the conditions also acquires and releases mutex.
self.mutex = threading.Lock()
# Notify not_empty whenever an item is added to the queue; a
# thread waiting to get is notified then.
self.not_empty = threading.Condition(self.mutex)
# Notify not_full whenever an item is removed from the queue;
# a thread waiting to put is notified then.
self.not_full = threading.Condition(self.mutex)
def qsize(self):
"""Return the approximate size of the queue (not reliable!)."""
self.mutex.acquire()
n = self._qsize()
self.mutex.release()
return n
def empty(self):
"""Return True if the queue is empty, False otherwise (not reliable!)."""
self.mutex.acquire()
n = self._empty()
self.mutex.release()
return n
def full(self):
"""Return True if the queue is full, False otherwise (not reliable!)."""
self.mutex.acquire()
n = self._full()
self.mutex.release()
return n
def put(self, item, block=True, timeout=None):
"""Put an item into the queue.
If optional args 'block' is true and 'timeout' is None (the default),
block if necessary until a free slot is available. If 'timeout' is
a positive number, it blocks at most 'timeout' seconds and raises
the Full exception if no free slot was available within that time.
Otherwise ('block' is false), put an item on the queue if a free slot
is immediately available, else raise the Full exception ('timeout'
is ignored in that case).
"""
self.not_full.acquire()
try:
if not block:
if self._full():
raise Full
elif timeout is None:
while self._full():
self.not_full.wait()
else:
if timeout < 0:
raise ValueError("'timeout' must be a positive number")
endtime = _time() + timeout
while self._full():
remaining = endtime - _time()
if remaining <= 0.0:
raise Full
self.not_full.wait(remaining)
self._put(item)
self.not_empty.notify()
finally:
self.not_full.release()
def put_nowait(self, item):
"""Put an item into the queue without blocking.
Only enqueue the item if a free slot is immediately available.
Otherwise raise the Full exception.
"""
return self.put(item, False)
def get(self, block=True, timeout=None):
"""Remove and return an item from the queue.
If optional args 'block' is true and 'timeout' is None (the default),
block if necessary until an item is available. If 'timeout' is
a positive number, it blocks at most 'timeout' seconds and raises
the Empty exception if no item was available within that time.
Otherwise ('block' is false), return an item if one is immediately
available, else raise the Empty exception ('timeout' is ignored
in that case).
"""
self.not_empty.acquire()
try:
if not block:
if self._empty():
raise Empty
elif timeout is None:
while self._empty():
self.not_empty.wait()
else:
if timeout < 0:
raise ValueError("'timeout' must be a positive number")
endtime = _time() + timeout
while self._empty():
remaining = endtime - _time()
if remaining <= 0.0:
raise Empty
self.not_empty.wait(remaining)
item = self._get()
self.not_full.notify()
return item
finally:
self.not_empty.release()
def get_nowait(self):
"""Remove and return an item from the queue without blocking.
Only get an item if one is immediately available. Otherwise
raise the Empty exception.
"""
return self.get(False)
# Override these methods to implement other queue organizations
# (e.g. stack or priority queue).
# These will only be called with appropriate locks held
# Initialize the queue representation
def _init(self, maxsize):
self.maxsize = maxsize
self.queue = deque()
def _qsize(self):
return len(self.queue)
# Check whether the queue is empty
def _empty(self):
return not self.queue
# Check whether the queue is full
def _full(self):
return self.maxsize > 0 and len(self.queue) == self.maxsize
# Put a new item in the queue
def _put(self, item):
self.queue.append(item)
# Get an item from the queue
def _get(self):
return self.queue.popleft()
| bsd-3-clause |
hobarrera/django | tests/view_tests/tests/test_i18n_deprecated.py | 33 | 10468 | # -*- coding:utf-8 -*-
from __future__ import unicode_literals
import gettext
import json
from os import path
from django.conf import settings
from django.test import (
SimpleTestCase, ignore_warnings, modify_settings, override_settings,
)
from django.test.selenium import SeleniumTestCase
from django.utils import six
from django.utils._os import upath
from django.utils.deprecation import RemovedInDjango20Warning
from django.utils.translation import override
from ..urls import locale_dir
@override_settings(ROOT_URLCONF='view_tests.urls')
@ignore_warnings(category=RemovedInDjango20Warning)
class JsI18NTests(SimpleTestCase):
"""
Tests deprecated django views in django/views/i18n.py
"""
def test_jsi18n(self):
"""The javascript_catalog can be deployed with language settings"""
for lang_code in ['es', 'fr', 'ru']:
with override(lang_code):
catalog = gettext.translation('djangojs', locale_dir, [lang_code])
if six.PY3:
trans_txt = catalog.gettext('this is to be translated')
else:
trans_txt = catalog.ugettext('this is to be translated')
response = self.client.get('/old_jsi18n/')
# response content must include a line like:
# "this is to be translated": <value of trans_txt Python variable>
# json.dumps() is used to be able to check unicode strings
self.assertContains(response, json.dumps(trans_txt), 1)
if lang_code == 'fr':
# Message with context (msgctxt)
self.assertContains(response, '"month name\\u0004May": "mai"', 1)
def test_jsoni18n(self):
"""
The json_catalog returns the language catalog and settings as JSON.
"""
with override('de'):
response = self.client.get('/old_jsoni18n/')
data = json.loads(response.content.decode('utf-8'))
self.assertIn('catalog', data)
self.assertIn('formats', data)
self.assertIn('plural', data)
self.assertEqual(data['catalog']['month name\x04May'], 'Mai')
self.assertIn('DATETIME_FORMAT', data['formats'])
self.assertEqual(data['plural'], '(n != 1)')
def test_jsi18n_with_missing_en_files(self):
"""
The javascript_catalog shouldn't load the fallback language in the
case that the current selected language is actually the one translated
from, and hence missing translation files completely.
This happens easily when you're translating from English to other
languages and you've set settings.LANGUAGE_CODE to some other language
than English.
"""
with self.settings(LANGUAGE_CODE='es'), override('en-us'):
response = self.client.get('/old_jsi18n/')
self.assertNotContains(response, 'esto tiene que ser traducido')
def test_jsoni18n_with_missing_en_files(self):
"""
Same as above for the json_catalog view. Here we also check for the
expected JSON format.
"""
with self.settings(LANGUAGE_CODE='es'), override('en-us'):
response = self.client.get('/old_jsoni18n/')
data = json.loads(response.content.decode('utf-8'))
self.assertIn('catalog', data)
self.assertIn('formats', data)
self.assertIn('plural', data)
self.assertEqual(data['catalog'], {})
self.assertIn('DATETIME_FORMAT', data['formats'])
self.assertIsNone(data['plural'])
def test_jsi18n_fallback_language(self):
"""
Let's make sure that the fallback language is still working properly
in cases where the selected language cannot be found.
"""
with self.settings(LANGUAGE_CODE='fr'), override('fi'):
response = self.client.get('/old_jsi18n/')
self.assertContains(response, 'il faut le traduire')
self.assertNotContains(response, "Untranslated string")
def test_i18n_english_variant(self):
with override('en-gb'):
response = self.client.get('/old_jsi18n/')
self.assertIn(
'"this color is to be translated": "this colour is to be translated"',
response.context['catalog_str']
)
def test_i18n_language_non_english_default(self):
"""
Check if the Javascript i18n view returns an empty language catalog
if the default language is non-English, the selected language
is English and there is not 'en' translation available. See #13388,
#3594 and #13726 for more details.
"""
with self.settings(LANGUAGE_CODE='fr'), override('en-us'):
response = self.client.get('/old_jsi18n/')
self.assertNotContains(response, 'Choisir une heure')
@modify_settings(INSTALLED_APPS={'append': 'view_tests.app0'})
def test_non_english_default_english_userpref(self):
"""
Same as above with the difference that there IS an 'en' translation
available. The Javascript i18n view must return a NON empty language catalog
with the proper English translations. See #13726 for more details.
"""
with self.settings(LANGUAGE_CODE='fr'), override('en-us'):
response = self.client.get('/old_jsi18n_english_translation/')
self.assertContains(response, 'this app0 string is to be translated')
def test_i18n_language_non_english_fallback(self):
"""
Makes sure that the fallback language is still working properly
in cases where the selected language cannot be found.
"""
with self.settings(LANGUAGE_CODE='fr'), override('none'):
response = self.client.get('/old_jsi18n/')
self.assertContains(response, 'Choisir une heure')
def test_escaping(self):
# Force a language via GET otherwise the gettext functions are a noop!
response = self.client.get('/old_jsi18n_admin/?language=de')
self.assertContains(response, '\\x04')
@modify_settings(INSTALLED_APPS={'append': ['view_tests.app5']})
def test_non_BMP_char(self):
"""
Non-BMP characters should not break the javascript_catalog (#21725).
"""
with self.settings(LANGUAGE_CODE='en-us'), override('fr'):
response = self.client.get('/old_jsi18n/app5/')
self.assertContains(response, 'emoji')
self.assertContains(response, '\\ud83d\\udca9')
@override_settings(ROOT_URLCONF='view_tests.urls')
@ignore_warnings(category=RemovedInDjango20Warning)
class JsI18NTestsMultiPackage(SimpleTestCase):
"""
Tests for django views in django/views/i18n.py that need to change
settings.LANGUAGE_CODE and merge JS translation from several packages.
"""
@modify_settings(INSTALLED_APPS={'append': ['view_tests.app1', 'view_tests.app2']})
def test_i18n_language_english_default(self):
"""
Check if the JavaScript i18n view returns a complete language catalog
if the default language is en-us, the selected language has a
translation available and a catalog composed by djangojs domain
translations of multiple Python packages is requested. See #13388,
#3594 and #13514 for more details.
"""
with self.settings(LANGUAGE_CODE='en-us'), override('fr'):
response = self.client.get('/old_jsi18n_multi_packages1/')
self.assertContains(response, 'il faut traduire cette cha\\u00eene de caract\\u00e8res de app1')
@modify_settings(INSTALLED_APPS={'append': ['view_tests.app3', 'view_tests.app4']})
def test_i18n_different_non_english_languages(self):
"""
Similar to above but with neither default or requested language being
English.
"""
with self.settings(LANGUAGE_CODE='fr'), override('es-ar'):
response = self.client.get('/old_jsi18n_multi_packages2/')
self.assertContains(response, 'este texto de app3 debe ser traducido')
def test_i18n_with_locale_paths(self):
extended_locale_paths = settings.LOCALE_PATHS + [
path.join(
path.dirname(path.dirname(path.abspath(upath(__file__)))),
'app3',
'locale',
),
]
with self.settings(LANGUAGE_CODE='es-ar', LOCALE_PATHS=extended_locale_paths):
with override('es-ar'):
response = self.client.get('/old_jsi18n/')
self.assertContains(response, 'este texto de app3 debe ser traducido')
@override_settings(ROOT_URLCONF='view_tests.urls')
@ignore_warnings(category=RemovedInDjango20Warning)
class JavascriptI18nTests(SeleniumTestCase):
# The test cases use fixtures & translations from these apps.
available_apps = [
'django.contrib.admin', 'django.contrib.auth',
'django.contrib.contenttypes', 'view_tests',
]
@override_settings(LANGUAGE_CODE='de')
def test_javascript_gettext(self):
self.selenium.get('%s%s' % (self.live_server_url, '/old_jsi18n_template/'))
elem = self.selenium.find_element_by_id("gettext")
self.assertEqual(elem.text, "Entfernen")
elem = self.selenium.find_element_by_id("ngettext_sing")
self.assertEqual(elem.text, "1 Element")
elem = self.selenium.find_element_by_id("ngettext_plur")
self.assertEqual(elem.text, "455 Elemente")
elem = self.selenium.find_element_by_id("pgettext")
self.assertEqual(elem.text, "Kann")
elem = self.selenium.find_element_by_id("npgettext_sing")
self.assertEqual(elem.text, "1 Resultat")
elem = self.selenium.find_element_by_id("npgettext_plur")
self.assertEqual(elem.text, "455 Resultate")
@modify_settings(INSTALLED_APPS={'append': ['view_tests.app1', 'view_tests.app2']})
@override_settings(LANGUAGE_CODE='fr')
def test_multiple_catalogs(self):
self.selenium.get('%s%s' % (self.live_server_url, '/old_jsi18n_multi_catalogs/'))
elem = self.selenium.find_element_by_id('app1string')
self.assertEqual(elem.text, 'il faut traduire cette chaîne de caractères de app1')
elem = self.selenium.find_element_by_id('app2string')
self.assertEqual(elem.text, 'il faut traduire cette chaîne de caractères de app2')
| bsd-3-clause |
pawelld/webias | webias/gnosis/xml/pickle/test/test_bltin.py | 3 | 2268 |
#
# basic test using only builtins --fpm
#
# (good diagnostic when I break things :-)
#
from types import *
import gnosis.xml.pickle as xml_pickle
from gnosis.xml.pickle.util import setInBody
import funcs
funcs.set_parser()
class foo_class:
def __init__(self):
pass
def checkfoo(o1,o2):
"Check that objects match (sync w/obj creation below)"
# make sure it pulled out the correct class
if o1.__class__ != foo_class or \
o2.__class__ != foo_class:
raise "ERROR(0)"
# check data
for attr in ['s1','s2','f','i','i2','li',
'j','n','d','l','tup']:
if getattr(o1,attr) != getattr(o2,attr):
raise "ERROR(1)"
### we print type+value to make sure unpickling really worked
##def printfoo(obj):
## print type(obj.s1), obj.s1
## print type(obj.s2), obj.s2
## print type(obj.f), obj.f
## print type(obj.i), obj.i, type(obj.i2), obj.i2
## print type(obj.li), obj.li
## print type(obj.j), obj.j
## print type(obj.n), obj.n
## print type(obj.d), obj.d['One'], obj.d['Two'], obj.d['Three']
## print type(obj.l), obj.l[0], obj.l[1], obj.l[2]
## print type(obj.tup), obj.tup[0], obj.tup[1], obj.tup[2]
xml_pickle.setParanoia(0) # allow it to use our namespace
foo = foo_class()
# try putting numeric content in body (doesn't matter which
# numeric type)
setInBody(ComplexType,1)
# test both code paths
# path 1 - non-nested ('attr' nodes)
foo.s1 = "this is a \" string with a ' in it"
foo.s2 = 'this is a \' string with a " in it'
foo.f = 123.456
foo.i = 789
foo.i2 = 0 # zero was a bug in 1.0.1
foo.li = 5678L
foo.j = 12+34j
foo.n = None
# path 2 - nested ('item/key/val' nodes)
foo.d = { 'One': "First dict item",
'Two': 222,
'Three': 333.444 }
foo.l = []
foo.l.append( "first list" )
foo.l.append( 321 )
foo.l.append( 12.34 )
foo.tup = ("tuple", 123, 444.333)
#xml_pickle.setVerbose(1)
#print "---PRE-PICKLE---"
#printfoo(foo)
x1 = xml_pickle.XML_Pickler(foo).dumps()
#print x1
#print "---POST-PICKLE---"
bar = xml_pickle.XML_Pickler().loads(x1)
#printfoo(bar)
checkfoo(foo,bar)
#x2 = xml_pickle.XML_Pickler(bar).dumps()
#print "---XML from original---"
#print x1
#print "---XML from copy---"
#print x2
print "** OK **"
| agpl-3.0 |
nvoron23/scikit-learn | sklearn/svm/classes.py | 126 | 40114 | import warnings
import numpy as np
from .base import _fit_liblinear, BaseSVC, BaseLibSVM
from ..base import BaseEstimator, RegressorMixin
from ..linear_model.base import LinearClassifierMixin, SparseCoefMixin, \
LinearModel
from ..feature_selection.from_model import _LearntSelectorMixin
from ..utils import check_X_y
from ..utils.validation import _num_samples
class LinearSVC(BaseEstimator, LinearClassifierMixin,
_LearntSelectorMixin, SparseCoefMixin):
"""Linear Support Vector Classification.
Similar to SVC with parameter kernel='linear', but implemented in terms of
liblinear rather than libsvm, so it has more flexibility in the choice of
penalties and loss functions and should scale better to large numbers of
samples.
This class supports both dense and sparse input and the multiclass support
is handled according to a one-vs-the-rest scheme.
Read more in the :ref:`User Guide <svm_classification>`.
Parameters
----------
C : float, optional (default=1.0)
Penalty parameter C of the error term.
loss : string, 'hinge' or 'squared_hinge' (default='squared_hinge')
Specifies the loss function. 'hinge' is the standard SVM loss
(used e.g. by the SVC class) while 'squared_hinge' is the
square of the hinge loss.
penalty : string, 'l1' or 'l2' (default='l2')
Specifies the norm used in the penalization. The 'l2'
penalty is the standard used in SVC. The 'l1' leads to `coef_`
vectors that are sparse.
dual : bool, (default=True)
Select the algorithm to either solve the dual or primal
optimization problem. Prefer dual=False when n_samples > n_features.
tol : float, optional (default=1e-4)
Tolerance for stopping criteria.
multi_class: string, 'ovr' or 'crammer_singer' (default='ovr')
Determines the multi-class strategy if `y` contains more than
two classes.
`ovr` trains n_classes one-vs-rest classifiers, while `crammer_singer`
optimizes a joint objective over all classes.
While `crammer_singer` is interesting from a theoretical perspective
as it is consistent, it is seldom used in practice as it rarely leads
to better accuracy and is more expensive to compute.
If `crammer_singer` is chosen, the options loss, penalty and dual will
be ignored.
fit_intercept : boolean, optional (default=True)
Whether to calculate the intercept for this model. If set
to false, no intercept will be used in calculations
(i.e. data is expected to be already centered).
intercept_scaling : float, optional (default=1)
When self.fit_intercept is True, instance vector x becomes
[x, self.intercept_scaling],
i.e. a "synthetic" feature with constant value equals to
intercept_scaling is appended to the instance vector.
The intercept becomes intercept_scaling * synthetic feature weight
Note! the synthetic feature weight is subject to l1/l2 regularization
as all other features.
To lessen the effect of regularization on synthetic feature weight
(and therefore on the intercept) intercept_scaling has to be increased.
class_weight : {dict, 'balanced'}, optional
Set the parameter C of class i to class_weight[i]*C for
SVC. If not given, all classes are supposed to have
weight one.
The "balanced" mode uses the values of y to automatically adjust
weights inversely proportional to class frequencies in the input data
as ``n_samples / (n_classes * np.bincount(y))``
verbose : int, (default=0)
Enable verbose output. Note that this setting takes advantage of a
per-process runtime setting in liblinear that, if enabled, may not work
properly in a multithreaded context.
random_state : int seed, RandomState instance, or None (default=None)
The seed of the pseudo random number generator to use when
shuffling the data.
max_iter : int, (default=1000)
The maximum number of iterations to be run.
Attributes
----------
coef_ : array, shape = [n_features] if n_classes == 2
else [n_classes, n_features]
Weights assigned to the features (coefficients in the primal
problem). This is only available in the case of a linear kernel.
`coef_` is a readonly property derived from `raw_coef_` that
follows the internal memory layout of liblinear.
intercept_ : array, shape = [1] if n_classes == 2 else [n_classes]
Constants in decision function.
Notes
-----
The underlying C implementation uses a random number generator to
select features when fitting the model. It is thus not uncommon
to have slightly different results for the same input data. If
that happens, try with a smaller ``tol`` parameter.
The underlying implementation (liblinear) uses a sparse internal
representation for the data that will incur a memory copy.
Predict output may not match that of standalone liblinear in certain
cases. See :ref:`differences from liblinear <liblinear_differences>`
in the narrative documentation.
**References:**
`LIBLINEAR: A Library for Large Linear Classification
<http://www.csie.ntu.edu.tw/~cjlin/liblinear/>`__
See also
--------
SVC
Implementation of Support Vector Machine classifier using libsvm:
the kernel can be non-linear but its SMO algorithm does not
scale to large number of samples as LinearSVC does.
Furthermore SVC multi-class mode is implemented using one
vs one scheme while LinearSVC uses one vs the rest. It is
possible to implement one vs the rest with SVC by using the
:class:`sklearn.multiclass.OneVsRestClassifier` wrapper.
Finally SVC can fit dense data without memory copy if the input
is C-contiguous. Sparse data will still incur memory copy though.
sklearn.linear_model.SGDClassifier
SGDClassifier can optimize the same cost function as LinearSVC
by adjusting the penalty and loss parameters. In addition it requires
less memory, allows incremental (online) learning, and implements
various loss functions and regularization regimes.
"""
def __init__(self, penalty='l2', loss='squared_hinge', dual=True, tol=1e-4,
C=1.0, multi_class='ovr', fit_intercept=True,
intercept_scaling=1, class_weight=None, verbose=0,
random_state=None, max_iter=1000):
self.dual = dual
self.tol = tol
self.C = C
self.multi_class = multi_class
self.fit_intercept = fit_intercept
self.intercept_scaling = intercept_scaling
self.class_weight = class_weight
self.verbose = verbose
self.random_state = random_state
self.max_iter = max_iter
self.penalty = penalty
self.loss = loss
def fit(self, X, y):
"""Fit the model according to the given training data.
Parameters
----------
X : {array-like, sparse matrix}, shape = [n_samples, n_features]
Training vector, where n_samples in the number of samples and
n_features is the number of features.
y : array-like, shape = [n_samples]
Target vector relative to X
Returns
-------
self : object
Returns self.
"""
# FIXME Remove l1/l2 support in 1.0 -----------------------------------
loss_l = self.loss.lower()
msg = ("loss='%s' has been deprecated in favor of "
"loss='%s' as of 0.16. Backward compatibility"
" for the loss='%s' will be removed in %s")
# FIXME change loss_l --> self.loss after 0.18
if loss_l in ('l1', 'l2'):
old_loss = self.loss
self.loss = {'l1': 'hinge', 'l2': 'squared_hinge'}.get(loss_l)
warnings.warn(msg % (old_loss, self.loss, old_loss, '1.0'),
DeprecationWarning)
# ---------------------------------------------------------------------
if self.C < 0:
raise ValueError("Penalty term must be positive; got (C=%r)"
% self.C)
X, y = check_X_y(X, y, accept_sparse='csr',
dtype=np.float64, order="C")
self.classes_ = np.unique(y)
self.coef_, self.intercept_, self.n_iter_ = _fit_liblinear(
X, y, self.C, self.fit_intercept, self.intercept_scaling,
self.class_weight, self.penalty, self.dual, self.verbose,
self.max_iter, self.tol, self.random_state, self.multi_class,
self.loss)
if self.multi_class == "crammer_singer" and len(self.classes_) == 2:
self.coef_ = (self.coef_[1] - self.coef_[0]).reshape(1, -1)
if self.fit_intercept:
intercept = self.intercept_[1] - self.intercept_[0]
self.intercept_ = np.array([intercept])
return self
class LinearSVR(LinearModel, RegressorMixin):
"""Linear Support Vector Regression.
Similar to SVR with parameter kernel='linear', but implemented in terms of
liblinear rather than libsvm, so it has more flexibility in the choice of
penalties and loss functions and should scale better to large numbers of
samples.
This class supports both dense and sparse input.
Read more in the :ref:`User Guide <svm_regression>`.
Parameters
----------
C : float, optional (default=1.0)
Penalty parameter C of the error term. The penalty is a squared
l2 penalty. The bigger this parameter, the less regularization is used.
loss : string, 'epsilon_insensitive' or 'squared_epsilon_insensitive'
(default='epsilon_insensitive')
Specifies the loss function. 'l1' is the epsilon-insensitive loss
(standard SVR) while 'l2' is the squared epsilon-insensitive loss.
epsilon : float, optional (default=0.1)
Epsilon parameter in the epsilon-insensitive loss function. Note
that the value of this parameter depends on the scale of the target
variable y. If unsure, set epsilon=0.
dual : bool, (default=True)
Select the algorithm to either solve the dual or primal
optimization problem. Prefer dual=False when n_samples > n_features.
tol : float, optional (default=1e-4)
Tolerance for stopping criteria.
fit_intercept : boolean, optional (default=True)
Whether to calculate the intercept for this model. If set
to false, no intercept will be used in calculations
(i.e. data is expected to be already centered).
intercept_scaling : float, optional (default=1)
When self.fit_intercept is True, instance vector x becomes
[x, self.intercept_scaling],
i.e. a "synthetic" feature with constant value equals to
intercept_scaling is appended to the instance vector.
The intercept becomes intercept_scaling * synthetic feature weight
Note! the synthetic feature weight is subject to l1/l2 regularization
as all other features.
To lessen the effect of regularization on synthetic feature weight
(and therefore on the intercept) intercept_scaling has to be increased.
verbose : int, (default=0)
Enable verbose output. Note that this setting takes advantage of a
per-process runtime setting in liblinear that, if enabled, may not work
properly in a multithreaded context.
random_state : int seed, RandomState instance, or None (default=None)
The seed of the pseudo random number generator to use when
shuffling the data.
max_iter : int, (default=1000)
The maximum number of iterations to be run.
Attributes
----------
coef_ : array, shape = [n_features] if n_classes == 2
else [n_classes, n_features]
Weights assigned to the features (coefficients in the primal
problem). This is only available in the case of a linear kernel.
`coef_` is a readonly property derived from `raw_coef_` that
follows the internal memory layout of liblinear.
intercept_ : array, shape = [1] if n_classes == 2 else [n_classes]
Constants in decision function.
See also
--------
LinearSVC
Implementation of Support Vector Machine classifier using the
same library as this class (liblinear).
SVR
Implementation of Support Vector Machine regression using libsvm:
the kernel can be non-linear but its SMO algorithm does not
scale to large number of samples as LinearSVC does.
sklearn.linear_model.SGDRegressor
SGDRegressor can optimize the same cost function as LinearSVR
by adjusting the penalty and loss parameters. In addition it requires
less memory, allows incremental (online) learning, and implements
various loss functions and regularization regimes.
"""
def __init__(self, epsilon=0.0, tol=1e-4, C=1.0,
loss='epsilon_insensitive', fit_intercept=True,
intercept_scaling=1., dual=True, verbose=0,
random_state=None, max_iter=1000):
self.tol = tol
self.C = C
self.epsilon = epsilon
self.fit_intercept = fit_intercept
self.intercept_scaling = intercept_scaling
self.verbose = verbose
self.random_state = random_state
self.max_iter = max_iter
self.dual = dual
self.loss = loss
def fit(self, X, y):
"""Fit the model according to the given training data.
Parameters
----------
X : {array-like, sparse matrix}, shape = [n_samples, n_features]
Training vector, where n_samples in the number of samples and
n_features is the number of features.
y : array-like, shape = [n_samples]
Target vector relative to X
Returns
-------
self : object
Returns self.
"""
# FIXME Remove l1/l2 support in 1.0 -----------------------------------
loss_l = self.loss.lower()
msg = ("loss='%s' has been deprecated in favor of "
"loss='%s' as of 0.16. Backward compatibility"
" for the loss='%s' will be removed in %s")
# FIXME change loss_l --> self.loss after 0.18
if loss_l in ('l1', 'l2'):
old_loss = self.loss
self.loss = {'l1': 'epsilon_insensitive',
'l2': 'squared_epsilon_insensitive'
}.get(loss_l)
warnings.warn(msg % (old_loss, self.loss, old_loss, '1.0'),
DeprecationWarning)
# ---------------------------------------------------------------------
if self.C < 0:
raise ValueError("Penalty term must be positive; got (C=%r)"
% self.C)
X, y = check_X_y(X, y, accept_sparse='csr',
dtype=np.float64, order="C")
penalty = 'l2' # SVR only accepts l2 penalty
self.coef_, self.intercept_, self.n_iter_ = _fit_liblinear(
X, y, self.C, self.fit_intercept, self.intercept_scaling,
None, penalty, self.dual, self.verbose,
self.max_iter, self.tol, self.random_state, loss=self.loss,
epsilon=self.epsilon)
self.coef_ = self.coef_.ravel()
return self
class SVC(BaseSVC):
"""C-Support Vector Classification.
The implementation is based on libsvm. The fit time complexity
is more than quadratic with the number of samples which makes it hard
to scale to dataset with more than a couple of 10000 samples.
The multiclass support is handled according to a one-vs-one scheme.
For details on the precise mathematical formulation of the provided
kernel functions and how `gamma`, `coef0` and `degree` affect each
other, see the corresponding section in the narrative documentation:
:ref:`svm_kernels`.
Read more in the :ref:`User Guide <svm_classification>`.
Parameters
----------
C : float, optional (default=1.0)
Penalty parameter C of the error term.
kernel : string, optional (default='rbf')
Specifies the kernel type to be used in the algorithm.
It must be one of 'linear', 'poly', 'rbf', 'sigmoid', 'precomputed' or
a callable.
If none is given, 'rbf' will be used. If a callable is given it is
used to pre-compute the kernel matrix from data matrices; that matrix
should be an array of shape ``(n_samples, n_samples)``.
degree : int, optional (default=3)
Degree of the polynomial kernel function ('poly').
Ignored by all other kernels.
gamma : float, optional (default='auto')
Kernel coefficient for 'rbf', 'poly' and 'sigmoid'.
If gamma is 'auto' then 1/n_features will be used instead.
coef0 : float, optional (default=0.0)
Independent term in kernel function.
It is only significant in 'poly' and 'sigmoid'.
probability : boolean, optional (default=False)
Whether to enable probability estimates. This must be enabled prior
to calling `fit`, and will slow down that method.
shrinking : boolean, optional (default=True)
Whether to use the shrinking heuristic.
tol : float, optional (default=1e-3)
Tolerance for stopping criterion.
cache_size : float, optional
Specify the size of the kernel cache (in MB).
class_weight : {dict, 'balanced'}, optional
Set the parameter C of class i to class_weight[i]*C for
SVC. If not given, all classes are supposed to have
weight one.
The "balanced" mode uses the values of y to automatically adjust
weights inversely proportional to class frequencies in the input data
as ``n_samples / (n_classes * np.bincount(y))``
verbose : bool, default: False
Enable verbose output. Note that this setting takes advantage of a
per-process runtime setting in libsvm that, if enabled, may not work
properly in a multithreaded context.
max_iter : int, optional (default=-1)
Hard limit on iterations within solver, or -1 for no limit.
decision_function_shape : 'ovo', 'ovr' or None, default=None
Whether to return a one-vs-rest ('ovr') ecision function of shape
(n_samples, n_classes) as all other classifiers, or the original
one-vs-one ('ovo') decision function of libsvm which has shape
(n_samples, n_classes * (n_classes - 1) / 2).
The default of None will currently behave as 'ovo' for backward
compatibility and raise a deprecation warning, but will change 'ovr'
in 0.18.
random_state : int seed, RandomState instance, or None (default)
The seed of the pseudo random number generator to use when
shuffling the data for probability estimation.
Attributes
----------
support_ : array-like, shape = [n_SV]
Indices of support vectors.
support_vectors_ : array-like, shape = [n_SV, n_features]
Support vectors.
n_support_ : array-like, dtype=int32, shape = [n_class]
Number of support vectors for each class.
dual_coef_ : array, shape = [n_class-1, n_SV]
Coefficients of the support vector in the decision function.
For multiclass, coefficient for all 1-vs-1 classifiers.
The layout of the coefficients in the multiclass case is somewhat
non-trivial. See the section about multi-class classification in the
SVM section of the User Guide for details.
coef_ : array, shape = [n_class-1, n_features]
Weights assigned to the features (coefficients in the primal
problem). This is only available in the case of a linear kernel.
`coef_` is a readonly property derived from `dual_coef_` and
`support_vectors_`.
intercept_ : array, shape = [n_class * (n_class-1) / 2]
Constants in decision function.
Examples
--------
>>> import numpy as np
>>> X = np.array([[-1, -1], [-2, -1], [1, 1], [2, 1]])
>>> y = np.array([1, 1, 2, 2])
>>> from sklearn.svm import SVC
>>> clf = SVC()
>>> clf.fit(X, y) #doctest: +NORMALIZE_WHITESPACE
SVC(C=1.0, cache_size=200, class_weight=None, coef0=0.0,
decision_function_shape=None, degree=3, gamma='auto', kernel='rbf',
max_iter=-1, probability=False, random_state=None, shrinking=True,
tol=0.001, verbose=False)
>>> print(clf.predict([[-0.8, -1]]))
[1]
See also
--------
SVR
Support Vector Machine for Regression implemented using libsvm.
LinearSVC
Scalable Linear Support Vector Machine for classification
implemented using liblinear. Check the See also section of
LinearSVC for more comparison element.
"""
def __init__(self, C=1.0, kernel='rbf', degree=3, gamma='auto',
coef0=0.0, shrinking=True, probability=False,
tol=1e-3, cache_size=200, class_weight=None,
verbose=False, max_iter=-1, decision_function_shape=None,
random_state=None):
super(SVC, self).__init__(
impl='c_svc', kernel=kernel, degree=degree, gamma=gamma,
coef0=coef0, tol=tol, C=C, nu=0., shrinking=shrinking,
probability=probability, cache_size=cache_size,
class_weight=class_weight, verbose=verbose, max_iter=max_iter,
decision_function_shape=decision_function_shape,
random_state=random_state)
class NuSVC(BaseSVC):
"""Nu-Support Vector Classification.
Similar to SVC but uses a parameter to control the number of support
vectors.
The implementation is based on libsvm.
Read more in the :ref:`User Guide <svm_classification>`.
Parameters
----------
nu : float, optional (default=0.5)
An upper bound on the fraction of training errors and a lower
bound of the fraction of support vectors. Should be in the
interval (0, 1].
kernel : string, optional (default='rbf')
Specifies the kernel type to be used in the algorithm.
It must be one of 'linear', 'poly', 'rbf', 'sigmoid', 'precomputed' or
a callable.
If none is given, 'rbf' will be used. If a callable is given it is
used to precompute the kernel matrix.
degree : int, optional (default=3)
Degree of the polynomial kernel function ('poly').
Ignored by all other kernels.
gamma : float, optional (default='auto')
Kernel coefficient for 'rbf', 'poly' and 'sigmoid'.
If gamma is 'auto' then 1/n_features will be used instead.
coef0 : float, optional (default=0.0)
Independent term in kernel function.
It is only significant in 'poly' and 'sigmoid'.
probability : boolean, optional (default=False)
Whether to enable probability estimates. This must be enabled prior
to calling `fit`, and will slow down that method.
shrinking : boolean, optional (default=True)
Whether to use the shrinking heuristic.
tol : float, optional (default=1e-3)
Tolerance for stopping criterion.
cache_size : float, optional
Specify the size of the kernel cache (in MB).
class_weight : {dict, 'auto'}, optional
Set the parameter C of class i to class_weight[i]*C for
SVC. If not given, all classes are supposed to have
weight one. The 'auto' mode uses the values of y to
automatically adjust weights inversely proportional to
class frequencies.
verbose : bool, default: False
Enable verbose output. Note that this setting takes advantage of a
per-process runtime setting in libsvm that, if enabled, may not work
properly in a multithreaded context.
max_iter : int, optional (default=-1)
Hard limit on iterations within solver, or -1 for no limit.
decision_function_shape : 'ovo', 'ovr' or None, default=None
Whether to return a one-vs-rest ('ovr') ecision function of shape
(n_samples, n_classes) as all other classifiers, or the original
one-vs-one ('ovo') decision function of libsvm which has shape
(n_samples, n_classes * (n_classes - 1) / 2).
The default of None will currently behave as 'ovo' for backward
compatibility and raise a deprecation warning, but will change 'ovr'
in 0.18.
random_state : int seed, RandomState instance, or None (default)
The seed of the pseudo random number generator to use when
shuffling the data for probability estimation.
Attributes
----------
support_ : array-like, shape = [n_SV]
Indices of support vectors.
support_vectors_ : array-like, shape = [n_SV, n_features]
Support vectors.
n_support_ : array-like, dtype=int32, shape = [n_class]
Number of support vectors for each class.
dual_coef_ : array, shape = [n_class-1, n_SV]
Coefficients of the support vector in the decision function.
For multiclass, coefficient for all 1-vs-1 classifiers.
The layout of the coefficients in the multiclass case is somewhat
non-trivial. See the section about multi-class classification in
the SVM section of the User Guide for details.
coef_ : array, shape = [n_class-1, n_features]
Weights assigned to the features (coefficients in the primal
problem). This is only available in the case of a linear kernel.
`coef_` is readonly property derived from `dual_coef_` and
`support_vectors_`.
intercept_ : array, shape = [n_class * (n_class-1) / 2]
Constants in decision function.
Examples
--------
>>> import numpy as np
>>> X = np.array([[-1, -1], [-2, -1], [1, 1], [2, 1]])
>>> y = np.array([1, 1, 2, 2])
>>> from sklearn.svm import NuSVC
>>> clf = NuSVC()
>>> clf.fit(X, y) #doctest: +NORMALIZE_WHITESPACE
NuSVC(cache_size=200, class_weight=None, coef0=0.0,
decision_function_shape=None, degree=3, gamma='auto', kernel='rbf',
max_iter=-1, nu=0.5, probability=False, random_state=None,
shrinking=True, tol=0.001, verbose=False)
>>> print(clf.predict([[-0.8, -1]]))
[1]
See also
--------
SVC
Support Vector Machine for classification using libsvm.
LinearSVC
Scalable linear Support Vector Machine for classification using
liblinear.
"""
def __init__(self, nu=0.5, kernel='rbf', degree=3, gamma='auto',
coef0=0.0, shrinking=True, probability=False,
tol=1e-3, cache_size=200, class_weight=None, verbose=False,
max_iter=-1, decision_function_shape=None, random_state=None):
super(NuSVC, self).__init__(
impl='nu_svc', kernel=kernel, degree=degree, gamma=gamma,
coef0=coef0, tol=tol, C=0., nu=nu, shrinking=shrinking,
probability=probability, cache_size=cache_size,
class_weight=class_weight, verbose=verbose, max_iter=max_iter,
decision_function_shape=decision_function_shape,
random_state=random_state)
class SVR(BaseLibSVM, RegressorMixin):
"""Epsilon-Support Vector Regression.
The free parameters in the model are C and epsilon.
The implementation is based on libsvm.
Read more in the :ref:`User Guide <svm_regression>`.
Parameters
----------
C : float, optional (default=1.0)
Penalty parameter C of the error term.
epsilon : float, optional (default=0.1)
Epsilon in the epsilon-SVR model. It specifies the epsilon-tube
within which no penalty is associated in the training loss function
with points predicted within a distance epsilon from the actual
value.
kernel : string, optional (default='rbf')
Specifies the kernel type to be used in the algorithm.
It must be one of 'linear', 'poly', 'rbf', 'sigmoid', 'precomputed' or
a callable.
If none is given, 'rbf' will be used. If a callable is given it is
used to precompute the kernel matrix.
degree : int, optional (default=3)
Degree of the polynomial kernel function ('poly').
Ignored by all other kernels.
gamma : float, optional (default='auto')
Kernel coefficient for 'rbf', 'poly' and 'sigmoid'.
If gamma is 'auto' then 1/n_features will be used instead.
coef0 : float, optional (default=0.0)
Independent term in kernel function.
It is only significant in 'poly' and 'sigmoid'.
shrinking : boolean, optional (default=True)
Whether to use the shrinking heuristic.
tol : float, optional (default=1e-3)
Tolerance for stopping criterion.
cache_size : float, optional
Specify the size of the kernel cache (in MB).
verbose : bool, default: False
Enable verbose output. Note that this setting takes advantage of a
per-process runtime setting in libsvm that, if enabled, may not work
properly in a multithreaded context.
max_iter : int, optional (default=-1)
Hard limit on iterations within solver, or -1 for no limit.
Attributes
----------
support_ : array-like, shape = [n_SV]
Indices of support vectors.
support_vectors_ : array-like, shape = [nSV, n_features]
Support vectors.
dual_coef_ : array, shape = [1, n_SV]
Coefficients of the support vector in the decision function.
coef_ : array, shape = [1, n_features]
Weights assigned to the features (coefficients in the primal
problem). This is only available in the case of a linear kernel.
`coef_` is readonly property derived from `dual_coef_` and
`support_vectors_`.
intercept_ : array, shape = [1]
Constants in decision function.
Examples
--------
>>> from sklearn.svm import SVR
>>> import numpy as np
>>> n_samples, n_features = 10, 5
>>> np.random.seed(0)
>>> y = np.random.randn(n_samples)
>>> X = np.random.randn(n_samples, n_features)
>>> clf = SVR(C=1.0, epsilon=0.2)
>>> clf.fit(X, y) #doctest: +NORMALIZE_WHITESPACE
SVR(C=1.0, cache_size=200, coef0=0.0, degree=3, epsilon=0.2, gamma='auto',
kernel='rbf', max_iter=-1, shrinking=True, tol=0.001, verbose=False)
See also
--------
NuSVR
Support Vector Machine for regression implemented using libsvm
using a parameter to control the number of support vectors.
LinearSVR
Scalable Linear Support Vector Machine for regression
implemented using liblinear.
"""
def __init__(self, kernel='rbf', degree=3, gamma='auto', coef0=0.0,
tol=1e-3, C=1.0, epsilon=0.1, shrinking=True,
cache_size=200, verbose=False, max_iter=-1):
super(SVR, self).__init__(
'epsilon_svr', kernel=kernel, degree=degree, gamma=gamma,
coef0=coef0, tol=tol, C=C, nu=0., epsilon=epsilon, verbose=verbose,
shrinking=shrinking, probability=False, cache_size=cache_size,
class_weight=None, max_iter=max_iter, random_state=None)
class NuSVR(BaseLibSVM, RegressorMixin):
"""Nu Support Vector Regression.
Similar to NuSVC, for regression, uses a parameter nu to control
the number of support vectors. However, unlike NuSVC, where nu
replaces C, here nu replaces the parameter epsilon of epsilon-SVR.
The implementation is based on libsvm.
Read more in the :ref:`User Guide <svm_regression>`.
Parameters
----------
C : float, optional (default=1.0)
Penalty parameter C of the error term.
nu : float, optional
An upper bound on the fraction of training errors and a lower bound of
the fraction of support vectors. Should be in the interval (0, 1]. By
default 0.5 will be taken.
kernel : string, optional (default='rbf')
Specifies the kernel type to be used in the algorithm.
It must be one of 'linear', 'poly', 'rbf', 'sigmoid', 'precomputed' or
a callable.
If none is given, 'rbf' will be used. If a callable is given it is
used to precompute the kernel matrix.
degree : int, optional (default=3)
Degree of the polynomial kernel function ('poly').
Ignored by all other kernels.
gamma : float, optional (default='auto')
Kernel coefficient for 'rbf', 'poly' and 'sigmoid'.
If gamma is 'auto' then 1/n_features will be used instead.
coef0 : float, optional (default=0.0)
Independent term in kernel function.
It is only significant in 'poly' and 'sigmoid'.
shrinking : boolean, optional (default=True)
Whether to use the shrinking heuristic.
tol : float, optional (default=1e-3)
Tolerance for stopping criterion.
cache_size : float, optional
Specify the size of the kernel cache (in MB).
verbose : bool, default: False
Enable verbose output. Note that this setting takes advantage of a
per-process runtime setting in libsvm that, if enabled, may not work
properly in a multithreaded context.
max_iter : int, optional (default=-1)
Hard limit on iterations within solver, or -1 for no limit.
Attributes
----------
support_ : array-like, shape = [n_SV]
Indices of support vectors.
support_vectors_ : array-like, shape = [nSV, n_features]
Support vectors.
dual_coef_ : array, shape = [1, n_SV]
Coefficients of the support vector in the decision function.
coef_ : array, shape = [1, n_features]
Weights assigned to the features (coefficients in the primal
problem). This is only available in the case of a linear kernel.
`coef_` is readonly property derived from `dual_coef_` and
`support_vectors_`.
intercept_ : array, shape = [1]
Constants in decision function.
Examples
--------
>>> from sklearn.svm import NuSVR
>>> import numpy as np
>>> n_samples, n_features = 10, 5
>>> np.random.seed(0)
>>> y = np.random.randn(n_samples)
>>> X = np.random.randn(n_samples, n_features)
>>> clf = NuSVR(C=1.0, nu=0.1)
>>> clf.fit(X, y) #doctest: +NORMALIZE_WHITESPACE
NuSVR(C=1.0, cache_size=200, coef0=0.0, degree=3, gamma='auto',
kernel='rbf', max_iter=-1, nu=0.1, shrinking=True, tol=0.001,
verbose=False)
See also
--------
NuSVC
Support Vector Machine for classification implemented with libsvm
with a parameter to control the number of support vectors.
SVR
epsilon Support Vector Machine for regression implemented with libsvm.
"""
def __init__(self, nu=0.5, C=1.0, kernel='rbf', degree=3,
gamma='auto', coef0=0.0, shrinking=True, tol=1e-3,
cache_size=200, verbose=False, max_iter=-1):
super(NuSVR, self).__init__(
'nu_svr', kernel=kernel, degree=degree, gamma=gamma, coef0=coef0,
tol=tol, C=C, nu=nu, epsilon=0., shrinking=shrinking,
probability=False, cache_size=cache_size, class_weight=None,
verbose=verbose, max_iter=max_iter, random_state=None)
class OneClassSVM(BaseLibSVM):
"""Unsupervised Outlier Detection.
Estimate the support of a high-dimensional distribution.
The implementation is based on libsvm.
Read more in the :ref:`User Guide <svm_outlier_detection>`.
Parameters
----------
kernel : string, optional (default='rbf')
Specifies the kernel type to be used in the algorithm.
It must be one of 'linear', 'poly', 'rbf', 'sigmoid', 'precomputed' or
a callable.
If none is given, 'rbf' will be used. If a callable is given it is
used to precompute the kernel matrix.
nu : float, optional
An upper bound on the fraction of training
errors and a lower bound of the fraction of support
vectors. Should be in the interval (0, 1]. By default 0.5
will be taken.
degree : int, optional (default=3)
Degree of the polynomial kernel function ('poly').
Ignored by all other kernels.
gamma : float, optional (default='auto')
Kernel coefficient for 'rbf', 'poly' and 'sigmoid'.
If gamma is 'auto' then 1/n_features will be used instead.
coef0 : float, optional (default=0.0)
Independent term in kernel function.
It is only significant in 'poly' and 'sigmoid'.
tol : float, optional
Tolerance for stopping criterion.
shrinking : boolean, optional
Whether to use the shrinking heuristic.
cache_size : float, optional
Specify the size of the kernel cache (in MB).
verbose : bool, default: False
Enable verbose output. Note that this setting takes advantage of a
per-process runtime setting in libsvm that, if enabled, may not work
properly in a multithreaded context.
max_iter : int, optional (default=-1)
Hard limit on iterations within solver, or -1 for no limit.
random_state : int seed, RandomState instance, or None (default)
The seed of the pseudo random number generator to use when
shuffling the data for probability estimation.
Attributes
----------
support_ : array-like, shape = [n_SV]
Indices of support vectors.
support_vectors_ : array-like, shape = [nSV, n_features]
Support vectors.
dual_coef_ : array, shape = [n_classes-1, n_SV]
Coefficients of the support vectors in the decision function.
coef_ : array, shape = [n_classes-1, n_features]
Weights assigned to the features (coefficients in the primal
problem). This is only available in the case of a linear kernel.
`coef_` is readonly property derived from `dual_coef_` and
`support_vectors_`
intercept_ : array, shape = [n_classes-1]
Constants in decision function.
"""
def __init__(self, kernel='rbf', degree=3, gamma='auto', coef0=0.0,
tol=1e-3, nu=0.5, shrinking=True, cache_size=200,
verbose=False, max_iter=-1, random_state=None):
super(OneClassSVM, self).__init__(
'one_class', kernel, degree, gamma, coef0, tol, 0., nu, 0.,
shrinking, False, cache_size, None, verbose, max_iter,
random_state)
def fit(self, X, y=None, sample_weight=None, **params):
"""
Detects the soft boundary of the set of samples X.
Parameters
----------
X : {array-like, sparse matrix}, shape (n_samples, n_features)
Set of samples, where n_samples is the number of samples and
n_features is the number of features.
sample_weight : array-like, shape (n_samples,)
Per-sample weights. Rescale C per sample. Higher weights
force the classifier to put more emphasis on these points.
Returns
-------
self : object
Returns self.
Notes
-----
If X is not a C-ordered contiguous array it is copied.
"""
super(OneClassSVM, self).fit(X, np.ones(_num_samples(X)), sample_weight=sample_weight,
**params)
return self
def decision_function(self, X):
"""Distance of the samples X to the separating hyperplane.
Parameters
----------
X : array-like, shape (n_samples, n_features)
Returns
-------
X : array-like, shape (n_samples,)
Returns the decision function of the samples.
"""
dec = self._decision_function(X)
return dec
| bsd-3-clause |
alonsebastian/SocialID | urls.py | 1 | 1921 | from django.conf.urls.defaults import patterns, include, url
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
(r'^admin/', include(admin.site.urls)),
(r'^accounts/login/$', 'accounts.views.customLogin'),
(r'^accounts/logout/$', 'django.contrib.auth.views.logout'),
(r'^accounts/register/$', 'accounts.views.register'),
(r'^accounts/confirmation/(?P<activation_key>\S*)/$', 'accounts.views.confirm'),
(r'accounts/changepass/$', 'accounts.views.changePassword'),
(r'^search/$', 'search.views.search'),
(r'^site/modify/$', 'personal_page.views.manage'),
(r'^$', 'static_ish.views.home'),
(r'^who-are-we/$', 'static_ish.views.about'),
(r'^how-it-works/$', 'static_ish.views.how'),
(r'^facebook/login/$', 'facebook.views.login'),
(r'^facebook/authentication_callback/$', 'facebook.views.authentication_callback'),
(r'^accounts/password/reset/$', 'django.contrib.auth.views.password_reset',
{'post_reset_redirect' : '/accounts/password/reset/done/'}),
(r'^accounts/password/reset/done/$', 'django.contrib.auth.views.password_reset_done'),
(r'^accounts/password/reset/(?P<uidb36>[0-9A-Za-z]+)-(?P<token>.+)/$', 'django.contrib.auth.views.password_reset_confirm',
{'post_reset_redirect' : '/accounts/password/done/'}),
(r'^accounts/password/done/$', 'django.contrib.auth.views.password_reset_complete'),
#SHOULD BE THE VERY LAST
(r'^(?P<id_>\S*)/$', 'personal_page.views.personal'),
# Examples:
# url(r'^$', 'demo.views.home', name='home'),
# url(r'^demo/', include('demo.foo.urls')),
# Uncomment the admin/doc line below to enable admin documentation:
# url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
# Uncomment the next line to enable the admin:
# url(r'^admin/', include(admin.site.urls)),
)
| gpl-2.0 |
copelco/Durham-Open-Data-Catalog | fabfile.py | 1 | 9452 | import ConfigParser
import os
import re
import yaml
from argyle import rabbitmq, postgres, nginx, system
from argyle.base import upload_template
from argyle.postgres import create_db_user, create_db
from argyle.supervisor import supervisor_command, upload_supervisor_app_conf
from argyle.system import service_command, start_service, stop_service, restart_service
from fabric.api import cd, env, get, hide, local, put, require, run, settings, sudo, task
from fabric.contrib import files, console, project
# Directory structure
PROJECT_ROOT = os.path.dirname(__file__)
CONF_ROOT = os.path.join(PROJECT_ROOT, 'conf')
SERVER_ROLES = ['app', 'lb', 'db']
env.project = 'OpenDataCatalog'
env.project_user = 'opendata'
env.repo = u'git@github.com:copelco/Durham-Open-Data-Catalog.git'
env.shell = '/bin/bash -c'
env.disable_known_hosts = True
env.port = 22
env.forward_agent = True
# Additional settings for argyle
env.ARGYLE_TEMPLATE_DIRS = (
os.path.join(CONF_ROOT, 'templates')
)
@task
def vagrant():
env.environment = 'production'
env.hosts = ['127.0.0.1']
env.port = 2222
env.branch = 'master'
env.server_name = 'dev.example.com'
setup_path()
@task
def production():
env.environment = 'production'
env.hosts = ['50.17.226.149']
env.branch = 'master'
env.server_name = 'opendatadurham.org'
setup_path()
def setup_path():
env.home = '/home/%(project_user)s/' % env
env.root = os.path.join(env.home, 'www', env.environment)
env.code_root = os.path.join(env.root, env.project)
env.project_root = os.path.join(env.code_root, env.project)
env.virtualenv_root = os.path.join(env.root, 'env')
env.log_dir = os.path.join(env.root, 'log')
env.db = '%s_%s' % (env.project, env.environment)
env.vhost = '%s_%s' % (env.project, env.environment)
env.settings = 'local_settings'
load_secrets()
def load_secrets():
stream = open(os.path.join(PROJECT_ROOT, "secrets.yaml"), 'r')
secrets = yaml.load(stream)
env_secrets = secrets[env.environment]
for key, val in env_secrets.iteritems():
setattr(env, key, val)
@task
def salt_reload():
sudo('salt-call --local state.highstate -l debug')
def know_github():
"""Make sure github.com is in the server's ssh known_hosts file"""
KEYLINE = "|1|t0+3ewjYdZOrDwi/LvvAw/UiGEs=|8TzF6lRm2rdxaXDcByTBWbUIbic= ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEAq2A7hRGmdnm9tUDbO9IDSwBK6TbQa+PXYPCPy6rbTrTtw7PHkccKrpp0yVhp5HdEIcKr6pLlVDBfOLX9QUsyCOV0wzfjIJNlGEYsdlLJizHhbn2mUjvSAHQqZETYP81eFzLQNnPHt4EVVUh7VfDESU84KezmD5QlWpXLmvU31/yMf+Se8xhHTvKSCZIFImWwoG6mbUoWf9nzpIoaSjB+weqqUUmpaaasXVal72J+UX2B+2RPW3RcT0eOzQgqlJL3RKrTJvdsjE3JEAvGq3lGHSZXy28G3skua2SmVi/w4yCE6gbODqnTWlg7+wC604ydGXA8VJiS5ap43JXiUFFAaQ=="
files.append("/etc/ssh/ssh_known_hosts", KEYLINE, use_sudo=True)
@task
def setup_server(*roles):
"""Install packages and add configurations for server given roles."""
require('environment')
roles = list(roles)
if not roles:
abort("setup_server requires one or more server roles, e.g. setup_server:app or setup_server:all")
if roles == ['all', ]:
roles = SERVER_ROLES
if 'base' not in roles:
roles.insert(0, 'base')
if 'app' in roles:
# Create project directories and install Python requirements
project_run('mkdir -p %(root)s' % env)
project_run('mkdir -p %(log_dir)s' % env)
# FIXME: update to SSH as normal user and use sudo
# we ssh as the project_user here to maintain ssh agent
# forwarding, because it doesn't work with sudo. read:
# http://serverfault.com/questions/107187/sudo-su-username-while-keeping-ssh-key-forwarding
with settings(user=env.project_user):
if not files.exists(env.code_root):
run('git clone --quiet %(repo)s %(code_root)s' % env)
with cd(env.code_root):
run('git checkout %(branch)s' % env)
run('git pull')
# Install and create virtualenv
# TODO: pip is installed by salt, should not need to test for it here
# TODO: we should make sure we install virtualenv as well
with settings(hide('everything'), warn_only=True):
test_for_pip = run('which pip')
if not test_for_pip:
sudo("easy_install -U pip")
with settings(hide('everything'), warn_only=True):
test_for_virtualenv = run('which virtualenv')
if not test_for_virtualenv:
sudo("pip install -U virtualenv")
if not files.exists(env.virtualenv_root):
project_run('virtualenv -p python2.7 --quiet --clear --distribute %s' % env.virtualenv_root)
# TODO: Why do we need this next part?
path_file = os.path.join(env.virtualenv_root, 'lib', 'python2.7', 'site-packages', 'project.pth')
files.append(path_file, env.project_root, use_sudo=True)
sudo('chown %s:%s %s' % (env.project_user, env.project_user, path_file))
update_requirements()
upload_local_settings()
syncdb()
upload_supervisor_app_conf(app_name=u'gunicorn')
upload_supervisor_app_conf(app_name=u'group')
# Restart services to pickup changes
supervisor_command('reload')
supervisor_command('stop %(environment)s:*' % env)
supervisor_command('start %(environment)s:*' % env)
if 'lb' in roles:
nginx.remove_default_site()
nginx.upload_nginx_site_conf(site_name=u'%(project)s-%(environment)s.conf' % env)
def project_run(cmd):
""" Uses sudo to allow developer to run commands as project user."""
sudo(cmd, user=env.project_user)
@task
def update_requirements():
"""Update required Python libraries."""
require('environment')
project_run(u'HOME=%(home)s %(virtualenv)s/bin/pip install --quiet --use-mirrors -r %(requirements)s' % {
'virtualenv': env.virtualenv_root,
'requirements': os.path.join(env.code_root, 'requirements', 'base.txt'),
'home': env.home,
})
@task
def manage_run(command):
"""Run a Django management command on the remote server."""
require('environment')
manage_base = u"%(virtualenv_root)s/bin/django-admin.py " % env
if '--settings' not in command:
command = u"%s --settings=%s" % (command, env.settings)
project_run(u'%s %s' % (manage_base, command))
@task
def manage_shell():
"""Drop into the remote Django shell."""
manage_run("shell")
@task
def syncdb():
"""Run syncdb and South migrations."""
manage_run('syncdb --noinput')
manage_run('migrate --noinput')
@task
def collectstatic():
"""Collect static files."""
manage_run('collectstatic --noinput')
def match_changes(changes, match):
pattern = re.compile(match)
return pattern.search(changes) is not None
@task
def deploy(branch=None):
"""Deploy to a given environment."""
require('environment')
if branch is not None:
env.branch = branch
requirements = False
migrations = False
# Fetch latest changes
with cd(env.code_root):
with settings(user=env.project_user):
run('git fetch origin')
# Look for new requirements or migrations
changes = run("git diff origin/%(branch)s --stat-name-width=9999" % env)
requirements = match_changes(changes, r"requirements/")
migrations = match_changes(changes, r"/migrations/")
if requirements or migrations:
supervisor_command('stop %(environment)s:*' % env)
with settings(user=env.project_user):
run("git reset --hard origin/%(branch)s" % env)
upload_local_settings()
if requirements:
update_requirements()
# New requirements might need new tables/migrations
syncdb()
elif migrations:
syncdb()
collectstatic()
supervisor_command('restart %(environment)s:*' % env)
@task
def upload_local_settings():
"""Upload local_settings.py template to server."""
require('environment')
dest = os.path.join(env.project_root, 'local_settings.py')
upload_template('django/local_settings.py', dest, use_sudo=True)
with settings(warn_only=True):
sudo('chown %s:%s %s' % (env.project_user, env.project_user, dest))
@task
def get_db_dump(clean=True):
"""Get db dump of remote enviroment."""
require('environment')
dump_file = '%(environment)s.sql' % env
temp_file = os.path.join(env.home, dump_file)
flags = '-Ox'
if clean:
flags += 'c'
sudo('pg_dump %s %s > %s' % (flags, env.db, temp_file), user=env.project_user)
get(temp_file, dump_file)
@task
def load_db_dump(dump_file):
"""Load db dump on a remote environment."""
require('environment')
temp_file = os.path.join(env.home, '%(environment)s.sql' % env)
put(dump_file, temp_file, use_sudo=True)
sudo('psql -d %s -f %s' % (env.db, temp_file), user=env.project_user)
@task
def salt_bootstrap():
salt_base = os.path.join(PROJECT_ROOT, "salt/")
minion_file = os.path.join(salt_base, "minion")
put(minion_file, "/etc/salt/minion", use_sudo=True)
salt_root = os.path.join(salt_base, 'roots/')
project.rsync_project(local_dir=salt_root, remote_dir="/tmp/salt",
delete=True)
sudo('rm -rf /srv/*')
sudo('mv /tmp/salt/* /srv/')
sudo('chown root:root -R /srv/')
sudo('salt-call --local state.highstate -l debug')
| mit |
Endika/server-tools | auth_from_http_remote_user/__openerp__.py | 23 | 1396 | # -*- coding: utf-8 -*-
##############################################################################
#
# Author: Laurent Mignon
# Copyright 2014 'ACSONE SA/NV'
#
# 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': 'Authenticate via HTTP Remote User',
'version': '8.0.1.0.0',
'category': 'Tools',
'author': "Acsone SA/NV,Odoo Community Association (OCA)",
'maintainer': 'ACSONE SA/NV',
'website': 'http://www.acsone.eu',
'depends': ['base', 'web', 'base_setup'],
"license": "AGPL-3",
'data': [],
"demo": [],
"test": [],
"active": False,
"installable": True,
"auto_install": False,
"application": False,
}
| agpl-3.0 |
jpcy/bgfx | 3rdparty/spirv-headers/include/spirv/1.0/spirv.py | 54 | 27578 | # Copyright (c) 2014-2018 The Khronos Group Inc.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and/or associated documentation files (the "Materials"),
# to deal in the Materials without restriction, including without limitation
# the rights to use, copy, modify, merge, publish, distribute, sublicense,
# and/or sell copies of the Materials, and to permit persons to whom the
# Materials are furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Materials.
#
# MODIFICATIONS TO THIS FILE MAY MEAN IT NO LONGER ACCURATELY REFLECTS KHRONOS
# STANDARDS. THE UNMODIFIED, NORMATIVE VERSIONS OF KHRONOS SPECIFICATIONS AND
# HEADER INFORMATION ARE LOCATED AT https://www.khronos.org/registry/
#
# THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM,OUT OF OR IN CONNECTION WITH THE MATERIALS OR THE USE OR OTHER DEALINGS
# IN THE MATERIALS.
# This header is automatically generated by the same tool that creates
# the Binary Section of the SPIR-V specification.
# Enumeration tokens for SPIR-V, in various styles:
# C, C++, C++11, JSON, Lua, Python
#
# - C will have tokens with a "Spv" prefix, e.g.: SpvSourceLanguageGLSL
# - C++ will have tokens in the "spv" name space, e.g.: spv::SourceLanguageGLSL
# - C++11 will use enum classes in the spv namespace, e.g.: spv::SourceLanguage::GLSL
# - Lua will use tables, e.g.: spv.SourceLanguage.GLSL
# - Python will use dictionaries, e.g.: spv['SourceLanguage']['GLSL']
#
# Some tokens act like mask values, which can be OR'd together,
# while others are mutually exclusive. The mask-like ones have
# "Mask" in their name, and a parallel enum that has the shift
# amount (1 << x) for each corresponding enumerant.
spv = {
'MagicNumber' : 0x07230203,
'Version' : 0x00010000,
'Revision' : 12,
'OpCodeMask' : 0xffff,
'WordCountShift' : 16,
'SourceLanguage' : {
'Unknown' : 0,
'ESSL' : 1,
'GLSL' : 2,
'OpenCL_C' : 3,
'OpenCL_CPP' : 4,
'HLSL' : 5,
},
'ExecutionModel' : {
'Vertex' : 0,
'TessellationControl' : 1,
'TessellationEvaluation' : 2,
'Geometry' : 3,
'Fragment' : 4,
'GLCompute' : 5,
'Kernel' : 6,
},
'AddressingModel' : {
'Logical' : 0,
'Physical32' : 1,
'Physical64' : 2,
},
'MemoryModel' : {
'Simple' : 0,
'GLSL450' : 1,
'OpenCL' : 2,
},
'ExecutionMode' : {
'Invocations' : 0,
'SpacingEqual' : 1,
'SpacingFractionalEven' : 2,
'SpacingFractionalOdd' : 3,
'VertexOrderCw' : 4,
'VertexOrderCcw' : 5,
'PixelCenterInteger' : 6,
'OriginUpperLeft' : 7,
'OriginLowerLeft' : 8,
'EarlyFragmentTests' : 9,
'PointMode' : 10,
'Xfb' : 11,
'DepthReplacing' : 12,
'DepthGreater' : 14,
'DepthLess' : 15,
'DepthUnchanged' : 16,
'LocalSize' : 17,
'LocalSizeHint' : 18,
'InputPoints' : 19,
'InputLines' : 20,
'InputLinesAdjacency' : 21,
'Triangles' : 22,
'InputTrianglesAdjacency' : 23,
'Quads' : 24,
'Isolines' : 25,
'OutputVertices' : 26,
'OutputPoints' : 27,
'OutputLineStrip' : 28,
'OutputTriangleStrip' : 29,
'VecTypeHint' : 30,
'ContractionOff' : 31,
'PostDepthCoverage' : 4446,
'StencilRefReplacingEXT' : 5027,
},
'StorageClass' : {
'UniformConstant' : 0,
'Input' : 1,
'Uniform' : 2,
'Output' : 3,
'Workgroup' : 4,
'CrossWorkgroup' : 5,
'Private' : 6,
'Function' : 7,
'Generic' : 8,
'PushConstant' : 9,
'AtomicCounter' : 10,
'Image' : 11,
'StorageBuffer' : 12,
},
'Dim' : {
'Dim1D' : 0,
'Dim2D' : 1,
'Dim3D' : 2,
'Cube' : 3,
'Rect' : 4,
'Buffer' : 5,
'SubpassData' : 6,
},
'SamplerAddressingMode' : {
'None' : 0,
'ClampToEdge' : 1,
'Clamp' : 2,
'Repeat' : 3,
'RepeatMirrored' : 4,
},
'SamplerFilterMode' : {
'Nearest' : 0,
'Linear' : 1,
},
'ImageFormat' : {
'Unknown' : 0,
'Rgba32f' : 1,
'Rgba16f' : 2,
'R32f' : 3,
'Rgba8' : 4,
'Rgba8Snorm' : 5,
'Rg32f' : 6,
'Rg16f' : 7,
'R11fG11fB10f' : 8,
'R16f' : 9,
'Rgba16' : 10,
'Rgb10A2' : 11,
'Rg16' : 12,
'Rg8' : 13,
'R16' : 14,
'R8' : 15,
'Rgba16Snorm' : 16,
'Rg16Snorm' : 17,
'Rg8Snorm' : 18,
'R16Snorm' : 19,
'R8Snorm' : 20,
'Rgba32i' : 21,
'Rgba16i' : 22,
'Rgba8i' : 23,
'R32i' : 24,
'Rg32i' : 25,
'Rg16i' : 26,
'Rg8i' : 27,
'R16i' : 28,
'R8i' : 29,
'Rgba32ui' : 30,
'Rgba16ui' : 31,
'Rgba8ui' : 32,
'R32ui' : 33,
'Rgb10a2ui' : 34,
'Rg32ui' : 35,
'Rg16ui' : 36,
'Rg8ui' : 37,
'R16ui' : 38,
'R8ui' : 39,
},
'ImageChannelOrder' : {
'R' : 0,
'A' : 1,
'RG' : 2,
'RA' : 3,
'RGB' : 4,
'RGBA' : 5,
'BGRA' : 6,
'ARGB' : 7,
'Intensity' : 8,
'Luminance' : 9,
'Rx' : 10,
'RGx' : 11,
'RGBx' : 12,
'Depth' : 13,
'DepthStencil' : 14,
'sRGB' : 15,
'sRGBx' : 16,
'sRGBA' : 17,
'sBGRA' : 18,
'ABGR' : 19,
},
'ImageChannelDataType' : {
'SnormInt8' : 0,
'SnormInt16' : 1,
'UnormInt8' : 2,
'UnormInt16' : 3,
'UnormShort565' : 4,
'UnormShort555' : 5,
'UnormInt101010' : 6,
'SignedInt8' : 7,
'SignedInt16' : 8,
'SignedInt32' : 9,
'UnsignedInt8' : 10,
'UnsignedInt16' : 11,
'UnsignedInt32' : 12,
'HalfFloat' : 13,
'Float' : 14,
'UnormInt24' : 15,
'UnormInt101010_2' : 16,
},
'ImageOperandsShift' : {
'Bias' : 0,
'Lod' : 1,
'Grad' : 2,
'ConstOffset' : 3,
'Offset' : 4,
'ConstOffsets' : 5,
'Sample' : 6,
'MinLod' : 7,
},
'ImageOperandsMask' : {
'MaskNone' : 0,
'Bias' : 0x00000001,
'Lod' : 0x00000002,
'Grad' : 0x00000004,
'ConstOffset' : 0x00000008,
'Offset' : 0x00000010,
'ConstOffsets' : 0x00000020,
'Sample' : 0x00000040,
'MinLod' : 0x00000080,
},
'FPFastMathModeShift' : {
'NotNaN' : 0,
'NotInf' : 1,
'NSZ' : 2,
'AllowRecip' : 3,
'Fast' : 4,
},
'FPFastMathModeMask' : {
'MaskNone' : 0,
'NotNaN' : 0x00000001,
'NotInf' : 0x00000002,
'NSZ' : 0x00000004,
'AllowRecip' : 0x00000008,
'Fast' : 0x00000010,
},
'FPRoundingMode' : {
'RTE' : 0,
'RTZ' : 1,
'RTP' : 2,
'RTN' : 3,
},
'LinkageType' : {
'Export' : 0,
'Import' : 1,
},
'AccessQualifier' : {
'ReadOnly' : 0,
'WriteOnly' : 1,
'ReadWrite' : 2,
},
'FunctionParameterAttribute' : {
'Zext' : 0,
'Sext' : 1,
'ByVal' : 2,
'Sret' : 3,
'NoAlias' : 4,
'NoCapture' : 5,
'NoWrite' : 6,
'NoReadWrite' : 7,
},
'Decoration' : {
'RelaxedPrecision' : 0,
'SpecId' : 1,
'Block' : 2,
'BufferBlock' : 3,
'RowMajor' : 4,
'ColMajor' : 5,
'ArrayStride' : 6,
'MatrixStride' : 7,
'GLSLShared' : 8,
'GLSLPacked' : 9,
'CPacked' : 10,
'BuiltIn' : 11,
'NoPerspective' : 13,
'Flat' : 14,
'Patch' : 15,
'Centroid' : 16,
'Sample' : 17,
'Invariant' : 18,
'Restrict' : 19,
'Aliased' : 20,
'Volatile' : 21,
'Constant' : 22,
'Coherent' : 23,
'NonWritable' : 24,
'NonReadable' : 25,
'Uniform' : 26,
'SaturatedConversion' : 28,
'Stream' : 29,
'Location' : 30,
'Component' : 31,
'Index' : 32,
'Binding' : 33,
'DescriptorSet' : 34,
'Offset' : 35,
'XfbBuffer' : 36,
'XfbStride' : 37,
'FuncParamAttr' : 38,
'FPRoundingMode' : 39,
'FPFastMathMode' : 40,
'LinkageAttributes' : 41,
'NoContraction' : 42,
'InputAttachmentIndex' : 43,
'Alignment' : 44,
'ExplicitInterpAMD' : 4999,
'OverrideCoverageNV' : 5248,
'PassthroughNV' : 5250,
'ViewportRelativeNV' : 5252,
'SecondaryViewportRelativeNV' : 5256,
'HlslCounterBufferGOOGLE' : 5634,
'HlslSemanticGOOGLE' : 5635,
},
'BuiltIn' : {
'Position' : 0,
'PointSize' : 1,
'ClipDistance' : 3,
'CullDistance' : 4,
'VertexId' : 5,
'InstanceId' : 6,
'PrimitiveId' : 7,
'InvocationId' : 8,
'Layer' : 9,
'ViewportIndex' : 10,
'TessLevelOuter' : 11,
'TessLevelInner' : 12,
'TessCoord' : 13,
'PatchVertices' : 14,
'FragCoord' : 15,
'PointCoord' : 16,
'FrontFacing' : 17,
'SampleId' : 18,
'SamplePosition' : 19,
'SampleMask' : 20,
'FragDepth' : 22,
'HelperInvocation' : 23,
'NumWorkgroups' : 24,
'WorkgroupSize' : 25,
'WorkgroupId' : 26,
'LocalInvocationId' : 27,
'GlobalInvocationId' : 28,
'LocalInvocationIndex' : 29,
'WorkDim' : 30,
'GlobalSize' : 31,
'EnqueuedWorkgroupSize' : 32,
'GlobalOffset' : 33,
'GlobalLinearId' : 34,
'SubgroupSize' : 36,
'SubgroupMaxSize' : 37,
'NumSubgroups' : 38,
'NumEnqueuedSubgroups' : 39,
'SubgroupId' : 40,
'SubgroupLocalInvocationId' : 41,
'VertexIndex' : 42,
'InstanceIndex' : 43,
'SubgroupEqMaskKHR' : 4416,
'SubgroupGeMaskKHR' : 4417,
'SubgroupGtMaskKHR' : 4418,
'SubgroupLeMaskKHR' : 4419,
'SubgroupLtMaskKHR' : 4420,
'BaseVertex' : 4424,
'BaseInstance' : 4425,
'DrawIndex' : 4426,
'DeviceIndex' : 4438,
'ViewIndex' : 4440,
'BaryCoordNoPerspAMD' : 4992,
'BaryCoordNoPerspCentroidAMD' : 4993,
'BaryCoordNoPerspSampleAMD' : 4994,
'BaryCoordSmoothAMD' : 4995,
'BaryCoordSmoothCentroidAMD' : 4996,
'BaryCoordSmoothSampleAMD' : 4997,
'BaryCoordPullModelAMD' : 4998,
'FragStencilRefEXT' : 5014,
'ViewportMaskNV' : 5253,
'SecondaryPositionNV' : 5257,
'SecondaryViewportMaskNV' : 5258,
'PositionPerViewNV' : 5261,
'ViewportMaskPerViewNV' : 5262,
},
'SelectionControlShift' : {
'Flatten' : 0,
'DontFlatten' : 1,
},
'SelectionControlMask' : {
'MaskNone' : 0,
'Flatten' : 0x00000001,
'DontFlatten' : 0x00000002,
},
'LoopControlShift' : {
'Unroll' : 0,
'DontUnroll' : 1,
},
'LoopControlMask' : {
'MaskNone' : 0,
'Unroll' : 0x00000001,
'DontUnroll' : 0x00000002,
},
'FunctionControlShift' : {
'Inline' : 0,
'DontInline' : 1,
'Pure' : 2,
'Const' : 3,
},
'FunctionControlMask' : {
'MaskNone' : 0,
'Inline' : 0x00000001,
'DontInline' : 0x00000002,
'Pure' : 0x00000004,
'Const' : 0x00000008,
},
'MemorySemanticsShift' : {
'Acquire' : 1,
'Release' : 2,
'AcquireRelease' : 3,
'SequentiallyConsistent' : 4,
'UniformMemory' : 6,
'SubgroupMemory' : 7,
'WorkgroupMemory' : 8,
'CrossWorkgroupMemory' : 9,
'AtomicCounterMemory' : 10,
'ImageMemory' : 11,
},
'MemorySemanticsMask' : {
'MaskNone' : 0,
'Acquire' : 0x00000002,
'Release' : 0x00000004,
'AcquireRelease' : 0x00000008,
'SequentiallyConsistent' : 0x00000010,
'UniformMemory' : 0x00000040,
'SubgroupMemory' : 0x00000080,
'WorkgroupMemory' : 0x00000100,
'CrossWorkgroupMemory' : 0x00000200,
'AtomicCounterMemory' : 0x00000400,
'ImageMemory' : 0x00000800,
},
'MemoryAccessShift' : {
'Volatile' : 0,
'Aligned' : 1,
'Nontemporal' : 2,
},
'MemoryAccessMask' : {
'MaskNone' : 0,
'Volatile' : 0x00000001,
'Aligned' : 0x00000002,
'Nontemporal' : 0x00000004,
},
'Scope' : {
'CrossDevice' : 0,
'Device' : 1,
'Workgroup' : 2,
'Subgroup' : 3,
'Invocation' : 4,
},
'GroupOperation' : {
'Reduce' : 0,
'InclusiveScan' : 1,
'ExclusiveScan' : 2,
},
'KernelEnqueueFlags' : {
'NoWait' : 0,
'WaitKernel' : 1,
'WaitWorkGroup' : 2,
},
'KernelProfilingInfoShift' : {
'CmdExecTime' : 0,
},
'KernelProfilingInfoMask' : {
'MaskNone' : 0,
'CmdExecTime' : 0x00000001,
},
'Capability' : {
'Matrix' : 0,
'Shader' : 1,
'Geometry' : 2,
'Tessellation' : 3,
'Addresses' : 4,
'Linkage' : 5,
'Kernel' : 6,
'Vector16' : 7,
'Float16Buffer' : 8,
'Float16' : 9,
'Float64' : 10,
'Int64' : 11,
'Int64Atomics' : 12,
'ImageBasic' : 13,
'ImageReadWrite' : 14,
'ImageMipmap' : 15,
'Pipes' : 17,
'Groups' : 18,
'DeviceEnqueue' : 19,
'LiteralSampler' : 20,
'AtomicStorage' : 21,
'Int16' : 22,
'TessellationPointSize' : 23,
'GeometryPointSize' : 24,
'ImageGatherExtended' : 25,
'StorageImageMultisample' : 27,
'UniformBufferArrayDynamicIndexing' : 28,
'SampledImageArrayDynamicIndexing' : 29,
'StorageBufferArrayDynamicIndexing' : 30,
'StorageImageArrayDynamicIndexing' : 31,
'ClipDistance' : 32,
'CullDistance' : 33,
'ImageCubeArray' : 34,
'SampleRateShading' : 35,
'ImageRect' : 36,
'SampledRect' : 37,
'GenericPointer' : 38,
'Int8' : 39,
'InputAttachment' : 40,
'SparseResidency' : 41,
'MinLod' : 42,
'Sampled1D' : 43,
'Image1D' : 44,
'SampledCubeArray' : 45,
'SampledBuffer' : 46,
'ImageBuffer' : 47,
'ImageMSArray' : 48,
'StorageImageExtendedFormats' : 49,
'ImageQuery' : 50,
'DerivativeControl' : 51,
'InterpolationFunction' : 52,
'TransformFeedback' : 53,
'GeometryStreams' : 54,
'StorageImageReadWithoutFormat' : 55,
'StorageImageWriteWithoutFormat' : 56,
'MultiViewport' : 57,
'SubgroupBallotKHR' : 4423,
'DrawParameters' : 4427,
'SubgroupVoteKHR' : 4431,
'StorageBuffer16BitAccess' : 4433,
'StorageUniformBufferBlock16' : 4433,
'StorageUniform16' : 4434,
'UniformAndStorageBuffer16BitAccess' : 4434,
'StoragePushConstant16' : 4435,
'StorageInputOutput16' : 4436,
'DeviceGroup' : 4437,
'MultiView' : 4439,
'VariablePointersStorageBuffer' : 4441,
'VariablePointers' : 4442,
'AtomicStorageOps' : 4445,
'SampleMaskPostDepthCoverage' : 4447,
'ImageGatherBiasLodAMD' : 5009,
'FragmentMaskAMD' : 5010,
'StencilExportEXT' : 5013,
'ImageReadWriteLodAMD' : 5015,
'SampleMaskOverrideCoverageNV' : 5249,
'GeometryShaderPassthroughNV' : 5251,
'ShaderViewportIndexLayerEXT' : 5254,
'ShaderViewportIndexLayerNV' : 5254,
'ShaderViewportMaskNV' : 5255,
'ShaderStereoViewNV' : 5259,
'PerViewAttributesNV' : 5260,
'SubgroupShuffleINTEL' : 5568,
'SubgroupBufferBlockIOINTEL' : 5569,
'SubgroupImageBlockIOINTEL' : 5570,
},
'Op' : {
'OpNop' : 0,
'OpUndef' : 1,
'OpSourceContinued' : 2,
'OpSource' : 3,
'OpSourceExtension' : 4,
'OpName' : 5,
'OpMemberName' : 6,
'OpString' : 7,
'OpLine' : 8,
'OpExtension' : 10,
'OpExtInstImport' : 11,
'OpExtInst' : 12,
'OpMemoryModel' : 14,
'OpEntryPoint' : 15,
'OpExecutionMode' : 16,
'OpCapability' : 17,
'OpTypeVoid' : 19,
'OpTypeBool' : 20,
'OpTypeInt' : 21,
'OpTypeFloat' : 22,
'OpTypeVector' : 23,
'OpTypeMatrix' : 24,
'OpTypeImage' : 25,
'OpTypeSampler' : 26,
'OpTypeSampledImage' : 27,
'OpTypeArray' : 28,
'OpTypeRuntimeArray' : 29,
'OpTypeStruct' : 30,
'OpTypeOpaque' : 31,
'OpTypePointer' : 32,
'OpTypeFunction' : 33,
'OpTypeEvent' : 34,
'OpTypeDeviceEvent' : 35,
'OpTypeReserveId' : 36,
'OpTypeQueue' : 37,
'OpTypePipe' : 38,
'OpTypeForwardPointer' : 39,
'OpConstantTrue' : 41,
'OpConstantFalse' : 42,
'OpConstant' : 43,
'OpConstantComposite' : 44,
'OpConstantSampler' : 45,
'OpConstantNull' : 46,
'OpSpecConstantTrue' : 48,
'OpSpecConstantFalse' : 49,
'OpSpecConstant' : 50,
'OpSpecConstantComposite' : 51,
'OpSpecConstantOp' : 52,
'OpFunction' : 54,
'OpFunctionParameter' : 55,
'OpFunctionEnd' : 56,
'OpFunctionCall' : 57,
'OpVariable' : 59,
'OpImageTexelPointer' : 60,
'OpLoad' : 61,
'OpStore' : 62,
'OpCopyMemory' : 63,
'OpCopyMemorySized' : 64,
'OpAccessChain' : 65,
'OpInBoundsAccessChain' : 66,
'OpPtrAccessChain' : 67,
'OpArrayLength' : 68,
'OpGenericPtrMemSemantics' : 69,
'OpInBoundsPtrAccessChain' : 70,
'OpDecorate' : 71,
'OpMemberDecorate' : 72,
'OpDecorationGroup' : 73,
'OpGroupDecorate' : 74,
'OpGroupMemberDecorate' : 75,
'OpVectorExtractDynamic' : 77,
'OpVectorInsertDynamic' : 78,
'OpVectorShuffle' : 79,
'OpCompositeConstruct' : 80,
'OpCompositeExtract' : 81,
'OpCompositeInsert' : 82,
'OpCopyObject' : 83,
'OpTranspose' : 84,
'OpSampledImage' : 86,
'OpImageSampleImplicitLod' : 87,
'OpImageSampleExplicitLod' : 88,
'OpImageSampleDrefImplicitLod' : 89,
'OpImageSampleDrefExplicitLod' : 90,
'OpImageSampleProjImplicitLod' : 91,
'OpImageSampleProjExplicitLod' : 92,
'OpImageSampleProjDrefImplicitLod' : 93,
'OpImageSampleProjDrefExplicitLod' : 94,
'OpImageFetch' : 95,
'OpImageGather' : 96,
'OpImageDrefGather' : 97,
'OpImageRead' : 98,
'OpImageWrite' : 99,
'OpImage' : 100,
'OpImageQueryFormat' : 101,
'OpImageQueryOrder' : 102,
'OpImageQuerySizeLod' : 103,
'OpImageQuerySize' : 104,
'OpImageQueryLod' : 105,
'OpImageQueryLevels' : 106,
'OpImageQuerySamples' : 107,
'OpConvertFToU' : 109,
'OpConvertFToS' : 110,
'OpConvertSToF' : 111,
'OpConvertUToF' : 112,
'OpUConvert' : 113,
'OpSConvert' : 114,
'OpFConvert' : 115,
'OpQuantizeToF16' : 116,
'OpConvertPtrToU' : 117,
'OpSatConvertSToU' : 118,
'OpSatConvertUToS' : 119,
'OpConvertUToPtr' : 120,
'OpPtrCastToGeneric' : 121,
'OpGenericCastToPtr' : 122,
'OpGenericCastToPtrExplicit' : 123,
'OpBitcast' : 124,
'OpSNegate' : 126,
'OpFNegate' : 127,
'OpIAdd' : 128,
'OpFAdd' : 129,
'OpISub' : 130,
'OpFSub' : 131,
'OpIMul' : 132,
'OpFMul' : 133,
'OpUDiv' : 134,
'OpSDiv' : 135,
'OpFDiv' : 136,
'OpUMod' : 137,
'OpSRem' : 138,
'OpSMod' : 139,
'OpFRem' : 140,
'OpFMod' : 141,
'OpVectorTimesScalar' : 142,
'OpMatrixTimesScalar' : 143,
'OpVectorTimesMatrix' : 144,
'OpMatrixTimesVector' : 145,
'OpMatrixTimesMatrix' : 146,
'OpOuterProduct' : 147,
'OpDot' : 148,
'OpIAddCarry' : 149,
'OpISubBorrow' : 150,
'OpUMulExtended' : 151,
'OpSMulExtended' : 152,
'OpAny' : 154,
'OpAll' : 155,
'OpIsNan' : 156,
'OpIsInf' : 157,
'OpIsFinite' : 158,
'OpIsNormal' : 159,
'OpSignBitSet' : 160,
'OpLessOrGreater' : 161,
'OpOrdered' : 162,
'OpUnordered' : 163,
'OpLogicalEqual' : 164,
'OpLogicalNotEqual' : 165,
'OpLogicalOr' : 166,
'OpLogicalAnd' : 167,
'OpLogicalNot' : 168,
'OpSelect' : 169,
'OpIEqual' : 170,
'OpINotEqual' : 171,
'OpUGreaterThan' : 172,
'OpSGreaterThan' : 173,
'OpUGreaterThanEqual' : 174,
'OpSGreaterThanEqual' : 175,
'OpULessThan' : 176,
'OpSLessThan' : 177,
'OpULessThanEqual' : 178,
'OpSLessThanEqual' : 179,
'OpFOrdEqual' : 180,
'OpFUnordEqual' : 181,
'OpFOrdNotEqual' : 182,
'OpFUnordNotEqual' : 183,
'OpFOrdLessThan' : 184,
'OpFUnordLessThan' : 185,
'OpFOrdGreaterThan' : 186,
'OpFUnordGreaterThan' : 187,
'OpFOrdLessThanEqual' : 188,
'OpFUnordLessThanEqual' : 189,
'OpFOrdGreaterThanEqual' : 190,
'OpFUnordGreaterThanEqual' : 191,
'OpShiftRightLogical' : 194,
'OpShiftRightArithmetic' : 195,
'OpShiftLeftLogical' : 196,
'OpBitwiseOr' : 197,
'OpBitwiseXor' : 198,
'OpBitwiseAnd' : 199,
'OpNot' : 200,
'OpBitFieldInsert' : 201,
'OpBitFieldSExtract' : 202,
'OpBitFieldUExtract' : 203,
'OpBitReverse' : 204,
'OpBitCount' : 205,
'OpDPdx' : 207,
'OpDPdy' : 208,
'OpFwidth' : 209,
'OpDPdxFine' : 210,
'OpDPdyFine' : 211,
'OpFwidthFine' : 212,
'OpDPdxCoarse' : 213,
'OpDPdyCoarse' : 214,
'OpFwidthCoarse' : 215,
'OpEmitVertex' : 218,
'OpEndPrimitive' : 219,
'OpEmitStreamVertex' : 220,
'OpEndStreamPrimitive' : 221,
'OpControlBarrier' : 224,
'OpMemoryBarrier' : 225,
'OpAtomicLoad' : 227,
'OpAtomicStore' : 228,
'OpAtomicExchange' : 229,
'OpAtomicCompareExchange' : 230,
'OpAtomicCompareExchangeWeak' : 231,
'OpAtomicIIncrement' : 232,
'OpAtomicIDecrement' : 233,
'OpAtomicIAdd' : 234,
'OpAtomicISub' : 235,
'OpAtomicSMin' : 236,
'OpAtomicUMin' : 237,
'OpAtomicSMax' : 238,
'OpAtomicUMax' : 239,
'OpAtomicAnd' : 240,
'OpAtomicOr' : 241,
'OpAtomicXor' : 242,
'OpPhi' : 245,
'OpLoopMerge' : 246,
'OpSelectionMerge' : 247,
'OpLabel' : 248,
'OpBranch' : 249,
'OpBranchConditional' : 250,
'OpSwitch' : 251,
'OpKill' : 252,
'OpReturn' : 253,
'OpReturnValue' : 254,
'OpUnreachable' : 255,
'OpLifetimeStart' : 256,
'OpLifetimeStop' : 257,
'OpGroupAsyncCopy' : 259,
'OpGroupWaitEvents' : 260,
'OpGroupAll' : 261,
'OpGroupAny' : 262,
'OpGroupBroadcast' : 263,
'OpGroupIAdd' : 264,
'OpGroupFAdd' : 265,
'OpGroupFMin' : 266,
'OpGroupUMin' : 267,
'OpGroupSMin' : 268,
'OpGroupFMax' : 269,
'OpGroupUMax' : 270,
'OpGroupSMax' : 271,
'OpReadPipe' : 274,
'OpWritePipe' : 275,
'OpReservedReadPipe' : 276,
'OpReservedWritePipe' : 277,
'OpReserveReadPipePackets' : 278,
'OpReserveWritePipePackets' : 279,
'OpCommitReadPipe' : 280,
'OpCommitWritePipe' : 281,
'OpIsValidReserveId' : 282,
'OpGetNumPipePackets' : 283,
'OpGetMaxPipePackets' : 284,
'OpGroupReserveReadPipePackets' : 285,
'OpGroupReserveWritePipePackets' : 286,
'OpGroupCommitReadPipe' : 287,
'OpGroupCommitWritePipe' : 288,
'OpEnqueueMarker' : 291,
'OpEnqueueKernel' : 292,
'OpGetKernelNDrangeSubGroupCount' : 293,
'OpGetKernelNDrangeMaxSubGroupSize' : 294,
'OpGetKernelWorkGroupSize' : 295,
'OpGetKernelPreferredWorkGroupSizeMultiple' : 296,
'OpRetainEvent' : 297,
'OpReleaseEvent' : 298,
'OpCreateUserEvent' : 299,
'OpIsValidEvent' : 300,
'OpSetUserEventStatus' : 301,
'OpCaptureEventProfilingInfo' : 302,
'OpGetDefaultQueue' : 303,
'OpBuildNDRange' : 304,
'OpImageSparseSampleImplicitLod' : 305,
'OpImageSparseSampleExplicitLod' : 306,
'OpImageSparseSampleDrefImplicitLod' : 307,
'OpImageSparseSampleDrefExplicitLod' : 308,
'OpImageSparseSampleProjImplicitLod' : 309,
'OpImageSparseSampleProjExplicitLod' : 310,
'OpImageSparseSampleProjDrefImplicitLod' : 311,
'OpImageSparseSampleProjDrefExplicitLod' : 312,
'OpImageSparseFetch' : 313,
'OpImageSparseGather' : 314,
'OpImageSparseDrefGather' : 315,
'OpImageSparseTexelsResident' : 316,
'OpNoLine' : 317,
'OpAtomicFlagTestAndSet' : 318,
'OpAtomicFlagClear' : 319,
'OpImageSparseRead' : 320,
'OpDecorateId' : 332,
'OpSubgroupBallotKHR' : 4421,
'OpSubgroupFirstInvocationKHR' : 4422,
'OpSubgroupAllKHR' : 4428,
'OpSubgroupAnyKHR' : 4429,
'OpSubgroupAllEqualKHR' : 4430,
'OpSubgroupReadInvocationKHR' : 4432,
'OpGroupIAddNonUniformAMD' : 5000,
'OpGroupFAddNonUniformAMD' : 5001,
'OpGroupFMinNonUniformAMD' : 5002,
'OpGroupUMinNonUniformAMD' : 5003,
'OpGroupSMinNonUniformAMD' : 5004,
'OpGroupFMaxNonUniformAMD' : 5005,
'OpGroupUMaxNonUniformAMD' : 5006,
'OpGroupSMaxNonUniformAMD' : 5007,
'OpFragmentMaskFetchAMD' : 5011,
'OpFragmentFetchAMD' : 5012,
'OpSubgroupShuffleINTEL' : 5571,
'OpSubgroupShuffleDownINTEL' : 5572,
'OpSubgroupShuffleUpINTEL' : 5573,
'OpSubgroupShuffleXorINTEL' : 5574,
'OpSubgroupBlockReadINTEL' : 5575,
'OpSubgroupBlockWriteINTEL' : 5576,
'OpSubgroupImageBlockReadINTEL' : 5577,
'OpSubgroupImageBlockWriteINTEL' : 5578,
'OpDecorateStringGOOGLE' : 5632,
'OpMemberDecorateStringGOOGLE' : 5633,
},
}
| bsd-2-clause |
BeATz-UnKNoWN/python-for-android | python-build/python-libs/gdata/src/gdata/urlfetch.py | 276 | 9330 | #!/usr/bin/python
#
# Copyright (C) 2008 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Provides HTTP functions for gdata.service to use on Google App Engine
AppEngineHttpClient: Provides an HTTP request method which uses App Engine's
urlfetch API. Set the http_client member of a GDataService object to an
instance of an AppEngineHttpClient to allow the gdata library to run on
Google App Engine.
run_on_appengine: Function which will modify an existing GDataService object
to allow it to run on App Engine. It works by creating a new instance of
the AppEngineHttpClient and replacing the GDataService object's
http_client.
HttpRequest: Function that wraps google.appengine.api.urlfetch.Fetch in a
common interface which is used by gdata.service.GDataService. In other
words, this module can be used as the gdata service request handler so
that all HTTP requests will be performed by the hosting Google App Engine
server.
"""
__author__ = 'api.jscudder (Jeff Scudder)'
import StringIO
import atom.service
import atom.http_interface
from google.appengine.api import urlfetch
def run_on_appengine(gdata_service):
"""Modifies a GDataService object to allow it to run on App Engine.
Args:
gdata_service: An instance of AtomService, GDataService, or any
of their subclasses which has an http_client member.
"""
gdata_service.http_client = AppEngineHttpClient()
class AppEngineHttpClient(atom.http_interface.GenericHttpClient):
def __init__(self, headers=None):
self.debug = False
self.headers = headers or {}
def request(self, operation, url, data=None, headers=None):
"""Performs an HTTP call to the server, supports GET, POST, PUT, and
DELETE.
Usage example, perform and HTTP GET on http://www.google.com/:
import atom.http
client = atom.http.HttpClient()
http_response = client.request('GET', 'http://www.google.com/')
Args:
operation: str The HTTP operation to be performed. This is usually one
of 'GET', 'POST', 'PUT', or 'DELETE'
data: filestream, list of parts, or other object which can be converted
to a string. Should be set to None when performing a GET or DELETE.
If data is a file-like object which can be read, this method will
read a chunk of 100K bytes at a time and send them.
If the data is a list of parts to be sent, each part will be
evaluated and sent.
url: The full URL to which the request should be sent. Can be a string
or atom.url.Url.
headers: dict of strings. HTTP headers which should be sent
in the request.
"""
all_headers = self.headers.copy()
if headers:
all_headers.update(headers)
# Construct the full payload.
# Assume that data is None or a string.
data_str = data
if data:
if isinstance(data, list):
# If data is a list of different objects, convert them all to strings
# and join them together.
converted_parts = [__ConvertDataPart(x) for x in data]
data_str = ''.join(converted_parts)
else:
data_str = __ConvertDataPart(data)
# If the list of headers does not include a Content-Length, attempt to
# calculate it based on the data object.
if data and 'Content-Length' not in all_headers:
all_headers['Content-Length'] = len(data_str)
# Set the content type to the default value if none was set.
if 'Content-Type' not in all_headers:
all_headers['Content-Type'] = 'application/atom+xml'
# Lookup the urlfetch operation which corresponds to the desired HTTP verb.
if operation == 'GET':
method = urlfetch.GET
elif operation == 'POST':
method = urlfetch.POST
elif operation == 'PUT':
method = urlfetch.PUT
elif operation == 'DELETE':
method = urlfetch.DELETE
else:
method = None
return HttpResponse(urlfetch.Fetch(url=str(url), payload=data_str,
method=method, headers=all_headers))
def HttpRequest(service, operation, data, uri, extra_headers=None,
url_params=None, escape_params=True, content_type='application/atom+xml'):
"""Performs an HTTP call to the server, supports GET, POST, PUT, and DELETE.
This function is deprecated, use AppEngineHttpClient.request instead.
To use this module with gdata.service, you can set this module to be the
http_request_handler so that HTTP requests use Google App Engine's urlfetch.
import gdata.service
import gdata.urlfetch
gdata.service.http_request_handler = gdata.urlfetch
Args:
service: atom.AtomService object which contains some of the parameters
needed to make the request. The following members are used to
construct the HTTP call: server (str), additional_headers (dict),
port (int), and ssl (bool).
operation: str The HTTP operation to be performed. This is usually one of
'GET', 'POST', 'PUT', or 'DELETE'
data: filestream, list of parts, or other object which can be
converted to a string.
Should be set to None when performing a GET or PUT.
If data is a file-like object which can be read, this method will read
a chunk of 100K bytes at a time and send them.
If the data is a list of parts to be sent, each part will be evaluated
and sent.
uri: The beginning of the URL to which the request should be sent.
Examples: '/', '/base/feeds/snippets',
'/m8/feeds/contacts/default/base'
extra_headers: dict of strings. HTTP headers which should be sent
in the request. These headers are in addition to those stored in
service.additional_headers.
url_params: dict of strings. Key value pairs to be added to the URL as
URL parameters. For example {'foo':'bar', 'test':'param'} will
become ?foo=bar&test=param.
escape_params: bool default True. If true, the keys and values in
url_params will be URL escaped when the form is constructed
(Special characters converted to %XX form.)
content_type: str The MIME type for the data being sent. Defaults to
'application/atom+xml', this is only used if data is set.
"""
full_uri = atom.service.BuildUri(uri, url_params, escape_params)
(server, port, ssl, partial_uri) = atom.service.ProcessUrl(service, full_uri)
# Construct the full URL for the request.
if ssl:
full_url = 'https://%s%s' % (server, partial_uri)
else:
full_url = 'http://%s%s' % (server, partial_uri)
# Construct the full payload.
# Assume that data is None or a string.
data_str = data
if data:
if isinstance(data, list):
# If data is a list of different objects, convert them all to strings
# and join them together.
converted_parts = [__ConvertDataPart(x) for x in data]
data_str = ''.join(converted_parts)
else:
data_str = __ConvertDataPart(data)
# Construct the dictionary of HTTP headers.
headers = {}
if isinstance(service.additional_headers, dict):
headers = service.additional_headers.copy()
if isinstance(extra_headers, dict):
for header, value in extra_headers.iteritems():
headers[header] = value
# Add the content type header (we don't need to calculate content length,
# since urlfetch.Fetch will calculate for us).
if content_type:
headers['Content-Type'] = content_type
# Lookup the urlfetch operation which corresponds to the desired HTTP verb.
if operation == 'GET':
method = urlfetch.GET
elif operation == 'POST':
method = urlfetch.POST
elif operation == 'PUT':
method = urlfetch.PUT
elif operation == 'DELETE':
method = urlfetch.DELETE
else:
method = None
return HttpResponse(urlfetch.Fetch(url=full_url, payload=data_str,
method=method, headers=headers))
def __ConvertDataPart(data):
if not data or isinstance(data, str):
return data
elif hasattr(data, 'read'):
# data is a file like object, so read it completely.
return data.read()
# The data object was not a file.
# Try to convert to a string and send the data.
return str(data)
class HttpResponse(object):
"""Translates a urlfetch resoinse to look like an hhtplib resoinse.
Used to allow the resoinse from HttpRequest to be usable by gdata.service
methods.
"""
def __init__(self, urlfetch_response):
self.body = StringIO.StringIO(urlfetch_response.content)
self.headers = urlfetch_response.headers
self.status = urlfetch_response.status_code
self.reason = ''
def read(self, length=None):
if not length:
return self.body.read()
else:
return self.body.read(length)
def getheader(self, name):
if not self.headers.has_key(name):
return self.headers[name.lower()]
return self.headers[name]
| apache-2.0 |
windedge/odoomrp-wip | mrp_production_project_estimated_cost/models/product.py | 19 | 1154 | # -*- encoding: utf-8 -*-
##############################################################################
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see http://www.gnu.org/licenses/.
#
##############################################################################
from openerp import models, fields
import openerp.addons.decimal_precision as dp
class ProductTemplate(models.Model):
_inherit = 'product.template'
manual_standard_cost = fields.Float(
string='Manual Standard Cost', digits=dp.get_precision('Product Price')
)
| agpl-3.0 |
thaim/ansible | lib/ansible/modules/network/fortios/fortios_system_replacemsg_spam.py | 13 | 10063 | #!/usr/bin/python
from __future__ import (absolute_import, division, print_function)
# Copyright 2019 Fortinet, Inc.
#
# 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 <https://www.gnu.org/licenses/>.
__metaclass__ = type
ANSIBLE_METADATA = {'status': ['preview'],
'supported_by': 'community',
'metadata_version': '1.1'}
DOCUMENTATION = '''
---
module: fortios_system_replacemsg_spam
short_description: Replacement messages in Fortinet's FortiOS and FortiGate.
description:
- This module is able to configure a FortiGate or FortiOS (FOS) device by allowing the
user to set and modify system_replacemsg feature and spam category.
Examples include all parameters and values need to be adjusted to datasources before usage.
Tested with FOS v6.0.5
version_added: "2.9"
author:
- Miguel Angel Munoz (@mamunozgonzalez)
- Nicolas Thomas (@thomnico)
notes:
- Requires fortiosapi library developed by Fortinet
- Run as a local_action in your playbook
requirements:
- fortiosapi>=0.9.8
options:
host:
description:
- FortiOS or FortiGate IP address.
type: str
required: false
username:
description:
- FortiOS or FortiGate username.
type: str
required: false
password:
description:
- FortiOS or FortiGate password.
type: str
default: ""
vdom:
description:
- Virtual domain, among those defined previously. A vdom is a
virtual instance of the FortiGate that can be configured and
used as a different unit.
type: str
default: root
https:
description:
- Indicates if the requests towards FortiGate must use HTTPS protocol.
type: bool
default: true
ssl_verify:
description:
- Ensures FortiGate certificate must be verified by a proper CA.
type: bool
default: true
state:
description:
- Indicates whether to create or remove the object.
type: str
required: true
choices:
- present
- absent
system_replacemsg_spam:
description:
- Replacement messages.
default: null
type: dict
suboptions:
buffer:
description:
- Message string.
type: str
format:
description:
- Format flag.
type: str
choices:
- none
- text
- html
- wml
header:
description:
- Header flag.
type: str
choices:
- none
- http
- 8bit
msg_type:
description:
- Message type.
type: str
'''
EXAMPLES = '''
- hosts: localhost
vars:
host: "192.168.122.40"
username: "admin"
password: ""
vdom: "root"
ssl_verify: "False"
tasks:
- name: Replacement messages.
fortios_system_replacemsg_spam:
host: "{{ host }}"
username: "{{ username }}"
password: "{{ password }}"
vdom: "{{ vdom }}"
https: "False"
state: "present"
system_replacemsg_spam:
buffer: "<your_own_value>"
format: "none"
header: "none"
msg_type: "<your_own_value>"
'''
RETURN = '''
build:
description: Build number of the fortigate image
returned: always
type: str
sample: '1547'
http_method:
description: Last method used to provision the content into FortiGate
returned: always
type: str
sample: 'PUT'
http_status:
description: Last result given by FortiGate on last operation applied
returned: always
type: str
sample: "200"
mkey:
description: Master key (id) used in the last call to FortiGate
returned: success
type: str
sample: "id"
name:
description: Name of the table used to fulfill the request
returned: always
type: str
sample: "urlfilter"
path:
description: Path of the table used to fulfill the request
returned: always
type: str
sample: "webfilter"
revision:
description: Internal revision number
returned: always
type: str
sample: "17.0.2.10658"
serial:
description: Serial number of the unit
returned: always
type: str
sample: "FGVMEVYYQT3AB5352"
status:
description: Indication of the operation's result
returned: always
type: str
sample: "success"
vdom:
description: Virtual domain used
returned: always
type: str
sample: "root"
version:
description: Version of the FortiGate
returned: always
type: str
sample: "v5.6.3"
'''
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.connection import Connection
from ansible.module_utils.network.fortios.fortios import FortiOSHandler
from ansible.module_utils.network.fortimanager.common import FAIL_SOCKET_MSG
def login(data, fos):
host = data['host']
username = data['username']
password = data['password']
ssl_verify = data['ssl_verify']
fos.debug('on')
if 'https' in data and not data['https']:
fos.https('off')
else:
fos.https('on')
fos.login(host, username, password, verify=ssl_verify)
def filter_system_replacemsg_spam_data(json):
option_list = ['buffer', 'format', 'header',
'msg_type']
dictionary = {}
for attribute in option_list:
if attribute in json and json[attribute] is not None:
dictionary[attribute] = json[attribute]
return dictionary
def underscore_to_hyphen(data):
if isinstance(data, list):
for elem in data:
elem = underscore_to_hyphen(elem)
elif isinstance(data, dict):
new_data = {}
for k, v in data.items():
new_data[k.replace('_', '-')] = underscore_to_hyphen(v)
data = new_data
return data
def system_replacemsg_spam(data, fos):
vdom = data['vdom']
state = data['state']
system_replacemsg_spam_data = data['system_replacemsg_spam']
filtered_data = underscore_to_hyphen(filter_system_replacemsg_spam_data(system_replacemsg_spam_data))
if state == "present":
return fos.set('system.replacemsg',
'spam',
data=filtered_data,
vdom=vdom)
elif state == "absent":
return fos.delete('system.replacemsg',
'spam',
mkey=filtered_data['msg-type'],
vdom=vdom)
def is_successful_status(status):
return status['status'] == "success" or \
status['http_method'] == "DELETE" and status['http_status'] == 404
def fortios_system_replacemsg(data, fos):
if data['system_replacemsg_spam']:
resp = system_replacemsg_spam(data, fos)
return not is_successful_status(resp), \
resp['status'] == "success", \
resp
def main():
fields = {
"host": {"required": False, "type": "str"},
"username": {"required": False, "type": "str"},
"password": {"required": False, "type": "str", "default": "", "no_log": True},
"vdom": {"required": False, "type": "str", "default": "root"},
"https": {"required": False, "type": "bool", "default": True},
"ssl_verify": {"required": False, "type": "bool", "default": True},
"state": {"required": True, "type": "str",
"choices": ["present", "absent"]},
"system_replacemsg_spam": {
"required": False, "type": "dict", "default": None,
"options": {
"buffer": {"required": False, "type": "str"},
"format": {"required": False, "type": "str",
"choices": ["none", "text", "html",
"wml"]},
"header": {"required": False, "type": "str",
"choices": ["none", "http", "8bit"]},
"msg_type": {"required": False, "type": "str"}
}
}
}
module = AnsibleModule(argument_spec=fields,
supports_check_mode=False)
# legacy_mode refers to using fortiosapi instead of HTTPAPI
legacy_mode = 'host' in module.params and module.params['host'] is not None and \
'username' in module.params and module.params['username'] is not None and \
'password' in module.params and module.params['password'] is not None
if not legacy_mode:
if module._socket_path:
connection = Connection(module._socket_path)
fos = FortiOSHandler(connection)
is_error, has_changed, result = fortios_system_replacemsg(module.params, fos)
else:
module.fail_json(**FAIL_SOCKET_MSG)
else:
try:
from fortiosapi import FortiOSAPI
except ImportError:
module.fail_json(msg="fortiosapi module is required")
fos = FortiOSAPI()
login(module.params, fos)
is_error, has_changed, result = fortios_system_replacemsg(module.params, fos)
fos.logout()
if not is_error:
module.exit_json(changed=has_changed, meta=result)
else:
module.fail_json(msg="Error in repo", meta=result)
if __name__ == '__main__':
main()
| mit |
googleapis/python-compute | google/cloud/compute_v1/services/target_pools/pagers.py | 1 | 5656 | # -*- coding: utf-8 -*-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
from typing import (
Any,
AsyncIterable,
Awaitable,
Callable,
Iterable,
Sequence,
Tuple,
Optional,
)
from google.cloud.compute_v1.types import compute
class AggregatedListPager:
"""A pager for iterating through ``aggregated_list`` requests.
This class thinly wraps an initial
:class:`google.cloud.compute_v1.types.TargetPoolAggregatedList` object, and
provides an ``__iter__`` method to iterate through its
``items`` field.
If there are more pages, the ``__iter__`` method will make additional
``AggregatedList`` requests and continue to iterate
through the ``items`` field on the
corresponding responses.
All the usual :class:`google.cloud.compute_v1.types.TargetPoolAggregatedList`
attributes are available on the pager. If multiple requests are made, only
the most recent response is retained, and thus used for attribute lookup.
"""
def __init__(
self,
method: Callable[..., compute.TargetPoolAggregatedList],
request: compute.AggregatedListTargetPoolsRequest,
response: compute.TargetPoolAggregatedList,
*,
metadata: Sequence[Tuple[str, str]] = ()
):
"""Instantiate the pager.
Args:
method (Callable): The method that was originally called, and
which instantiated this pager.
request (google.cloud.compute_v1.types.AggregatedListTargetPoolsRequest):
The initial request object.
response (google.cloud.compute_v1.types.TargetPoolAggregatedList):
The initial response object.
metadata (Sequence[Tuple[str, str]]): Strings which should be
sent along with the request as metadata.
"""
self._method = method
self._request = compute.AggregatedListTargetPoolsRequest(request)
self._response = response
self._metadata = metadata
def __getattr__(self, name: str) -> Any:
return getattr(self._response, name)
@property
def pages(self) -> Iterable[compute.TargetPoolAggregatedList]:
yield self._response
while self._response.next_page_token:
self._request.page_token = self._response.next_page_token
self._response = self._method(self._request, metadata=self._metadata)
yield self._response
def __iter__(self) -> Iterable[Tuple[str, compute.TargetPoolsScopedList]]:
for page in self.pages:
yield from page.items.items()
def get(self, key: str) -> Optional[compute.TargetPoolsScopedList]:
return self._response.items.get(key)
def __repr__(self) -> str:
return "{0}<{1!r}>".format(self.__class__.__name__, self._response)
class ListPager:
"""A pager for iterating through ``list`` requests.
This class thinly wraps an initial
:class:`google.cloud.compute_v1.types.TargetPoolList` object, and
provides an ``__iter__`` method to iterate through its
``items`` field.
If there are more pages, the ``__iter__`` method will make additional
``List`` requests and continue to iterate
through the ``items`` field on the
corresponding responses.
All the usual :class:`google.cloud.compute_v1.types.TargetPoolList`
attributes are available on the pager. If multiple requests are made, only
the most recent response is retained, and thus used for attribute lookup.
"""
def __init__(
self,
method: Callable[..., compute.TargetPoolList],
request: compute.ListTargetPoolsRequest,
response: compute.TargetPoolList,
*,
metadata: Sequence[Tuple[str, str]] = ()
):
"""Instantiate the pager.
Args:
method (Callable): The method that was originally called, and
which instantiated this pager.
request (google.cloud.compute_v1.types.ListTargetPoolsRequest):
The initial request object.
response (google.cloud.compute_v1.types.TargetPoolList):
The initial response object.
metadata (Sequence[Tuple[str, str]]): Strings which should be
sent along with the request as metadata.
"""
self._method = method
self._request = compute.ListTargetPoolsRequest(request)
self._response = response
self._metadata = metadata
def __getattr__(self, name: str) -> Any:
return getattr(self._response, name)
@property
def pages(self) -> Iterable[compute.TargetPoolList]:
yield self._response
while self._response.next_page_token:
self._request.page_token = self._response.next_page_token
self._response = self._method(self._request, metadata=self._metadata)
yield self._response
def __iter__(self) -> Iterable[compute.TargetPool]:
for page in self.pages:
yield from page.items
def __repr__(self) -> str:
return "{0}<{1!r}>".format(self.__class__.__name__, self._response)
| apache-2.0 |
keyme/visual-diff | gui.py | 1 | 4290 | #!/usr/bin/python3
from functools import partial
from math import ceil
import tkinter as tk
from zoom_map import ZoomMap
class _Context(tk.Text):
CONTEXT_COUNT = 3 # Lines to display before/after the current one
# TODO: What about files with over 99,999 lines?
LINE_NUMBER_WIDTH = 5 # Number of characters to allocate for line numbers
PRELUDE_WIDTH = LINE_NUMBER_WIDTH + 2 # Line number, colon, space
# TODO: What about files with very long lines? They currently wrap around to
# the next line and push later context out of the widget. Should we truncate
# them instead? and if so, should we change which part gets cut based on the
# location of the token within the line?
TEXT_WIDTH = 80
def __init__(self, tk_parent, data, zoom_map):
height = 2 * self.CONTEXT_COUNT + 1
width = self.PRELUDE_WIDTH + self.TEXT_WIDTH
super().__init__(tk_parent, width=width, height=height,
state=tk.DISABLED, font="TkFixedFont")
self.pack()
# TODO: Use a NamedTuple?
self._tokens, self._lines, self._boundaries = data
self._zoom_map = zoom_map
def display(self, pixel):
# The zoom level is equivalent to the number of tokens described by the
# current pixel in the map.
zoom_level = self._zoom_map.zoom_level
first_token_index = int(pixel * zoom_level)
last_token_index = min(first_token_index + ceil(zoom_level),
len(self._boundaries)) - 1
if not (0 <= first_token_index < len(self._boundaries)):
# TODO: Restrict panning so that we can't go outside the image.
return # We're out of range of the image. Skip it.
line_number = self._boundaries[first_token_index][0][0]
# Recall that line_number comes from the token module, which starts
# counting at 1 instead of 0.
start = line_number - self.CONTEXT_COUNT - 1
end = line_number + self.CONTEXT_COUNT
lines = ["{:>{}}: {}".format(i + 1, self.LINE_NUMBER_WIDTH,
self._lines[i])
if 0 <= i < len(self._lines) else ""
for i in range(start, end)]
text = "\n".join(lines)
# Update the displayed code
self.configure(state=tk.NORMAL)
self.delete("1.0", tk.END)
self.insert(tk.INSERT, text)
# Highlight the tokens of interest...
(ar, ac) = self._boundaries[first_token_index][0]
(br, bc) = self._boundaries[last_token_index][1]
self.tag_add("token",
"{}.{}".format(self.CONTEXT_COUNT + 1,
ac + self.PRELUDE_WIDTH),
"{}.{}".format(self.CONTEXT_COUNT + 1 + br - ar,
bc + self.PRELUDE_WIDTH))
self.tag_config("token", background="yellow")
# ...but don't highlight the line numbers on multi-line tokens.
for i in range(self.CONTEXT_COUNT):
line = i + self.CONTEXT_COUNT + 2
self.tag_remove("token",
"{}.{}".format(line, 0),
"{}.{}".format(line, self.PRELUDE_WIDTH))
# Remember to disable editing again when we're done, so users can't
# modify the code we're displaying!
self.configure(state=tk.DISABLED)
class _Gui(tk.Frame):
def __init__(self, matrix, data_a, data_b, root):
super().__init__(root)
self.pack(fill=tk.BOTH, expand="true")
self._map = ZoomMap(self, matrix)
self._contexts = [_Context(self, data, self._map)
for data in (data_a, data_b)]
[self._map.bind(event, self._on_motion)
for event in ["<Motion>", "<Enter>"]]
def _on_motion(self, event):
# We're using (row, col) format, so the first one changes with Y.
self._contexts[0].display(self._map.canvasy(event.y))
self._contexts[1].display(self._map.canvasx(event.x))
def launch(matrix, data_a, data_b):
root = tk.Tk()
def _quit(event):
root.destroy()
[root.bind("<Control-{}>".format(char), _quit) for char in "wWqQ"]
gui = _Gui(matrix, data_a, data_b, root)
root.mainloop()
| gpl-3.0 |
salexkidd/restframework-definable-serializer | definable_serializer/tests/for_test/migrations/0001_initial.py | 1 | 1872 | # Generated by Django 2.0 on 2017-12-04 00:09
import definable_serializer.models.compat
import definable_serializer.models.fields
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name='Answer',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('data', definable_serializer.models.compat.YAMLField()),
('create_at', models.DateTimeField(auto_now_add=True)),
('update_at', models.DateTimeField(auto_now=True)),
],
options={
'ordering': ('id',),
},
),
migrations.CreateModel(
name='Paper',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('definition', definable_serializer.models.fields.DefinableSerializerByYAMLField()),
],
options={
'abstract': False,
},
),
migrations.AddField(
model_name='answer',
name='paper',
field=models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, to='for_test.Paper'),
),
migrations.AddField(
model_name='answer',
name='respondent',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL),
),
migrations.AlterUniqueTogether(
name='answer',
unique_together={('paper', 'respondent')},
),
]
| mit |
kmee/stock-logistics-warehouse | stock_available_sale/models/product_product.py | 5 | 4972 | # -*- coding: utf-8 -*-
# © 2014 Numérigraphe SARL
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from collections import Counter
from openerp import models, api, fields
import openerp.addons.decimal_precision as dp
class ProductProduct(models.Model):
"""Add the computation for the stock available to promise"""
_inherit = 'product.product'
quoted_qty = fields.Float(
compute='_get_quoted_qty',
type='float',
digits_compute=dp.get_precision('Product Unit of Measure'),
string='Quoted',
help="Total quantity of this Product that have been included in "
"Quotations (Draft Sale Orders).\n"
"In a context with a single Warehouse, this includes "
"Quotation processed in this Warehouse.\n"
"In a context with a single Stock Location, this includes "
"Quotation processed at any Warehouse using "
"this Location, or any of its children, as it's Stock "
"Location.\n"
"Otherwise, this includes every Quotation.")
@api.multi
@api.depends('quoted_qty')
def _immediately_usable_qty(self):
"""Subtract quoted quantity from qty available to promise
This is the same implementation as for templates."""
super(ProductProduct, self)._immediately_usable_qty()
for product in self:
product.immediately_usable_qty -= product.quoted_qty
@api.multi
def _get_quoted_qty(self):
"""Compute the quantities in Quotations."""
domain = [
('state', '=', 'draft'),
('product_id', 'in', self.ids)]
# Limit to a specific company
if self.env.context.get('force_company', False):
domain.append(('company_id', '=',
self.env.context['force_company']))
# when we search locations, should children be searched too?
if self.env.context.get('compute_child', True):
loc_op = 'child_of'
else:
loc_op = 'in'
# Limit to some locations
# Take warehouses that have these locations as stock locations
if self.env.context.get('location', False):
# Search by ID
if isinstance(self.env.context['location'], (int, long)):
domain.append(
('order_id.warehouse_id.lot_stock_id', loc_op,
[self.env.context['location']]))
# Search by name
elif isinstance(self.env.context['location'], basestring):
location_ids = [
l.id
for l in self.env['stock.location'].search([
('complete_name', 'ilike',
self.env.context['location'])])]
domain.append(
('order_id.warehouse_id.lot_stock_id', loc_op,
location_ids))
# Search by whatever the context has - probably a list of IDs
else:
domain.append(
('order_id.warehouse_id.lot_stock_id', loc_op,
self.env.context['location']))
# Limit to a warehouse
if self.env.context.get('warehouse', False):
domain.append(
('order_id.warehouse_id', '=', self.env.context['warehouse']))
# Limit to a period
from_date = self.env.context.get('from_date', False)
to_date = self.env.context.get('to_date', False)
if from_date:
domain.extend([
('order_id.requested_date', '>=', from_date),
'&', # only consider 'date' when 'equested_date' is empty
('order_id.requested_date', '=', False),
('order_id.date', '>=', from_date),
])
if to_date:
domain.extend([
('order_id.requested_date', '<=', to_date),
'&', # only consider 'date' when 'equested_date' is empty
('order_id.requested_date', '=', False),
('order_id.date', '<=', to_date),
])
# Compute the quoted quantity for each product
results = Counter()
for group in self.env['sale.order.line'].read_group(
domain, ['product_uom_qty', 'product_id', 'product_uom'],
['product_id', 'product_uom'],
lazy=False):
product_id = group['product_id'][0]
uom_id = group['product_uom'][0]
# Compute the quoted quantity in the product's UoM
# Rounding is OK since small values have not been squashed before
results += Counter({
product_id: self.env['product.uom']._compute_qty(
uom_id, group['product_uom_qty'],
self.browse(product_id).uom_id.id)})
for product in self:
product.quoted_qty = results.get(product.id, 0.0)
| agpl-3.0 |
iamjy/beaglebone-kernel | tools/perf/scripts/python/sctop.py | 11180 | 1924 | # system call top
# (c) 2010, Tom Zanussi <tzanussi@gmail.com>
# Licensed under the terms of the GNU GPL License version 2
#
# Periodically displays system-wide system call totals, broken down by
# syscall. If a [comm] arg is specified, only syscalls called by
# [comm] are displayed. If an [interval] arg is specified, the display
# will be refreshed every [interval] seconds. The default interval is
# 3 seconds.
import os, sys, thread, time
sys.path.append(os.environ['PERF_EXEC_PATH'] + \
'/scripts/python/Perf-Trace-Util/lib/Perf/Trace')
from perf_trace_context import *
from Core import *
from Util import *
usage = "perf script -s sctop.py [comm] [interval]\n";
for_comm = None
default_interval = 3
interval = default_interval
if len(sys.argv) > 3:
sys.exit(usage)
if len(sys.argv) > 2:
for_comm = sys.argv[1]
interval = int(sys.argv[2])
elif len(sys.argv) > 1:
try:
interval = int(sys.argv[1])
except ValueError:
for_comm = sys.argv[1]
interval = default_interval
syscalls = autodict()
def trace_begin():
thread.start_new_thread(print_syscall_totals, (interval,))
pass
def raw_syscalls__sys_enter(event_name, context, common_cpu,
common_secs, common_nsecs, common_pid, common_comm,
id, args):
if for_comm is not None:
if common_comm != for_comm:
return
try:
syscalls[id] += 1
except TypeError:
syscalls[id] = 1
def print_syscall_totals(interval):
while 1:
clear_term()
if for_comm is not None:
print "\nsyscall events for %s:\n\n" % (for_comm),
else:
print "\nsyscall events:\n\n",
print "%-40s %10s\n" % ("event", "count"),
print "%-40s %10s\n" % ("----------------------------------------", \
"----------"),
for id, val in sorted(syscalls.iteritems(), key = lambda(k, v): (v, k), \
reverse = True):
try:
print "%-40s %10d\n" % (syscall_name(id), val),
except TypeError:
pass
syscalls.clear()
time.sleep(interval)
| gpl-2.0 |
DucQuang1/youtube-dl | youtube_dl/extractor/nosvideo.py | 128 | 2519 | # coding: utf-8
from __future__ import unicode_literals
import re
from .common import InfoExtractor
from ..compat import (
compat_urllib_request,
)
from ..utils import (
ExtractorError,
urlencode_postdata,
xpath_text,
xpath_with_ns,
)
_x = lambda p: xpath_with_ns(p, {'xspf': 'http://xspf.org/ns/0/'})
class NosVideoIE(InfoExtractor):
_VALID_URL = r'https?://(?:www\.)?nosvideo\.com/' + \
'(?:embed/|\?v=)(?P<id>[A-Za-z0-9]{12})/?'
_PLAYLIST_URL = 'http://nosvideo.com/xml/{xml_id:s}.xml'
_FILE_DELETED_REGEX = r'<b>File Not Found</b>'
_TEST = {
'url': 'http://nosvideo.com/?v=mu8fle7g7rpq',
'md5': '6124ed47130d8be3eacae635b071e6b6',
'info_dict': {
'id': 'mu8fle7g7rpq',
'ext': 'mp4',
'title': 'big_buck_bunny_480p_surround-fix.avi.mp4',
'thumbnail': 're:^https?://.*\.jpg$',
}
}
def _real_extract(self, url):
video_id = self._match_id(url)
fields = {
'id': video_id,
'op': 'download1',
'method_free': 'Continue to Video',
}
req = compat_urllib_request.Request(url, urlencode_postdata(fields))
req.add_header('Content-type', 'application/x-www-form-urlencoded')
webpage = self._download_webpage(req, video_id,
'Downloading download page')
if re.search(self._FILE_DELETED_REGEX, webpage) is not None:
raise ExtractorError('Video %s does not exist' % video_id,
expected=True)
xml_id = self._search_regex(r'php\|([^\|]+)\|', webpage, 'XML ID')
playlist_url = self._PLAYLIST_URL.format(xml_id=xml_id)
playlist = self._download_xml(playlist_url, video_id)
track = playlist.find(_x('.//xspf:track'))
if track is None:
raise ExtractorError(
'XML playlist is missing the \'track\' element',
expected=True)
title = xpath_text(track, _x('./xspf:title'), 'title')
url = xpath_text(track, _x('./xspf:file'), 'URL', fatal=True)
thumbnail = xpath_text(track, _x('./xspf:image'), 'thumbnail')
if title is not None:
title = title.strip()
formats = [{
'format_id': 'sd',
'url': url,
}]
return {
'id': video_id,
'title': title,
'thumbnail': thumbnail,
'formats': formats,
}
| unlicense |
losalamos/PowerParser | docs/breathe-3.2.0/breathe/parser/doxygen/compoundsuper.py | 2 | 237779 | #!/usr/bin/env python
#
# Generated Thu Jun 11 18:44:25 2009 by generateDS.py.
#
import sys
import getopt
from xml.dom import minidom
from xml.dom import Node
#
# User methods
#
# Calls to the methods in these classes are generated by generateDS.py.
# You can replace these methods by re-implementing the following class
# in a module named generatedssuper.py.
try:
from generatedssuper import GeneratedsSuper
except ImportError as exp:
class GeneratedsSuper:
def format_string(self, input_data, input_name=''):
return input_data
def format_integer(self, input_data, input_name=''):
return '%d' % input_data
def format_float(self, input_data, input_name=''):
return '%f' % input_data
def format_double(self, input_data, input_name=''):
return '%e' % input_data
def format_boolean(self, input_data, input_name=''):
return '%s' % input_data
#
# If you have installed IPython you can uncomment and use the following.
# IPython is available from http://ipython.scipy.org/.
#
## from IPython.Shell import IPShellEmbed
## args = ''
## ipshell = IPShellEmbed(args,
## banner = 'Dropping into IPython',
## exit_msg = 'Leaving Interpreter, back to program.')
# Then use the following line where and when you want to drop into the
# IPython shell:
# ipshell('<some message> -- Entering ipshell.\nHit Ctrl-D to exit')
#
# Globals
#
ExternalEncoding = 'ascii'
#
# Support/utility functions.
#
def showIndent(outfile, level):
for idx in range(level):
outfile.write(' ')
def quote_xml(inStr):
s1 = (isinstance(inStr, basestring) and inStr or
'%s' % inStr)
s1 = s1.replace('&', '&')
s1 = s1.replace('<', '<')
s1 = s1.replace('>', '>')
return s1
def quote_attrib(inStr):
s1 = (isinstance(inStr, basestring) and inStr or
'%s' % inStr)
s1 = s1.replace('&', '&')
s1 = s1.replace('<', '<')
s1 = s1.replace('>', '>')
if '"' in s1:
if "'" in s1:
s1 = '"%s"' % s1.replace('"', """)
else:
s1 = "'%s'" % s1
else:
s1 = '"%s"' % s1
return s1
def quote_python(inStr):
s1 = inStr
if s1.find("'") == -1:
if s1.find('\n') == -1:
return "'%s'" % s1
else:
return "'''%s'''" % s1
else:
if s1.find('"') != -1:
s1 = s1.replace('"', '\\"')
if s1.find('\n') == -1:
return '"%s"' % s1
else:
return '"""%s"""' % s1
class MixedContainer:
node_type = "mixedcontainer"
# Constants for category:
CategoryNone = 0
CategoryText = 1
CategorySimple = 2
CategoryComplex = 3
# Constants for content_type:
TypeNone = 0
TypeText = 1
TypeString = 2
TypeInteger = 3
TypeFloat = 4
TypeDecimal = 5
TypeDouble = 6
TypeBoolean = 7
def __init__(self, category, content_type, name, value):
self.category = category
self.content_type = content_type
self.name = name
self.value = value
def getCategory(self):
return self.category
def getContenttype(self, content_type):
return self.content_type
def getValue(self):
return self.value
def getName(self):
return self.name
class _MemberSpec(object):
def __init__(self, name='', data_type='', container=0):
self.name = name
self.data_type = data_type
self.container = container
def set_name(self, name): self.name = name
def get_name(self): return self.name
def set_data_type(self, data_type): self.data_type = data_type
def get_data_type(self): return self.data_type
def set_container(self, container): self.container = container
def get_container(self): return self.container
#
# Data representation classes.
#
class DoxygenType(GeneratedsSuper):
subclass = None
superclass = None
def __init__(self, version=None, compounddef=None):
self.version = version
self.compounddef = compounddef
def factory(*args_, **kwargs_):
if DoxygenType.subclass:
return DoxygenType.subclass(*args_, **kwargs_)
else:
return DoxygenType(*args_, **kwargs_)
factory = staticmethod(factory)
def get_compounddef(self): return self.compounddef
def set_compounddef(self, compounddef): self.compounddef = compounddef
def get_version(self): return self.version
def set_version(self, version): self.version = version
def hasContent_(self):
if (
self.compounddef is not None
):
return True
else:
return False
def build(self, node_):
attrs = node_.attributes
self.buildAttributes(attrs)
for child_ in node_.childNodes:
nodeName_ = child_.nodeName.split(':')[-1]
self.buildChildren(child_, nodeName_)
def buildAttributes(self, attrs):
if attrs.get('version'):
self.version = attrs.get('version').value
def buildChildren(self, child_, nodeName_):
if child_.nodeType == Node.ELEMENT_NODE and \
nodeName_ == 'compounddef':
obj_ = compounddefType.factory()
obj_.build(child_)
self.set_compounddef(obj_)
# end class DoxygenType
class compounddefType(GeneratedsSuper):
subclass = None
superclass = None
def __init__(self, kind=None, prot=None, id=None, compoundname=None, title=None, basecompoundref=None, derivedcompoundref=None, includes=None, includedby=None, incdepgraph=None, invincdepgraph=None, innerdir=None, innerfile=None, innerclass=None, innernamespace=None, innerpage=None, innergroup=None, templateparamlist=None, sectiondef=None, briefdescription=None, detaileddescription=None, inheritancegraph=None, collaborationgraph=None, programlisting=None, location=None, listofallmembers=None):
self.kind = kind
self.prot = prot
self.id = id
self.compoundname = compoundname
self.title = title
if basecompoundref is None:
self.basecompoundref = []
else:
self.basecompoundref = basecompoundref
if derivedcompoundref is None:
self.derivedcompoundref = []
else:
self.derivedcompoundref = derivedcompoundref
if includes is None:
self.includes = []
else:
self.includes = includes
if includedby is None:
self.includedby = []
else:
self.includedby = includedby
self.incdepgraph = incdepgraph
self.invincdepgraph = invincdepgraph
if innerdir is None:
self.innerdir = []
else:
self.innerdir = innerdir
if innerfile is None:
self.innerfile = []
else:
self.innerfile = innerfile
if innerclass is None:
self.innerclass = []
else:
self.innerclass = innerclass
if innernamespace is None:
self.innernamespace = []
else:
self.innernamespace = innernamespace
if innerpage is None:
self.innerpage = []
else:
self.innerpage = innerpage
if innergroup is None:
self.innergroup = []
else:
self.innergroup = innergroup
self.templateparamlist = templateparamlist
if sectiondef is None:
self.sectiondef = []
else:
self.sectiondef = sectiondef
self.briefdescription = briefdescription
self.detaileddescription = detaileddescription
self.inheritancegraph = inheritancegraph
self.collaborationgraph = collaborationgraph
self.programlisting = programlisting
self.location = location
self.listofallmembers = listofallmembers
self.namespaces = []
def factory(*args_, **kwargs_):
if compounddefType.subclass:
return compounddefType.subclass(*args_, **kwargs_)
else:
return compounddefType(*args_, **kwargs_)
factory = staticmethod(factory)
def get_compoundname(self): return self.compoundname
def set_compoundname(self, compoundname): self.compoundname = compoundname
def get_title(self): return self.title
def set_title(self, title): self.title = title
def get_basecompoundref(self): return self.basecompoundref
def set_basecompoundref(self, basecompoundref): self.basecompoundref = basecompoundref
def add_basecompoundref(self, value): self.basecompoundref.append(value)
def insert_basecompoundref(self, index, value): self.basecompoundref[index] = value
def get_derivedcompoundref(self): return self.derivedcompoundref
def set_derivedcompoundref(self, derivedcompoundref): self.derivedcompoundref = derivedcompoundref
def add_derivedcompoundref(self, value): self.derivedcompoundref.append(value)
def insert_derivedcompoundref(self, index, value): self.derivedcompoundref[index] = value
def get_includes(self): return self.includes
def set_includes(self, includes): self.includes = includes
def add_includes(self, value): self.includes.append(value)
def insert_includes(self, index, value): self.includes[index] = value
def get_includedby(self): return self.includedby
def set_includedby(self, includedby): self.includedby = includedby
def add_includedby(self, value): self.includedby.append(value)
def insert_includedby(self, index, value): self.includedby[index] = value
def get_incdepgraph(self): return self.incdepgraph
def set_incdepgraph(self, incdepgraph): self.incdepgraph = incdepgraph
def get_invincdepgraph(self): return self.invincdepgraph
def set_invincdepgraph(self, invincdepgraph): self.invincdepgraph = invincdepgraph
def get_innerdir(self): return self.innerdir
def set_innerdir(self, innerdir): self.innerdir = innerdir
def add_innerdir(self, value): self.innerdir.append(value)
def insert_innerdir(self, index, value): self.innerdir[index] = value
def get_innerfile(self): return self.innerfile
def set_innerfile(self, innerfile): self.innerfile = innerfile
def add_innerfile(self, value): self.innerfile.append(value)
def insert_innerfile(self, index, value): self.innerfile[index] = value
def get_innerclass(self): return self.innerclass
def set_innerclass(self, innerclass): self.innerclass = innerclass
def add_innerclass(self, value): self.innerclass.append(value)
def insert_innerclass(self, index, value): self.innerclass[index] = value
def get_innernamespace(self): return self.innernamespace
def set_innernamespace(self, innernamespace): self.innernamespace = innernamespace
def add_innernamespace(self, value): self.innernamespace.append(value)
def insert_innernamespace(self, index, value): self.innernamespace[index] = value
def get_innerpage(self): return self.innerpage
def set_innerpage(self, innerpage): self.innerpage = innerpage
def add_innerpage(self, value): self.innerpage.append(value)
def insert_innerpage(self, index, value): self.innerpage[index] = value
def get_innergroup(self): return self.innergroup
def set_innergroup(self, innergroup): self.innergroup = innergroup
def add_innergroup(self, value): self.innergroup.append(value)
def insert_innergroup(self, index, value): self.innergroup[index] = value
def get_templateparamlist(self): return self.templateparamlist
def set_templateparamlist(self, templateparamlist): self.templateparamlist = templateparamlist
def get_sectiondef(self): return self.sectiondef
def set_sectiondef(self, sectiondef): self.sectiondef = sectiondef
def add_sectiondef(self, value): self.sectiondef.append(value)
def insert_sectiondef(self, index, value): self.sectiondef[index] = value
def get_briefdescription(self): return self.briefdescription
def set_briefdescription(self, briefdescription): self.briefdescription = briefdescription
def get_detaileddescription(self): return self.detaileddescription
def set_detaileddescription(self, detaileddescription): self.detaileddescription = detaileddescription
def get_inheritancegraph(self): return self.inheritancegraph
def set_inheritancegraph(self, inheritancegraph): self.inheritancegraph = inheritancegraph
def get_collaborationgraph(self): return self.collaborationgraph
def set_collaborationgraph(self, collaborationgraph): self.collaborationgraph = collaborationgraph
def get_programlisting(self): return self.programlisting
def set_programlisting(self, programlisting): self.programlisting = programlisting
def get_location(self): return self.location
def set_location(self, location): self.location = location
def get_listofallmembers(self): return self.listofallmembers
def set_listofallmembers(self, listofallmembers): self.listofallmembers = listofallmembers
def get_kind(self): return self.kind
def set_kind(self, kind): self.kind = kind
def get_prot(self): return self.prot
def set_prot(self, prot): self.prot = prot
def get_id(self): return self.id
def set_id(self, id): self.id = id
def hasContent_(self):
if (
self.compoundname is not None or
self.title is not None or
self.basecompoundref is not None or
self.derivedcompoundref is not None or
self.includes is not None or
self.includedby is not None or
self.incdepgraph is not None or
self.invincdepgraph is not None or
self.innerdir is not None or
self.innerfile is not None or
self.innerclass is not None or
self.innernamespace is not None or
self.innerpage is not None or
self.innergroup is not None or
self.templateparamlist is not None or
self.sectiondef is not None or
self.briefdescription is not None or
self.detaileddescription is not None or
self.inheritancegraph is not None or
self.collaborationgraph is not None or
self.programlisting is not None or
self.location is not None or
self.listofallmembers is not None
):
return True
else:
return False
def build(self, node_):
attrs = node_.attributes
self.buildAttributes(attrs)
for child_ in node_.childNodes:
nodeName_ = child_.nodeName.split(':')[-1]
self.buildChildren(child_, nodeName_)
def buildAttributes(self, attrs):
if attrs.get('kind'):
self.kind = attrs.get('kind').value
if attrs.get('prot'):
self.prot = attrs.get('prot').value
if attrs.get('id'):
self.id = attrs.get('id').value
def buildChildren(self, child_, nodeName_):
if child_.nodeType == Node.ELEMENT_NODE and \
nodeName_ == 'compoundname':
compoundname_ = ''
for text__content_ in child_.childNodes:
compoundname_ += text__content_.nodeValue
self.compoundname = compoundname_
elif child_.nodeType == Node.ELEMENT_NODE and \
nodeName_ == 'title':
obj_ = docTitleType.factory()
obj_.build(child_)
self.set_title(obj_)
elif child_.nodeType == Node.ELEMENT_NODE and \
nodeName_ == 'basecompoundref':
obj_ = compoundRefType.factory()
obj_.build(child_)
self.basecompoundref.append(obj_)
elif child_.nodeType == Node.ELEMENT_NODE and \
nodeName_ == 'derivedcompoundref':
obj_ = compoundRefType.factory()
obj_.build(child_)
self.derivedcompoundref.append(obj_)
elif child_.nodeType == Node.ELEMENT_NODE and \
nodeName_ == 'includes':
obj_ = incType.factory()
obj_.build(child_)
self.includes.append(obj_)
elif child_.nodeType == Node.ELEMENT_NODE and \
nodeName_ == 'includedby':
obj_ = incType.factory()
obj_.build(child_)
self.includedby.append(obj_)
elif child_.nodeType == Node.ELEMENT_NODE and \
nodeName_ == 'incdepgraph':
obj_ = graphType.factory()
obj_.build(child_)
self.set_incdepgraph(obj_)
elif child_.nodeType == Node.ELEMENT_NODE and \
nodeName_ == 'invincdepgraph':
obj_ = graphType.factory()
obj_.build(child_)
self.set_invincdepgraph(obj_)
elif child_.nodeType == Node.ELEMENT_NODE and \
nodeName_ == 'innerdir':
obj_ = refType.factory(nodeName_)
obj_.build(child_)
self.innerdir.append(obj_)
elif child_.nodeType == Node.ELEMENT_NODE and \
nodeName_ == 'innerfile':
obj_ = refType.factory(nodeName_)
obj_.build(child_)
self.innerfile.append(obj_)
elif child_.nodeType == Node.ELEMENT_NODE and \
nodeName_ == 'innerclass':
obj_ = refType.factory(nodeName_)
obj_.build(child_)
self.innerclass.append(obj_)
self.namespaces.append(obj_.content_[0].getValue())
elif child_.nodeType == Node.ELEMENT_NODE and \
nodeName_ == 'innernamespace':
obj_ = refType.factory(nodeName_)
obj_.build(child_)
self.innernamespace.append(obj_)
self.namespaces.append(obj_.content_[0].getValue())
elif child_.nodeType == Node.ELEMENT_NODE and \
nodeName_ == 'innerpage':
obj_ = refType.factory(nodeName_)
obj_.build(child_)
self.innerpage.append(obj_)
elif child_.nodeType == Node.ELEMENT_NODE and \
nodeName_ == 'innergroup':
obj_ = refType.factory(nodeName_)
obj_.build(child_)
self.innergroup.append(obj_)
elif child_.nodeType == Node.ELEMENT_NODE and \
nodeName_ == 'templateparamlist':
obj_ = templateparamlistType.factory()
obj_.build(child_)
self.set_templateparamlist(obj_)
elif child_.nodeType == Node.ELEMENT_NODE and \
nodeName_ == 'sectiondef':
obj_ = sectiondefType.factory()
obj_.build(child_)
self.sectiondef.append(obj_)
elif child_.nodeType == Node.ELEMENT_NODE and \
nodeName_ == 'briefdescription':
obj_ = descriptionType.factory()
obj_.build(child_)
self.set_briefdescription(obj_)
elif child_.nodeType == Node.ELEMENT_NODE and \
nodeName_ == 'detaileddescription':
obj_ = descriptionType.factory()
obj_.build(child_)
self.set_detaileddescription(obj_)
elif child_.nodeType == Node.ELEMENT_NODE and \
nodeName_ == 'inheritancegraph':
obj_ = graphType.factory()
obj_.build(child_)
self.set_inheritancegraph(obj_)
elif child_.nodeType == Node.ELEMENT_NODE and \
nodeName_ == 'collaborationgraph':
obj_ = graphType.factory()
obj_.build(child_)
self.set_collaborationgraph(obj_)
elif child_.nodeType == Node.ELEMENT_NODE and \
nodeName_ == 'programlisting':
obj_ = listingType.factory()
obj_.build(child_)
self.set_programlisting(obj_)
elif child_.nodeType == Node.ELEMENT_NODE and \
nodeName_ == 'location':
obj_ = locationType.factory()
obj_.build(child_)
self.set_location(obj_)
elif child_.nodeType == Node.ELEMENT_NODE and \
nodeName_ == 'listofallmembers':
obj_ = listofallmembersType.factory()
obj_.build(child_)
self.set_listofallmembers(obj_)
# end class compounddefType
class listofallmembersType(GeneratedsSuper):
subclass = None
superclass = None
def __init__(self, member=None):
if member is None:
self.member = []
else:
self.member = member
def factory(*args_, **kwargs_):
if listofallmembersType.subclass:
return listofallmembersType.subclass(*args_, **kwargs_)
else:
return listofallmembersType(*args_, **kwargs_)
factory = staticmethod(factory)
def get_member(self): return self.member
def set_member(self, member): self.member = member
def add_member(self, value): self.member.append(value)
def insert_member(self, index, value): self.member[index] = value
def hasContent_(self):
if (
self.member is not None
):
return True
else:
return False
def build(self, node_):
attrs = node_.attributes
self.buildAttributes(attrs)
for child_ in node_.childNodes:
nodeName_ = child_.nodeName.split(':')[-1]
self.buildChildren(child_, nodeName_)
def buildAttributes(self, attrs):
pass
def buildChildren(self, child_, nodeName_):
if child_.nodeType == Node.ELEMENT_NODE and \
nodeName_ == 'member':
obj_ = memberRefType.factory()
obj_.build(child_)
self.member.append(obj_)
# end class listofallmembersType
class memberRefType(GeneratedsSuper):
subclass = None
superclass = None
def __init__(self, virt=None, prot=None, refid=None, ambiguityscope=None, scope=None, name=None):
self.virt = virt
self.prot = prot
self.refid = refid
self.ambiguityscope = ambiguityscope
self.scope = scope
self.name = name
def factory(*args_, **kwargs_):
if memberRefType.subclass:
return memberRefType.subclass(*args_, **kwargs_)
else:
return memberRefType(*args_, **kwargs_)
factory = staticmethod(factory)
def get_scope(self): return self.scope
def set_scope(self, scope): self.scope = scope
def get_name(self): return self.name
def set_name(self, name): self.name = name
def get_virt(self): return self.virt
def set_virt(self, virt): self.virt = virt
def get_prot(self): return self.prot
def set_prot(self, prot): self.prot = prot
def get_refid(self): return self.refid
def set_refid(self, refid): self.refid = refid
def get_ambiguityscope(self): return self.ambiguityscope
def set_ambiguityscope(self, ambiguityscope): self.ambiguityscope = ambiguityscope
def hasContent_(self):
if (
self.scope is not None or
self.name is not None
):
return True
else:
return False
def build(self, node_):
attrs = node_.attributes
self.buildAttributes(attrs)
for child_ in node_.childNodes:
nodeName_ = child_.nodeName.split(':')[-1]
self.buildChildren(child_, nodeName_)
def buildAttributes(self, attrs):
if attrs.get('virt'):
self.virt = attrs.get('virt').value
if attrs.get('prot'):
self.prot = attrs.get('prot').value
if attrs.get('refid'):
self.refid = attrs.get('refid').value
if attrs.get('ambiguityscope'):
self.ambiguityscope = attrs.get('ambiguityscope').value
def buildChildren(self, child_, nodeName_):
if child_.nodeType == Node.ELEMENT_NODE and \
nodeName_ == 'scope':
scope_ = ''
for text__content_ in child_.childNodes:
scope_ += text__content_.nodeValue
self.scope = scope_
elif child_.nodeType == Node.ELEMENT_NODE and \
nodeName_ == 'name':
name_ = ''
for text__content_ in child_.childNodes:
name_ += text__content_.nodeValue
self.name = name_
# end class memberRefType
class scope(GeneratedsSuper):
subclass = None
superclass = None
def __init__(self, valueOf_=''):
self.valueOf_ = valueOf_
def factory(*args_, **kwargs_):
if scope.subclass:
return scope.subclass(*args_, **kwargs_)
else:
return scope(*args_, **kwargs_)
factory = staticmethod(factory)
def getValueOf_(self): return self.valueOf_
def setValueOf_(self, valueOf_): self.valueOf_ = valueOf_
def hasContent_(self):
if (
self.valueOf_ is not None
):
return True
else:
return False
def build(self, node_):
attrs = node_.attributes
self.buildAttributes(attrs)
self.valueOf_ = ''
for child_ in node_.childNodes:
nodeName_ = child_.nodeName.split(':')[-1]
self.buildChildren(child_, nodeName_)
def buildAttributes(self, attrs):
pass
def buildChildren(self, child_, nodeName_):
if child_.nodeType == Node.TEXT_NODE:
self.valueOf_ += child_.nodeValue
elif child_.nodeType == Node.CDATA_SECTION_NODE:
self.valueOf_ += '![CDATA['+child_.nodeValue+']]'
# end class scope
class name(GeneratedsSuper):
subclass = None
superclass = None
def __init__(self, valueOf_=''):
self.valueOf_ = valueOf_
def factory(*args_, **kwargs_):
if name.subclass:
return name.subclass(*args_, **kwargs_)
else:
return name(*args_, **kwargs_)
factory = staticmethod(factory)
def getValueOf_(self): return self.valueOf_
def setValueOf_(self, valueOf_): self.valueOf_ = valueOf_
def hasContent_(self):
if (
self.valueOf_ is not None
):
return True
else:
return False
def build(self, node_):
attrs = node_.attributes
self.buildAttributes(attrs)
self.valueOf_ = ''
for child_ in node_.childNodes:
nodeName_ = child_.nodeName.split(':')[-1]
self.buildChildren(child_, nodeName_)
def buildAttributes(self, attrs):
pass
def buildChildren(self, child_, nodeName_):
if child_.nodeType == Node.TEXT_NODE:
self.valueOf_ += child_.nodeValue
elif child_.nodeType == Node.CDATA_SECTION_NODE:
self.valueOf_ += '![CDATA['+child_.nodeValue+']]'
# end class name
class compoundRefType(GeneratedsSuper):
subclass = None
superclass = None
def __init__(self, virt=None, prot=None, refid=None, valueOf_='', mixedclass_=None, content_=None):
self.virt = virt
self.prot = prot
self.refid = refid
if mixedclass_ is None:
self.mixedclass_ = MixedContainer
else:
self.mixedclass_ = mixedclass_
if content_ is None:
self.content_ = []
else:
self.content_ = content_
def factory(*args_, **kwargs_):
if compoundRefType.subclass:
return compoundRefType.subclass(*args_, **kwargs_)
else:
return compoundRefType(*args_, **kwargs_)
factory = staticmethod(factory)
def get_virt(self): return self.virt
def set_virt(self, virt): self.virt = virt
def get_prot(self): return self.prot
def set_prot(self, prot): self.prot = prot
def get_refid(self): return self.refid
def set_refid(self, refid): self.refid = refid
def getValueOf_(self): return self.valueOf_
def setValueOf_(self, valueOf_): self.valueOf_ = valueOf_
def hasContent_(self):
if (
self.valueOf_ is not None
):
return True
else:
return False
def build(self, node_):
attrs = node_.attributes
self.buildAttributes(attrs)
self.valueOf_ = ''
for child_ in node_.childNodes:
nodeName_ = child_.nodeName.split(':')[-1]
self.buildChildren(child_, nodeName_)
def buildAttributes(self, attrs):
if attrs.get('virt'):
self.virt = attrs.get('virt').value
if attrs.get('prot'):
self.prot = attrs.get('prot').value
if attrs.get('refid'):
self.refid = attrs.get('refid').value
def buildChildren(self, child_, nodeName_):
if child_.nodeType == Node.TEXT_NODE:
obj_ = self.mixedclass_(MixedContainer.CategoryText,
MixedContainer.TypeNone, '', child_.nodeValue)
self.content_.append(obj_)
if child_.nodeType == Node.TEXT_NODE:
self.valueOf_ += child_.nodeValue
elif child_.nodeType == Node.CDATA_SECTION_NODE:
self.valueOf_ += '![CDATA['+child_.nodeValue+']]'
# end class compoundRefType
class reimplementType(GeneratedsSuper):
subclass = None
superclass = None
def __init__(self, refid=None, valueOf_='', mixedclass_=None, content_=None):
self.refid = refid
if mixedclass_ is None:
self.mixedclass_ = MixedContainer
else:
self.mixedclass_ = mixedclass_
if content_ is None:
self.content_ = []
else:
self.content_ = content_
def factory(*args_, **kwargs_):
if reimplementType.subclass:
return reimplementType.subclass(*args_, **kwargs_)
else:
return reimplementType(*args_, **kwargs_)
factory = staticmethod(factory)
def get_refid(self): return self.refid
def set_refid(self, refid): self.refid = refid
def getValueOf_(self): return self.valueOf_
def setValueOf_(self, valueOf_): self.valueOf_ = valueOf_
def hasContent_(self):
if (
self.valueOf_ is not None
):
return True
else:
return False
def build(self, node_):
attrs = node_.attributes
self.buildAttributes(attrs)
self.valueOf_ = ''
for child_ in node_.childNodes:
nodeName_ = child_.nodeName.split(':')[-1]
self.buildChildren(child_, nodeName_)
def buildAttributes(self, attrs):
if attrs.get('refid'):
self.refid = attrs.get('refid').value
def buildChildren(self, child_, nodeName_):
if child_.nodeType == Node.TEXT_NODE:
obj_ = self.mixedclass_(MixedContainer.CategoryText,
MixedContainer.TypeNone, '', child_.nodeValue)
self.content_.append(obj_)
if child_.nodeType == Node.TEXT_NODE:
self.valueOf_ += child_.nodeValue
elif child_.nodeType == Node.CDATA_SECTION_NODE:
self.valueOf_ += '![CDATA['+child_.nodeValue+']]'
# end class reimplementType
class incType(GeneratedsSuper):
subclass = None
superclass = None
def __init__(self, local=None, refid=None, valueOf_='', mixedclass_=None, content_=None):
self.local = local
self.refid = refid
if mixedclass_ is None:
self.mixedclass_ = MixedContainer
else:
self.mixedclass_ = mixedclass_
if content_ is None:
self.content_ = []
else:
self.content_ = content_
def factory(*args_, **kwargs_):
if incType.subclass:
return incType.subclass(*args_, **kwargs_)
else:
return incType(*args_, **kwargs_)
factory = staticmethod(factory)
def get_local(self): return self.local
def set_local(self, local): self.local = local
def get_refid(self): return self.refid
def set_refid(self, refid): self.refid = refid
def getValueOf_(self): return self.valueOf_
def setValueOf_(self, valueOf_): self.valueOf_ = valueOf_
def hasContent_(self):
if (
self.valueOf_ is not None
):
return True
else:
return False
def build(self, node_):
attrs = node_.attributes
self.buildAttributes(attrs)
self.valueOf_ = ''
for child_ in node_.childNodes:
nodeName_ = child_.nodeName.split(':')[-1]
self.buildChildren(child_, nodeName_)
def buildAttributes(self, attrs):
if attrs.get('local'):
self.local = attrs.get('local').value
if attrs.get('refid'):
self.refid = attrs.get('refid').value
def buildChildren(self, child_, nodeName_):
if child_.nodeType == Node.TEXT_NODE:
obj_ = self.mixedclass_(MixedContainer.CategoryText,
MixedContainer.TypeNone, '', child_.nodeValue)
self.content_.append(obj_)
if child_.nodeType == Node.TEXT_NODE:
self.valueOf_ += child_.nodeValue
elif child_.nodeType == Node.CDATA_SECTION_NODE:
self.valueOf_ += '![CDATA['+child_.nodeValue+']]'
# end class incType
class refType(GeneratedsSuper):
subclass = None
superclass = None
def __init__(self, prot=None, refid=None, valueOf_='', mixedclass_=None, content_=None):
self.prot = prot
self.refid = refid
if mixedclass_ is None:
self.mixedclass_ = MixedContainer
else:
self.mixedclass_ = mixedclass_
if content_ is None:
self.content_ = []
else:
self.content_ = content_
def factory(*args_, **kwargs_):
if refType.subclass:
return refType.subclass(*args_, **kwargs_)
else:
return refType(*args_, **kwargs_)
factory = staticmethod(factory)
def get_prot(self): return self.prot
def set_prot(self, prot): self.prot = prot
def get_refid(self): return self.refid
def set_refid(self, refid): self.refid = refid
def getValueOf_(self): return self.valueOf_
def setValueOf_(self, valueOf_): self.valueOf_ = valueOf_
def hasContent_(self):
if (
self.valueOf_ is not None
):
return True
else:
return False
def build(self, node_):
attrs = node_.attributes
self.buildAttributes(attrs)
self.valueOf_ = ''
for child_ in node_.childNodes:
nodeName_ = child_.nodeName.split(':')[-1]
self.buildChildren(child_, nodeName_)
def buildAttributes(self, attrs):
if attrs.get('prot'):
self.prot = attrs.get('prot').value
if attrs.get('refid'):
self.refid = attrs.get('refid').value
def buildChildren(self, child_, nodeName_):
if child_.nodeType == Node.TEXT_NODE:
obj_ = self.mixedclass_(MixedContainer.CategoryText,
MixedContainer.TypeNone, '', child_.nodeValue)
self.content_.append(obj_)
if child_.nodeType == Node.TEXT_NODE:
self.valueOf_ += child_.nodeValue
elif child_.nodeType == Node.CDATA_SECTION_NODE:
self.valueOf_ += '![CDATA['+child_.nodeValue+']]'
# end class refType
class refTextType(GeneratedsSuper):
subclass = None
superclass = None
def __init__(self, refid=None, kindref=None, external=None, valueOf_='', mixedclass_=None, content_=None):
self.refid = refid
self.kindref = kindref
self.external = external
if mixedclass_ is None:
self.mixedclass_ = MixedContainer
else:
self.mixedclass_ = mixedclass_
if content_ is None:
self.content_ = []
else:
self.content_ = content_
def factory(*args_, **kwargs_):
if refTextType.subclass:
return refTextType.subclass(*args_, **kwargs_)
else:
return refTextType(*args_, **kwargs_)
factory = staticmethod(factory)
def get_refid(self): return self.refid
def set_refid(self, refid): self.refid = refid
def get_kindref(self): return self.kindref
def set_kindref(self, kindref): self.kindref = kindref
def get_external(self): return self.external
def set_external(self, external): self.external = external
def getValueOf_(self): return self.valueOf_
def setValueOf_(self, valueOf_): self.valueOf_ = valueOf_
def hasContent_(self):
if (
self.valueOf_ is not None
):
return True
else:
return False
def build(self, node_):
attrs = node_.attributes
self.buildAttributes(attrs)
self.valueOf_ = ''
for child_ in node_.childNodes:
nodeName_ = child_.nodeName.split(':')[-1]
self.buildChildren(child_, nodeName_)
def buildAttributes(self, attrs):
if attrs.get('refid'):
self.refid = attrs.get('refid').value
if attrs.get('kindref'):
self.kindref = attrs.get('kindref').value
if attrs.get('external'):
self.external = attrs.get('external').value
def buildChildren(self, child_, nodeName_):
if child_.nodeType == Node.TEXT_NODE:
obj_ = self.mixedclass_(MixedContainer.CategoryText,
MixedContainer.TypeNone, '', child_.nodeValue)
self.content_.append(obj_)
if child_.nodeType == Node.TEXT_NODE:
self.valueOf_ += child_.nodeValue
elif child_.nodeType == Node.CDATA_SECTION_NODE:
self.valueOf_ += '![CDATA['+child_.nodeValue+']]'
# end class refTextType
class sectiondefType(GeneratedsSuper):
subclass = None
superclass = None
def __init__(self, kind=None, header=None, description=None, memberdef=None):
self.kind = kind
self.header = header
self.description = description
if memberdef is None:
self.memberdef = []
else:
self.memberdef = memberdef
def factory(*args_, **kwargs_):
if sectiondefType.subclass:
return sectiondefType.subclass(*args_, **kwargs_)
else:
return sectiondefType(*args_, **kwargs_)
factory = staticmethod(factory)
def get_header(self): return self.header
def set_header(self, header): self.header = header
def get_description(self): return self.description
def set_description(self, description): self.description = description
def get_memberdef(self): return self.memberdef
def set_memberdef(self, memberdef): self.memberdef = memberdef
def add_memberdef(self, value): self.memberdef.append(value)
def insert_memberdef(self, index, value): self.memberdef[index] = value
def get_kind(self): return self.kind
def set_kind(self, kind): self.kind = kind
def hasContent_(self):
if (
self.header is not None or
self.description is not None or
self.memberdef is not None
):
return True
else:
return False
def build(self, node_):
attrs = node_.attributes
self.buildAttributes(attrs)
for child_ in node_.childNodes:
nodeName_ = child_.nodeName.split(':')[-1]
self.buildChildren(child_, nodeName_)
def buildAttributes(self, attrs):
if attrs.get('kind'):
self.kind = attrs.get('kind').value
def buildChildren(self, child_, nodeName_):
if child_.nodeType == Node.ELEMENT_NODE and \
nodeName_ == 'header':
header_ = ''
for text__content_ in child_.childNodes:
header_ += text__content_.nodeValue
self.header = header_
elif child_.nodeType == Node.ELEMENT_NODE and \
nodeName_ == 'description':
obj_ = descriptionType.factory()
obj_.build(child_)
self.set_description(obj_)
elif child_.nodeType == Node.ELEMENT_NODE and \
nodeName_ == 'memberdef':
obj_ = memberdefType.factory()
obj_.build(child_)
self.memberdef.append(obj_)
# end class sectiondefType
class memberdefType(GeneratedsSuper):
subclass = None
superclass = None
def __init__(self, initonly=None, kind=None, volatile=None, const=None, raisexx=None, virt=None, readable=None, prot=None, explicit=None, new=None, final=None, writable=None, add=None, static=None, remove=None, sealed=None, mutable=None, gettable=None, inline=None, settable=None, id=None, templateparamlist=None, type_=None, definition=None, argsstring=None, name=None, read=None, write=None, bitfield=None, reimplements=None, reimplementedby=None, param=None, enumvalue=None, initializer=None, exceptions=None, briefdescription=None, detaileddescription=None, inbodydescription=None, location=None, references=None, referencedby=None):
self.initonly = initonly
self.kind = kind
self.volatile = volatile
self.const = const
self.raisexx = raisexx
self.virt = virt
self.readable = readable
self.prot = prot
self.explicit = explicit
self.new = new
self.final = final
self.writable = writable
self.add = add
self.static = static
self.remove = remove
self.sealed = sealed
self.mutable = mutable
self.gettable = gettable
self.inline = inline
self.settable = settable
self.id = id
self.templateparamlist = templateparamlist
self.type_ = type_
self.definition = definition
self.argsstring = argsstring
self.name = name
self.read = read
self.write = write
self.bitfield = bitfield
if reimplements is None:
self.reimplements = []
else:
self.reimplements = reimplements
if reimplementedby is None:
self.reimplementedby = []
else:
self.reimplementedby = reimplementedby
if param is None:
self.param = []
else:
self.param = param
if enumvalue is None:
self.enumvalue = []
else:
self.enumvalue = enumvalue
self.initializer = initializer
self.exceptions = exceptions
self.briefdescription = briefdescription
self.detaileddescription = detaileddescription
self.inbodydescription = inbodydescription
self.location = location
if references is None:
self.references = []
else:
self.references = references
if referencedby is None:
self.referencedby = []
else:
self.referencedby = referencedby
def factory(*args_, **kwargs_):
if memberdefType.subclass:
return memberdefType.subclass(*args_, **kwargs_)
else:
return memberdefType(*args_, **kwargs_)
factory = staticmethod(factory)
def get_templateparamlist(self): return self.templateparamlist
def set_templateparamlist(self, templateparamlist): self.templateparamlist = templateparamlist
def get_type(self): return self.type_
def set_type(self, type_): self.type_ = type_
def get_definition(self): return self.definition
def set_definition(self, definition): self.definition = definition
def get_argsstring(self): return self.argsstring
def set_argsstring(self, argsstring): self.argsstring = argsstring
def get_name(self): return self.name
def set_name(self, name): self.name = name
def get_read(self): return self.read
def set_read(self, read): self.read = read
def get_write(self): return self.write
def set_write(self, write): self.write = write
def get_bitfield(self): return self.bitfield
def set_bitfield(self, bitfield): self.bitfield = bitfield
def get_reimplements(self): return self.reimplements
def set_reimplements(self, reimplements): self.reimplements = reimplements
def add_reimplements(self, value): self.reimplements.append(value)
def insert_reimplements(self, index, value): self.reimplements[index] = value
def get_reimplementedby(self): return self.reimplementedby
def set_reimplementedby(self, reimplementedby): self.reimplementedby = reimplementedby
def add_reimplementedby(self, value): self.reimplementedby.append(value)
def insert_reimplementedby(self, index, value): self.reimplementedby[index] = value
def get_param(self): return self.param
def set_param(self, param): self.param = param
def add_param(self, value): self.param.append(value)
def insert_param(self, index, value): self.param[index] = value
def get_enumvalue(self): return self.enumvalue
def set_enumvalue(self, enumvalue): self.enumvalue = enumvalue
def add_enumvalue(self, value): self.enumvalue.append(value)
def insert_enumvalue(self, index, value): self.enumvalue[index] = value
def get_initializer(self): return self.initializer
def set_initializer(self, initializer): self.initializer = initializer
def get_exceptions(self): return self.exceptions
def set_exceptions(self, exceptions): self.exceptions = exceptions
def get_briefdescription(self): return self.briefdescription
def set_briefdescription(self, briefdescription): self.briefdescription = briefdescription
def get_detaileddescription(self): return self.detaileddescription
def set_detaileddescription(self, detaileddescription): self.detaileddescription = detaileddescription
def get_inbodydescription(self): return self.inbodydescription
def set_inbodydescription(self, inbodydescription): self.inbodydescription = inbodydescription
def get_location(self): return self.location
def set_location(self, location): self.location = location
def get_references(self): return self.references
def set_references(self, references): self.references = references
def add_references(self, value): self.references.append(value)
def insert_references(self, index, value): self.references[index] = value
def get_referencedby(self): return self.referencedby
def set_referencedby(self, referencedby): self.referencedby = referencedby
def add_referencedby(self, value): self.referencedby.append(value)
def insert_referencedby(self, index, value): self.referencedby[index] = value
def get_initonly(self): return self.initonly
def set_initonly(self, initonly): self.initonly = initonly
def get_kind(self): return self.kind
def set_kind(self, kind): self.kind = kind
def get_volatile(self): return self.volatile
def set_volatile(self, volatile): self.volatile = volatile
def get_const(self): return self.const
def set_const(self, const): self.const = const
def get_raise(self): return self.raisexx
def set_raise(self, raisexx): self.raisexx = raisexx
def get_virt(self): return self.virt
def set_virt(self, virt): self.virt = virt
def get_readable(self): return self.readable
def set_readable(self, readable): self.readable = readable
def get_prot(self): return self.prot
def set_prot(self, prot): self.prot = prot
def get_explicit(self): return self.explicit
def set_explicit(self, explicit): self.explicit = explicit
def get_new(self): return self.new
def set_new(self, new): self.new = new
def get_final(self): return self.final
def set_final(self, final): self.final = final
def get_writable(self): return self.writable
def set_writable(self, writable): self.writable = writable
def get_add(self): return self.add
def set_add(self, add): self.add = add
def get_static(self): return self.static
def set_static(self, static): self.static = static
def get_remove(self): return self.remove
def set_remove(self, remove): self.remove = remove
def get_sealed(self): return self.sealed
def set_sealed(self, sealed): self.sealed = sealed
def get_mutable(self): return self.mutable
def set_mutable(self, mutable): self.mutable = mutable
def get_gettable(self): return self.gettable
def set_gettable(self, gettable): self.gettable = gettable
def get_inline(self): return self.inline
def set_inline(self, inline): self.inline = inline
def get_settable(self): return self.settable
def set_settable(self, settable): self.settable = settable
def get_id(self): return self.id
def set_id(self, id): self.id = id
def hasContent_(self):
if (
self.templateparamlist is not None or
self.type_ is not None or
self.definition is not None or
self.argsstring is not None or
self.name is not None or
self.read is not None or
self.write is not None or
self.bitfield is not None or
self.reimplements is not None or
self.reimplementedby is not None or
self.param is not None or
self.enumvalue is not None or
self.initializer is not None or
self.exceptions is not None or
self.briefdescription is not None or
self.detaileddescription is not None or
self.inbodydescription is not None or
self.location is not None or
self.references is not None or
self.referencedby is not None
):
return True
else:
return False
def build(self, node_):
attrs = node_.attributes
self.buildAttributes(attrs)
for child_ in node_.childNodes:
nodeName_ = child_.nodeName.split(':')[-1]
self.buildChildren(child_, nodeName_)
def buildAttributes(self, attrs):
if attrs.get('initonly'):
self.initonly = attrs.get('initonly').value
if attrs.get('kind'):
self.kind = attrs.get('kind').value
if attrs.get('volatile'):
self.volatile = attrs.get('volatile').value
if attrs.get('const'):
self.const = attrs.get('const').value
if attrs.get('raise'):
self.raisexx = attrs.get('raise').value
if attrs.get('virt'):
self.virt = attrs.get('virt').value
if attrs.get('readable'):
self.readable = attrs.get('readable').value
if attrs.get('prot'):
self.prot = attrs.get('prot').value
if attrs.get('explicit'):
self.explicit = attrs.get('explicit').value
if attrs.get('new'):
self.new = attrs.get('new').value
if attrs.get('final'):
self.final = attrs.get('final').value
if attrs.get('writable'):
self.writable = attrs.get('writable').value
if attrs.get('add'):
self.add = attrs.get('add').value
if attrs.get('static'):
self.static = attrs.get('static').value
if attrs.get('remove'):
self.remove = attrs.get('remove').value
if attrs.get('sealed'):
self.sealed = attrs.get('sealed').value
if attrs.get('mutable'):
self.mutable = attrs.get('mutable').value
if attrs.get('gettable'):
self.gettable = attrs.get('gettable').value
if attrs.get('inline'):
self.inline = attrs.get('inline').value
if attrs.get('settable'):
self.settable = attrs.get('settable').value
if attrs.get('id'):
self.id = attrs.get('id').value
def buildChildren(self, child_, nodeName_):
if child_.nodeType == Node.ELEMENT_NODE and \
nodeName_ == 'templateparamlist':
obj_ = templateparamlistType.factory()
obj_.build(child_)
self.set_templateparamlist(obj_)
elif child_.nodeType == Node.ELEMENT_NODE and \
nodeName_ == 'type':
obj_ = linkedTextType.factory()
obj_.build(child_)
self.set_type(obj_)
elif child_.nodeType == Node.ELEMENT_NODE and \
nodeName_ == 'definition':
definition_ = ''
for text__content_ in child_.childNodes:
definition_ += text__content_.nodeValue
self.definition = definition_
elif child_.nodeType == Node.ELEMENT_NODE and \
nodeName_ == 'argsstring':
argsstring_ = ''
for text__content_ in child_.childNodes:
argsstring_ += text__content_.nodeValue
self.argsstring = argsstring_
elif child_.nodeType == Node.ELEMENT_NODE and \
nodeName_ == 'name':
name_ = ''
for text__content_ in child_.childNodes:
name_ += text__content_.nodeValue
self.name = name_
elif child_.nodeType == Node.ELEMENT_NODE and \
nodeName_ == 'read':
read_ = ''
for text__content_ in child_.childNodes:
read_ += text__content_.nodeValue
self.read = read_
elif child_.nodeType == Node.ELEMENT_NODE and \
nodeName_ == 'write':
write_ = ''
for text__content_ in child_.childNodes:
write_ += text__content_.nodeValue
self.write = write_
elif child_.nodeType == Node.ELEMENT_NODE and \
nodeName_ == 'bitfield':
bitfield_ = ''
for text__content_ in child_.childNodes:
bitfield_ += text__content_.nodeValue
self.bitfield = bitfield_
elif child_.nodeType == Node.ELEMENT_NODE and \
nodeName_ == 'reimplements':
obj_ = reimplementType.factory()
obj_.build(child_)
self.reimplements.append(obj_)
elif child_.nodeType == Node.ELEMENT_NODE and \
nodeName_ == 'reimplementedby':
obj_ = reimplementType.factory()
obj_.build(child_)
self.reimplementedby.append(obj_)
elif child_.nodeType == Node.ELEMENT_NODE and \
nodeName_ == 'param':
obj_ = paramType.factory()
obj_.build(child_)
self.param.append(obj_)
elif child_.nodeType == Node.ELEMENT_NODE and \
nodeName_ == 'enumvalue':
obj_ = enumvalueType.factory()
obj_.build(child_)
self.enumvalue.append(obj_)
elif child_.nodeType == Node.ELEMENT_NODE and \
nodeName_ == 'initializer':
obj_ = linkedTextType.factory()
obj_.build(child_)
self.set_initializer(obj_)
elif child_.nodeType == Node.ELEMENT_NODE and \
nodeName_ == 'exceptions':
obj_ = linkedTextType.factory()
obj_.build(child_)
self.set_exceptions(obj_)
elif child_.nodeType == Node.ELEMENT_NODE and \
nodeName_ == 'briefdescription':
obj_ = descriptionType.factory()
obj_.build(child_)
self.set_briefdescription(obj_)
elif child_.nodeType == Node.ELEMENT_NODE and \
nodeName_ == 'detaileddescription':
obj_ = descriptionType.factory()
obj_.build(child_)
self.set_detaileddescription(obj_)
elif child_.nodeType == Node.ELEMENT_NODE and \
nodeName_ == 'inbodydescription':
obj_ = descriptionType.factory()
obj_.build(child_)
self.set_inbodydescription(obj_)
elif child_.nodeType == Node.ELEMENT_NODE and \
nodeName_ == 'location':
obj_ = locationType.factory()
obj_.build(child_)
self.set_location(obj_)
elif child_.nodeType == Node.ELEMENT_NODE and \
nodeName_ == 'references':
obj_ = referenceType.factory()
obj_.build(child_)
self.references.append(obj_)
elif child_.nodeType == Node.ELEMENT_NODE and \
nodeName_ == 'referencedby':
obj_ = referenceType.factory()
obj_.build(child_)
self.referencedby.append(obj_)
# end class memberdefType
class definition(GeneratedsSuper):
subclass = None
superclass = None
def __init__(self, valueOf_=''):
self.valueOf_ = valueOf_
def factory(*args_, **kwargs_):
if definition.subclass:
return definition.subclass(*args_, **kwargs_)
else:
return definition(*args_, **kwargs_)
factory = staticmethod(factory)
def getValueOf_(self): return self.valueOf_
def setValueOf_(self, valueOf_): self.valueOf_ = valueOf_
def hasContent_(self):
if (
self.valueOf_ is not None
):
return True
else:
return False
def build(self, node_):
attrs = node_.attributes
self.buildAttributes(attrs)
self.valueOf_ = ''
for child_ in node_.childNodes:
nodeName_ = child_.nodeName.split(':')[-1]
self.buildChildren(child_, nodeName_)
def buildAttributes(self, attrs):
pass
def buildChildren(self, child_, nodeName_):
if child_.nodeType == Node.TEXT_NODE:
self.valueOf_ += child_.nodeValue
elif child_.nodeType == Node.CDATA_SECTION_NODE:
self.valueOf_ += '![CDATA['+child_.nodeValue+']]'
# end class definition
class argsstring(GeneratedsSuper):
subclass = None
superclass = None
def __init__(self, valueOf_=''):
self.valueOf_ = valueOf_
def factory(*args_, **kwargs_):
if argsstring.subclass:
return argsstring.subclass(*args_, **kwargs_)
else:
return argsstring(*args_, **kwargs_)
factory = staticmethod(factory)
def getValueOf_(self): return self.valueOf_
def setValueOf_(self, valueOf_): self.valueOf_ = valueOf_
def export(self, outfile, level, namespace_='', name_='argsstring', namespacedef_=''):
showIndent(outfile, level)
outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, ))
self.exportAttributes(outfile, level, namespace_, name_='argsstring')
if self.hasContent_():
outfile.write('>\n')
self.exportChildren(outfile, level + 1, namespace_, name_)
showIndent(outfile, level)
outfile.write('</%s%s>\n' % (namespace_, name_))
else:
outfile.write(' />\n')
def hasContent_(self):
if (
self.valueOf_ is not None
):
return True
else:
return False
def build(self, node_):
attrs = node_.attributes
self.buildAttributes(attrs)
self.valueOf_ = ''
for child_ in node_.childNodes:
nodeName_ = child_.nodeName.split(':')[-1]
self.buildChildren(child_, nodeName_)
def buildAttributes(self, attrs):
pass
def buildChildren(self, child_, nodeName_):
if child_.nodeType == Node.TEXT_NODE:
self.valueOf_ += child_.nodeValue
elif child_.nodeType == Node.CDATA_SECTION_NODE:
self.valueOf_ += '![CDATA['+child_.nodeValue+']]'
# end class argsstring
class read(GeneratedsSuper):
subclass = None
superclass = None
def __init__(self, valueOf_=''):
self.valueOf_ = valueOf_
def factory(*args_, **kwargs_):
if read.subclass:
return read.subclass(*args_, **kwargs_)
else:
return read(*args_, **kwargs_)
factory = staticmethod(factory)
def getValueOf_(self): return self.valueOf_
def setValueOf_(self, valueOf_): self.valueOf_ = valueOf_
def hasContent_(self):
if (
self.valueOf_ is not None
):
return True
else:
return False
def build(self, node_):
attrs = node_.attributes
self.buildAttributes(attrs)
self.valueOf_ = ''
for child_ in node_.childNodes:
nodeName_ = child_.nodeName.split(':')[-1]
self.buildChildren(child_, nodeName_)
def buildAttributes(self, attrs):
pass
def buildChildren(self, child_, nodeName_):
if child_.nodeType == Node.TEXT_NODE:
self.valueOf_ += child_.nodeValue
elif child_.nodeType == Node.CDATA_SECTION_NODE:
self.valueOf_ += '![CDATA['+child_.nodeValue+']]'
# end class read
class write(GeneratedsSuper):
subclass = None
superclass = None
def __init__(self, valueOf_=''):
self.valueOf_ = valueOf_
def factory(*args_, **kwargs_):
if write.subclass:
return write.subclass(*args_, **kwargs_)
else:
return write(*args_, **kwargs_)
factory = staticmethod(factory)
def getValueOf_(self): return self.valueOf_
def setValueOf_(self, valueOf_): self.valueOf_ = valueOf_
def hasContent_(self):
if (
self.valueOf_ is not None
):
return True
else:
return False
def build(self, node_):
attrs = node_.attributes
self.buildAttributes(attrs)
self.valueOf_ = ''
for child_ in node_.childNodes:
nodeName_ = child_.nodeName.split(':')[-1]
self.buildChildren(child_, nodeName_)
def buildAttributes(self, attrs):
pass
def buildChildren(self, child_, nodeName_):
if child_.nodeType == Node.TEXT_NODE:
self.valueOf_ += child_.nodeValue
elif child_.nodeType == Node.CDATA_SECTION_NODE:
self.valueOf_ += '![CDATA['+child_.nodeValue+']]'
# end class write
class bitfield(GeneratedsSuper):
subclass = None
superclass = None
def __init__(self, valueOf_=''):
self.valueOf_ = valueOf_
def factory(*args_, **kwargs_):
if bitfield.subclass:
return bitfield.subclass(*args_, **kwargs_)
else:
return bitfield(*args_, **kwargs_)
factory = staticmethod(factory)
def getValueOf_(self): return self.valueOf_
def setValueOf_(self, valueOf_): self.valueOf_ = valueOf_
def hasContent_(self):
if (
self.valueOf_ is not None
):
return True
else:
return False
def build(self, node_):
attrs = node_.attributes
self.buildAttributes(attrs)
self.valueOf_ = ''
for child_ in node_.childNodes:
nodeName_ = child_.nodeName.split(':')[-1]
self.buildChildren(child_, nodeName_)
def buildAttributes(self, attrs):
pass
def buildChildren(self, child_, nodeName_):
if child_.nodeType == Node.TEXT_NODE:
self.valueOf_ += child_.nodeValue
elif child_.nodeType == Node.CDATA_SECTION_NODE:
self.valueOf_ += '![CDATA['+child_.nodeValue+']]'
# end class bitfield
class descriptionType(GeneratedsSuper):
subclass = None
superclass = None
def __init__(self, title=None, para=None, sect1=None, internal=None, mixedclass_=None, content_=None):
if mixedclass_ is None:
self.mixedclass_ = MixedContainer
else:
self.mixedclass_ = mixedclass_
if content_ is None:
self.content_ = []
else:
self.content_ = content_
def factory(*args_, **kwargs_):
if descriptionType.subclass:
return descriptionType.subclass(*args_, **kwargs_)
else:
return descriptionType(*args_, **kwargs_)
factory = staticmethod(factory)
def get_title(self): return self.title
def set_title(self, title): self.title = title
def get_para(self): return self.para
def set_para(self, para): self.para = para
def add_para(self, value): self.para.append(value)
def insert_para(self, index, value): self.para[index] = value
def get_sect1(self): return self.sect1
def set_sect1(self, sect1): self.sect1 = sect1
def add_sect1(self, value): self.sect1.append(value)
def insert_sect1(self, index, value): self.sect1[index] = value
def get_internal(self): return self.internal
def set_internal(self, internal): self.internal = internal
def hasContent_(self):
if (
self.title is not None or
self.para is not None or
self.sect1 is not None or
self.internal is not None
):
return True
else:
return False
def build(self, node_):
attrs = node_.attributes
self.buildAttributes(attrs)
for child_ in node_.childNodes:
nodeName_ = child_.nodeName.split(':')[-1]
self.buildChildren(child_, nodeName_)
def buildAttributes(self, attrs):
pass
def buildChildren(self, child_, nodeName_):
if child_.nodeType == Node.ELEMENT_NODE and \
nodeName_ == 'title':
childobj_ = docTitleType.factory()
childobj_.build(child_)
obj_ = self.mixedclass_(MixedContainer.CategoryComplex,
MixedContainer.TypeNone, 'title', childobj_)
self.content_.append(obj_)
elif child_.nodeType == Node.ELEMENT_NODE and \
nodeName_ == 'para':
childobj_ = docParaType.factory()
childobj_.build(child_)
obj_ = self.mixedclass_(MixedContainer.CategoryComplex,
MixedContainer.TypeNone, 'para', childobj_)
self.content_.append(obj_)
elif child_.nodeType == Node.ELEMENT_NODE and \
nodeName_ == 'sect1':
childobj_ = docSect1Type.factory()
childobj_.build(child_)
obj_ = self.mixedclass_(MixedContainer.CategoryComplex,
MixedContainer.TypeNone, 'sect1', childobj_)
self.content_.append(obj_)
elif child_.nodeType == Node.ELEMENT_NODE and \
nodeName_ == 'internal':
childobj_ = docInternalType.factory()
childobj_.build(child_)
obj_ = self.mixedclass_(MixedContainer.CategoryComplex,
MixedContainer.TypeNone, 'internal', childobj_)
self.content_.append(obj_)
# end class descriptionType
class enumvalueType(GeneratedsSuper):
subclass = None
superclass = None
def __init__(self, prot=None, id=None, name=None, initializer=None, briefdescription=None, detaileddescription=None, mixedclass_=None, content_=None):
self.prot = prot
self.id = id
if mixedclass_ is None:
self.mixedclass_ = MixedContainer
else:
self.mixedclass_ = mixedclass_
if content_ is None:
self.content_ = []
else:
self.content_ = content_
def factory(*args_, **kwargs_):
if enumvalueType.subclass:
return enumvalueType.subclass(*args_, **kwargs_)
else:
return enumvalueType(*args_, **kwargs_)
factory = staticmethod(factory)
def get_name(self): return self.name
def set_name(self, name): self.name = name
def get_initializer(self): return self.initializer
def set_initializer(self, initializer): self.initializer = initializer
def get_briefdescription(self): return self.briefdescription
def set_briefdescription(self, briefdescription): self.briefdescription = briefdescription
def get_detaileddescription(self): return self.detaileddescription
def set_detaileddescription(self, detaileddescription): self.detaileddescription = detaileddescription
def get_prot(self): return self.prot
def set_prot(self, prot): self.prot = prot
def get_id(self): return self.id
def set_id(self, id): self.id = id
def hasContent_(self):
if (
self.name is not None or
self.initializer is not None or
self.briefdescription is not None or
self.detaileddescription is not None
):
return True
else:
return False
def build(self, node_):
attrs = node_.attributes
self.buildAttributes(attrs)
for child_ in node_.childNodes:
nodeName_ = child_.nodeName.split(':')[-1]
self.buildChildren(child_, nodeName_)
def buildAttributes(self, attrs):
if attrs.get('prot'):
self.prot = attrs.get('prot').value
if attrs.get('id'):
self.id = attrs.get('id').value
def buildChildren(self, child_, nodeName_):
if child_.nodeType == Node.ELEMENT_NODE and \
nodeName_ == 'name':
value_ = []
for text_ in child_.childNodes:
value_.append(text_.nodeValue)
valuestr_ = ''.join(value_)
obj_ = self.mixedclass_(MixedContainer.CategorySimple,
MixedContainer.TypeString, 'name', valuestr_)
self.content_.append(obj_)
elif child_.nodeType == Node.ELEMENT_NODE and \
nodeName_ == 'initializer':
childobj_ = linkedTextType.factory()
childobj_.build(child_)
obj_ = self.mixedclass_(MixedContainer.CategoryComplex,
MixedContainer.TypeNone, 'initializer', childobj_)
self.content_.append(obj_)
elif child_.nodeType == Node.ELEMENT_NODE and \
nodeName_ == 'briefdescription':
childobj_ = descriptionType.factory()
childobj_.build(child_)
obj_ = self.mixedclass_(MixedContainer.CategoryComplex,
MixedContainer.TypeNone, 'briefdescription', childobj_)
self.content_.append(obj_)
elif child_.nodeType == Node.ELEMENT_NODE and \
nodeName_ == 'detaileddescription':
childobj_ = descriptionType.factory()
childobj_.build(child_)
obj_ = self.mixedclass_(MixedContainer.CategoryComplex,
MixedContainer.TypeNone, 'detaileddescription', childobj_)
self.content_.append(obj_)
elif child_.nodeType == Node.TEXT_NODE:
obj_ = self.mixedclass_(MixedContainer.CategoryText,
MixedContainer.TypeNone, '', child_.nodeValue)
self.content_.append(obj_)
# end class enumvalueType
class templateparamlistType(GeneratedsSuper):
subclass = None
superclass = None
def __init__(self, param=None):
if param is None:
self.param = []
else:
self.param = param
def factory(*args_, **kwargs_):
if templateparamlistType.subclass:
return templateparamlistType.subclass(*args_, **kwargs_)
else:
return templateparamlistType(*args_, **kwargs_)
factory = staticmethod(factory)
def get_param(self): return self.param
def set_param(self, param): self.param = param
def add_param(self, value): self.param.append(value)
def insert_param(self, index, value): self.param[index] = value
def hasContent_(self):
if (
self.param is not None
):
return True
else:
return False
def build(self, node_):
attrs = node_.attributes
self.buildAttributes(attrs)
for child_ in node_.childNodes:
nodeName_ = child_.nodeName.split(':')[-1]
self.buildChildren(child_, nodeName_)
def buildAttributes(self, attrs):
pass
def buildChildren(self, child_, nodeName_):
if child_.nodeType == Node.ELEMENT_NODE and \
nodeName_ == 'param':
obj_ = paramType.factory()
obj_.build(child_)
self.param.append(obj_)
# end class templateparamlistType
class paramType(GeneratedsSuper):
subclass = None
superclass = None
def __init__(self, type_=None, declname=None, defname=None, array=None, defval=None, briefdescription=None):
self.type_ = type_
self.declname = declname
self.defname = defname
self.array = array
self.defval = defval
self.briefdescription = briefdescription
def factory(*args_, **kwargs_):
if paramType.subclass:
return paramType.subclass(*args_, **kwargs_)
else:
return paramType(*args_, **kwargs_)
factory = staticmethod(factory)
def get_type(self): return self.type_
def set_type(self, type_): self.type_ = type_
def get_declname(self): return self.declname
def set_declname(self, declname): self.declname = declname
def get_defname(self): return self.defname
def set_defname(self, defname): self.defname = defname
def get_array(self): return self.array
def set_array(self, array): self.array = array
def get_defval(self): return self.defval
def set_defval(self, defval): self.defval = defval
def get_briefdescription(self): return self.briefdescription
def set_briefdescription(self, briefdescription): self.briefdescription = briefdescription
def hasContent_(self):
if (
self.type_ is not None or
self.declname is not None or
self.defname is not None or
self.array is not None or
self.defval is not None or
self.briefdescription is not None
):
return True
else:
return False
def build(self, node_):
attrs = node_.attributes
self.buildAttributes(attrs)
for child_ in node_.childNodes:
nodeName_ = child_.nodeName.split(':')[-1]
self.buildChildren(child_, nodeName_)
def buildAttributes(self, attrs):
pass
def buildChildren(self, child_, nodeName_):
if child_.nodeType == Node.ELEMENT_NODE and \
nodeName_ == 'type':
obj_ = linkedTextType.factory()
obj_.build(child_)
self.set_type(obj_)
elif child_.nodeType == Node.ELEMENT_NODE and \
nodeName_ == 'declname':
declname_ = ''
for text__content_ in child_.childNodes:
declname_ += text__content_.nodeValue
self.declname = declname_
elif child_.nodeType == Node.ELEMENT_NODE and \
nodeName_ == 'defname':
defname_ = ''
for text__content_ in child_.childNodes:
defname_ += text__content_.nodeValue
self.defname = defname_
elif child_.nodeType == Node.ELEMENT_NODE and \
nodeName_ == 'array':
array_ = ''
for text__content_ in child_.childNodes:
array_ += text__content_.nodeValue
self.array = array_
elif child_.nodeType == Node.ELEMENT_NODE and \
nodeName_ == 'defval':
obj_ = linkedTextType.factory()
obj_.build(child_)
self.set_defval(obj_)
elif child_.nodeType == Node.ELEMENT_NODE and \
nodeName_ == 'briefdescription':
obj_ = descriptionType.factory()
obj_.build(child_)
self.set_briefdescription(obj_)
# end class paramType
class declname(GeneratedsSuper):
subclass = None
superclass = None
def __init__(self, valueOf_=''):
self.valueOf_ = valueOf_
def factory(*args_, **kwargs_):
if declname.subclass:
return declname.subclass(*args_, **kwargs_)
else:
return declname(*args_, **kwargs_)
factory = staticmethod(factory)
def getValueOf_(self): return self.valueOf_
def setValueOf_(self, valueOf_): self.valueOf_ = valueOf_
def hasContent_(self):
if (
self.valueOf_ is not None
):
return True
else:
return False
def build(self, node_):
attrs = node_.attributes
self.buildAttributes(attrs)
self.valueOf_ = ''
for child_ in node_.childNodes:
nodeName_ = child_.nodeName.split(':')[-1]
self.buildChildren(child_, nodeName_)
def buildAttributes(self, attrs):
pass
def buildChildren(self, child_, nodeName_):
if child_.nodeType == Node.TEXT_NODE:
self.valueOf_ += child_.nodeValue
elif child_.nodeType == Node.CDATA_SECTION_NODE:
self.valueOf_ += '![CDATA['+child_.nodeValue+']]'
# end class declname
class defname(GeneratedsSuper):
subclass = None
superclass = None
def __init__(self, valueOf_=''):
self.valueOf_ = valueOf_
def factory(*args_, **kwargs_):
if defname.subclass:
return defname.subclass(*args_, **kwargs_)
else:
return defname(*args_, **kwargs_)
factory = staticmethod(factory)
def getValueOf_(self): return self.valueOf_
def setValueOf_(self, valueOf_): self.valueOf_ = valueOf_
def hasContent_(self):
if (
self.valueOf_ is not None
):
return True
else:
return False
def build(self, node_):
attrs = node_.attributes
self.buildAttributes(attrs)
self.valueOf_ = ''
for child_ in node_.childNodes:
nodeName_ = child_.nodeName.split(':')[-1]
self.buildChildren(child_, nodeName_)
def buildAttributes(self, attrs):
pass
def buildChildren(self, child_, nodeName_):
if child_.nodeType == Node.TEXT_NODE:
self.valueOf_ += child_.nodeValue
elif child_.nodeType == Node.CDATA_SECTION_NODE:
self.valueOf_ += '![CDATA['+child_.nodeValue+']]'
# end class defname
class array(GeneratedsSuper):
subclass = None
superclass = None
def __init__(self, valueOf_=''):
self.valueOf_ = valueOf_
def factory(*args_, **kwargs_):
if array.subclass:
return array.subclass(*args_, **kwargs_)
else:
return array(*args_, **kwargs_)
factory = staticmethod(factory)
def getValueOf_(self): return self.valueOf_
def setValueOf_(self, valueOf_): self.valueOf_ = valueOf_
def hasContent_(self):
if (
self.valueOf_ is not None
):
return True
else:
return False
def build(self, node_):
attrs = node_.attributes
self.buildAttributes(attrs)
self.valueOf_ = ''
for child_ in node_.childNodes:
nodeName_ = child_.nodeName.split(':')[-1]
self.buildChildren(child_, nodeName_)
def buildAttributes(self, attrs):
pass
def buildChildren(self, child_, nodeName_):
if child_.nodeType == Node.TEXT_NODE:
self.valueOf_ += child_.nodeValue
elif child_.nodeType == Node.CDATA_SECTION_NODE:
self.valueOf_ += '![CDATA['+child_.nodeValue+']]'
# end class array
class linkedTextType(GeneratedsSuper):
subclass = None
superclass = None
def __init__(self, ref=None, mixedclass_=None, content_=None):
if mixedclass_ is None:
self.mixedclass_ = MixedContainer
else:
self.mixedclass_ = mixedclass_
if content_ is None:
self.content_ = []
else:
self.content_ = content_
def factory(*args_, **kwargs_):
if linkedTextType.subclass:
return linkedTextType.subclass(*args_, **kwargs_)
else:
return linkedTextType(*args_, **kwargs_)
factory = staticmethod(factory)
def get_ref(self): return self.ref
def set_ref(self, ref): self.ref = ref
def add_ref(self, value): self.ref.append(value)
def insert_ref(self, index, value): self.ref[index] = value
def hasContent_(self):
if (
self.ref is not None
):
return True
else:
return False
def build(self, node_):
attrs = node_.attributes
self.buildAttributes(attrs)
for child_ in node_.childNodes:
nodeName_ = child_.nodeName.split(':')[-1]
self.buildChildren(child_, nodeName_)
def buildAttributes(self, attrs):
pass
def buildChildren(self, child_, nodeName_):
if child_.nodeType == Node.ELEMENT_NODE and \
nodeName_ == 'ref':
childobj_ = docRefTextType.factory()
childobj_.build(child_)
obj_ = self.mixedclass_(MixedContainer.CategoryComplex,
MixedContainer.TypeNone, 'ref', childobj_)
self.content_.append(obj_)
elif child_.nodeType == Node.TEXT_NODE:
obj_ = self.mixedclass_(MixedContainer.CategoryText,
MixedContainer.TypeNone, '', child_.nodeValue)
self.content_.append(obj_)
# end class linkedTextType
class graphType(GeneratedsSuper):
subclass = None
superclass = None
def __init__(self, node=None):
if node is None:
self.node = []
else:
self.node = node
def factory(*args_, **kwargs_):
if graphType.subclass:
return graphType.subclass(*args_, **kwargs_)
else:
return graphType(*args_, **kwargs_)
factory = staticmethod(factory)
def get_node(self): return self.node
def set_node(self, node): self.node = node
def add_node(self, value): self.node.append(value)
def insert_node(self, index, value): self.node[index] = value
def hasContent_(self):
if (
self.node is not None
):
return True
else:
return False
def build(self, node_):
attrs = node_.attributes
self.buildAttributes(attrs)
for child_ in node_.childNodes:
nodeName_ = child_.nodeName.split(':')[-1]
self.buildChildren(child_, nodeName_)
def buildAttributes(self, attrs):
pass
def buildChildren(self, child_, nodeName_):
if child_.nodeType == Node.ELEMENT_NODE and \
nodeName_ == 'node':
obj_ = nodeType.factory()
obj_.build(child_)
self.node.append(obj_)
# end class graphType
class nodeType(GeneratedsSuper):
subclass = None
superclass = None
def __init__(self, id=None, label=None, link=None, childnode=None):
self.id = id
self.label = label
self.link = link
if childnode is None:
self.childnode = []
else:
self.childnode = childnode
def factory(*args_, **kwargs_):
if nodeType.subclass:
return nodeType.subclass(*args_, **kwargs_)
else:
return nodeType(*args_, **kwargs_)
factory = staticmethod(factory)
def get_label(self): return self.label
def set_label(self, label): self.label = label
def get_link(self): return self.link
def set_link(self, link): self.link = link
def get_childnode(self): return self.childnode
def set_childnode(self, childnode): self.childnode = childnode
def add_childnode(self, value): self.childnode.append(value)
def insert_childnode(self, index, value): self.childnode[index] = value
def get_id(self): return self.id
def set_id(self, id): self.id = id
def hasContent_(self):
if (
self.label is not None or
self.link is not None or
self.childnode is not None
):
return True
else:
return False
def build(self, node_):
attrs = node_.attributes
self.buildAttributes(attrs)
for child_ in node_.childNodes:
nodeName_ = child_.nodeName.split(':')[-1]
self.buildChildren(child_, nodeName_)
def buildAttributes(self, attrs):
if attrs.get('id'):
self.id = attrs.get('id').value
def buildChildren(self, child_, nodeName_):
if child_.nodeType == Node.ELEMENT_NODE and \
nodeName_ == 'label':
label_ = ''
for text__content_ in child_.childNodes:
label_ += text__content_.nodeValue
self.label = label_
elif child_.nodeType == Node.ELEMENT_NODE and \
nodeName_ == 'link':
obj_ = linkType.factory()
obj_.build(child_)
self.set_link(obj_)
elif child_.nodeType == Node.ELEMENT_NODE and \
nodeName_ == 'childnode':
obj_ = childnodeType.factory()
obj_.build(child_)
self.childnode.append(obj_)
# end class nodeType
class label(GeneratedsSuper):
subclass = None
superclass = None
def __init__(self, valueOf_=''):
self.valueOf_ = valueOf_
def factory(*args_, **kwargs_):
if label.subclass:
return label.subclass(*args_, **kwargs_)
else:
return label(*args_, **kwargs_)
factory = staticmethod(factory)
def getValueOf_(self): return self.valueOf_
def setValueOf_(self, valueOf_): self.valueOf_ = valueOf_
def hasContent_(self):
if (
self.valueOf_ is not None
):
return True
else:
return False
def build(self, node_):
attrs = node_.attributes
self.buildAttributes(attrs)
self.valueOf_ = ''
for child_ in node_.childNodes:
nodeName_ = child_.nodeName.split(':')[-1]
self.buildChildren(child_, nodeName_)
def buildAttributes(self, attrs):
pass
def buildChildren(self, child_, nodeName_):
if child_.nodeType == Node.TEXT_NODE:
self.valueOf_ += child_.nodeValue
elif child_.nodeType == Node.CDATA_SECTION_NODE:
self.valueOf_ += '![CDATA['+child_.nodeValue+']]'
# end class label
class childnodeType(GeneratedsSuper):
subclass = None
superclass = None
def __init__(self, relation=None, refid=None, edgelabel=None):
self.relation = relation
self.refid = refid
if edgelabel is None:
self.edgelabel = []
else:
self.edgelabel = edgelabel
def factory(*args_, **kwargs_):
if childnodeType.subclass:
return childnodeType.subclass(*args_, **kwargs_)
else:
return childnodeType(*args_, **kwargs_)
factory = staticmethod(factory)
def get_edgelabel(self): return self.edgelabel
def set_edgelabel(self, edgelabel): self.edgelabel = edgelabel
def add_edgelabel(self, value): self.edgelabel.append(value)
def insert_edgelabel(self, index, value): self.edgelabel[index] = value
def get_relation(self): return self.relation
def set_relation(self, relation): self.relation = relation
def get_refid(self): return self.refid
def set_refid(self, refid): self.refid = refid
def export(self, outfile, level, namespace_='', name_='childnodeType', namespacedef_=''):
showIndent(outfile, level)
outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, ))
self.exportAttributes(outfile, level, namespace_, name_='childnodeType')
if self.hasContent_():
outfile.write('>\n')
self.exportChildren(outfile, level + 1, namespace_, name_)
showIndent(outfile, level)
outfile.write('</%s%s>\n' % (namespace_, name_))
else:
outfile.write(' />\n')
def exportAttributes(self, outfile, level, namespace_='', name_='childnodeType'):
if self.relation is not None:
outfile.write(' relation=%s' % (quote_attrib(self.relation), ))
if self.refid is not None:
outfile.write(' refid=%s' % (self.format_string(quote_attrib(self.refid).encode(ExternalEncoding), input_name='refid'), ))
def exportChildren(self, outfile, level, namespace_='', name_='childnodeType'):
for edgelabel_ in self.edgelabel:
showIndent(outfile, level)
outfile.write('<%sedgelabel>%s</%sedgelabel>\n' % (namespace_, self.format_string(quote_xml(edgelabel_).encode(ExternalEncoding), input_name='edgelabel'), namespace_))
def hasContent_(self):
if (
self.edgelabel is not None
):
return True
else:
return False
def build(self, node_):
attrs = node_.attributes
self.buildAttributes(attrs)
for child_ in node_.childNodes:
nodeName_ = child_.nodeName.split(':')[-1]
self.buildChildren(child_, nodeName_)
def buildAttributes(self, attrs):
if attrs.get('relation'):
self.relation = attrs.get('relation').value
if attrs.get('refid'):
self.refid = attrs.get('refid').value
def buildChildren(self, child_, nodeName_):
if child_.nodeType == Node.ELEMENT_NODE and \
nodeName_ == 'edgelabel':
edgelabel_ = ''
for text__content_ in child_.childNodes:
edgelabel_ += text__content_.nodeValue
self.edgelabel.append(edgelabel_)
# end class childnodeType
class edgelabel(GeneratedsSuper):
subclass = None
superclass = None
def __init__(self, valueOf_=''):
self.valueOf_ = valueOf_
def factory(*args_, **kwargs_):
if edgelabel.subclass:
return edgelabel.subclass(*args_, **kwargs_)
else:
return edgelabel(*args_, **kwargs_)
factory = staticmethod(factory)
def getValueOf_(self): return self.valueOf_
def setValueOf_(self, valueOf_): self.valueOf_ = valueOf_
def export(self, outfile, level, namespace_='', name_='edgelabel', namespacedef_=''):
showIndent(outfile, level)
outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, ))
self.exportAttributes(outfile, level, namespace_, name_='edgelabel')
if self.hasContent_():
outfile.write('>\n')
self.exportChildren(outfile, level + 1, namespace_, name_)
showIndent(outfile, level)
outfile.write('</%s%s>\n' % (namespace_, name_))
else:
outfile.write(' />\n')
def exportAttributes(self, outfile, level, namespace_='', name_='edgelabel'):
pass
def exportChildren(self, outfile, level, namespace_='', name_='edgelabel'):
if self.valueOf_.find('![CDATA')>-1:
value=quote_xml('%s' % self.valueOf_)
value=value.replace('![CDATA','<![CDATA')
value=value.replace(']]',']]>')
outfile.write(value)
else:
outfile.write(quote_xml('%s' % self.valueOf_))
def hasContent_(self):
if (
self.valueOf_ is not None
):
return True
else:
return False
def build(self, node_):
attrs = node_.attributes
self.buildAttributes(attrs)
self.valueOf_ = ''
for child_ in node_.childNodes:
nodeName_ = child_.nodeName.split(':')[-1]
self.buildChildren(child_, nodeName_)
def buildAttributes(self, attrs):
pass
def buildChildren(self, child_, nodeName_):
if child_.nodeType == Node.TEXT_NODE:
self.valueOf_ += child_.nodeValue
elif child_.nodeType == Node.CDATA_SECTION_NODE:
self.valueOf_ += '![CDATA['+child_.nodeValue+']]'
# end class edgelabel
class linkType(GeneratedsSuper):
subclass = None
superclass = None
def __init__(self, refid=None, external=None, valueOf_=''):
self.refid = refid
self.external = external
self.valueOf_ = valueOf_
def factory(*args_, **kwargs_):
if linkType.subclass:
return linkType.subclass(*args_, **kwargs_)
else:
return linkType(*args_, **kwargs_)
factory = staticmethod(factory)
def get_refid(self): return self.refid
def set_refid(self, refid): self.refid = refid
def get_external(self): return self.external
def set_external(self, external): self.external = external
def getValueOf_(self): return self.valueOf_
def setValueOf_(self, valueOf_): self.valueOf_ = valueOf_
def export(self, outfile, level, namespace_='', name_='linkType', namespacedef_=''):
showIndent(outfile, level)
outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, ))
self.exportAttributes(outfile, level, namespace_, name_='linkType')
if self.hasContent_():
outfile.write('>\n')
self.exportChildren(outfile, level + 1, namespace_, name_)
showIndent(outfile, level)
outfile.write('</%s%s>\n' % (namespace_, name_))
else:
outfile.write(' />\n')
def exportAttributes(self, outfile, level, namespace_='', name_='linkType'):
if self.refid is not None:
outfile.write(' refid=%s' % (self.format_string(quote_attrib(self.refid).encode(ExternalEncoding), input_name='refid'), ))
if self.external is not None:
outfile.write(' external=%s' % (self.format_string(quote_attrib(self.external).encode(ExternalEncoding), input_name='external'), ))
def exportChildren(self, outfile, level, namespace_='', name_='linkType'):
if self.valueOf_.find('![CDATA')>-1:
value=quote_xml('%s' % self.valueOf_)
value=value.replace('![CDATA','<![CDATA')
value=value.replace(']]',']]>')
outfile.write(value)
else:
outfile.write(quote_xml('%s' % self.valueOf_))
def hasContent_(self):
if (
self.valueOf_ is not None
):
return True
else:
return False
def build(self, node_):
attrs = node_.attributes
self.buildAttributes(attrs)
self.valueOf_ = ''
for child_ in node_.childNodes:
nodeName_ = child_.nodeName.split(':')[-1]
self.buildChildren(child_, nodeName_)
def buildAttributes(self, attrs):
if attrs.get('refid'):
self.refid = attrs.get('refid').value
if attrs.get('external'):
self.external = attrs.get('external').value
def buildChildren(self, child_, nodeName_):
if child_.nodeType == Node.TEXT_NODE:
self.valueOf_ += child_.nodeValue
elif child_.nodeType == Node.CDATA_SECTION_NODE:
self.valueOf_ += '![CDATA['+child_.nodeValue+']]'
# end class linkType
class listingType(GeneratedsSuper):
subclass = None
superclass = None
def __init__(self, codeline=None):
if codeline is None:
self.codeline = []
else:
self.codeline = codeline
def factory(*args_, **kwargs_):
if listingType.subclass:
return listingType.subclass(*args_, **kwargs_)
else:
return listingType(*args_, **kwargs_)
factory = staticmethod(factory)
def get_codeline(self): return self.codeline
def set_codeline(self, codeline): self.codeline = codeline
def add_codeline(self, value): self.codeline.append(value)
def insert_codeline(self, index, value): self.codeline[index] = value
def export(self, outfile, level, namespace_='', name_='listingType', namespacedef_=''):
showIndent(outfile, level)
outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, ))
self.exportAttributes(outfile, level, namespace_, name_='listingType')
if self.hasContent_():
outfile.write('>\n')
self.exportChildren(outfile, level + 1, namespace_, name_)
showIndent(outfile, level)
outfile.write('</%s%s>\n' % (namespace_, name_))
else:
outfile.write(' />\n')
def exportAttributes(self, outfile, level, namespace_='', name_='listingType'):
pass
def exportChildren(self, outfile, level, namespace_='', name_='listingType'):
for codeline_ in self.codeline:
codeline_.export(outfile, level, namespace_, name_='codeline')
def hasContent_(self):
if (
self.codeline is not None
):
return True
else:
return False
def build(self, node_):
attrs = node_.attributes
self.buildAttributes(attrs)
for child_ in node_.childNodes:
nodeName_ = child_.nodeName.split(':')[-1]
self.buildChildren(child_, nodeName_)
def buildAttributes(self, attrs):
pass
def buildChildren(self, child_, nodeName_):
if child_.nodeType == Node.ELEMENT_NODE and \
nodeName_ == 'codeline':
obj_ = codelineType.factory()
obj_.build(child_)
self.codeline.append(obj_)
# end class listingType
class codelineType(GeneratedsSuper):
subclass = None
superclass = None
def __init__(self, external=None, lineno=None, refkind=None, refid=None, highlight=None):
self.external = external
self.lineno = lineno
self.refkind = refkind
self.refid = refid
if highlight is None:
self.highlight = []
else:
self.highlight = highlight
def factory(*args_, **kwargs_):
if codelineType.subclass:
return codelineType.subclass(*args_, **kwargs_)
else:
return codelineType(*args_, **kwargs_)
factory = staticmethod(factory)
def get_highlight(self): return self.highlight
def set_highlight(self, highlight): self.highlight = highlight
def add_highlight(self, value): self.highlight.append(value)
def insert_highlight(self, index, value): self.highlight[index] = value
def get_external(self): return self.external
def set_external(self, external): self.external = external
def get_lineno(self): return self.lineno
def set_lineno(self, lineno): self.lineno = lineno
def get_refkind(self): return self.refkind
def set_refkind(self, refkind): self.refkind = refkind
def get_refid(self): return self.refid
def set_refid(self, refid): self.refid = refid
def export(self, outfile, level, namespace_='', name_='codelineType', namespacedef_=''):
showIndent(outfile, level)
outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, ))
self.exportAttributes(outfile, level, namespace_, name_='codelineType')
if self.hasContent_():
outfile.write('>\n')
self.exportChildren(outfile, level + 1, namespace_, name_)
showIndent(outfile, level)
outfile.write('</%s%s>\n' % (namespace_, name_))
else:
outfile.write(' />\n')
def exportAttributes(self, outfile, level, namespace_='', name_='codelineType'):
if self.external is not None:
outfile.write(' external=%s' % (quote_attrib(self.external), ))
if self.lineno is not None:
outfile.write(' lineno="%s"' % self.format_integer(self.lineno, input_name='lineno'))
if self.refkind is not None:
outfile.write(' refkind=%s' % (quote_attrib(self.refkind), ))
if self.refid is not None:
outfile.write(' refid=%s' % (self.format_string(quote_attrib(self.refid).encode(ExternalEncoding), input_name='refid'), ))
def exportChildren(self, outfile, level, namespace_='', name_='codelineType'):
for highlight_ in self.highlight:
highlight_.export(outfile, level, namespace_, name_='highlight')
def hasContent_(self):
if (
self.highlight is not None
):
return True
else:
return False
def build(self, node_):
attrs = node_.attributes
self.buildAttributes(attrs)
for child_ in node_.childNodes:
nodeName_ = child_.nodeName.split(':')[-1]
self.buildChildren(child_, nodeName_)
def buildAttributes(self, attrs):
if attrs.get('external'):
self.external = attrs.get('external').value
if attrs.get('lineno'):
try:
self.lineno = int(attrs.get('lineno').value)
except ValueError as exp:
raise ValueError('Bad integer attribute (lineno): %s' % exp)
if attrs.get('refkind'):
self.refkind = attrs.get('refkind').value
if attrs.get('refid'):
self.refid = attrs.get('refid').value
def buildChildren(self, child_, nodeName_):
if child_.nodeType == Node.ELEMENT_NODE and \
nodeName_ == 'highlight':
obj_ = highlightType.factory()
obj_.build(child_)
self.highlight.append(obj_)
# end class codelineType
class highlightType(GeneratedsSuper):
subclass = None
superclass = None
def __init__(self, classxx=None, sp=None, ref=None, mixedclass_=None, content_=None):
self.classxx = classxx
if mixedclass_ is None:
self.mixedclass_ = MixedContainer
else:
self.mixedclass_ = mixedclass_
if content_ is None:
self.content_ = []
else:
self.content_ = content_
def factory(*args_, **kwargs_):
if highlightType.subclass:
return highlightType.subclass(*args_, **kwargs_)
else:
return highlightType(*args_, **kwargs_)
factory = staticmethod(factory)
def get_sp(self): return self.sp
def set_sp(self, sp): self.sp = sp
def add_sp(self, value): self.sp.append(value)
def insert_sp(self, index, value): self.sp[index] = value
def get_ref(self): return self.ref
def set_ref(self, ref): self.ref = ref
def add_ref(self, value): self.ref.append(value)
def insert_ref(self, index, value): self.ref[index] = value
def get_class(self): return self.classxx
def set_class(self, classxx): self.classxx = classxx
def export(self, outfile, level, namespace_='', name_='highlightType', namespacedef_=''):
showIndent(outfile, level)
outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, ))
self.exportAttributes(outfile, level, namespace_, name_='highlightType')
outfile.write('>')
self.exportChildren(outfile, level + 1, namespace_, name_)
outfile.write('</%s%s>\n' % (namespace_, name_))
def exportAttributes(self, outfile, level, namespace_='', name_='highlightType'):
if self.classxx is not None:
outfile.write(' class=%s' % (quote_attrib(self.classxx), ))
def exportChildren(self, outfile, level, namespace_='', name_='highlightType'):
for item_ in self.content_:
item_.export(outfile, level, item_.name, namespace_)
def hasContent_(self):
if (
self.sp is not None or
self.ref is not None
):
return True
else:
return False
def build(self, node_):
attrs = node_.attributes
self.buildAttributes(attrs)
for child_ in node_.childNodes:
nodeName_ = child_.nodeName.split(':')[-1]
self.buildChildren(child_, nodeName_)
def buildAttributes(self, attrs):
if attrs.get('class'):
self.classxx = attrs.get('class').value
def buildChildren(self, child_, nodeName_):
if child_.nodeType == Node.ELEMENT_NODE and \
nodeName_ == 'sp':
value_ = []
for text_ in child_.childNodes:
value_.append(text_.nodeValue)
# We make this unicode so that our unicode renderer catch-all picks it up
# otherwise it would go through as 'str' and we'd have to pick it up too
valuestr_ = u' '
obj_ = self.mixedclass_(MixedContainer.CategorySimple,
MixedContainer.TypeString, 'sp', valuestr_)
self.content_.append(obj_)
elif child_.nodeType == Node.ELEMENT_NODE and \
nodeName_ == 'ref':
childobj_ = docRefTextType.factory()
childobj_.build(child_)
obj_ = self.mixedclass_(MixedContainer.CategoryComplex,
MixedContainer.TypeNone, 'ref', childobj_)
self.content_.append(obj_)
elif child_.nodeType == Node.TEXT_NODE:
obj_ = self.mixedclass_(MixedContainer.CategoryText,
MixedContainer.TypeNone, '', child_.nodeValue)
self.content_.append(obj_)
# end class highlightType
class sp(GeneratedsSuper):
subclass = None
superclass = None
def __init__(self, valueOf_=''):
self.valueOf_ = valueOf_
def factory(*args_, **kwargs_):
if sp.subclass:
return sp.subclass(*args_, **kwargs_)
else:
return sp(*args_, **kwargs_)
factory = staticmethod(factory)
def getValueOf_(self): return self.valueOf_
def setValueOf_(self, valueOf_): self.valueOf_ = valueOf_
def export(self, outfile, level, namespace_='', name_='sp', namespacedef_=''):
showIndent(outfile, level)
outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, ))
self.exportAttributes(outfile, level, namespace_, name_='sp')
if self.hasContent_():
outfile.write('>\n')
self.exportChildren(outfile, level + 1, namespace_, name_)
showIndent(outfile, level)
outfile.write('</%s%s>\n' % (namespace_, name_))
else:
outfile.write(' />\n')
def exportAttributes(self, outfile, level, namespace_='', name_='sp'):
pass
def exportChildren(self, outfile, level, namespace_='', name_='sp'):
if self.valueOf_.find('![CDATA')>-1:
value=quote_xml('%s' % self.valueOf_)
value=value.replace('![CDATA','<![CDATA')
value=value.replace(']]',']]>')
outfile.write(value)
else:
outfile.write(quote_xml('%s' % self.valueOf_))
def hasContent_(self):
if (
self.valueOf_ is not None
):
return True
else:
return False
def build(self, node_):
attrs = node_.attributes
self.buildAttributes(attrs)
self.valueOf_ = ''
for child_ in node_.childNodes:
nodeName_ = child_.nodeName.split(':')[-1]
self.buildChildren(child_, nodeName_)
def buildAttributes(self, attrs):
pass
def buildChildren(self, child_, nodeName_):
if child_.nodeType == Node.TEXT_NODE:
self.valueOf_ += child_.nodeValue
elif child_.nodeType == Node.CDATA_SECTION_NODE:
self.valueOf_ += '![CDATA['+child_.nodeValue+']]'
# end class sp
class referenceType(GeneratedsSuper):
subclass = None
superclass = None
def __init__(self, endline=None, startline=None, refid=None, compoundref=None, valueOf_='', mixedclass_=None, content_=None):
self.endline = endline
self.startline = startline
self.refid = refid
self.compoundref = compoundref
if mixedclass_ is None:
self.mixedclass_ = MixedContainer
else:
self.mixedclass_ = mixedclass_
if content_ is None:
self.content_ = []
else:
self.content_ = content_
def factory(*args_, **kwargs_):
if referenceType.subclass:
return referenceType.subclass(*args_, **kwargs_)
else:
return referenceType(*args_, **kwargs_)
factory = staticmethod(factory)
def get_endline(self): return self.endline
def set_endline(self, endline): self.endline = endline
def get_startline(self): return self.startline
def set_startline(self, startline): self.startline = startline
def get_refid(self): return self.refid
def set_refid(self, refid): self.refid = refid
def get_compoundref(self): return self.compoundref
def set_compoundref(self, compoundref): self.compoundref = compoundref
def getValueOf_(self): return self.valueOf_
def setValueOf_(self, valueOf_): self.valueOf_ = valueOf_
def export(self, outfile, level, namespace_='', name_='referenceType', namespacedef_=''):
showIndent(outfile, level)
outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, ))
self.exportAttributes(outfile, level, namespace_, name_='referenceType')
outfile.write('>')
self.exportChildren(outfile, level + 1, namespace_, name_)
outfile.write('</%s%s>\n' % (namespace_, name_))
def exportAttributes(self, outfile, level, namespace_='', name_='referenceType'):
if self.endline is not None:
outfile.write(' endline="%s"' % self.format_integer(self.endline, input_name='endline'))
if self.startline is not None:
outfile.write(' startline="%s"' % self.format_integer(self.startline, input_name='startline'))
if self.refid is not None:
outfile.write(' refid=%s' % (self.format_string(quote_attrib(self.refid).encode(ExternalEncoding), input_name='refid'), ))
if self.compoundref is not None:
outfile.write(' compoundref=%s' % (self.format_string(quote_attrib(self.compoundref).encode(ExternalEncoding), input_name='compoundref'), ))
def exportChildren(self, outfile, level, namespace_='', name_='referenceType'):
if self.valueOf_.find('![CDATA')>-1:
value=quote_xml('%s' % self.valueOf_)
value=value.replace('![CDATA','<![CDATA')
value=value.replace(']]',']]>')
outfile.write(value)
else:
outfile.write(quote_xml('%s' % self.valueOf_))
def hasContent_(self):
if (
self.valueOf_ is not None
):
return True
else:
return False
def build(self, node_):
attrs = node_.attributes
self.buildAttributes(attrs)
self.valueOf_ = ''
for child_ in node_.childNodes:
nodeName_ = child_.nodeName.split(':')[-1]
self.buildChildren(child_, nodeName_)
def buildAttributes(self, attrs):
if attrs.get('endline'):
try:
self.endline = int(attrs.get('endline').value)
except ValueError as exp:
raise ValueError('Bad integer attribute (endline): %s' % exp)
if attrs.get('startline'):
try:
self.startline = int(attrs.get('startline').value)
except ValueError as exp:
raise ValueError('Bad integer attribute (startline): %s' % exp)
if attrs.get('refid'):
self.refid = attrs.get('refid').value
if attrs.get('compoundref'):
self.compoundref = attrs.get('compoundref').value
def buildChildren(self, child_, nodeName_):
if child_.nodeType == Node.TEXT_NODE:
obj_ = self.mixedclass_(MixedContainer.CategoryText,
MixedContainer.TypeNone, '', child_.nodeValue)
self.content_.append(obj_)
if child_.nodeType == Node.TEXT_NODE:
self.valueOf_ += child_.nodeValue
elif child_.nodeType == Node.CDATA_SECTION_NODE:
self.valueOf_ += '![CDATA['+child_.nodeValue+']]'
# end class referenceType
class locationType(GeneratedsSuper):
subclass = None
superclass = None
def __init__(self, bodystart=None, line=None, bodyend=None, bodyfile=None, file=None, valueOf_=''):
self.bodystart = bodystart
self.line = line
self.bodyend = bodyend
self.bodyfile = bodyfile
self.file = file
self.valueOf_ = valueOf_
def factory(*args_, **kwargs_):
if locationType.subclass:
return locationType.subclass(*args_, **kwargs_)
else:
return locationType(*args_, **kwargs_)
factory = staticmethod(factory)
def get_bodystart(self): return self.bodystart
def set_bodystart(self, bodystart): self.bodystart = bodystart
def get_line(self): return self.line
def set_line(self, line): self.line = line
def get_bodyend(self): return self.bodyend
def set_bodyend(self, bodyend): self.bodyend = bodyend
def get_bodyfile(self): return self.bodyfile
def set_bodyfile(self, bodyfile): self.bodyfile = bodyfile
def get_file(self): return self.file
def set_file(self, file): self.file = file
def getValueOf_(self): return self.valueOf_
def setValueOf_(self, valueOf_): self.valueOf_ = valueOf_
def export(self, outfile, level, namespace_='', name_='locationType', namespacedef_=''):
showIndent(outfile, level)
outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, ))
self.exportAttributes(outfile, level, namespace_, name_='locationType')
if self.hasContent_():
outfile.write('>\n')
self.exportChildren(outfile, level + 1, namespace_, name_)
showIndent(outfile, level)
outfile.write('</%s%s>\n' % (namespace_, name_))
else:
outfile.write(' />\n')
def exportAttributes(self, outfile, level, namespace_='', name_='locationType'):
if self.bodystart is not None:
outfile.write(' bodystart="%s"' % self.format_integer(self.bodystart, input_name='bodystart'))
if self.line is not None:
outfile.write(' line="%s"' % self.format_integer(self.line, input_name='line'))
if self.bodyend is not None:
outfile.write(' bodyend="%s"' % self.format_integer(self.bodyend, input_name='bodyend'))
if self.bodyfile is not None:
outfile.write(' bodyfile=%s' % (self.format_string(quote_attrib(self.bodyfile).encode(ExternalEncoding), input_name='bodyfile'), ))
if self.file is not None:
outfile.write(' file=%s' % (self.format_string(quote_attrib(self.file).encode(ExternalEncoding), input_name='file'), ))
def exportChildren(self, outfile, level, namespace_='', name_='locationType'):
if self.valueOf_.find('![CDATA')>-1:
value=quote_xml('%s' % self.valueOf_)
value=value.replace('![CDATA','<![CDATA')
value=value.replace(']]',']]>')
outfile.write(value)
else:
outfile.write(quote_xml('%s' % self.valueOf_))
def hasContent_(self):
if (
self.valueOf_ is not None
):
return True
else:
return False
def build(self, node_):
attrs = node_.attributes
self.buildAttributes(attrs)
self.valueOf_ = ''
for child_ in node_.childNodes:
nodeName_ = child_.nodeName.split(':')[-1]
self.buildChildren(child_, nodeName_)
def buildAttributes(self, attrs):
if attrs.get('bodystart'):
try:
self.bodystart = int(attrs.get('bodystart').value)
except ValueError as exp:
raise ValueError('Bad integer attribute (bodystart): %s' % exp)
if attrs.get('line'):
try:
self.line = int(attrs.get('line').value)
except ValueError as exp:
raise ValueError('Bad integer attribute (line): %s' % exp)
if attrs.get('bodyend'):
try:
self.bodyend = int(attrs.get('bodyend').value)
except ValueError as exp:
raise ValueError('Bad integer attribute (bodyend): %s' % exp)
if attrs.get('bodyfile'):
self.bodyfile = attrs.get('bodyfile').value
if attrs.get('file'):
self.file = attrs.get('file').value
def buildChildren(self, child_, nodeName_):
if child_.nodeType == Node.TEXT_NODE:
self.valueOf_ += child_.nodeValue
elif child_.nodeType == Node.CDATA_SECTION_NODE:
self.valueOf_ += '![CDATA['+child_.nodeValue+']]'
# end class locationType
class docSect1Type(GeneratedsSuper):
subclass = None
superclass = None
def __init__(self, id=None, title=None, para=None, sect2=None, internal=None, mixedclass_=None, content_=None):
self.id = id
if mixedclass_ is None:
self.mixedclass_ = MixedContainer
else:
self.mixedclass_ = mixedclass_
if content_ is None:
self.content_ = []
else:
self.content_ = content_
def factory(*args_, **kwargs_):
if docSect1Type.subclass:
return docSect1Type.subclass(*args_, **kwargs_)
else:
return docSect1Type(*args_, **kwargs_)
factory = staticmethod(factory)
def get_title(self): return self.title
def set_title(self, title): self.title = title
def get_para(self): return self.para
def set_para(self, para): self.para = para
def add_para(self, value): self.para.append(value)
def insert_para(self, index, value): self.para[index] = value
def get_sect2(self): return self.sect2
def set_sect2(self, sect2): self.sect2 = sect2
def add_sect2(self, value): self.sect2.append(value)
def insert_sect2(self, index, value): self.sect2[index] = value
def get_internal(self): return self.internal
def set_internal(self, internal): self.internal = internal
def get_id(self): return self.id
def set_id(self, id): self.id = id
def export(self, outfile, level, namespace_='', name_='docSect1Type', namespacedef_=''):
showIndent(outfile, level)
outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, ))
self.exportAttributes(outfile, level, namespace_, name_='docSect1Type')
outfile.write('>')
self.exportChildren(outfile, level + 1, namespace_, name_)
outfile.write('</%s%s>\n' % (namespace_, name_))
def exportAttributes(self, outfile, level, namespace_='', name_='docSect1Type'):
if self.id is not None:
outfile.write(' id=%s' % (self.format_string(quote_attrib(self.id).encode(ExternalEncoding), input_name='id'), ))
def exportChildren(self, outfile, level, namespace_='', name_='docSect1Type'):
for item_ in self.content_:
item_.export(outfile, level, item_.name, namespace_)
def hasContent_(self):
if (
self.title is not None or
self.para is not None or
self.sect2 is not None or
self.internal is not None
):
return True
else:
return False
def build(self, node_):
attrs = node_.attributes
self.buildAttributes(attrs)
for child_ in node_.childNodes:
nodeName_ = child_.nodeName.split(':')[-1]
self.buildChildren(child_, nodeName_)
def buildAttributes(self, attrs):
if attrs.get('id'):
self.id = attrs.get('id').value
def buildChildren(self, child_, nodeName_):
if child_.nodeType == Node.ELEMENT_NODE and \
nodeName_ == 'title':
childobj_ = docTitleType.factory()
childobj_.build(child_)
obj_ = self.mixedclass_(MixedContainer.CategoryComplex,
MixedContainer.TypeNone, 'title', childobj_)
self.content_.append(obj_)
elif child_.nodeType == Node.ELEMENT_NODE and \
nodeName_ == 'para':
childobj_ = docParaType.factory()
childobj_.build(child_)
obj_ = self.mixedclass_(MixedContainer.CategoryComplex,
MixedContainer.TypeNone, 'para', childobj_)
self.content_.append(obj_)
elif child_.nodeType == Node.ELEMENT_NODE and \
nodeName_ == 'sect2':
childobj_ = docSect2Type.factory()
childobj_.build(child_)
obj_ = self.mixedclass_(MixedContainer.CategoryComplex,
MixedContainer.TypeNone, 'sect2', childobj_)
self.content_.append(obj_)
elif child_.nodeType == Node.ELEMENT_NODE and \
nodeName_ == 'internal':
childobj_ = docInternalS1Type.factory()
childobj_.build(child_)
obj_ = self.mixedclass_(MixedContainer.CategoryComplex,
MixedContainer.TypeNone, 'internal', childobj_)
self.content_.append(obj_)
elif child_.nodeType == Node.TEXT_NODE:
obj_ = self.mixedclass_(MixedContainer.CategoryText,
MixedContainer.TypeNone, '', child_.nodeValue)
self.content_.append(obj_)
# end class docSect1Type
class docSect2Type(GeneratedsSuper):
subclass = None
superclass = None
def __init__(self, id=None, title=None, para=None, sect3=None, internal=None, mixedclass_=None, content_=None):
self.id = id
if mixedclass_ is None:
self.mixedclass_ = MixedContainer
else:
self.mixedclass_ = mixedclass_
if content_ is None:
self.content_ = []
else:
self.content_ = content_
def factory(*args_, **kwargs_):
if docSect2Type.subclass:
return docSect2Type.subclass(*args_, **kwargs_)
else:
return docSect2Type(*args_, **kwargs_)
factory = staticmethod(factory)
def get_title(self): return self.title
def set_title(self, title): self.title = title
def get_para(self): return self.para
def set_para(self, para): self.para = para
def add_para(self, value): self.para.append(value)
def insert_para(self, index, value): self.para[index] = value
def get_sect3(self): return self.sect3
def set_sect3(self, sect3): self.sect3 = sect3
def add_sect3(self, value): self.sect3.append(value)
def insert_sect3(self, index, value): self.sect3[index] = value
def get_internal(self): return self.internal
def set_internal(self, internal): self.internal = internal
def get_id(self): return self.id
def set_id(self, id): self.id = id
def export(self, outfile, level, namespace_='', name_='docSect2Type', namespacedef_=''):
showIndent(outfile, level)
outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, ))
self.exportAttributes(outfile, level, namespace_, name_='docSect2Type')
outfile.write('>')
self.exportChildren(outfile, level + 1, namespace_, name_)
outfile.write('</%s%s>\n' % (namespace_, name_))
def exportAttributes(self, outfile, level, namespace_='', name_='docSect2Type'):
if self.id is not None:
outfile.write(' id=%s' % (self.format_string(quote_attrib(self.id).encode(ExternalEncoding), input_name='id'), ))
def exportChildren(self, outfile, level, namespace_='', name_='docSect2Type'):
for item_ in self.content_:
item_.export(outfile, level, item_.name, namespace_)
def hasContent_(self):
if (
self.title is not None or
self.para is not None or
self.sect3 is not None or
self.internal is not None
):
return True
else:
return False
def build(self, node_):
attrs = node_.attributes
self.buildAttributes(attrs)
for child_ in node_.childNodes:
nodeName_ = child_.nodeName.split(':')[-1]
self.buildChildren(child_, nodeName_)
def buildAttributes(self, attrs):
if attrs.get('id'):
self.id = attrs.get('id').value
def buildChildren(self, child_, nodeName_):
if child_.nodeType == Node.ELEMENT_NODE and \
nodeName_ == 'title':
childobj_ = docTitleType.factory()
childobj_.build(child_)
obj_ = self.mixedclass_(MixedContainer.CategoryComplex,
MixedContainer.TypeNone, 'title', childobj_)
self.content_.append(obj_)
elif child_.nodeType == Node.ELEMENT_NODE and \
nodeName_ == 'para':
childobj_ = docParaType.factory()
childobj_.build(child_)
obj_ = self.mixedclass_(MixedContainer.CategoryComplex,
MixedContainer.TypeNone, 'para', childobj_)
self.content_.append(obj_)
elif child_.nodeType == Node.ELEMENT_NODE and \
nodeName_ == 'sect3':
childobj_ = docSect3Type.factory()
childobj_.build(child_)
obj_ = self.mixedclass_(MixedContainer.CategoryComplex,
MixedContainer.TypeNone, 'sect3', childobj_)
self.content_.append(obj_)
elif child_.nodeType == Node.ELEMENT_NODE and \
nodeName_ == 'internal':
childobj_ = docInternalS2Type.factory()
childobj_.build(child_)
obj_ = self.mixedclass_(MixedContainer.CategoryComplex,
MixedContainer.TypeNone, 'internal', childobj_)
self.content_.append(obj_)
elif child_.nodeType == Node.TEXT_NODE:
obj_ = self.mixedclass_(MixedContainer.CategoryText,
MixedContainer.TypeNone, '', child_.nodeValue)
self.content_.append(obj_)
# end class docSect2Type
class docSect3Type(GeneratedsSuper):
subclass = None
superclass = None
def __init__(self, id=None, title=None, para=None, sect4=None, internal=None, mixedclass_=None, content_=None):
self.id = id
if mixedclass_ is None:
self.mixedclass_ = MixedContainer
else:
self.mixedclass_ = mixedclass_
if content_ is None:
self.content_ = []
else:
self.content_ = content_
def factory(*args_, **kwargs_):
if docSect3Type.subclass:
return docSect3Type.subclass(*args_, **kwargs_)
else:
return docSect3Type(*args_, **kwargs_)
factory = staticmethod(factory)
def get_title(self): return self.title
def set_title(self, title): self.title = title
def get_para(self): return self.para
def set_para(self, para): self.para = para
def add_para(self, value): self.para.append(value)
def insert_para(self, index, value): self.para[index] = value
def get_sect4(self): return self.sect4
def set_sect4(self, sect4): self.sect4 = sect4
def add_sect4(self, value): self.sect4.append(value)
def insert_sect4(self, index, value): self.sect4[index] = value
def get_internal(self): return self.internal
def set_internal(self, internal): self.internal = internal
def get_id(self): return self.id
def set_id(self, id): self.id = id
def export(self, outfile, level, namespace_='', name_='docSect3Type', namespacedef_=''):
showIndent(outfile, level)
outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, ))
self.exportAttributes(outfile, level, namespace_, name_='docSect3Type')
outfile.write('>')
self.exportChildren(outfile, level + 1, namespace_, name_)
outfile.write('</%s%s>\n' % (namespace_, name_))
def exportAttributes(self, outfile, level, namespace_='', name_='docSect3Type'):
if self.id is not None:
outfile.write(' id=%s' % (self.format_string(quote_attrib(self.id).encode(ExternalEncoding), input_name='id'), ))
def exportChildren(self, outfile, level, namespace_='', name_='docSect3Type'):
for item_ in self.content_:
item_.export(outfile, level, item_.name, namespace_)
def hasContent_(self):
if (
self.title is not None or
self.para is not None or
self.sect4 is not None or
self.internal is not None
):
return True
else:
return False
def build(self, node_):
attrs = node_.attributes
self.buildAttributes(attrs)
for child_ in node_.childNodes:
nodeName_ = child_.nodeName.split(':')[-1]
self.buildChildren(child_, nodeName_)
def buildAttributes(self, attrs):
if attrs.get('id'):
self.id = attrs.get('id').value
def buildChildren(self, child_, nodeName_):
if child_.nodeType == Node.ELEMENT_NODE and \
nodeName_ == 'title':
childobj_ = docTitleType.factory()
childobj_.build(child_)
obj_ = self.mixedclass_(MixedContainer.CategoryComplex,
MixedContainer.TypeNone, 'title', childobj_)
self.content_.append(obj_)
elif child_.nodeType == Node.ELEMENT_NODE and \
nodeName_ == 'para':
childobj_ = docParaType.factory()
childobj_.build(child_)
obj_ = self.mixedclass_(MixedContainer.CategoryComplex,
MixedContainer.TypeNone, 'para', childobj_)
self.content_.append(obj_)
elif child_.nodeType == Node.ELEMENT_NODE and \
nodeName_ == 'sect4':
childobj_ = docSect4Type.factory()
childobj_.build(child_)
obj_ = self.mixedclass_(MixedContainer.CategoryComplex,
MixedContainer.TypeNone, 'sect4', childobj_)
self.content_.append(obj_)
elif child_.nodeType == Node.ELEMENT_NODE and \
nodeName_ == 'internal':
childobj_ = docInternalS3Type.factory()
childobj_.build(child_)
obj_ = self.mixedclass_(MixedContainer.CategoryComplex,
MixedContainer.TypeNone, 'internal', childobj_)
self.content_.append(obj_)
elif child_.nodeType == Node.TEXT_NODE:
obj_ = self.mixedclass_(MixedContainer.CategoryText,
MixedContainer.TypeNone, '', child_.nodeValue)
self.content_.append(obj_)
# end class docSect3Type
class docSect4Type(GeneratedsSuper):
subclass = None
superclass = None
def __init__(self, id=None, title=None, para=None, internal=None, mixedclass_=None, content_=None):
self.id = id
if mixedclass_ is None:
self.mixedclass_ = MixedContainer
else:
self.mixedclass_ = mixedclass_
if content_ is None:
self.content_ = []
else:
self.content_ = content_
def factory(*args_, **kwargs_):
if docSect4Type.subclass:
return docSect4Type.subclass(*args_, **kwargs_)
else:
return docSect4Type(*args_, **kwargs_)
factory = staticmethod(factory)
def get_title(self): return self.title
def set_title(self, title): self.title = title
def get_para(self): return self.para
def set_para(self, para): self.para = para
def add_para(self, value): self.para.append(value)
def insert_para(self, index, value): self.para[index] = value
def get_internal(self): return self.internal
def set_internal(self, internal): self.internal = internal
def get_id(self): return self.id
def set_id(self, id): self.id = id
def export(self, outfile, level, namespace_='', name_='docSect4Type', namespacedef_=''):
showIndent(outfile, level)
outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, ))
self.exportAttributes(outfile, level, namespace_, name_='docSect4Type')
outfile.write('>')
self.exportChildren(outfile, level + 1, namespace_, name_)
outfile.write('</%s%s>\n' % (namespace_, name_))
def exportAttributes(self, outfile, level, namespace_='', name_='docSect4Type'):
if self.id is not None:
outfile.write(' id=%s' % (self.format_string(quote_attrib(self.id).encode(ExternalEncoding), input_name='id'), ))
def exportChildren(self, outfile, level, namespace_='', name_='docSect4Type'):
for item_ in self.content_:
item_.export(outfile, level, item_.name, namespace_)
def hasContent_(self):
if (
self.title is not None or
self.para is not None or
self.internal is not None
):
return True
else:
return False
def build(self, node_):
attrs = node_.attributes
self.buildAttributes(attrs)
for child_ in node_.childNodes:
nodeName_ = child_.nodeName.split(':')[-1]
self.buildChildren(child_, nodeName_)
def buildAttributes(self, attrs):
if attrs.get('id'):
self.id = attrs.get('id').value
def buildChildren(self, child_, nodeName_):
if child_.nodeType == Node.ELEMENT_NODE and \
nodeName_ == 'title':
childobj_ = docTitleType.factory()
childobj_.build(child_)
obj_ = self.mixedclass_(MixedContainer.CategoryComplex,
MixedContainer.TypeNone, 'title', childobj_)
self.content_.append(obj_)
elif child_.nodeType == Node.ELEMENT_NODE and \
nodeName_ == 'para':
childobj_ = docParaType.factory()
childobj_.build(child_)
obj_ = self.mixedclass_(MixedContainer.CategoryComplex,
MixedContainer.TypeNone, 'para', childobj_)
self.content_.append(obj_)
elif child_.nodeType == Node.ELEMENT_NODE and \
nodeName_ == 'internal':
childobj_ = docInternalS4Type.factory()
childobj_.build(child_)
obj_ = self.mixedclass_(MixedContainer.CategoryComplex,
MixedContainer.TypeNone, 'internal', childobj_)
self.content_.append(obj_)
elif child_.nodeType == Node.TEXT_NODE:
obj_ = self.mixedclass_(MixedContainer.CategoryText,
MixedContainer.TypeNone, '', child_.nodeValue)
self.content_.append(obj_)
# end class docSect4Type
class docInternalType(GeneratedsSuper):
subclass = None
superclass = None
def __init__(self, para=None, sect1=None, mixedclass_=None, content_=None):
if mixedclass_ is None:
self.mixedclass_ = MixedContainer
else:
self.mixedclass_ = mixedclass_
if content_ is None:
self.content_ = []
else:
self.content_ = content_
def factory(*args_, **kwargs_):
if docInternalType.subclass:
return docInternalType.subclass(*args_, **kwargs_)
else:
return docInternalType(*args_, **kwargs_)
factory = staticmethod(factory)
def get_para(self): return self.para
def set_para(self, para): self.para = para
def add_para(self, value): self.para.append(value)
def insert_para(self, index, value): self.para[index] = value
def get_sect1(self): return self.sect1
def set_sect1(self, sect1): self.sect1 = sect1
def add_sect1(self, value): self.sect1.append(value)
def insert_sect1(self, index, value): self.sect1[index] = value
def export(self, outfile, level, namespace_='', name_='docInternalType', namespacedef_=''):
showIndent(outfile, level)
outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, ))
self.exportAttributes(outfile, level, namespace_, name_='docInternalType')
outfile.write('>')
self.exportChildren(outfile, level + 1, namespace_, name_)
outfile.write('</%s%s>\n' % (namespace_, name_))
def exportAttributes(self, outfile, level, namespace_='', name_='docInternalType'):
pass
def exportChildren(self, outfile, level, namespace_='', name_='docInternalType'):
for item_ in self.content_:
item_.export(outfile, level, item_.name, namespace_)
def hasContent_(self):
if (
self.para is not None or
self.sect1 is not None
):
return True
else:
return False
def build(self, node_):
attrs = node_.attributes
self.buildAttributes(attrs)
for child_ in node_.childNodes:
nodeName_ = child_.nodeName.split(':')[-1]
self.buildChildren(child_, nodeName_)
def buildAttributes(self, attrs):
pass
def buildChildren(self, child_, nodeName_):
if child_.nodeType == Node.ELEMENT_NODE and \
nodeName_ == 'para':
childobj_ = docParaType.factory()
childobj_.build(child_)
obj_ = self.mixedclass_(MixedContainer.CategoryComplex,
MixedContainer.TypeNone, 'para', childobj_)
self.content_.append(obj_)
elif child_.nodeType == Node.ELEMENT_NODE and \
nodeName_ == 'sect1':
childobj_ = docSect1Type.factory()
childobj_.build(child_)
obj_ = self.mixedclass_(MixedContainer.CategoryComplex,
MixedContainer.TypeNone, 'sect1', childobj_)
self.content_.append(obj_)
elif child_.nodeType == Node.TEXT_NODE:
obj_ = self.mixedclass_(MixedContainer.CategoryText,
MixedContainer.TypeNone, '', child_.nodeValue)
self.content_.append(obj_)
# end class docInternalType
class docInternalS1Type(GeneratedsSuper):
subclass = None
superclass = None
def __init__(self, para=None, sect2=None, mixedclass_=None, content_=None):
if mixedclass_ is None:
self.mixedclass_ = MixedContainer
else:
self.mixedclass_ = mixedclass_
if content_ is None:
self.content_ = []
else:
self.content_ = content_
def factory(*args_, **kwargs_):
if docInternalS1Type.subclass:
return docInternalS1Type.subclass(*args_, **kwargs_)
else:
return docInternalS1Type(*args_, **kwargs_)
factory = staticmethod(factory)
def get_para(self): return self.para
def set_para(self, para): self.para = para
def add_para(self, value): self.para.append(value)
def insert_para(self, index, value): self.para[index] = value
def get_sect2(self): return self.sect2
def set_sect2(self, sect2): self.sect2 = sect2
def add_sect2(self, value): self.sect2.append(value)
def insert_sect2(self, index, value): self.sect2[index] = value
def export(self, outfile, level, namespace_='', name_='docInternalS1Type', namespacedef_=''):
showIndent(outfile, level)
outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, ))
self.exportAttributes(outfile, level, namespace_, name_='docInternalS1Type')
outfile.write('>')
self.exportChildren(outfile, level + 1, namespace_, name_)
outfile.write('</%s%s>\n' % (namespace_, name_))
def exportAttributes(self, outfile, level, namespace_='', name_='docInternalS1Type'):
pass
def exportChildren(self, outfile, level, namespace_='', name_='docInternalS1Type'):
for item_ in self.content_:
item_.export(outfile, level, item_.name, namespace_)
def hasContent_(self):
if (
self.para is not None or
self.sect2 is not None
):
return True
else:
return False
def build(self, node_):
attrs = node_.attributes
self.buildAttributes(attrs)
for child_ in node_.childNodes:
nodeName_ = child_.nodeName.split(':')[-1]
self.buildChildren(child_, nodeName_)
def buildAttributes(self, attrs):
pass
def buildChildren(self, child_, nodeName_):
if child_.nodeType == Node.ELEMENT_NODE and \
nodeName_ == 'para':
childobj_ = docParaType.factory()
childobj_.build(child_)
obj_ = self.mixedclass_(MixedContainer.CategoryComplex,
MixedContainer.TypeNone, 'para', childobj_)
self.content_.append(obj_)
elif child_.nodeType == Node.ELEMENT_NODE and \
nodeName_ == 'sect2':
childobj_ = docSect2Type.factory()
childobj_.build(child_)
obj_ = self.mixedclass_(MixedContainer.CategoryComplex,
MixedContainer.TypeNone, 'sect2', childobj_)
self.content_.append(obj_)
elif child_.nodeType == Node.TEXT_NODE:
obj_ = self.mixedclass_(MixedContainer.CategoryText,
MixedContainer.TypeNone, '', child_.nodeValue)
self.content_.append(obj_)
# end class docInternalS1Type
class docInternalS2Type(GeneratedsSuper):
subclass = None
superclass = None
def __init__(self, para=None, sect3=None, mixedclass_=None, content_=None):
if mixedclass_ is None:
self.mixedclass_ = MixedContainer
else:
self.mixedclass_ = mixedclass_
if content_ is None:
self.content_ = []
else:
self.content_ = content_
def factory(*args_, **kwargs_):
if docInternalS2Type.subclass:
return docInternalS2Type.subclass(*args_, **kwargs_)
else:
return docInternalS2Type(*args_, **kwargs_)
factory = staticmethod(factory)
def get_para(self): return self.para
def set_para(self, para): self.para = para
def add_para(self, value): self.para.append(value)
def insert_para(self, index, value): self.para[index] = value
def get_sect3(self): return self.sect3
def set_sect3(self, sect3): self.sect3 = sect3
def add_sect3(self, value): self.sect3.append(value)
def insert_sect3(self, index, value): self.sect3[index] = value
def export(self, outfile, level, namespace_='', name_='docInternalS2Type', namespacedef_=''):
showIndent(outfile, level)
outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, ))
self.exportAttributes(outfile, level, namespace_, name_='docInternalS2Type')
outfile.write('>')
self.exportChildren(outfile, level + 1, namespace_, name_)
outfile.write('</%s%s>\n' % (namespace_, name_))
def exportAttributes(self, outfile, level, namespace_='', name_='docInternalS2Type'):
pass
def exportChildren(self, outfile, level, namespace_='', name_='docInternalS2Type'):
for item_ in self.content_:
item_.export(outfile, level, item_.name, namespace_)
def hasContent_(self):
if (
self.para is not None or
self.sect3 is not None
):
return True
else:
return False
def build(self, node_):
attrs = node_.attributes
self.buildAttributes(attrs)
for child_ in node_.childNodes:
nodeName_ = child_.nodeName.split(':')[-1]
self.buildChildren(child_, nodeName_)
def buildAttributes(self, attrs):
pass
def buildChildren(self, child_, nodeName_):
if child_.nodeType == Node.ELEMENT_NODE and \
nodeName_ == 'para':
childobj_ = docParaType.factory()
childobj_.build(child_)
obj_ = self.mixedclass_(MixedContainer.CategoryComplex,
MixedContainer.TypeNone, 'para', childobj_)
self.content_.append(obj_)
elif child_.nodeType == Node.ELEMENT_NODE and \
nodeName_ == 'sect3':
childobj_ = docSect3Type.factory()
childobj_.build(child_)
obj_ = self.mixedclass_(MixedContainer.CategoryComplex,
MixedContainer.TypeNone, 'sect3', childobj_)
self.content_.append(obj_)
elif child_.nodeType == Node.TEXT_NODE:
obj_ = self.mixedclass_(MixedContainer.CategoryText,
MixedContainer.TypeNone, '', child_.nodeValue)
self.content_.append(obj_)
# end class docInternalS2Type
class docInternalS3Type(GeneratedsSuper):
subclass = None
superclass = None
def __init__(self, para=None, sect3=None, mixedclass_=None, content_=None):
if mixedclass_ is None:
self.mixedclass_ = MixedContainer
else:
self.mixedclass_ = mixedclass_
if content_ is None:
self.content_ = []
else:
self.content_ = content_
def factory(*args_, **kwargs_):
if docInternalS3Type.subclass:
return docInternalS3Type.subclass(*args_, **kwargs_)
else:
return docInternalS3Type(*args_, **kwargs_)
factory = staticmethod(factory)
def get_para(self): return self.para
def set_para(self, para): self.para = para
def add_para(self, value): self.para.append(value)
def insert_para(self, index, value): self.para[index] = value
def get_sect3(self): return self.sect3
def set_sect3(self, sect3): self.sect3 = sect3
def add_sect3(self, value): self.sect3.append(value)
def insert_sect3(self, index, value): self.sect3[index] = value
def export(self, outfile, level, namespace_='', name_='docInternalS3Type', namespacedef_=''):
showIndent(outfile, level)
outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, ))
self.exportAttributes(outfile, level, namespace_, name_='docInternalS3Type')
outfile.write('>')
self.exportChildren(outfile, level + 1, namespace_, name_)
outfile.write('</%s%s>\n' % (namespace_, name_))
def exportAttributes(self, outfile, level, namespace_='', name_='docInternalS3Type'):
pass
def exportChildren(self, outfile, level, namespace_='', name_='docInternalS3Type'):
for item_ in self.content_:
item_.export(outfile, level, item_.name, namespace_)
def hasContent_(self):
if (
self.para is not None or
self.sect3 is not None
):
return True
else:
return False
def build(self, node_):
attrs = node_.attributes
self.buildAttributes(attrs)
for child_ in node_.childNodes:
nodeName_ = child_.nodeName.split(':')[-1]
self.buildChildren(child_, nodeName_)
def buildAttributes(self, attrs):
pass
def buildChildren(self, child_, nodeName_):
if child_.nodeType == Node.ELEMENT_NODE and \
nodeName_ == 'para':
childobj_ = docParaType.factory()
childobj_.build(child_)
obj_ = self.mixedclass_(MixedContainer.CategoryComplex,
MixedContainer.TypeNone, 'para', childobj_)
self.content_.append(obj_)
elif child_.nodeType == Node.ELEMENT_NODE and \
nodeName_ == 'sect3':
childobj_ = docSect4Type.factory()
childobj_.build(child_)
obj_ = self.mixedclass_(MixedContainer.CategoryComplex,
MixedContainer.TypeNone, 'sect3', childobj_)
self.content_.append(obj_)
elif child_.nodeType == Node.TEXT_NODE:
obj_ = self.mixedclass_(MixedContainer.CategoryText,
MixedContainer.TypeNone, '', child_.nodeValue)
self.content_.append(obj_)
# end class docInternalS3Type
class docInternalS4Type(GeneratedsSuper):
subclass = None
superclass = None
def __init__(self, para=None, mixedclass_=None, content_=None):
if mixedclass_ is None:
self.mixedclass_ = MixedContainer
else:
self.mixedclass_ = mixedclass_
if content_ is None:
self.content_ = []
else:
self.content_ = content_
def factory(*args_, **kwargs_):
if docInternalS4Type.subclass:
return docInternalS4Type.subclass(*args_, **kwargs_)
else:
return docInternalS4Type(*args_, **kwargs_)
factory = staticmethod(factory)
def get_para(self): return self.para
def set_para(self, para): self.para = para
def add_para(self, value): self.para.append(value)
def insert_para(self, index, value): self.para[index] = value
def export(self, outfile, level, namespace_='', name_='docInternalS4Type', namespacedef_=''):
showIndent(outfile, level)
outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, ))
self.exportAttributes(outfile, level, namespace_, name_='docInternalS4Type')
outfile.write('>')
self.exportChildren(outfile, level + 1, namespace_, name_)
outfile.write('</%s%s>\n' % (namespace_, name_))
def exportAttributes(self, outfile, level, namespace_='', name_='docInternalS4Type'):
pass
def exportChildren(self, outfile, level, namespace_='', name_='docInternalS4Type'):
for item_ in self.content_:
item_.export(outfile, level, item_.name, namespace_)
def hasContent_(self):
if (
self.para is not None
):
return True
else:
return False
def build(self, node_):
attrs = node_.attributes
self.buildAttributes(attrs)
for child_ in node_.childNodes:
nodeName_ = child_.nodeName.split(':')[-1]
self.buildChildren(child_, nodeName_)
def buildAttributes(self, attrs):
pass
def buildChildren(self, child_, nodeName_):
if child_.nodeType == Node.ELEMENT_NODE and \
nodeName_ == 'para':
childobj_ = docParaType.factory()
childobj_.build(child_)
obj_ = self.mixedclass_(MixedContainer.CategoryComplex,
MixedContainer.TypeNone, 'para', childobj_)
self.content_.append(obj_)
elif child_.nodeType == Node.TEXT_NODE:
obj_ = self.mixedclass_(MixedContainer.CategoryText,
MixedContainer.TypeNone, '', child_.nodeValue)
self.content_.append(obj_)
# end class docInternalS4Type
class docTitleType(GeneratedsSuper):
subclass = None
superclass = None
def __init__(self, valueOf_='', mixedclass_=None, content_=None):
if mixedclass_ is None:
self.mixedclass_ = MixedContainer
else:
self.mixedclass_ = mixedclass_
if content_ is None:
self.content_ = []
else:
self.content_ = content_
def factory(*args_, **kwargs_):
if docTitleType.subclass:
return docTitleType.subclass(*args_, **kwargs_)
else:
return docTitleType(*args_, **kwargs_)
factory = staticmethod(factory)
def getValueOf_(self): return self.valueOf_
def setValueOf_(self, valueOf_): self.valueOf_ = valueOf_
def export(self, outfile, level, namespace_='', name_='docTitleType', namespacedef_=''):
showIndent(outfile, level)
outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, ))
self.exportAttributes(outfile, level, namespace_, name_='docTitleType')
outfile.write('>')
self.exportChildren(outfile, level + 1, namespace_, name_)
outfile.write('</%s%s>\n' % (namespace_, name_))
def exportAttributes(self, outfile, level, namespace_='', name_='docTitleType'):
pass
def exportChildren(self, outfile, level, namespace_='', name_='docTitleType'):
if self.valueOf_.find('![CDATA')>-1:
value=quote_xml('%s' % self.valueOf_)
value=value.replace('![CDATA','<![CDATA')
value=value.replace(']]',']]>')
outfile.write(value)
else:
outfile.write(quote_xml('%s' % self.valueOf_))
def hasContent_(self):
if (
self.valueOf_ is not None
):
return True
else:
return False
def build(self, node_):
attrs = node_.attributes
self.buildAttributes(attrs)
self.valueOf_ = ''
for child_ in node_.childNodes:
nodeName_ = child_.nodeName.split(':')[-1]
self.buildChildren(child_, nodeName_)
def buildAttributes(self, attrs):
pass
def buildChildren(self, child_, nodeName_):
if child_.nodeType == Node.TEXT_NODE:
obj_ = self.mixedclass_(MixedContainer.CategoryText,
MixedContainer.TypeNone, '', child_.nodeValue)
self.content_.append(obj_)
if child_.nodeType == Node.TEXT_NODE:
self.valueOf_ += child_.nodeValue
elif child_.nodeType == Node.CDATA_SECTION_NODE:
self.valueOf_ += '![CDATA['+child_.nodeValue+']]'
# end class docTitleType
class docParaType(GeneratedsSuper):
subclass = None
superclass = None
def __init__(self, valueOf_='', mixedclass_=None, content_=None):
if mixedclass_ is None:
self.mixedclass_ = MixedContainer
else:
self.mixedclass_ = mixedclass_
if content_ is None:
self.content_ = []
else:
self.content_ = content_
def factory(*args_, **kwargs_):
if docParaType.subclass:
return docParaType.subclass(*args_, **kwargs_)
else:
return docParaType(*args_, **kwargs_)
factory = staticmethod(factory)
def getValueOf_(self): return self.valueOf_
def setValueOf_(self, valueOf_): self.valueOf_ = valueOf_
def export(self, outfile, level, namespace_='', name_='docParaType', namespacedef_=''):
showIndent(outfile, level)
outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, ))
self.exportAttributes(outfile, level, namespace_, name_='docParaType')
outfile.write('>')
self.exportChildren(outfile, level + 1, namespace_, name_)
outfile.write('</%s%s>\n' % (namespace_, name_))
def exportAttributes(self, outfile, level, namespace_='', name_='docParaType'):
pass
def exportChildren(self, outfile, level, namespace_='', name_='docParaType'):
if self.valueOf_.find('![CDATA')>-1:
value=quote_xml('%s' % self.valueOf_)
value=value.replace('![CDATA','<![CDATA')
value=value.replace(']]',']]>')
outfile.write(value)
else:
outfile.write(quote_xml('%s' % self.valueOf_))
def hasContent_(self):
if (
self.valueOf_ is not None
):
return True
else:
return False
def build(self, node_):
attrs = node_.attributes
self.buildAttributes(attrs)
self.valueOf_ = ''
for child_ in node_.childNodes:
nodeName_ = child_.nodeName.split(':')[-1]
self.buildChildren(child_, nodeName_)
def buildAttributes(self, attrs):
pass
def buildChildren(self, child_, nodeName_):
if child_.nodeType == Node.TEXT_NODE:
obj_ = self.mixedclass_(MixedContainer.CategoryText,
MixedContainer.TypeNone, '', child_.nodeValue)
self.content_.append(obj_)
if child_.nodeType == Node.TEXT_NODE:
self.valueOf_ += child_.nodeValue
elif child_.nodeType == Node.CDATA_SECTION_NODE:
self.valueOf_ += '![CDATA['+child_.nodeValue+']]'
# end class docParaType
class docMarkupType(GeneratedsSuper):
subclass = None
superclass = None
def __init__(self, valueOf_='', mixedclass_=None, content_=None):
if mixedclass_ is None:
self.mixedclass_ = MixedContainer
else:
self.mixedclass_ = mixedclass_
if content_ is None:
self.content_ = []
else:
self.content_ = content_
def factory(*args_, **kwargs_):
if docMarkupType.subclass:
return docMarkupType.subclass(*args_, **kwargs_)
else:
return docMarkupType(*args_, **kwargs_)
factory = staticmethod(factory)
def getValueOf_(self): return self.valueOf_
def setValueOf_(self, valueOf_): self.valueOf_ = valueOf_
def export(self, outfile, level, namespace_='', name_='docMarkupType', namespacedef_=''):
showIndent(outfile, level)
outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, ))
self.exportAttributes(outfile, level, namespace_, name_='docMarkupType')
outfile.write('>')
self.exportChildren(outfile, level + 1, namespace_, name_)
outfile.write('</%s%s>\n' % (namespace_, name_))
def exportAttributes(self, outfile, level, namespace_='', name_='docMarkupType'):
pass
def exportChildren(self, outfile, level, namespace_='', name_='docMarkupType'):
if self.valueOf_.find('![CDATA')>-1:
value=quote_xml('%s' % self.valueOf_)
value=value.replace('![CDATA','<![CDATA')
value=value.replace(']]',']]>')
outfile.write(value)
else:
outfile.write(quote_xml('%s' % self.valueOf_))
def hasContent_(self):
if (
self.valueOf_ is not None
):
return True
else:
return False
def build(self, node_):
attrs = node_.attributes
self.buildAttributes(attrs)
self.valueOf_ = ''
for child_ in node_.childNodes:
nodeName_ = child_.nodeName.split(':')[-1]
self.buildChildren(child_, nodeName_)
def buildAttributes(self, attrs):
pass
def buildChildren(self, child_, nodeName_):
if child_.nodeType == Node.TEXT_NODE:
obj_ = self.mixedclass_(MixedContainer.CategoryText,
MixedContainer.TypeNone, '', child_.nodeValue)
self.content_.append(obj_)
if child_.nodeType == Node.TEXT_NODE:
self.valueOf_ += child_.nodeValue
elif child_.nodeType == Node.CDATA_SECTION_NODE:
self.valueOf_ += '![CDATA['+child_.nodeValue+']]'
# end class docMarkupType
class docURLLink(GeneratedsSuper):
subclass = None
superclass = None
def __init__(self, url=None, valueOf_='', mixedclass_=None, content_=None):
self.url = url
if mixedclass_ is None:
self.mixedclass_ = MixedContainer
else:
self.mixedclass_ = mixedclass_
if content_ is None:
self.content_ = []
else:
self.content_ = content_
def factory(*args_, **kwargs_):
if docURLLink.subclass:
return docURLLink.subclass(*args_, **kwargs_)
else:
return docURLLink(*args_, **kwargs_)
factory = staticmethod(factory)
def get_url(self): return self.url
def set_url(self, url): self.url = url
def getValueOf_(self): return self.valueOf_
def setValueOf_(self, valueOf_): self.valueOf_ = valueOf_
def export(self, outfile, level, namespace_='', name_='docURLLink', namespacedef_=''):
showIndent(outfile, level)
outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, ))
self.exportAttributes(outfile, level, namespace_, name_='docURLLink')
outfile.write('>')
self.exportChildren(outfile, level + 1, namespace_, name_)
outfile.write('</%s%s>\n' % (namespace_, name_))
def exportAttributes(self, outfile, level, namespace_='', name_='docURLLink'):
if self.url is not None:
outfile.write(' url=%s' % (self.format_string(quote_attrib(self.url).encode(ExternalEncoding), input_name='url'), ))
def exportChildren(self, outfile, level, namespace_='', name_='docURLLink'):
if self.valueOf_.find('![CDATA')>-1:
value=quote_xml('%s' % self.valueOf_)
value=value.replace('![CDATA','<![CDATA')
value=value.replace(']]',']]>')
outfile.write(value)
else:
outfile.write(quote_xml('%s' % self.valueOf_))
def hasContent_(self):
if (
self.valueOf_ is not None
):
return True
else:
return False
def build(self, node_):
attrs = node_.attributes
self.buildAttributes(attrs)
self.valueOf_ = ''
for child_ in node_.childNodes:
nodeName_ = child_.nodeName.split(':')[-1]
self.buildChildren(child_, nodeName_)
def buildAttributes(self, attrs):
if attrs.get('url'):
self.url = attrs.get('url').value
def buildChildren(self, child_, nodeName_):
if child_.nodeType == Node.TEXT_NODE:
obj_ = self.mixedclass_(MixedContainer.CategoryText,
MixedContainer.TypeNone, '', child_.nodeValue)
self.content_.append(obj_)
if child_.nodeType == Node.TEXT_NODE:
self.valueOf_ += child_.nodeValue
elif child_.nodeType == Node.CDATA_SECTION_NODE:
self.valueOf_ += '![CDATA['+child_.nodeValue+']]'
# end class docURLLink
class docAnchorType(GeneratedsSuper):
subclass = None
superclass = None
def __init__(self, id=None, valueOf_='', mixedclass_=None, content_=None):
self.id = id
if mixedclass_ is None:
self.mixedclass_ = MixedContainer
else:
self.mixedclass_ = mixedclass_
if content_ is None:
self.content_ = []
else:
self.content_ = content_
def factory(*args_, **kwargs_):
if docAnchorType.subclass:
return docAnchorType.subclass(*args_, **kwargs_)
else:
return docAnchorType(*args_, **kwargs_)
factory = staticmethod(factory)
def get_id(self): return self.id
def set_id(self, id): self.id = id
def getValueOf_(self): return self.valueOf_
def setValueOf_(self, valueOf_): self.valueOf_ = valueOf_
def export(self, outfile, level, namespace_='', name_='docAnchorType', namespacedef_=''):
showIndent(outfile, level)
outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, ))
self.exportAttributes(outfile, level, namespace_, name_='docAnchorType')
outfile.write('>')
self.exportChildren(outfile, level + 1, namespace_, name_)
outfile.write('</%s%s>\n' % (namespace_, name_))
def exportAttributes(self, outfile, level, namespace_='', name_='docAnchorType'):
if self.id is not None:
outfile.write(' id=%s' % (self.format_string(quote_attrib(self.id).encode(ExternalEncoding), input_name='id'), ))
def exportChildren(self, outfile, level, namespace_='', name_='docAnchorType'):
if self.valueOf_.find('![CDATA')>-1:
value=quote_xml('%s' % self.valueOf_)
value=value.replace('![CDATA','<![CDATA')
value=value.replace(']]',']]>')
outfile.write(value)
else:
outfile.write(quote_xml('%s' % self.valueOf_))
def hasContent_(self):
if (
self.valueOf_ is not None
):
return True
else:
return False
def build(self, node_):
attrs = node_.attributes
self.buildAttributes(attrs)
self.valueOf_ = ''
for child_ in node_.childNodes:
nodeName_ = child_.nodeName.split(':')[-1]
self.buildChildren(child_, nodeName_)
def buildAttributes(self, attrs):
if attrs.get('id'):
self.id = attrs.get('id').value
def buildChildren(self, child_, nodeName_):
if child_.nodeType == Node.TEXT_NODE:
obj_ = self.mixedclass_(MixedContainer.CategoryText,
MixedContainer.TypeNone, '', child_.nodeValue)
self.content_.append(obj_)
if child_.nodeType == Node.TEXT_NODE:
self.valueOf_ += child_.nodeValue
elif child_.nodeType == Node.CDATA_SECTION_NODE:
self.valueOf_ += '![CDATA['+child_.nodeValue+']]'
# end class docAnchorType
class docFormulaType(GeneratedsSuper):
subclass = None
superclass = None
def __init__(self, id=None, valueOf_='', mixedclass_=None, content_=None):
self.id = id
if mixedclass_ is None:
self.mixedclass_ = MixedContainer
else:
self.mixedclass_ = mixedclass_
if content_ is None:
self.content_ = []
else:
self.content_ = content_
def factory(*args_, **kwargs_):
if docFormulaType.subclass:
return docFormulaType.subclass(*args_, **kwargs_)
else:
return docFormulaType(*args_, **kwargs_)
factory = staticmethod(factory)
def get_id(self): return self.id
def set_id(self, id): self.id = id
def getValueOf_(self): return self.valueOf_
def setValueOf_(self, valueOf_): self.valueOf_ = valueOf_
def export(self, outfile, level, namespace_='', name_='docFormulaType', namespacedef_=''):
showIndent(outfile, level)
outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, ))
self.exportAttributes(outfile, level, namespace_, name_='docFormulaType')
outfile.write('>')
self.exportChildren(outfile, level + 1, namespace_, name_)
outfile.write('</%s%s>\n' % (namespace_, name_))
def exportAttributes(self, outfile, level, namespace_='', name_='docFormulaType'):
if self.id is not None:
outfile.write(' id=%s' % (self.format_string(quote_attrib(self.id).encode(ExternalEncoding), input_name='id'), ))
def exportChildren(self, outfile, level, namespace_='', name_='docFormulaType'):
if self.valueOf_.find('![CDATA')>-1:
value=quote_xml('%s' % self.valueOf_)
value=value.replace('![CDATA','<![CDATA')
value=value.replace(']]',']]>')
outfile.write(value)
else:
outfile.write(quote_xml('%s' % self.valueOf_))
def hasContent_(self):
if (
self.valueOf_ is not None
):
return True
else:
return False
def build(self, node_):
attrs = node_.attributes
self.buildAttributes(attrs)
self.valueOf_ = ''
for child_ in node_.childNodes:
nodeName_ = child_.nodeName.split(':')[-1]
self.buildChildren(child_, nodeName_)
def buildAttributes(self, attrs):
if attrs.get('id'):
self.id = attrs.get('id').value
def buildChildren(self, child_, nodeName_):
if child_.nodeType == Node.TEXT_NODE:
obj_ = self.mixedclass_(MixedContainer.CategoryText,
MixedContainer.TypeNone, '', child_.nodeValue)
self.content_.append(obj_)
if child_.nodeType == Node.TEXT_NODE:
self.valueOf_ += child_.nodeValue
elif child_.nodeType == Node.CDATA_SECTION_NODE:
self.valueOf_ += '![CDATA['+child_.nodeValue+']]'
# end class docFormulaType
class docIndexEntryType(GeneratedsSuper):
subclass = None
superclass = None
def __init__(self, primaryie=None, secondaryie=None):
self.primaryie = primaryie
self.secondaryie = secondaryie
def factory(*args_, **kwargs_):
if docIndexEntryType.subclass:
return docIndexEntryType.subclass(*args_, **kwargs_)
else:
return docIndexEntryType(*args_, **kwargs_)
factory = staticmethod(factory)
def get_primaryie(self): return self.primaryie
def set_primaryie(self, primaryie): self.primaryie = primaryie
def get_secondaryie(self): return self.secondaryie
def set_secondaryie(self, secondaryie): self.secondaryie = secondaryie
def export(self, outfile, level, namespace_='', name_='docIndexEntryType', namespacedef_=''):
showIndent(outfile, level)
outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, ))
self.exportAttributes(outfile, level, namespace_, name_='docIndexEntryType')
if self.hasContent_():
outfile.write('>\n')
self.exportChildren(outfile, level + 1, namespace_, name_)
showIndent(outfile, level)
outfile.write('</%s%s>\n' % (namespace_, name_))
else:
outfile.write(' />\n')
def exportAttributes(self, outfile, level, namespace_='', name_='docIndexEntryType'):
pass
def exportChildren(self, outfile, level, namespace_='', name_='docIndexEntryType'):
if self.primaryie is not None:
showIndent(outfile, level)
outfile.write('<%sprimaryie>%s</%sprimaryie>\n' % (namespace_, self.format_string(quote_xml(self.primaryie).encode(ExternalEncoding), input_name='primaryie'), namespace_))
if self.secondaryie is not None:
showIndent(outfile, level)
outfile.write('<%ssecondaryie>%s</%ssecondaryie>\n' % (namespace_, self.format_string(quote_xml(self.secondaryie).encode(ExternalEncoding), input_name='secondaryie'), namespace_))
def hasContent_(self):
if (
self.primaryie is not None or
self.secondaryie is not None
):
return True
else:
return False
def build(self, node_):
attrs = node_.attributes
self.buildAttributes(attrs)
for child_ in node_.childNodes:
nodeName_ = child_.nodeName.split(':')[-1]
self.buildChildren(child_, nodeName_)
def buildAttributes(self, attrs):
pass
def buildChildren(self, child_, nodeName_):
if child_.nodeType == Node.ELEMENT_NODE and \
nodeName_ == 'primaryie':
primaryie_ = ''
for text__content_ in child_.childNodes:
primaryie_ += text__content_.nodeValue
self.primaryie = primaryie_
elif child_.nodeType == Node.ELEMENT_NODE and \
nodeName_ == 'secondaryie':
secondaryie_ = ''
for text__content_ in child_.childNodes:
secondaryie_ += text__content_.nodeValue
self.secondaryie = secondaryie_
# end class docIndexEntryType
class docListType(GeneratedsSuper):
subclass = None
superclass = None
def __init__(self, listitem=None):
if listitem is None:
self.listitem = []
else:
self.listitem = listitem
def factory(*args_, **kwargs_):
if docListType.subclass:
return docListType.subclass(*args_, **kwargs_)
else:
return docListType(*args_, **kwargs_)
factory = staticmethod(factory)
def get_listitem(self): return self.listitem
def set_listitem(self, listitem): self.listitem = listitem
def add_listitem(self, value): self.listitem.append(value)
def insert_listitem(self, index, value): self.listitem[index] = value
def export(self, outfile, level, namespace_='', name_='docListType', namespacedef_=''):
showIndent(outfile, level)
outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, ))
self.exportAttributes(outfile, level, namespace_, name_='docListType')
if self.hasContent_():
outfile.write('>\n')
self.exportChildren(outfile, level + 1, namespace_, name_)
showIndent(outfile, level)
outfile.write('</%s%s>\n' % (namespace_, name_))
else:
outfile.write(' />\n')
def exportAttributes(self, outfile, level, namespace_='', name_='docListType'):
pass
def exportChildren(self, outfile, level, namespace_='', name_='docListType'):
for listitem_ in self.listitem:
listitem_.export(outfile, level, namespace_, name_='listitem')
def hasContent_(self):
if (
self.listitem is not None
):
return True
else:
return False
def build(self, node_):
attrs = node_.attributes
self.buildAttributes(attrs)
for child_ in node_.childNodes:
nodeName_ = child_.nodeName.split(':')[-1]
self.buildChildren(child_, nodeName_)
def buildAttributes(self, attrs):
pass
def buildChildren(self, child_, nodeName_):
if child_.nodeType == Node.ELEMENT_NODE and \
nodeName_ == 'listitem':
obj_ = docListItemType.factory()
obj_.build(child_)
self.listitem.append(obj_)
# end class docListType
class docListItemType(GeneratedsSuper):
subclass = None
superclass = None
def __init__(self, para=None):
if para is None:
self.para = []
else:
self.para = para
def factory(*args_, **kwargs_):
if docListItemType.subclass:
return docListItemType.subclass(*args_, **kwargs_)
else:
return docListItemType(*args_, **kwargs_)
factory = staticmethod(factory)
def get_para(self): return self.para
def set_para(self, para): self.para = para
def add_para(self, value): self.para.append(value)
def insert_para(self, index, value): self.para[index] = value
def export(self, outfile, level, namespace_='', name_='docListItemType', namespacedef_=''):
showIndent(outfile, level)
outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, ))
self.exportAttributes(outfile, level, namespace_, name_='docListItemType')
if self.hasContent_():
outfile.write('>\n')
self.exportChildren(outfile, level + 1, namespace_, name_)
showIndent(outfile, level)
outfile.write('</%s%s>\n' % (namespace_, name_))
else:
outfile.write(' />\n')
def exportAttributes(self, outfile, level, namespace_='', name_='docListItemType'):
pass
def exportChildren(self, outfile, level, namespace_='', name_='docListItemType'):
for para_ in self.para:
para_.export(outfile, level, namespace_, name_='para')
def hasContent_(self):
if (
self.para is not None
):
return True
else:
return False
def build(self, node_):
attrs = node_.attributes
self.buildAttributes(attrs)
for child_ in node_.childNodes:
nodeName_ = child_.nodeName.split(':')[-1]
self.buildChildren(child_, nodeName_)
def buildAttributes(self, attrs):
pass
def buildChildren(self, child_, nodeName_):
if child_.nodeType == Node.ELEMENT_NODE and \
nodeName_ == 'para':
obj_ = docParaType.factory()
obj_.build(child_)
self.para.append(obj_)
# end class docListItemType
class docSimpleSectType(GeneratedsSuper):
subclass = None
superclass = None
def __init__(self, kind=None, title=None, para=None):
self.kind = kind
self.title = title
if para is None:
self.para = []
else:
self.para = para
def factory(*args_, **kwargs_):
if docSimpleSectType.subclass:
return docSimpleSectType.subclass(*args_, **kwargs_)
else:
return docSimpleSectType(*args_, **kwargs_)
factory = staticmethod(factory)
def get_title(self): return self.title
def set_title(self, title): self.title = title
def get_para(self): return self.para
def set_para(self, para): self.para = para
def add_para(self, value): self.para.append(value)
def insert_para(self, index, value): self.para[index] = value
def get_kind(self): return self.kind
def set_kind(self, kind): self.kind = kind
def export(self, outfile, level, namespace_='', name_='docSimpleSectType', namespacedef_=''):
showIndent(outfile, level)
outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, ))
self.exportAttributes(outfile, level, namespace_, name_='docSimpleSectType')
if self.hasContent_():
outfile.write('>\n')
self.exportChildren(outfile, level + 1, namespace_, name_)
showIndent(outfile, level)
outfile.write('</%s%s>\n' % (namespace_, name_))
else:
outfile.write(' />\n')
def exportAttributes(self, outfile, level, namespace_='', name_='docSimpleSectType'):
if self.kind is not None:
outfile.write(' kind=%s' % (quote_attrib(self.kind), ))
def exportChildren(self, outfile, level, namespace_='', name_='docSimpleSectType'):
if self.title:
self.title.export(outfile, level, namespace_, name_='title')
for para_ in self.para:
para_.export(outfile, level, namespace_, name_='para')
def hasContent_(self):
if (
self.title is not None or
self.para is not None
):
return True
else:
return False
def build(self, node_):
attrs = node_.attributes
self.buildAttributes(attrs)
for child_ in node_.childNodes:
nodeName_ = child_.nodeName.split(':')[-1]
self.buildChildren(child_, nodeName_)
def buildAttributes(self, attrs):
if attrs.get('kind'):
self.kind = attrs.get('kind').value
def buildChildren(self, child_, nodeName_):
if child_.nodeType == Node.ELEMENT_NODE and \
nodeName_ == 'title':
obj_ = docTitleType.factory()
obj_.build(child_)
self.set_title(obj_)
elif child_.nodeType == Node.ELEMENT_NODE and \
nodeName_ == 'para':
obj_ = docParaType.factory()
obj_.build(child_)
self.para.append(obj_)
# end class docSimpleSectType
class docVarListEntryType(GeneratedsSuper):
subclass = None
superclass = None
def __init__(self, term=None):
self.term = term
def factory(*args_, **kwargs_):
if docVarListEntryType.subclass:
return docVarListEntryType.subclass(*args_, **kwargs_)
else:
return docVarListEntryType(*args_, **kwargs_)
factory = staticmethod(factory)
def get_term(self): return self.term
def set_term(self, term): self.term = term
def export(self, outfile, level, namespace_='', name_='docVarListEntryType', namespacedef_=''):
showIndent(outfile, level)
outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, ))
self.exportAttributes(outfile, level, namespace_, name_='docVarListEntryType')
if self.hasContent_():
outfile.write('>\n')
self.exportChildren(outfile, level + 1, namespace_, name_)
showIndent(outfile, level)
outfile.write('</%s%s>\n' % (namespace_, name_))
else:
outfile.write(' />\n')
def exportAttributes(self, outfile, level, namespace_='', name_='docVarListEntryType'):
pass
def exportChildren(self, outfile, level, namespace_='', name_='docVarListEntryType'):
if self.term:
self.term.export(outfile, level, namespace_, name_='term', )
def hasContent_(self):
if (
self.term is not None
):
return True
else:
return False
def build(self, node_):
attrs = node_.attributes
self.buildAttributes(attrs)
for child_ in node_.childNodes:
nodeName_ = child_.nodeName.split(':')[-1]
self.buildChildren(child_, nodeName_)
def buildAttributes(self, attrs):
pass
def buildChildren(self, child_, nodeName_):
if child_.nodeType == Node.ELEMENT_NODE and \
nodeName_ == 'term':
obj_ = docTitleType.factory()
obj_.build(child_)
self.set_term(obj_)
# end class docVarListEntryType
class docVariableListType(GeneratedsSuper):
subclass = None
superclass = None
def __init__(self, valueOf_=''):
self.valueOf_ = valueOf_
def factory(*args_, **kwargs_):
if docVariableListType.subclass:
return docVariableListType.subclass(*args_, **kwargs_)
else:
return docVariableListType(*args_, **kwargs_)
factory = staticmethod(factory)
def getValueOf_(self): return self.valueOf_
def setValueOf_(self, valueOf_): self.valueOf_ = valueOf_
def export(self, outfile, level, namespace_='', name_='docVariableListType', namespacedef_=''):
showIndent(outfile, level)
outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, ))
self.exportAttributes(outfile, level, namespace_, name_='docVariableListType')
if self.hasContent_():
outfile.write('>\n')
self.exportChildren(outfile, level + 1, namespace_, name_)
showIndent(outfile, level)
outfile.write('</%s%s>\n' % (namespace_, name_))
else:
outfile.write(' />\n')
def exportAttributes(self, outfile, level, namespace_='', name_='docVariableListType'):
pass
def exportChildren(self, outfile, level, namespace_='', name_='docVariableListType'):
if self.valueOf_.find('![CDATA')>-1:
value=quote_xml('%s' % self.valueOf_)
value=value.replace('![CDATA','<![CDATA')
value=value.replace(']]',']]>')
outfile.write(value)
else:
outfile.write(quote_xml('%s' % self.valueOf_))
def hasContent_(self):
if (
self.valueOf_ is not None
):
return True
else:
return False
def build(self, node_):
attrs = node_.attributes
self.buildAttributes(attrs)
self.valueOf_ = ''
for child_ in node_.childNodes:
nodeName_ = child_.nodeName.split(':')[-1]
self.buildChildren(child_, nodeName_)
def buildAttributes(self, attrs):
pass
def buildChildren(self, child_, nodeName_):
if child_.nodeType == Node.TEXT_NODE:
self.valueOf_ += child_.nodeValue
elif child_.nodeType == Node.CDATA_SECTION_NODE:
self.valueOf_ += '![CDATA['+child_.nodeValue+']]'
# end class docVariableListType
class docRefTextType(GeneratedsSuper):
subclass = None
superclass = None
def __init__(self, refid=None, kindref=None, external=None, valueOf_='', mixedclass_=None, content_=None):
self.refid = refid
self.kindref = kindref
self.external = external
if mixedclass_ is None:
self.mixedclass_ = MixedContainer
else:
self.mixedclass_ = mixedclass_
if content_ is None:
self.content_ = []
else:
self.content_ = content_
def factory(*args_, **kwargs_):
if docRefTextType.subclass:
return docRefTextType.subclass(*args_, **kwargs_)
else:
return docRefTextType(*args_, **kwargs_)
factory = staticmethod(factory)
def get_refid(self): return self.refid
def set_refid(self, refid): self.refid = refid
def get_kindref(self): return self.kindref
def set_kindref(self, kindref): self.kindref = kindref
def get_external(self): return self.external
def set_external(self, external): self.external = external
def getValueOf_(self): return self.valueOf_
def setValueOf_(self, valueOf_): self.valueOf_ = valueOf_
def export(self, outfile, level, namespace_='', name_='docRefTextType', namespacedef_=''):
showIndent(outfile, level)
outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, ))
self.exportAttributes(outfile, level, namespace_, name_='docRefTextType')
outfile.write('>')
self.exportChildren(outfile, level + 1, namespace_, name_)
outfile.write('</%s%s>\n' % (namespace_, name_))
def exportAttributes(self, outfile, level, namespace_='', name_='docRefTextType'):
if self.refid is not None:
outfile.write(' refid=%s' % (self.format_string(quote_attrib(self.refid).encode(ExternalEncoding), input_name='refid'), ))
if self.kindref is not None:
outfile.write(' kindref=%s' % (quote_attrib(self.kindref), ))
if self.external is not None:
outfile.write(' external=%s' % (self.format_string(quote_attrib(self.external).encode(ExternalEncoding), input_name='external'), ))
def exportChildren(self, outfile, level, namespace_='', name_='docRefTextType'):
if self.valueOf_.find('![CDATA')>-1:
value=quote_xml('%s' % self.valueOf_)
value=value.replace('![CDATA','<![CDATA')
value=value.replace(']]',']]>')
outfile.write(value)
else:
outfile.write(quote_xml('%s' % self.valueOf_))
def hasContent_(self):
if (
self.valueOf_ is not None
):
return True
else:
return False
def build(self, node_):
attrs = node_.attributes
self.buildAttributes(attrs)
self.valueOf_ = ''
for child_ in node_.childNodes:
nodeName_ = child_.nodeName.split(':')[-1]
self.buildChildren(child_, nodeName_)
def buildAttributes(self, attrs):
if attrs.get('refid'):
self.refid = attrs.get('refid').value
if attrs.get('kindref'):
self.kindref = attrs.get('kindref').value
if attrs.get('external'):
self.external = attrs.get('external').value
def buildChildren(self, child_, nodeName_):
if child_.nodeType == Node.TEXT_NODE:
obj_ = self.mixedclass_(MixedContainer.CategoryText,
MixedContainer.TypeNone, '', child_.nodeValue)
self.content_.append(obj_)
if child_.nodeType == Node.TEXT_NODE:
self.valueOf_ += child_.nodeValue
elif child_.nodeType == Node.CDATA_SECTION_NODE:
self.valueOf_ += '![CDATA['+child_.nodeValue+']]'
# end class docRefTextType
class docTableType(GeneratedsSuper):
subclass = None
superclass = None
def __init__(self, rows=None, cols=None, row=None, caption=None):
self.rows = rows
self.cols = cols
if row is None:
self.row = []
else:
self.row = row
self.caption = caption
def factory(*args_, **kwargs_):
if docTableType.subclass:
return docTableType.subclass(*args_, **kwargs_)
else:
return docTableType(*args_, **kwargs_)
factory = staticmethod(factory)
def get_row(self): return self.row
def set_row(self, row): self.row = row
def add_row(self, value): self.row.append(value)
def insert_row(self, index, value): self.row[index] = value
def get_caption(self): return self.caption
def set_caption(self, caption): self.caption = caption
def get_rows(self): return self.rows
def set_rows(self, rows): self.rows = rows
def get_cols(self): return self.cols
def set_cols(self, cols): self.cols = cols
def export(self, outfile, level, namespace_='', name_='docTableType', namespacedef_=''):
showIndent(outfile, level)
outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, ))
self.exportAttributes(outfile, level, namespace_, name_='docTableType')
if self.hasContent_():
outfile.write('>\n')
self.exportChildren(outfile, level + 1, namespace_, name_)
showIndent(outfile, level)
outfile.write('</%s%s>\n' % (namespace_, name_))
else:
outfile.write(' />\n')
def exportAttributes(self, outfile, level, namespace_='', name_='docTableType'):
if self.rows is not None:
outfile.write(' rows="%s"' % self.format_integer(self.rows, input_name='rows'))
if self.cols is not None:
outfile.write(' cols="%s"' % self.format_integer(self.cols, input_name='cols'))
def exportChildren(self, outfile, level, namespace_='', name_='docTableType'):
for row_ in self.row:
row_.export(outfile, level, namespace_, name_='row')
if self.caption:
self.caption.export(outfile, level, namespace_, name_='caption')
def hasContent_(self):
if (
self.row is not None or
self.caption is not None
):
return True
else:
return False
def build(self, node_):
attrs = node_.attributes
self.buildAttributes(attrs)
for child_ in node_.childNodes:
nodeName_ = child_.nodeName.split(':')[-1]
self.buildChildren(child_, nodeName_)
def buildAttributes(self, attrs):
if attrs.get('rows'):
try:
self.rows = int(attrs.get('rows').value)
except ValueError as exp:
raise ValueError('Bad integer attribute (rows): %s' % exp)
if attrs.get('cols'):
try:
self.cols = int(attrs.get('cols').value)
except ValueError as exp:
raise ValueError('Bad integer attribute (cols): %s' % exp)
def buildChildren(self, child_, nodeName_):
if child_.nodeType == Node.ELEMENT_NODE and \
nodeName_ == 'row':
obj_ = docRowType.factory()
obj_.build(child_)
self.row.append(obj_)
elif child_.nodeType == Node.ELEMENT_NODE and \
nodeName_ == 'caption':
obj_ = docCaptionType.factory()
obj_.build(child_)
self.set_caption(obj_)
# end class docTableType
class docRowType(GeneratedsSuper):
subclass = None
superclass = None
def __init__(self, entry=None):
if entry is None:
self.entry = []
else:
self.entry = entry
def factory(*args_, **kwargs_):
if docRowType.subclass:
return docRowType.subclass(*args_, **kwargs_)
else:
return docRowType(*args_, **kwargs_)
factory = staticmethod(factory)
def get_entry(self): return self.entry
def set_entry(self, entry): self.entry = entry
def add_entry(self, value): self.entry.append(value)
def insert_entry(self, index, value): self.entry[index] = value
def export(self, outfile, level, namespace_='', name_='docRowType', namespacedef_=''):
showIndent(outfile, level)
outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, ))
self.exportAttributes(outfile, level, namespace_, name_='docRowType')
if self.hasContent_():
outfile.write('>\n')
self.exportChildren(outfile, level + 1, namespace_, name_)
showIndent(outfile, level)
outfile.write('</%s%s>\n' % (namespace_, name_))
else:
outfile.write(' />\n')
def exportAttributes(self, outfile, level, namespace_='', name_='docRowType'):
pass
def exportChildren(self, outfile, level, namespace_='', name_='docRowType'):
for entry_ in self.entry:
entry_.export(outfile, level, namespace_, name_='entry')
def hasContent_(self):
if (
self.entry is not None
):
return True
else:
return False
def build(self, node_):
attrs = node_.attributes
self.buildAttributes(attrs)
for child_ in node_.childNodes:
nodeName_ = child_.nodeName.split(':')[-1]
self.buildChildren(child_, nodeName_)
def buildAttributes(self, attrs):
pass
def buildChildren(self, child_, nodeName_):
if child_.nodeType == Node.ELEMENT_NODE and \
nodeName_ == 'entry':
obj_ = docEntryType.factory()
obj_.build(child_)
self.entry.append(obj_)
# end class docRowType
class docEntryType(GeneratedsSuper):
subclass = None
superclass = None
def __init__(self, thead=None, para=None):
self.thead = thead
if para is None:
self.para = []
else:
self.para = para
def factory(*args_, **kwargs_):
if docEntryType.subclass:
return docEntryType.subclass(*args_, **kwargs_)
else:
return docEntryType(*args_, **kwargs_)
factory = staticmethod(factory)
def get_para(self): return self.para
def set_para(self, para): self.para = para
def add_para(self, value): self.para.append(value)
def insert_para(self, index, value): self.para[index] = value
def get_thead(self): return self.thead
def set_thead(self, thead): self.thead = thead
def export(self, outfile, level, namespace_='', name_='docEntryType', namespacedef_=''):
showIndent(outfile, level)
outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, ))
self.exportAttributes(outfile, level, namespace_, name_='docEntryType')
if self.hasContent_():
outfile.write('>\n')
self.exportChildren(outfile, level + 1, namespace_, name_)
showIndent(outfile, level)
outfile.write('</%s%s>\n' % (namespace_, name_))
else:
outfile.write(' />\n')
def exportAttributes(self, outfile, level, namespace_='', name_='docEntryType'):
if self.thead is not None:
outfile.write(' thead=%s' % (quote_attrib(self.thead), ))
def exportChildren(self, outfile, level, namespace_='', name_='docEntryType'):
for para_ in self.para:
para_.export(outfile, level, namespace_, name_='para')
def hasContent_(self):
if (
self.para is not None
):
return True
else:
return False
def build(self, node_):
attrs = node_.attributes
self.buildAttributes(attrs)
for child_ in node_.childNodes:
nodeName_ = child_.nodeName.split(':')[-1]
self.buildChildren(child_, nodeName_)
def buildAttributes(self, attrs):
if attrs.get('thead'):
self.thead = attrs.get('thead').value
def buildChildren(self, child_, nodeName_):
if child_.nodeType == Node.ELEMENT_NODE and \
nodeName_ == 'para':
obj_ = docParaType.factory()
obj_.build(child_)
self.para.append(obj_)
# end class docEntryType
class docCaptionType(GeneratedsSuper):
subclass = None
superclass = None
def __init__(self, valueOf_='', mixedclass_=None, content_=None):
if mixedclass_ is None:
self.mixedclass_ = MixedContainer
else:
self.mixedclass_ = mixedclass_
if content_ is None:
self.content_ = []
else:
self.content_ = content_
def factory(*args_, **kwargs_):
if docCaptionType.subclass:
return docCaptionType.subclass(*args_, **kwargs_)
else:
return docCaptionType(*args_, **kwargs_)
factory = staticmethod(factory)
def getValueOf_(self): return self.valueOf_
def setValueOf_(self, valueOf_): self.valueOf_ = valueOf_
def export(self, outfile, level, namespace_='', name_='docCaptionType', namespacedef_=''):
showIndent(outfile, level)
outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, ))
self.exportAttributes(outfile, level, namespace_, name_='docCaptionType')
outfile.write('>')
self.exportChildren(outfile, level + 1, namespace_, name_)
outfile.write('</%s%s>\n' % (namespace_, name_))
def exportAttributes(self, outfile, level, namespace_='', name_='docCaptionType'):
pass
def exportChildren(self, outfile, level, namespace_='', name_='docCaptionType'):
if self.valueOf_.find('![CDATA')>-1:
value=quote_xml('%s' % self.valueOf_)
value=value.replace('![CDATA','<![CDATA')
value=value.replace(']]',']]>')
outfile.write(value)
else:
outfile.write(quote_xml('%s' % self.valueOf_))
def hasContent_(self):
if (
self.valueOf_ is not None
):
return True
else:
return False
def build(self, node_):
attrs = node_.attributes
self.buildAttributes(attrs)
self.valueOf_ = ''
for child_ in node_.childNodes:
nodeName_ = child_.nodeName.split(':')[-1]
self.buildChildren(child_, nodeName_)
def buildAttributes(self, attrs):
pass
def buildChildren(self, child_, nodeName_):
if child_.nodeType == Node.TEXT_NODE:
obj_ = self.mixedclass_(MixedContainer.CategoryText,
MixedContainer.TypeNone, '', child_.nodeValue)
self.content_.append(obj_)
if child_.nodeType == Node.TEXT_NODE:
self.valueOf_ += child_.nodeValue
elif child_.nodeType == Node.CDATA_SECTION_NODE:
self.valueOf_ += '![CDATA['+child_.nodeValue+']]'
# end class docCaptionType
class docHeadingType(GeneratedsSuper):
subclass = None
superclass = None
def __init__(self, level=None, valueOf_='', mixedclass_=None, content_=None):
self.level = level
if mixedclass_ is None:
self.mixedclass_ = MixedContainer
else:
self.mixedclass_ = mixedclass_
if content_ is None:
self.content_ = []
else:
self.content_ = content_
def factory(*args_, **kwargs_):
if docHeadingType.subclass:
return docHeadingType.subclass(*args_, **kwargs_)
else:
return docHeadingType(*args_, **kwargs_)
factory = staticmethod(factory)
def get_level(self): return self.level
def set_level(self, level): self.level = level
def getValueOf_(self): return self.valueOf_
def setValueOf_(self, valueOf_): self.valueOf_ = valueOf_
def export(self, outfile, level, namespace_='', name_='docHeadingType', namespacedef_=''):
showIndent(outfile, level)
outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, ))
self.exportAttributes(outfile, level, namespace_, name_='docHeadingType')
outfile.write('>')
self.exportChildren(outfile, level + 1, namespace_, name_)
outfile.write('</%s%s>\n' % (namespace_, name_))
def exportAttributes(self, outfile, level, namespace_='', name_='docHeadingType'):
if self.level is not None:
outfile.write(' level="%s"' % self.format_integer(self.level, input_name='level'))
def exportChildren(self, outfile, level, namespace_='', name_='docHeadingType'):
if self.valueOf_.find('![CDATA')>-1:
value=quote_xml('%s' % self.valueOf_)
value=value.replace('![CDATA','<![CDATA')
value=value.replace(']]',']]>')
outfile.write(value)
else:
outfile.write(quote_xml('%s' % self.valueOf_))
def hasContent_(self):
if (
self.valueOf_ is not None
):
return True
else:
return False
def build(self, node_):
attrs = node_.attributes
self.buildAttributes(attrs)
self.valueOf_ = ''
for child_ in node_.childNodes:
nodeName_ = child_.nodeName.split(':')[-1]
self.buildChildren(child_, nodeName_)
def buildAttributes(self, attrs):
if attrs.get('level'):
try:
self.level = int(attrs.get('level').value)
except ValueError as exp:
raise ValueError('Bad integer attribute (level): %s' % exp)
def buildChildren(self, child_, nodeName_):
if child_.nodeType == Node.TEXT_NODE:
obj_ = self.mixedclass_(MixedContainer.CategoryText,
MixedContainer.TypeNone, '', child_.nodeValue)
self.content_.append(obj_)
if child_.nodeType == Node.TEXT_NODE:
self.valueOf_ += child_.nodeValue
elif child_.nodeType == Node.CDATA_SECTION_NODE:
self.valueOf_ += '![CDATA['+child_.nodeValue+']]'
# end class docHeadingType
class docImageType(GeneratedsSuper):
subclass = None
superclass = None
def __init__(self, width=None, type_=None, name=None, height=None, valueOf_='', mixedclass_=None, content_=None):
self.width = width
self.type_ = type_
self.name = name
self.height = height
if mixedclass_ is None:
self.mixedclass_ = MixedContainer
else:
self.mixedclass_ = mixedclass_
if content_ is None:
self.content_ = []
else:
self.content_ = content_
def factory(*args_, **kwargs_):
if docImageType.subclass:
return docImageType.subclass(*args_, **kwargs_)
else:
return docImageType(*args_, **kwargs_)
factory = staticmethod(factory)
def get_width(self): return self.width
def set_width(self, width): self.width = width
def get_type(self): return self.type_
def set_type(self, type_): self.type_ = type_
def get_name(self): return self.name
def set_name(self, name): self.name = name
def get_height(self): return self.height
def set_height(self, height): self.height = height
def getValueOf_(self): return self.valueOf_
def setValueOf_(self, valueOf_): self.valueOf_ = valueOf_
def export(self, outfile, level, namespace_='', name_='docImageType', namespacedef_=''):
showIndent(outfile, level)
outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, ))
self.exportAttributes(outfile, level, namespace_, name_='docImageType')
outfile.write('>')
self.exportChildren(outfile, level + 1, namespace_, name_)
outfile.write('</%s%s>\n' % (namespace_, name_))
def exportAttributes(self, outfile, level, namespace_='', name_='docImageType'):
if self.width is not None:
outfile.write(' width=%s' % (self.format_string(quote_attrib(self.width).encode(ExternalEncoding), input_name='width'), ))
if self.type_ is not None:
outfile.write(' type=%s' % (quote_attrib(self.type_), ))
if self.name is not None:
outfile.write(' name=%s' % (self.format_string(quote_attrib(self.name).encode(ExternalEncoding), input_name='name'), ))
if self.height is not None:
outfile.write(' height=%s' % (self.format_string(quote_attrib(self.height).encode(ExternalEncoding), input_name='height'), ))
def exportChildren(self, outfile, level, namespace_='', name_='docImageType'):
if self.valueOf_.find('![CDATA')>-1:
value=quote_xml('%s' % self.valueOf_)
value=value.replace('![CDATA','<![CDATA')
value=value.replace(']]',']]>')
outfile.write(value)
else:
outfile.write(quote_xml('%s' % self.valueOf_))
def hasContent_(self):
if (
self.valueOf_ is not None
):
return True
else:
return False
def build(self, node_):
attrs = node_.attributes
self.buildAttributes(attrs)
self.valueOf_ = ''
for child_ in node_.childNodes:
nodeName_ = child_.nodeName.split(':')[-1]
self.buildChildren(child_, nodeName_)
def buildAttributes(self, attrs):
if attrs.get('width'):
self.width = attrs.get('width').value
if attrs.get('type'):
self.type_ = attrs.get('type').value
if attrs.get('name'):
self.name = attrs.get('name').value
if attrs.get('height'):
self.height = attrs.get('height').value
def buildChildren(self, child_, nodeName_):
if child_.nodeType == Node.TEXT_NODE:
obj_ = self.mixedclass_(MixedContainer.CategoryText,
MixedContainer.TypeNone, '', child_.nodeValue)
self.content_.append(obj_)
if child_.nodeType == Node.TEXT_NODE:
self.valueOf_ += child_.nodeValue
elif child_.nodeType == Node.CDATA_SECTION_NODE:
self.valueOf_ += '![CDATA['+child_.nodeValue+']]'
# end class docImageType
class docDotFileType(GeneratedsSuper):
subclass = None
superclass = None
def __init__(self, name=None, valueOf_='', mixedclass_=None, content_=None):
self.name = name
if mixedclass_ is None:
self.mixedclass_ = MixedContainer
else:
self.mixedclass_ = mixedclass_
if content_ is None:
self.content_ = []
else:
self.content_ = content_
def factory(*args_, **kwargs_):
if docDotFileType.subclass:
return docDotFileType.subclass(*args_, **kwargs_)
else:
return docDotFileType(*args_, **kwargs_)
factory = staticmethod(factory)
def get_name(self): return self.name
def set_name(self, name): self.name = name
def getValueOf_(self): return self.valueOf_
def setValueOf_(self, valueOf_): self.valueOf_ = valueOf_
def export(self, outfile, level, namespace_='', name_='docDotFileType', namespacedef_=''):
showIndent(outfile, level)
outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, ))
self.exportAttributes(outfile, level, namespace_, name_='docDotFileType')
outfile.write('>')
self.exportChildren(outfile, level + 1, namespace_, name_)
outfile.write('</%s%s>\n' % (namespace_, name_))
def exportAttributes(self, outfile, level, namespace_='', name_='docDotFileType'):
if self.name is not None:
outfile.write(' name=%s' % (self.format_string(quote_attrib(self.name).encode(ExternalEncoding), input_name='name'), ))
def exportChildren(self, outfile, level, namespace_='', name_='docDotFileType'):
if self.valueOf_.find('![CDATA')>-1:
value=quote_xml('%s' % self.valueOf_)
value=value.replace('![CDATA','<![CDATA')
value=value.replace(']]',']]>')
outfile.write(value)
else:
outfile.write(quote_xml('%s' % self.valueOf_))
def hasContent_(self):
if (
self.valueOf_ is not None
):
return True
else:
return False
def build(self, node_):
attrs = node_.attributes
self.buildAttributes(attrs)
self.valueOf_ = ''
for child_ in node_.childNodes:
nodeName_ = child_.nodeName.split(':')[-1]
self.buildChildren(child_, nodeName_)
def buildAttributes(self, attrs):
if attrs.get('name'):
self.name = attrs.get('name').value
def buildChildren(self, child_, nodeName_):
if child_.nodeType == Node.TEXT_NODE:
obj_ = self.mixedclass_(MixedContainer.CategoryText,
MixedContainer.TypeNone, '', child_.nodeValue)
self.content_.append(obj_)
if child_.nodeType == Node.TEXT_NODE:
self.valueOf_ += child_.nodeValue
elif child_.nodeType == Node.CDATA_SECTION_NODE:
self.valueOf_ += '![CDATA['+child_.nodeValue+']]'
# end class docDotFileType
class docTocItemType(GeneratedsSuper):
subclass = None
superclass = None
def __init__(self, id=None, valueOf_='', mixedclass_=None, content_=None):
self.id = id
if mixedclass_ is None:
self.mixedclass_ = MixedContainer
else:
self.mixedclass_ = mixedclass_
if content_ is None:
self.content_ = []
else:
self.content_ = content_
def factory(*args_, **kwargs_):
if docTocItemType.subclass:
return docTocItemType.subclass(*args_, **kwargs_)
else:
return docTocItemType(*args_, **kwargs_)
factory = staticmethod(factory)
def get_id(self): return self.id
def set_id(self, id): self.id = id
def getValueOf_(self): return self.valueOf_
def setValueOf_(self, valueOf_): self.valueOf_ = valueOf_
def export(self, outfile, level, namespace_='', name_='docTocItemType', namespacedef_=''):
showIndent(outfile, level)
outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, ))
self.exportAttributes(outfile, level, namespace_, name_='docTocItemType')
outfile.write('>')
self.exportChildren(outfile, level + 1, namespace_, name_)
outfile.write('</%s%s>\n' % (namespace_, name_))
def exportAttributes(self, outfile, level, namespace_='', name_='docTocItemType'):
if self.id is not None:
outfile.write(' id=%s' % (self.format_string(quote_attrib(self.id).encode(ExternalEncoding), input_name='id'), ))
def exportChildren(self, outfile, level, namespace_='', name_='docTocItemType'):
if self.valueOf_.find('![CDATA')>-1:
value=quote_xml('%s' % self.valueOf_)
value=value.replace('![CDATA','<![CDATA')
value=value.replace(']]',']]>')
outfile.write(value)
else:
outfile.write(quote_xml('%s' % self.valueOf_))
def hasContent_(self):
if (
self.valueOf_ is not None
):
return True
else:
return False
def build(self, node_):
attrs = node_.attributes
self.buildAttributes(attrs)
self.valueOf_ = ''
for child_ in node_.childNodes:
nodeName_ = child_.nodeName.split(':')[-1]
self.buildChildren(child_, nodeName_)
def buildAttributes(self, attrs):
if attrs.get('id'):
self.id = attrs.get('id').value
def buildChildren(self, child_, nodeName_):
if child_.nodeType == Node.TEXT_NODE:
obj_ = self.mixedclass_(MixedContainer.CategoryText,
MixedContainer.TypeNone, '', child_.nodeValue)
self.content_.append(obj_)
if child_.nodeType == Node.TEXT_NODE:
self.valueOf_ += child_.nodeValue
elif child_.nodeType == Node.CDATA_SECTION_NODE:
self.valueOf_ += '![CDATA['+child_.nodeValue+']]'
# end class docTocItemType
class docTocListType(GeneratedsSuper):
subclass = None
superclass = None
def __init__(self, tocitem=None):
if tocitem is None:
self.tocitem = []
else:
self.tocitem = tocitem
def factory(*args_, **kwargs_):
if docTocListType.subclass:
return docTocListType.subclass(*args_, **kwargs_)
else:
return docTocListType(*args_, **kwargs_)
factory = staticmethod(factory)
def get_tocitem(self): return self.tocitem
def set_tocitem(self, tocitem): self.tocitem = tocitem
def add_tocitem(self, value): self.tocitem.append(value)
def insert_tocitem(self, index, value): self.tocitem[index] = value
def export(self, outfile, level, namespace_='', name_='docTocListType', namespacedef_=''):
showIndent(outfile, level)
outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, ))
self.exportAttributes(outfile, level, namespace_, name_='docTocListType')
if self.hasContent_():
outfile.write('>\n')
self.exportChildren(outfile, level + 1, namespace_, name_)
showIndent(outfile, level)
outfile.write('</%s%s>\n' % (namespace_, name_))
else:
outfile.write(' />\n')
def exportAttributes(self, outfile, level, namespace_='', name_='docTocListType'):
pass
def exportChildren(self, outfile, level, namespace_='', name_='docTocListType'):
for tocitem_ in self.tocitem:
tocitem_.export(outfile, level, namespace_, name_='tocitem')
def hasContent_(self):
if (
self.tocitem is not None
):
return True
else:
return False
def build(self, node_):
attrs = node_.attributes
self.buildAttributes(attrs)
for child_ in node_.childNodes:
nodeName_ = child_.nodeName.split(':')[-1]
self.buildChildren(child_, nodeName_)
def buildAttributes(self, attrs):
pass
def buildChildren(self, child_, nodeName_):
if child_.nodeType == Node.ELEMENT_NODE and \
nodeName_ == 'tocitem':
obj_ = docTocItemType.factory()
obj_.build(child_)
self.tocitem.append(obj_)
# end class docTocListType
class docLanguageType(GeneratedsSuper):
subclass = None
superclass = None
def __init__(self, langid=None, para=None):
self.langid = langid
if para is None:
self.para = []
else:
self.para = para
def factory(*args_, **kwargs_):
if docLanguageType.subclass:
return docLanguageType.subclass(*args_, **kwargs_)
else:
return docLanguageType(*args_, **kwargs_)
factory = staticmethod(factory)
def get_para(self): return self.para
def set_para(self, para): self.para = para
def add_para(self, value): self.para.append(value)
def insert_para(self, index, value): self.para[index] = value
def get_langid(self): return self.langid
def set_langid(self, langid): self.langid = langid
def export(self, outfile, level, namespace_='', name_='docLanguageType', namespacedef_=''):
showIndent(outfile, level)
outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, ))
self.exportAttributes(outfile, level, namespace_, name_='docLanguageType')
if self.hasContent_():
outfile.write('>\n')
self.exportChildren(outfile, level + 1, namespace_, name_)
showIndent(outfile, level)
outfile.write('</%s%s>\n' % (namespace_, name_))
else:
outfile.write(' />\n')
def exportAttributes(self, outfile, level, namespace_='', name_='docLanguageType'):
if self.langid is not None:
outfile.write(' langid=%s' % (self.format_string(quote_attrib(self.langid).encode(ExternalEncoding), input_name='langid'), ))
def exportChildren(self, outfile, level, namespace_='', name_='docLanguageType'):
for para_ in self.para:
para_.export(outfile, level, namespace_, name_='para')
def hasContent_(self):
if (
self.para is not None
):
return True
else:
return False
def build(self, node_):
attrs = node_.attributes
self.buildAttributes(attrs)
for child_ in node_.childNodes:
nodeName_ = child_.nodeName.split(':')[-1]
self.buildChildren(child_, nodeName_)
def buildAttributes(self, attrs):
if attrs.get('langid'):
self.langid = attrs.get('langid').value
def buildChildren(self, child_, nodeName_):
if child_.nodeType == Node.ELEMENT_NODE and \
nodeName_ == 'para':
obj_ = docParaType.factory()
obj_.build(child_)
self.para.append(obj_)
# end class docLanguageType
class docParamListType(GeneratedsSuper):
subclass = None
superclass = None
def __init__(self, kind=None, parameteritem=None):
self.kind = kind
if parameteritem is None:
self.parameteritem = []
else:
self.parameteritem = parameteritem
def factory(*args_, **kwargs_):
if docParamListType.subclass:
return docParamListType.subclass(*args_, **kwargs_)
else:
return docParamListType(*args_, **kwargs_)
factory = staticmethod(factory)
def get_parameteritem(self): return self.parameteritem
def set_parameteritem(self, parameteritem): self.parameteritem = parameteritem
def add_parameteritem(self, value): self.parameteritem.append(value)
def insert_parameteritem(self, index, value): self.parameteritem[index] = value
def get_kind(self): return self.kind
def set_kind(self, kind): self.kind = kind
def export(self, outfile, level, namespace_='', name_='docParamListType', namespacedef_=''):
showIndent(outfile, level)
outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, ))
self.exportAttributes(outfile, level, namespace_, name_='docParamListType')
if self.hasContent_():
outfile.write('>\n')
self.exportChildren(outfile, level + 1, namespace_, name_)
showIndent(outfile, level)
outfile.write('</%s%s>\n' % (namespace_, name_))
else:
outfile.write(' />\n')
def exportAttributes(self, outfile, level, namespace_='', name_='docParamListType'):
if self.kind is not None:
outfile.write(' kind=%s' % (quote_attrib(self.kind), ))
def exportChildren(self, outfile, level, namespace_='', name_='docParamListType'):
for parameteritem_ in self.parameteritem:
parameteritem_.export(outfile, level, namespace_, name_='parameteritem')
def hasContent_(self):
if (
self.parameteritem is not None
):
return True
else:
return False
def build(self, node_):
attrs = node_.attributes
self.buildAttributes(attrs)
for child_ in node_.childNodes:
nodeName_ = child_.nodeName.split(':')[-1]
self.buildChildren(child_, nodeName_)
def buildAttributes(self, attrs):
if attrs.get('kind'):
self.kind = attrs.get('kind').value
def buildChildren(self, child_, nodeName_):
if child_.nodeType == Node.ELEMENT_NODE and \
nodeName_ == 'parameteritem':
obj_ = docParamListItem.factory()
obj_.build(child_)
self.parameteritem.append(obj_)
# end class docParamListType
class docParamListItem(GeneratedsSuper):
subclass = None
superclass = None
def __init__(self, parameternamelist=None, parameterdescription=None):
if parameternamelist is None:
self.parameternamelist = []
else:
self.parameternamelist = parameternamelist
self.parameterdescription = parameterdescription
def factory(*args_, **kwargs_):
if docParamListItem.subclass:
return docParamListItem.subclass(*args_, **kwargs_)
else:
return docParamListItem(*args_, **kwargs_)
factory = staticmethod(factory)
def get_parameternamelist(self): return self.parameternamelist
def set_parameternamelist(self, parameternamelist): self.parameternamelist = parameternamelist
def add_parameternamelist(self, value): self.parameternamelist.append(value)
def insert_parameternamelist(self, index, value): self.parameternamelist[index] = value
def get_parameterdescription(self): return self.parameterdescription
def set_parameterdescription(self, parameterdescription): self.parameterdescription = parameterdescription
def export(self, outfile, level, namespace_='', name_='docParamListItem', namespacedef_=''):
showIndent(outfile, level)
outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, ))
self.exportAttributes(outfile, level, namespace_, name_='docParamListItem')
if self.hasContent_():
outfile.write('>\n')
self.exportChildren(outfile, level + 1, namespace_, name_)
showIndent(outfile, level)
outfile.write('</%s%s>\n' % (namespace_, name_))
else:
outfile.write(' />\n')
def exportAttributes(self, outfile, level, namespace_='', name_='docParamListItem'):
pass
def exportChildren(self, outfile, level, namespace_='', name_='docParamListItem'):
for parameternamelist_ in self.parameternamelist:
parameternamelist_.export(outfile, level, namespace_, name_='parameternamelist')
if self.parameterdescription:
self.parameterdescription.export(outfile, level, namespace_, name_='parameterdescription', )
def hasContent_(self):
if (
self.parameternamelist is not None or
self.parameterdescription is not None
):
return True
else:
return False
def build(self, node_):
attrs = node_.attributes
self.buildAttributes(attrs)
for child_ in node_.childNodes:
nodeName_ = child_.nodeName.split(':')[-1]
self.buildChildren(child_, nodeName_)
def buildAttributes(self, attrs):
pass
def buildChildren(self, child_, nodeName_):
if child_.nodeType == Node.ELEMENT_NODE and \
nodeName_ == 'parameternamelist':
obj_ = docParamNameList.factory()
obj_.build(child_)
self.parameternamelist.append(obj_)
elif child_.nodeType == Node.ELEMENT_NODE and \
nodeName_ == 'parameterdescription':
obj_ = descriptionType.factory()
obj_.build(child_)
self.set_parameterdescription(obj_)
# end class docParamListItem
class docParamNameList(GeneratedsSuper):
subclass = None
superclass = None
def __init__(self, parametername=None):
if parametername is None:
self.parametername = []
else:
self.parametername = parametername
def factory(*args_, **kwargs_):
if docParamNameList.subclass:
return docParamNameList.subclass(*args_, **kwargs_)
else:
return docParamNameList(*args_, **kwargs_)
factory = staticmethod(factory)
def get_parametername(self): return self.parametername
def set_parametername(self, parametername): self.parametername = parametername
def add_parametername(self, value): self.parametername.append(value)
def insert_parametername(self, index, value): self.parametername[index] = value
def export(self, outfile, level, namespace_='', name_='docParamNameList', namespacedef_=''):
showIndent(outfile, level)
outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, ))
self.exportAttributes(outfile, level, namespace_, name_='docParamNameList')
if self.hasContent_():
outfile.write('>\n')
self.exportChildren(outfile, level + 1, namespace_, name_)
showIndent(outfile, level)
outfile.write('</%s%s>\n' % (namespace_, name_))
else:
outfile.write(' />\n')
def exportAttributes(self, outfile, level, namespace_='', name_='docParamNameList'):
pass
def exportChildren(self, outfile, level, namespace_='', name_='docParamNameList'):
for parametername_ in self.parametername:
parametername_.export(outfile, level, namespace_, name_='parametername')
def hasContent_(self):
if (
self.parametername is not None
):
return True
else:
return False
def build(self, node_):
attrs = node_.attributes
self.buildAttributes(attrs)
for child_ in node_.childNodes:
nodeName_ = child_.nodeName.split(':')[-1]
self.buildChildren(child_, nodeName_)
def buildAttributes(self, attrs):
pass
def buildChildren(self, child_, nodeName_):
if child_.nodeType == Node.ELEMENT_NODE and \
nodeName_ == 'parametername':
obj_ = docParamName.factory()
obj_.build(child_)
self.parametername.append(obj_)
# end class docParamNameList
class docParamName(GeneratedsSuper):
subclass = None
superclass = None
def __init__(self, direction=None, ref=None, mixedclass_=None, content_=None):
self.direction = direction
if mixedclass_ is None:
self.mixedclass_ = MixedContainer
else:
self.mixedclass_ = mixedclass_
if content_ is None:
self.content_ = []
else:
self.content_ = content_
def factory(*args_, **kwargs_):
if docParamName.subclass:
return docParamName.subclass(*args_, **kwargs_)
else:
return docParamName(*args_, **kwargs_)
factory = staticmethod(factory)
def get_ref(self): return self.ref
def set_ref(self, ref): self.ref = ref
def get_direction(self): return self.direction
def set_direction(self, direction): self.direction = direction
def export(self, outfile, level, namespace_='', name_='docParamName', namespacedef_=''):
showIndent(outfile, level)
outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, ))
self.exportAttributes(outfile, level, namespace_, name_='docParamName')
outfile.write('>')
self.exportChildren(outfile, level + 1, namespace_, name_)
outfile.write('</%s%s>\n' % (namespace_, name_))
def exportAttributes(self, outfile, level, namespace_='', name_='docParamName'):
if self.direction is not None:
outfile.write(' direction=%s' % (quote_attrib(self.direction), ))
def exportChildren(self, outfile, level, namespace_='', name_='docParamName'):
for item_ in self.content_:
item_.export(outfile, level, item_.name, namespace_)
def hasContent_(self):
if (
self.ref is not None
):
return True
else:
return False
def build(self, node_):
attrs = node_.attributes
self.buildAttributes(attrs)
for child_ in node_.childNodes:
nodeName_ = child_.nodeName.split(':')[-1]
self.buildChildren(child_, nodeName_)
def buildAttributes(self, attrs):
if attrs.get('direction'):
self.direction = attrs.get('direction').value
def buildChildren(self, child_, nodeName_):
if child_.nodeType == Node.ELEMENT_NODE and \
nodeName_ == 'ref':
childobj_ = docRefTextType.factory()
childobj_.build(child_)
obj_ = self.mixedclass_(MixedContainer.CategoryComplex,
MixedContainer.TypeNone, 'ref', childobj_)
self.content_.append(obj_)
elif child_.nodeType == Node.TEXT_NODE:
obj_ = self.mixedclass_(MixedContainer.CategoryText,
MixedContainer.TypeNone, '', child_.nodeValue)
self.content_.append(obj_)
# end class docParamName
class docXRefSectType(GeneratedsSuper):
subclass = None
superclass = None
def __init__(self, id=None, xreftitle=None, xrefdescription=None):
self.id = id
if xreftitle is None:
self.xreftitle = []
else:
self.xreftitle = xreftitle
self.xrefdescription = xrefdescription
def factory(*args_, **kwargs_):
if docXRefSectType.subclass:
return docXRefSectType.subclass(*args_, **kwargs_)
else:
return docXRefSectType(*args_, **kwargs_)
factory = staticmethod(factory)
def get_xreftitle(self): return self.xreftitle
def set_xreftitle(self, xreftitle): self.xreftitle = xreftitle
def add_xreftitle(self, value): self.xreftitle.append(value)
def insert_xreftitle(self, index, value): self.xreftitle[index] = value
def get_xrefdescription(self): return self.xrefdescription
def set_xrefdescription(self, xrefdescription): self.xrefdescription = xrefdescription
def get_id(self): return self.id
def set_id(self, id): self.id = id
def export(self, outfile, level, namespace_='', name_='docXRefSectType', namespacedef_=''):
showIndent(outfile, level)
outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, ))
self.exportAttributes(outfile, level, namespace_, name_='docXRefSectType')
if self.hasContent_():
outfile.write('>\n')
self.exportChildren(outfile, level + 1, namespace_, name_)
showIndent(outfile, level)
outfile.write('</%s%s>\n' % (namespace_, name_))
else:
outfile.write(' />\n')
def exportAttributes(self, outfile, level, namespace_='', name_='docXRefSectType'):
if self.id is not None:
outfile.write(' id=%s' % (self.format_string(quote_attrib(self.id).encode(ExternalEncoding), input_name='id'), ))
def exportChildren(self, outfile, level, namespace_='', name_='docXRefSectType'):
for xreftitle_ in self.xreftitle:
showIndent(outfile, level)
outfile.write('<%sxreftitle>%s</%sxreftitle>\n' % (namespace_, self.format_string(quote_xml(xreftitle_).encode(ExternalEncoding), input_name='xreftitle'), namespace_))
if self.xrefdescription:
self.xrefdescription.export(outfile, level, namespace_, name_='xrefdescription', )
def hasContent_(self):
if (
self.xreftitle is not None or
self.xrefdescription is not None
):
return True
else:
return False
def build(self, node_):
attrs = node_.attributes
self.buildAttributes(attrs)
for child_ in node_.childNodes:
nodeName_ = child_.nodeName.split(':')[-1]
self.buildChildren(child_, nodeName_)
def buildAttributes(self, attrs):
if attrs.get('id'):
self.id = attrs.get('id').value
def buildChildren(self, child_, nodeName_):
if child_.nodeType == Node.ELEMENT_NODE and \
nodeName_ == 'xreftitle':
xreftitle_ = ''
for text__content_ in child_.childNodes:
xreftitle_ += text__content_.nodeValue
self.xreftitle.append(xreftitle_)
elif child_.nodeType == Node.ELEMENT_NODE and \
nodeName_ == 'xrefdescription':
obj_ = descriptionType.factory()
obj_.build(child_)
self.set_xrefdescription(obj_)
# end class docXRefSectType
class docCopyType(GeneratedsSuper):
subclass = None
superclass = None
def __init__(self, link=None, para=None, sect1=None, internal=None):
self.link = link
if para is None:
self.para = []
else:
self.para = para
if sect1 is None:
self.sect1 = []
else:
self.sect1 = sect1
self.internal = internal
def factory(*args_, **kwargs_):
if docCopyType.subclass:
return docCopyType.subclass(*args_, **kwargs_)
else:
return docCopyType(*args_, **kwargs_)
factory = staticmethod(factory)
def get_para(self): return self.para
def set_para(self, para): self.para = para
def add_para(self, value): self.para.append(value)
def insert_para(self, index, value): self.para[index] = value
def get_sect1(self): return self.sect1
def set_sect1(self, sect1): self.sect1 = sect1
def add_sect1(self, value): self.sect1.append(value)
def insert_sect1(self, index, value): self.sect1[index] = value
def get_internal(self): return self.internal
def set_internal(self, internal): self.internal = internal
def get_link(self): return self.link
def set_link(self, link): self.link = link
def export(self, outfile, level, namespace_='', name_='docCopyType', namespacedef_=''):
showIndent(outfile, level)
outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, ))
self.exportAttributes(outfile, level, namespace_, name_='docCopyType')
if self.hasContent_():
outfile.write('>\n')
self.exportChildren(outfile, level + 1, namespace_, name_)
showIndent(outfile, level)
outfile.write('</%s%s>\n' % (namespace_, name_))
else:
outfile.write(' />\n')
def exportAttributes(self, outfile, level, namespace_='', name_='docCopyType'):
if self.link is not None:
outfile.write(' link=%s' % (self.format_string(quote_attrib(self.link).encode(ExternalEncoding), input_name='link'), ))
def exportChildren(self, outfile, level, namespace_='', name_='docCopyType'):
for para_ in self.para:
para_.export(outfile, level, namespace_, name_='para')
for sect1_ in self.sect1:
sect1_.export(outfile, level, namespace_, name_='sect1')
if self.internal:
self.internal.export(outfile, level, namespace_, name_='internal')
def hasContent_(self):
if (
self.para is not None or
self.sect1 is not None or
self.internal is not None
):
return True
else:
return False
def build(self, node_):
attrs = node_.attributes
self.buildAttributes(attrs)
for child_ in node_.childNodes:
nodeName_ = child_.nodeName.split(':')[-1]
self.buildChildren(child_, nodeName_)
def buildAttributes(self, attrs):
if attrs.get('link'):
self.link = attrs.get('link').value
def buildChildren(self, child_, nodeName_):
if child_.nodeType == Node.ELEMENT_NODE and \
nodeName_ == 'para':
obj_ = docParaType.factory()
obj_.build(child_)
self.para.append(obj_)
elif child_.nodeType == Node.ELEMENT_NODE and \
nodeName_ == 'sect1':
obj_ = docSect1Type.factory()
obj_.build(child_)
self.sect1.append(obj_)
elif child_.nodeType == Node.ELEMENT_NODE and \
nodeName_ == 'internal':
obj_ = docInternalType.factory()
obj_.build(child_)
self.set_internal(obj_)
# end class docCopyType
class docCharType(GeneratedsSuper):
subclass = None
superclass = None
def __init__(self, char=None, valueOf_=''):
self.char = char
self.valueOf_ = valueOf_
def factory(*args_, **kwargs_):
if docCharType.subclass:
return docCharType.subclass(*args_, **kwargs_)
else:
return docCharType(*args_, **kwargs_)
factory = staticmethod(factory)
def get_char(self): return self.char
def set_char(self, char): self.char = char
def getValueOf_(self): return self.valueOf_
def setValueOf_(self, valueOf_): self.valueOf_ = valueOf_
def export(self, outfile, level, namespace_='', name_='docCharType', namespacedef_=''):
showIndent(outfile, level)
outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, ))
self.exportAttributes(outfile, level, namespace_, name_='docCharType')
if self.hasContent_():
outfile.write('>\n')
self.exportChildren(outfile, level + 1, namespace_, name_)
showIndent(outfile, level)
outfile.write('</%s%s>\n' % (namespace_, name_))
else:
outfile.write(' />\n')
def exportAttributes(self, outfile, level, namespace_='', name_='docCharType'):
if self.char is not None:
outfile.write(' char=%s' % (quote_attrib(self.char), ))
def exportChildren(self, outfile, level, namespace_='', name_='docCharType'):
if self.valueOf_.find('![CDATA')>-1:
value=quote_xml('%s' % self.valueOf_)
value=value.replace('![CDATA','<![CDATA')
value=value.replace(']]',']]>')
outfile.write(value)
else:
outfile.write(quote_xml('%s' % self.valueOf_))
def hasContent_(self):
if (
self.valueOf_ is not None
):
return True
else:
return False
def build(self, node_):
attrs = node_.attributes
self.buildAttributes(attrs)
self.valueOf_ = ''
for child_ in node_.childNodes:
nodeName_ = child_.nodeName.split(':')[-1]
self.buildChildren(child_, nodeName_)
def buildAttributes(self, attrs):
if attrs.get('char'):
self.char = attrs.get('char').value
def buildChildren(self, child_, nodeName_):
if child_.nodeType == Node.TEXT_NODE:
self.valueOf_ += child_.nodeValue
elif child_.nodeType == Node.CDATA_SECTION_NODE:
self.valueOf_ += '![CDATA['+child_.nodeValue+']]'
# end class docCharType
class docEmptyType(GeneratedsSuper):
subclass = None
superclass = None
def __init__(self, valueOf_=''):
self.valueOf_ = valueOf_
def factory(*args_, **kwargs_):
if docEmptyType.subclass:
return docEmptyType.subclass(*args_, **kwargs_)
else:
return docEmptyType(*args_, **kwargs_)
factory = staticmethod(factory)
def getValueOf_(self): return self.valueOf_
def setValueOf_(self, valueOf_): self.valueOf_ = valueOf_
def export(self, outfile, level, namespace_='', name_='docEmptyType', namespacedef_=''):
showIndent(outfile, level)
outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, ))
self.exportAttributes(outfile, level, namespace_, name_='docEmptyType')
if self.hasContent_():
outfile.write('>\n')
self.exportChildren(outfile, level + 1, namespace_, name_)
showIndent(outfile, level)
outfile.write('</%s%s>\n' % (namespace_, name_))
else:
outfile.write(' />\n')
def exportAttributes(self, outfile, level, namespace_='', name_='docEmptyType'):
pass
def exportChildren(self, outfile, level, namespace_='', name_='docEmptyType'):
if self.valueOf_.find('![CDATA')>-1:
value=quote_xml('%s' % self.valueOf_)
value=value.replace('![CDATA','<![CDATA')
value=value.replace(']]',']]>')
outfile.write(value)
else:
outfile.write(quote_xml('%s' % self.valueOf_))
def hasContent_(self):
if (
self.valueOf_ is not None
):
return True
else:
return False
def build(self, node_):
attrs = node_.attributes
self.buildAttributes(attrs)
self.valueOf_ = ''
for child_ in node_.childNodes:
nodeName_ = child_.nodeName.split(':')[-1]
self.buildChildren(child_, nodeName_)
def buildAttributes(self, attrs):
pass
def buildChildren(self, child_, nodeName_):
if child_.nodeType == Node.TEXT_NODE:
self.valueOf_ += child_.nodeValue
elif child_.nodeType == Node.CDATA_SECTION_NODE:
self.valueOf_ += '![CDATA['+child_.nodeValue+']]'
# end class docEmptyType
USAGE_TEXT = """
Usage: python <Parser>.py [ -s ] <in_xml_file>
Options:
-s Use the SAX parser, not the minidom parser.
"""
def usage():
print(USAGE_TEXT)
sys.exit(1)
def parse(inFileName):
doc = minidom.parse(inFileName)
rootNode = doc.documentElement
rootObj = DoxygenType.factory()
rootObj.build(rootNode)
# Enable Python to collect the space used by the DOM.
doc = None
sys.stdout.write('<?xml version="1.0" ?>\n')
rootObj.export(sys.stdout, 0, name_="doxygen",
namespacedef_='')
return rootObj
def parseString(inString):
doc = minidom.parseString(inString)
rootNode = doc.documentElement
rootObj = DoxygenType.factory()
rootObj.build(rootNode)
# Enable Python to collect the space used by the DOM.
doc = None
sys.stdout.write('<?xml version="1.0" ?>\n')
rootObj.export(sys.stdout, 0, name_="doxygen",
namespacedef_='')
return rootObj
def parseLiteral(inFileName):
doc = minidom.parse(inFileName)
rootNode = doc.documentElement
rootObj = DoxygenType.factory()
rootObj.build(rootNode)
# Enable Python to collect the space used by the DOM.
doc = None
sys.stdout.write('from compound import *\n\n')
sys.stdout.write('rootObj = doxygen(\n')
rootObj.exportLiteral(sys.stdout, 0, name_="doxygen")
sys.stdout.write(')\n')
return rootObj
def main():
args = sys.argv[1:]
if len(args) == 1:
parse(args[0])
else:
usage()
if __name__ == '__main__':
main()
#import pdb
#pdb.run('main()')
| apache-2.0 |
PlushBeaver/FanFicFare | included_dependencies/six.py | 320 | 27344 | """Utilities for writing code that runs on Python 2 and 3"""
# Copyright (c) 2010-2014 Benjamin Peterson
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
from __future__ import absolute_import
import functools
import operator
import sys
import types
__author__ = "Benjamin Peterson <benjamin@python.org>"
__version__ = "1.8.0"
# Useful for very coarse version differentiation.
PY2 = sys.version_info[0] == 2
PY3 = sys.version_info[0] == 3
if PY3:
string_types = str,
integer_types = int,
class_types = type,
text_type = str
binary_type = bytes
MAXSIZE = sys.maxsize
else:
string_types = basestring,
integer_types = (int, long)
class_types = (type, types.ClassType)
text_type = unicode
binary_type = str
if sys.platform.startswith("java"):
# Jython always uses 32 bits.
MAXSIZE = int((1 << 31) - 1)
else:
# It's possible to have sizeof(long) != sizeof(Py_ssize_t).
class X(object):
def __len__(self):
return 1 << 31
try:
len(X())
except OverflowError:
# 32-bit
MAXSIZE = int((1 << 31) - 1)
else:
# 64-bit
MAXSIZE = int((1 << 63) - 1)
del X
def _add_doc(func, doc):
"""Add documentation to a function."""
func.__doc__ = doc
def _import_module(name):
"""Import module, returning the module after the last dot."""
__import__(name)
return sys.modules[name]
class _LazyDescr(object):
def __init__(self, name):
self.name = name
def __get__(self, obj, tp):
result = self._resolve()
setattr(obj, self.name, result) # Invokes __set__.
# This is a bit ugly, but it avoids running this again.
delattr(obj.__class__, self.name)
return result
class MovedModule(_LazyDescr):
def __init__(self, name, old, new=None):
super(MovedModule, self).__init__(name)
if PY3:
if new is None:
new = name
self.mod = new
else:
self.mod = old
def _resolve(self):
return _import_module(self.mod)
def __getattr__(self, attr):
_module = self._resolve()
value = getattr(_module, attr)
setattr(self, attr, value)
return value
class _LazyModule(types.ModuleType):
def __init__(self, name):
super(_LazyModule, self).__init__(name)
self.__doc__ = self.__class__.__doc__
def __dir__(self):
attrs = ["__doc__", "__name__"]
attrs += [attr.name for attr in self._moved_attributes]
return attrs
# Subclasses should override this
_moved_attributes = []
class MovedAttribute(_LazyDescr):
def __init__(self, name, old_mod, new_mod, old_attr=None, new_attr=None):
super(MovedAttribute, self).__init__(name)
if PY3:
if new_mod is None:
new_mod = name
self.mod = new_mod
if new_attr is None:
if old_attr is None:
new_attr = name
else:
new_attr = old_attr
self.attr = new_attr
else:
self.mod = old_mod
if old_attr is None:
old_attr = name
self.attr = old_attr
def _resolve(self):
module = _import_module(self.mod)
return getattr(module, self.attr)
class _SixMetaPathImporter(object):
"""
A meta path importer to import six.moves and its submodules.
This class implements a PEP302 finder and loader. It should be compatible
with Python 2.5 and all existing versions of Python3
"""
def __init__(self, six_module_name):
self.name = six_module_name
self.known_modules = {}
def _add_module(self, mod, *fullnames):
for fullname in fullnames:
self.known_modules[self.name + "." + fullname] = mod
def _get_module(self, fullname):
return self.known_modules[self.name + "." + fullname]
def find_module(self, fullname, path=None):
if fullname in self.known_modules:
return self
return None
def __get_module(self, fullname):
try:
return self.known_modules[fullname]
except KeyError:
raise ImportError("This loader does not know module " + fullname)
def load_module(self, fullname):
try:
# in case of a reload
return sys.modules[fullname]
except KeyError:
pass
mod = self.__get_module(fullname)
if isinstance(mod, MovedModule):
mod = mod._resolve()
else:
mod.__loader__ = self
sys.modules[fullname] = mod
return mod
def is_package(self, fullname):
"""
Return true, if the named module is a package.
We need this method to get correct spec objects with
Python 3.4 (see PEP451)
"""
return hasattr(self.__get_module(fullname), "__path__")
def get_code(self, fullname):
"""Return None
Required, if is_package is implemented"""
self.__get_module(fullname) # eventually raises ImportError
return None
get_source = get_code # same as get_code
_importer = _SixMetaPathImporter(__name__)
class _MovedItems(_LazyModule):
"""Lazy loading of moved objects"""
__path__ = [] # mark as package
_moved_attributes = [
MovedAttribute("cStringIO", "cStringIO", "io", "StringIO"),
MovedAttribute("filter", "itertools", "builtins", "ifilter", "filter"),
MovedAttribute("filterfalse", "itertools", "itertools", "ifilterfalse", "filterfalse"),
MovedAttribute("input", "__builtin__", "builtins", "raw_input", "input"),
MovedAttribute("intern", "__builtin__", "sys"),
MovedAttribute("map", "itertools", "builtins", "imap", "map"),
MovedAttribute("range", "__builtin__", "builtins", "xrange", "range"),
MovedAttribute("reload_module", "__builtin__", "imp", "reload"),
MovedAttribute("reduce", "__builtin__", "functools"),
MovedAttribute("shlex_quote", "pipes", "shlex", "quote"),
MovedAttribute("StringIO", "StringIO", "io"),
MovedAttribute("UserDict", "UserDict", "collections"),
MovedAttribute("UserList", "UserList", "collections"),
MovedAttribute("UserString", "UserString", "collections"),
MovedAttribute("xrange", "__builtin__", "builtins", "xrange", "range"),
MovedAttribute("zip", "itertools", "builtins", "izip", "zip"),
MovedAttribute("zip_longest", "itertools", "itertools", "izip_longest", "zip_longest"),
MovedModule("builtins", "__builtin__"),
MovedModule("configparser", "ConfigParser"),
MovedModule("copyreg", "copy_reg"),
MovedModule("dbm_gnu", "gdbm", "dbm.gnu"),
MovedModule("_dummy_thread", "dummy_thread", "_dummy_thread"),
MovedModule("http_cookiejar", "cookielib", "http.cookiejar"),
MovedModule("http_cookies", "Cookie", "http.cookies"),
MovedModule("html_entities", "htmlentitydefs", "html.entities"),
MovedModule("html_parser", "HTMLParser", "html.parser"),
MovedModule("http_client", "httplib", "http.client"),
MovedModule("email_mime_multipart", "email.MIMEMultipart", "email.mime.multipart"),
MovedModule("email_mime_nonmultipart", "email.MIMENonMultipart", "email.mime.nonmultipart"),
MovedModule("email_mime_text", "email.MIMEText", "email.mime.text"),
MovedModule("email_mime_base", "email.MIMEBase", "email.mime.base"),
MovedModule("BaseHTTPServer", "BaseHTTPServer", "http.server"),
MovedModule("CGIHTTPServer", "CGIHTTPServer", "http.server"),
MovedModule("SimpleHTTPServer", "SimpleHTTPServer", "http.server"),
MovedModule("cPickle", "cPickle", "pickle"),
MovedModule("queue", "Queue"),
MovedModule("reprlib", "repr"),
MovedModule("socketserver", "SocketServer"),
MovedModule("_thread", "thread", "_thread"),
MovedModule("tkinter", "Tkinter"),
MovedModule("tkinter_dialog", "Dialog", "tkinter.dialog"),
MovedModule("tkinter_filedialog", "FileDialog", "tkinter.filedialog"),
MovedModule("tkinter_scrolledtext", "ScrolledText", "tkinter.scrolledtext"),
MovedModule("tkinter_simpledialog", "SimpleDialog", "tkinter.simpledialog"),
MovedModule("tkinter_tix", "Tix", "tkinter.tix"),
MovedModule("tkinter_ttk", "ttk", "tkinter.ttk"),
MovedModule("tkinter_constants", "Tkconstants", "tkinter.constants"),
MovedModule("tkinter_dnd", "Tkdnd", "tkinter.dnd"),
MovedModule("tkinter_colorchooser", "tkColorChooser",
"tkinter.colorchooser"),
MovedModule("tkinter_commondialog", "tkCommonDialog",
"tkinter.commondialog"),
MovedModule("tkinter_tkfiledialog", "tkFileDialog", "tkinter.filedialog"),
MovedModule("tkinter_font", "tkFont", "tkinter.font"),
MovedModule("tkinter_messagebox", "tkMessageBox", "tkinter.messagebox"),
MovedModule("tkinter_tksimpledialog", "tkSimpleDialog",
"tkinter.simpledialog"),
MovedModule("urllib_parse", __name__ + ".moves.urllib_parse", "urllib.parse"),
MovedModule("urllib_error", __name__ + ".moves.urllib_error", "urllib.error"),
MovedModule("urllib", __name__ + ".moves.urllib", __name__ + ".moves.urllib"),
MovedModule("urllib_robotparser", "robotparser", "urllib.robotparser"),
MovedModule("xmlrpc_client", "xmlrpclib", "xmlrpc.client"),
MovedModule("xmlrpc_server", "SimpleXMLRPCServer", "xmlrpc.server"),
MovedModule("winreg", "_winreg"),
]
for attr in _moved_attributes:
setattr(_MovedItems, attr.name, attr)
if isinstance(attr, MovedModule):
_importer._add_module(attr, "moves." + attr.name)
del attr
_MovedItems._moved_attributes = _moved_attributes
moves = _MovedItems(__name__ + ".moves")
_importer._add_module(moves, "moves")
class Module_six_moves_urllib_parse(_LazyModule):
"""Lazy loading of moved objects in six.moves.urllib_parse"""
_urllib_parse_moved_attributes = [
MovedAttribute("ParseResult", "urlparse", "urllib.parse"),
MovedAttribute("SplitResult", "urlparse", "urllib.parse"),
MovedAttribute("parse_qs", "urlparse", "urllib.parse"),
MovedAttribute("parse_qsl", "urlparse", "urllib.parse"),
MovedAttribute("urldefrag", "urlparse", "urllib.parse"),
MovedAttribute("urljoin", "urlparse", "urllib.parse"),
MovedAttribute("urlparse", "urlparse", "urllib.parse"),
MovedAttribute("urlsplit", "urlparse", "urllib.parse"),
MovedAttribute("urlunparse", "urlparse", "urllib.parse"),
MovedAttribute("urlunsplit", "urlparse", "urllib.parse"),
MovedAttribute("quote", "urllib", "urllib.parse"),
MovedAttribute("quote_plus", "urllib", "urllib.parse"),
MovedAttribute("unquote", "urllib", "urllib.parse"),
MovedAttribute("unquote_plus", "urllib", "urllib.parse"),
MovedAttribute("urlencode", "urllib", "urllib.parse"),
MovedAttribute("splitquery", "urllib", "urllib.parse"),
MovedAttribute("splittag", "urllib", "urllib.parse"),
MovedAttribute("splituser", "urllib", "urllib.parse"),
MovedAttribute("uses_fragment", "urlparse", "urllib.parse"),
MovedAttribute("uses_netloc", "urlparse", "urllib.parse"),
MovedAttribute("uses_params", "urlparse", "urllib.parse"),
MovedAttribute("uses_query", "urlparse", "urllib.parse"),
MovedAttribute("uses_relative", "urlparse", "urllib.parse"),
]
for attr in _urllib_parse_moved_attributes:
setattr(Module_six_moves_urllib_parse, attr.name, attr)
del attr
Module_six_moves_urllib_parse._moved_attributes = _urllib_parse_moved_attributes
_importer._add_module(Module_six_moves_urllib_parse(__name__ + ".moves.urllib_parse"),
"moves.urllib_parse", "moves.urllib.parse")
class Module_six_moves_urllib_error(_LazyModule):
"""Lazy loading of moved objects in six.moves.urllib_error"""
_urllib_error_moved_attributes = [
MovedAttribute("URLError", "urllib2", "urllib.error"),
MovedAttribute("HTTPError", "urllib2", "urllib.error"),
MovedAttribute("ContentTooShortError", "urllib", "urllib.error"),
]
for attr in _urllib_error_moved_attributes:
setattr(Module_six_moves_urllib_error, attr.name, attr)
del attr
Module_six_moves_urllib_error._moved_attributes = _urllib_error_moved_attributes
_importer._add_module(Module_six_moves_urllib_error(__name__ + ".moves.urllib.error"),
"moves.urllib_error", "moves.urllib.error")
class Module_six_moves_urllib_request(_LazyModule):
"""Lazy loading of moved objects in six.moves.urllib_request"""
_urllib_request_moved_attributes = [
MovedAttribute("urlopen", "urllib2", "urllib.request"),
MovedAttribute("install_opener", "urllib2", "urllib.request"),
MovedAttribute("build_opener", "urllib2", "urllib.request"),
MovedAttribute("pathname2url", "urllib", "urllib.request"),
MovedAttribute("url2pathname", "urllib", "urllib.request"),
MovedAttribute("getproxies", "urllib", "urllib.request"),
MovedAttribute("Request", "urllib2", "urllib.request"),
MovedAttribute("OpenerDirector", "urllib2", "urllib.request"),
MovedAttribute("HTTPDefaultErrorHandler", "urllib2", "urllib.request"),
MovedAttribute("HTTPRedirectHandler", "urllib2", "urllib.request"),
MovedAttribute("HTTPCookieProcessor", "urllib2", "urllib.request"),
MovedAttribute("ProxyHandler", "urllib2", "urllib.request"),
MovedAttribute("BaseHandler", "urllib2", "urllib.request"),
MovedAttribute("HTTPPasswordMgr", "urllib2", "urllib.request"),
MovedAttribute("HTTPPasswordMgrWithDefaultRealm", "urllib2", "urllib.request"),
MovedAttribute("AbstractBasicAuthHandler", "urllib2", "urllib.request"),
MovedAttribute("HTTPBasicAuthHandler", "urllib2", "urllib.request"),
MovedAttribute("ProxyBasicAuthHandler", "urllib2", "urllib.request"),
MovedAttribute("AbstractDigestAuthHandler", "urllib2", "urllib.request"),
MovedAttribute("HTTPDigestAuthHandler", "urllib2", "urllib.request"),
MovedAttribute("ProxyDigestAuthHandler", "urllib2", "urllib.request"),
MovedAttribute("HTTPHandler", "urllib2", "urllib.request"),
MovedAttribute("HTTPSHandler", "urllib2", "urllib.request"),
MovedAttribute("FileHandler", "urllib2", "urllib.request"),
MovedAttribute("FTPHandler", "urllib2", "urllib.request"),
MovedAttribute("CacheFTPHandler", "urllib2", "urllib.request"),
MovedAttribute("UnknownHandler", "urllib2", "urllib.request"),
MovedAttribute("HTTPErrorProcessor", "urllib2", "urllib.request"),
MovedAttribute("urlretrieve", "urllib", "urllib.request"),
MovedAttribute("urlcleanup", "urllib", "urllib.request"),
MovedAttribute("URLopener", "urllib", "urllib.request"),
MovedAttribute("FancyURLopener", "urllib", "urllib.request"),
MovedAttribute("proxy_bypass", "urllib", "urllib.request"),
]
for attr in _urllib_request_moved_attributes:
setattr(Module_six_moves_urllib_request, attr.name, attr)
del attr
Module_six_moves_urllib_request._moved_attributes = _urllib_request_moved_attributes
_importer._add_module(Module_six_moves_urllib_request(__name__ + ".moves.urllib.request"),
"moves.urllib_request", "moves.urllib.request")
class Module_six_moves_urllib_response(_LazyModule):
"""Lazy loading of moved objects in six.moves.urllib_response"""
_urllib_response_moved_attributes = [
MovedAttribute("addbase", "urllib", "urllib.response"),
MovedAttribute("addclosehook", "urllib", "urllib.response"),
MovedAttribute("addinfo", "urllib", "urllib.response"),
MovedAttribute("addinfourl", "urllib", "urllib.response"),
]
for attr in _urllib_response_moved_attributes:
setattr(Module_six_moves_urllib_response, attr.name, attr)
del attr
Module_six_moves_urllib_response._moved_attributes = _urllib_response_moved_attributes
_importer._add_module(Module_six_moves_urllib_response(__name__ + ".moves.urllib.response"),
"moves.urllib_response", "moves.urllib.response")
class Module_six_moves_urllib_robotparser(_LazyModule):
"""Lazy loading of moved objects in six.moves.urllib_robotparser"""
_urllib_robotparser_moved_attributes = [
MovedAttribute("RobotFileParser", "robotparser", "urllib.robotparser"),
]
for attr in _urllib_robotparser_moved_attributes:
setattr(Module_six_moves_urllib_robotparser, attr.name, attr)
del attr
Module_six_moves_urllib_robotparser._moved_attributes = _urllib_robotparser_moved_attributes
_importer._add_module(Module_six_moves_urllib_robotparser(__name__ + ".moves.urllib.robotparser"),
"moves.urllib_robotparser", "moves.urllib.robotparser")
class Module_six_moves_urllib(types.ModuleType):
"""Create a six.moves.urllib namespace that resembles the Python 3 namespace"""
__path__ = [] # mark as package
parse = _importer._get_module("moves.urllib_parse")
error = _importer._get_module("moves.urllib_error")
request = _importer._get_module("moves.urllib_request")
response = _importer._get_module("moves.urllib_response")
robotparser = _importer._get_module("moves.urllib_robotparser")
def __dir__(self):
return ['parse', 'error', 'request', 'response', 'robotparser']
_importer._add_module(Module_six_moves_urllib(__name__ + ".moves.urllib"),
"moves.urllib")
def add_move(move):
"""Add an item to six.moves."""
setattr(_MovedItems, move.name, move)
def remove_move(name):
"""Remove item from six.moves."""
try:
delattr(_MovedItems, name)
except AttributeError:
try:
del moves.__dict__[name]
except KeyError:
raise AttributeError("no such move, %r" % (name,))
if PY3:
_meth_func = "__func__"
_meth_self = "__self__"
_func_closure = "__closure__"
_func_code = "__code__"
_func_defaults = "__defaults__"
_func_globals = "__globals__"
else:
_meth_func = "im_func"
_meth_self = "im_self"
_func_closure = "func_closure"
_func_code = "func_code"
_func_defaults = "func_defaults"
_func_globals = "func_globals"
try:
advance_iterator = next
except NameError:
def advance_iterator(it):
return it.next()
next = advance_iterator
try:
callable = callable
except NameError:
def callable(obj):
return any("__call__" in klass.__dict__ for klass in type(obj).__mro__)
if PY3:
def get_unbound_function(unbound):
return unbound
create_bound_method = types.MethodType
Iterator = object
else:
def get_unbound_function(unbound):
return unbound.im_func
def create_bound_method(func, obj):
return types.MethodType(func, obj, obj.__class__)
class Iterator(object):
def next(self):
return type(self).__next__(self)
callable = callable
_add_doc(get_unbound_function,
"""Get the function out of a possibly unbound function""")
get_method_function = operator.attrgetter(_meth_func)
get_method_self = operator.attrgetter(_meth_self)
get_function_closure = operator.attrgetter(_func_closure)
get_function_code = operator.attrgetter(_func_code)
get_function_defaults = operator.attrgetter(_func_defaults)
get_function_globals = operator.attrgetter(_func_globals)
if PY3:
def iterkeys(d, **kw):
return iter(d.keys(**kw))
def itervalues(d, **kw):
return iter(d.values(**kw))
def iteritems(d, **kw):
return iter(d.items(**kw))
def iterlists(d, **kw):
return iter(d.lists(**kw))
else:
def iterkeys(d, **kw):
return iter(d.iterkeys(**kw))
def itervalues(d, **kw):
return iter(d.itervalues(**kw))
def iteritems(d, **kw):
return iter(d.iteritems(**kw))
def iterlists(d, **kw):
return iter(d.iterlists(**kw))
_add_doc(iterkeys, "Return an iterator over the keys of a dictionary.")
_add_doc(itervalues, "Return an iterator over the values of a dictionary.")
_add_doc(iteritems,
"Return an iterator over the (key, value) pairs of a dictionary.")
_add_doc(iterlists,
"Return an iterator over the (key, [values]) pairs of a dictionary.")
if PY3:
def b(s):
return s.encode("latin-1")
def u(s):
return s
unichr = chr
if sys.version_info[1] <= 1:
def int2byte(i):
return bytes((i,))
else:
# This is about 2x faster than the implementation above on 3.2+
int2byte = operator.methodcaller("to_bytes", 1, "big")
byte2int = operator.itemgetter(0)
indexbytes = operator.getitem
iterbytes = iter
import io
StringIO = io.StringIO
BytesIO = io.BytesIO
else:
def b(s):
return s
# Workaround for standalone backslash
def u(s):
return unicode(s.replace(r'\\', r'\\\\'), "unicode_escape")
unichr = unichr
int2byte = chr
def byte2int(bs):
return ord(bs[0])
def indexbytes(buf, i):
return ord(buf[i])
def iterbytes(buf):
return (ord(byte) for byte in buf)
import StringIO
StringIO = BytesIO = StringIO.StringIO
_add_doc(b, """Byte literal""")
_add_doc(u, """Text literal""")
if PY3:
exec_ = getattr(moves.builtins, "exec")
def reraise(tp, value, tb=None):
if value is None:
value = tp()
if value.__traceback__ is not tb:
raise value.with_traceback(tb)
raise value
else:
def exec_(_code_, _globs_=None, _locs_=None):
"""Execute code in a namespace."""
if _globs_ is None:
frame = sys._getframe(1)
_globs_ = frame.f_globals
if _locs_ is None:
_locs_ = frame.f_locals
del frame
elif _locs_ is None:
_locs_ = _globs_
exec("""exec _code_ in _globs_, _locs_""")
exec_("""def reraise(tp, value, tb=None):
raise tp, value, tb
""")
print_ = getattr(moves.builtins, "print", None)
if print_ is None:
def print_(*args, **kwargs):
"""The new-style print function for Python 2.4 and 2.5."""
fp = kwargs.pop("file", sys.stdout)
if fp is None:
return
def write(data):
if not isinstance(data, basestring):
data = str(data)
# If the file has an encoding, encode unicode with it.
if (isinstance(fp, file) and
isinstance(data, unicode) and
fp.encoding is not None):
errors = getattr(fp, "errors", None)
if errors is None:
errors = "strict"
data = data.encode(fp.encoding, errors)
fp.write(data)
want_unicode = False
sep = kwargs.pop("sep", None)
if sep is not None:
if isinstance(sep, unicode):
want_unicode = True
elif not isinstance(sep, str):
raise TypeError("sep must be None or a string")
end = kwargs.pop("end", None)
if end is not None:
if isinstance(end, unicode):
want_unicode = True
elif not isinstance(end, str):
raise TypeError("end must be None or a string")
if kwargs:
raise TypeError("invalid keyword arguments to print()")
if not want_unicode:
for arg in args:
if isinstance(arg, unicode):
want_unicode = True
break
if want_unicode:
newline = unicode("\n")
space = unicode(" ")
else:
newline = "\n"
space = " "
if sep is None:
sep = space
if end is None:
end = newline
for i, arg in enumerate(args):
if i:
write(sep)
write(arg)
write(end)
_add_doc(reraise, """Reraise an exception.""")
if sys.version_info[0:2] < (3, 4):
def wraps(wrapped, assigned=functools.WRAPPER_ASSIGNMENTS,
updated=functools.WRAPPER_UPDATES):
def wrapper(f):
f = functools.wraps(wrapped)(f)
f.__wrapped__ = wrapped
return f
return wrapper
else:
wraps = functools.wraps
def with_metaclass(meta, *bases):
"""Create a base class with a metaclass."""
# This requires a bit of explanation: the basic idea is to make a dummy
# metaclass for one level of class instantiation that replaces itself with
# the actual metaclass.
class metaclass(meta):
def __new__(cls, name, this_bases, d):
return meta(name, bases, d)
return type.__new__(metaclass, 'temporary_class', (), {})
def add_metaclass(metaclass):
"""Class decorator for creating a class with a metaclass."""
def wrapper(cls):
orig_vars = cls.__dict__.copy()
slots = orig_vars.get('__slots__')
if slots is not None:
if isinstance(slots, str):
slots = [slots]
for slots_var in slots:
orig_vars.pop(slots_var)
orig_vars.pop('__dict__', None)
orig_vars.pop('__weakref__', None)
return metaclass(cls.__name__, cls.__bases__, orig_vars)
return wrapper
# Complete the moves implementation.
# This code is at the end of this module to speed up module loading.
# Turn this module into a package.
__path__ = [] # required for PEP 302 and PEP 451
__package__ = __name__ # see PEP 366 @ReservedAssignment
if globals().get("__spec__") is not None:
__spec__.submodule_search_locations = [] # PEP 451 @UndefinedVariable
# Remove other six meta path importers, since they cause problems. This can
# happen if six is removed from sys.modules and then reloaded. (Setuptools does
# this for some reason.)
if sys.meta_path:
for i, importer in enumerate(sys.meta_path):
# Here's some real nastiness: Another "instance" of the six module might
# be floating around. Therefore, we can't use isinstance() to check for
# the six meta path importer, since the other six instance will have
# inserted an importer with different class.
if (type(importer).__name__ == "_SixMetaPathImporter" and
importer.name == __name__):
del sys.meta_path[i]
break
del i, importer
# Finally, add the importer to the meta path import hook.
sys.meta_path.append(_importer)
| gpl-3.0 |
cobalys/django | django/utils/daemonize.py | 13 | 1911 | import os
import sys
if os.name == 'posix':
def become_daemon(our_home_dir='.', out_log='/dev/null',
err_log='/dev/null', umask=022):
"Robustly turn into a UNIX daemon, running in our_home_dir."
# First fork
try:
if os.fork() > 0:
sys.exit(0) # kill off parent
except OSError as e:
sys.stderr.write("fork #1 failed: (%d) %s\n" % (e.errno, e.strerror))
sys.exit(1)
os.setsid()
os.chdir(our_home_dir)
os.umask(umask)
# Second fork
try:
if os.fork() > 0:
os._exit(0)
except OSError as e:
sys.stderr.write("fork #2 failed: (%d) %s\n" % (e.errno, e.strerror))
os._exit(1)
si = open('/dev/null', 'r')
so = open(out_log, 'a+', 0)
se = open(err_log, 'a+', 0)
os.dup2(si.fileno(), sys.stdin.fileno())
os.dup2(so.fileno(), sys.stdout.fileno())
os.dup2(se.fileno(), sys.stderr.fileno())
# Set custom file descriptors so that they get proper buffering.
sys.stdout, sys.stderr = so, se
else:
def become_daemon(our_home_dir='.', out_log=None, err_log=None, umask=022):
"""
If we're not running under a POSIX system, just simulate the daemon
mode by doing redirections and directory changing.
"""
os.chdir(our_home_dir)
os.umask(umask)
sys.stdin.close()
sys.stdout.close()
sys.stderr.close()
if err_log:
sys.stderr = open(err_log, 'a', 0)
else:
sys.stderr = NullDevice()
if out_log:
sys.stdout = open(out_log, 'a', 0)
else:
sys.stdout = NullDevice()
class NullDevice:
"A writeable object that writes to nowhere -- like /dev/null."
def write(self, s):
pass
| bsd-3-clause |
jamesblunt/sympy | sympy/assumptions/handlers/sets.py | 14 | 20791 | """
Handlers for predicates related to set membership: integer, rational, etc.
"""
from __future__ import print_function, division
from sympy.assumptions import Q, ask
from sympy.assumptions.handlers import CommonHandler, test_closed_group
from sympy.core.logic import fuzzy_not
from sympy.core.numbers import pi
from sympy import I, S, C, denom
class AskIntegerHandler(CommonHandler):
"""
Handler for Q.integer
Test that an expression belongs to the field of integer numbers
"""
@staticmethod
def _number(expr, assumptions):
# helper method
try:
i = int(expr.round())
if not (expr - i).equals(0):
raise TypeError
return True
except TypeError:
return False
@staticmethod
def Add(expr, assumptions):
"""
Integer + Integer -> Integer
Integer + !Integer -> !Integer
!Integer + !Integer -> ?
"""
if expr.is_number:
return AskIntegerHandler._number(expr, assumptions)
return test_closed_group(expr, assumptions, Q.integer)
@staticmethod
def Mul(expr, assumptions):
"""
Integer*Integer -> Integer
Integer*Irrational -> !Integer
Odd/Even -> !Integer
Integer*Rational -> ?
"""
if expr.is_number:
return AskIntegerHandler._number(expr, assumptions)
_output = True
for arg in expr.args:
if not ask(Q.integer(arg), assumptions):
if arg.is_Rational:
if arg.q == 2:
return ask(Q.even(2*expr), assumptions)
if ~(arg.q & 1):
return None
elif ask(Q.irrational(arg), assumptions):
if _output:
_output = False
else:
return
else:
return
else:
return _output
Pow = Add
int, Integer = [staticmethod(CommonHandler.AlwaysTrue)]*2
Pi, Exp1, GoldenRatio, Infinity, NegativeInfinity, ImaginaryUnit = \
[staticmethod(CommonHandler.AlwaysFalse)]*6
@staticmethod
def Rational(expr, assumptions):
# rationals with denominator one get
# evaluated to Integers
return False
@staticmethod
def Float(expr, assumptions):
return int(expr) == expr
@staticmethod
def Abs(expr, assumptions):
return ask(Q.integer(expr.args[0]), assumptions)
@staticmethod
def MatrixElement(expr, assumptions):
return ask(Q.integer_elements(expr.args[0]), assumptions)
Determinant = Trace = MatrixElement
class AskRationalHandler(CommonHandler):
"""
Handler for Q.rational
Test that an expression belongs to the field of rational numbers
"""
@staticmethod
def Add(expr, assumptions):
"""
Rational + Rational -> Rational
Rational + !Rational -> !Rational
!Rational + !Rational -> ?
"""
if expr.is_number:
if expr.as_real_imag()[1]:
return False
return test_closed_group(expr, assumptions, Q.rational)
Mul = Add
@staticmethod
def Pow(expr, assumptions):
"""
Rational ** Integer -> Rational
Irrational ** Rational -> Irrational
Rational ** Irrational -> ?
"""
if ask(Q.integer(expr.exp), assumptions):
return ask(Q.rational(expr.base), assumptions)
elif ask(Q.rational(expr.exp), assumptions):
if ask(Q.prime(expr.base), assumptions):
return False
Rational, Float = \
[staticmethod(CommonHandler.AlwaysTrue)]*2 # Float is finite-precision
ImaginaryUnit, Infinity, NegativeInfinity, Pi, Exp1, GoldenRatio = \
[staticmethod(CommonHandler.AlwaysFalse)]*6
@staticmethod
def exp(expr, assumptions):
x = expr.args[0]
if ask(Q.rational(x), assumptions):
return ask(~Q.nonzero(x), assumptions)
@staticmethod
def cot(expr, assumptions):
x = expr.args[0]
if ask(Q.rational(x), assumptions):
return False
@staticmethod
def log(expr, assumptions):
x = expr.args[0]
if ask(Q.rational(x), assumptions):
return ask(~Q.nonzero(x - 1), assumptions)
sin, cos, tan, asin, atan = [exp]*5
acos, acot = log, cot
class AskIrrationalHandler(CommonHandler):
@staticmethod
def Basic(expr, assumptions):
_real = ask(Q.real(expr), assumptions)
if _real:
_rational = ask(Q.rational(expr), assumptions)
if _rational is None:
return None
return not _rational
else:
return _real
class AskRealHandler(CommonHandler):
"""
Handler for Q.real
Test that an expression belongs to the field of real numbers
"""
@staticmethod
def _number(expr, assumptions):
# let as_real_imag() work first since the expression may
# be simpler to evaluate
i = expr.as_real_imag()[1].evalf(2)
if i._prec != 1:
return not i
# allow None to be returned if we couldn't show for sure
# that i was 0
@staticmethod
def Add(expr, assumptions):
"""
Real + Real -> Real
Real + (Complex & !Real) -> !Real
"""
if expr.is_number:
return AskRealHandler._number(expr, assumptions)
return test_closed_group(expr, assumptions, Q.real)
@staticmethod
def Mul(expr, assumptions):
"""
Real*Real -> Real
Real*Imaginary -> !Real
Imaginary*Imaginary -> Real
"""
if expr.is_number:
return AskRealHandler._number(expr, assumptions)
result = True
for arg in expr.args:
if ask(Q.real(arg), assumptions):
pass
elif ask(Q.imaginary(arg), assumptions):
result = result ^ True
else:
break
else:
return result
@staticmethod
def Pow(expr, assumptions):
"""
Real**Integer -> Real
Positive**Real -> Real
Real**(Integer/Even) -> Real if base is nonnegative
Real**(Integer/Odd) -> Real
Imaginary**(Integer/Even) -> Real
Imaginary**(Integer/Odd) -> not Real
Imaginary**Real -> ? since Real could be 0 (giving real) or 1 (giving imaginary)
b**Imaginary -> Real if log(b) is imaginary and b != 0 and exponent != integer multiple of I*pi/log(b)
Real**Real -> ? e.g. sqrt(-1) is imaginary and sqrt(2) is not
"""
if expr.is_number:
return AskRealHandler._number(expr, assumptions)
if expr.base.func == C.exp:
if ask(Q.imaginary(expr.base.args[0]), assumptions):
if ask(Q.imaginary(expr.exp), assumptions):
return True
# If the i = (exp's arg)/(I*pi) is an integer or half-integer
# multiple of I*pi then 2*i will be an integer. In addition,
# exp(i*I*pi) = (-1)**i so the overall realness of the expr
# can be determined by replacing exp(i*I*pi) with (-1)**i.
i = expr.base.args[0]/I/pi
if ask(Q.integer(2*i), assumptions):
return ask(Q.real(((-1)**i)**expr.exp), assumptions)
return
if ask(Q.imaginary(expr.base), assumptions):
if ask(Q.integer(expr.exp), assumptions):
odd = ask(Q.odd(expr.exp), assumptions)
if odd is not None:
return not odd
return
if ask(Q.imaginary(expr.exp), assumptions):
imlog = ask(Q.imaginary(C.log(expr.base)), assumptions)
if imlog is not None:
# I**i -> real, log(I) is imag;
# (2*I)**i -> complex, log(2*I) is not imag
return imlog
if ask(Q.real(expr.base), assumptions):
if ask(Q.real(expr.exp), assumptions):
if expr.exp.is_Rational and \
ask(Q.even(expr.exp.q), assumptions):
return ask(Q.positive(expr.base), assumptions)
elif ask(Q.integer(expr.exp), assumptions):
return True
elif ask(Q.positive(expr.base), assumptions):
return True
elif ask(Q.negative(expr.base), assumptions):
return False
Rational, Float, Pi, Exp1, GoldenRatio, Abs, re, im = \
[staticmethod(CommonHandler.AlwaysTrue)]*8
ImaginaryUnit, Infinity, NegativeInfinity = \
[staticmethod(CommonHandler.AlwaysFalse)]*3
@staticmethod
def sin(expr, assumptions):
if ask(Q.real(expr.args[0]), assumptions):
return True
cos = sin
@staticmethod
def exp(expr, assumptions):
return ask(Q.integer(expr.args[0]/I/pi) | Q.real(expr.args[0]), assumptions)
@staticmethod
def log(expr, assumptions):
return ask(Q.positive(expr.args[0]), assumptions)
@staticmethod
def MatrixElement(expr, assumptions):
return ask(Q.real_elements(expr.args[0]), assumptions)
Determinant = Trace = MatrixElement
class AskExtendedRealHandler(AskRealHandler):
"""
Handler for Q.extended_real
Test that an expression belongs to the field of extended real numbers,
that is real numbers union {Infinity, -Infinity}
"""
@staticmethod
def Add(expr, assumptions):
return test_closed_group(expr, assumptions, Q.extended_real)
Mul, Pow = [Add]*2
Infinity, NegativeInfinity = [staticmethod(CommonHandler.AlwaysTrue)]*2
class AskHermitianHandler(AskRealHandler):
"""
Handler for Q.hermitian
Test that an expression belongs to the field of Hermitian operators
"""
@staticmethod
def Add(expr, assumptions):
"""
Hermitian + Hermitian -> Hermitian
Hermitian + !Hermitian -> !Hermitian
"""
if expr.is_number:
return AskRealHandler._number(expr, assumptions)
return test_closed_group(expr, assumptions, Q.hermitian)
@staticmethod
def Mul(expr, assumptions):
"""
As long as there is at most only one noncommutative term:
Hermitian*Hermitian -> Hermitian
Hermitian*Antihermitian -> !Hermitian
Antihermitian*Antihermitian -> Hermitian
"""
if expr.is_number:
return AskRealHandler._number(expr, assumptions)
nccount = 0
result = True
for arg in expr.args:
if ask(Q.antihermitian(arg), assumptions):
result = result ^ True
elif not ask(Q.hermitian(arg), assumptions):
break
if ask(~Q.commutative(arg), assumptions):
nccount += 1
if nccount > 1:
break
else:
return result
@staticmethod
def Pow(expr, assumptions):
"""
Hermitian**Integer -> Hermitian
"""
if expr.is_number:
return AskRealHandler._number(expr, assumptions)
if ask(Q.hermitian(expr.base), assumptions):
if ask(Q.integer(expr.exp), assumptions):
return True
@staticmethod
def sin(expr, assumptions):
if ask(Q.hermitian(expr.args[0]), assumptions):
return True
cos, exp = [sin]*2
class AskComplexHandler(CommonHandler):
"""
Handler for Q.complex
Test that an expression belongs to the field of complex numbers
"""
@staticmethod
def Add(expr, assumptions):
return test_closed_group(expr, assumptions, Q.complex)
Mul, Pow = [Add]*2
Number, sin, cos, log, exp, re, im, NumberSymbol, Abs, ImaginaryUnit = \
[staticmethod(CommonHandler.AlwaysTrue)]*10 # they are all complex functions or expressions
Infinity, NegativeInfinity = [staticmethod(CommonHandler.AlwaysFalse)]*2
@staticmethod
def MatrixElement(expr, assumptions):
return ask(Q.complex_elements(expr.args[0]), assumptions)
Determinant = Trace = MatrixElement
class AskImaginaryHandler(CommonHandler):
"""
Handler for Q.imaginary
Test that an expression belongs to the field of imaginary numbers,
that is, numbers in the form x*I, where x is real
"""
@staticmethod
def _number(expr, assumptions):
# let as_real_imag() work first since the expression may
# be simpler to evaluate
r = expr.as_real_imag()[0].evalf(2)
if r._prec != 1:
return not r
# allow None to be returned if we couldn't show for sure
# that r was 0
@staticmethod
def Add(expr, assumptions):
"""
Imaginary + Imaginary -> Imaginary
Imaginary + Complex -> ?
Imaginary + Real -> !Imaginary
"""
if expr.is_number:
return AskImaginaryHandler._number(expr, assumptions)
reals = 0
for arg in expr.args:
if ask(Q.imaginary(arg), assumptions):
pass
elif ask(Q.real(arg), assumptions):
reals += 1
else:
break
else:
if reals == 0:
return True
if reals == 1 or (len(expr.args) == reals):
# two reals could sum 0 thus giving an imaginary
return False
@staticmethod
def Mul(expr, assumptions):
"""
Real*Imaginary -> Imaginary
Imaginary*Imaginary -> Real
"""
if expr.is_number:
return AskImaginaryHandler._number(expr, assumptions)
result = False
reals = 0
for arg in expr.args:
if ask(Q.imaginary(arg), assumptions):
result = result ^ True
elif not ask(Q.real(arg), assumptions):
break
else:
if reals == len(expr.args):
return False
return result
@staticmethod
def Pow(expr, assumptions):
"""
Imaginary**Odd -> Imaginary
Imaginary**Even -> Real
b**Imaginary -> !Imaginary if exponent is an integer multiple of I*pi/log(b)
Imaginary**Real -> ?
Positive**Real -> Real
Negative**Integer -> Real
Negative**(Integer/2) -> Imaginary
Negative**Real -> not Imaginary if exponent is not Rational
"""
if expr.is_number:
return AskImaginaryHandler._number(expr, assumptions)
if expr.base.func == C.exp:
if ask(Q.imaginary(expr.base.args[0]), assumptions):
if ask(Q.imaginary(expr.exp), assumptions):
return False
i = expr.base.args[0]/I/pi
if ask(Q.integer(2*i), assumptions):
return ask(Q.imaginary(((-1)**i)**expr.exp), assumptions)
if ask(Q.imaginary(expr.base), assumptions):
if ask(Q.integer(expr.exp), assumptions):
odd = ask(Q.odd(expr.exp), assumptions)
if odd is not None:
return odd
return
if ask(Q.imaginary(expr.exp), assumptions):
imlog = ask(Q.imaginary(C.log(expr.base)), assumptions)
if imlog is not None:
return False # I**i -> real; (2*I)**i -> complex ==> not imaginary
if ask(Q.real(expr.base) & Q.real(expr.exp), assumptions):
if ask(Q.positive(expr.base), assumptions):
return False
else:
rat = ask(Q.rational(expr.exp), assumptions)
if not rat:
return rat
if ask(Q.integer(expr.exp), assumptions):
return False
else:
half = ask(Q.integer(2*expr.exp), assumptions)
if half:
return ask(Q.negative(expr.base), assumptions)
return half
@staticmethod
def log(expr, assumptions):
if ask(Q.real(expr.args[0]), assumptions):
if ask(Q.positive(expr.args[0]), assumptions):
return False
return
# XXX it should be enough to do
# return ask(Q.nonpositive(expr.args[0]), assumptions)
# but ask(Q.nonpositive(exp(x)), Q.imaginary(x)) -> None;
# it should return True since exp(x) will be either 0 or complex
if expr.args[0].func == C.exp:
if expr.args[0].args[0] in [I, -I]:
return True
im = ask(Q.imaginary(expr.args[0]), assumptions)
if im is False:
return False
@staticmethod
def exp(expr, assumptions):
a = expr.args[0]/I/pi
return ask(Q.integer(2*a) & ~Q.integer(a), assumptions)
@staticmethod
def Number(expr, assumptions):
return not (expr.as_real_imag()[1] == 0)
NumberSymbol = Number
ImaginaryUnit = staticmethod(CommonHandler.AlwaysTrue)
class AskAntiHermitianHandler(AskImaginaryHandler):
"""
Handler for Q.antihermitian
Test that an expression belongs to the field of anti-Hermitian operators,
that is, operators in the form x*I, where x is Hermitian
"""
@staticmethod
def Add(expr, assumptions):
"""
Antihermitian + Antihermitian -> Antihermitian
Antihermitian + !Antihermitian -> !Antihermitian
"""
if expr.is_number:
return AskImaginaryHandler._number(expr, assumptions)
return test_closed_group(expr, assumptions, Q.antihermitian)
@staticmethod
def Mul(expr, assumptions):
"""
As long as there is at most only one noncommutative term:
Hermitian*Hermitian -> !Antihermitian
Hermitian*Antihermitian -> Antihermitian
Antihermitian*Antihermitian -> !Antihermitian
"""
if expr.is_number:
return AskImaginaryHandler._number(expr, assumptions)
nccount = 0
result = False
for arg in expr.args:
if ask(Q.antihermitian(arg), assumptions):
result = result ^ True
elif not ask(Q.hermitian(arg), assumptions):
break
if ask(~Q.commutative(arg), assumptions):
nccount += 1
if nccount > 1:
break
else:
return result
@staticmethod
def Pow(expr, assumptions):
"""
Hermitian**Integer -> !Antihermitian
Antihermitian**Even -> !Antihermitian
Antihermitian**Odd -> Antihermitian
"""
if expr.is_number:
return AskImaginaryHandler._number(expr, assumptions)
if ask(Q.hermitian(expr.base), assumptions):
if ask(Q.integer(expr.exp), assumptions):
return False
elif ask(Q.antihermitian(expr.base), assumptions):
if ask(Q.even(expr.exp), assumptions):
return False
elif ask(Q.odd(expr.exp), assumptions):
return True
class AskAlgebraicHandler(CommonHandler):
"""Handler for Q.algebraic key. """
@staticmethod
def Add(expr, assumptions):
return test_closed_group(expr, assumptions, Q.algebraic)
@staticmethod
def Mul(expr, assumptions):
return test_closed_group(expr, assumptions, Q.algebraic)
@staticmethod
def Pow(expr, assumptions):
return expr.exp.is_Rational and ask(
Q.algebraic(expr.base), assumptions)
@staticmethod
def Rational(expr, assumptions):
return expr.q != 0
Float, GoldenRatio, ImaginaryUnit, AlgebraicNumber = \
[staticmethod(CommonHandler.AlwaysTrue)]*4
Infinity, NegativeInfinity, ComplexInfinity, Pi, Exp1 = \
[staticmethod(CommonHandler.AlwaysFalse)]*5
@staticmethod
def exp(expr, assumptions):
x = expr.args[0]
if ask(Q.algebraic(x), assumptions):
return ask(~Q.nonzero(x), assumptions)
@staticmethod
def cot(expr, assumptions):
x = expr.args[0]
if ask(Q.algebraic(x), assumptions):
return False
@staticmethod
def log(expr, assumptions):
x = expr.args[0]
if ask(Q.algebraic(x), assumptions):
return ask(~Q.nonzero(x - 1), assumptions)
sin, cos, tan, asin, atan = [exp]*5
acos, acot = log, cot
| bsd-3-clause |
bobrock/eden | modules/s3db/workflow.py | 13 | 3277 | # -*- coding: utf-8 -*-
"""
S3 Workflow Engine Data Model
@copyright: 2012-2015 (c) Sahana Software Foundation
@license: MIT
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
"""
__all__ = ["S3WorkflowStatusModel"]
from gluon import *
from gluon.storage import Storage
from ..s3 import *
# =============================================================================
class S3WorkflowStatusModel(S3Model):
""" Model to store the workflow status of records """
name = ["workflow_status",
"workflow_entity",
]
def model(self):
auth = current.auth
define_table = self.define_table
db = current.db
# ---------------------------------------------------------------------
# Entities which can have a workflow status
#
# @note: the respective entity tables need to also define the
# super_link("workflow_id", "workflow_entity"), and have
# their super-entity configured like:
# s3db.configure(tablename, super_entity="workflow_entity")
#
we_types = Storage(project_task = T("Project Task"),
)
tablename = "workflow_entity"
s3db.super_entity(tablename, "workflow_id",
we_types,
)
# Status as component
self.add_components(tablename,
workflow_status="workflow_id",
)
# ---------------------------------------------------------------------
# Workflow Status
# - as tuple (workflow name, status name)
# - as component of workflow entities
#
tablename = "workflow_status"
define_table(tablename,
super_link("workflow_id", "workflow_entity"),
Field("name",
length=64,
notnull=True),
Field("status",
length=64,
notnull=True),
*s3_meta_fields(),
)
return Storage()
# END =========================================================================
| mit |
sorenk/ansible | lib/ansible/module_utils/facts/default_collectors.py | 55 | 7579 | # This code is part of Ansible, but is an independent component.
# This particular file snippet, and this file snippet only, is BSD licensed.
# Modules you write using this snippet, which is embedded dynamically by Ansible
# still belong to the author of the module, and may assign their own license
# to the complete work.
#
# (c) 2017 Red Hat Inc.
#
# Redistribution and use in source and binary forms, with or without modification,
# are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
# IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
# USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
from ansible.module_utils.facts.other.facter import FacterFactCollector
from ansible.module_utils.facts.other.ohai import OhaiFactCollector
from ansible.module_utils.facts.system.apparmor import ApparmorFactCollector
from ansible.module_utils.facts.system.caps import SystemCapabilitiesFactCollector
from ansible.module_utils.facts.system.chroot import ChrootFactCollector
from ansible.module_utils.facts.system.cmdline import CmdLineFactCollector
from ansible.module_utils.facts.system.distribution import DistributionFactCollector
from ansible.module_utils.facts.system.date_time import DateTimeFactCollector
from ansible.module_utils.facts.system.env import EnvFactCollector
from ansible.module_utils.facts.system.dns import DnsFactCollector
from ansible.module_utils.facts.system.fips import FipsFactCollector
from ansible.module_utils.facts.system.local import LocalFactCollector
from ansible.module_utils.facts.system.lsb import LSBFactCollector
from ansible.module_utils.facts.system.pkg_mgr import PkgMgrFactCollector
from ansible.module_utils.facts.system.pkg_mgr import OpenBSDPkgMgrFactCollector
from ansible.module_utils.facts.system.platform import PlatformFactCollector
from ansible.module_utils.facts.system.python import PythonFactCollector
from ansible.module_utils.facts.system.selinux import SelinuxFactCollector
from ansible.module_utils.facts.system.service_mgr import ServiceMgrFactCollector
from ansible.module_utils.facts.system.ssh_pub_keys import SshPubKeyFactCollector
from ansible.module_utils.facts.system.user import UserFactCollector
from ansible.module_utils.facts.hardware.base import HardwareCollector
from ansible.module_utils.facts.hardware.aix import AIXHardwareCollector
from ansible.module_utils.facts.hardware.darwin import DarwinHardwareCollector
from ansible.module_utils.facts.hardware.dragonfly import DragonFlyHardwareCollector
from ansible.module_utils.facts.hardware.freebsd import FreeBSDHardwareCollector
from ansible.module_utils.facts.hardware.hpux import HPUXHardwareCollector
from ansible.module_utils.facts.hardware.hurd import HurdHardwareCollector
from ansible.module_utils.facts.hardware.linux import LinuxHardwareCollector
from ansible.module_utils.facts.hardware.netbsd import NetBSDHardwareCollector
from ansible.module_utils.facts.hardware.openbsd import OpenBSDHardwareCollector
from ansible.module_utils.facts.hardware.sunos import SunOSHardwareCollector
from ansible.module_utils.facts.network.base import NetworkCollector
from ansible.module_utils.facts.network.aix import AIXNetworkCollector
from ansible.module_utils.facts.network.darwin import DarwinNetworkCollector
from ansible.module_utils.facts.network.dragonfly import DragonFlyNetworkCollector
from ansible.module_utils.facts.network.freebsd import FreeBSDNetworkCollector
from ansible.module_utils.facts.network.hpux import HPUXNetworkCollector
from ansible.module_utils.facts.network.hurd import HurdNetworkCollector
from ansible.module_utils.facts.network.linux import LinuxNetworkCollector
from ansible.module_utils.facts.network.iscsi import IscsiInitiatorNetworkCollector
from ansible.module_utils.facts.network.netbsd import NetBSDNetworkCollector
from ansible.module_utils.facts.network.openbsd import OpenBSDNetworkCollector
from ansible.module_utils.facts.network.sunos import SunOSNetworkCollector
from ansible.module_utils.facts.virtual.base import VirtualCollector
from ansible.module_utils.facts.virtual.dragonfly import DragonFlyVirtualCollector
from ansible.module_utils.facts.virtual.freebsd import FreeBSDVirtualCollector
from ansible.module_utils.facts.virtual.hpux import HPUXVirtualCollector
from ansible.module_utils.facts.virtual.linux import LinuxVirtualCollector
from ansible.module_utils.facts.virtual.netbsd import NetBSDVirtualCollector
from ansible.module_utils.facts.virtual.openbsd import OpenBSDVirtualCollector
from ansible.module_utils.facts.virtual.sunos import SunOSVirtualCollector
# these should always be first due to most other facts depending on them
_base = [
PlatformFactCollector,
DistributionFactCollector,
LSBFactCollector
]
# These restrict what is possible in others
_restrictive = [
SelinuxFactCollector,
ApparmorFactCollector,
ChrootFactCollector,
FipsFactCollector
]
# general info, not required but probably useful for other facts
_general = [
PythonFactCollector,
SystemCapabilitiesFactCollector,
PkgMgrFactCollector,
OpenBSDPkgMgrFactCollector,
ServiceMgrFactCollector,
CmdLineFactCollector,
DateTimeFactCollector,
EnvFactCollector,
SshPubKeyFactCollector,
UserFactCollector
]
# virtual, this might also limit hardware/networking
_virtual = [
VirtualCollector,
DragonFlyVirtualCollector,
FreeBSDVirtualCollector,
LinuxVirtualCollector,
OpenBSDVirtualCollector,
NetBSDVirtualCollector,
SunOSVirtualCollector,
HPUXVirtualCollector
]
_hardware = [
HardwareCollector,
AIXHardwareCollector,
DarwinHardwareCollector,
DragonFlyHardwareCollector,
FreeBSDHardwareCollector,
HPUXHardwareCollector,
HurdHardwareCollector,
LinuxHardwareCollector,
NetBSDHardwareCollector,
OpenBSDHardwareCollector,
SunOSHardwareCollector
]
_network = [
DnsFactCollector,
NetworkCollector,
AIXNetworkCollector,
DarwinNetworkCollector,
DragonFlyNetworkCollector,
FreeBSDNetworkCollector,
HPUXNetworkCollector,
HurdNetworkCollector,
IscsiInitiatorNetworkCollector,
LinuxNetworkCollector,
NetBSDNetworkCollector,
OpenBSDNetworkCollector,
SunOSNetworkCollector
]
# other fact sources
_extra_facts = [
LocalFactCollector,
FacterFactCollector,
OhaiFactCollector
]
# TODO: make config driven
collectors = _base + _restrictive + _general + _virtual + _hardware + _network + _extra_facts
| gpl-3.0 |
alajara/servo | tests/wpt/web-platform-tests/tools/wptserve/tests/functional/test_request.py | 109 | 2919 | import unittest
import wptserve
from .base import TestUsingServer
class TestInputFile(TestUsingServer):
def test_seek(self):
@wptserve.handlers.handler
def handler(request, response):
rv = []
f = request.raw_input
f.seek(5)
rv.append(f.read(2))
rv.append(f.tell())
f.seek(0)
rv.append(f.readline())
rv.append(f.tell())
rv.append(f.read(-1))
rv.append(f.tell())
f.seek(0)
rv.append(f.read())
f.seek(0)
rv.extend(f.readlines())
return " ".join(str(item) for item in rv)
route = ("POST", "/test/test_seek", handler)
self.server.router.register(*route)
resp = self.request(route[1], method="POST", body="12345ab\ncdef")
self.assertEqual(200, resp.getcode())
self.assertEqual(["ab", "7", "12345ab\n", "8", "cdef", "12",
"12345ab\ncdef", "12345ab\n", "cdef"],
resp.read().split(" "))
def test_iter(self):
@wptserve.handlers.handler
def handler(request, response):
f = request.raw_input
return " ".join(line for line in f)
route = ("POST", "/test/test_iter", handler)
self.server.router.register(*route)
resp = self.request(route[1], method="POST", body="12345\nabcdef\r\nzyxwv")
self.assertEqual(200, resp.getcode())
self.assertEqual(["12345\n", "abcdef\r\n", "zyxwv"], resp.read().split(" "))
class TestRequest(TestUsingServer):
def test_body(self):
@wptserve.handlers.handler
def handler(request, response):
request.raw_input.seek(5)
return request.body
route = ("POST", "/test/test_body", handler)
self.server.router.register(*route)
resp = self.request(route[1], method="POST", body="12345ab\ncdef")
self.assertEqual("12345ab\ncdef", resp.read())
def test_route_match(self):
@wptserve.handlers.handler
def handler(request, response):
return request.route_match["match"] + " " + request.route_match["*"]
route = ("GET", "/test/{match}_*", handler)
self.server.router.register(*route)
resp = self.request("/test/some_route")
self.assertEqual("some route", resp.read())
class TestAuth(TestUsingServer):
def test_auth(self):
@wptserve.handlers.handler
def handler(request, response):
return " ".join((request.auth.username, request.auth.password))
route = ("GET", "/test/test_auth", handler)
self.server.router.register(*route)
resp = self.request(route[1], auth=("test", "PASS"))
self.assertEqual(200, resp.getcode())
self.assertEqual(["test", "PASS"], resp.read().split(" "))
if __name__ == '__main__':
unittest.main()
| mpl-2.0 |
kamar42/merdeka-backend | merdeka/apps/mdk/views.py | 1 | 2179 | from django.shortcuts import render
from merdeka.apps.utils.func import find_model, make_response, json_response, jsonify, set_data, set_status, set_message, set_child
from .models import GoodsChilds
def api_view(request, **kwargs):
resp = make_response()
m = kwargs.get('model', None)
# drop if model is empty
if m is None:
set_status(resp, 'failed')
set_message(resp, 'Model Not Found')
return json_response(resp)
if '_' in m:
_model = ''
for _m in m.split('_'):
_model += _m[:1].upper() + _m[1:].lower()
else:
_model = m[:1].upper() + m[1:].lower()
model = find_model('mdk', _model)
# drop if model was not Found
if model is None:
set_status(resp, 'failed')
set_message(resp, 'Model Not Found')
return json_response(resp)
q = request.GET.get('slug', None)
records = model.objects.all()
if q:
records = model.objects.filter(unique_name=q)
# filtering goods and goodschild
if _model == 'Goods':
g = request.GET.get('goods', None)
if g:
records = model.objects.filter(commodity_id=g)
# c = GoodsChilds.objects.filter(goods=records)
# set_child(resp, [dict(
# id=_c.pk,
# name=_c.name,
# slug=_c.unique_name
# ) for _c in c])
elif _model == 'GoodsChilds':
g = request.GET.get('goods', None)
if g:
records = model.objects.filter(goods_id=g)
set_message(resp, 'We found '+str(records.count())+' records.')
if _model == 'Data':
set_data(resp, [dict(
id=r.pk,
commodity=r.commodity.name,
goods=r.goods.name,
goods_child=r.goods_child.name,
price=str(r.price),
unit=r.unit.name,
venue=r.venue.name,
province=r.province.name,
city=r.city.name
) for r in records])
else:
set_data(resp, [dict(
id=r.pk,
name=r.name,
slug=r.unique_name
) for r in records])
return json_response(resp)
| mit |
shinglyu/servo | tests/wpt/css-tests/tools/pywebsocket/src/test/test_handshake_hybi00.py | 466 | 17345 | #!/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 handshake.hybi00 module."""
import unittest
import set_sys_path # Update sys.path to locate mod_pywebsocket module.
from mod_pywebsocket.handshake._base import HandshakeException
from mod_pywebsocket.handshake.hybi00 import Handshaker
from mod_pywebsocket.handshake.hybi00 import _validate_subprotocol
from test import mock
_TEST_KEY1 = '4 @1 46546xW%0l 1 5'
_TEST_KEY2 = '12998 5 Y3 1 .P00'
_TEST_KEY3 = '^n:ds[4U'
_TEST_CHALLENGE_RESPONSE = '8jKS\'y:G*Co,Wxa-'
_GOOD_REQUEST = (
80,
'GET',
'/demo',
{
'Host': 'example.com',
'Connection': 'Upgrade',
'Sec-WebSocket-Key2': _TEST_KEY2,
'Sec-WebSocket-Protocol': 'sample',
'Upgrade': 'WebSocket',
'Sec-WebSocket-Key1': _TEST_KEY1,
'Origin': 'http://example.com',
},
_TEST_KEY3)
_GOOD_REQUEST_CAPITALIZED_HEADER_VALUES = (
80,
'GET',
'/demo',
{
'Host': 'example.com',
'Connection': 'UPGRADE',
'Sec-WebSocket-Key2': _TEST_KEY2,
'Sec-WebSocket-Protocol': 'sample',
'Upgrade': 'WEBSOCKET',
'Sec-WebSocket-Key1': _TEST_KEY1,
'Origin': 'http://example.com',
},
_TEST_KEY3)
_GOOD_REQUEST_CASE_MIXED_HEADER_NAMES = (
80,
'GET',
'/demo',
{
'hOsT': 'example.com',
'cOnNeCtIoN': 'Upgrade',
'sEc-wEbsOcKeT-kEy2': _TEST_KEY2,
'sEc-wEbsOcKeT-pRoToCoL': 'sample',
'uPgRaDe': 'WebSocket',
'sEc-wEbsOcKeT-kEy1': _TEST_KEY1,
'oRiGiN': 'http://example.com',
},
_TEST_KEY3)
_GOOD_RESPONSE_DEFAULT_PORT = (
'HTTP/1.1 101 WebSocket Protocol Handshake\r\n'
'Upgrade: WebSocket\r\n'
'Connection: Upgrade\r\n'
'Sec-WebSocket-Location: ws://example.com/demo\r\n'
'Sec-WebSocket-Origin: http://example.com\r\n'
'Sec-WebSocket-Protocol: sample\r\n'
'\r\n' +
_TEST_CHALLENGE_RESPONSE)
_GOOD_RESPONSE_SECURE = (
'HTTP/1.1 101 WebSocket Protocol Handshake\r\n'
'Upgrade: WebSocket\r\n'
'Connection: Upgrade\r\n'
'Sec-WebSocket-Location: wss://example.com/demo\r\n'
'Sec-WebSocket-Origin: http://example.com\r\n'
'Sec-WebSocket-Protocol: sample\r\n'
'\r\n' +
_TEST_CHALLENGE_RESPONSE)
_GOOD_REQUEST_NONDEFAULT_PORT = (
8081,
'GET',
'/demo',
{
'Host': 'example.com:8081',
'Connection': 'Upgrade',
'Sec-WebSocket-Key2': _TEST_KEY2,
'Sec-WebSocket-Protocol': 'sample',
'Upgrade': 'WebSocket',
'Sec-WebSocket-Key1': _TEST_KEY1,
'Origin': 'http://example.com',
},
_TEST_KEY3)
_GOOD_RESPONSE_NONDEFAULT_PORT = (
'HTTP/1.1 101 WebSocket Protocol Handshake\r\n'
'Upgrade: WebSocket\r\n'
'Connection: Upgrade\r\n'
'Sec-WebSocket-Location: ws://example.com:8081/demo\r\n'
'Sec-WebSocket-Origin: http://example.com\r\n'
'Sec-WebSocket-Protocol: sample\r\n'
'\r\n' +
_TEST_CHALLENGE_RESPONSE)
_GOOD_RESPONSE_SECURE_NONDEF = (
'HTTP/1.1 101 WebSocket Protocol Handshake\r\n'
'Upgrade: WebSocket\r\n'
'Connection: Upgrade\r\n'
'Sec-WebSocket-Location: wss://example.com:8081/demo\r\n'
'Sec-WebSocket-Origin: http://example.com\r\n'
'Sec-WebSocket-Protocol: sample\r\n'
'\r\n' +
_TEST_CHALLENGE_RESPONSE)
_GOOD_REQUEST_NO_PROTOCOL = (
80,
'GET',
'/demo',
{
'Host': 'example.com',
'Connection': 'Upgrade',
'Sec-WebSocket-Key2': _TEST_KEY2,
'Upgrade': 'WebSocket',
'Sec-WebSocket-Key1': _TEST_KEY1,
'Origin': 'http://example.com',
},
_TEST_KEY3)
_GOOD_RESPONSE_NO_PROTOCOL = (
'HTTP/1.1 101 WebSocket Protocol Handshake\r\n'
'Upgrade: WebSocket\r\n'
'Connection: Upgrade\r\n'
'Sec-WebSocket-Location: ws://example.com/demo\r\n'
'Sec-WebSocket-Origin: http://example.com\r\n'
'\r\n' +
_TEST_CHALLENGE_RESPONSE)
_GOOD_REQUEST_WITH_OPTIONAL_HEADERS = (
80,
'GET',
'/demo',
{
'Host': 'example.com',
'Connection': 'Upgrade',
'Sec-WebSocket-Key2': _TEST_KEY2,
'EmptyValue': '',
'Sec-WebSocket-Protocol': 'sample',
'AKey': 'AValue',
'Upgrade': 'WebSocket',
'Sec-WebSocket-Key1': _TEST_KEY1,
'Origin': 'http://example.com',
},
_TEST_KEY3)
# TODO(tyoshino): Include \r \n in key3, challenge response.
_GOOD_REQUEST_WITH_NONPRINTABLE_KEY = (
80,
'GET',
'/demo',
{
'Host': 'example.com',
'Connection': 'Upgrade',
'Sec-WebSocket-Key2': 'y R2 48 Q1O4 e|BV3 i5 1 u- 65',
'Sec-WebSocket-Protocol': 'sample',
'Upgrade': 'WebSocket',
'Sec-WebSocket-Key1': '36 7 74 i 92 2\'m 9 0G',
'Origin': 'http://example.com',
},
''.join(map(chr, [0x01, 0xd1, 0xdd, 0x3b, 0xd1, 0x56, 0x63, 0xff])))
_GOOD_RESPONSE_WITH_NONPRINTABLE_KEY = (
'HTTP/1.1 101 WebSocket Protocol Handshake\r\n'
'Upgrade: WebSocket\r\n'
'Connection: Upgrade\r\n'
'Sec-WebSocket-Location: ws://example.com/demo\r\n'
'Sec-WebSocket-Origin: http://example.com\r\n'
'Sec-WebSocket-Protocol: sample\r\n'
'\r\n' +
''.join(map(chr, [0x0b, 0x99, 0xfa, 0x55, 0xbd, 0x01, 0x23, 0x7b,
0x45, 0xa2, 0xf1, 0xd0, 0x87, 0x8a, 0xee, 0xeb])))
_GOOD_REQUEST_WITH_QUERY_PART = (
80,
'GET',
'/demo?e=mc2',
{
'Host': 'example.com',
'Connection': 'Upgrade',
'Sec-WebSocket-Key2': _TEST_KEY2,
'Sec-WebSocket-Protocol': 'sample',
'Upgrade': 'WebSocket',
'Sec-WebSocket-Key1': _TEST_KEY1,
'Origin': 'http://example.com',
},
_TEST_KEY3)
_GOOD_RESPONSE_WITH_QUERY_PART = (
'HTTP/1.1 101 WebSocket Protocol Handshake\r\n'
'Upgrade: WebSocket\r\n'
'Connection: Upgrade\r\n'
'Sec-WebSocket-Location: ws://example.com/demo?e=mc2\r\n'
'Sec-WebSocket-Origin: http://example.com\r\n'
'Sec-WebSocket-Protocol: sample\r\n'
'\r\n' +
_TEST_CHALLENGE_RESPONSE)
_BAD_REQUESTS = (
( # HTTP request
80,
'GET',
'/demo',
{
'Host': 'www.google.com',
'User-Agent': 'Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.5;'
' en-US; rv:1.9.1.3) Gecko/20090824 Firefox/3.5.3'
' GTB6 GTBA',
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,'
'*/*;q=0.8',
'Accept-Language': 'en-us,en;q=0.5',
'Accept-Encoding': 'gzip,deflate',
'Accept-Charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.7',
'Keep-Alive': '300',
'Connection': 'keep-alive',
}),
( # Wrong method
80,
'POST',
'/demo',
{
'Host': 'example.com',
'Connection': 'Upgrade',
'Sec-WebSocket-Key2': _TEST_KEY2,
'Sec-WebSocket-Protocol': 'sample',
'Upgrade': 'WebSocket',
'Sec-WebSocket-Key1': _TEST_KEY1,
'Origin': 'http://example.com',
},
_TEST_KEY3),
( # Missing Upgrade
80,
'GET',
'/demo',
{
'Host': 'example.com',
'Connection': 'Upgrade',
'Sec-WebSocket-Key2': _TEST_KEY2,
'Sec-WebSocket-Protocol': 'sample',
'Sec-WebSocket-Key1': _TEST_KEY1,
'Origin': 'http://example.com',
},
_TEST_KEY3),
( # Wrong Upgrade
80,
'GET',
'/demo',
{
'Host': 'example.com',
'Connection': 'Upgrade',
'Sec-WebSocket-Key2': _TEST_KEY2,
'Sec-WebSocket-Protocol': 'sample',
'Upgrade': 'NonWebSocket',
'Sec-WebSocket-Key1': _TEST_KEY1,
'Origin': 'http://example.com',
},
_TEST_KEY3),
( # Empty WebSocket-Protocol
80,
'GET',
'/demo',
{
'Host': 'example.com',
'Connection': 'Upgrade',
'Sec-WebSocket-Key2': _TEST_KEY2,
'Sec-WebSocket-Protocol': '',
'Upgrade': 'WebSocket',
'Sec-WebSocket-Key1': _TEST_KEY1,
'Origin': 'http://example.com',
},
_TEST_KEY3),
( # Wrong port number format
80,
'GET',
'/demo',
{
'Host': 'example.com:0x50',
'Connection': 'Upgrade',
'Sec-WebSocket-Key2': _TEST_KEY2,
'Sec-WebSocket-Protocol': 'sample',
'Upgrade': 'WebSocket',
'Sec-WebSocket-Key1': _TEST_KEY1,
'Origin': 'http://example.com',
},
_TEST_KEY3),
( # Header/connection port mismatch
8080,
'GET',
'/demo',
{
'Host': 'example.com',
'Connection': 'Upgrade',
'Sec-WebSocket-Key2': _TEST_KEY2,
'Sec-WebSocket-Protocol': 'sample',
'Upgrade': 'WebSocket',
'Sec-WebSocket-Key1': _TEST_KEY1,
'Origin': 'http://example.com',
},
_TEST_KEY3),
( # Illegal WebSocket-Protocol
80,
'GET',
'/demo',
{
'Host': 'example.com',
'Connection': 'Upgrade',
'Sec-WebSocket-Key2': _TEST_KEY2,
'Sec-WebSocket-Protocol': 'illegal\x09protocol',
'Upgrade': 'WebSocket',
'Sec-WebSocket-Key1': _TEST_KEY1,
'Origin': 'http://example.com',
},
_TEST_KEY3),
)
def _create_request(request_def):
data = ''
if len(request_def) > 4:
data = request_def[4]
conn = mock.MockConn(data)
conn.local_addr = ('0.0.0.0', request_def[0])
return mock.MockRequest(
method=request_def[1],
uri=request_def[2],
headers_in=request_def[3],
connection=conn)
def _create_get_memorized_lines(lines):
"""Creates a function that returns the given string."""
def get_memorized_lines():
return lines
return get_memorized_lines
def _create_requests_with_lines(request_lines_set):
requests = []
for lines in request_lines_set:
request = _create_request(_GOOD_REQUEST)
request.connection.get_memorized_lines = _create_get_memorized_lines(
lines)
requests.append(request)
return requests
class HyBi00HandshakerTest(unittest.TestCase):
def test_good_request_default_port(self):
request = _create_request(_GOOD_REQUEST)
handshaker = Handshaker(request, mock.MockDispatcher())
handshaker.do_handshake()
self.assertEqual(_GOOD_RESPONSE_DEFAULT_PORT,
request.connection.written_data())
self.assertEqual('/demo', request.ws_resource)
self.assertEqual('http://example.com', request.ws_origin)
self.assertEqual('ws://example.com/demo', request.ws_location)
self.assertEqual('sample', request.ws_protocol)
def test_good_request_capitalized_header_values(self):
request = _create_request(_GOOD_REQUEST_CAPITALIZED_HEADER_VALUES)
handshaker = Handshaker(request, mock.MockDispatcher())
handshaker.do_handshake()
self.assertEqual(_GOOD_RESPONSE_DEFAULT_PORT,
request.connection.written_data())
def test_good_request_case_mixed_header_names(self):
request = _create_request(_GOOD_REQUEST_CASE_MIXED_HEADER_NAMES)
handshaker = Handshaker(request, mock.MockDispatcher())
handshaker.do_handshake()
self.assertEqual(_GOOD_RESPONSE_DEFAULT_PORT,
request.connection.written_data())
def test_good_request_secure_default_port(self):
request = _create_request(_GOOD_REQUEST)
request.connection.local_addr = ('0.0.0.0', 443)
request.is_https_ = True
handshaker = Handshaker(request, mock.MockDispatcher())
handshaker.do_handshake()
self.assertEqual(_GOOD_RESPONSE_SECURE,
request.connection.written_data())
self.assertEqual('sample', request.ws_protocol)
def test_good_request_nondefault_port(self):
request = _create_request(_GOOD_REQUEST_NONDEFAULT_PORT)
handshaker = Handshaker(request,
mock.MockDispatcher())
handshaker.do_handshake()
self.assertEqual(_GOOD_RESPONSE_NONDEFAULT_PORT,
request.connection.written_data())
self.assertEqual('sample', request.ws_protocol)
def test_good_request_secure_non_default_port(self):
request = _create_request(_GOOD_REQUEST_NONDEFAULT_PORT)
request.is_https_ = True
handshaker = Handshaker(request, mock.MockDispatcher())
handshaker.do_handshake()
self.assertEqual(_GOOD_RESPONSE_SECURE_NONDEF,
request.connection.written_data())
self.assertEqual('sample', request.ws_protocol)
def test_good_request_default_no_protocol(self):
request = _create_request(_GOOD_REQUEST_NO_PROTOCOL)
handshaker = Handshaker(request, mock.MockDispatcher())
handshaker.do_handshake()
self.assertEqual(_GOOD_RESPONSE_NO_PROTOCOL,
request.connection.written_data())
self.assertEqual(None, request.ws_protocol)
def test_good_request_optional_headers(self):
request = _create_request(_GOOD_REQUEST_WITH_OPTIONAL_HEADERS)
handshaker = Handshaker(request, mock.MockDispatcher())
handshaker.do_handshake()
self.assertEqual('AValue',
request.headers_in['AKey'])
self.assertEqual('',
request.headers_in['EmptyValue'])
def test_good_request_with_nonprintable_key(self):
request = _create_request(_GOOD_REQUEST_WITH_NONPRINTABLE_KEY)
handshaker = Handshaker(request, mock.MockDispatcher())
handshaker.do_handshake()
self.assertEqual(_GOOD_RESPONSE_WITH_NONPRINTABLE_KEY,
request.connection.written_data())
self.assertEqual('sample', request.ws_protocol)
def test_good_request_with_query_part(self):
request = _create_request(_GOOD_REQUEST_WITH_QUERY_PART)
handshaker = Handshaker(request, mock.MockDispatcher())
handshaker.do_handshake()
self.assertEqual(_GOOD_RESPONSE_WITH_QUERY_PART,
request.connection.written_data())
self.assertEqual('ws://example.com/demo?e=mc2', request.ws_location)
def test_bad_requests(self):
for request in map(_create_request, _BAD_REQUESTS):
handshaker = Handshaker(request, mock.MockDispatcher())
self.assertRaises(HandshakeException, handshaker.do_handshake)
class HyBi00ValidateSubprotocolTest(unittest.TestCase):
def test_validate_subprotocol(self):
# should succeed.
_validate_subprotocol('sample')
_validate_subprotocol('Sample')
_validate_subprotocol('sample\x7eprotocol')
_validate_subprotocol('sample\x20protocol')
# should fail.
self.assertRaises(HandshakeException,
_validate_subprotocol,
'')
self.assertRaises(HandshakeException,
_validate_subprotocol,
'sample\x19protocol')
self.assertRaises(HandshakeException,
_validate_subprotocol,
'sample\x7fprotocol')
self.assertRaises(HandshakeException,
_validate_subprotocol,
# "Japan" in Japanese
u'\u65e5\u672c')
if __name__ == '__main__':
unittest.main()
# vi:sts=4 sw=4 et
| mpl-2.0 |
ryfeus/lambda-packs | Lxml_requests/source/wheel/signatures/__init__.py | 565 | 3779 | """
Create and verify jws-js format Ed25519 signatures.
"""
__all__ = [ 'sign', 'verify' ]
import json
from ..util import urlsafe_b64decode, urlsafe_b64encode, native, binary
ed25519ll = None
ALG = "Ed25519"
def get_ed25519ll():
"""Lazy import-and-test of ed25519 module"""
global ed25519ll
if not ed25519ll:
try:
import ed25519ll # fast (thousands / s)
except (ImportError, OSError): # pragma nocover
from . import ed25519py as ed25519ll # pure Python (hundreds / s)
test()
return ed25519ll
def sign(payload, keypair):
"""Return a JWS-JS format signature given a JSON-serializable payload and
an Ed25519 keypair."""
get_ed25519ll()
#
header = {
"alg": ALG,
"jwk": {
"kty": ALG, # alg -> kty in jwk-08.
"vk": native(urlsafe_b64encode(keypair.vk))
}
}
encoded_header = urlsafe_b64encode(binary(json.dumps(header, sort_keys=True)))
encoded_payload = urlsafe_b64encode(binary(json.dumps(payload, sort_keys=True)))
secured_input = b".".join((encoded_header, encoded_payload))
sig_msg = ed25519ll.crypto_sign(secured_input, keypair.sk)
signature = sig_msg[:ed25519ll.SIGNATUREBYTES]
encoded_signature = urlsafe_b64encode(signature)
return {"recipients":
[{"header":native(encoded_header),
"signature":native(encoded_signature)}],
"payload": native(encoded_payload)}
def assertTrue(condition, message=""):
if not condition:
raise ValueError(message)
def verify(jwsjs):
"""Return (decoded headers, payload) if all signatures in jwsjs are
consistent, else raise ValueError.
Caller must decide whether the keys are actually trusted."""
get_ed25519ll()
# XXX forbid duplicate keys in JSON input using object_pairs_hook (2.7+)
recipients = jwsjs["recipients"]
encoded_payload = binary(jwsjs["payload"])
headers = []
for recipient in recipients:
assertTrue(len(recipient) == 2, "Unknown recipient key {0}".format(recipient))
h = binary(recipient["header"])
s = binary(recipient["signature"])
header = json.loads(native(urlsafe_b64decode(h)))
assertTrue(header["alg"] == ALG,
"Unexpected algorithm {0}".format(header["alg"]))
if "alg" in header["jwk"] and not "kty" in header["jwk"]:
header["jwk"]["kty"] = header["jwk"]["alg"] # b/w for JWK < -08
assertTrue(header["jwk"]["kty"] == ALG, # true for Ed25519
"Unexpected key type {0}".format(header["jwk"]["kty"]))
vk = urlsafe_b64decode(binary(header["jwk"]["vk"]))
secured_input = b".".join((h, encoded_payload))
sig = urlsafe_b64decode(s)
sig_msg = sig+secured_input
verified_input = native(ed25519ll.crypto_sign_open(sig_msg, vk))
verified_header, verified_payload = verified_input.split('.')
verified_header = binary(verified_header)
decoded_header = native(urlsafe_b64decode(verified_header))
headers.append(json.loads(decoded_header))
verified_payload = binary(verified_payload)
# only return header, payload that have passed through the crypto library.
payload = json.loads(native(urlsafe_b64decode(verified_payload)))
return headers, payload
def test():
kp = ed25519ll.crypto_sign_keypair()
payload = {'test': 'onstartup'}
jwsjs = json.loads(json.dumps(sign(payload, kp)))
verify(jwsjs)
jwsjs['payload'] += 'x'
try:
verify(jwsjs)
except ValueError:
pass
else: # pragma no cover
raise RuntimeError("No error from bad wheel.signatures payload.")
| mit |
ryfeus/lambda-packs | Lxml_requests/source/google/protobuf/internal/import_test_package/__init__.py | 165 | 1768 | # Protocol Buffers - Google's data interchange format
# Copyright 2008 Google Inc. All rights reserved.
# https://developers.google.com/protocol-buffers/
#
# 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.
"""Sample module importing a nested proto from itself."""
from google.protobuf.internal.import_test_package import outer_pb2 as myproto
| mit |
ccomb/OpenUpgrade | addons/hr_expense/report/__init__.py | 380 | 1071 | # -*- 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/>.
#
##############################################################################
import hr_expense_report
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
| agpl-3.0 |
GeoCat/QGIS | python/plugins/processing/algs/grass7/ext/i_in_spotvgt.py | 15 | 1336 | # -*- coding: utf-8 -*-
"""
***************************************************************************
i_in_spotvgt.py
---------------
Date : April 2016
Copyright : (C) 2016 by Médéric Ribreux
Email : medspx at medspx dot fr
***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************
"""
__author__ = 'Médéric Ribreux'
__date__ = 'April 2016'
__copyright__ = '(C) 2016, Médéric Ribreux'
# This will get replaced with a git SHA1 when you do a git archive
__revision__ = '$Format:%H$'
def processInputs(alg):
# Here, we apply directly the algorithm
# So we just need to get the projection of the layer !
layer = alg.getParameterValue('input')
alg.setSessionProjectionFromLayer(layer, alg.commands)
| gpl-2.0 |
apanju/odoo | addons/point_of_sale/report/pos_lines.py | 230 | 2464 | # -*- 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/>.
#
##############################################################################
import time
from openerp.osv import osv
from openerp.report import report_sxw
class pos_lines(report_sxw.rml_parse):
def __init__(self, cr, uid, name, context):
super(pos_lines, self).__init__(cr, uid, name, context=context)
self.total = 0.0
self.localcontext.update({
'time': time,
'total_quantity': self.__total_quantity__,
'taxes':self.__taxes__,
})
def __total_quantity__(self, obj):
tot = 0
for line in obj.lines:
tot += line.qty
self.total = tot
return self.total
def __taxes__(self, obj):
self.cr.execute ( " Select acct.name from pos_order as po " \
" LEFT JOIN pos_order_line as pol ON po.id = pol.order_id " \
" LEFT JOIN product_product as pp ON pol.product_id = pp.id"
" LEFT JOIN product_taxes_rel as ptr ON pp.product_tmpl_id = ptr.prod_id " \
" LEFT JOIN account_tax as acct ON acct.id = ptr.tax_id " \
" WHERE pol.id = %s", (obj.id,))
res=self.cr.fetchone()[0]
return res
class report_pos_lines(osv.AbstractModel):
_name = 'report.point_of_sale.report_saleslines'
_inherit = 'report.abstract_report'
_template = 'point_of_sale.report_saleslines'
_wrapped_report_class = pos_lines
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
| agpl-3.0 |
emedinaa/contentbox | third_party/django_summernote/tests.py | 5 | 6465 | # -*- coding: utf-8 -*-
from django.contrib.admin.sites import AdminSite
from django.core.urlresolvers import reverse
from django.test import TestCase
from django_summernote.settings import summernote_config
from imp import reload
class DjangoSummernoteTest(TestCase):
def setUp(self):
self.site = AdminSite()
def test_base(self):
self.assertTrue(True)
def test_url(self):
url = reverse('django_summernote-editor', kwargs={'id': 'foobar'})
response = self.client.get(url)
self.assertEqual(response.status_code, 200)
self.assertContains(response, 'summernote.min.js')
self.assertContains(response, 'summernote.css')
def test_widget(self):
from django_summernote.widgets import SummernoteWidget
widget = SummernoteWidget()
html = widget.render(
'foobar', 'lorem ipsum', attrs={'id': 'id_foobar'}
)
url = reverse('django_summernote-editor', kwargs={'id': 'id_foobar'})
assert url in html
assert 'id="id_foobar"' in html
def test_widget_inplace(self):
from django_summernote.widgets import SummernoteInplaceWidget
widget = SummernoteInplaceWidget()
html = widget.render(
'foobar', 'lorem ipsum', attrs={'id': 'id_foobar'}
)
assert 'summernote' in html
def test_form(self):
from django import forms
from django_summernote.widgets import SummernoteWidget
class SimpleForm(forms.Form):
foobar = forms.CharField(widget=SummernoteWidget())
f = SimpleForm()
html = f.as_p()
url = reverse('django_summernote-editor', kwargs={'id': 'id_foobar'})
assert url in html
assert 'id="id_foobar"' in html
def test_empty(self):
from django import forms
from django_summernote.widgets import SummernoteWidget
class SimpleForm(forms.Form):
foobar = forms.CharField(widget=SummernoteWidget())
should_be_parsed_as_empty = '<p><br></p>'
should_not_be_parsed_as_empty = '<p>lorem ipsum</p>'
f = SimpleForm({'foobar': should_be_parsed_as_empty})
assert not f.is_valid()
assert not f.cleaned_data.get('foobar')
f = SimpleForm({'foobar': should_not_be_parsed_as_empty})
assert f.is_valid()
assert f.cleaned_data.get('foobar')
def test_attachment(self):
import os
url = reverse('django_summernote-upload_attachment')
with open(__file__, 'rb') as fp:
response = self.client.post(url, {'files': [fp]})
self.assertEqual(response.status_code, 200)
self.assertContains(
response, '"name": "%s"' % os.path.basename(__file__))
self.assertContains(response, '"url": ')
self.assertContains(response, '"size": ')
def test_attachment_with_custom_storage(self):
summernote_config['attachment_storage_class'] = \
'django.core.files.storage.DefaultStorage'
# reloading module to apply custom stroage class
from django_summernote import models
reload(models)
url = reverse('django_summernote-upload_attachment')
with open(__file__, 'rb') as fp:
response = self.client.post(url, {'files': [fp]})
self.assertEqual(response.status_code, 200)
def test_attachment_with_bad_storage(self):
from django.core.exceptions import ImproperlyConfigured
# ValueError
summernote_config['attachment_storage_class'] = \
'wow_no_dot_storage_class_name'
with self.assertRaises(ImproperlyConfigured):
from django_summernote import models
reload(models)
# ImportError
summernote_config['attachment_storage_class'] = \
'wow.such.fake.storage'
with self.assertRaises(ImproperlyConfigured):
from django_summernote import models
reload(models)
# AttributeError
summernote_config['attachment_storage_class'] = \
'django.core.files.storage.DogeStorage'
with self.assertRaises(ImproperlyConfigured):
from django_summernote import models
reload(models)
def test_attachment_bad_request(self):
url = reverse('django_summernote-upload_attachment')
response = self.client.get(url)
self.assertNotEqual(response.status_code, 200)
def test_attachment_no_attachment(self):
url = reverse('django_summernote-upload_attachment')
response = self.client.post(url)
self.assertNotEqual(response.status_code, 200)
def test_attachment_filesize_exceed(self):
import os
url = reverse('django_summernote-upload_attachment')
size = os.path.getsize(__file__)
old_limit = summernote_config['attachment_filesize_limit']
summernote_config['attachment_filesize_limit'] = size - 1
with open(__file__, 'rb') as fp:
response = self.client.post(url, {'files': [fp]})
self.assertNotEqual(response.status_code, 200)
summernote_config['attachment_filesize_limit'] = old_limit
def test_lang_ko(self):
old_lang = summernote_config['lang']
summernote_config['lang'] = 'ko-KR'
from django_summernote import widgets
reload(widgets)
widget = widgets.SummernoteInplaceWidget()
summernote_config['lang'] = old_lang
assert '/django_summernote/lang/summernote-ko-KR.js' in widget.Media.js
def test_admin_model(self):
from django.db import models
from django_summernote.admin import SummernoteModelAdmin
from django_summernote.admin import SummernoteInlineModelAdmin
from django_summernote.widgets import SummernoteWidget
class SimpleParentModel(models.Model):
foobar = models.TextField()
class SimpleModel(models.Model):
foobar = models.TextField()
parent = models.ForeignKey(SimpleParentModel)
class SimpleModelInline(SummernoteInlineModelAdmin):
model = SimpleModel
class SimpleParentModelAdmin(SummernoteModelAdmin):
inlines = [SimpleModelInline]
ma = SimpleParentModelAdmin(SimpleParentModel, self.site)
assert isinstance(
ma.get_form(None).base_fields['foobar'].widget,
SummernoteWidget
)
| apache-2.0 |
pastephens/pysal | pysal/cg/tests/test_geoJSON.py | 6 | 1829 | import pysal
from pysal.cg.shapes import Point, Chain
import doctest
import unittest
class test_MultiPloygon(unittest.TestCase):
def test___init__1(self):
"""
Tests conversion of polygons with multiple shells to
geoJSON multipolygons. and back.
"""
shp = pysal.open(pysal.examples.get_path("NAT.shp"),'r')
multipolygons = [p for p in shp if len(p.parts) > 1]
geoJSON = [p.__geo_interface__ for p in multipolygons]
for poly in multipolygons:
json = poly.__geo_interface__
shape = pysal.cg.asShape(json)
self.assertEquals(json['type'],'MultiPolygon')
self.assertEquals(str(shape.holes), str(poly.holes))
self.assertEquals(str(shape.parts), str(poly.parts))
class test_MultiLineString(unittest.TestCase):
def test_multipart_chain(self):
vertices = [[Point((0, 0)), Point((1, 0)), Point((1, 5))],
[Point((-5, -5)), Point((-5, 0)), Point((0, 0))]]
#part A
chain0 = Chain(vertices[0])
#part B
chain1 = Chain(vertices[1])
#part A and B
chain2 = Chain(vertices)
json = chain0.__geo_interface__
self.assertEquals(json['type'], 'LineString')
self.assertEquals(len(json['coordinates']), 3)
json = chain1.__geo_interface__
self.assertEquals(json['type'], 'LineString')
self.assertEquals(len(json['coordinates']), 3)
json = chain2.__geo_interface__
self.assertEquals(json['type'], 'MultiLineString')
self.assertEquals(len(json['coordinates']), 2)
chain3 = pysal.cg.asShape(json)
self.assertEquals(chain2.parts, chain3.parts)
if __name__ == '__main__':
unittest.main()
#runner = unittest.TextTestRunner()
#runner.run(suite)
| bsd-3-clause |
keichan100yen/ode-ext | boost/libs/python/test/numpy/ndarray.py | 5 | 2942 | #!/usr/bin/env python
# Copyright Jim Bosch & Ankit Daftery 2010-2012.
# Distributed under the Boost Software License, Version 1.0.
# (See accompanying file LICENSE_1_0.txt or copy at
# http://www.boost.org/LICENSE_1_0.txt)
import ndarray_ext
import unittest
import numpy
class TestNdarray(unittest.TestCase):
def testNdzeros(self):
for dtp in (numpy.int16, numpy.int32, numpy.float32, numpy.complex128):
v = numpy.zeros(60, dtype=dtp)
dt = numpy.dtype(dtp)
for shape in ((60,),(6,10),(4,3,5),(2,2,3,5)):
a1 = ndarray_ext.zeros(shape,dt)
a2 = v.reshape(a1.shape)
self.assertEqual(shape,a1.shape)
self.assert_((a1 == a2).all())
def testNdzeros_matrix(self):
for dtp in (numpy.int16, numpy.int32, numpy.float32, numpy.complex128):
dt = numpy.dtype(dtp)
shape = (6, 10)
a1 = ndarray_ext.zeros_matrix(shape, dt)
a2 = numpy.matrix(numpy.zeros(shape, dtype=dtp))
self.assertEqual(shape,a1.shape)
self.assert_((a1 == a2).all())
self.assertEqual(type(a1), type(a2))
def testNdarray(self):
a = range(0,60)
for dtp in (numpy.int16, numpy.int32, numpy.float32, numpy.complex128):
v = numpy.array(a, dtype=dtp)
dt = numpy.dtype(dtp)
a1 = ndarray_ext.array(a)
a2 = ndarray_ext.array(a,dt)
self.assert_((a1 == v).all())
self.assert_((a2 == v).all())
for shape in ((60,),(6,10),(4,3,5),(2,2,3,5)):
a1 = a1.reshape(shape)
self.assertEqual(shape,a1.shape)
a2 = a2.reshape(shape)
self.assertEqual(shape,a2.shape)
def testNdempty(self):
for dtp in (numpy.int16, numpy.int32, numpy.float32, numpy.complex128):
dt = numpy.dtype(dtp)
for shape in ((60,),(6,10),(4,3,5),(2,2,3,5)):
a1 = ndarray_ext.empty(shape,dt)
a2 = ndarray_ext.c_empty(shape,dt)
self.assertEqual(shape,a1.shape)
self.assertEqual(shape,a2.shape)
def testTranspose(self):
for dtp in (numpy.int16, numpy.int32, numpy.float32, numpy.complex128):
dt = numpy.dtype(dtp)
for shape in ((6,10),(4,3,5),(2,2,3,5)):
a1 = numpy.empty(shape,dt)
a2 = a1.transpose()
a1 = ndarray_ext.transpose(a1)
self.assertEqual(a1.shape,a2.shape)
def testSqueeze(self):
a1 = numpy.array([[[3,4,5]]])
a2 = a1.squeeze()
a1 = ndarray_ext.squeeze(a1)
self.assertEqual(a1.shape,a2.shape)
def testReshape(self):
a1 = numpy.empty((2,2))
a2 = ndarray_ext.reshape(a1,(1,4))
self.assertEqual(a2.shape,(1,4))
if __name__=="__main__":
unittest.main()
| mit |
idlead/scikit-learn | sklearn/externals/joblib/__init__.py | 23 | 4764 | """ Joblib is a set of tools to provide **lightweight pipelining in
Python**. In particular, joblib offers:
1. transparent disk-caching of the output values and lazy re-evaluation
(memoize pattern)
2. easy simple parallel computing
3. logging and tracing of the execution
Joblib is optimized to be **fast** and **robust** in particular on large
data and has specific optimizations for `numpy` arrays. It is
**BSD-licensed**.
============================== ============================================
**User documentation**: http://pythonhosted.org/joblib
**Download packages**: http://pypi.python.org/pypi/joblib#downloads
**Source code**: http://github.com/joblib/joblib
**Report issues**: http://github.com/joblib/joblib/issues
============================== ============================================
Vision
--------
The vision is to provide tools to easily achieve better performance and
reproducibility when working with long running jobs.
* **Avoid computing twice the same thing**: code is rerun over an
over, for instance when prototyping computational-heavy jobs (as in
scientific development), but hand-crafted solution to alleviate this
issue is error-prone and often leads to unreproducible results
* **Persist to disk transparently**: persisting in an efficient way
arbitrary objects containing large data is hard. Using
joblib's caching mechanism avoids hand-written persistence and
implicitly links the file on disk to the execution context of
the original Python object. As a result, joblib's persistence is
good for resuming an application status or computational job, eg
after a crash.
Joblib strives to address these problems while **leaving your code and
your flow control as unmodified as possible** (no framework, no new
paradigms).
Main features
------------------
1) **Transparent and fast disk-caching of output value:** a memoize or
make-like functionality for Python functions that works well for
arbitrary Python objects, including very large numpy arrays. Separate
persistence and flow-execution logic from domain logic or algorithmic
code by writing the operations as a set of steps with well-defined
inputs and outputs: Python functions. Joblib can save their
computation to disk and rerun it only if necessary::
>>> from sklearn.externals.joblib import Memory
>>> mem = Memory(cachedir='/tmp/joblib')
>>> import numpy as np
>>> a = np.vander(np.arange(3)).astype(np.float)
>>> square = mem.cache(np.square)
>>> b = square(a) # doctest: +ELLIPSIS
________________________________________________________________________________
[Memory] Calling square...
square(array([[ 0., 0., 1.],
[ 1., 1., 1.],
[ 4., 2., 1.]]))
___________________________________________________________square - 0...s, 0.0min
>>> c = square(a)
>>> # The above call did not trigger an evaluation
2) **Embarrassingly parallel helper:** to make is easy to write readable
parallel code and debug it quickly::
>>> from sklearn.externals.joblib import Parallel, delayed
>>> from math import sqrt
>>> Parallel(n_jobs=1)(delayed(sqrt)(i**2) for i in range(10))
[0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0]
3) **Logging/tracing:** The different functionalities will
progressively acquire better logging mechanism to help track what
has been ran, and capture I/O easily. In addition, Joblib will
provide a few I/O primitives, to easily define define logging and
display streams, and provide a way of compiling a report.
We want to be able to quickly inspect what has been run.
4) **Fast compressed Persistence**: a replacement for pickle to work
efficiently on Python objects containing large data (
*joblib.dump* & *joblib.load* ).
..
>>> import shutil ; shutil.rmtree('/tmp/joblib/')
"""
# PEP0440 compatible formatted version, see:
# https://www.python.org/dev/peps/pep-0440/
#
# Generic release markers:
# X.Y
# X.Y.Z # For bugfix releases
#
# Admissible pre-release markers:
# X.YaN # Alpha release
# X.YbN # Beta release
# X.YrcN # Release Candidate
# X.Y # Final release
#
# Dev branch marker is: 'X.Y.dev' or 'X.Y.devN' where N is an integer.
# 'X.Y.dev0' is the canonical version of 'X.Y.dev'
#
__version__ = '0.9.3'
from .memory import Memory, MemorizedResult
from .logger import PrintTime
from .logger import Logger
from .hashing import hash
from .numpy_pickle import dump
from .numpy_pickle import load
from .parallel import Parallel
from .parallel import delayed
from .parallel import cpu_count
| bsd-3-clause |
Slim80/Fulgor_Kernel_Lollipop | tools/perf/scripts/python/futex-contention.py | 11261 | 1486 | # futex contention
# (c) 2010, Arnaldo Carvalho de Melo <acme@redhat.com>
# Licensed under the terms of the GNU GPL License version 2
#
# Translation of:
#
# http://sourceware.org/systemtap/wiki/WSFutexContention
#
# to perf python scripting.
#
# Measures futex contention
import os, sys
sys.path.append(os.environ['PERF_EXEC_PATH'] + '/scripts/python/Perf-Trace-Util/lib/Perf/Trace')
from Util import *
process_names = {}
thread_thislock = {}
thread_blocktime = {}
lock_waits = {} # long-lived stats on (tid,lock) blockage elapsed time
process_names = {} # long-lived pid-to-execname mapping
def syscalls__sys_enter_futex(event, ctxt, cpu, s, ns, tid, comm,
nr, uaddr, op, val, utime, uaddr2, val3):
cmd = op & FUTEX_CMD_MASK
if cmd != FUTEX_WAIT:
return # we don't care about originators of WAKE events
process_names[tid] = comm
thread_thislock[tid] = uaddr
thread_blocktime[tid] = nsecs(s, ns)
def syscalls__sys_exit_futex(event, ctxt, cpu, s, ns, tid, comm,
nr, ret):
if thread_blocktime.has_key(tid):
elapsed = nsecs(s, ns) - thread_blocktime[tid]
add_stats(lock_waits, (tid, thread_thislock[tid]), elapsed)
del thread_blocktime[tid]
del thread_thislock[tid]
def trace_begin():
print "Press control+C to stop and show the summary"
def trace_end():
for (tid, lock) in lock_waits:
min, max, avg, count = lock_waits[tid, lock]
print "%s[%d] lock %x contended %d times, %d avg ns" % \
(process_names[tid], tid, lock, count, avg)
| gpl-2.0 |
DigitalCampus/django-oppia | tests/profile/models/test_models.py | 1 | 9519 | from django.core.exceptions import ValidationError
from django.db.utils import IntegrityError
from oppia.test import OppiaTestCase
from profile.models import UserProfile, CustomField, UserProfileCustomField
class ProfileCustomFieldsTest(OppiaTestCase):
fixtures = ['tests/test_user.json',
'tests/test_oppia.json',
'tests/test_quiz.json',
'tests/test_course_permissions.json']
VALUE_STR_DEFAULT = "my string"
def test_custom_field_model_name(self):
custom_field = CustomField(
id='my_cf_key',
label='String',
required=True,
type='str')
custom_field.save()
self.assertEqual(str(custom_field), 'my_cf_key')
def test_teacher_only(self):
user = self.normal_user
self.assertFalse(user.userprofile.is_teacher_only())
'''
Upload permissions
'''
def test_get_can_upload_admin(self):
profile = UserProfile.objects.get(user=self.admin_user)
self.assertEqual(profile.get_can_upload(), True)
def test_get_can_upload_staff(self):
profile = UserProfile.objects.get(user=self.staff_user)
self.assertEqual(profile.get_can_upload(), True)
def test_get_can_upload_teacher(self):
profile = UserProfile.objects.get(user=self.teacher_user)
self.assertEqual(profile.get_can_upload(), True)
def test_get_can_upload_user(self):
profile = UserProfile.objects.get(user=self.normal_user)
self.assertEqual(profile.get_can_upload(), False)
def test_get_can_upload_activity_log_admin(self):
profile = UserProfile.objects.get(user=self.admin_user)
self.assertEqual(profile.get_can_upload_activitylog(), True)
def test_get_can_upload_activity_log_staff(self):
profile = UserProfile.objects.get(user=self.staff_user)
self.assertEqual(profile.get_can_upload_activitylog(), True)
def test_get_can_upload_activity_log_teacher(self):
profile = UserProfile.objects.get(user=self.teacher_user)
self.assertEqual(profile.get_can_upload_activitylog(), False)
def test_get_can_upload_activity_log_user(self):
profile = UserProfile.objects.get(user=self.normal_user)
self.assertEqual(profile.get_can_upload_activitylog(), False)
'''
Custom fields
'''
def test_user_custom_field_model_name(self):
custom_field = CustomField(
id='str',
label='String',
required=True,
type='str')
custom_field.save()
upcf = UserProfileCustomField(key_name=custom_field,
user=self.normal_user,
value_str=self.VALUE_STR_DEFAULT)
upcf.save()
self.assertEqual('str: demo', str(upcf))
# test get_value string
def test_custom_field_get_value_str(self):
custom_field = CustomField(
id='str',
label='String',
required=True,
type='str')
custom_field.save()
upcf = UserProfileCustomField(key_name=custom_field,
user=self.normal_user,
value_str=self.VALUE_STR_DEFAULT)
upcf.save()
self.assertEqual(upcf.get_value(), self.VALUE_STR_DEFAULT)
self.assertNotEqual(upcf.get_value(), True)
self.assertNotEqual(upcf.get_value(), False)
self.assertNotEqual(upcf.get_value(), None)
self.assertNotEqual(upcf.get_value(), 123)
# test get_value int
def test_custom_field_get_value_int(self):
custom_field = CustomField(
id='int',
label='Integer',
required=True,
type='int')
custom_field.save()
upcf = UserProfileCustomField(key_name=custom_field,
user=self.normal_user,
value_int=123)
upcf.save()
self.assertEqual(upcf.get_value(), 123)
self.assertNotEqual(upcf.get_value(), "123")
self.assertNotEqual(upcf.get_value(), True)
self.assertNotEqual(upcf.get_value(), False)
self.assertNotEqual(upcf.get_value(), None)
# get get value bool
def test_custom_field_get_value_bool(self):
custom_field = CustomField(
id='bool',
label='Boolean',
required=True,
type='bool')
custom_field.save()
upcf = UserProfileCustomField(key_name=custom_field,
user=self.normal_user,
value_bool=True)
upcf.save()
self.assertEqual(upcf.get_value(), True)
self.assertNotEqual(upcf.get_value(), "True")
self.assertNotEqual(upcf.get_value(), 123)
self.assertNotEqual(upcf.get_value(), False)
self.assertNotEqual(upcf.get_value(), None)
# test multiple rows in userprofilecustomfield
def test_custom_field_multiple_rows(self):
custom_field = CustomField(
id='str',
label='String',
required=True,
type='str')
custom_field.save()
upcf = UserProfileCustomField(key_name=custom_field,
user=self.normal_user,
value_str=self.VALUE_STR_DEFAULT)
upcf.save()
with self.assertRaises(IntegrityError):
upcf = UserProfileCustomField(key_name=custom_field,
user=self.normal_user,
value_str="my other string")
upcf.save()
def test_wrong_type_bool_in_int(self):
custom_field = CustomField(
id='int',
label='Integer',
required=True,
type='int')
custom_field.save()
upcf = UserProfileCustomField(key_name=custom_field,
user=self.normal_user,
value_int=True)
upcf.save()
self.assertEqual(True, upcf.get_value())
upcf.value_int = False
upcf.save()
self.assertEqual(False, upcf.get_value())
def test_wrong_type_bool_in_str(self):
custom_field = CustomField(
id='str',
label='String',
required=True,
type='str')
custom_field.save()
upcf = UserProfileCustomField(key_name=custom_field,
user=self.normal_user,
value_str=True)
upcf.save()
self.assertEqual(True, upcf.get_value())
upcf.value_str = False
upcf.save()
self.assertEqual(False, upcf.get_value())
def test_wrong_type_int_in_bool_123(self):
custom_field = CustomField(
id='bool',
label='Boolean',
required=True,
type='bool')
custom_field.save()
with self.assertRaises(ValidationError):
UserProfileCustomField(key_name=custom_field,
user=self.normal_user,
value_bool=123).save()
def test_wrong_type_int_in_bool_0(self):
custom_field = CustomField(
id='bool',
label='Boolean',
required=True,
type='bool')
custom_field.save()
upcf = UserProfileCustomField(key_name=custom_field,
user=self.normal_user,
value_bool=0)
upcf.save()
self.assertEqual(0, upcf.get_value())
def test_wrong_type_int_in_bool_1(self):
custom_field = CustomField(
id='bool',
label='Boolean',
required=True,
type='bool')
custom_field.save()
upcf = UserProfileCustomField(key_name=custom_field,
user=self.normal_user,
value_bool=1)
upcf.save()
self.assertEqual(1, upcf.get_value())
def test_wrong_type_int_in_str(self):
custom_field = CustomField(
id='str',
label='String',
required=True,
type='str')
custom_field.save()
upcf = UserProfileCustomField(key_name=custom_field,
user=self.normal_user,
value_str=123)
upcf.save()
self.assertEqual(123, upcf.get_value())
def test_wrong_type_str_in_bool(self):
custom_field = CustomField(
id='bool',
label='Boolean',
required=True,
type='bool')
custom_field.save()
with self.assertRaises(ValidationError):
UserProfileCustomField(key_name=custom_field,
user=self.normal_user,
value_bool=self.VALUE_STR_DEFAULT).save()
def test_wrong_type_str_in_int(self):
custom_field = CustomField(
id='int',
label='Integer',
required=True,
type='int')
custom_field.save()
with self.assertRaises(ValueError):
UserProfileCustomField(key_name=custom_field,
user=self.normal_user,
value_int=self.VALUE_STR_DEFAULT).save()
| gpl-3.0 |
Jollyplum/cassandra | pylib/cqlshlib/cqlhandling.py | 46 | 13013 | # 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.
# code for dealing with CQL's syntax, rules, interpretation
# i.e., stuff that's not necessarily cqlsh-specific
import traceback
from cassandra.metadata import cql_keywords_reserved
from . import pylexotron, util
Hint = pylexotron.Hint
class CqlParsingRuleSet(pylexotron.ParsingRuleSet):
available_compression_classes = (
'DeflateCompressor',
'SnappyCompressor',
'LZ4Compressor',
)
available_compaction_classes = (
'LeveledCompactionStrategy',
'SizeTieredCompactionStrategy',
'DateTieredCompactionStrategy',
'TimeWindowCompactionStrategy'
)
replication_strategies = (
'SimpleStrategy',
'OldNetworkTopologyStrategy',
'NetworkTopologyStrategy'
)
replication_factor_strategies = (
'SimpleStrategy',
'org.apache.cassandra.locator.SimpleStrategy',
'OldNetworkTopologyStrategy',
'org.apache.cassandra.locator.OldNetworkTopologyStrategy'
)
def __init__(self, *args, **kwargs):
pylexotron.ParsingRuleSet.__init__(self, *args, **kwargs)
# note: commands_end_with_newline may be extended by callers.
self.commands_end_with_newline = set()
self.set_reserved_keywords(cql_keywords_reserved)
def set_reserved_keywords(self, keywords):
"""
We cannot let resreved cql keywords be simple 'identifier' since this caused
problems with completion, see CASSANDRA-10415
"""
syntax = '<reserved_identifier> ::= /(' + '|'.join(r'\b{}\b'.format(k) for k in keywords) + ')/ ;'
self.append_rules(syntax)
def completer_for(self, rulename, symname):
def registrator(f):
def completerwrapper(ctxt):
cass = ctxt.get_binding('cassandra_conn', None)
if cass is None:
return ()
return f(ctxt, cass)
completerwrapper.func_name = 'completerwrapper_on_' + f.func_name
self.register_completer(completerwrapper, rulename, symname)
return completerwrapper
return registrator
def explain_completion(self, rulename, symname, explanation=None):
if explanation is None:
explanation = '<%s>' % (symname,)
@self.completer_for(rulename, symname)
def explainer(ctxt, cass):
return [Hint(explanation)]
return explainer
def cql_massage_tokens(self, toklist):
curstmt = []
output = []
term_on_nl = False
for t in toklist:
if t[0] == 'endline':
if term_on_nl:
t = ('endtoken',) + t[1:]
else:
# don't put any 'endline' tokens in output
continue
# Convert all unicode tokens to ascii, where possible. This
# helps avoid problems with performing unicode-incompatible
# operations on tokens (like .lower()). See CASSANDRA-9083
# for one example of this.
str_token = t[1]
if isinstance(str_token, unicode):
try:
str_token = str_token.encode('ascii')
t = (t[0], str_token) + t[2:]
except UnicodeEncodeError:
pass
curstmt.append(t)
if t[0] == 'endtoken':
term_on_nl = False
output.extend(curstmt)
curstmt = []
else:
if len(curstmt) == 1:
# first token in statement; command word
cmd = t[1].lower()
term_on_nl = bool(cmd in self.commands_end_with_newline)
output.extend(curstmt)
return output
def cql_parse(self, text, startsymbol='Start'):
tokens = self.lex(text)
tokens = self.cql_massage_tokens(tokens)
return self.parse(startsymbol, tokens, init_bindings={'*SRC*': text})
def cql_whole_parse_tokens(self, toklist, srcstr=None, startsymbol='Start'):
return self.whole_match(startsymbol, toklist, srcstr=srcstr)
def cql_split_statements(self, text):
tokens = self.lex(text)
tokens = self.cql_massage_tokens(tokens)
stmts = util.split_list(tokens, lambda t: t[0] == 'endtoken')
output = []
in_batch = False
in_pg_string = len([st for st in tokens if len(st) > 0 and st[0] == 'unclosedPgString']) == 1
for stmt in stmts:
if in_batch:
output[-1].extend(stmt)
else:
output.append(stmt)
if len(stmt) > 2:
if stmt[-3][1].upper() == 'APPLY':
in_batch = False
elif stmt[0][1].upper() == 'BEGIN':
in_batch = True
return output, in_batch or in_pg_string
def cql_complete_single(self, text, partial, init_bindings={}, ignore_case=True,
startsymbol='Start'):
tokens = (self.cql_split_statements(text)[0] or [[]])[-1]
bindings = init_bindings.copy()
# handle some different completion scenarios- in particular, completing
# inside a string literal
prefix = None
dequoter = util.identity
lasttype = None
if tokens:
lasttype = tokens[-1][0]
if lasttype == 'unclosedString':
prefix = self.token_dequote(tokens[-1])
tokens = tokens[:-1]
partial = prefix + partial
dequoter = self.dequote_value
requoter = self.escape_value
elif lasttype == 'unclosedName':
prefix = self.token_dequote(tokens[-1])
tokens = tokens[:-1]
partial = prefix + partial
dequoter = self.dequote_name
requoter = self.escape_name
elif lasttype == 'unclosedComment':
return []
bindings['partial'] = partial
bindings['*LASTTYPE*'] = lasttype
bindings['*SRC*'] = text
# find completions for the position
completions = self.complete(startsymbol, tokens, bindings)
hints, strcompletes = util.list_bifilter(pylexotron.is_hint, completions)
# it's possible to get a newline token from completion; of course, we
# don't want to actually have that be a candidate, we just want to hint
if '\n' in strcompletes:
strcompletes.remove('\n')
if partial == '':
hints.append(Hint('<enter>'))
# find matches with the partial word under completion
if ignore_case:
partial = partial.lower()
f = lambda s: s and dequoter(s).lower().startswith(partial)
else:
f = lambda s: s and dequoter(s).startswith(partial)
candidates = filter(f, strcompletes)
if prefix is not None:
# dequote, re-escape, strip quotes: gets us the right quoted text
# for completion. the opening quote is already there on the command
# line and not part of the word under completion, and readline
# fills in the closing quote for us.
candidates = [requoter(dequoter(c))[len(prefix) + 1:-1] for c in candidates]
# the above process can result in an empty string; this doesn't help for
# completions
candidates = filter(None, candidates)
# prefix a space when desirable for pleasant cql formatting
if tokens:
newcandidates = []
for c in candidates:
if self.want_space_between(tokens[-1], c) \
and prefix is None \
and not text[-1].isspace() \
and not c[0].isspace():
c = ' ' + c
newcandidates.append(c)
candidates = newcandidates
# append a space for single, complete identifiers
if len(candidates) == 1 and candidates[0][-1].isalnum() \
and lasttype != 'unclosedString' \
and lasttype != 'unclosedName':
candidates[0] += ' '
return candidates, hints
@staticmethod
def want_space_between(tok, following):
if following in (',', ')', ':'):
return False
if tok[0] == 'op' and tok[1] in (',', ')', '='):
return True
if tok[0] == 'stringLiteral' and following[0] != ';':
return True
if tok[0] == 'star' and following[0] != ')':
return True
if tok[0] == 'endtoken':
return True
if tok[1][-1].isalnum() and following[0] != ',':
return True
return False
def cql_complete(self, text, partial, cassandra_conn=None, ignore_case=True, debug=False,
startsymbol='Start'):
init_bindings = {'cassandra_conn': cassandra_conn}
if debug:
init_bindings['*DEBUG*'] = True
print "cql_complete(%r, partial=%r)" % (text, partial)
completions, hints = self.cql_complete_single(text, partial, init_bindings,
startsymbol=startsymbol)
if hints:
hints = [h.text for h in hints]
hints.append('')
if len(completions) == 1 and len(hints) == 0:
c = completions[0]
if debug:
print "** Got one completion: %r. Checking for further matches...\n" % (c,)
if not c.isspace():
new_c = self.cql_complete_multiple(text, c, init_bindings, startsymbol=startsymbol)
completions = [new_c]
if debug:
print "** New list of completions: %r" % (completions,)
return hints + completions
def cql_complete_multiple(self, text, first, init_bindings, startsymbol='Start'):
debug = init_bindings.get('*DEBUG*', False)
try:
completions, hints = self.cql_complete_single(text + first, '', init_bindings,
startsymbol=startsymbol)
except Exception:
if debug:
print "** completion expansion had a problem:"
traceback.print_exc()
return first
if hints:
if not first[-1].isspace():
first += ' '
if debug:
print "** completion expansion found hints: %r" % (hints,)
return first
if len(completions) == 1 and completions[0] != '':
if debug:
print "** Got another completion: %r." % (completions[0],)
if completions[0][0] in (',', ')', ':') and first[-1] == ' ':
first = first[:-1]
first += completions[0]
else:
common_prefix = util.find_common_prefix(completions)
if common_prefix == '':
return first
if common_prefix[0] in (',', ')', ':') and first[-1] == ' ':
first = first[:-1]
if debug:
print "** Got a partial completion: %r." % (common_prefix,)
return first + common_prefix
if debug:
print "** New total completion: %r. Checking for further matches...\n" % (first,)
return self.cql_complete_multiple(text, first, init_bindings, startsymbol=startsymbol)
@staticmethod
def cql_extract_orig(toklist, srcstr):
# low end of span for first token, to high end of span for last token
return srcstr[toklist[0][2][0]:toklist[-1][2][1]]
@staticmethod
def token_dequote(tok):
if tok[0] == 'unclosedName':
# strip one quote
return tok[1][1:].replace('""', '"')
if tok[0] == 'quotedStringLiteral':
# strip quotes
return tok[1][1:-1].replace("''", "'")
if tok[0] == 'unclosedString':
# strip one quote
return tok[1][1:].replace("''", "'")
if tok[0] == 'unclosedComment':
return ''
return tok[1]
@staticmethod
def token_is_word(tok):
return tok[0] == 'identifier'
| apache-2.0 |
ehudmagal/robotqcapp | boto/vpc/vpc.py | 25 | 1944 | # Copyright (c) 2009-2010 Mitch Garnaat http://garnaat.org/
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish, dis-
# tribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the fol-
# lowing conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABIL-
# ITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
# SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
"""
Represents a Virtual Private Cloud.
"""
from boto.ec2.ec2object import TaggedEC2Object
class VPC(TaggedEC2Object):
def __init__(self, connection=None):
TaggedEC2Object.__init__(self, connection)
self.id = None
self.dhcp_options_id = None
self.state = None
self.cidr_block = None
def __repr__(self):
return 'VPC:%s' % self.id
def endElement(self, name, value, connection):
if name == 'vpcId':
self.id = value
elif name == 'dhcpOptionsId':
self.dhcp_options_id = value
elif name == 'state':
self.state = value
elif name == 'cidrBlock':
self.cidr_block = value
else:
setattr(self, name, value)
def delete(self):
return self.connection.delete_vpc(self.id)
| bsd-3-clause |
belmiromoreira/nova | nova/tests/unit/api/openstack/compute/contrib/test_extended_server_attributes.py | 26 | 9040 | # Copyright 2011 OpenStack Foundation
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from oslo_config import cfg
from oslo_serialization import jsonutils
import webob
from nova.api.openstack import wsgi as os_wsgi
from nova import compute
from nova import db
from nova import exception
from nova import objects
from nova.objects import instance as instance_obj
from nova import test
from nova.tests.unit.api.openstack import fakes
NAME_FMT = cfg.CONF.instance_name_template
UUID1 = '00000000-0000-0000-0000-000000000001'
UUID2 = '00000000-0000-0000-0000-000000000002'
UUID3 = '00000000-0000-0000-0000-000000000003'
UUID4 = '00000000-0000-0000-0000-000000000004'
UUID5 = '00000000-0000-0000-0000-000000000005'
def fake_compute_get(*args, **kwargs):
fields = instance_obj.INSTANCE_DEFAULT_FIELDS
return objects.Instance._from_db_object(
args[1], objects.Instance(),
fakes.stub_instance(1, uuid=UUID3, host="host-fake",
node="node-fake",
reservation_id="r-1", launch_index=0,
kernel_id=UUID4, ramdisk_id=UUID5,
display_name="hostname-1",
root_device_name="/dev/vda",
user_data="userdata"), fields)
def fake_compute_get_all(*args, **kwargs):
db_list = [
fakes.stub_instance(1, uuid=UUID1, host="host-1", node="node-1",
reservation_id="r-1", launch_index=0,
kernel_id=UUID4, ramdisk_id=UUID5,
display_name="hostname-1",
root_device_name="/dev/vda",
user_data="userdata"),
fakes.stub_instance(2, uuid=UUID2, host="host-2", node="node-2",
reservation_id="r-2", launch_index=1,
kernel_id=UUID4, ramdisk_id=UUID5,
display_name="hostname-2",
root_device_name="/dev/vda",
user_data="userdata")
]
fields = instance_obj.INSTANCE_DEFAULT_FIELDS
return instance_obj._make_instance_list(args[1],
objects.InstanceList(),
db_list, fields)
class ExtendedServerAttributesTestV21(test.TestCase):
content_type = 'application/json'
prefix = 'OS-EXT-SRV-ATTR:'
fake_url = '/v2/fake'
wsgi_api_version = os_wsgi.DEFAULT_API_VERSION
def setUp(self):
super(ExtendedServerAttributesTestV21, self).setUp()
fakes.stub_out_nw_api(self.stubs)
self.stubs.Set(compute.api.API, 'get', fake_compute_get)
self.stubs.Set(compute.api.API, 'get_all', fake_compute_get_all)
self.stubs.Set(db, 'instance_get_by_uuid', fake_compute_get)
def _make_request(self, url):
req = fakes.HTTPRequest.blank(url)
req.headers['Accept'] = self.content_type
req.headers = {os_wsgi.API_VERSION_REQUEST_HEADER:
self.wsgi_api_version}
res = req.get_response(
fakes.wsgi_app_v21(init_only=('servers',
'os-extended-server-attributes')))
return res
def _get_server(self, body):
return jsonutils.loads(body).get('server')
def _get_servers(self, body):
return jsonutils.loads(body).get('servers')
def assertServerAttributes(self, server, host, node, instance_name):
self.assertEqual(server.get('%shost' % self.prefix), host)
self.assertEqual(server.get('%sinstance_name' % self.prefix),
instance_name)
self.assertEqual(server.get('%shypervisor_hostname' % self.prefix),
node)
def test_show(self):
url = self.fake_url + '/servers/%s' % UUID3
res = self._make_request(url)
self.assertEqual(res.status_int, 200)
self.assertServerAttributes(self._get_server(res.body),
host='host-fake',
node='node-fake',
instance_name=NAME_FMT % 1)
def test_detail(self):
url = self.fake_url + '/servers/detail'
res = self._make_request(url)
self.assertEqual(res.status_int, 200)
for i, server in enumerate(self._get_servers(res.body)):
self.assertServerAttributes(server,
host='host-%s' % (i + 1),
node='node-%s' % (i + 1),
instance_name=NAME_FMT % (i + 1))
def test_no_instance_passthrough_404(self):
def fake_compute_get(*args, **kwargs):
raise exception.InstanceNotFound(instance_id='fake')
self.stubs.Set(compute.api.API, 'get', fake_compute_get)
url = self.fake_url + '/servers/70f6db34-de8d-4fbd-aafb-4065bdfa6115'
res = self._make_request(url)
self.assertEqual(res.status_int, 404)
class ExtendedServerAttributesTestV2(ExtendedServerAttributesTestV21):
def setUp(self):
super(ExtendedServerAttributesTestV2, self).setUp()
self.flags(
osapi_compute_extension=[
'nova.api.openstack.compute.contrib.select_extensions'],
osapi_compute_ext_list=['Extended_server_attributes'])
def _make_request(self, url):
req = webob.Request.blank(url)
req.headers['Accept'] = self.content_type
res = req.get_response(fakes.wsgi_app(init_only=('servers',)))
return res
class ExtendedServerAttributesTestV23(ExtendedServerAttributesTestV21):
wsgi_api_version = '2.3'
def assertServerAttributes(self, server, host, node, instance_name,
reservation_id, launch_index, kernel_id,
ramdisk_id, hostname, root_device_name,
user_data):
super(ExtendedServerAttributesTestV23, self).assertServerAttributes(
server, host, node, instance_name)
self.assertEqual(server.get('%sreservation_id' % self.prefix),
reservation_id)
self.assertEqual(server.get('%slaunch_index' % self.prefix),
launch_index)
self.assertEqual(server.get('%skernel_id' % self.prefix),
kernel_id)
self.assertEqual(server.get('%sramdisk_id' % self.prefix),
ramdisk_id)
self.assertEqual(server.get('%shostname' % self.prefix),
hostname)
self.assertEqual(server.get('%sroot_device_name' % self.prefix),
root_device_name)
self.assertEqual(server.get('%suser_data' % self.prefix),
user_data)
def test_show(self):
url = self.fake_url + '/servers/%s' % UUID3
res = self._make_request(url)
self.assertEqual(res.status_int, 200)
self.assertServerAttributes(self._get_server(res.body),
host='host-fake',
node='node-fake',
instance_name=NAME_FMT % 1,
reservation_id="r-1",
launch_index=0,
kernel_id=UUID4,
ramdisk_id=UUID5,
hostname="hostname-1",
root_device_name="/dev/vda",
user_data="userdata")
def test_detail(self):
url = self.fake_url + '/servers/detail'
res = self._make_request(url)
self.assertEqual(res.status_int, 200)
for i, server in enumerate(self._get_servers(res.body)):
self.assertServerAttributes(server,
host='host-%s' % (i + 1),
node='node-%s' % (i + 1),
instance_name=NAME_FMT % (i + 1),
reservation_id="r-%s" % (i + 1),
launch_index=i,
kernel_id=UUID4,
ramdisk_id=UUID5,
hostname="hostname-%s" % (i + 1),
root_device_name="/dev/vda",
user_data="userdata")
| apache-2.0 |
ingydotnet/crockford-py | package/info.py | 1 | 1307 | def get():
info = {}
info.update(
{ 'author': 'Ingy dot Net',
'author_email': 'ingy@ingy.net',
'classifiers': [ 'Development Status :: 2 - Pre-Alpha',
'License :: OSI Approved :: BSD License',
'Programming Language :: Python',
'Intended Audience :: Developers'],
'description': "Encode and decode using Douglas Crockford's base32 encoding scheme:",
'long_description': 'crockford - Encode and Decode using the Crockford Base32 scheme\n---------------------------------------------------------------\n\nInstallation\n------------\n\nUse::\n\n > sudo pip install crockford\n\nor::\n\n > sudo easy install crockford\n\nor::\n\n > git clone git://github.com/ingydotnet/crockford-py.git\n > cd crockford-py\n > sudo make install\n\nUsage\n-----\n\n import crockford\n\n base32 = crockford.b32encode(string)\n string = crockford.b32decode(base32)\n\nAuthors\n-------\n\n* Ingy dot Net <ingy@ingy.net>\n\nCopyright\n---------\n\ncrockford is Copyright (c) 2011, Ingy dot Net\n\ncrockford is licensed under the New BSD License. See the LICENSE file.\n',
'name': 'crockford',
'packages': ['crockford'],
'scripts': [],
'url': 'http://github.com/ingydotnet/crockford-py/',
'version': '0.0.2'}
)
return info
| bsd-2-clause |
Zouyiran/ryu | ryu/ofproto/ofproto_common.py | 36 | 1225 | # Copyright (C) 2011, 2012 Nippon Telegraph and Telephone Corporation.
# Copyright (C) 2011 Isaku Yamahata <yamahata at valinux co jp>
#
# 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 struct import calcsize
OFP_HEADER_PACK_STR = '!BBHI'
OFP_HEADER_SIZE = 8
assert calcsize(OFP_HEADER_PACK_STR) == OFP_HEADER_SIZE
# note: while IANA assigned port number for OpenFlow is 6653,
# 6633 is (still) the defacto standard.
OFP_TCP_PORT = 6633
OFP_SSL_PORT = 6633
# Vendor/Experimenter IDs
# https://rs.opennetworking.org/wiki/display/PUBLIC/ONF+Registry
NX_EXPERIMENTER_ID = 0x00002320 # Nicira
BSN_EXPERIMENTER_ID = 0x005c16c7 # Big Switch Networks
ONF_EXPERIMENTER_ID = 0x4f4e4600 # OpenFlow Extensions for 1.3.X Pack 1
| apache-2.0 |
xbmc/xbmc-antiquated | xbmc/lib/libPython/Python/Lib/test/test_charmapcodec.py | 24 | 1593 | """ Python character mapping codec test
This uses the test codec in testcodec.py and thus also tests the
encodings package lookup scheme.
Written by Marc-Andre Lemburg (mal@lemburg.com).
(c) Copyright 2000 Guido van Rossum.
"""#"
import test.test_support, unittest
# test codec's full path name (see test/testcodec.py)
codecname = 'test.testcodec'
class CharmapCodecTest(unittest.TestCase):
def test_constructorx(self):
self.assertEquals(unicode('abc', codecname), u'abc')
self.assertEquals(unicode('xdef', codecname), u'abcdef')
self.assertEquals(unicode('defx', codecname), u'defabc')
self.assertEquals(unicode('dxf', codecname), u'dabcf')
self.assertEquals(unicode('dxfx', codecname), u'dabcfabc')
def test_encodex(self):
self.assertEquals(u'abc'.encode(codecname), 'abc')
self.assertEquals(u'xdef'.encode(codecname), 'abcdef')
self.assertEquals(u'defx'.encode(codecname), 'defabc')
self.assertEquals(u'dxf'.encode(codecname), 'dabcf')
self.assertEquals(u'dxfx'.encode(codecname), 'dabcfabc')
def test_constructory(self):
self.assertEquals(unicode('ydef', codecname), u'def')
self.assertEquals(unicode('defy', codecname), u'def')
self.assertEquals(unicode('dyf', codecname), u'df')
self.assertEquals(unicode('dyfy', codecname), u'df')
def test_maptoundefined(self):
self.assertRaises(UnicodeError, unicode, 'abc\001', codecname)
def test_main():
test.test_support.run_unittest(CharmapCodecTest)
if __name__ == "__main__":
test_main()
| gpl-2.0 |
nhicher/ansible | test/units/modules/network/f5/test_bigip_vcmp_guest.py | 4 | 5825 | # -*- coding: utf-8 -*-
#
# Copyright (c) 2017 F5 Networks Inc.
# GNU General Public License v3.0 (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import os
import json
import pytest
import sys
from nose.plugins.skip import SkipTest
if sys.version_info < (2, 7):
raise SkipTest("F5 Ansible modules require Python >= 2.7")
from units.compat import unittest
from units.compat.mock import Mock
from units.compat.mock import patch
from ansible.module_utils.basic import AnsibleModule
try:
from library.modules.bigip_vcmp_guest import Parameters
from library.modules.bigip_vcmp_guest import ModuleManager
from library.modules.bigip_vcmp_guest import ArgumentSpec
from library.module_utils.network.f5.common import F5ModuleError
from library.module_utils.network.f5.common import iControlUnexpectedHTTPError
from test.unit.modules.utils import set_module_args
except ImportError:
try:
from ansible.modules.network.f5.bigip_vcmp_guest import Parameters
from ansible.modules.network.f5.bigip_vcmp_guest import ModuleManager
from ansible.modules.network.f5.bigip_vcmp_guest import ArgumentSpec
from ansible.module_utils.network.f5.common import F5ModuleError
from ansible.module_utils.network.f5.common import iControlUnexpectedHTTPError
from units.modules.utils import set_module_args
except ImportError:
raise SkipTest("F5 Ansible modules require the f5-sdk Python library")
fixture_path = os.path.join(os.path.dirname(__file__), 'fixtures')
fixture_data = {}
def load_fixture(name):
path = os.path.join(fixture_path, name)
if path in fixture_data:
return fixture_data[path]
with open(path) as f:
data = f.read()
try:
data = json.loads(data)
except Exception:
pass
fixture_data[path] = data
return data
class TestParameters(unittest.TestCase):
def test_module_parameters(self):
args = dict(
initial_image='BIGIP-12.1.0.1.0.1447-HF1.iso',
mgmt_network='bridged',
mgmt_address='1.2.3.4/24',
vlans=[
'vlan1',
'vlan2'
]
)
p = Parameters(params=args)
assert p.initial_image == 'BIGIP-12.1.0.1.0.1447-HF1.iso'
assert p.mgmt_network == 'bridged'
def test_module_parameters_mgmt_bridged_without_subnet(self):
args = dict(
mgmt_network='bridged',
mgmt_address='1.2.3.4'
)
p = Parameters(params=args)
assert p.mgmt_network == 'bridged'
assert p.mgmt_address == '1.2.3.4/32'
def test_module_parameters_mgmt_address_cidr(self):
args = dict(
mgmt_network='bridged',
mgmt_address='1.2.3.4/24'
)
p = Parameters(params=args)
assert p.mgmt_network == 'bridged'
assert p.mgmt_address == '1.2.3.4/24'
def test_module_parameters_mgmt_address_subnet(self):
args = dict(
mgmt_network='bridged',
mgmt_address='1.2.3.4/255.255.255.0'
)
p = Parameters(params=args)
assert p.mgmt_network == 'bridged'
assert p.mgmt_address == '1.2.3.4/24'
def test_module_parameters_mgmt_route(self):
args = dict(
mgmt_route='1.2.3.4'
)
p = Parameters(params=args)
assert p.mgmt_route == '1.2.3.4'
def test_module_parameters_vcmp_software_image_facts(self):
# vCMP images may include a forward slash in their names. This is probably
# related to the slots on the system, but it is not a valid value to specify
# that slot when providing an initial image
args = dict(
initial_image='BIGIP-12.1.0.1.0.1447-HF1.iso/1',
)
p = Parameters(params=args)
assert p.initial_image == 'BIGIP-12.1.0.1.0.1447-HF1.iso/1'
def test_api_parameters(self):
args = dict(
initialImage="BIGIP-tmos-tier2-13.1.0.0.0.931.iso",
managementGw="2.2.2.2",
managementIp="1.1.1.1/24",
managementNetwork="bridged",
state="deployed",
vlans=[
"/Common/vlan1",
"/Common/vlan2"
]
)
p = Parameters(params=args)
assert p.initial_image == 'BIGIP-tmos-tier2-13.1.0.0.0.931.iso'
assert p.mgmt_route == '2.2.2.2'
assert p.mgmt_address == '1.1.1.1/24'
assert '/Common/vlan1' in p.vlans
assert '/Common/vlan2' in p.vlans
class TestManager(unittest.TestCase):
def setUp(self):
self.spec = ArgumentSpec()
self.patcher1 = patch('time.sleep')
self.patcher1.start()
def tearDown(self):
self.patcher1.stop()
def test_create_vlan(self, *args):
set_module_args(dict(
name="guest1",
mgmt_network="bridged",
mgmt_address="10.10.10.10/24",
initial_image="BIGIP-13.1.0.0.0.931.iso",
server='localhost',
password='password',
user='admin'
))
module = AnsibleModule(
argument_spec=self.spec.argument_spec,
supports_check_mode=self.spec.supports_check_mode
)
# Override methods to force specific logic in the module to happen
mm = ModuleManager(module=module)
mm.create_on_device = Mock(return_value=True)
mm.exists = Mock(return_value=False)
mm.is_deployed = Mock(side_effect=[False, True, True, True, True])
mm.deploy_on_device = Mock(return_value=True)
results = mm.exec_module()
assert results['changed'] is True
assert results['name'] == 'guest1'
| gpl-3.0 |
harshaneelhg/scikit-learn | sklearn/utils/tests/test_murmurhash.py | 261 | 2836 | # Author: Olivier Grisel <olivier.grisel@ensta.org>
#
# License: BSD 3 clause
import numpy as np
from sklearn.externals.six import b, u
from sklearn.utils.murmurhash import murmurhash3_32
from numpy.testing import assert_array_almost_equal
from numpy.testing import assert_array_equal
from nose.tools import assert_equal, assert_true
def test_mmhash3_int():
assert_equal(murmurhash3_32(3), 847579505)
assert_equal(murmurhash3_32(3, seed=0), 847579505)
assert_equal(murmurhash3_32(3, seed=42), -1823081949)
assert_equal(murmurhash3_32(3, positive=False), 847579505)
assert_equal(murmurhash3_32(3, seed=0, positive=False), 847579505)
assert_equal(murmurhash3_32(3, seed=42, positive=False), -1823081949)
assert_equal(murmurhash3_32(3, positive=True), 847579505)
assert_equal(murmurhash3_32(3, seed=0, positive=True), 847579505)
assert_equal(murmurhash3_32(3, seed=42, positive=True), 2471885347)
def test_mmhash3_int_array():
rng = np.random.RandomState(42)
keys = rng.randint(-5342534, 345345, size=3 * 2 * 1).astype(np.int32)
keys = keys.reshape((3, 2, 1))
for seed in [0, 42]:
expected = np.array([murmurhash3_32(int(k), seed)
for k in keys.flat])
expected = expected.reshape(keys.shape)
assert_array_equal(murmurhash3_32(keys, seed), expected)
for seed in [0, 42]:
expected = np.array([murmurhash3_32(k, seed, positive=True)
for k in keys.flat])
expected = expected.reshape(keys.shape)
assert_array_equal(murmurhash3_32(keys, seed, positive=True),
expected)
def test_mmhash3_bytes():
assert_equal(murmurhash3_32(b('foo'), 0), -156908512)
assert_equal(murmurhash3_32(b('foo'), 42), -1322301282)
assert_equal(murmurhash3_32(b('foo'), 0, positive=True), 4138058784)
assert_equal(murmurhash3_32(b('foo'), 42, positive=True), 2972666014)
def test_mmhash3_unicode():
assert_equal(murmurhash3_32(u('foo'), 0), -156908512)
assert_equal(murmurhash3_32(u('foo'), 42), -1322301282)
assert_equal(murmurhash3_32(u('foo'), 0, positive=True), 4138058784)
assert_equal(murmurhash3_32(u('foo'), 42, positive=True), 2972666014)
def test_no_collision_on_byte_range():
previous_hashes = set()
for i in range(100):
h = murmurhash3_32(' ' * i, 0)
assert_true(h not in previous_hashes,
"Found collision on growing empty string")
def test_uniform_distribution():
n_bins, n_samples = 10, 100000
bins = np.zeros(n_bins, dtype=np.float)
for i in range(n_samples):
bins[murmurhash3_32(i, positive=True) % n_bins] += 1
means = bins / n_samples
expected = np.ones(n_bins) / n_bins
assert_array_almost_equal(means / expected, np.ones(n_bins), 2)
| bsd-3-clause |
40223202/test2 | static/Brython3.1.1-20150328-091302/Lib/multiprocessing/dummy/__init__.py | 693 | 4380 | #
# Support for the API of the multiprocessing package using threads
#
# multiprocessing/dummy/__init__.py
#
# Copyright (c) 2006-2008, R Oudkerk
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# 1. Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# 3. Neither the name of author nor the names of any contributors may be
# used to endorse or promote products derived from this software
# without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR 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.
#
__all__ = [
'Process', 'current_process', 'active_children', 'freeze_support',
'Lock', 'RLock', 'Semaphore', 'BoundedSemaphore', 'Condition',
'Event', 'Barrier', 'Queue', 'Manager', 'Pipe', 'Pool', 'JoinableQueue'
]
#
# Imports
#
import threading
import sys
import weakref
#brython fix me
#import array
from multiprocessing.dummy.connection import Pipe
from threading import Lock, RLock, Semaphore, BoundedSemaphore
from threading import Event, Condition, Barrier
from queue import Queue
#
#
#
class DummyProcess(threading.Thread):
def __init__(self, group=None, target=None, name=None, args=(), kwargs={}):
threading.Thread.__init__(self, group, target, name, args, kwargs)
self._pid = None
self._children = weakref.WeakKeyDictionary()
self._start_called = False
self._parent = current_process()
def start(self):
assert self._parent is current_process()
self._start_called = True
if hasattr(self._parent, '_children'):
self._parent._children[self] = None
threading.Thread.start(self)
@property
def exitcode(self):
if self._start_called and not self.is_alive():
return 0
else:
return None
#
#
#
Process = DummyProcess
current_process = threading.current_thread
current_process()._children = weakref.WeakKeyDictionary()
def active_children():
children = current_process()._children
for p in list(children):
if not p.is_alive():
children.pop(p, None)
return list(children)
def freeze_support():
pass
#
#
#
class Namespace(object):
def __init__(self, **kwds):
self.__dict__.update(kwds)
def __repr__(self):
items = list(self.__dict__.items())
temp = []
for name, value in items:
if not name.startswith('_'):
temp.append('%s=%r' % (name, value))
temp.sort()
return 'Namespace(%s)' % str.join(', ', temp)
dict = dict
list = list
#brython fix me
#def Array(typecode, sequence, lock=True):
# return array.array(typecode, sequence)
class Value(object):
def __init__(self, typecode, value, lock=True):
self._typecode = typecode
self._value = value
def _get(self):
return self._value
def _set(self, value):
self._value = value
value = property(_get, _set)
def __repr__(self):
return '<%r(%r, %r)>'%(type(self).__name__,self._typecode,self._value)
def Manager():
return sys.modules[__name__]
def shutdown():
pass
def Pool(processes=None, initializer=None, initargs=()):
from multiprocessing.pool import ThreadPool
return ThreadPool(processes, initializer, initargs)
JoinableQueue = Queue
| gpl-3.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.