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
DDEFISHER/servo
tests/wpt/web-platform-tests/tools/pytest/_pytest/vendored_packages/pluggy.py
178
29861
""" PluginManager, basic initialization and tracing. pluggy is the cristallized core of plugin management as used by some 150 plugins for pytest. Pluggy uses semantic versioning. Breaking changes are only foreseen for Major releases (incremented X in "X.Y.Z"). If you want to use pluggy in your project you should thus use a dependency restriction like "pluggy>=0.1.0,<1.0" to avoid surprises. pluggy is concerned with hook specification, hook implementations and hook calling. For any given hook specification a hook call invokes up to N implementations. A hook implementation can influence its position and type of execution: if attributed "tryfirst" or "trylast" it will be tried to execute first or last. However, if attributed "hookwrapper" an implementation can wrap all calls to non-hookwrapper implementations. A hookwrapper can thus execute some code ahead and after the execution of other hooks. Hook specification is done by way of a regular python function where both the function name and the names of all its arguments are significant. Each hook implementation function is verified against the original specification function, including the names of all its arguments. To allow for hook specifications to evolve over the livetime of a project, hook implementations can accept less arguments. One can thus add new arguments and semantics to a hook specification by adding another argument typically without breaking existing hook implementations. The chosen approach is meant to let a hook designer think carefuly about which objects are needed by an extension writer. By contrast, subclass-based extension mechanisms often expose a lot more state and behaviour than needed, thus restricting future developments. Pluggy currently consists of functionality for: - a way to register new hook specifications. Without a hook specification no hook calling can be performed. - a registry of plugins which contain hook implementation functions. It is possible to register plugins for which a hook specification is not yet known and validate all hooks when the system is in a more referentially consistent state. Setting an "optionalhook" attribution to a hook implementation will avoid PluginValidationError's if a specification is missing. This allows to have optional integration between plugins. - a "hook" relay object from which you can launch 1:N calls to registered hook implementation functions - a mechanism for ordering hook implementation functions - mechanisms for two different type of 1:N calls: "firstresult" for when the call should stop when the first implementation returns a non-None result. And the other (default) way of guaranteeing that all hook implementations will be called and their non-None result collected. - mechanisms for "historic" extension points such that all newly registered functions will receive all hook calls that happened before their registration. - a mechanism for discovering plugin objects which are based on setuptools based entry points. - a simple tracing mechanism, including tracing of plugin calls and their arguments. """ import sys import inspect __version__ = '0.3.1' __all__ = ["PluginManager", "PluginValidationError", "HookspecMarker", "HookimplMarker"] _py3 = sys.version_info > (3, 0) class HookspecMarker: """ Decorator helper class for marking functions as hook specifications. You can instantiate it with a project_name to get a decorator. Calling PluginManager.add_hookspecs later will discover all marked functions if the PluginManager uses the same project_name. """ def __init__(self, project_name): self.project_name = project_name def __call__(self, function=None, firstresult=False, historic=False): """ if passed a function, directly sets attributes on the function which will make it discoverable to add_hookspecs(). If passed no function, returns a decorator which can be applied to a function later using the attributes supplied. If firstresult is True the 1:N hook call (N being the number of registered hook implementation functions) will stop at I<=N when the I'th function returns a non-None result. If historic is True calls to a hook will be memorized and replayed on later registered plugins. """ def setattr_hookspec_opts(func): if historic and firstresult: raise ValueError("cannot have a historic firstresult hook") setattr(func, self.project_name + "_spec", dict(firstresult=firstresult, historic=historic)) return func if function is not None: return setattr_hookspec_opts(function) else: return setattr_hookspec_opts class HookimplMarker: """ Decorator helper class for marking functions as hook implementations. You can instantiate with a project_name to get a decorator. Calling PluginManager.register later will discover all marked functions if the PluginManager uses the same project_name. """ def __init__(self, project_name): self.project_name = project_name def __call__(self, function=None, hookwrapper=False, optionalhook=False, tryfirst=False, trylast=False): """ if passed a function, directly sets attributes on the function which will make it discoverable to register(). If passed no function, returns a decorator which can be applied to a function later using the attributes supplied. If optionalhook is True a missing matching hook specification will not result in an error (by default it is an error if no matching spec is found). If tryfirst is True this hook implementation will run as early as possible in the chain of N hook implementations for a specfication. If trylast is True this hook implementation will run as late as possible in the chain of N hook implementations. If hookwrapper is True the hook implementations needs to execute exactly one "yield". The code before the yield is run early before any non-hookwrapper function is run. The code after the yield is run after all non-hookwrapper function have run. The yield receives an ``_CallOutcome`` object representing the exception or result outcome of the inner calls (including other hookwrapper calls). """ def setattr_hookimpl_opts(func): setattr(func, self.project_name + "_impl", dict(hookwrapper=hookwrapper, optionalhook=optionalhook, tryfirst=tryfirst, trylast=trylast)) return func if function is None: return setattr_hookimpl_opts else: return setattr_hookimpl_opts(function) def normalize_hookimpl_opts(opts): opts.setdefault("tryfirst", False) opts.setdefault("trylast", False) opts.setdefault("hookwrapper", False) opts.setdefault("optionalhook", False) class _TagTracer: def __init__(self): self._tag2proc = {} self.writer = None self.indent = 0 def get(self, name): return _TagTracerSub(self, (name,)) def format_message(self, tags, args): if isinstance(args[-1], dict): extra = args[-1] args = args[:-1] else: extra = {} content = " ".join(map(str, args)) indent = " " * self.indent lines = [ "%s%s [%s]\n" % (indent, content, ":".join(tags)) ] for name, value in extra.items(): lines.append("%s %s: %s\n" % (indent, name, value)) return lines def processmessage(self, tags, args): if self.writer is not None and args: lines = self.format_message(tags, args) self.writer(''.join(lines)) try: self._tag2proc[tags](tags, args) except KeyError: pass def setwriter(self, writer): self.writer = writer def setprocessor(self, tags, processor): if isinstance(tags, str): tags = tuple(tags.split(":")) else: assert isinstance(tags, tuple) self._tag2proc[tags] = processor class _TagTracerSub: def __init__(self, root, tags): self.root = root self.tags = tags def __call__(self, *args): self.root.processmessage(self.tags, args) def setmyprocessor(self, processor): self.root.setprocessor(self.tags, processor) def get(self, name): return self.__class__(self.root, self.tags + (name,)) def _raise_wrapfail(wrap_controller, msg): co = wrap_controller.gi_code raise RuntimeError("wrap_controller at %r %s:%d %s" % (co.co_name, co.co_filename, co.co_firstlineno, msg)) def _wrapped_call(wrap_controller, func): """ Wrap calling to a function with a generator which needs to yield exactly once. The yield point will trigger calling the wrapped function and return its _CallOutcome to the yield point. The generator then needs to finish (raise StopIteration) in order for the wrapped call to complete. """ try: next(wrap_controller) # first yield except StopIteration: _raise_wrapfail(wrap_controller, "did not yield") call_outcome = _CallOutcome(func) try: wrap_controller.send(call_outcome) _raise_wrapfail(wrap_controller, "has second yield") except StopIteration: pass return call_outcome.get_result() class _CallOutcome: """ Outcome of a function call, either an exception or a proper result. Calling the ``get_result`` method will return the result or reraise the exception raised when the function was called. """ excinfo = None def __init__(self, func): try: self.result = func() except BaseException: self.excinfo = sys.exc_info() def force_result(self, result): self.result = result self.excinfo = None def get_result(self): if self.excinfo is None: return self.result else: ex = self.excinfo if _py3: raise ex[1].with_traceback(ex[2]) _reraise(*ex) # noqa if not _py3: exec(""" def _reraise(cls, val, tb): raise cls, val, tb """) class _TracedHookExecution: def __init__(self, pluginmanager, before, after): self.pluginmanager = pluginmanager self.before = before self.after = after self.oldcall = pluginmanager._inner_hookexec assert not isinstance(self.oldcall, _TracedHookExecution) self.pluginmanager._inner_hookexec = self def __call__(self, hook, hook_impls, kwargs): self.before(hook.name, hook_impls, kwargs) outcome = _CallOutcome(lambda: self.oldcall(hook, hook_impls, kwargs)) self.after(outcome, hook.name, hook_impls, kwargs) return outcome.get_result() def undo(self): self.pluginmanager._inner_hookexec = self.oldcall class PluginManager(object): """ Core Pluginmanager class which manages registration of plugin objects and 1:N hook calling. You can register new hooks by calling ``addhooks(module_or_class)``. You can register plugin objects (which contain hooks) by calling ``register(plugin)``. The Pluginmanager is initialized with a prefix that is searched for in the names of the dict of registered plugin objects. An optional excludefunc allows to blacklist names which are not considered as hooks despite a matching prefix. For debugging purposes you can call ``enable_tracing()`` which will subsequently send debug information to the trace helper. """ def __init__(self, project_name, implprefix=None): """ if implprefix is given implementation functions will be recognized if their name matches the implprefix. """ self.project_name = project_name self._name2plugin = {} self._plugin2hookcallers = {} self._plugin_distinfo = [] self.trace = _TagTracer().get("pluginmanage") self.hook = _HookRelay(self.trace.root.get("hook")) self._implprefix = implprefix self._inner_hookexec = lambda hook, methods, kwargs: \ _MultiCall(methods, kwargs, hook.spec_opts).execute() def _hookexec(self, hook, methods, kwargs): # called from all hookcaller instances. # enable_tracing will set its own wrapping function at self._inner_hookexec return self._inner_hookexec(hook, methods, kwargs) def register(self, plugin, name=None): """ Register a plugin and return its canonical name or None if the name is blocked from registering. Raise a ValueError if the plugin is already registered. """ plugin_name = name or self.get_canonical_name(plugin) if plugin_name in self._name2plugin or plugin in self._plugin2hookcallers: if self._name2plugin.get(plugin_name, -1) is None: return # blocked plugin, return None to indicate no registration raise ValueError("Plugin already registered: %s=%s\n%s" % (plugin_name, plugin, self._name2plugin)) # XXX if an error happens we should make sure no state has been # changed at point of return self._name2plugin[plugin_name] = plugin # register matching hook implementations of the plugin self._plugin2hookcallers[plugin] = hookcallers = [] for name in dir(plugin): hookimpl_opts = self.parse_hookimpl_opts(plugin, name) if hookimpl_opts is not None: normalize_hookimpl_opts(hookimpl_opts) method = getattr(plugin, name) hookimpl = HookImpl(plugin, plugin_name, method, hookimpl_opts) hook = getattr(self.hook, name, None) if hook is None: hook = _HookCaller(name, self._hookexec) setattr(self.hook, name, hook) elif hook.has_spec(): self._verify_hook(hook, hookimpl) hook._maybe_apply_history(hookimpl) hook._add_hookimpl(hookimpl) hookcallers.append(hook) return plugin_name def parse_hookimpl_opts(self, plugin, name): method = getattr(plugin, name) res = getattr(method, self.project_name + "_impl", None) if res is not None and not isinstance(res, dict): # false positive res = None elif res is None and self._implprefix and name.startswith(self._implprefix): res = {} return res def unregister(self, plugin=None, name=None): """ unregister a plugin object and all its contained hook implementations from internal data structures. """ if name is None: assert plugin is not None, "one of name or plugin needs to be specified" name = self.get_name(plugin) if plugin is None: plugin = self.get_plugin(name) # if self._name2plugin[name] == None registration was blocked: ignore if self._name2plugin.get(name): del self._name2plugin[name] for hookcaller in self._plugin2hookcallers.pop(plugin, []): hookcaller._remove_plugin(plugin) return plugin def set_blocked(self, name): """ block registrations of the given name, unregister if already registered. """ self.unregister(name=name) self._name2plugin[name] = None def is_blocked(self, name): """ return True if the name blogs registering plugins of that name. """ return name in self._name2plugin and self._name2plugin[name] is None def add_hookspecs(self, module_or_class): """ add new hook specifications defined in the given module_or_class. Functions are recognized if they have been decorated accordingly. """ names = [] for name in dir(module_or_class): spec_opts = self.parse_hookspec_opts(module_or_class, name) if spec_opts is not None: hc = getattr(self.hook, name, None) if hc is None: hc = _HookCaller(name, self._hookexec, module_or_class, spec_opts) setattr(self.hook, name, hc) else: # plugins registered this hook without knowing the spec hc.set_specification(module_or_class, spec_opts) for hookfunction in (hc._wrappers + hc._nonwrappers): self._verify_hook(hc, hookfunction) names.append(name) if not names: raise ValueError("did not find any %r hooks in %r" % (self.project_name, module_or_class)) def parse_hookspec_opts(self, module_or_class, name): method = getattr(module_or_class, name) return getattr(method, self.project_name + "_spec", None) def get_plugins(self): """ return the set of registered plugins. """ return set(self._plugin2hookcallers) def is_registered(self, plugin): """ Return True if the plugin is already registered. """ return plugin in self._plugin2hookcallers def get_canonical_name(self, plugin): """ Return canonical name for a plugin object. Note that a plugin may be registered under a different name which was specified by the caller of register(plugin, name). To obtain the name of an registered plugin use ``get_name(plugin)`` instead.""" return getattr(plugin, "__name__", None) or str(id(plugin)) def get_plugin(self, name): """ Return a plugin or None for the given name. """ return self._name2plugin.get(name) def get_name(self, plugin): """ Return name for registered plugin or None if not registered. """ for name, val in self._name2plugin.items(): if plugin == val: return name def _verify_hook(self, hook, hookimpl): if hook.is_historic() and hookimpl.hookwrapper: raise PluginValidationError( "Plugin %r\nhook %r\nhistoric incompatible to hookwrapper" % (hookimpl.plugin_name, hook.name)) for arg in hookimpl.argnames: if arg not in hook.argnames: raise PluginValidationError( "Plugin %r\nhook %r\nargument %r not available\n" "plugin definition: %s\n" "available hookargs: %s" % (hookimpl.plugin_name, hook.name, arg, _formatdef(hookimpl.function), ", ".join(hook.argnames))) def check_pending(self): """ Verify that all hooks which have not been verified against a hook specification are optional, otherwise raise PluginValidationError""" for name in self.hook.__dict__: if name[0] != "_": hook = getattr(self.hook, name) if not hook.has_spec(): for hookimpl in (hook._wrappers + hook._nonwrappers): if not hookimpl.optionalhook: raise PluginValidationError( "unknown hook %r in plugin %r" % (name, hookimpl.plugin)) def load_setuptools_entrypoints(self, entrypoint_name): """ Load modules from querying the specified setuptools entrypoint name. Return the number of loaded plugins. """ from pkg_resources import iter_entry_points, DistributionNotFound for ep in iter_entry_points(entrypoint_name): # is the plugin registered or blocked? if self.get_plugin(ep.name) or self.is_blocked(ep.name): continue try: plugin = ep.load() except DistributionNotFound: continue self.register(plugin, name=ep.name) self._plugin_distinfo.append((plugin, ep.dist)) return len(self._plugin_distinfo) def list_plugin_distinfo(self): """ return list of distinfo/plugin tuples for all setuptools registered plugins. """ return list(self._plugin_distinfo) def list_name_plugin(self): """ return list of name/plugin pairs. """ return list(self._name2plugin.items()) def get_hookcallers(self, plugin): """ get all hook callers for the specified plugin. """ return self._plugin2hookcallers.get(plugin) def add_hookcall_monitoring(self, before, after): """ add before/after tracing functions for all hooks and return an undo function which, when called, will remove the added tracers. ``before(hook_name, hook_impls, kwargs)`` will be called ahead of all hook calls and receive a hookcaller instance, a list of HookImpl instances and the keyword arguments for the hook call. ``after(outcome, hook_name, hook_impls, kwargs)`` receives the same arguments as ``before`` but also a :py:class:`_CallOutcome`` object which represents the result of the overall hook call. """ return _TracedHookExecution(self, before, after).undo def enable_tracing(self): """ enable tracing of hook calls and return an undo function. """ hooktrace = self.hook._trace def before(hook_name, methods, kwargs): hooktrace.root.indent += 1 hooktrace(hook_name, kwargs) def after(outcome, hook_name, methods, kwargs): if outcome.excinfo is None: hooktrace("finish", hook_name, "-->", outcome.result) hooktrace.root.indent -= 1 return self.add_hookcall_monitoring(before, after) def subset_hook_caller(self, name, remove_plugins): """ Return a new _HookCaller instance for the named method which manages calls to all registered plugins except the ones from remove_plugins. """ orig = getattr(self.hook, name) plugins_to_remove = [plug for plug in remove_plugins if hasattr(plug, name)] if plugins_to_remove: hc = _HookCaller(orig.name, orig._hookexec, orig._specmodule_or_class, orig.spec_opts) for hookimpl in (orig._wrappers + orig._nonwrappers): plugin = hookimpl.plugin if plugin not in plugins_to_remove: hc._add_hookimpl(hookimpl) # we also keep track of this hook caller so it # gets properly removed on plugin unregistration self._plugin2hookcallers.setdefault(plugin, []).append(hc) return hc return orig class _MultiCall: """ execute a call into multiple python functions/methods. """ # XXX note that the __multicall__ argument is supported only # for pytest compatibility reasons. It was never officially # supported there and is explicitly deprecated since 2.8 # so we can remove it soon, allowing to avoid the below recursion # in execute() and simplify/speed up the execute loop. def __init__(self, hook_impls, kwargs, specopts={}): self.hook_impls = hook_impls self.kwargs = kwargs self.kwargs["__multicall__"] = self self.specopts = specopts def execute(self): all_kwargs = self.kwargs self.results = results = [] firstresult = self.specopts.get("firstresult") while self.hook_impls: hook_impl = self.hook_impls.pop() args = [all_kwargs[argname] for argname in hook_impl.argnames] if hook_impl.hookwrapper: return _wrapped_call(hook_impl.function(*args), self.execute) res = hook_impl.function(*args) if res is not None: if firstresult: return res results.append(res) if not firstresult: return results def __repr__(self): status = "%d meths" % (len(self.hook_impls),) if hasattr(self, "results"): status = ("%d results, " % len(self.results)) + status return "<_MultiCall %s, kwargs=%r>" % (status, self.kwargs) def varnames(func, startindex=None): """ return argument name tuple for a function, method, class or callable. In case of a class, its "__init__" method is considered. For methods the "self" parameter is not included unless you are passing an unbound method with Python3 (which has no supports for unbound methods) """ cache = getattr(func, "__dict__", {}) try: return cache["_varnames"] except KeyError: pass if inspect.isclass(func): try: func = func.__init__ except AttributeError: return () startindex = 1 else: if not inspect.isfunction(func) and not inspect.ismethod(func): func = getattr(func, '__call__', func) if startindex is None: startindex = int(inspect.ismethod(func)) try: rawcode = func.__code__ except AttributeError: return () try: x = rawcode.co_varnames[startindex:rawcode.co_argcount] except AttributeError: x = () else: defaults = func.__defaults__ if defaults: x = x[:-len(defaults)] try: cache["_varnames"] = x except TypeError: pass return x class _HookRelay: """ hook holder object for performing 1:N hook calls where N is the number of registered plugins. """ def __init__(self, trace): self._trace = trace class _HookCaller(object): def __init__(self, name, hook_execute, specmodule_or_class=None, spec_opts=None): self.name = name self._wrappers = [] self._nonwrappers = [] self._hookexec = hook_execute if specmodule_or_class is not None: assert spec_opts is not None self.set_specification(specmodule_or_class, spec_opts) def has_spec(self): return hasattr(self, "_specmodule_or_class") def set_specification(self, specmodule_or_class, spec_opts): assert not self.has_spec() self._specmodule_or_class = specmodule_or_class specfunc = getattr(specmodule_or_class, self.name) argnames = varnames(specfunc, startindex=inspect.isclass(specmodule_or_class)) assert "self" not in argnames # sanity check self.argnames = ["__multicall__"] + list(argnames) self.spec_opts = spec_opts if spec_opts.get("historic"): self._call_history = [] def is_historic(self): return hasattr(self, "_call_history") def _remove_plugin(self, plugin): def remove(wrappers): for i, method in enumerate(wrappers): if method.plugin == plugin: del wrappers[i] return True if remove(self._wrappers) is None: if remove(self._nonwrappers) is None: raise ValueError("plugin %r not found" % (plugin,)) def _add_hookimpl(self, hookimpl): if hookimpl.hookwrapper: methods = self._wrappers else: methods = self._nonwrappers if hookimpl.trylast: methods.insert(0, hookimpl) elif hookimpl.tryfirst: methods.append(hookimpl) else: # find last non-tryfirst method i = len(methods) - 1 while i >= 0 and methods[i].tryfirst: i -= 1 methods.insert(i + 1, hookimpl) def __repr__(self): return "<_HookCaller %r>" % (self.name,) def __call__(self, **kwargs): assert not self.is_historic() return self._hookexec(self, self._nonwrappers + self._wrappers, kwargs) def call_historic(self, proc=None, kwargs=None): self._call_history.append((kwargs or {}, proc)) # historizing hooks don't return results self._hookexec(self, self._nonwrappers + self._wrappers, kwargs) def call_extra(self, methods, kwargs): """ Call the hook with some additional temporarily participating methods using the specified kwargs as call parameters. """ old = list(self._nonwrappers), list(self._wrappers) for method in methods: opts = dict(hookwrapper=False, trylast=False, tryfirst=False) hookimpl = HookImpl(None, "<temp>", method, opts) self._add_hookimpl(hookimpl) try: return self(**kwargs) finally: self._nonwrappers, self._wrappers = old def _maybe_apply_history(self, method): if self.is_historic(): for kwargs, proc in self._call_history: res = self._hookexec(self, [method], kwargs) if res and proc is not None: proc(res[0]) class HookImpl: def __init__(self, plugin, plugin_name, function, hook_impl_opts): self.function = function self.argnames = varnames(self.function) self.plugin = plugin self.opts = hook_impl_opts self.plugin_name = plugin_name self.__dict__.update(hook_impl_opts) class PluginValidationError(Exception): """ plugin failed validation. """ if hasattr(inspect, 'signature'): def _formatdef(func): return "%s%s" % ( func.__name__, str(inspect.signature(func)) ) else: def _formatdef(func): return "%s%s" % ( func.__name__, inspect.formatargspec(*inspect.getargspec(func)) )
mpl-2.0
TanguyPatte/phantomjs-packaging
src/breakpad/src/third_party/protobuf/protobuf/python/google/protobuf/internal/descriptor_test.py
295
10605
#! /usr/bin/python # # Protocol Buffers - Google's data interchange format # Copyright 2008 Google Inc. All rights reserved. # http://code.google.com/p/protobuf/ # # 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. """Unittest for google.protobuf.internal.descriptor.""" __author__ = 'robinson@google.com (Will Robinson)' import unittest from google.protobuf import unittest_import_pb2 from google.protobuf import unittest_pb2 from google.protobuf import descriptor_pb2 from google.protobuf import descriptor from google.protobuf import text_format TEST_EMPTY_MESSAGE_DESCRIPTOR_ASCII = """ name: 'TestEmptyMessage' """ class DescriptorTest(unittest.TestCase): def setUp(self): self.my_file = descriptor.FileDescriptor( name='some/filename/some.proto', package='protobuf_unittest' ) self.my_enum = descriptor.EnumDescriptor( name='ForeignEnum', full_name='protobuf_unittest.ForeignEnum', filename=None, file=self.my_file, values=[ descriptor.EnumValueDescriptor(name='FOREIGN_FOO', index=0, number=4), descriptor.EnumValueDescriptor(name='FOREIGN_BAR', index=1, number=5), descriptor.EnumValueDescriptor(name='FOREIGN_BAZ', index=2, number=6), ]) self.my_message = descriptor.Descriptor( name='NestedMessage', full_name='protobuf_unittest.TestAllTypes.NestedMessage', filename=None, file=self.my_file, containing_type=None, fields=[ descriptor.FieldDescriptor( name='bb', full_name='protobuf_unittest.TestAllTypes.NestedMessage.bb', index=0, number=1, type=5, cpp_type=1, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None), ], nested_types=[], enum_types=[ self.my_enum, ], extensions=[]) self.my_method = descriptor.MethodDescriptor( name='Bar', full_name='protobuf_unittest.TestService.Bar', index=0, containing_service=None, input_type=None, output_type=None) self.my_service = descriptor.ServiceDescriptor( name='TestServiceWithOptions', full_name='protobuf_unittest.TestServiceWithOptions', file=self.my_file, index=0, methods=[ self.my_method ]) def testEnumFixups(self): self.assertEqual(self.my_enum, self.my_enum.values[0].type) def testContainingTypeFixups(self): self.assertEqual(self.my_message, self.my_message.fields[0].containing_type) self.assertEqual(self.my_message, self.my_enum.containing_type) def testContainingServiceFixups(self): self.assertEqual(self.my_service, self.my_method.containing_service) def testGetOptions(self): self.assertEqual(self.my_enum.GetOptions(), descriptor_pb2.EnumOptions()) self.assertEqual(self.my_enum.values[0].GetOptions(), descriptor_pb2.EnumValueOptions()) self.assertEqual(self.my_message.GetOptions(), descriptor_pb2.MessageOptions()) self.assertEqual(self.my_message.fields[0].GetOptions(), descriptor_pb2.FieldOptions()) self.assertEqual(self.my_method.GetOptions(), descriptor_pb2.MethodOptions()) self.assertEqual(self.my_service.GetOptions(), descriptor_pb2.ServiceOptions()) def testFileDescriptorReferences(self): self.assertEqual(self.my_enum.file, self.my_file) self.assertEqual(self.my_message.file, self.my_file) def testFileDescriptor(self): self.assertEqual(self.my_file.name, 'some/filename/some.proto') self.assertEqual(self.my_file.package, 'protobuf_unittest') class DescriptorCopyToProtoTest(unittest.TestCase): """Tests for CopyTo functions of Descriptor.""" def _AssertProtoEqual(self, actual_proto, expected_class, expected_ascii): expected_proto = expected_class() text_format.Merge(expected_ascii, expected_proto) self.assertEqual( actual_proto, expected_proto, 'Not equal,\nActual:\n%s\nExpected:\n%s\n' % (str(actual_proto), str(expected_proto))) def _InternalTestCopyToProto(self, desc, expected_proto_class, expected_proto_ascii): actual = expected_proto_class() desc.CopyToProto(actual) self._AssertProtoEqual( actual, expected_proto_class, expected_proto_ascii) def testCopyToProto_EmptyMessage(self): self._InternalTestCopyToProto( unittest_pb2.TestEmptyMessage.DESCRIPTOR, descriptor_pb2.DescriptorProto, TEST_EMPTY_MESSAGE_DESCRIPTOR_ASCII) def testCopyToProto_NestedMessage(self): TEST_NESTED_MESSAGE_ASCII = """ name: 'NestedMessage' field: < name: 'bb' number: 1 label: 1 # Optional type: 5 # TYPE_INT32 > """ self._InternalTestCopyToProto( unittest_pb2.TestAllTypes.NestedMessage.DESCRIPTOR, descriptor_pb2.DescriptorProto, TEST_NESTED_MESSAGE_ASCII) def testCopyToProto_ForeignNestedMessage(self): TEST_FOREIGN_NESTED_ASCII = """ name: 'TestForeignNested' field: < name: 'foreign_nested' number: 1 label: 1 # Optional type: 11 # TYPE_MESSAGE type_name: '.protobuf_unittest.TestAllTypes.NestedMessage' > """ self._InternalTestCopyToProto( unittest_pb2.TestForeignNested.DESCRIPTOR, descriptor_pb2.DescriptorProto, TEST_FOREIGN_NESTED_ASCII) def testCopyToProto_ForeignEnum(self): TEST_FOREIGN_ENUM_ASCII = """ name: 'ForeignEnum' value: < name: 'FOREIGN_FOO' number: 4 > value: < name: 'FOREIGN_BAR' number: 5 > value: < name: 'FOREIGN_BAZ' number: 6 > """ self._InternalTestCopyToProto( unittest_pb2._FOREIGNENUM, descriptor_pb2.EnumDescriptorProto, TEST_FOREIGN_ENUM_ASCII) def testCopyToProto_Options(self): TEST_DEPRECATED_FIELDS_ASCII = """ name: 'TestDeprecatedFields' field: < name: 'deprecated_int32' number: 1 label: 1 # Optional type: 5 # TYPE_INT32 options: < deprecated: true > > """ self._InternalTestCopyToProto( unittest_pb2.TestDeprecatedFields.DESCRIPTOR, descriptor_pb2.DescriptorProto, TEST_DEPRECATED_FIELDS_ASCII) def testCopyToProto_AllExtensions(self): TEST_EMPTY_MESSAGE_WITH_EXTENSIONS_ASCII = """ name: 'TestEmptyMessageWithExtensions' extension_range: < start: 1 end: 536870912 > """ self._InternalTestCopyToProto( unittest_pb2.TestEmptyMessageWithExtensions.DESCRIPTOR, descriptor_pb2.DescriptorProto, TEST_EMPTY_MESSAGE_WITH_EXTENSIONS_ASCII) def testCopyToProto_SeveralExtensions(self): TEST_MESSAGE_WITH_SEVERAL_EXTENSIONS_ASCII = """ name: 'TestMultipleExtensionRanges' extension_range: < start: 42 end: 43 > extension_range: < start: 4143 end: 4244 > extension_range: < start: 65536 end: 536870912 > """ self._InternalTestCopyToProto( unittest_pb2.TestMultipleExtensionRanges.DESCRIPTOR, descriptor_pb2.DescriptorProto, TEST_MESSAGE_WITH_SEVERAL_EXTENSIONS_ASCII) def testCopyToProto_FileDescriptor(self): UNITTEST_IMPORT_FILE_DESCRIPTOR_ASCII = (""" name: 'google/protobuf/unittest_import.proto' package: 'protobuf_unittest_import' message_type: < name: 'ImportMessage' field: < name: 'd' number: 1 label: 1 # Optional type: 5 # TYPE_INT32 > > """ + """enum_type: < name: 'ImportEnum' value: < name: 'IMPORT_FOO' number: 7 > value: < name: 'IMPORT_BAR' number: 8 > value: < name: 'IMPORT_BAZ' number: 9 > > options: < java_package: 'com.google.protobuf.test' optimize_for: 1 # SPEED > """) self._InternalTestCopyToProto( unittest_import_pb2.DESCRIPTOR, descriptor_pb2.FileDescriptorProto, UNITTEST_IMPORT_FILE_DESCRIPTOR_ASCII) def testCopyToProto_ServiceDescriptor(self): TEST_SERVICE_ASCII = """ name: 'TestService' method: < name: 'Foo' input_type: '.protobuf_unittest.FooRequest' output_type: '.protobuf_unittest.FooResponse' > method: < name: 'Bar' input_type: '.protobuf_unittest.BarRequest' output_type: '.protobuf_unittest.BarResponse' > """ self._InternalTestCopyToProto( unittest_pb2.TestService.DESCRIPTOR, descriptor_pb2.ServiceDescriptorProto, TEST_SERVICE_ASCII) if __name__ == '__main__': unittest.main()
bsd-3-clause
jbking/demo-appengine-django-golang
myproject/django/utils/datastructures.py
102
15759
import copy import warnings from django.utils import six class MergeDict(object): """ A simple class for creating new "virtual" dictionaries that actually look up values in more than one dictionary, passed in the constructor. If a key appears in more than one of the given dictionaries, only the first occurrence will be used. """ def __init__(self, *dicts): self.dicts = dicts def __getitem__(self, key): for dict_ in self.dicts: try: return dict_[key] except KeyError: pass raise KeyError def __copy__(self): return self.__class__(*self.dicts) def get(self, key, default=None): try: return self[key] except KeyError: return default # This is used by MergeDicts of MultiValueDicts. def getlist(self, key): for dict_ in self.dicts: if key in dict_: return dict_.getlist(key) return [] def _iteritems(self): seen = set() for dict_ in self.dicts: for item in six.iteritems(dict_): k = item[0] if k in seen: continue seen.add(k) yield item def _iterkeys(self): for k, v in self._iteritems(): yield k def _itervalues(self): for k, v in self._iteritems(): yield v if six.PY3: items = _iteritems keys = _iterkeys values = _itervalues else: iteritems = _iteritems iterkeys = _iterkeys itervalues = _itervalues def items(self): return list(self.iteritems()) def keys(self): return list(self.iterkeys()) def values(self): return list(self.itervalues()) def has_key(self, key): for dict_ in self.dicts: if key in dict_: return True return False __contains__ = has_key __iter__ = _iterkeys def copy(self): """Returns a copy of this object.""" return self.__copy__() def __str__(self): ''' Returns something like "{'key1': 'val1', 'key2': 'val2', 'key3': 'val3'}" instead of the generic "<object meta-data>" inherited from object. ''' return str(dict(self.items())) def __repr__(self): ''' Returns something like MergeDict({'key1': 'val1', 'key2': 'val2'}, {'key3': 'val3'}) instead of generic "<object meta-data>" inherited from object. ''' dictreprs = ', '.join(repr(d) for d in self.dicts) return '%s(%s)' % (self.__class__.__name__, dictreprs) class SortedDict(dict): """ A dictionary that keeps its keys in the order in which they're inserted. """ def __new__(cls, *args, **kwargs): instance = super(SortedDict, cls).__new__(cls, *args, **kwargs) instance.keyOrder = [] return instance def __init__(self, data=None): if data is None or isinstance(data, dict): data = data or [] super(SortedDict, self).__init__(data) self.keyOrder = list(data) if data else [] else: super(SortedDict, self).__init__() super_set = super(SortedDict, self).__setitem__ for key, value in data: # Take the ordering from first key if key not in self: self.keyOrder.append(key) # But override with last value in data (dict() does this) super_set(key, value) def __deepcopy__(self, memo): return self.__class__([(key, copy.deepcopy(value, memo)) for key, value in self.items()]) def __copy__(self): # The Python's default copy implementation will alter the state # of self. The reason for this seems complex but is likely related to # subclassing dict. return self.copy() def __setitem__(self, key, value): if key not in self: self.keyOrder.append(key) super(SortedDict, self).__setitem__(key, value) def __delitem__(self, key): super(SortedDict, self).__delitem__(key) self.keyOrder.remove(key) def __iter__(self): return iter(self.keyOrder) def __reversed__(self): return reversed(self.keyOrder) def pop(self, k, *args): result = super(SortedDict, self).pop(k, *args) try: self.keyOrder.remove(k) except ValueError: # Key wasn't in the dictionary in the first place. No problem. pass return result def popitem(self): result = super(SortedDict, self).popitem() self.keyOrder.remove(result[0]) return result def _iteritems(self): for key in self.keyOrder: yield key, self[key] def _iterkeys(self): for key in self.keyOrder: yield key def _itervalues(self): for key in self.keyOrder: yield self[key] if six.PY3: items = _iteritems keys = _iterkeys values = _itervalues else: iteritems = _iteritems iterkeys = _iterkeys itervalues = _itervalues def items(self): return [(k, self[k]) for k in self.keyOrder] def keys(self): return self.keyOrder[:] def values(self): return [self[k] for k in self.keyOrder] def update(self, dict_): for k, v in six.iteritems(dict_): self[k] = v def setdefault(self, key, default): if key not in self: self.keyOrder.append(key) return super(SortedDict, self).setdefault(key, default) def value_for_index(self, index): """Returns the value of the item at the given zero-based index.""" # This, and insert() are deprecated because they cannot be implemented # using collections.OrderedDict (Python 2.7 and up), which we'll # eventually switch to warnings.warn( "SortedDict.value_for_index is deprecated", PendingDeprecationWarning, stacklevel=2 ) return self[self.keyOrder[index]] def insert(self, index, key, value): """Inserts the key, value pair before the item with the given index.""" warnings.warn( "SortedDict.insert is deprecated", PendingDeprecationWarning, stacklevel=2 ) if key in self.keyOrder: n = self.keyOrder.index(key) del self.keyOrder[n] if n < index: index -= 1 self.keyOrder.insert(index, key) super(SortedDict, self).__setitem__(key, value) def copy(self): """Returns a copy of this object.""" # This way of initializing the copy means it works for subclasses, too. return self.__class__(self) def __repr__(self): """ Replaces the normal dict.__repr__ with a version that returns the keys in their sorted order. """ return '{%s}' % ', '.join(['%r: %r' % (k, v) for k, v in six.iteritems(self)]) def clear(self): super(SortedDict, self).clear() self.keyOrder = [] class MultiValueDictKeyError(KeyError): pass class MultiValueDict(dict): """ A subclass of dictionary customized to handle multiple values for the same key. >>> d = MultiValueDict({'name': ['Adrian', 'Simon'], 'position': ['Developer']}) >>> d['name'] 'Simon' >>> d.getlist('name') ['Adrian', 'Simon'] >>> d.getlist('doesnotexist') [] >>> d.getlist('doesnotexist', ['Adrian', 'Simon']) ['Adrian', 'Simon'] >>> d.get('lastname', 'nonexistent') 'nonexistent' >>> d.setlist('lastname', ['Holovaty', 'Willison']) This class exists to solve the irritating problem raised by cgi.parse_qs, which returns a list for every key, even though most Web forms submit single name-value pairs. """ def __init__(self, key_to_list_mapping=()): super(MultiValueDict, self).__init__(key_to_list_mapping) def __repr__(self): return "<%s: %s>" % (self.__class__.__name__, super(MultiValueDict, self).__repr__()) def __getitem__(self, key): """ Returns the last data value for this key, or [] if it's an empty list; raises KeyError if not found. """ try: list_ = super(MultiValueDict, self).__getitem__(key) except KeyError: raise MultiValueDictKeyError("Key %r not found in %r" % (key, self)) try: return list_[-1] except IndexError: return [] def __setitem__(self, key, value): super(MultiValueDict, self).__setitem__(key, [value]) def __copy__(self): return self.__class__([ (k, v[:]) for k, v in self.lists() ]) def __deepcopy__(self, memo=None): if memo is None: memo = {} result = self.__class__() memo[id(self)] = result for key, value in dict.items(self): dict.__setitem__(result, copy.deepcopy(key, memo), copy.deepcopy(value, memo)) return result def __getstate__(self): obj_dict = self.__dict__.copy() obj_dict['_data'] = dict([(k, self.getlist(k)) for k in self]) return obj_dict def __setstate__(self, obj_dict): data = obj_dict.pop('_data', {}) for k, v in data.items(): self.setlist(k, v) self.__dict__.update(obj_dict) def get(self, key, default=None): """ Returns the last data value for the passed key. If key doesn't exist or value is an empty list, then default is returned. """ try: val = self[key] except KeyError: return default if val == []: return default return val def getlist(self, key, default=None): """ Returns the list of values for the passed key. If key doesn't exist, then a default value is returned. """ try: return super(MultiValueDict, self).__getitem__(key) except KeyError: if default is None: return [] return default def setlist(self, key, list_): super(MultiValueDict, self).__setitem__(key, list_) def setdefault(self, key, default=None): if key not in self: self[key] = default # Do not return default here because __setitem__() may store # another value -- QueryDict.__setitem__() does. Look it up. return self[key] def setlistdefault(self, key, default_list=None): if key not in self: if default_list is None: default_list = [] self.setlist(key, default_list) # Do not return default_list here because setlist() may store # another value -- QueryDict.setlist() does. Look it up. return self.getlist(key) def appendlist(self, key, value): """Appends an item to the internal list associated with key.""" self.setlistdefault(key).append(value) def _iteritems(self): """ Yields (key, value) pairs, where value is the last item in the list associated with the key. """ for key in self: yield key, self[key] def _iterlists(self): """Yields (key, list) pairs.""" return six.iteritems(super(MultiValueDict, self)) def _itervalues(self): """Yield the last value on every key list.""" for key in self: yield self[key] if six.PY3: items = _iteritems lists = _iterlists values = _itervalues else: iteritems = _iteritems iterlists = _iterlists itervalues = _itervalues def items(self): return list(self.iteritems()) def lists(self): return list(self.iterlists()) def values(self): return list(self.itervalues()) def copy(self): """Returns a shallow copy of this object.""" return copy.copy(self) def update(self, *args, **kwargs): """ update() extends rather than replaces existing key lists. Also accepts keyword args. """ if len(args) > 1: raise TypeError("update expected at most 1 arguments, got %d" % len(args)) if args: other_dict = args[0] if isinstance(other_dict, MultiValueDict): for key, value_list in other_dict.lists(): self.setlistdefault(key).extend(value_list) else: try: for key, value in other_dict.items(): self.setlistdefault(key).append(value) except TypeError: raise ValueError("MultiValueDict.update() takes either a MultiValueDict or dictionary") for key, value in six.iteritems(kwargs): self.setlistdefault(key).append(value) def dict(self): """ Returns current object as a dict with singular values. """ return dict((key, self[key]) for key in self) class ImmutableList(tuple): """ A tuple-like object that raises useful errors when it is asked to mutate. Example:: >>> a = ImmutableList(range(5), warning="You cannot mutate this.") >>> a[3] = '4' Traceback (most recent call last): ... AttributeError: You cannot mutate this. """ def __new__(cls, *args, **kwargs): if 'warning' in kwargs: warning = kwargs['warning'] del kwargs['warning'] else: warning = 'ImmutableList object is immutable.' self = tuple.__new__(cls, *args, **kwargs) self.warning = warning return self def complain(self, *wargs, **kwargs): if isinstance(self.warning, Exception): raise self.warning else: raise AttributeError(self.warning) # All list mutation functions complain. __delitem__ = complain __delslice__ = complain __iadd__ = complain __imul__ = complain __setitem__ = complain __setslice__ = complain append = complain extend = complain insert = complain pop = complain remove = complain sort = complain reverse = complain class DictWrapper(dict): """ Wraps accesses to a dictionary so that certain values (those starting with the specified prefix) are passed through a function before being returned. The prefix is removed before looking up the real value. Used by the SQL construction code to ensure that values are correctly quoted before being used. """ def __init__(self, data, func, prefix): super(DictWrapper, self).__init__(data) self.func = func self.prefix = prefix def __getitem__(self, key): """ Retrieves the real value after stripping the prefix string (if present). If the prefix is present, pass the value through self.func before returning, otherwise return the raw value. """ if key.startswith(self.prefix): use_func = True key = key[len(self.prefix):] else: use_func = False value = super(DictWrapper, self).__getitem__(key) if use_func: return self.func(value) return value
mit
wjakob/layerlab
recipes/utils/materials.py
1
6279
# Complex-valued IOR curves for a few metals from scipy import interpolate lambda_gold = [298.75705, 302.400421, 306.133759, 309.960449, 313.884003, 317.908142, 322.036835, 326.274139, 330.624481, 335.092377, 339.682678, 344.400482, 349.251221, 354.240509, 359.37442, 364.659332, 370.10202, 375.709625, 381.489777, 387.450562, 393.600555, 399.948975, 406.505493, 413.280579, 420.285339, 427.531647, 435.032196, 442.800629, 450.851562, 459.200653, 467.864838, 476.862213, 486.212463, 495.936707, 506.057861, 516.600769, 527.592224, 539.061646, 551.040771, 563.564453, 576.670593, 590.400818, 604.800842, 619.920898, 635.816284, 652.548279, 670.184753, 688.800964, 708.481018, 729.318665, 751.41925, 774.901123, 799.897949, 826.561157, 855.063293, 885.601257] eta_gold = [1.795+1.920375j, 1.812+1.92j, 1.822625+1.918875j, 1.83+1.916j, 1.837125+1.911375j, 1.84+1.904j, 1.83425+1.891375j, 1.824+1.878j, 1.812+1.86825j, 1.798+1.86j, 1.782+1.85175j, 1.766+1.846j, 1.7525+1.84525j, 1.74+1.848j, 1.727625+1.852375j, 1.716+1.862j, 1.705875+1.883j, 1.696+1.906j, 1.68475+1.9225j, 1.674+1.936j, 1.666+1.94775j, 1.658+1.956j, 1.64725+1.959375j, 1.636+1.958j, 1.628+1.951375j, 1.616+1.94j, 1.59625+1.9245j, 1.562+1.904j, 1.502125+1.875875j, 1.426+1.846j, 1.345875+1.814625j, 1.242+1.796j, 1.08675+1.797375j, 0.916+1.84j, 0.7545+1.9565j, 0.608+2.12j, 0.49175+2.32625j, 0.402+2.54j, 0.3455+2.730625j, 0.306+2.88j, 0.267625+2.940625j, 0.236+2.97j, 0.212375+3.015j, 0.194+3.06j, 0.17775+3.07j, 0.166+3.15j, 0.161+3.445812j, 0.16+3.8j, 0.160875+4.087687j, 0.164+4.357j, 0.1695+4.610188j, 0.176+4.86j, 0.181375+5.125813j, 0.188+5.39j, 0.198125+5.63125j, 0.21+5.88j] lambda_aluminium = [298.75705, 302.400421, 306.133759, 309.960449, 313.884003, 317.908142, 322.036835, 326.274139, 330.624481, 335.092377, 339.682678, 344.400482, 349.251221, 354.240509, 359.37442, 364.659332, 370.10202, 375.709625, 381.489777, 387.450562, 393.600555, 399.948975, 406.505493, 413.280579, 420.285339, 427.531647, 435.032196, 442.800629, 450.851562, 459.200653, 467.864838, 476.862213, 486.212463, 495.936707, 506.057861, 516.600769, 527.592224, 539.061646, 551.040771, 563.564453, 576.670593, 590.400818, 604.800842, 619.920898, 635.816284, 652.548279, 670.184753, 688.800964, 708.481018, 729.318665, 751.41925, 774.901123, 799.897949, 826.561157, 855.063293, 885.601257] eta_aluminium = [(0.273375+3.59375j), (0.28+3.64j), (0.286813+3.689375j), (0.294+3.74j), (0.301875+3.789375j), (0.31+3.84j), (0.317875+3.894375j), (0.326+3.95j), (0.33475+4.005j), (0.344+4.06j), (0.353813+4.11375j), (0.364+4.17j), (0.374375+4.23375j), (0.385+4.3j), (0.39575+4.365j), (0.407+4.43j), (0.419125+4.49375j), (0.432+4.56j), (0.445688+4.63375j), (0.46+4.71j), (0.474688+4.784375j), (0.49+4.86j), (0.506188+4.938125j), (0.523+5.02j), (0.540063+5.10875j), (0.558+5.2j), (0.577313+5.29j), (0.598+5.38j), (0.620313+5.48j), (0.644+5.58j), (0.668625+5.69j), (0.695+5.8j), (0.72375+5.915j), (0.755+6.03j), (0.789+6.15j), (0.826+6.28j), (0.867+6.42j), (0.912+6.55j), (0.963+6.7j), (1.02+6.85j), (1.08+7j), (1.15+7.15j), (1.22+7.31j), (1.3+7.48j), (1.39+7.65j), (1.49+7.82j), (1.6+8.01j), (1.74+8.21j), (1.91+8.39j), (2.14+8.57j), (2.41+8.62j), (2.63+8.6j), (2.8+8.45j), (2.74+8.31j), (2.58+8.21j), (2.24+8.21j)] lambda_copper = [302.400421, 306.133759, 309.960449, 313.884003, 317.908142, 322.036835, 326.274139, 330.624481, 335.092377, 339.682678, 344.400482, 349.251221, 354.240509, 359.37442, 364.659332, 370.10202, 375.709625, 381.489777, 387.450562, 393.600555, 399.948975, 406.505493, 413.280579, 420.285339, 427.531647, 435.032196, 442.800629, 450.851562, 459.200653, 467.864838, 476.862213, 486.212463, 495.936707, 506.057861, 516.600769, 527.592224, 539.061646, 551.040771, 563.564453, 576.670593, 590.400818, 604.800842, 619.920898, 635.816284, 652.548279, 670.184753, 688.800964, 708.481018, 729.318665, 751.41925, 774.901123, 799.897949, 826.561157, 855.063293, 885.601257] eta_copper = [(1.38+1.687j), (1.358438+1.703313j), (1.34+1.72j), (1.329063+1.744563j), (1.325+1.77j), (1.3325+1.791625j), (1.34+1.81j), (1.334375+1.822125j), (1.325+1.834j), (1.317812+1.85175j), (1.31+1.872j), (1.300313+1.89425j), (1.29+1.916j), (1.281563+1.931688j), (1.27+1.95j), (1.249062+1.972438j), (1.225+2.015j), (1.2+2.121562j), (1.18+2.21j), (1.174375+2.177188j), (1.175+2.13j), (1.1775+2.160063j), (1.18+2.21j), (1.178125+2.249938j), (1.175+2.289j), (1.172812+2.326j), (1.17+2.362j), (1.165312+2.397625j), (1.16+2.433j), (1.155312+2.469187j), (1.15+2.504j), (1.142812+2.535875j), (1.135+2.564j), (1.131562+2.589625j), (1.12+2.605j), (1.092437+2.595562j), (1.04+2.583j), (0.950375+2.5765j), (0.826+2.599j), (0.645875+2.678062j), (0.468+2.809j), (0.35125+3.01075j), (0.272+3.24j), (0.230813+3.458187j), (0.214+3.67j), (0.20925+3.863125j), (0.213+4.05j), (0.21625+4.239563j), (0.223+4.43j), (0.2365+4.619563j), (0.25+4.817j), (0.254188+5.034125j), (0.26+5.26j), (0.28+5.485625j), (0.3+5.717j)] lambda_chrome = [300.194, 307.643005, 316.276001, 323.708008, 333.279999, 341.542999, 351.217987, 362.514984, 372.312012, 385.031006, 396.10202, 409.175018, 424.58902, 438.09201, 455.80899, 471.406982, 490.040009, 512.314026, 532.102966, 558.468018, 582.06604, 610.739014, 700.452026, 815.65802, 826.53302, 849.17804, 860.971985, 885.570984] eta_chrome = [(0.98+2.67j), (1.02+2.76j), (1.06+2.85j), (1.12+2.95j), (1.18+3.04j), (1.26+3.12j), (1.33+3.18j), (1.39+3.24j), (1.43+3.31j), (1.44+3.4j), (1.48+3.54j), (1.54+3.71j), (1.65+3.89j), (1.8+4.06j), (1.99+4.22j), (2.22+4.36j), (2.49+4.44j), (2.75+4.46j), (2.98+4.45j), (3.18+4.41j), (3.34+4.38j), (3.48+4.36j), (3.84+4.37j), (4.23+4.34j), (4.27+4.33j), (4.31+4.32j), (4.33+4.32j), (4.38+4.31j)] gold = interpolate.interp1d(lambda_gold, eta_gold, kind='cubic') copper = interpolate.interp1d(lambda_copper, eta_copper, kind='cubic') aluminium = interpolate.interp1d(lambda_aluminium, eta_aluminium, kind='cubic') chrome = interpolate.interp1d(lambda_chrome, eta_chrome, kind='cubic')
bsd-2-clause
angus-ai/angus-jumpingsumo
wrapper.py
1
3347
# -*- coding: utf-8 -*- #!/usr/bin/env python # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. import os import subprocess import threading import time import angus WIDTH = 640 def img_generator(file_path): with open(file_path, "rb") as f: buff = "" for chunk in f: buff += chunk s = buff.find('\xff\xd8') e = buff.find('\xff\xd9') if s != -1 and e != -1: jpg = buff[s:e + 2] buff = buff[e + 2:] yield jpg def command(img, service): file_path = '/tmp/imgtmp.jpg' with open(file_path, 'wb') as f: f.write(img) job = service.process({'image': open(file_path, 'rb')}) result = job.result['faces'] if len(result) > 0 and result[0]['roi_confidence'] > 0.5: roi = result[0]['roi'] x = roi[0] w = roi[2] cmd_angle = (x + w * 0.5) - WIDTH / 2 print w if abs(cmd_angle) > WIDTH / 8: if cmd_angle > 0: return "Right" else: return "Left" elif w > 100: return "Back" elif w < 80: return "Forw" return None def command_loop(singleton, sub, service): img = singleton[0] if img is None: return cmd = command(img, service) if cmd == "Right": sub.stdin.write("u") sub.stdin.flush() elif cmd == "Left": sub.stdin.write("y") sub.stdin.flush() elif cmd == "Back": sub.stdin.write("i") sub.stdin.flush() elif cmd == "Forw": sub.stdin.write("o") sub.stdin.flush() def loop(singleton, sub, service): while True: command_loop(singleton, sub, service) # print "Loop" time.sleep(1) def launch(input_path, sub, service): singleton = [None] count = 0 thread = threading.Thread(target=loop, args=(singleton, sub, service)) thread.daemon = True thread.start() for img in img_generator(input_path): singleton[0] = img count += 1 if count > 600: break sub.stdin.write("q") sub.stdin.flush() def main(): os.environ[ 'LD_LIBRARY_PATH'] = "../ARSDKBuildUtils/Targets/Unix/Install/lib" sub = subprocess.Popen( ["./JumpingSumoInterface"], stdin=subprocess.PIPE, stdout=None, stderr=subprocess.STDOUT) time.sleep(2) conn = angus.connect() service = conn.services.get_service('face_detection', 1) launch("./video_fifo", sub, service) if __name__ == "__main__": main()
apache-2.0
nhatbui/pysuite
pookeeper/pookeeper/pookeeper.py
1
7385
import os from collections import defaultdict, OrderedDict from twisted.internet.protocol import Factory from twisted.protocols.basic import LineReceiver from twisted.internet import reactor class ZooKeeper(LineReceiver): def __init__(self, connection_addr, znodes, ephem_nodes): self.address = connection_addr self.znodes = znodes self.ephem_nodes = ephem_nodes def connectionMade(self): self.sendLine("true:Connected") def connectionLost(self): # Delete all ephemeral nodes associated # with this connection/address. for node in self.ephem_nodes[self.address]: self.delete_node(node) del self.ephem_nodes[self.address] def delete_node(self, node): # Delete node from parent's children listing parent, child_name = os.path.split(node) del self.znodes[parent]['children'][child_name] # Delete node and all its children :( stack = [node] while len(stack): curr_node = stack.pop() stack.extend(self.znodes[curr_node]['children'].keys()) # Notify watchers self.notify_watchers(curr_node) del self.znodes[curr_node] def notify_watchers(self, node): # Notify watchers while len(self.znodes[node]['watchers']): watcher = self.znodes[node]['watchers'].pop() watcher.sendLine('true:WATCHER_NOTICE:DELETED:{}'.format(node)) def lineReceived(self, msg): # Check command idx = msg.find(':') if idx == -1: self.sendLine('false:bad message') cmd = msg[:idx] if cmd == 'CREATE': self.handle_CREATENODE(msg[(idx+1):]) elif cmd == 'ECREATE': self.handle_CREATEEPHEMERALNODE(msg[(idx+1):]) elif cmd == 'DELETE': self.handle_DELETENODE(msg[(idx+1):]) elif cmd == 'EXISTS': self.handle_EXISTSNODE(msg[(idx+1):]) elif cmd == 'GET': self.handle_GET(msg[(idx+1):]) elif cmd == 'SET': self.handle_SET(msg[(idx+1):]) elif cmd == 'CHILDREN': self.handle_GETCHILDREN(msg[(idx+1):]) elif cmd == 'WATCH': self.handle_WATCH(msg[(idx+1):]) else: self.sendLine('false:unknown command') def handle_CREATENODE(self, node): # Check if znode path starts with a slash if node[0] != '/': self.sendLine('false') # Check path up to node exists p, _ = os.path.split(node) if p not in self.znodes: self.sendLine('false') return # Check if node already exists if node in self.znodes: self.sendLine('false:node already exists') return parent, child = os.path.split(node) self.znodes[node] = { 'parent': parent, 'children': {}, 'watchers': []} self.znodes[parent]['children'][child] = True self.sendLine('true:CREATED:{}'.format(node)) def handle_CREATEEPHEMERALNODE(self, node): # Check if znode path starts with a slash if node[0] != '/': self.sendLine('false:bad node name') # Check path up to node exists p, _ = os.path.split(node) if p not in self.znodes: self.sendLine('false:path up to node does not exist') else: parent, child = os.path.split(node) self.znodes[node] = { 'parent': parent, 'children': {}, 'watchers': []} self.znodes[parent]['children'][child] = True # Add as ephemeral node self.ephem_nodes[self.address].append(node) self.sendLine('true:CREATED_ENODE:{}'.format(node)) def handle_DELETENODE(self, node): # Check if znode path starts with a slash if node[0] != '/': self.sendLine('false') # Check that node exists if node in self.znodes: # Delete node from parent's children listing parent, child_name = os.path.split(node) del self.znodes[parent]['children'][child_name] # Delete node and all its children :( stack = [node] while len(stack): curr_node = stack.pop() stack.extend(self.znodes[curr_node]['children'].keys()) # Notify watchers while len(self.znodes[curr_node]['watchers']): watcher = self.znodes[curr_node]['watchers'].pop() watcher.sendLine('true:WATCHER_NOTICE:DELETED:{}'.format(curr_node)) del self.znodes[curr_node] self.sendLine('true:DELETED:{}'.format(node)) else: self.sendLine('false:NOT DELETED:{}'.format(node)) def handle_EXISTSNODE(self, node): # Check if znode path starts with a slash if node[0] != '/': self.sendLine('false') # Check that node exists if node in self.znodes: self.sendLine('true') else: self.sendLine('false') def handle_GET(self, node): # Check if znode path starts with a slash if node[0] != '/': self.sendLine('false') # Check that node exists if node in self.znodes: self.sendLine(self.znodes[node]['data']) else: self.sendLine('false') def handle_SET(self, msg): idx = msg.find(':') if idx == -1: self.sendLine('false') node = msg[:idx] data = msg[(idx+1):] # Check if znode path starts with a slash if node[0] != '/': self.sendLine('false') # Check that node exists if node in self.znodes: self.znodes[node]['data'] = data # Notify watchers while len(self.znodes[node]['watchers']): watcher = self.znodes[node]['watchers'].pop() watcher.sendLine('true:WATCHER_NOFITY:CHANGED:{}'.format(node)) self.sendLine('true:SET:{}'.format(node)) else: self.sendLine('false') def handle_GETCHILDREN(self, node): # Check if znode path starts with a slash if node[0] != '/': self.sendLine('false') # Check that node exists if node in self.znodes: self.sendLine(','.join(self.znodes[node]['children'].keys())) else: self.sendLine('false') def handle_WATCH(self, node): # Check if znode path starts with a slash if node[0] != '/': self.sendLine('false:WATCHING:improper naming:{}'.format(node)) # Check that node exists if node in self.znodes: self.znodes[node]['watchers'].append(self) self.sendLine('true:WATCHING:{}'.format(node)) else: self.sendLine('false:WATCHING:node does not exist:{}'.format(node)) class ZooKeeperFactory(Factory): def __init__(self): self.znodes = {'/': { 'parent': None, 'children': OrderedDict(), 'watchers': [] } } self.ephem_nodes = defaultdict(list) def buildProtocol(self, addr): return ZooKeeper(addr, self.znodes, self.ephem_nodes) if __name__ == '__main__': reactor.listenTCP(8123, ZooKeeperFactory()) print('Starting on port 8123') reactor.run()
mit
TangHao1987/intellij-community
python/lib/Lib/distutils/command/bdist_msi.py
88
30900
# -*- coding: iso-8859-1 -*- # Copyright (C) 2005, 2006 Martin v. Löwis # Licensed to PSF under a Contributor Agreement. # The bdist_wininst command proper # based on bdist_wininst """ Implements the bdist_msi command. """ import sys, os, string from distutils.core import Command from distutils.util import get_platform from distutils.dir_util import remove_tree from distutils.sysconfig import get_python_version from distutils.version import StrictVersion from distutils.errors import DistutilsOptionError from distutils import log import msilib from msilib import schema, sequence, text from msilib import Directory, Feature, Dialog, add_data class PyDialog(Dialog): """Dialog class with a fixed layout: controls at the top, then a ruler, then a list of buttons: back, next, cancel. Optionally a bitmap at the left.""" def __init__(self, *args, **kw): """Dialog(database, name, x, y, w, h, attributes, title, first, default, cancel, bitmap=true)""" Dialog.__init__(self, *args) ruler = self.h - 36 bmwidth = 152*ruler/328 #if kw.get("bitmap", True): # self.bitmap("Bitmap", 0, 0, bmwidth, ruler, "PythonWin") self.line("BottomLine", 0, ruler, self.w, 0) def title(self, title): "Set the title text of the dialog at the top." # name, x, y, w, h, flags=Visible|Enabled|Transparent|NoPrefix, # text, in VerdanaBold10 self.text("Title", 15, 10, 320, 60, 0x30003, r"{\VerdanaBold10}%s" % title) def back(self, title, next, name = "Back", active = 1): """Add a back button with a given title, the tab-next button, its name in the Control table, possibly initially disabled. Return the button, so that events can be associated""" if active: flags = 3 # Visible|Enabled else: flags = 1 # Visible return self.pushbutton(name, 180, self.h-27 , 56, 17, flags, title, next) def cancel(self, title, next, name = "Cancel", active = 1): """Add a cancel button with a given title, the tab-next button, its name in the Control table, possibly initially disabled. Return the button, so that events can be associated""" if active: flags = 3 # Visible|Enabled else: flags = 1 # Visible return self.pushbutton(name, 304, self.h-27, 56, 17, flags, title, next) def next(self, title, next, name = "Next", active = 1): """Add a Next button with a given title, the tab-next button, its name in the Control table, possibly initially disabled. Return the button, so that events can be associated""" if active: flags = 3 # Visible|Enabled else: flags = 1 # Visible return self.pushbutton(name, 236, self.h-27, 56, 17, flags, title, next) def xbutton(self, name, title, next, xpos): """Add a button with a given title, the tab-next button, its name in the Control table, giving its x position; the y-position is aligned with the other buttons. Return the button, so that events can be associated""" return self.pushbutton(name, int(self.w*xpos - 28), self.h-27, 56, 17, 3, title, next) class bdist_msi (Command): description = "create a Microsoft Installer (.msi) binary distribution" user_options = [('bdist-dir=', None, "temporary directory for creating the distribution"), ('keep-temp', 'k', "keep the pseudo-installation tree around after " + "creating the distribution archive"), ('target-version=', None, "require a specific python version" + " on the target system"), ('no-target-compile', 'c', "do not compile .py to .pyc on the target system"), ('no-target-optimize', 'o', "do not compile .py to .pyo (optimized)" "on the target system"), ('dist-dir=', 'd', "directory to put final built distributions in"), ('skip-build', None, "skip rebuilding everything (for testing/debugging)"), ('install-script=', None, "basename of installation script to be run after" "installation or before deinstallation"), ('pre-install-script=', None, "Fully qualified filename of a script to be run before " "any files are installed. This script need not be in the " "distribution"), ] boolean_options = ['keep-temp', 'no-target-compile', 'no-target-optimize', 'skip-build'] def initialize_options (self): self.bdist_dir = None self.keep_temp = 0 self.no_target_compile = 0 self.no_target_optimize = 0 self.target_version = None self.dist_dir = None self.skip_build = 0 self.install_script = None self.pre_install_script = None def finalize_options (self): if self.bdist_dir is None: bdist_base = self.get_finalized_command('bdist').bdist_base self.bdist_dir = os.path.join(bdist_base, 'msi') short_version = get_python_version() if self.target_version: if not self.skip_build and self.distribution.has_ext_modules()\ and self.target_version != short_version: raise DistutilsOptionError, \ "target version can only be %s, or the '--skip_build'" \ " option must be specified" % (short_version,) else: self.target_version = short_version self.set_undefined_options('bdist', ('dist_dir', 'dist_dir')) if self.pre_install_script: raise DistutilsOptionError, "the pre-install-script feature is not yet implemented" if self.install_script: for script in self.distribution.scripts: if self.install_script == os.path.basename(script): break else: raise DistutilsOptionError, \ "install_script '%s' not found in scripts" % \ self.install_script self.install_script_key = None # finalize_options() def run (self): if not self.skip_build: self.run_command('build') install = self.reinitialize_command('install', reinit_subcommands=1) install.prefix = self.bdist_dir install.skip_build = self.skip_build install.warn_dir = 0 install_lib = self.reinitialize_command('install_lib') # we do not want to include pyc or pyo files install_lib.compile = 0 install_lib.optimize = 0 if self.distribution.has_ext_modules(): # If we are building an installer for a Python version other # than the one we are currently running, then we need to ensure # our build_lib reflects the other Python version rather than ours. # Note that for target_version!=sys.version, we must have skipped the # build step, so there is no issue with enforcing the build of this # version. target_version = self.target_version if not target_version: assert self.skip_build, "Should have already checked this" target_version = sys.version[0:3] plat_specifier = ".%s-%s" % (get_platform(), target_version) build = self.get_finalized_command('build') build.build_lib = os.path.join(build.build_base, 'lib' + plat_specifier) log.info("installing to %s", self.bdist_dir) install.ensure_finalized() # avoid warning of 'install_lib' about installing # into a directory not in sys.path sys.path.insert(0, os.path.join(self.bdist_dir, 'PURELIB')) install.run() del sys.path[0] self.mkpath(self.dist_dir) fullname = self.distribution.get_fullname() installer_name = self.get_installer_filename(fullname) installer_name = os.path.abspath(installer_name) if os.path.exists(installer_name): os.unlink(installer_name) metadata = self.distribution.metadata author = metadata.author if not author: author = metadata.maintainer if not author: author = "UNKNOWN" version = metadata.get_version() # ProductVersion must be strictly numeric # XXX need to deal with prerelease versions sversion = "%d.%d.%d" % StrictVersion(version).version # Prefix ProductName with Python x.y, so that # it sorts together with the other Python packages # in Add-Remove-Programs (APR) product_name = "Python %s %s" % (self.target_version, self.distribution.get_fullname()) self.db = msilib.init_database(installer_name, schema, product_name, msilib.gen_uuid(), sversion, author) msilib.add_tables(self.db, sequence) props = [('DistVersion', version)] email = metadata.author_email or metadata.maintainer_email if email: props.append(("ARPCONTACT", email)) if metadata.url: props.append(("ARPURLINFOABOUT", metadata.url)) if props: add_data(self.db, 'Property', props) self.add_find_python() self.add_files() self.add_scripts() self.add_ui() self.db.Commit() if hasattr(self.distribution, 'dist_files'): self.distribution.dist_files.append(('bdist_msi', self.target_version, fullname)) if not self.keep_temp: remove_tree(self.bdist_dir, dry_run=self.dry_run) def add_files(self): db = self.db cab = msilib.CAB("distfiles") f = Feature(db, "default", "Default Feature", "Everything", 1, directory="TARGETDIR") f.set_current() rootdir = os.path.abspath(self.bdist_dir) root = Directory(db, cab, None, rootdir, "TARGETDIR", "SourceDir") db.Commit() todo = [root] while todo: dir = todo.pop() for file in os.listdir(dir.absolute): afile = os.path.join(dir.absolute, file) if os.path.isdir(afile): newdir = Directory(db, cab, dir, file, file, "%s|%s" % (dir.make_short(file), file)) todo.append(newdir) else: key = dir.add_file(file) if file==self.install_script: if self.install_script_key: raise DistutilsOptionError, "Multiple files with name %s" % file self.install_script_key = '[#%s]' % key cab.commit(db) def add_find_python(self): """Adds code to the installer to compute the location of Python. Properties PYTHON.MACHINE, PYTHON.USER, PYTHONDIR and PYTHON will be set in both the execute and UI sequences; PYTHONDIR will be set from PYTHON.USER if defined, else from PYTHON.MACHINE. PYTHON is PYTHONDIR\python.exe""" install_path = r"SOFTWARE\Python\PythonCore\%s\InstallPath" % self.target_version add_data(self.db, "RegLocator", [("python.machine", 2, install_path, None, 2), ("python.user", 1, install_path, None, 2)]) add_data(self.db, "AppSearch", [("PYTHON.MACHINE", "python.machine"), ("PYTHON.USER", "python.user")]) add_data(self.db, "CustomAction", [("PythonFromMachine", 51+256, "PYTHONDIR", "[PYTHON.MACHINE]"), ("PythonFromUser", 51+256, "PYTHONDIR", "[PYTHON.USER]"), ("PythonExe", 51+256, "PYTHON", "[PYTHONDIR]\\python.exe"), ("InitialTargetDir", 51+256, "TARGETDIR", "[PYTHONDIR]")]) add_data(self.db, "InstallExecuteSequence", [("PythonFromMachine", "PYTHON.MACHINE", 401), ("PythonFromUser", "PYTHON.USER", 402), ("PythonExe", None, 403), ("InitialTargetDir", 'TARGETDIR=""', 404), ]) add_data(self.db, "InstallUISequence", [("PythonFromMachine", "PYTHON.MACHINE", 401), ("PythonFromUser", "PYTHON.USER", 402), ("PythonExe", None, 403), ("InitialTargetDir", 'TARGETDIR=""', 404), ]) def add_scripts(self): if self.install_script: add_data(self.db, "CustomAction", [("install_script", 50, "PYTHON", self.install_script_key)]) add_data(self.db, "InstallExecuteSequence", [("install_script", "NOT Installed", 6800)]) if self.pre_install_script: scriptfn = os.path.join(self.bdist_dir, "preinstall.bat") f = open(scriptfn, "w") # The batch file will be executed with [PYTHON], so that %1 # is the path to the Python interpreter; %0 will be the path # of the batch file. # rem =""" # %1 %0 # exit # """ # <actual script> f.write('rem ="""\n%1 %0\nexit\n"""\n') f.write(open(self.pre_install_script).read()) f.close() add_data(self.db, "Binary", [("PreInstall", msilib.Binary(scriptfn)) ]) add_data(self.db, "CustomAction", [("PreInstall", 2, "PreInstall", None) ]) add_data(self.db, "InstallExecuteSequence", [("PreInstall", "NOT Installed", 450)]) def add_ui(self): db = self.db x = y = 50 w = 370 h = 300 title = "[ProductName] Setup" # see "Dialog Style Bits" modal = 3 # visible | modal modeless = 1 # visible track_disk_space = 32 # UI customization properties add_data(db, "Property", # See "DefaultUIFont Property" [("DefaultUIFont", "DlgFont8"), # See "ErrorDialog Style Bit" ("ErrorDialog", "ErrorDlg"), ("Progress1", "Install"), # modified in maintenance type dlg ("Progress2", "installs"), ("MaintenanceForm_Action", "Repair"), # possible values: ALL, JUSTME ("WhichUsers", "ALL") ]) # Fonts, see "TextStyle Table" add_data(db, "TextStyle", [("DlgFont8", "Tahoma", 9, None, 0), ("DlgFontBold8", "Tahoma", 8, None, 1), #bold ("VerdanaBold10", "Verdana", 10, None, 1), ("VerdanaRed9", "Verdana", 9, 255, 0), ]) # UI Sequences, see "InstallUISequence Table", "Using a Sequence Table" # Numbers indicate sequence; see sequence.py for how these action integrate add_data(db, "InstallUISequence", [("PrepareDlg", "Not Privileged or Windows9x or Installed", 140), ("WhichUsersDlg", "Privileged and not Windows9x and not Installed", 141), # In the user interface, assume all-users installation if privileged. ("SelectDirectoryDlg", "Not Installed", 1230), # XXX no support for resume installations yet #("ResumeDlg", "Installed AND (RESUME OR Preselected)", 1240), ("MaintenanceTypeDlg", "Installed AND NOT RESUME AND NOT Preselected", 1250), ("ProgressDlg", None, 1280)]) add_data(db, 'ActionText', text.ActionText) add_data(db, 'UIText', text.UIText) ##################################################################### # Standard dialogs: FatalError, UserExit, ExitDialog fatal=PyDialog(db, "FatalError", x, y, w, h, modal, title, "Finish", "Finish", "Finish") fatal.title("[ProductName] Installer ended prematurely") fatal.back("< Back", "Finish", active = 0) fatal.cancel("Cancel", "Back", active = 0) fatal.text("Description1", 15, 70, 320, 80, 0x30003, "[ProductName] setup ended prematurely because of an error. Your system has not been modified. To install this program at a later time, please run the installation again.") fatal.text("Description2", 15, 155, 320, 20, 0x30003, "Click the Finish button to exit the Installer.") c=fatal.next("Finish", "Cancel", name="Finish") c.event("EndDialog", "Exit") user_exit=PyDialog(db, "UserExit", x, y, w, h, modal, title, "Finish", "Finish", "Finish") user_exit.title("[ProductName] Installer was interrupted") user_exit.back("< Back", "Finish", active = 0) user_exit.cancel("Cancel", "Back", active = 0) user_exit.text("Description1", 15, 70, 320, 80, 0x30003, "[ProductName] setup was interrupted. Your system has not been modified. " "To install this program at a later time, please run the installation again.") user_exit.text("Description2", 15, 155, 320, 20, 0x30003, "Click the Finish button to exit the Installer.") c = user_exit.next("Finish", "Cancel", name="Finish") c.event("EndDialog", "Exit") exit_dialog = PyDialog(db, "ExitDialog", x, y, w, h, modal, title, "Finish", "Finish", "Finish") exit_dialog.title("Completing the [ProductName] Installer") exit_dialog.back("< Back", "Finish", active = 0) exit_dialog.cancel("Cancel", "Back", active = 0) exit_dialog.text("Description", 15, 235, 320, 20, 0x30003, "Click the Finish button to exit the Installer.") c = exit_dialog.next("Finish", "Cancel", name="Finish") c.event("EndDialog", "Return") ##################################################################### # Required dialog: FilesInUse, ErrorDlg inuse = PyDialog(db, "FilesInUse", x, y, w, h, 19, # KeepModeless|Modal|Visible title, "Retry", "Retry", "Retry", bitmap=False) inuse.text("Title", 15, 6, 200, 15, 0x30003, r"{\DlgFontBold8}Files in Use") inuse.text("Description", 20, 23, 280, 20, 0x30003, "Some files that need to be updated are currently in use.") inuse.text("Text", 20, 55, 330, 50, 3, "The following applications are using files that need to be updated by this setup. Close these applications and then click Retry to continue the installation or Cancel to exit it.") inuse.control("List", "ListBox", 20, 107, 330, 130, 7, "FileInUseProcess", None, None, None) c=inuse.back("Exit", "Ignore", name="Exit") c.event("EndDialog", "Exit") c=inuse.next("Ignore", "Retry", name="Ignore") c.event("EndDialog", "Ignore") c=inuse.cancel("Retry", "Exit", name="Retry") c.event("EndDialog","Retry") # See "Error Dialog". See "ICE20" for the required names of the controls. error = Dialog(db, "ErrorDlg", 50, 10, 330, 101, 65543, # Error|Minimize|Modal|Visible title, "ErrorText", None, None) error.text("ErrorText", 50,9,280,48,3, "") #error.control("ErrorIcon", "Icon", 15, 9, 24, 24, 5242881, None, "py.ico", None, None) error.pushbutton("N",120,72,81,21,3,"No",None).event("EndDialog","ErrorNo") error.pushbutton("Y",240,72,81,21,3,"Yes",None).event("EndDialog","ErrorYes") error.pushbutton("A",0,72,81,21,3,"Abort",None).event("EndDialog","ErrorAbort") error.pushbutton("C",42,72,81,21,3,"Cancel",None).event("EndDialog","ErrorCancel") error.pushbutton("I",81,72,81,21,3,"Ignore",None).event("EndDialog","ErrorIgnore") error.pushbutton("O",159,72,81,21,3,"Ok",None).event("EndDialog","ErrorOk") error.pushbutton("R",198,72,81,21,3,"Retry",None).event("EndDialog","ErrorRetry") ##################################################################### # Global "Query Cancel" dialog cancel = Dialog(db, "CancelDlg", 50, 10, 260, 85, 3, title, "No", "No", "No") cancel.text("Text", 48, 15, 194, 30, 3, "Are you sure you want to cancel [ProductName] installation?") #cancel.control("Icon", "Icon", 15, 15, 24, 24, 5242881, None, # "py.ico", None, None) c=cancel.pushbutton("Yes", 72, 57, 56, 17, 3, "Yes", "No") c.event("EndDialog", "Exit") c=cancel.pushbutton("No", 132, 57, 56, 17, 3, "No", "Yes") c.event("EndDialog", "Return") ##################################################################### # Global "Wait for costing" dialog costing = Dialog(db, "WaitForCostingDlg", 50, 10, 260, 85, modal, title, "Return", "Return", "Return") costing.text("Text", 48, 15, 194, 30, 3, "Please wait while the installer finishes determining your disk space requirements.") c = costing.pushbutton("Return", 102, 57, 56, 17, 3, "Return", None) c.event("EndDialog", "Exit") ##################################################################### # Preparation dialog: no user input except cancellation prep = PyDialog(db, "PrepareDlg", x, y, w, h, modeless, title, "Cancel", "Cancel", "Cancel") prep.text("Description", 15, 70, 320, 40, 0x30003, "Please wait while the Installer prepares to guide you through the installation.") prep.title("Welcome to the [ProductName] Installer") c=prep.text("ActionText", 15, 110, 320, 20, 0x30003, "Pondering...") c.mapping("ActionText", "Text") c=prep.text("ActionData", 15, 135, 320, 30, 0x30003, None) c.mapping("ActionData", "Text") prep.back("Back", None, active=0) prep.next("Next", None, active=0) c=prep.cancel("Cancel", None) c.event("SpawnDialog", "CancelDlg") ##################################################################### # Target directory selection seldlg = PyDialog(db, "SelectDirectoryDlg", x, y, w, h, modal, title, "Next", "Next", "Cancel") seldlg.title("Select Destination Directory") version = sys.version[:3]+" " seldlg.text("Hint", 15, 30, 300, 40, 3, "The destination directory should contain a Python %sinstallation" % version) seldlg.back("< Back", None, active=0) c = seldlg.next("Next >", "Cancel") c.event("SetTargetPath", "TARGETDIR", ordering=1) c.event("SpawnWaitDialog", "WaitForCostingDlg", ordering=2) c.event("EndDialog", "Return", ordering=3) c = seldlg.cancel("Cancel", "DirectoryCombo") c.event("SpawnDialog", "CancelDlg") seldlg.control("DirectoryCombo", "DirectoryCombo", 15, 70, 272, 80, 393219, "TARGETDIR", None, "DirectoryList", None) seldlg.control("DirectoryList", "DirectoryList", 15, 90, 308, 136, 3, "TARGETDIR", None, "PathEdit", None) seldlg.control("PathEdit", "PathEdit", 15, 230, 306, 16, 3, "TARGETDIR", None, "Next", None) c = seldlg.pushbutton("Up", 306, 70, 18, 18, 3, "Up", None) c.event("DirectoryListUp", "0") c = seldlg.pushbutton("NewDir", 324, 70, 30, 18, 3, "New", None) c.event("DirectoryListNew", "0") ##################################################################### # Disk cost cost = PyDialog(db, "DiskCostDlg", x, y, w, h, modal, title, "OK", "OK", "OK", bitmap=False) cost.text("Title", 15, 6, 200, 15, 0x30003, "{\DlgFontBold8}Disk Space Requirements") cost.text("Description", 20, 20, 280, 20, 0x30003, "The disk space required for the installation of the selected features.") cost.text("Text", 20, 53, 330, 60, 3, "The highlighted volumes (if any) do not have enough disk space " "available for the currently selected features. You can either " "remove some files from the highlighted volumes, or choose to " "install less features onto local drive(s), or select different " "destination drive(s).") cost.control("VolumeList", "VolumeCostList", 20, 100, 330, 150, 393223, None, "{120}{70}{70}{70}{70}", None, None) cost.xbutton("OK", "Ok", None, 0.5).event("EndDialog", "Return") ##################################################################### # WhichUsers Dialog. Only available on NT, and for privileged users. # This must be run before FindRelatedProducts, because that will # take into account whether the previous installation was per-user # or per-machine. We currently don't support going back to this # dialog after "Next" was selected; to support this, we would need to # find how to reset the ALLUSERS property, and how to re-run # FindRelatedProducts. # On Windows9x, the ALLUSERS property is ignored on the command line # and in the Property table, but installer fails according to the documentation # if a dialog attempts to set ALLUSERS. whichusers = PyDialog(db, "WhichUsersDlg", x, y, w, h, modal, title, "AdminInstall", "Next", "Cancel") whichusers.title("Select whether to install [ProductName] for all users of this computer.") # A radio group with two options: allusers, justme g = whichusers.radiogroup("AdminInstall", 15, 60, 260, 50, 3, "WhichUsers", "", "Next") g.add("ALL", 0, 5, 150, 20, "Install for all users") g.add("JUSTME", 0, 25, 150, 20, "Install just for me") whichusers.back("Back", None, active=0) c = whichusers.next("Next >", "Cancel") c.event("[ALLUSERS]", "1", 'WhichUsers="ALL"', 1) c.event("EndDialog", "Return", ordering = 2) c = whichusers.cancel("Cancel", "AdminInstall") c.event("SpawnDialog", "CancelDlg") ##################################################################### # Installation Progress dialog (modeless) progress = PyDialog(db, "ProgressDlg", x, y, w, h, modeless, title, "Cancel", "Cancel", "Cancel", bitmap=False) progress.text("Title", 20, 15, 200, 15, 0x30003, "{\DlgFontBold8}[Progress1] [ProductName]") progress.text("Text", 35, 65, 300, 30, 3, "Please wait while the Installer [Progress2] [ProductName]. " "This may take several minutes.") progress.text("StatusLabel", 35, 100, 35, 20, 3, "Status:") c=progress.text("ActionText", 70, 100, w-70, 20, 3, "Pondering...") c.mapping("ActionText", "Text") #c=progress.text("ActionData", 35, 140, 300, 20, 3, None) #c.mapping("ActionData", "Text") c=progress.control("ProgressBar", "ProgressBar", 35, 120, 300, 10, 65537, None, "Progress done", None, None) c.mapping("SetProgress", "Progress") progress.back("< Back", "Next", active=False) progress.next("Next >", "Cancel", active=False) progress.cancel("Cancel", "Back").event("SpawnDialog", "CancelDlg") ################################################################### # Maintenance type: repair/uninstall maint = PyDialog(db, "MaintenanceTypeDlg", x, y, w, h, modal, title, "Next", "Next", "Cancel") maint.title("Welcome to the [ProductName] Setup Wizard") maint.text("BodyText", 15, 63, 330, 42, 3, "Select whether you want to repair or remove [ProductName].") g=maint.radiogroup("RepairRadioGroup", 15, 108, 330, 60, 3, "MaintenanceForm_Action", "", "Next") #g.add("Change", 0, 0, 200, 17, "&Change [ProductName]") g.add("Repair", 0, 18, 200, 17, "&Repair [ProductName]") g.add("Remove", 0, 36, 200, 17, "Re&move [ProductName]") maint.back("< Back", None, active=False) c=maint.next("Finish", "Cancel") # Change installation: Change progress dialog to "Change", then ask # for feature selection #c.event("[Progress1]", "Change", 'MaintenanceForm_Action="Change"', 1) #c.event("[Progress2]", "changes", 'MaintenanceForm_Action="Change"', 2) # Reinstall: Change progress dialog to "Repair", then invoke reinstall # Also set list of reinstalled features to "ALL" c.event("[REINSTALL]", "ALL", 'MaintenanceForm_Action="Repair"', 5) c.event("[Progress1]", "Repairing", 'MaintenanceForm_Action="Repair"', 6) c.event("[Progress2]", "repairs", 'MaintenanceForm_Action="Repair"', 7) c.event("Reinstall", "ALL", 'MaintenanceForm_Action="Repair"', 8) # Uninstall: Change progress to "Remove", then invoke uninstall # Also set list of removed features to "ALL" c.event("[REMOVE]", "ALL", 'MaintenanceForm_Action="Remove"', 11) c.event("[Progress1]", "Removing", 'MaintenanceForm_Action="Remove"', 12) c.event("[Progress2]", "removes", 'MaintenanceForm_Action="Remove"', 13) c.event("Remove", "ALL", 'MaintenanceForm_Action="Remove"', 14) # Close dialog when maintenance action scheduled c.event("EndDialog", "Return", 'MaintenanceForm_Action<>"Change"', 20) #c.event("NewDialog", "SelectFeaturesDlg", 'MaintenanceForm_Action="Change"', 21) maint.cancel("Cancel", "RepairRadioGroup").event("SpawnDialog", "CancelDlg") def get_installer_filename(self, fullname): # Factored out to allow overriding in subclasses installer_name = os.path.join(self.dist_dir, "%s.win32-py%s.msi" % (fullname, self.target_version)) return installer_name
apache-2.0
LiangfengD/code-for-blog
2009/pygame_creeps_game/utils.py
12
1122
class Timer(object): """ A Timer that can periodically call a given callback function. After creation, you should call update() with the amount of time passed since the last call to update() in milliseconds. The callback calls will result synchronously during these calls to update() """ def __init__(self, interval, callback, oneshot=False): """ Create a new Timer. interval: The timer interval in milliseconds callback: Callable, to call when each interval expires oneshot: True for a timer that only acts once """ self.interval = interval self.callback = callback self.oneshot = oneshot self.time = 0 self.alive = True def update(self, time_passed): if not self.alive: return self.time += time_passed if self.time > self.interval: self.time -= self.interval self.callback() if self.oneshot: self.alive = False
unlicense
muffl0n/ansible-modules-extras
packaging/os/pkgng.py
60
11130
#!/usr/bin/python # -*- coding: utf-8 -*- # (c) 2013, bleader # Written by bleader <bleader@ratonland.org> # Based on pkgin module written by Shaun Zinck <shaun.zinck at gmail.com> # that was based on pacman module written by Afterburn <http://github.com/afterburn> # that was based on apt module written by Matthew Williams <matthew@flowroute.com> # # This module is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This software is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this software. If not, see <http://www.gnu.org/licenses/>. DOCUMENTATION = ''' --- module: pkgng short_description: Package manager for FreeBSD >= 9.0 description: - Manage binary packages for FreeBSD using 'pkgng' which is available in versions after 9.0. version_added: "1.2" options: name: description: - name of package to install/remove required: true state: description: - state of the package choices: [ 'present', 'absent' ] required: false default: present cached: description: - use local package base or try to fetch an updated one choices: [ 'yes', 'no' ] required: false default: no annotation: description: - a comma-separated list of keyvalue-pairs of the form <+/-/:><key>[=<value>]. A '+' denotes adding an annotation, a '-' denotes removing an annotation, and ':' denotes modifying an annotation. If setting or modifying annotations, a value must be provided. required: false version_added: "1.6" pkgsite: description: - for pkgng versions before 1.1.4, specify packagesite to use for downloading packages, if not specified, use settings from /usr/local/etc/pkg.conf for newer pkgng versions, specify a the name of a repository configured in /usr/local/etc/pkg/repos required: false rootdir: description: - for pkgng versions 1.5 and later, pkg will install all packages within the specified root directory required: false author: "bleader (@bleader)" notes: - When using pkgsite, be careful that already in cache packages won't be downloaded again. ''' EXAMPLES = ''' # Install package foo - pkgng: name=foo state=present # Annotate package foo and bar - pkgng: name=foo,bar annotation=+test1=baz,-test2,:test3=foobar # Remove packages foo and bar - pkgng: name=foo,bar state=absent ''' import json import shlex import os import re import sys def query_package(module, pkgng_path, name, rootdir_arg): rc, out, err = module.run_command("%s %s info -g -e %s" % (pkgng_path, rootdir_arg, name)) if rc == 0: return True return False def pkgng_older_than(module, pkgng_path, compare_version): rc, out, err = module.run_command("%s -v" % pkgng_path) version = map(lambda x: int(x), re.split(r'[\._]', out)) i = 0 new_pkgng = True while compare_version[i] == version[i]: i += 1 if i == min(len(compare_version), len(version)): break else: if compare_version[i] > version[i]: new_pkgng = False return not new_pkgng def remove_packages(module, pkgng_path, packages, rootdir_arg): remove_c = 0 # Using a for loop incase of error, we can report the package that failed for package in packages: # Query the package first, to see if we even need to remove if not query_package(module, pkgng_path, package, rootdir_arg): continue if not module.check_mode: rc, out, err = module.run_command("%s %s delete -y %s" % (pkgng_path, rootdir_arg, package)) if not module.check_mode and query_package(module, pkgng_path, package, rootdir_arg): module.fail_json(msg="failed to remove %s: %s" % (package, out)) remove_c += 1 if remove_c > 0: return (True, "removed %s package(s)" % remove_c) return (False, "package(s) already absent") def install_packages(module, pkgng_path, packages, cached, pkgsite, rootdir_arg): install_c = 0 # as of pkg-1.1.4, PACKAGESITE is deprecated in favor of repository definitions # in /usr/local/etc/pkg/repos old_pkgng = pkgng_older_than(module, pkgng_path, [1, 1, 4]) if pkgsite != "": if old_pkgng: pkgsite = "PACKAGESITE=%s" % (pkgsite) else: pkgsite = "-r %s" % (pkgsite) batch_var = 'env BATCH=yes' # This environment variable skips mid-install prompts, # setting them to their default values. if not module.check_mode and not cached: if old_pkgng: rc, out, err = module.run_command("%s %s update" % (pkgsite, pkgng_path)) else: rc, out, err = module.run_command("%s update" % (pkgng_path)) if rc != 0: module.fail_json(msg="Could not update catalogue") for package in packages: if query_package(module, pkgng_path, package, rootdir_arg): continue if not module.check_mode: if old_pkgng: rc, out, err = module.run_command("%s %s %s install -g -U -y %s" % (batch_var, pkgsite, pkgng_path, package)) else: rc, out, err = module.run_command("%s %s %s install %s -g -U -y %s" % (batch_var, pkgng_path, rootdir_arg, pkgsite, package)) if not module.check_mode and not query_package(module, pkgng_path, package, rootdir_arg): module.fail_json(msg="failed to install %s: %s" % (package, out), stderr=err) install_c += 1 if install_c > 0: return (True, "added %s package(s)" % (install_c)) return (False, "package(s) already present") def annotation_query(module, pkgng_path, package, tag, rootdir_arg): rc, out, err = module.run_command("%s %s info -g -A %s" % (pkgng_path, rootdir_arg, package)) match = re.search(r'^\s*(?P<tag>%s)\s*:\s*(?P<value>\w+)' % tag, out, flags=re.MULTILINE) if match: return match.group('value') return False def annotation_add(module, pkgng_path, package, tag, value, rootdir_arg): _value = annotation_query(module, pkgng_path, package, tag, rootdir_arg) if not _value: # Annotation does not exist, add it. rc, out, err = module.run_command('%s %s annotate -y -A %s %s "%s"' % (pkgng_path, rootdir_arg, package, tag, value)) if rc != 0: module.fail_json("could not annotate %s: %s" % (package, out), stderr=err) return True elif _value != value: # Annotation exists, but value differs module.fail_json( mgs="failed to annotate %s, because %s is already set to %s, but should be set to %s" % (package, tag, _value, value)) return False else: # Annotation exists, nothing to do return False def annotation_delete(module, pkgng_path, package, tag, value, rootdir_arg): _value = annotation_query(module, pkgng_path, package, tag, rootdir_arg) if _value: rc, out, err = module.run_command('%s %s annotate -y -D %s %s' % (pkgng_path, rootdir_arg, package, tag)) if rc != 0: module.fail_json("could not delete annotation to %s: %s" % (package, out), stderr=err) return True return False def annotation_modify(module, pkgng_path, package, tag, value, rootdir_arg): _value = annotation_query(module, pkgng_path, package, tag, rootdir_arg) if not value: # No such tag module.fail_json("could not change annotation to %s: tag %s does not exist" % (package, tag)) elif _value == value: # No change in value return False else: rc,out,err = module.run_command('%s %s annotate -y -M %s %s "%s"' % (pkgng_path, rootdir_arg, package, tag, value)) if rc != 0: module.fail_json("could not change annotation annotation to %s: %s" % (package, out), stderr=err) return True def annotate_packages(module, pkgng_path, packages, annotation, rootdir_arg): annotate_c = 0 annotations = map(lambda _annotation: re.match(r'(?P<operation>[\+-:])(?P<tag>\w+)(=(?P<value>\w+))?', _annotation).groupdict(), re.split(r',', annotation)) operation = { '+': annotation_add, '-': annotation_delete, ':': annotation_modify } for package in packages: for _annotation in annotations: if operation[_annotation['operation']](module, pkgng_path, package, _annotation['tag'], _annotation['value']): annotate_c += 1 if annotate_c > 0: return (True, "added %s annotations." % annotate_c) return (False, "changed no annotations") def main(): module = AnsibleModule( argument_spec = dict( state = dict(default="present", choices=["present","absent"], required=False), name = dict(aliases=["pkg"], required=True), cached = dict(default=False, type='bool'), annotation = dict(default="", required=False), pkgsite = dict(default="", required=False), rootdir = dict(default="", required=False)), supports_check_mode = True) pkgng_path = module.get_bin_path('pkg', True) p = module.params pkgs = p["name"].split(",") changed = False msgs = [] rootdir_arg = "" if p["rootdir"] != "": old_pkgng = pkgng_older_than(module, pkgng_path, [1, 5, 0]) if old_pkgng: module.fail_json(msg="To use option 'rootdir' pkg version must be 1.5 or greater") else: rootdir_arg = "--rootdir %s" % (p["rootdir"]) if p["state"] == "present": _changed, _msg = install_packages(module, pkgng_path, pkgs, p["cached"], p["pkgsite"], rootdir_arg) changed = changed or _changed msgs.append(_msg) elif p["state"] == "absent": _changed, _msg = remove_packages(module, pkgng_path, pkgs, rootdir_arg) changed = changed or _changed msgs.append(_msg) if p["annotation"]: _changed, _msg = annotate_packages(module, pkgng_path, pkgs, p["annotation"], rootdir_arg) changed = changed or _changed msgs.append(_msg) module.exit_json(changed=changed, msg=", ".join(msgs)) # import module snippets from ansible.module_utils.basic import * main()
gpl-3.0
RickMohr/otm-core
opentreemap/opentreemap/context_processors.py
3
2411
# -*- coding: utf-8 -*- from __future__ import print_function from __future__ import unicode_literals from __future__ import division import copy from django.conf import settings from django.contrib.staticfiles import finders from django.utils.timezone import now from django.utils.translation import ugettext as _ from treemap.util import get_last_visited_instance from treemap.models import InstanceUser REPLACEABLE_TERMS = { 'Resource': {'singular': _('Resource'), 'plural': _('Resources')} } def global_settings(request): last_instance = get_last_visited_instance(request) if hasattr(request, 'user') and request.user.is_authenticated(): last_effective_instance_user =\ request.user.get_effective_instance_user(last_instance) _update_last_seen(last_effective_instance_user) else: if hasattr(request, 'instance'): instance = request.instance default_role = instance.default_role last_effective_instance_user = InstanceUser( role=default_role, instance=instance) else: last_effective_instance_user = None if hasattr(request, 'instance') and request.instance.logo: logo_url = request.instance.logo.url else: logo_url = settings.STATIC_URL + "img/logo.png" try: comment_file_path = finders.find('version.txt') with open(comment_file_path, 'r') as f: header_comment = f.read() except: header_comment = "Version information not available\n" term = copy.copy(REPLACEABLE_TERMS) if hasattr(request, 'instance'): term.update(request.instance.config.get('terms', {})) ctx = { 'SITE_ROOT': settings.SITE_ROOT, 'settings': settings, 'last_instance': last_instance, 'last_effective_instance_user': last_effective_instance_user, 'logo_url': logo_url, 'header_comment': header_comment, 'term': term, } return ctx def _update_last_seen(last_effective_instance_user): # Update the instance user's "last seen" date if necessary. # Done here instead of in middleware to avoid looking up # the request's InstanceUser again. iu = last_effective_instance_user today = now().date() if iu and iu.id and (not iu.last_seen or iu.last_seen < today): iu.last_seen = today iu.save_base()
agpl-3.0
boto/botoflow
botoflow/constants.py
2
3075
# Copyright 2013 Amazon.com, Inc. or its affiliates. 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. # A copy of the License is located at # # http://aws.amazon.com/apache2.0 # # or in the "license" file accompanying this file. This file 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. """This module contains various workflow, activity and time constants. Tasklist settings +++++++++++++++++ .. py:data:: USE_WORKER_TASK_LIST Use task list of the ActivityWorker or WorkflowWorker that is used to register activity or workflow as the default task list for the activity or workflow type. .. py:data:: NO_DEFAULT_TASK_LIST Do not specify task list on registration. Which means that task list is required when scheduling activity. Child workflow termination policy settings ++++++++++++++++++++++++++++++++++++++++++ You can learn more about *Child Workflows* from the official `SWF Developer Guide <http://docs.aws.amazon.com/amazonswf/latest/developerguide/swf-dg-adv.html#swf-dev-adv-child-workflows>`_. .. py:data:: CHILD_TERMINATE The child executions will be terminated. .. py:data:: CHILD_REQUEST_CANCEL Request to cancel will be attempted for each child execution by recording a :py:class:`~botoflow.history_events.events.WorkflowExecutionCancelRequested` event in its history. It is up to the decider to take appropriate actions when it receives an execution history with this event. .. py:data:: CHILD_ABANDON Child policy to abandon the parent workflow. If there are any child workflows still running the will be allowed to continue without notice. Time multipliers ++++++++++++++++ The time multiplier constants are just an attempt at making setting various workflow or activity timeouts more readable. Consider the following examples and their readability: .. code-block:: python @activities(schedule_to_start_timeout=120, start_to_close_timeout=23400) class ImportantBusinessActivities(object): ... # using the time multiplier constants from botoflow.constants import MINUTES, HOURS @activities(schedule_to_start_timeout=2*MINUTES, start_to_close_timeout=30*MINUTES + 6*HOURS) class ImportantBusinessActivities(object): ... .. py:data:: SECONDS ``2*SECONDS = 2`` .. py:data:: MINUTES ``2*MINUTES = 120`` .. py:data:: HOURS ``2*HOURS = 7200`` .. py:data:: DAYS ``2*DAYS = 172800`` .. py:data:: WEEKS ``2*WEEKS = 1209600`` """ # TASK LIST SETTINGS USE_WORKER_TASK_LIST = "USE_WORKER_TASK_LIST" NO_DEFAULT_TASK_LIST = "NO_DEFAULT_TASK_LIST" # CHILD POLICIES CHILD_TERMINATE = "TERMINATE" CHILD_REQUEST_CANCEL = "REQUEST_CANCEL" CHILD_ABANDON = "ABANDON" # TIME MULTIPLIERS SECONDS = 1 MINUTES = 60 HOURS = 3600 DAYS = 86400 WEEKS = 604800
apache-2.0
FluidityStokes/fluidity
tests/mms_tracer_P1dg_cdg_diff_steady_3d_cjc_inhNmnnbc/cdg3d.py
1
1504
import os from fluidity_tools import stat_parser from sympy import * from numpy import array,max,abs meshtemplate=''' Point(1) = {0.0,0.0,0,0.1}; Extrude {1,0,0} { Point{1}; Layers{<layers>}; } Extrude {0,1,0} { Line{1}; Layers{<layers>}; } Extrude {0,0,1} { Surface{5}; Layers{<layers>}; } //Z-normal surface, z=0 Physical Surface(28) = {5}; //Z-normal surface, z=1 Physical Surface(29) = {27}; //Y-normal surface, y=0 Physical Surface(30) = {14}; //Y-normal surface, y=1 Physical Surface(31) = {22}; //X-normal surface, x=0 Physical Surface(32) = {26}; //X-normal surface, x=1 Physical Surface(33) = {18}; Physical Volume(34) = {1}; ''' def generate_meshfile(name,layers): geo = meshtemplate.replace('<layers>',str(layers)) open(name+".geo",'w').write(geo) os.system("gmsh -3 "+name+".geo") os.system("../../bin/gmsh2triangle "+name+".msh") def run_test(layers, binary): '''run_test(layers, binary) Run a single test of the channel problem. Layers is the number of mesh points in the cross-channel direction. The mesh is unstructured and isotropic. binary is a string containing the fluidity command to run. The return value is the error in u and p at the end of the simulation.''' generate_meshfile("channel",layers) os.system(binary+" channel_viscous.flml") s=stat_parser("channel-flow-dg.stat") return (s["Water"]['AnalyticUVelocitySolutionError']['l2norm'][-1], s["Water"]['AnalyticPressureSolutionError']['l2norm'][-1])
lgpl-2.1
jpush/jbox
Server/venv/lib/python3.5/site-packages/werkzeug/_reloader.py
144
8336
import os import sys import time import subprocess import threading from itertools import chain from werkzeug._internal import _log from werkzeug._compat import PY2, iteritems, text_type def _iter_module_files(): """This iterates over all relevant Python files. It goes through all loaded files from modules, all files in folders of already loaded modules as well as all files reachable through a package. """ # The list call is necessary on Python 3 in case the module # dictionary modifies during iteration. for module in list(sys.modules.values()): if module is None: continue filename = getattr(module, '__file__', None) if filename: old = None while not os.path.isfile(filename): old = filename filename = os.path.dirname(filename) if filename == old: break else: if filename[-4:] in ('.pyc', '.pyo'): filename = filename[:-1] yield filename def _find_observable_paths(extra_files=None): """Finds all paths that should be observed.""" rv = set(os.path.abspath(x) for x in sys.path) for filename in extra_files or (): rv.add(os.path.dirname(os.path.abspath(filename))) for module in list(sys.modules.values()): fn = getattr(module, '__file__', None) if fn is None: continue fn = os.path.abspath(fn) rv.add(os.path.dirname(fn)) return _find_common_roots(rv) def _find_common_roots(paths): """Out of some paths it finds the common roots that need monitoring.""" paths = [x.split(os.path.sep) for x in paths] root = {} for chunks in sorted(paths, key=len, reverse=True): node = root for chunk in chunks: node = node.setdefault(chunk, {}) node.clear() rv = set() def _walk(node, path): for prefix, child in iteritems(node): _walk(child, path + (prefix,)) if not node: rv.add('/'.join(path)) _walk(root, ()) return rv class ReloaderLoop(object): name = None # monkeypatched by testsuite. wrapping with `staticmethod` is required in # case time.sleep has been replaced by a non-c function (e.g. by # `eventlet.monkey_patch`) before we get here _sleep = staticmethod(time.sleep) def __init__(self, extra_files=None, interval=1): self.extra_files = set(os.path.abspath(x) for x in extra_files or ()) self.interval = interval def run(self): pass def restart_with_reloader(self): """Spawn a new Python interpreter with the same arguments as this one, but running the reloader thread. """ while 1: _log('info', ' * Restarting with %s' % self.name) args = [sys.executable] + sys.argv new_environ = os.environ.copy() new_environ['WERKZEUG_RUN_MAIN'] = 'true' # a weird bug on windows. sometimes unicode strings end up in the # environment and subprocess.call does not like this, encode them # to latin1 and continue. if os.name == 'nt' and PY2: for key, value in iteritems(new_environ): if isinstance(value, text_type): new_environ[key] = value.encode('iso-8859-1') exit_code = subprocess.call(args, env=new_environ, close_fds=False) if exit_code != 3: return exit_code def trigger_reload(self, filename): self.log_reload(filename) sys.exit(3) def log_reload(self, filename): filename = os.path.abspath(filename) _log('info', ' * Detected change in %r, reloading' % filename) class StatReloaderLoop(ReloaderLoop): name = 'stat' def run(self): mtimes = {} while 1: for filename in chain(_iter_module_files(), self.extra_files): try: mtime = os.stat(filename).st_mtime except OSError: continue old_time = mtimes.get(filename) if old_time is None: mtimes[filename] = mtime continue elif mtime > old_time: self.trigger_reload(filename) self._sleep(self.interval) class WatchdogReloaderLoop(ReloaderLoop): def __init__(self, *args, **kwargs): ReloaderLoop.__init__(self, *args, **kwargs) from watchdog.observers import Observer from watchdog.events import FileSystemEventHandler self.observable_paths = set() def _check_modification(filename): if filename in self.extra_files: self.trigger_reload(filename) dirname = os.path.dirname(filename) if dirname.startswith(tuple(self.observable_paths)): if filename.endswith(('.pyc', '.pyo')): self.trigger_reload(filename[:-1]) elif filename.endswith('.py'): self.trigger_reload(filename) class _CustomHandler(FileSystemEventHandler): def on_created(self, event): _check_modification(event.src_path) def on_modified(self, event): _check_modification(event.src_path) def on_moved(self, event): _check_modification(event.src_path) _check_modification(event.dest_path) def on_deleted(self, event): _check_modification(event.src_path) reloader_name = Observer.__name__.lower() if reloader_name.endswith('observer'): reloader_name = reloader_name[:-8] reloader_name += ' reloader' self.name = reloader_name self.observer_class = Observer self.event_handler = _CustomHandler() self.should_reload = False def trigger_reload(self, filename): # This is called inside an event handler, which means throwing # SystemExit has no effect. # https://github.com/gorakhargosh/watchdog/issues/294 self.should_reload = True self.log_reload(filename) def run(self): watches = {} observer = self.observer_class() observer.start() while not self.should_reload: to_delete = set(watches) paths = _find_observable_paths(self.extra_files) for path in paths: if path not in watches: try: watches[path] = observer.schedule( self.event_handler, path, recursive=True) except OSError: # Clear this path from list of watches We don't want # the same error message showing again in the next # iteration. watches[path] = None to_delete.discard(path) for path in to_delete: watch = watches.pop(path, None) if watch is not None: observer.unschedule(watch) self.observable_paths = paths self._sleep(self.interval) sys.exit(3) reloader_loops = { 'stat': StatReloaderLoop, 'watchdog': WatchdogReloaderLoop, } try: __import__('watchdog.observers') except ImportError: reloader_loops['auto'] = reloader_loops['stat'] else: reloader_loops['auto'] = reloader_loops['watchdog'] def run_with_reloader(main_func, extra_files=None, interval=1, reloader_type='auto'): """Run the given function in an independent python interpreter.""" import signal reloader = reloader_loops[reloader_type](extra_files, interval) signal.signal(signal.SIGTERM, lambda *args: sys.exit(0)) try: if os.environ.get('WERKZEUG_RUN_MAIN') == 'true': t = threading.Thread(target=main_func, args=()) t.setDaemon(True) t.start() reloader.run() else: sys.exit(reloader.restart_with_reloader()) except KeyboardInterrupt: pass
mit
hzlf/openbroadcast
website/apps/__rework_in_progress/importer/api.py
1
7486
from django.conf import settings from django.conf.urls.defaults import * from django.contrib.auth.models import User from django.db.models import Count import json from tastypie import fields from tastypie.authentication import * from tastypie.authorization import * from tastypie.resources import ModelResource, Resource, ALL, ALL_WITH_RELATIONS from tastypie.cache import SimpleCache from tastypie.utils import trailing_slash from tastypie.exceptions import ImmediateHttpResponse from django.http import HttpResponse from importer.models import Import, ImportFile from alibrary.api import MediaResource # file = request.FILES[u'files[]'] class ImportFileResource(ModelResource): import_session = fields.ForeignKey('importer.api.ImportResource', 'import_session', null=True, full=False) media = fields.ForeignKey('alibrary.api.MediaResource', 'media', null=True, full=True) class Meta: queryset = ImportFile.objects.all() list_allowed_methods = ['get', 'post'] detail_allowed_methods = ['get', 'post', 'put', 'delete'] resource_name = 'importfile' # excludes = ['type','results_musicbrainz'] excludes = ['type',] authentication = Authentication() authorization = Authorization() always_return_data = True filtering = { 'import_session': ALL_WITH_RELATIONS, 'created': ['exact', 'range', 'gt', 'gte', 'lt', 'lte'], } def dehydrate(self, bundle): bundle.data['status'] = bundle.obj.get_status_display().lower(); # offload json parsing to the backend # TODO: remove in js, enable here """ bundle.data['import_tag'] = json.loads(bundle.data['import_tag']) bundle.data['results_acoustid'] = json.loads(bundle.data['results_acoustid']) bundle.data['results_musicbrainz'] = json.loads(bundle.data['results_musicbrainz']) bundle.data['results_discogs'] = json.loads(bundle.data['results_discogs']) bundle.data['results_tag'] = json.loads(bundle.data['results_tag']) """ return bundle def obj_update(self, bundle, request, **kwargs): #import time #time.sleep(3) return super(ImportFileResource, self).obj_update(bundle, request, **kwargs) def obj_create(self, bundle, request, **kwargs): """ Little switch to play with jquery fileupload """ try: #import_id = request.GET['import_session'] import_id = request.GET.get('import_session', None) uuid_key = request.GET.get('uuid_key', None) print "####################################" print request.FILES[u'files[]'] if import_id: imp = Import.objects.get(pk=import_id) bundle.data['import_session'] = imp elif uuid_key: imp, created = Import.objects.get_or_create(uuid_key=uuid_key, user=request.user) bundle.data['import_session'] = imp else: bundle.data['import_session'] = None bundle.data['file'] = request.FILES[u'files[]'] except Exception, e: print e return super(ImportFileResource, self).obj_create(bundle, request, **kwargs) class ImportResource(ModelResource): files = fields.ToManyField('importer.api.ImportFileResource', 'files', full=True, null=True) class Meta: queryset = Import.objects.all() list_allowed_methods = ['get', 'post'] detail_allowed_methods = ['get', 'post', 'put', 'delete'] #list_allowed_methods = ['get',] #detail_allowed_methods = ['get',] resource_name = 'import' excludes = ['updated',] include_absolute_url = True authentication = Authentication() authorization = Authorization() always_return_data = True filtering = { #'channel': ALL_WITH_RELATIONS, 'created': ['exact', 'range', 'gt', 'gte', 'lt', 'lte'], } def save_related(self, obj): return True # additional methods def prepend_urls(self): return [ url(r"^(?P<resource_name>%s)/(?P<pk>\w[\w/-]*)/import-all%s$" % (self._meta.resource_name, trailing_slash()), self.wrap_view('import_all'), name="importer_api_import_all"), url(r"^(?P<resource_name>%s)/(?P<pk>\w[\w/-]*)/apply-to-all%s$" % (self._meta.resource_name, trailing_slash()), self.wrap_view('apply_to_all'), name="importer_api_apply_to_all"), ] def import_all(self, request, **kwargs): self.method_check(request, allowed=['get']) self.is_authenticated(request) self.throttle_check(request) import_session = Import.objects.get(**self.remove_api_resource_names(kwargs)) import_files = import_session.files.filter(status=2) # first to a batch update import_files.update(status=6) # save again to trigger pos-save actions for import_file in import_files: import_file.status = 6 import_file.save() bundle = self.build_bundle(obj=import_session, request=request) bundle = self.full_dehydrate(bundle) self.log_throttled_access(request) return self.create_response(request, bundle) """ mass aply import tag """ def apply_to_all(self, request, **kwargs): self.method_check(request, allowed=['post']) self.is_authenticated(request) self.throttle_check(request) import_session = Import.objects.get(**self.remove_api_resource_names(kwargs)) item_id = request.POST.get('item_id', None) ct = request.POST.get('ct', None) print 'item_id: %s' % item_id print 'ct: %s' % ct if not (ct and item_id): raise ImmediateHttpResponse(response=HttpResponse(status=410)) import_files = import_session.files.filter(status__in=(2,4)) source = import_files.filter(pk=item_id) # exclude current one import_files = import_files.exclude(pk=item_id) try: source = source[0] print source # print source.import_tag except: source = None if source: sit = source.import_tag for import_file in import_files: dit = import_file.import_tag if ct == 'artist': map = ('artist', 'alibrary_artist_id', 'mb_artist_id', 'force_artist') if ct == 'release': map = ('release', 'alibrary_release_id', 'mb_release_id', 'force_release') for key in map: src = sit.get(key, None) if src: dit[key] = src else: dit.pop(key, None) import_file.import_tag = dit import_file.save() bundle = self.build_bundle(obj=import_session, request=request) bundle = self.full_dehydrate(bundle) self.log_throttled_access(request) return self.create_response(request, bundle)
gpl-3.0
snehasi/servo
python/servo/post_build_commands.py
16
9628
# Copyright 2013 The Servo Project Developers. See the COPYRIGHT # file at the top-level directory of this distribution. # # 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. from __future__ import print_function, unicode_literals import os import os.path as path import subprocess from shutil import copytree, rmtree, copy2 from mach.registrar import Registrar from mach.decorators import ( CommandArgument, CommandProvider, Command, ) from servo.command_base import ( CommandBase, call, check_call, is_linux, is_windows, is_macosx, set_osmesa_env, get_browserhtml_path, ) def read_file(filename, if_exists=False): if if_exists and not path.exists(filename): return None with open(filename) as f: return f.read() @CommandProvider class PostBuildCommands(CommandBase): @Command('run', description='Run Servo', category='post-build') @CommandArgument('--release', '-r', action='store_true', help='Run the release build') @CommandArgument('--dev', '-d', action='store_true', help='Run the dev build') @CommandArgument('--android', action='store_true', default=None, help='Run on an Android device through `adb shell`') @CommandArgument('--debug', action='store_true', help='Enable the debugger. Not specifying a ' '--debugger option will result in the default ' 'debugger being used. The following arguments ' 'have no effect without this.') @CommandArgument('--debugger', default=None, type=str, help='Name of debugger to use.') @CommandArgument('--browserhtml', '-b', action='store_true', help='Launch with Browser.html') @CommandArgument('--headless', '-z', action='store_true', help='Launch in headless mode') @CommandArgument('--software', '-s', action='store_true', help='Launch with software rendering') @CommandArgument( 'params', nargs='...', help="Command-line arguments to be passed through to Servo") def run(self, params, release=False, dev=False, android=None, debug=False, debugger=None, browserhtml=False, headless=False, software=False): env = self.build_env() env["RUST_BACKTRACE"] = "1" # Make --debugger imply --debug if debugger: debug = True if android is None: android = self.config["build"]["android"] if android: if debug: print("Android on-device debugging is not supported by mach yet. See") print("https://github.com/servo/servo/wiki/Building-for-Android#debugging-on-device") return script = [ "am force-stop com.mozilla.servo", "echo servo >/sdcard/servo/android_params" ] for param in params: script += [ "echo '%s' >>/sdcard/servo/android_params" % param.replace("'", "\\'") ] script += [ "am start com.mozilla.servo/com.mozilla.servo.MainActivity", "exit" ] shell = subprocess.Popen(["adb", "shell"], stdin=subprocess.PIPE) shell.communicate("\n".join(script) + "\n") return shell.wait() args = [self.get_binary_path(release, dev)] if browserhtml: browserhtml_path = get_browserhtml_path(args[0]) if is_macosx(): # Enable borderless on OSX args = args + ['-b'] elif is_windows(): # Convert to a relative path to avoid mingw -> Windows path conversions browserhtml_path = path.relpath(browserhtml_path, os.getcwd()) args = args + ['--pref', 'dom.mozbrowser.enabled', '--pref', 'dom.forcetouch.enabled', '--pref', 'shell.builtin-key-shortcuts.enabled=false', path.join(browserhtml_path, 'index.html')] if headless: set_osmesa_env(args[0], env) args.append('-z') if software: if not is_linux(): print("Software rendering is only supported on Linux at the moment.") return env['LIBGL_ALWAYS_SOFTWARE'] = "1" # Borrowed and modified from: # http://hg.mozilla.org/mozilla-central/file/c9cfa9b91dea/python/mozbuild/mozbuild/mach_commands.py#l883 if debug: import mozdebug if not debugger: # No debugger name was provided. Look for the default ones on # current OS. debugger = mozdebug.get_default_debugger_name( mozdebug.DebuggerSearch.KeepLooking) self.debuggerInfo = mozdebug.get_debugger_info(debugger) if not self.debuggerInfo: print("Could not find a suitable debugger in your PATH.") return 1 command = self.debuggerInfo.path if debugger == 'gdb' or debugger == 'lldb': rustCommand = 'rust-' + debugger try: subprocess.check_call([rustCommand, '--version'], env=env, stdout=open(os.devnull, 'w')) except (OSError, subprocess.CalledProcessError): pass else: command = rustCommand # Prepend the debugger args. args = ([command] + self.debuggerInfo.args + args + params) else: args = args + params try: check_call(args, env=env) except subprocess.CalledProcessError as e: print("Servo exited with return value %d" % e.returncode) return e.returncode except OSError as e: if e.errno == 2: print("Servo Binary can't be found! Run './mach build'" " and try again!") else: raise e @Command('rr-record', description='Run Servo whilst recording execution with rr', category='post-build') @CommandArgument('--release', '-r', action='store_true', help='Use release build') @CommandArgument('--dev', '-d', action='store_true', help='Use dev build') @CommandArgument( 'params', nargs='...', help="Command-line arguments to be passed through to Servo") def rr_record(self, release=False, dev=False, params=[]): env = self.build_env() env["RUST_BACKTRACE"] = "1" servo_cmd = [self.get_binary_path(release, dev)] + params rr_cmd = ['rr', '--fatal-errors', 'record'] try: check_call(rr_cmd + servo_cmd) except OSError as e: if e.errno == 2: print("rr binary can't be found!") else: raise e @Command('rr-replay', description='Replay the most recent execution of Servo that was recorded with rr', category='post-build') def rr_replay(self): try: check_call(['rr', '--fatal-errors', 'replay']) except OSError as e: if e.errno == 2: print("rr binary can't be found!") else: raise e @Command('doc', description='Generate documentation', category='post-build') @CommandArgument( 'params', nargs='...', help="Command-line arguments to be passed through to cargo doc") def doc(self, params): self.ensure_bootstrapped() if not path.exists(path.join(self.config["tools"]["rust-root"], "doc")): Registrar.dispatch("bootstrap-rust-docs", context=self.context) rust_docs = path.join(self.config["tools"]["rust-root"], "doc") docs = path.join(self.get_target_dir(), "doc") if not path.exists(docs): os.makedirs(docs) if read_file(path.join(docs, "version_info.html"), if_exists=True) != \ read_file(path.join(rust_docs, "version_info.html")): print("Copying Rust documentation.") # copytree doesn't like the destination already existing. for name in os.listdir(rust_docs): if not name.startswith('.'): full_name = path.join(rust_docs, name) destination = path.join(docs, name) if path.isdir(full_name): if path.exists(destination): rmtree(destination) copytree(full_name, destination) else: copy2(full_name, destination) return call(["cargo", "doc"] + params, env=self.build_env(), cwd=self.servo_crate()) @Command('browse-doc', description='Generate documentation and open it in a web browser', category='post-build') def serve_docs(self): self.doc([]) import webbrowser webbrowser.open("file://" + path.abspath(path.join( self.get_target_dir(), "doc", "servo", "index.html")))
mpl-2.0
blois/AndroidSDKCloneMin
ndk/prebuilt/linux-x86_64/lib/python2.7/distutils/emxccompiler.py
250
11931
"""distutils.emxccompiler Provides the EMXCCompiler class, a subclass of UnixCCompiler that handles the EMX port of the GNU C compiler to OS/2. """ # issues: # # * OS/2 insists that DLLs can have names no longer than 8 characters # We put export_symbols in a def-file, as though the DLL can have # an arbitrary length name, but truncate the output filename. # # * only use OMF objects and use LINK386 as the linker (-Zomf) # # * always build for multithreading (-Zmt) as the accompanying OS/2 port # of Python is only distributed with threads enabled. # # tested configurations: # # * EMX gcc 2.81/EMX 0.9d fix03 __revision__ = "$Id$" import os,sys,copy from distutils.ccompiler import gen_preprocess_options, gen_lib_options from distutils.unixccompiler import UnixCCompiler from distutils.file_util import write_file from distutils.errors import DistutilsExecError, CompileError, UnknownFileError from distutils import log class EMXCCompiler (UnixCCompiler): compiler_type = 'emx' obj_extension = ".obj" static_lib_extension = ".lib" shared_lib_extension = ".dll" static_lib_format = "%s%s" shared_lib_format = "%s%s" res_extension = ".res" # compiled resource file exe_extension = ".exe" def __init__ (self, verbose=0, dry_run=0, force=0): UnixCCompiler.__init__ (self, verbose, dry_run, force) (status, details) = check_config_h() self.debug_print("Python's GCC status: %s (details: %s)" % (status, details)) if status is not CONFIG_H_OK: self.warn( "Python's pyconfig.h doesn't seem to support your compiler. " + ("Reason: %s." % details) + "Compiling may fail because of undefined preprocessor macros.") (self.gcc_version, self.ld_version) = \ get_versions() self.debug_print(self.compiler_type + ": gcc %s, ld %s\n" % (self.gcc_version, self.ld_version) ) # Hard-code GCC because that's what this is all about. # XXX optimization, warnings etc. should be customizable. self.set_executables(compiler='gcc -Zomf -Zmt -O3 -fomit-frame-pointer -mprobe -Wall', compiler_so='gcc -Zomf -Zmt -O3 -fomit-frame-pointer -mprobe -Wall', linker_exe='gcc -Zomf -Zmt -Zcrtdll', linker_so='gcc -Zomf -Zmt -Zcrtdll -Zdll') # want the gcc library statically linked (so that we don't have # to distribute a version dependent on the compiler we have) self.dll_libraries=["gcc"] # __init__ () def _compile(self, obj, src, ext, cc_args, extra_postargs, pp_opts): if ext == '.rc': # gcc requires '.rc' compiled to binary ('.res') files !!! try: self.spawn(["rc", "-r", src]) except DistutilsExecError, msg: raise CompileError, msg else: # for other files use the C-compiler try: self.spawn(self.compiler_so + cc_args + [src, '-o', obj] + extra_postargs) except DistutilsExecError, msg: raise CompileError, msg def link (self, target_desc, objects, output_filename, output_dir=None, libraries=None, library_dirs=None, runtime_library_dirs=None, export_symbols=None, debug=0, extra_preargs=None, extra_postargs=None, build_temp=None, target_lang=None): # use separate copies, so we can modify the lists extra_preargs = copy.copy(extra_preargs or []) libraries = copy.copy(libraries or []) objects = copy.copy(objects or []) # Additional libraries libraries.extend(self.dll_libraries) # handle export symbols by creating a def-file # with executables this only works with gcc/ld as linker if ((export_symbols is not None) and (target_desc != self.EXECUTABLE)): # (The linker doesn't do anything if output is up-to-date. # So it would probably better to check if we really need this, # but for this we had to insert some unchanged parts of # UnixCCompiler, and this is not what we want.) # we want to put some files in the same directory as the # object files are, build_temp doesn't help much # where are the object files temp_dir = os.path.dirname(objects[0]) # name of dll to give the helper files the same base name (dll_name, dll_extension) = os.path.splitext( os.path.basename(output_filename)) # generate the filenames for these files def_file = os.path.join(temp_dir, dll_name + ".def") # Generate .def file contents = [ "LIBRARY %s INITINSTANCE TERMINSTANCE" % \ os.path.splitext(os.path.basename(output_filename))[0], "DATA MULTIPLE NONSHARED", "EXPORTS"] for sym in export_symbols: contents.append(' "%s"' % sym) self.execute(write_file, (def_file, contents), "writing %s" % def_file) # next add options for def-file and to creating import libraries # for gcc/ld the def-file is specified as any other object files objects.append(def_file) #end: if ((export_symbols is not None) and # (target_desc != self.EXECUTABLE or self.linker_dll == "gcc")): # who wants symbols and a many times larger output file # should explicitly switch the debug mode on # otherwise we let dllwrap/ld strip the output file # (On my machine: 10KB < stripped_file < ??100KB # unstripped_file = stripped_file + XXX KB # ( XXX=254 for a typical python extension)) if not debug: extra_preargs.append("-s") UnixCCompiler.link(self, target_desc, objects, output_filename, output_dir, libraries, library_dirs, runtime_library_dirs, None, # export_symbols, we do this in our def-file debug, extra_preargs, extra_postargs, build_temp, target_lang) # link () # -- Miscellaneous methods ----------------------------------------- # override the object_filenames method from CCompiler to # support rc and res-files def object_filenames (self, source_filenames, strip_dir=0, output_dir=''): if output_dir is None: output_dir = '' obj_names = [] for src_name in source_filenames: # use normcase to make sure '.rc' is really '.rc' and not '.RC' (base, ext) = os.path.splitext (os.path.normcase(src_name)) if ext not in (self.src_extensions + ['.rc']): raise UnknownFileError, \ "unknown file type '%s' (from '%s')" % \ (ext, src_name) if strip_dir: base = os.path.basename (base) if ext == '.rc': # these need to be compiled to object files obj_names.append (os.path.join (output_dir, base + self.res_extension)) else: obj_names.append (os.path.join (output_dir, base + self.obj_extension)) return obj_names # object_filenames () # override the find_library_file method from UnixCCompiler # to deal with file naming/searching differences def find_library_file(self, dirs, lib, debug=0): shortlib = '%s.lib' % lib longlib = 'lib%s.lib' % lib # this form very rare # get EMX's default library directory search path try: emx_dirs = os.environ['LIBRARY_PATH'].split(';') except KeyError: emx_dirs = [] for dir in dirs + emx_dirs: shortlibp = os.path.join(dir, shortlib) longlibp = os.path.join(dir, longlib) if os.path.exists(shortlibp): return shortlibp elif os.path.exists(longlibp): return longlibp # Oops, didn't find it in *any* of 'dirs' return None # class EMXCCompiler # Because these compilers aren't configured in Python's pyconfig.h file by # default, we should at least warn the user if he is using a unmodified # version. CONFIG_H_OK = "ok" CONFIG_H_NOTOK = "not ok" CONFIG_H_UNCERTAIN = "uncertain" def check_config_h(): """Check if the current Python installation (specifically, pyconfig.h) appears amenable to building extensions with GCC. Returns a tuple (status, details), where 'status' is one of the following constants: CONFIG_H_OK all is well, go ahead and compile CONFIG_H_NOTOK doesn't look good CONFIG_H_UNCERTAIN not sure -- unable to read pyconfig.h 'details' is a human-readable string explaining the situation. Note there are two ways to conclude "OK": either 'sys.version' contains the string "GCC" (implying that this Python was built with GCC), or the installed "pyconfig.h" contains the string "__GNUC__". """ # XXX since this function also checks sys.version, it's not strictly a # "pyconfig.h" check -- should probably be renamed... from distutils import sysconfig import string # if sys.version contains GCC then python was compiled with # GCC, and the pyconfig.h file should be OK if string.find(sys.version,"GCC") >= 0: return (CONFIG_H_OK, "sys.version mentions 'GCC'") fn = sysconfig.get_config_h_filename() try: # It would probably better to read single lines to search. # But we do this only once, and it is fast enough f = open(fn) try: s = f.read() finally: f.close() except IOError, exc: # if we can't read this file, we cannot say it is wrong # the compiler will complain later about this file as missing return (CONFIG_H_UNCERTAIN, "couldn't read '%s': %s" % (fn, exc.strerror)) else: # "pyconfig.h" contains an "#ifdef __GNUC__" or something similar if string.find(s,"__GNUC__") >= 0: return (CONFIG_H_OK, "'%s' mentions '__GNUC__'" % fn) else: return (CONFIG_H_NOTOK, "'%s' does not mention '__GNUC__'" % fn) def get_versions(): """ Try to find out the versions of gcc and ld. If not possible it returns None for it. """ from distutils.version import StrictVersion from distutils.spawn import find_executable import re gcc_exe = find_executable('gcc') if gcc_exe: out = os.popen(gcc_exe + ' -dumpversion','r') try: out_string = out.read() finally: out.close() result = re.search('(\d+\.\d+\.\d+)',out_string) if result: gcc_version = StrictVersion(result.group(1)) else: gcc_version = None else: gcc_version = None # EMX ld has no way of reporting version number, and we use GCC # anyway - so we can link OMF DLLs ld_version = None return (gcc_version, ld_version)
apache-2.0
gao-feng/auditns
tools/perf/util/setup.py
2079
1438
#!/usr/bin/python2 from distutils.core import setup, Extension from os import getenv from distutils.command.build_ext import build_ext as _build_ext from distutils.command.install_lib import install_lib as _install_lib class build_ext(_build_ext): def finalize_options(self): _build_ext.finalize_options(self) self.build_lib = build_lib self.build_temp = build_tmp class install_lib(_install_lib): def finalize_options(self): _install_lib.finalize_options(self) self.build_dir = build_lib cflags = ['-fno-strict-aliasing', '-Wno-write-strings'] cflags += getenv('CFLAGS', '').split() build_lib = getenv('PYTHON_EXTBUILD_LIB') build_tmp = getenv('PYTHON_EXTBUILD_TMP') libtraceevent = getenv('LIBTRACEEVENT') liblk = getenv('LIBLK') ext_sources = [f.strip() for f in file('util/python-ext-sources') if len(f.strip()) > 0 and f[0] != '#'] perf = Extension('perf', sources = ext_sources, include_dirs = ['util/include'], extra_compile_args = cflags, extra_objects = [libtraceevent, liblk], ) setup(name='perf', version='0.1', description='Interface with the Linux profiling infrastructure', author='Arnaldo Carvalho de Melo', author_email='acme@redhat.com', license='GPLv2', url='http://perf.wiki.kernel.org', ext_modules=[perf], cmdclass={'build_ext': build_ext, 'install_lib': install_lib})
gpl-2.0
NEricN/RobotCSimulator
Python/App/Lib/test/test_calendar.py
73
28850
import calendar import unittest from test import test_support import locale import datetime result_2004_text = """ 2004 January February March Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su 1 2 3 4 1 1 2 3 4 5 6 7 5 6 7 8 9 10 11 2 3 4 5 6 7 8 8 9 10 11 12 13 14 12 13 14 15 16 17 18 9 10 11 12 13 14 15 15 16 17 18 19 20 21 19 20 21 22 23 24 25 16 17 18 19 20 21 22 22 23 24 25 26 27 28 26 27 28 29 30 31 23 24 25 26 27 28 29 29 30 31 April May June Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su 1 2 3 4 1 2 1 2 3 4 5 6 5 6 7 8 9 10 11 3 4 5 6 7 8 9 7 8 9 10 11 12 13 12 13 14 15 16 17 18 10 11 12 13 14 15 16 14 15 16 17 18 19 20 19 20 21 22 23 24 25 17 18 19 20 21 22 23 21 22 23 24 25 26 27 26 27 28 29 30 24 25 26 27 28 29 30 28 29 30 31 July August September Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su 1 2 3 4 1 1 2 3 4 5 5 6 7 8 9 10 11 2 3 4 5 6 7 8 6 7 8 9 10 11 12 12 13 14 15 16 17 18 9 10 11 12 13 14 15 13 14 15 16 17 18 19 19 20 21 22 23 24 25 16 17 18 19 20 21 22 20 21 22 23 24 25 26 26 27 28 29 30 31 23 24 25 26 27 28 29 27 28 29 30 30 31 October November December Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su 1 2 3 1 2 3 4 5 6 7 1 2 3 4 5 4 5 6 7 8 9 10 8 9 10 11 12 13 14 6 7 8 9 10 11 12 11 12 13 14 15 16 17 15 16 17 18 19 20 21 13 14 15 16 17 18 19 18 19 20 21 22 23 24 22 23 24 25 26 27 28 20 21 22 23 24 25 26 25 26 27 28 29 30 31 29 30 27 28 29 30 31 """ result_2004_html = """ <?xml version="1.0" encoding="ascii"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ascii" /> <link rel="stylesheet" type="text/css" href="calendar.css" /> <title>Calendar for 2004</title> </head> <body> <table border="0" cellpadding="0" cellspacing="0" class="year"> <tr><th colspan="3" class="year">2004</th></tr><tr><td><table border="0" cellpadding="0" cellspacing="0" class="month"> <tr><th colspan="7" class="month">January</th></tr> <tr><th class="mon">Mon</th><th class="tue">Tue</th><th class="wed">Wed</th><th class="thu">Thu</th><th class="fri">Fri</th><th class="sat">Sat</th><th class="sun">Sun</th></tr> <tr><td class="noday">&nbsp;</td><td class="noday">&nbsp;</td><td class="noday">&nbsp;</td><td class="thu">1</td><td class="fri">2</td><td class="sat">3</td><td class="sun">4</td></tr> <tr><td class="mon">5</td><td class="tue">6</td><td class="wed">7</td><td class="thu">8</td><td class="fri">9</td><td class="sat">10</td><td class="sun">11</td></tr> <tr><td class="mon">12</td><td class="tue">13</td><td class="wed">14</td><td class="thu">15</td><td class="fri">16</td><td class="sat">17</td><td class="sun">18</td></tr> <tr><td class="mon">19</td><td class="tue">20</td><td class="wed">21</td><td class="thu">22</td><td class="fri">23</td><td class="sat">24</td><td class="sun">25</td></tr> <tr><td class="mon">26</td><td class="tue">27</td><td class="wed">28</td><td class="thu">29</td><td class="fri">30</td><td class="sat">31</td><td class="noday">&nbsp;</td></tr> </table> </td><td><table border="0" cellpadding="0" cellspacing="0" class="month"> <tr><th colspan="7" class="month">February</th></tr> <tr><th class="mon">Mon</th><th class="tue">Tue</th><th class="wed">Wed</th><th class="thu">Thu</th><th class="fri">Fri</th><th class="sat">Sat</th><th class="sun">Sun</th></tr> <tr><td class="noday">&nbsp;</td><td class="noday">&nbsp;</td><td class="noday">&nbsp;</td><td class="noday">&nbsp;</td><td class="noday">&nbsp;</td><td class="noday">&nbsp;</td><td class="sun">1</td></tr> <tr><td class="mon">2</td><td class="tue">3</td><td class="wed">4</td><td class="thu">5</td><td class="fri">6</td><td class="sat">7</td><td class="sun">8</td></tr> <tr><td class="mon">9</td><td class="tue">10</td><td class="wed">11</td><td class="thu">12</td><td class="fri">13</td><td class="sat">14</td><td class="sun">15</td></tr> <tr><td class="mon">16</td><td class="tue">17</td><td class="wed">18</td><td class="thu">19</td><td class="fri">20</td><td class="sat">21</td><td class="sun">22</td></tr> <tr><td class="mon">23</td><td class="tue">24</td><td class="wed">25</td><td class="thu">26</td><td class="fri">27</td><td class="sat">28</td><td class="sun">29</td></tr> </table> </td><td><table border="0" cellpadding="0" cellspacing="0" class="month"> <tr><th colspan="7" class="month">March</th></tr> <tr><th class="mon">Mon</th><th class="tue">Tue</th><th class="wed">Wed</th><th class="thu">Thu</th><th class="fri">Fri</th><th class="sat">Sat</th><th class="sun">Sun</th></tr> <tr><td class="mon">1</td><td class="tue">2</td><td class="wed">3</td><td class="thu">4</td><td class="fri">5</td><td class="sat">6</td><td class="sun">7</td></tr> <tr><td class="mon">8</td><td class="tue">9</td><td class="wed">10</td><td class="thu">11</td><td class="fri">12</td><td class="sat">13</td><td class="sun">14</td></tr> <tr><td class="mon">15</td><td class="tue">16</td><td class="wed">17</td><td class="thu">18</td><td class="fri">19</td><td class="sat">20</td><td class="sun">21</td></tr> <tr><td class="mon">22</td><td class="tue">23</td><td class="wed">24</td><td class="thu">25</td><td class="fri">26</td><td class="sat">27</td><td class="sun">28</td></tr> <tr><td class="mon">29</td><td class="tue">30</td><td class="wed">31</td><td class="noday">&nbsp;</td><td class="noday">&nbsp;</td><td class="noday">&nbsp;</td><td class="noday">&nbsp;</td></tr> </table> </td></tr><tr><td><table border="0" cellpadding="0" cellspacing="0" class="month"> <tr><th colspan="7" class="month">April</th></tr> <tr><th class="mon">Mon</th><th class="tue">Tue</th><th class="wed">Wed</th><th class="thu">Thu</th><th class="fri">Fri</th><th class="sat">Sat</th><th class="sun">Sun</th></tr> <tr><td class="noday">&nbsp;</td><td class="noday">&nbsp;</td><td class="noday">&nbsp;</td><td class="thu">1</td><td class="fri">2</td><td class="sat">3</td><td class="sun">4</td></tr> <tr><td class="mon">5</td><td class="tue">6</td><td class="wed">7</td><td class="thu">8</td><td class="fri">9</td><td class="sat">10</td><td class="sun">11</td></tr> <tr><td class="mon">12</td><td class="tue">13</td><td class="wed">14</td><td class="thu">15</td><td class="fri">16</td><td class="sat">17</td><td class="sun">18</td></tr> <tr><td class="mon">19</td><td class="tue">20</td><td class="wed">21</td><td class="thu">22</td><td class="fri">23</td><td class="sat">24</td><td class="sun">25</td></tr> <tr><td class="mon">26</td><td class="tue">27</td><td class="wed">28</td><td class="thu">29</td><td class="fri">30</td><td class="noday">&nbsp;</td><td class="noday">&nbsp;</td></tr> </table> </td><td><table border="0" cellpadding="0" cellspacing="0" class="month"> <tr><th colspan="7" class="month">May</th></tr> <tr><th class="mon">Mon</th><th class="tue">Tue</th><th class="wed">Wed</th><th class="thu">Thu</th><th class="fri">Fri</th><th class="sat">Sat</th><th class="sun">Sun</th></tr> <tr><td class="noday">&nbsp;</td><td class="noday">&nbsp;</td><td class="noday">&nbsp;</td><td class="noday">&nbsp;</td><td class="noday">&nbsp;</td><td class="sat">1</td><td class="sun">2</td></tr> <tr><td class="mon">3</td><td class="tue">4</td><td class="wed">5</td><td class="thu">6</td><td class="fri">7</td><td class="sat">8</td><td class="sun">9</td></tr> <tr><td class="mon">10</td><td class="tue">11</td><td class="wed">12</td><td class="thu">13</td><td class="fri">14</td><td class="sat">15</td><td class="sun">16</td></tr> <tr><td class="mon">17</td><td class="tue">18</td><td class="wed">19</td><td class="thu">20</td><td class="fri">21</td><td class="sat">22</td><td class="sun">23</td></tr> <tr><td class="mon">24</td><td class="tue">25</td><td class="wed">26</td><td class="thu">27</td><td class="fri">28</td><td class="sat">29</td><td class="sun">30</td></tr> <tr><td class="mon">31</td><td class="noday">&nbsp;</td><td class="noday">&nbsp;</td><td class="noday">&nbsp;</td><td class="noday">&nbsp;</td><td class="noday">&nbsp;</td><td class="noday">&nbsp;</td></tr> </table> </td><td><table border="0" cellpadding="0" cellspacing="0" class="month"> <tr><th colspan="7" class="month">June</th></tr> <tr><th class="mon">Mon</th><th class="tue">Tue</th><th class="wed">Wed</th><th class="thu">Thu</th><th class="fri">Fri</th><th class="sat">Sat</th><th class="sun">Sun</th></tr> <tr><td class="noday">&nbsp;</td><td class="tue">1</td><td class="wed">2</td><td class="thu">3</td><td class="fri">4</td><td class="sat">5</td><td class="sun">6</td></tr> <tr><td class="mon">7</td><td class="tue">8</td><td class="wed">9</td><td class="thu">10</td><td class="fri">11</td><td class="sat">12</td><td class="sun">13</td></tr> <tr><td class="mon">14</td><td class="tue">15</td><td class="wed">16</td><td class="thu">17</td><td class="fri">18</td><td class="sat">19</td><td class="sun">20</td></tr> <tr><td class="mon">21</td><td class="tue">22</td><td class="wed">23</td><td class="thu">24</td><td class="fri">25</td><td class="sat">26</td><td class="sun">27</td></tr> <tr><td class="mon">28</td><td class="tue">29</td><td class="wed">30</td><td class="noday">&nbsp;</td><td class="noday">&nbsp;</td><td class="noday">&nbsp;</td><td class="noday">&nbsp;</td></tr> </table> </td></tr><tr><td><table border="0" cellpadding="0" cellspacing="0" class="month"> <tr><th colspan="7" class="month">July</th></tr> <tr><th class="mon">Mon</th><th class="tue">Tue</th><th class="wed">Wed</th><th class="thu">Thu</th><th class="fri">Fri</th><th class="sat">Sat</th><th class="sun">Sun</th></tr> <tr><td class="noday">&nbsp;</td><td class="noday">&nbsp;</td><td class="noday">&nbsp;</td><td class="thu">1</td><td class="fri">2</td><td class="sat">3</td><td class="sun">4</td></tr> <tr><td class="mon">5</td><td class="tue">6</td><td class="wed">7</td><td class="thu">8</td><td class="fri">9</td><td class="sat">10</td><td class="sun">11</td></tr> <tr><td class="mon">12</td><td class="tue">13</td><td class="wed">14</td><td class="thu">15</td><td class="fri">16</td><td class="sat">17</td><td class="sun">18</td></tr> <tr><td class="mon">19</td><td class="tue">20</td><td class="wed">21</td><td class="thu">22</td><td class="fri">23</td><td class="sat">24</td><td class="sun">25</td></tr> <tr><td class="mon">26</td><td class="tue">27</td><td class="wed">28</td><td class="thu">29</td><td class="fri">30</td><td class="sat">31</td><td class="noday">&nbsp;</td></tr> </table> </td><td><table border="0" cellpadding="0" cellspacing="0" class="month"> <tr><th colspan="7" class="month">August</th></tr> <tr><th class="mon">Mon</th><th class="tue">Tue</th><th class="wed">Wed</th><th class="thu">Thu</th><th class="fri">Fri</th><th class="sat">Sat</th><th class="sun">Sun</th></tr> <tr><td class="noday">&nbsp;</td><td class="noday">&nbsp;</td><td class="noday">&nbsp;</td><td class="noday">&nbsp;</td><td class="noday">&nbsp;</td><td class="noday">&nbsp;</td><td class="sun">1</td></tr> <tr><td class="mon">2</td><td class="tue">3</td><td class="wed">4</td><td class="thu">5</td><td class="fri">6</td><td class="sat">7</td><td class="sun">8</td></tr> <tr><td class="mon">9</td><td class="tue">10</td><td class="wed">11</td><td class="thu">12</td><td class="fri">13</td><td class="sat">14</td><td class="sun">15</td></tr> <tr><td class="mon">16</td><td class="tue">17</td><td class="wed">18</td><td class="thu">19</td><td class="fri">20</td><td class="sat">21</td><td class="sun">22</td></tr> <tr><td class="mon">23</td><td class="tue">24</td><td class="wed">25</td><td class="thu">26</td><td class="fri">27</td><td class="sat">28</td><td class="sun">29</td></tr> <tr><td class="mon">30</td><td class="tue">31</td><td class="noday">&nbsp;</td><td class="noday">&nbsp;</td><td class="noday">&nbsp;</td><td class="noday">&nbsp;</td><td class="noday">&nbsp;</td></tr> </table> </td><td><table border="0" cellpadding="0" cellspacing="0" class="month"> <tr><th colspan="7" class="month">September</th></tr> <tr><th class="mon">Mon</th><th class="tue">Tue</th><th class="wed">Wed</th><th class="thu">Thu</th><th class="fri">Fri</th><th class="sat">Sat</th><th class="sun">Sun</th></tr> <tr><td class="noday">&nbsp;</td><td class="noday">&nbsp;</td><td class="wed">1</td><td class="thu">2</td><td class="fri">3</td><td class="sat">4</td><td class="sun">5</td></tr> <tr><td class="mon">6</td><td class="tue">7</td><td class="wed">8</td><td class="thu">9</td><td class="fri">10</td><td class="sat">11</td><td class="sun">12</td></tr> <tr><td class="mon">13</td><td class="tue">14</td><td class="wed">15</td><td class="thu">16</td><td class="fri">17</td><td class="sat">18</td><td class="sun">19</td></tr> <tr><td class="mon">20</td><td class="tue">21</td><td class="wed">22</td><td class="thu">23</td><td class="fri">24</td><td class="sat">25</td><td class="sun">26</td></tr> <tr><td class="mon">27</td><td class="tue">28</td><td class="wed">29</td><td class="thu">30</td><td class="noday">&nbsp;</td><td class="noday">&nbsp;</td><td class="noday">&nbsp;</td></tr> </table> </td></tr><tr><td><table border="0" cellpadding="0" cellspacing="0" class="month"> <tr><th colspan="7" class="month">October</th></tr> <tr><th class="mon">Mon</th><th class="tue">Tue</th><th class="wed">Wed</th><th class="thu">Thu</th><th class="fri">Fri</th><th class="sat">Sat</th><th class="sun">Sun</th></tr> <tr><td class="noday">&nbsp;</td><td class="noday">&nbsp;</td><td class="noday">&nbsp;</td><td class="noday">&nbsp;</td><td class="fri">1</td><td class="sat">2</td><td class="sun">3</td></tr> <tr><td class="mon">4</td><td class="tue">5</td><td class="wed">6</td><td class="thu">7</td><td class="fri">8</td><td class="sat">9</td><td class="sun">10</td></tr> <tr><td class="mon">11</td><td class="tue">12</td><td class="wed">13</td><td class="thu">14</td><td class="fri">15</td><td class="sat">16</td><td class="sun">17</td></tr> <tr><td class="mon">18</td><td class="tue">19</td><td class="wed">20</td><td class="thu">21</td><td class="fri">22</td><td class="sat">23</td><td class="sun">24</td></tr> <tr><td class="mon">25</td><td class="tue">26</td><td class="wed">27</td><td class="thu">28</td><td class="fri">29</td><td class="sat">30</td><td class="sun">31</td></tr> </table> </td><td><table border="0" cellpadding="0" cellspacing="0" class="month"> <tr><th colspan="7" class="month">November</th></tr> <tr><th class="mon">Mon</th><th class="tue">Tue</th><th class="wed">Wed</th><th class="thu">Thu</th><th class="fri">Fri</th><th class="sat">Sat</th><th class="sun">Sun</th></tr> <tr><td class="mon">1</td><td class="tue">2</td><td class="wed">3</td><td class="thu">4</td><td class="fri">5</td><td class="sat">6</td><td class="sun">7</td></tr> <tr><td class="mon">8</td><td class="tue">9</td><td class="wed">10</td><td class="thu">11</td><td class="fri">12</td><td class="sat">13</td><td class="sun">14</td></tr> <tr><td class="mon">15</td><td class="tue">16</td><td class="wed">17</td><td class="thu">18</td><td class="fri">19</td><td class="sat">20</td><td class="sun">21</td></tr> <tr><td class="mon">22</td><td class="tue">23</td><td class="wed">24</td><td class="thu">25</td><td class="fri">26</td><td class="sat">27</td><td class="sun">28</td></tr> <tr><td class="mon">29</td><td class="tue">30</td><td class="noday">&nbsp;</td><td class="noday">&nbsp;</td><td class="noday">&nbsp;</td><td class="noday">&nbsp;</td><td class="noday">&nbsp;</td></tr> </table> </td><td><table border="0" cellpadding="0" cellspacing="0" class="month"> <tr><th colspan="7" class="month">December</th></tr> <tr><th class="mon">Mon</th><th class="tue">Tue</th><th class="wed">Wed</th><th class="thu">Thu</th><th class="fri">Fri</th><th class="sat">Sat</th><th class="sun">Sun</th></tr> <tr><td class="noday">&nbsp;</td><td class="noday">&nbsp;</td><td class="wed">1</td><td class="thu">2</td><td class="fri">3</td><td class="sat">4</td><td class="sun">5</td></tr> <tr><td class="mon">6</td><td class="tue">7</td><td class="wed">8</td><td class="thu">9</td><td class="fri">10</td><td class="sat">11</td><td class="sun">12</td></tr> <tr><td class="mon">13</td><td class="tue">14</td><td class="wed">15</td><td class="thu">16</td><td class="fri">17</td><td class="sat">18</td><td class="sun">19</td></tr> <tr><td class="mon">20</td><td class="tue">21</td><td class="wed">22</td><td class="thu">23</td><td class="fri">24</td><td class="sat">25</td><td class="sun">26</td></tr> <tr><td class="mon">27</td><td class="tue">28</td><td class="wed">29</td><td class="thu">30</td><td class="fri">31</td><td class="noday">&nbsp;</td><td class="noday">&nbsp;</td></tr> </table> </td></tr></table></body> </html> """ class OutputTestCase(unittest.TestCase): def normalize_calendar(self, s): # Filters out locale dependent strings def neitherspacenordigit(c): return not c.isspace() and not c.isdigit() lines = [] for line in s.splitlines(False): # Drop texts, as they are locale dependent if line and not filter(neitherspacenordigit, line): lines.append(line) return lines def test_output(self): self.assertEqual( self.normalize_calendar(calendar.calendar(2004)), self.normalize_calendar(result_2004_text) ) def test_output_textcalendar(self): self.assertEqual( calendar.TextCalendar().formatyear(2004).strip(), result_2004_text.strip() ) def test_output_htmlcalendar(self): self.assertEqual( calendar.HTMLCalendar().formatyearpage(2004).strip(), result_2004_html.strip() ) class CalendarTestCase(unittest.TestCase): def test_isleap(self): # Make sure that the return is right for a few years, and # ensure that the return values are 1 or 0, not just true or # false (see SF bug #485794). Specific additional tests may # be appropriate; this tests a single "cycle". self.assertEqual(calendar.isleap(2000), 1) self.assertEqual(calendar.isleap(2001), 0) self.assertEqual(calendar.isleap(2002), 0) self.assertEqual(calendar.isleap(2003), 0) def test_setfirstweekday(self): self.assertRaises(ValueError, calendar.setfirstweekday, 'flabber') self.assertRaises(ValueError, calendar.setfirstweekday, -1) self.assertRaises(ValueError, calendar.setfirstweekday, 200) orig = calendar.firstweekday() calendar.setfirstweekday(calendar.SUNDAY) self.assertEqual(calendar.firstweekday(), calendar.SUNDAY) calendar.setfirstweekday(calendar.MONDAY) self.assertEqual(calendar.firstweekday(), calendar.MONDAY) calendar.setfirstweekday(orig) def test_enumerateweekdays(self): self.assertRaises(IndexError, calendar.day_abbr.__getitem__, -10) self.assertRaises(IndexError, calendar.day_name.__getitem__, 10) self.assertEqual(len([d for d in calendar.day_abbr]), 7) def test_days(self): for attr in "day_name", "day_abbr": value = getattr(calendar, attr) self.assertEqual(len(value), 7) self.assertEqual(len(value[:]), 7) # ensure they're all unique self.assertEqual(len(set(value)), 7) # verify it "acts like a sequence" in two forms of iteration self.assertEqual(value[::-1], list(reversed(value))) def test_months(self): for attr in "month_name", "month_abbr": value = getattr(calendar, attr) self.assertEqual(len(value), 13) self.assertEqual(len(value[:]), 13) self.assertEqual(value[0], "") # ensure they're all unique self.assertEqual(len(set(value)), 13) # verify it "acts like a sequence" in two forms of iteration self.assertEqual(value[::-1], list(reversed(value))) def test_localecalendars(self): # ensure that Locale{Text,HTML}Calendar resets the locale properly # (it is still not thread-safe though) old_october = calendar.TextCalendar().formatmonthname(2010, 10, 10) try: cal = calendar.LocaleTextCalendar(locale='') local_weekday = cal.formatweekday(1, 10) local_month = cal.formatmonthname(2010, 10, 10) except locale.Error: # cannot set the system default locale -- skip rest of test raise unittest.SkipTest('cannot set the system default locale') # should be encodable local_weekday.encode('utf-8') local_month.encode('utf-8') self.assertEqual(len(local_weekday), 10) self.assertGreaterEqual(len(local_month), 10) cal = calendar.LocaleHTMLCalendar(locale='') local_weekday = cal.formatweekday(1) local_month = cal.formatmonthname(2010, 10) # should be encodable local_weekday.encode('utf-8') local_month.encode('utf-8') new_october = calendar.TextCalendar().formatmonthname(2010, 10, 10) self.assertEqual(old_october, new_october) def test_itermonthdates(self): # ensure itermonthdates doesn't overflow after datetime.MAXYEAR # see #15421 list(calendar.Calendar().itermonthdates(datetime.MAXYEAR, 12)) class MonthCalendarTestCase(unittest.TestCase): def setUp(self): self.oldfirstweekday = calendar.firstweekday() calendar.setfirstweekday(self.firstweekday) def tearDown(self): calendar.setfirstweekday(self.oldfirstweekday) def check_weeks(self, year, month, weeks): cal = calendar.monthcalendar(year, month) self.assertEqual(len(cal), len(weeks)) for i in xrange(len(weeks)): self.assertEqual(weeks[i], sum(day != 0 for day in cal[i])) class MondayTestCase(MonthCalendarTestCase): firstweekday = calendar.MONDAY def test_february(self): # A 28-day february starting on monday (7+7+7+7 days) self.check_weeks(1999, 2, (7, 7, 7, 7)) # A 28-day february starting on tuesday (6+7+7+7+1 days) self.check_weeks(2005, 2, (6, 7, 7, 7, 1)) # A 28-day february starting on sunday (1+7+7+7+6 days) self.check_weeks(1987, 2, (1, 7, 7, 7, 6)) # A 29-day february starting on monday (7+7+7+7+1 days) self.check_weeks(1988, 2, (7, 7, 7, 7, 1)) # A 29-day february starting on tuesday (6+7+7+7+2 days) self.check_weeks(1972, 2, (6, 7, 7, 7, 2)) # A 29-day february starting on sunday (1+7+7+7+7 days) self.check_weeks(2004, 2, (1, 7, 7, 7, 7)) def test_april(self): # A 30-day april starting on monday (7+7+7+7+2 days) self.check_weeks(1935, 4, (7, 7, 7, 7, 2)) # A 30-day april starting on tuesday (6+7+7+7+3 days) self.check_weeks(1975, 4, (6, 7, 7, 7, 3)) # A 30-day april starting on sunday (1+7+7+7+7+1 days) self.check_weeks(1945, 4, (1, 7, 7, 7, 7, 1)) # A 30-day april starting on saturday (2+7+7+7+7 days) self.check_weeks(1995, 4, (2, 7, 7, 7, 7)) # A 30-day april starting on friday (3+7+7+7+6 days) self.check_weeks(1994, 4, (3, 7, 7, 7, 6)) def test_december(self): # A 31-day december starting on monday (7+7+7+7+3 days) self.check_weeks(1980, 12, (7, 7, 7, 7, 3)) # A 31-day december starting on tuesday (6+7+7+7+4 days) self.check_weeks(1987, 12, (6, 7, 7, 7, 4)) # A 31-day december starting on sunday (1+7+7+7+7+2 days) self.check_weeks(1968, 12, (1, 7, 7, 7, 7, 2)) # A 31-day december starting on thursday (4+7+7+7+6 days) self.check_weeks(1988, 12, (4, 7, 7, 7, 6)) # A 31-day december starting on friday (3+7+7+7+7 days) self.check_weeks(2017, 12, (3, 7, 7, 7, 7)) # A 31-day december starting on saturday (2+7+7+7+7+1 days) self.check_weeks(2068, 12, (2, 7, 7, 7, 7, 1)) class SundayTestCase(MonthCalendarTestCase): firstweekday = calendar.SUNDAY def test_february(self): # A 28-day february starting on sunday (7+7+7+7 days) self.check_weeks(2009, 2, (7, 7, 7, 7)) # A 28-day february starting on monday (6+7+7+7+1 days) self.check_weeks(1999, 2, (6, 7, 7, 7, 1)) # A 28-day february starting on saturday (1+7+7+7+6 days) self.check_weeks(1997, 2, (1, 7, 7, 7, 6)) # A 29-day february starting on sunday (7+7+7+7+1 days) self.check_weeks(2004, 2, (7, 7, 7, 7, 1)) # A 29-day february starting on monday (6+7+7+7+2 days) self.check_weeks(1960, 2, (6, 7, 7, 7, 2)) # A 29-day february starting on saturday (1+7+7+7+7 days) self.check_weeks(1964, 2, (1, 7, 7, 7, 7)) def test_april(self): # A 30-day april starting on sunday (7+7+7+7+2 days) self.check_weeks(1923, 4, (7, 7, 7, 7, 2)) # A 30-day april starting on monday (6+7+7+7+3 days) self.check_weeks(1918, 4, (6, 7, 7, 7, 3)) # A 30-day april starting on saturday (1+7+7+7+7+1 days) self.check_weeks(1950, 4, (1, 7, 7, 7, 7, 1)) # A 30-day april starting on friday (2+7+7+7+7 days) self.check_weeks(1960, 4, (2, 7, 7, 7, 7)) # A 30-day april starting on thursday (3+7+7+7+6 days) self.check_weeks(1909, 4, (3, 7, 7, 7, 6)) def test_december(self): # A 31-day december starting on sunday (7+7+7+7+3 days) self.check_weeks(2080, 12, (7, 7, 7, 7, 3)) # A 31-day december starting on monday (6+7+7+7+4 days) self.check_weeks(1941, 12, (6, 7, 7, 7, 4)) # A 31-day december starting on saturday (1+7+7+7+7+2 days) self.check_weeks(1923, 12, (1, 7, 7, 7, 7, 2)) # A 31-day december starting on wednesday (4+7+7+7+6 days) self.check_weeks(1948, 12, (4, 7, 7, 7, 6)) # A 31-day december starting on thursday (3+7+7+7+7 days) self.check_weeks(1927, 12, (3, 7, 7, 7, 7)) # A 31-day december starting on friday (2+7+7+7+7+1 days) self.check_weeks(1995, 12, (2, 7, 7, 7, 7, 1)) class MonthRangeTestCase(unittest.TestCase): def test_january(self): # Tests valid lower boundary case. self.assertEqual(calendar.monthrange(2004,1), (3,31)) def test_february_leap(self): # Tests February during leap year. self.assertEqual(calendar.monthrange(2004,2), (6,29)) def test_february_nonleap(self): # Tests February in non-leap year. self.assertEqual(calendar.monthrange(2010,2), (0,28)) def test_december(self): # Tests valid upper boundary case. self.assertEqual(calendar.monthrange(2004,12), (2,31)) def test_zeroth_month(self): # Tests low invalid boundary case. with self.assertRaises(calendar.IllegalMonthError): calendar.monthrange(2004, 0) def test_thirteenth_month(self): # Tests high invalid boundary case. with self.assertRaises(calendar.IllegalMonthError): calendar.monthrange(2004, 13) class LeapdaysTestCase(unittest.TestCase): def test_no_range(self): # test when no range i.e. two identical years as args self.assertEqual(calendar.leapdays(2010,2010), 0) def test_no_leapdays(self): # test when no leap years in range self.assertEqual(calendar.leapdays(2010,2011), 0) def test_no_leapdays_upper_boundary(self): # test no leap years in range, when upper boundary is a leap year self.assertEqual(calendar.leapdays(2010,2012), 0) def test_one_leapday_lower_boundary(self): # test when one leap year in range, lower boundary is leap year self.assertEqual(calendar.leapdays(2012,2013), 1) def test_several_leapyears_in_range(self): self.assertEqual(calendar.leapdays(1997,2020), 5) def test_main(): test_support.run_unittest( OutputTestCase, CalendarTestCase, MondayTestCase, SundayTestCase, MonthRangeTestCase, LeapdaysTestCase, ) if __name__ == "__main__": test_main()
apache-2.0
wangyikai/grpc
src/python/grpcio_test/grpc_test/framework/interfaces/face/_event_invocation_synchronous_event_service.py
11
15944
# Copyright 2015, 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. """Test code for the Face layer of RPC Framework.""" import abc import unittest # test_interfaces is referenced from specification in this module. from grpc.framework.interfaces.face import face from grpc_test.framework.common import test_constants from grpc_test.framework.common import test_control from grpc_test.framework.common import test_coverage from grpc_test.framework.interfaces.face import _3069_test_constant from grpc_test.framework.interfaces.face import _digest from grpc_test.framework.interfaces.face import _receiver from grpc_test.framework.interfaces.face import _stock_service from grpc_test.framework.interfaces.face import test_interfaces # pylint: disable=unused-import class TestCase(test_coverage.Coverage, unittest.TestCase): """A test of the Face layer of RPC Framework. Concrete subclasses must have an "implementation" attribute of type test_interfaces.Implementation and an "invoker_constructor" attribute of type _invocation.InvokerConstructor. """ __metaclass__ = abc.ABCMeta NAME = 'EventInvocationSynchronousEventServiceTest' def setUp(self): """See unittest.TestCase.setUp for full specification. Overriding implementations must call this implementation. """ self._control = test_control.PauseFailControl() self._digest = _digest.digest( _stock_service.STOCK_TEST_SERVICE, self._control, None) generic_stub, dynamic_stubs, self._memo = self.implementation.instantiate( self._digest.methods, self._digest.event_method_implementations, None) self._invoker = self.invoker_constructor.construct_invoker( generic_stub, dynamic_stubs, self._digest.methods) def tearDown(self): """See unittest.TestCase.tearDown for full specification. Overriding implementations must call this implementation. """ self._invoker = None self.implementation.destantiate(self._memo) def testSuccessfulUnaryRequestUnaryResponse(self): for (group, method), test_messages_sequence in ( self._digest.unary_unary_messages_sequences.iteritems()): for test_messages in test_messages_sequence: request = test_messages.request() receiver = _receiver.Receiver() self._invoker.event(group, method)( request, receiver, receiver.abort, test_constants.LONG_TIMEOUT) receiver.block_until_terminated() response = receiver.unary_response() test_messages.verify(request, response, self) def testSuccessfulUnaryRequestStreamResponse(self): for (group, method), test_messages_sequence in ( self._digest.unary_stream_messages_sequences.iteritems()): for test_messages in test_messages_sequence: request = test_messages.request() receiver = _receiver.Receiver() self._invoker.event(group, method)( request, receiver, receiver.abort, test_constants.LONG_TIMEOUT) receiver.block_until_terminated() responses = receiver.stream_responses() test_messages.verify(request, responses, self) def testSuccessfulStreamRequestUnaryResponse(self): for (group, method), test_messages_sequence in ( self._digest.stream_unary_messages_sequences.iteritems()): for test_messages in test_messages_sequence: requests = test_messages.requests() receiver = _receiver.Receiver() call_consumer = self._invoker.event(group, method)( receiver, receiver.abort, test_constants.LONG_TIMEOUT) for request in requests: call_consumer.consume(request) call_consumer.terminate() receiver.block_until_terminated() response = receiver.unary_response() test_messages.verify(requests, response, self) def testSuccessfulStreamRequestStreamResponse(self): for (group, method), test_messages_sequence in ( self._digest.stream_stream_messages_sequences.iteritems()): for test_messages in test_messages_sequence: requests = test_messages.requests() receiver = _receiver.Receiver() call_consumer = self._invoker.event(group, method)( receiver, receiver.abort, test_constants.LONG_TIMEOUT) for request in requests: call_consumer.consume(request) call_consumer.terminate() receiver.block_until_terminated() responses = receiver.stream_responses() test_messages.verify(requests, responses, self) def testSequentialInvocations(self): # pylint: disable=cell-var-from-loop for (group, method), test_messages_sequence in ( self._digest.unary_unary_messages_sequences.iteritems()): for test_messages in test_messages_sequence: first_request = test_messages.request() second_request = test_messages.request() second_receiver = _receiver.Receiver() def make_second_invocation(): self._invoker.event(group, method)( second_request, second_receiver, second_receiver.abort, test_constants.LONG_TIMEOUT) class FirstReceiver(_receiver.Receiver): def complete(self, terminal_metadata, code, details): super(FirstReceiver, self).complete( terminal_metadata, code, details) make_second_invocation() first_receiver = FirstReceiver() self._invoker.event(group, method)( first_request, first_receiver, first_receiver.abort, test_constants.LONG_TIMEOUT) second_receiver.block_until_terminated() first_response = first_receiver.unary_response() second_response = second_receiver.unary_response() test_messages.verify(first_request, first_response, self) test_messages.verify(second_request, second_response, self) def testParallelInvocations(self): for (group, method), test_messages_sequence in ( self._digest.unary_unary_messages_sequences.iteritems()): for test_messages in test_messages_sequence: first_request = test_messages.request() first_receiver = _receiver.Receiver() second_request = test_messages.request() second_receiver = _receiver.Receiver() self._invoker.event(group, method)( first_request, first_receiver, first_receiver.abort, test_constants.LONG_TIMEOUT) self._invoker.event(group, method)( second_request, second_receiver, second_receiver.abort, test_constants.LONG_TIMEOUT) first_receiver.block_until_terminated() second_receiver.block_until_terminated() first_response = first_receiver.unary_response() second_response = second_receiver.unary_response() test_messages.verify(first_request, first_response, self) test_messages.verify(second_request, second_response, self) @unittest.skip('TODO(nathaniel): implement.') def testWaitingForSomeButNotAllParallelInvocations(self): raise NotImplementedError() def testCancelledUnaryRequestUnaryResponse(self): for (group, method), test_messages_sequence in ( self._digest.unary_unary_messages_sequences.iteritems()): for test_messages in test_messages_sequence: request = test_messages.request() receiver = _receiver.Receiver() with self._control.pause(): call = self._invoker.event(group, method)( request, receiver, receiver.abort, test_constants.LONG_TIMEOUT) call.cancel() receiver.block_until_terminated() self.assertIs(face.Abortion.Kind.CANCELLED, receiver.abortion().kind) def testCancelledUnaryRequestStreamResponse(self): for (group, method), test_messages_sequence in ( self._digest.unary_stream_messages_sequences.iteritems()): for test_messages in test_messages_sequence: request = test_messages.request() receiver = _receiver.Receiver() call = self._invoker.event(group, method)( request, receiver, receiver.abort, test_constants.LONG_TIMEOUT) call.cancel() receiver.block_until_terminated() self.assertIs(face.Abortion.Kind.CANCELLED, receiver.abortion().kind) def testCancelledStreamRequestUnaryResponse(self): for (group, method), test_messages_sequence in ( self._digest.stream_unary_messages_sequences.iteritems()): for test_messages in test_messages_sequence: requests = test_messages.requests() receiver = _receiver.Receiver() call_consumer = self._invoker.event(group, method)( receiver, receiver.abort, test_constants.LONG_TIMEOUT) for request in requests: call_consumer.consume(request) call_consumer.cancel() receiver.block_until_terminated() self.assertIs(face.Abortion.Kind.CANCELLED, receiver.abortion().kind) def testCancelledStreamRequestStreamResponse(self): for (group, method), test_messages_sequence in ( self._digest.stream_stream_messages_sequences.iteritems()): for unused_test_messages in test_messages_sequence: receiver = _receiver.Receiver() call_consumer = self._invoker.event(group, method)( receiver, receiver.abort, test_constants.LONG_TIMEOUT) call_consumer.cancel() receiver.block_until_terminated() self.assertIs(face.Abortion.Kind.CANCELLED, receiver.abortion().kind) def testExpiredUnaryRequestUnaryResponse(self): for (group, method), test_messages_sequence in ( self._digest.unary_unary_messages_sequences.iteritems()): for test_messages in test_messages_sequence: request = test_messages.request() receiver = _receiver.Receiver() with self._control.pause(): self._invoker.event(group, method)( request, receiver, receiver.abort, _3069_test_constant.REALLY_SHORT_TIMEOUT) receiver.block_until_terminated() self.assertIs(face.Abortion.Kind.EXPIRED, receiver.abortion().kind) def testExpiredUnaryRequestStreamResponse(self): for (group, method), test_messages_sequence in ( self._digest.unary_stream_messages_sequences.iteritems()): for test_messages in test_messages_sequence: request = test_messages.request() receiver = _receiver.Receiver() with self._control.pause(): self._invoker.event(group, method)( request, receiver, receiver.abort, _3069_test_constant.REALLY_SHORT_TIMEOUT) receiver.block_until_terminated() self.assertIs(face.Abortion.Kind.EXPIRED, receiver.abortion().kind) def testExpiredStreamRequestUnaryResponse(self): for (group, method), test_messages_sequence in ( self._digest.stream_unary_messages_sequences.iteritems()): for unused_test_messages in test_messages_sequence: receiver = _receiver.Receiver() self._invoker.event(group, method)( receiver, receiver.abort, _3069_test_constant.REALLY_SHORT_TIMEOUT) receiver.block_until_terminated() self.assertIs(face.Abortion.Kind.EXPIRED, receiver.abortion().kind) def testExpiredStreamRequestStreamResponse(self): for (group, method), test_messages_sequence in ( self._digest.stream_stream_messages_sequences.iteritems()): for test_messages in test_messages_sequence: requests = test_messages.requests() receiver = _receiver.Receiver() call_consumer = self._invoker.event(group, method)( receiver, receiver.abort, _3069_test_constant.REALLY_SHORT_TIMEOUT) for request in requests: call_consumer.consume(request) receiver.block_until_terminated() self.assertIs(face.Abortion.Kind.EXPIRED, receiver.abortion().kind) def testFailedUnaryRequestUnaryResponse(self): for (group, method), test_messages_sequence in ( self._digest.unary_unary_messages_sequences.iteritems()): for test_messages in test_messages_sequence: request = test_messages.request() receiver = _receiver.Receiver() with self._control.fail(): self._invoker.event(group, method)( request, receiver, receiver.abort, test_constants.LONG_TIMEOUT) receiver.block_until_terminated() self.assertIs( face.Abortion.Kind.REMOTE_FAILURE, receiver.abortion().kind) def testFailedUnaryRequestStreamResponse(self): for (group, method), test_messages_sequence in ( self._digest.unary_stream_messages_sequences.iteritems()): for test_messages in test_messages_sequence: request = test_messages.request() receiver = _receiver.Receiver() with self._control.fail(): self._invoker.event(group, method)( request, receiver, receiver.abort, test_constants.LONG_TIMEOUT) receiver.block_until_terminated() self.assertIs( face.Abortion.Kind.REMOTE_FAILURE, receiver.abortion().kind) def testFailedStreamRequestUnaryResponse(self): for (group, method), test_messages_sequence in ( self._digest.stream_unary_messages_sequences.iteritems()): for test_messages in test_messages_sequence: requests = test_messages.requests() receiver = _receiver.Receiver() with self._control.fail(): call_consumer = self._invoker.event(group, method)( receiver, receiver.abort, test_constants.LONG_TIMEOUT) for request in requests: call_consumer.consume(request) call_consumer.terminate() receiver.block_until_terminated() self.assertIs( face.Abortion.Kind.REMOTE_FAILURE, receiver.abortion().kind) def testFailedStreamRequestStreamResponse(self): for (group, method), test_messages_sequence in ( self._digest.stream_stream_messages_sequences.iteritems()): for test_messages in test_messages_sequence: requests = test_messages.requests() receiver = _receiver.Receiver() with self._control.fail(): call_consumer = self._invoker.event(group, method)( receiver, receiver.abort, test_constants.LONG_TIMEOUT) for request in requests: call_consumer.consume(request) call_consumer.terminate() receiver.block_until_terminated() self.assertIs( face.Abortion.Kind.REMOTE_FAILURE, receiver.abortion().kind)
bsd-3-clause
michael-berlin/vitess
py/vtdb/db_object_custom_sharded.py
6
1827
"""Module containing base class for tables in custom sharded keyspace. Vitess sharding scheme is range-sharded. Vitess supports routing for other sharding schemes by allowing explicit shard_name addressing. This implementation is not fully complete as yet. """ from vtdb import db_object from vtdb import dbexceptions from vtdb import shard_constants from vtdb import vtgate_cursor class DBObjectCustomSharded(db_object.DBObjectBase): """Base class for custom-sharded db classes. This class is intended to support a custom sharding scheme, where the user controls the routing of their queries by passing in the shard_name explicitly.This provides helper methods for common database access operations. """ keyspace = None sharding = shard_constants.CUSTOM_SHARDED table_name = None columns_list = None @classmethod def create_shard_routing(class_, *pargs, **kwargs): routing = db_object.ShardRouting(keyspace) routing.shard_name = kargs.get('shard_name') if routing.shard_name is None: dbexceptions.InternalError("For custom sharding, shard_name cannot be None.") if (_is_iterable_container(routing.shard_name) and is_dml): raise dbexceptions.InternalError( "Writes are not allowed on multiple shards.") return routing @classmethod def create_vtgate_cursor(class_, vtgate_conn, tablet_type, is_dml, **cursor_kargs): # FIXME:extend VTGateCursor's api to accept shard_names # and allow queries based on that. routing = class_.create_shard_routing(**cursor_kargs) cursor = vtgate_cursor.VTGateCursor(vtgate_conn, class_.keyspace, tablet_type, keyranges=[routing.shard_name,], writable=is_dml) return cursor
bsd-3-clause
crempp/mdweb
mdweb/SiteMapView.py
1
2696
"""MDWeb SiteMap View Object.""" import datetime import logging import numbers import os import pytz import time from flask import ( current_app as app, make_response, render_template_string, url_for, ) from flask.views import View #: Template string to use for the sitemap generation # (is there a better place to put this?, not in the theme) # pylint: disable=C0301 SITEMAP_TEMPLATE = """<?xml version="1.0" encoding="utf-8"?> <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd"> {% for page in pages -%} <url> <loc>{{page.loc|safe}}</loc> <lastmod>{{page.lastmod|safe}}</lastmod> {%- if page.changefreq %} <changefreq>{{page.changefreq|safe}}</changefreq> {%- endif %} {%- if page.priority %} <priority>{{page.priority|safe}}</priority> {%- endif %} </url> {%- endfor %} </urlset> """ class SiteMapView(View): """Sitemap View Object.""" sitemap_cache = None def dispatch_request(self): """Flask dispatch method.""" if self.sitemap_cache is None: self.sitemap_cache = self.generate_sitemap() response = make_response(self.sitemap_cache) response.headers["Content-Type"] = "application/xml" return response @classmethod def generate_sitemap(cls): """Generate sitemap.xml. Makes a list of urls and date modified.""" logging.info("Generating sitemap...") start = time.time() pages = [] index_url = url_for('index', _external=True) for url, page in app.navigation.get_page_dict().items(): if page.meta_inf.published: mtime = os.path.getmtime(page.page_path) if isinstance(mtime, numbers.Real): mtime = datetime.datetime.fromtimestamp(mtime) mtime.replace(tzinfo=pytz.UTC) # lastmod = mtime.strftime('%Y-%m-%dT%H:%M:%S%z') lastmod = mtime.strftime('%Y-%m-%d') pages.append({ 'loc': "%s%s" % (index_url, url), 'lastmod': lastmod, 'changefreq': page.meta_inf.sitemap_changefreq, 'priority': page.meta_inf.sitemap_priority, }) sitemap_xml = render_template_string(SITEMAP_TEMPLATE, pages=pages) end = time.time() logging.info("completed sitemap generation in %s seconds", (end - start)) return sitemap_xml
mit
yangbh/Hammer
lib/knock/modules/dns/rdtypes/ANY/LOC.py
3
12894
# Copyright (C) 2003-2007, 2009-2011 Nominum, Inc. # # Permission to use, copy, modify, and distribute this software and its # documentation for any purpose with or without fee is hereby granted, # provided that the above copyright notice and this permission notice # appear in all copies. # # THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES # WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF # MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR # ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES # WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN # ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT # OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. import cStringIO import struct import dns.exception import dns.rdata _pows = (1L, 10L, 100L, 1000L, 10000L, 100000L, 1000000L, 10000000L, 100000000L, 1000000000L, 10000000000L) # default values are in centimeters _default_size = 100.0 _default_hprec = 1000000.0 _default_vprec = 1000.0 def _exponent_of(what, desc): exp = None for i in xrange(len(_pows)): if what // _pows[i] == 0L: exp = i - 1 break if exp is None or exp < 0: raise dns.exception.SyntaxError("%s value out of bounds" % desc) return exp def _float_to_tuple(what): if what < 0: sign = -1 what *= -1 else: sign = 1 what = long(round(what * 3600000)) degrees = int(what // 3600000) what -= degrees * 3600000 minutes = int(what // 60000) what -= minutes * 60000 seconds = int(what // 1000) what -= int(seconds * 1000) what = int(what) return (degrees * sign, minutes, seconds, what) def _tuple_to_float(what): if what[0] < 0: sign = -1 value = float(what[0]) * -1 else: sign = 1 value = float(what[0]) value += float(what[1]) / 60.0 value += float(what[2]) / 3600.0 value += float(what[3]) / 3600000.0 return sign * value def _encode_size(what, desc): what = long(what); exponent = _exponent_of(what, desc) & 0xF base = what // pow(10, exponent) & 0xF return base * 16 + exponent def _decode_size(what, desc): exponent = what & 0x0F if exponent > 9: raise dns.exception.SyntaxError("bad %s exponent" % desc) base = (what & 0xF0) >> 4 if base > 9: raise dns.exception.SyntaxError("bad %s base" % desc) return long(base) * pow(10, exponent) class LOC(dns.rdata.Rdata): """LOC record @ivar latitude: latitude @type latitude: (int, int, int, int) tuple specifying the degrees, minutes, seconds, and milliseconds of the coordinate. @ivar longitude: longitude @type longitude: (int, int, int, int) tuple specifying the degrees, minutes, seconds, and milliseconds of the coordinate. @ivar altitude: altitude @type altitude: float @ivar size: size of the sphere @type size: float @ivar horizontal_precision: horizontal precision @type horizontal_precision: float @ivar vertical_precision: vertical precision @type vertical_precision: float @see: RFC 1876""" __slots__ = ['latitude', 'longitude', 'altitude', 'size', 'horizontal_precision', 'vertical_precision'] def __init__(self, rdclass, rdtype, latitude, longitude, altitude, size=_default_size, hprec=_default_hprec, vprec=_default_vprec): """Initialize a LOC record instance. The parameters I{latitude} and I{longitude} may be either a 4-tuple of integers specifying (degrees, minutes, seconds, milliseconds), or they may be floating point values specifying the number of degrees. The other parameters are floats. Size, horizontal precision, and vertical precision are specified in centimeters.""" super(LOC, self).__init__(rdclass, rdtype) if isinstance(latitude, int) or isinstance(latitude, long): latitude = float(latitude) if isinstance(latitude, float): latitude = _float_to_tuple(latitude) self.latitude = latitude if isinstance(longitude, int) or isinstance(longitude, long): longitude = float(longitude) if isinstance(longitude, float): longitude = _float_to_tuple(longitude) self.longitude = longitude self.altitude = float(altitude) self.size = float(size) self.horizontal_precision = float(hprec) self.vertical_precision = float(vprec) def to_text(self, origin=None, relativize=True, **kw): if self.latitude[0] > 0: lat_hemisphere = 'N' lat_degrees = self.latitude[0] else: lat_hemisphere = 'S' lat_degrees = -1 * self.latitude[0] if self.longitude[0] > 0: long_hemisphere = 'E' long_degrees = self.longitude[0] else: long_hemisphere = 'W' long_degrees = -1 * self.longitude[0] text = "%d %d %d.%03d %s %d %d %d.%03d %s %0.2fm" % ( lat_degrees, self.latitude[1], self.latitude[2], self.latitude[3], lat_hemisphere, long_degrees, self.longitude[1], self.longitude[2], self.longitude[3], long_hemisphere, self.altitude / 100.0 ) # do not print default values if self.size != _default_size or \ self.horizontal_precision != _default_hprec or \ self.vertical_precision != _default_vprec: text += " %0.2fm %0.2fm %0.2fm" % ( self.size / 100.0, self.horizontal_precision / 100.0, self.vertical_precision / 100.0 ) return text def from_text(cls, rdclass, rdtype, tok, origin = None, relativize = True): latitude = [0, 0, 0, 0] longitude = [0, 0, 0, 0] size = _default_size hprec = _default_hprec vprec = _default_vprec latitude[0] = tok.get_int() t = tok.get_string() if t.isdigit(): latitude[1] = int(t) t = tok.get_string() if '.' in t: (seconds, milliseconds) = t.split('.') if not seconds.isdigit(): raise dns.exception.SyntaxError('bad latitude seconds value') latitude[2] = int(seconds) if latitude[2] >= 60: raise dns.exception.SyntaxError('latitude seconds >= 60') l = len(milliseconds) if l == 0 or l > 3 or not milliseconds.isdigit(): raise dns.exception.SyntaxError('bad latitude milliseconds value') if l == 1: m = 100 elif l == 2: m = 10 else: m = 1 latitude[3] = m * int(milliseconds) t = tok.get_string() elif t.isdigit(): latitude[2] = int(t) t = tok.get_string() if t == 'S': latitude[0] *= -1 elif t != 'N': raise dns.exception.SyntaxError('bad latitude hemisphere value') longitude[0] = tok.get_int() t = tok.get_string() if t.isdigit(): longitude[1] = int(t) t = tok.get_string() if '.' in t: (seconds, milliseconds) = t.split('.') if not seconds.isdigit(): raise dns.exception.SyntaxError('bad longitude seconds value') longitude[2] = int(seconds) if longitude[2] >= 60: raise dns.exception.SyntaxError('longitude seconds >= 60') l = len(milliseconds) if l == 0 or l > 3 or not milliseconds.isdigit(): raise dns.exception.SyntaxError('bad longitude milliseconds value') if l == 1: m = 100 elif l == 2: m = 10 else: m = 1 longitude[3] = m * int(milliseconds) t = tok.get_string() elif t.isdigit(): longitude[2] = int(t) t = tok.get_string() if t == 'W': longitude[0] *= -1 elif t != 'E': raise dns.exception.SyntaxError('bad longitude hemisphere value') t = tok.get_string() if t[-1] == 'm': t = t[0 : -1] altitude = float(t) * 100.0 # m -> cm token = tok.get().unescape() if not token.is_eol_or_eof(): value = token.value if value[-1] == 'm': value = value[0 : -1] size = float(value) * 100.0 # m -> cm token = tok.get().unescape() if not token.is_eol_or_eof(): value = token.value if value[-1] == 'm': value = value[0 : -1] hprec = float(value) * 100.0 # m -> cm token = tok.get().unescape() if not token.is_eol_or_eof(): value = token.value if value[-1] == 'm': value = value[0 : -1] vprec = float(value) * 100.0 # m -> cm tok.get_eol() return cls(rdclass, rdtype, latitude, longitude, altitude, size, hprec, vprec) from_text = classmethod(from_text) def to_wire(self, file, compress = None, origin = None): if self.latitude[0] < 0: sign = -1 degrees = long(-1 * self.latitude[0]) else: sign = 1 degrees = long(self.latitude[0]) milliseconds = (degrees * 3600000 + self.latitude[1] * 60000 + self.latitude[2] * 1000 + self.latitude[3]) * sign latitude = 0x80000000L + milliseconds if self.longitude[0] < 0: sign = -1 degrees = long(-1 * self.longitude[0]) else: sign = 1 degrees = long(self.longitude[0]) milliseconds = (degrees * 3600000 + self.longitude[1] * 60000 + self.longitude[2] * 1000 + self.longitude[3]) * sign longitude = 0x80000000L + milliseconds altitude = long(self.altitude) + 10000000L size = _encode_size(self.size, "size") hprec = _encode_size(self.horizontal_precision, "horizontal precision") vprec = _encode_size(self.vertical_precision, "vertical precision") wire = struct.pack("!BBBBIII", 0, size, hprec, vprec, latitude, longitude, altitude) file.write(wire) def from_wire(cls, rdclass, rdtype, wire, current, rdlen, origin = None): (version, size, hprec, vprec, latitude, longitude, altitude) = \ struct.unpack("!BBBBIII", wire[current : current + rdlen]) if latitude > 0x80000000L: latitude = float(latitude - 0x80000000L) / 3600000 else: latitude = -1 * float(0x80000000L - latitude) / 3600000 if latitude < -90.0 or latitude > 90.0: raise dns.exception.FormError("bad latitude") if longitude > 0x80000000L: longitude = float(longitude - 0x80000000L) / 3600000 else: longitude = -1 * float(0x80000000L - longitude) / 3600000 if longitude < -180.0 or longitude > 180.0: raise dns.exception.FormError("bad longitude") altitude = float(altitude) - 10000000.0 size = _decode_size(size, "size") hprec = _decode_size(hprec, "horizontal precision") vprec = _decode_size(vprec, "vertical precision") return cls(rdclass, rdtype, latitude, longitude, altitude, size, hprec, vprec) from_wire = classmethod(from_wire) def _cmp(self, other): f = cStringIO.StringIO() self.to_wire(f) wire1 = f.getvalue() f.seek(0) f.truncate() other.to_wire(f) wire2 = f.getvalue() f.close() return cmp(wire1, wire2) def _get_float_latitude(self): return _tuple_to_float(self.latitude) def _set_float_latitude(self, value): self.latitude = _float_to_tuple(value) float_latitude = property(_get_float_latitude, _set_float_latitude, doc="latitude as a floating point value") def _get_float_longitude(self): return _tuple_to_float(self.longitude) def _set_float_longitude(self, value): self.longitude = _float_to_tuple(value) float_longitude = property(_get_float_longitude, _set_float_longitude, doc="longitude as a floating point value")
gpl-2.0
jumping/Diamond
src/collectors/jolokia/jolokia.py
3
8461
# coding=utf-8 """ Collects JMX metrics from the Jolokia Agent. Jolokia is an HTTP bridge that provides access to JMX MBeans without the need to write Java code. See the [Reference Guide](http://www.jolokia.org/reference/html/index.html) for more information. By default, all MBeans will be queried for metrics. All numerical values will be published to Graphite; anything else will be ignored. JolokiaCollector will create a reasonable namespace for each metric based on each MBeans domain and name. e.g) ```java.lang:name=ParNew,type=GarbageCollector``` would become ```java.lang.name_ParNew.type_GarbageCollector```. #### Dependencies * Jolokia * A running JVM with Jolokia installed/configured #### Example Configuration If desired, JolokiaCollector can be configured to query specific MBeans by providing a list of ```mbeans```. If ```mbeans``` is not provided, all MBeans will be queried for metrics. Note that the mbean prefix is checked both with and without rewrites (including fixup re-writes) applied. This allows you to specify "java.lang:name=ParNew,type=GarbageCollector" (the raw name from jolokia) or "java.lang.name_ParNew.type_GarbageCollector" (the fixed name as used for output) If the ```regex``` flag is set to True, mbeans will match based on regular expressions rather than a plain textual match. The ```rewrite``` section provides a way of renaming the data keys before it sent out to the handler. The section consists of pairs of from-to regular expressions. If the resultant name is completely blank, the metric is not published, providing a way to exclude specific metrics within an mbean. ``` host = localhost port = 8778 mbeans = "java.lang:name=ParNew,type=GarbageCollector", "org.apache.cassandra.metrics:name=WriteTimeouts,type=ClientRequestMetrics" [rewrite] java = coffee "-v\d+\.\d+\.\d+" = "-AllVersions" ".*GetS2Activities.*" = "" ``` """ import diamond.collector import base64 import json import re import urllib import urllib2 class JolokiaCollector(diamond.collector.Collector): LIST_URL = "/list" READ_URL = "/?ignoreErrors=true&p=read/%s:*" """ These domains contain MBeans that are for management purposes, or otherwise do not contain useful metrics """ IGNORE_DOMAINS = ['JMImplementation', 'jmx4perl', 'jolokia', 'com.sun.management', 'java.util.logging'] def get_default_config_help(self): config_help = super(JolokiaCollector, self).get_default_config_help() config_help.update({ 'mbeans': "Pipe delimited list of MBeans for which to collect" " stats. If not provided, all stats will" " be collected.", 'regex': "Contols if mbeans option matches with regex," " False by default.", 'username': "Username for authentication", 'password': "Password for authentication", 'host': 'Hostname', 'port': 'Port', 'rewrite': "This sub-section of the config contains pairs of" " from-to regex rewrites.", 'path': 'Path to jolokia. typically "jmx" or "jolokia"' }) return config_help def get_default_config(self): config = super(JolokiaCollector, self).get_default_config() config.update({ 'mbeans': [], 'regex': False, 'rewrite': [], 'path': 'jolokia', 'username': None, 'password': None, 'host': 'localhost', 'port': 8778, }) return config def __init__(self, *args, **kwargs): super(JolokiaCollector, self).__init__(*args, **kwargs) self.mbeans = [] self.rewrite = {} if isinstance(self.config['mbeans'], basestring): for mbean in self.config['mbeans'].split('|'): self.mbeans.append(mbean.strip()) elif isinstance(self.config['mbeans'], list): self.mbeans = self.config['mbeans'] if isinstance(self.config['rewrite'], dict): self.rewrite = self.config['rewrite'] def check_mbean(self, mbean): if not self.mbeans: return True mbeanfix = self.clean_up(mbean) if self.config['regex'] is not None: for chkbean in self.mbeans: if re.match(chkbean, mbean) is not None or \ re.match(chkbean, mbeanfix) is not None: return True else: if mbean in self.mbeans or mbeanfix in self.mbeans: return True def collect(self): listing = self.list_request() try: domains = listing['value'] if listing['status'] == 200 else {} for domain in domains.keys(): if domain not in self.IGNORE_DOMAINS: obj = self.read_request(domain) mbeans = obj['value'] if obj['status'] == 200 else {} for k, v in mbeans.iteritems(): if self.check_mbean(k): self.collect_bean(k, v) except KeyError: # The reponse was totally empty, or not an expected format self.log.error('Unable to retrieve MBean listing.') def read_json(self, request): json_str = request.read() return json.loads(json_str) def list_request(self): try: url = "http://%s:%s/%s%s" % (self.config['host'], self.config['port'], self.config['path'], self.LIST_URL) response = urllib2.urlopen(self._create_request(url)) return self.read_json(response) except (urllib2.HTTPError, ValueError): self.log.error('Unable to read JSON response.') return {} def read_request(self, domain): try: url_path = self.READ_URL % self.escape_domain(domain) url = "http://%s:%s/%s%s" % (self.config['host'], self.config['port'], self.config['path'], url_path) response = urllib2.urlopen(self._create_request(url)) return self.read_json(response) except (urllib2.HTTPError, ValueError): self.log.error('Unable to read JSON response.') return {} # escape the JMX domain per https://jolokia.org/reference/html/protocol.html # the Jolokia documentation suggests that, when using the p query parameter, # simply urlencoding should be sufficient, but in practice, the '!' appears # necessary (and not harmful) def escape_domain(self, domain): domain = re.sub('!', '!!', domain) domain = re.sub('/', '!/', domain) domain = re.sub('"', '!"', domain) domain = urllib.quote(domain) return domain def _create_request(self, url): req = urllib2.Request(url) username = self.config["username"] password = self.config["password"] if username is not None and password is not None: base64string = base64.encodestring('%s:%s' % ( username, password)).replace('\n', '') req.add_header("Authorization", "Basic %s" % base64string) return req def clean_up(self, text): text = re.sub('["\'(){}<>\[\]]', '', text) text = re.sub('[:,.]+', '.', text) text = re.sub('[^a-zA-Z0-9_.+-]+', '_', text) for (oldstr, newstr) in self.rewrite.items(): text = re.sub(oldstr, newstr, text) return text def collect_bean(self, prefix, obj): for k, v in obj.iteritems(): if type(v) in [int, float, long]: key = "%s.%s" % (prefix, k) key = self.clean_up(key) if key != "": self.publish(key, v) elif type(v) in [dict]: self.collect_bean("%s.%s" % (prefix, k), v) elif type(v) in [list]: self.interpret_bean_with_list("%s.%s" % (prefix, k), v) # There's no unambiguous way to interpret list values, so # this hook lets subclasses handle them. def interpret_bean_with_list(self, prefix, values): pass
mit
kangkot/arangodb
3rdParty/V8-4.3.61/tools/testrunner/server/status_handler.py
123
4154
# Copyright 2012 the V8 project authors. All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following # disclaimer in the documentation and/or other materials provided # with the distribution. # * Neither the name of Google Inc. nor the names of its # contributors may be used to endorse or promote products derived # from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import socket import SocketServer from . import compression from . import constants def _StatusQuery(peer, query): sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) code = sock.connect_ex((peer.address, constants.STATUS_PORT)) if code != 0: # TODO(jkummerow): disconnect (after 3 failures?) return compression.Send(query, sock) compression.Send(constants.END_OF_STREAM, sock) rec = compression.Receiver(sock) data = None while not rec.IsDone(): data = rec.Current() assert data[0] == query[0] data = data[1] rec.Advance() sock.close() return data def RequestTrustedPubkeys(peer, server): pubkey_list = _StatusQuery(peer, [constants.LIST_TRUSTED_PUBKEYS]) for pubkey in pubkey_list: if server.IsTrusted(pubkey): continue result = _StatusQuery(peer, [constants.GET_SIGNED_PUBKEY, pubkey]) server.AcceptNewTrusted(result) def NotifyNewTrusted(peer, data): _StatusQuery(peer, [constants.NOTIFY_NEW_TRUSTED] + data) def ITrustYouNow(peer): _StatusQuery(peer, [constants.TRUST_YOU_NOW]) def TryTransitiveTrust(peer, pubkey, server): if _StatusQuery(peer, [constants.DO_YOU_TRUST, pubkey]): result = _StatusQuery(peer, [constants.GET_SIGNED_PUBKEY, pubkey]) server.AcceptNewTrusted(result) class StatusHandler(SocketServer.BaseRequestHandler): def handle(self): rec = compression.Receiver(self.request) while not rec.IsDone(): data = rec.Current() action = data[0] if action == constants.LIST_TRUSTED_PUBKEYS: response = self.server.daemon.ListTrusted() compression.Send([action, response], self.request) elif action == constants.GET_SIGNED_PUBKEY: response = self.server.daemon.SignTrusted(data[1]) compression.Send([action, response], self.request) elif action == constants.NOTIFY_NEW_TRUSTED: self.server.daemon.AcceptNewTrusted(data[1:]) pass # No response. elif action == constants.TRUST_YOU_NOW: self.server.daemon.MarkPeerAsTrusting(self.client_address[0]) pass # No response. elif action == constants.DO_YOU_TRUST: response = self.server.daemon.IsTrusted(data[1]) compression.Send([action, response], self.request) rec.Advance() compression.Send(constants.END_OF_STREAM, self.request) class StatusSocketServer(SocketServer.ThreadingMixIn, SocketServer.TCPServer): def __init__(self, daemon): address = (daemon.ip, constants.STATUS_PORT) SocketServer.TCPServer.__init__(self, address, StatusHandler) self.daemon = daemon
apache-2.0
TemoaProject/temoa
temoa_model/temoa_config.py
1
19245
""" Tools for Energy Model Optimization and Analysis (Temoa): An open source framework for energy systems optimization modeling Copyright (C) 2015, NC State University 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. A complete copy of the GNU General Public License v2 (GPLv2) is available in LICENSE.txt. Users uncompressing this from an archive may not have received this license file. If not, see <http://www.gnu.org/licenses/>. """ from os.path import abspath, isfile, splitext, dirname from os import sep import re def db_2_dat(ifile, ofile, options): # Adapted from DB_to_DAT.py import sqlite3 import sys import re import getopt def write_tech_mga(f): cur.execute("SELECT tech FROM technologies") f.write("set tech_mga :=\n") for row in cur: f.write(row[0] + '\n') f.write(';\n\n') def write_tech_sector(f): sectors = set() cur.execute("SELECT sector FROM technologies") for row in cur: sectors.add(row[0]) for s in sectors: cur.execute("SELECT tech FROM technologies WHERE sector == '" + s + "'") f.write("set tech_" + s + " :=\n") for row in cur: f.write(row[0] + '\n') f.write(';\n\n') def query_table (t_properties, f): t_type = t_properties[0] #table type (set or param) t_name = t_properties[1] #table name t_dtname = t_properties[2] #DAT table name when DB table must be subdivided t_flag = t_properties[3] #table flag, if any t_index = t_properties[4] #table column index after which '#' should be specified if type(t_flag) is list: #tech production table has a list for flags; this is currently hard-wired db_query = "SELECT * FROM " + t_name + " WHERE flag=='p' OR flag=='pb' OR flag=='ps'" cur.execute(db_query) if cur.fetchone() is None: return if t_type == "set": f.write("set " + t_dtname + " := \n") else: f.write("param " + t_dtname + " := \n") elif t_flag != '': #check to see if flag is empty, if not use it to make table db_query = "SELECT * FROM " + t_name + " WHERE flag=='" + t_flag + "'" cur.execute(db_query) if cur.fetchone() is None: return if t_type == "set": f.write("set " + t_dtname + " := \n") else: f.write("param " + t_dtname + " := \n") else: #Only other possible case is empty flag, then 1-to-1 correspodence between DB and DAT table names db_query = "SELECT * FROM " + t_name cur.execute(db_query) if cur.fetchone() is None: return if t_type == "set": f.write("set " + t_name + " := \n") else: f.write("param " + t_name + " := \n") cur.execute(db_query) if t_index == 0: #make sure that units and descriptions are commented out in DAT file for line in cur: str_row = str(line[0]) + "\n" f.write(str_row) print(str_row) else: for line in cur: before_comments = line[:t_index+1] before_comments = re.sub('[(]', '', str(before_comments)) before_comments = re.sub('[\',)]', ' ', str(before_comments)) after_comments = line[t_index+2:] after_comments = re.sub('[(]', '', str(after_comments)) after_comments = re.sub('[\',)]', ' ', str(after_comments)) search_afcom = re.search(r'^\W+$', str(after_comments)) #Search if after_comments is empty. if not search_afcom : str_row = before_comments + "# " + after_comments + "\n" else : str_row = before_comments + "\n" f.write(str_row) print(str_row) f.write(';\n\n') #[set or param, table_name, DAT fieldname, flag (if any), index (where to insert '#') table_list = [ ['set', 'time_periods', 'time_exist', 'e', 0], ['set', 'time_periods', 'time_future', 'f', 0], ['set', 'time_season', '', '', 0], ['set', 'time_of_day', '', '', 0], ['set', 'regions', '', '', 0], ['set', 'tech_curtailment', '', '', 0], ['set', 'tech_flex', '', '', 0], ['set', 'tech_reserve', '', '', 0], ['set', 'technologies', 'tech_resource', 'r', 0], ['set', 'technologies', 'tech_production', ['p','pb','ps'], 0], ['set', 'technologies', 'tech_baseload', 'pb', 0], ['set', 'technologies', 'tech_storage', 'ps', 0], ['set', 'tech_ramping', '', '', 0], ['set', 'tech_exchange', '', '', 0], ['set', 'commodities', 'commodity_physical', 'p', 0], ['set', 'commodities', 'commodity_emissions', 'e', 0], ['set', 'commodities', 'commodity_demand', 'd', 0], ['set', 'tech_groups', '', '', 0], ['set', 'tech_annual', '', '', 0], ['set', 'groups', '', '', 0], ['param','MinGenGroupTarget', '', '', 2], ['param','MinGenGroupWeight', '', '', 3], ['param','LinkedTechs', '', '', 3], ['param','SegFrac', '', '', 2], ['param','DemandSpecificDistribution','', '', 4], ['param','CapacityToActivity', '', '', 2], ['param','PlanningReserveMargin', '', '', 2], ['param','GlobalDiscountRate', '', '', 0], ['param','MyopicBaseyear', '', '', 0], ['param','DiscountRate', '', '', 3], ['param','EmissionActivity', '', '', 6], ['param','EmissionLimit', '', '', 3], ['param','Demand', '', '', 3], ['param','TechOutputSplit', '', '', 4], ['param','TechInputSplit', '', '', 4], ['param','MinCapacity', '', '', 3], ['param','MaxCapacity', '', '', 3], ['param','MaxActivity', '', '', 3], ['param','MinActivity', '', '', 3], ['param','MaxResource', '', '', 2], ['param','GrowthRateMax', '', '', 2], ['param','GrowthRateSeed', '', '', 2], ['param','LifetimeTech', '', '', 2], ['param','LifetimeProcess', '', '', 3], ['param','LifetimeLoanTech', '', '', 2], ['param','CapacityFactorTech', '', '', 4], ['param','CapacityFactorProcess', '', '', 5], ['param','Efficiency', '', '', 5], ['param','ExistingCapacity', '', '', 3], ['param','CostInvest', '', '', 3], ['param','CostFixed', '', '', 4], ['param','CostVariable', '', '', 4], ['param','CapacityCredit', '', '', 4], ['param','RampUp', '', '', 2], ['param','RampDown', '', '', 2], ['param','StorageInitFrac', '', '', 3], ['param','StorageDuration', '', '', 2]] with open(ofile, 'w') as f: f.write('data ;\n\n') #connect to the database con = sqlite3.connect(ifile, isolation_level=None) cur = con.cursor() # a database cursor is a control structure that enables traversal over the records in a database con.text_factory = str #this ensures data is explored with the correct UTF-8 encoding # Return the full list of existing tables. table_exist = cur.execute("SELECT name FROM sqlite_master WHERE type='table'").fetchall() table_exist = [i[0] for i in table_exist] for table in table_list: if table[1] in table_exist: query_table(table, f) if options.mga_weight == 'integer': write_tech_mga(f) if options.mga_weight == 'normalized': write_tech_sector(f) # Making sure the database is empty from the begining for a myopic solve if options.myopic: cur.execute("DELETE FROM Output_CapacityByPeriodAndTech WHERE scenario="+"'"+str(options.scenario)+"'") cur.execute("DELETE FROM Output_Emissions WHERE scenario="+"'"+str(options.scenario)+"'") cur.execute("DELETE FROM Output_Costs WHERE scenario="+"'"+str(options.scenario)+"'") cur.execute("DELETE FROM Output_Objective WHERE scenario="+"'"+str(options.scenario)+"'") cur.execute("DELETE FROM Output_VFlow_In WHERE scenario="+"'"+str(options.scenario)+"'") cur.execute("DELETE FROM Output_VFlow_Out WHERE scenario="+"'"+str(options.scenario)+"'") cur.execute("DELETE FROM Output_V_Capacity WHERE scenario="+"'"+str(options.scenario)+"'") cur.execute("DELETE FROM Output_Curtailment WHERE scenario="+"'"+str(options.scenario)+"'") cur.execute("VACUUM") con.commit() cur.close() con.close() class TemoaConfig( object ): states = ( ('mga', 'exclusive'), ) tokens = ( 'dot_dat', 'output', 'scenario', 'how_to_cite', 'version', 'solver', 'neos', 'keep_pyomo_lp_file', 'saveEXCEL', 'myopic' 'keep_myopic_databases' 'saveTEXTFILE', 'mgaslack', 'mgaiter', 'path_to_data', 'path_to_logs', 'mgaweight' ) t_ANY_ignore = '[ \t]' def __init__(self, **kwargs): # Make compatible with Python 2.7 and 3 try: import queue except: import Queue as queue self.__error = list() self.__mga_todo = queue.Queue() self.__mga_done = queue.Queue() self.file_location = None self.dot_dat = list() # Use Kevin's name. self.output = None # May update to a list if multiple output is required. self.scenario = None self.saveEXCEL = False self.myopic = False self.KeepMyopicDBs = False self.saveTEXTFILE = False self.how_to_cite = None self.version = False self.neos = False self.generateSolverLP = False self.keepPyomoLP = False self.mga = None # mga slack value self.mga_iter = None self.mga_weight = None # To keep consistent with Kevin's argumetn parser, will be removed in the future. self.graph_format = None self.show_capacity = False self.graph_type = 'separate_vintages' self.use_splines = False #Introduced during UI Development self.path_to_data = re.sub('temoa_model$', 'data_files', dirname(abspath(__file__)))# Path to where automated excel and text log folder will be save as output. self.path_to_logs = self.path_to_data+sep+"debug_logs" #Path to where debug logs will be generated for each run. By default in debug_logs folder in db_io. self.path_to_lp_files = None self.abort_temoa = False if 'd_solver' in kwargs.keys(): self.solver = kwargs['d_solver'] else: self.solver = None def __repr__(self): width = 25 spacer = '\n' + '-'*width + '\n' msg = spacer msg += '{:>{}s}: {}\n'.format('Config file', width, self.file_location) for i in self.dot_dat: if self.dot_dat.index(i) == 0: msg += '{:>{}s}: {}\n'.format('Input file', width, i) else: msg += '{:>25s} {}\n'.format(' ', i) msg += '{:>{}s}: {}\n'.format('Output file', width, self.output) msg += '{:>{}s}: {}\n'.format('Scenario', width, self.scenario) msg += '{:>{}s}: {}\n'.format('Spreadsheet output', width, self.saveEXCEL) msg += '{:>{}s}: {}\n'.format('Myopic scheme', width, self.myopic) msg += '{:>{}s}: {}\n'.format('Retain myopic databases', width, self.KeepMyopicDBs) msg += spacer msg += '{:>{}s}: {}\n'.format('Citation output status', width, self.how_to_cite) msg += '{:>{}s}: {}\n'.format('NEOS status', width, self.neos) msg += '{:>{}s}: {}\n'.format('Version output status', width, self.version) msg += spacer msg += '{:>{}s}: {}\n'.format('Selected solver status', width, self.solver) msg += '{:>{}s}: {}\n'.format('Solver LP write status', width, self.generateSolverLP) msg += '{:>{}s}: {}\n'.format('Pyomo LP write status', width, self.keepPyomoLP) msg += spacer msg += '{:>{}s}: {}\n'.format('MGA slack value', width, self.mga) msg += '{:>{}s}: {}\n'.format('MGA # of iterations', width, self.mga_iter) msg += '{:>{}s}: {}\n'.format('MGA weighting method', width, self.mga_weight) msg += '**NOTE: If you are performing MGA runs, navigate to the DAT file and make any modifications to the MGA sets before proceeding.' return msg def t_ANY_COMMENT(self, t): r'\#.*' pass def t_dot_dat(self, t): r'--input[\s\=]+[-\\\/\:\.\~\w]+(\.dat|\.db|\.sqlite)\b' self.dot_dat.append(abspath(t.value.replace('=', ' ').split()[1])) def t_output(self, t): r'--output[\s\=]+[-\\\/\:\.\~\w]+(\.db|\.sqlite)\b' self.output = abspath(t.value.replace('=', ' ').split()[1]) def t_scenario(self, t): r'--scenario[\s\=]+\w+\b' self.scenario = t.value.replace('=', ' ').split()[1] def t_saveEXCEL(self, t): r'--saveEXCEL\b' self.saveEXCEL = True def t_myopic(self, t): r'--myopic\b' self.myopic = True def t_keep_myopic_databases(self, t): r'--keep_myopic_databases\b' self.KeepMyopicDBs = True def t_saveTEXTFILE(self, t): r'--saveTEXTFILE\b' self.saveTEXTFILE = True def t_path_to_data(self, t): r'--path_to_data[\s\=]+[-\\\/\:\.\~\w\ ]+\b' self.path_to_data = abspath(t.value.replace('=', ',').split(",")[1]) def t_path_to_logs(self, t): r'--path_to_logs[\s\=]+[-\\\/\:\.\~\w\ ]+\b' self.path_to_logs = abspath(t.value.replace('=', ',').split(",")[1]) def t_how_to_cite(self, t): r'--how_to_cite\b' self.how_to_cite = True def t_version(self, t): r'--version\b' self.version = True def t_neos(self, t): r'--neos\b' self.neos = True def t_solver(self, t): r'--solver[\s\=]+\w+\b' self.solver = t.value.replace('=', ' ').split()[1] def t_keep_pyomo_lp_file(self, t): r'--keep_pyomo_lp_file\b' self.keepPyomoLP = True def t_begin_mga(self, t): r'--mga[\s\=]+\{' t.lexer.push_state('mga') t.lexer.level = 1 def t_mga_mgaslack(self, t): r'slack[\s\=]+[\.\d]+' self.mga = float(t.value.replace('=', ' ').split()[1]) def t_mga_mgaiter(self, t): r'iteration[\s\=]+[\d]+' self.mga_iter = int(t.value.replace('=', ' ').split()[1]) def t_mga_mgaweight(self, t): r'weight[\s\=]+(integer|normalized|distance)\b' self.mga_weight = t.value.replace('=', ' ').split()[1] def t_mga_end(self, t): r'\}' t.lexer.pop_state() t.lexer.level -= 1 def t_ANY_newline(self,t): r'\n+|(\r\n)+|\r+' # '\n' (In linux) = '\r\n' (In Windows) = '\r' (In Mac OS) t.lexer.lineno += len(t.value) def t_ANY_error(self, t): if not self.__error: self.__error.append({'line': [t.lineno, t.lineno], 'index': [t.lexpos, t.lexpos], 'value': t.value[0]}) elif t.lexpos - self.__error[-1]['index'][-1] == 1: self.__error[-1]['line' ][-1] = t.lineno self.__error[-1]['index'][-1] = t.lexpos self.__error[-1]['value'] += t.value[0] else: self.__error.append({'line': [t.lineno, t.lineno], 'index': [t.lexpos, t.lexpos], 'value': t.value[0]}) t.lexer.skip(1) def next_mga(self): if not self.__mga_todo.empty(): self.__mga_done.put(self.scenario) self.scenario = self.__mga_todo.get() return True else: return False def build(self,**kwargs): import ply.lex as lex, os, sys db_or_dat = True # True means input file is a db file. False means input is a dat file. if 'config' in kwargs: if isfile(kwargs['config']): self.file_location= abspath(kwargs.pop('config')) else: msg = 'No such file exists: {}'.format(kwargs.pop('config')) raise Exception( msg ) self.lexer = lex.lex(module=self, **kwargs) if self.file_location: try: with open(self.file_location, encoding="utf8") as f: self.lexer.input(f.read()) except: with open(self.file_location, 'r') as f: self.lexer.input(f.read()) while True: tok = self.lexer.token() if not tok: break if self.__error: width = 25 msg = '\nIllegal character(s) in config file:\n' msg += '-'*width + '\n' for e in self.__error: msg += "Line {} to {}: '{}'\n".format(e['line'][0], e['line'][1], e['value']) msg += '-'*width + '\n' sys.stderr.write(msg) try: txt_file = open(self.path_to_logs+os.sep+"Complete_OutputLog.log", "w") except BaseException as io_exc: sys.stderr.write("Log file cannot be opened. Please check path. Trying to find:\n"+self.path_to_logs+" folder\n") txt_file = open("OutputLog.log", "w") txt_file.write( msg ) txt_file.close() self.abort_temoa = True if not self.dot_dat: raise Exception('Input file not specified.') for i in self.dot_dat: if not isfile(i): raise Exception('Cannot locate input file: {}'.format(i)) i_name, i_ext = splitext(i) if (i_ext == '.dat') or (i_ext == '.txt'): db_or_dat = False elif (i_ext == '.db') or (i_ext == '.sqlite') or (i_ext == '.sqlite3') or (i_ext == 'sqlitedb'): db_or_dat = True if not self.output and db_or_dat: raise Exception('Output file not specified.') if db_or_dat and not isfile(self.output): raise Exception('Cannot locate output file: {}.'.format(self.output)) if not self.scenario and db_or_dat: raise Exception('Scenario name not specified.') if self.mga_iter: for i in range(self.mga_iter): self.__mga_todo.put(self.scenario + '_mga_' + str(i)) f = open(os.devnull, 'w'); sys.stdout = f # Suppress the original DB_to_DAT.py output counter = 0 for ifile in self.dot_dat: i_name, i_ext = splitext(ifile) if i_ext != '.dat': ofile = i_name + '.dat' db_2_dat(ifile, ofile, self) self.dot_dat[self.dot_dat.index(ifile)] = ofile counter += 1 f.close() sys.stdout = sys.__stdout__ if counter > 0: sys.stderr.write("\n{} .db DD file(s) converted\n".format(counter))
gpl-2.0
tyagiarpit/servo
tests/wpt/css-tests/tools/html5lib/html5lib/treewalkers/pulldom.py
1729
2302
from __future__ import absolute_import, division, unicode_literals from xml.dom.pulldom import START_ELEMENT, END_ELEMENT, \ COMMENT, IGNORABLE_WHITESPACE, CHARACTERS from . import _base from ..constants import voidElements class TreeWalker(_base.TreeWalker): def __iter__(self): ignore_until = None previous = None for event in self.tree: if previous is not None and \ (ignore_until is None or previous[1] is ignore_until): if previous[1] is ignore_until: ignore_until = None for token in self.tokens(previous, event): yield token if token["type"] == "EmptyTag": ignore_until = previous[1] previous = event if ignore_until is None or previous[1] is ignore_until: for token in self.tokens(previous, None): yield token elif ignore_until is not None: raise ValueError("Illformed DOM event stream: void element without END_ELEMENT") def tokens(self, event, next): type, node = event if type == START_ELEMENT: name = node.nodeName namespace = node.namespaceURI attrs = {} for attr in list(node.attributes.keys()): attr = node.getAttributeNode(attr) attrs[(attr.namespaceURI, attr.localName)] = attr.value if name in voidElements: for token in self.emptyTag(namespace, name, attrs, not next or next[1] is not node): yield token else: yield self.startTag(namespace, name, attrs) elif type == END_ELEMENT: name = node.nodeName namespace = node.namespaceURI if name not in voidElements: yield self.endTag(namespace, name) elif type == COMMENT: yield self.comment(node.nodeValue) elif type in (IGNORABLE_WHITESPACE, CHARACTERS): for token in self.text(node.nodeValue): yield token else: yield self.unknown(type)
mpl-2.0
alexus37/AugmentedRealityChess
pythonAnimations/pyOpenGLChess/engineDirectory/oglc-env/lib/python2.7/site-packages/OpenGL/GL/ARB/texture_view.py
9
1978
'''OpenGL extension ARB.texture_view This module customises the behaviour of the OpenGL.raw.GL.ARB.texture_view to provide a more Python-friendly API Overview (from the spec) This extension allows a texture's data store to be "viewed" in multiple ways, either reinterpreting the data format/type as a different format/ type with the same element size, or by clamping the mipmap level range or array slice range. The goals of this extension are to avoid having these alternate views become shared mutable containers of shared mutable objects, and to add the views to the API in a minimally invasive way. No new object types are added. Conceptually, a texture object is split into the following parts: - A data store holding texel data. - State describing which portions of the data store to use, and how to interpret the data elements. - An embedded sampler object. - Various other texture parameters. With this extension, multiple textures can share a data store and have different state describing which portions of the data store to use and how to interpret the data elements. The data store is refcounted and not destroyed until the last texture sharing it is deleted. This extension leverages the ARB_texture_storage concept of an "immutable texture". Views can only be created of textures created with TexStorage. The official definition of this extension is available here: http://www.opengl.org/registry/specs/ARB/texture_view.txt ''' from OpenGL import platform, constant, arrays from OpenGL import extensions, wrapper import ctypes from OpenGL.raw.GL import _types, _glgets from OpenGL.raw.GL.ARB.texture_view import * from OpenGL.raw.GL.ARB.texture_view import _EXTENSION_NAME def glInitTextureViewARB(): '''Return boolean indicating whether this extension is available''' from OpenGL import extensions return extensions.hasGLExtension( _EXTENSION_NAME ) ### END AUTOGENERATED SECTION
mit
Francis-Liu/animated-broccoli
nova/vnc/xvp_proxy.py
16
6278
#!/usr/bin/env python # Copyright (c) 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. """Eventlet WSGI Services to proxy VNC for XCP protocol.""" import socket import eventlet import eventlet.green import eventlet.greenio import eventlet.wsgi from oslo_config import cfg from oslo_log import log as logging import webob from nova.consoleauth import rpcapi as consoleauth_rpcapi from nova import context from nova.i18n import _LI from nova import version from nova import wsgi LOG = logging.getLogger(__name__) xvp_proxy_opts = [ cfg.IntOpt('xvpvncproxy_port', default=6081, min=1, max=65535, help='Port that the XCP VNC proxy should bind to'), cfg.StrOpt('xvpvncproxy_host', default='0.0.0.0', help='Address that the XCP VNC proxy should bind to'), ] CONF = cfg.CONF CONF.register_opts(xvp_proxy_opts) class XCPVNCProxy(object): """Class to use the xvp auth protocol to proxy instance vnc consoles.""" def one_way_proxy(self, source, dest): """Proxy tcp connection from source to dest.""" while True: try: d = source.recv(32384) except Exception: d = None # If recv fails, send a write shutdown the other direction if d is None or len(d) == 0: dest.shutdown(socket.SHUT_WR) break # If send fails, terminate proxy in both directions try: # sendall raises an exception on write error, unlike send dest.sendall(d) except Exception: source.close() dest.close() break def handshake(self, req, connect_info, sockets): """Execute hypervisor-specific vnc auth handshaking (if needed).""" host = connect_info['host'] port = int(connect_info['port']) server = eventlet.connect((host, port)) # Handshake as necessary if connect_info.get('internal_access_path'): server.sendall("CONNECT %s HTTP/1.1\r\n\r\n" % connect_info['internal_access_path']) data = "" while True: b = server.recv(1) if b: data += b if data.find("\r\n\r\n") != -1: if not data.split("\r\n")[0].find("200"): LOG.info(_LI("Error in handshake format: %s"), data) return break if not b or len(data) > 4096: LOG.info(_LI("Error in handshake: %s"), data) return client = req.environ['eventlet.input'].get_socket() client.sendall("HTTP/1.1 200 OK\r\n\r\n") sockets['client'] = client sockets['server'] = server def proxy_connection(self, req, connect_info, start_response): """Spawn bi-directional vnc proxy.""" sockets = {} t0 = eventlet.spawn(self.handshake, req, connect_info, sockets) t0.wait() if not sockets.get('client') or not sockets.get('server'): LOG.info(_LI("Invalid request: %s"), req) start_response('400 Invalid Request', [('content-type', 'text/html')]) return "Invalid Request" client = sockets['client'] server = sockets['server'] t1 = eventlet.spawn(self.one_way_proxy, client, server) t2 = eventlet.spawn(self.one_way_proxy, server, client) t1.wait() t2.wait() # Make sure our sockets are closed server.close() client.close() def __call__(self, environ, start_response): try: req = webob.Request(environ) LOG.info(_LI("Request: %s"), req) token = req.params.get('token') if not token: LOG.info(_LI("Request made with missing token: %s"), req) start_response('400 Invalid Request', [('content-type', 'text/html')]) return "Invalid Request" ctxt = context.get_admin_context() api = consoleauth_rpcapi.ConsoleAuthAPI() connect_info = api.check_token(ctxt, token) if not connect_info: LOG.info(_LI("Request made with invalid token: %s"), req) start_response('401 Not Authorized', [('content-type', 'text/html')]) return "Not Authorized" return self.proxy_connection(req, connect_info, start_response) except Exception as e: LOG.info(_LI("Unexpected error: %s"), e) class SafeHttpProtocol(eventlet.wsgi.HttpProtocol): """HttpProtocol wrapper to suppress IOErrors. The proxy code above always shuts down client connections, so we catch the IOError that raises when the SocketServer tries to flush the connection. """ def finish(self): try: eventlet.green.BaseHTTPServer.BaseHTTPRequestHandler.finish(self) except IOError: pass eventlet.greenio.shutdown_safe(self.connection) self.connection.close() def get_wsgi_server(): LOG.info(_LI("Starting nova-xvpvncproxy node (version %s)"), version.version_string_with_package()) return wsgi.Server("XCP VNC Proxy", XCPVNCProxy(), protocol=SafeHttpProtocol, host=CONF.xvpvncproxy_host, port=CONF.xvpvncproxy_port)
apache-2.0
reaperhulk/bcrypt
tests/test_bcrypt.py
2
16169
import os import pytest import bcrypt _test_vectors = [ ( b"Kk4DQuMMfZL9o", b"$2b$04$cVWp4XaNU8a4v1uMRum2SO", b"$2b$04$cVWp4XaNU8a4v1uMRum2SO026BWLIoQMD/TXg5uZV.0P.uO8m3YEm", ), ( b"9IeRXmnGxMYbs", b"$2b$04$pQ7gRO7e6wx/936oXhNjrO", b"$2b$04$pQ7gRO7e6wx/936oXhNjrOUNOHL1D0h1N2IDbJZYs.1ppzSof6SPy", ), ( b"xVQVbwa1S0M8r", b"$2b$04$SQe9knOzepOVKoYXo9xTte", b"$2b$04$SQe9knOzepOVKoYXo9xTteNYr6MBwVz4tpriJVe3PNgYufGIsgKcW", ), ( b"Zfgr26LWd22Za", b"$2b$04$eH8zX.q5Q.j2hO1NkVYJQO", b"$2b$04$eH8zX.q5Q.j2hO1NkVYJQOM6KxntS/ow3.YzVmFrE4t//CoF4fvne", ), ( b"Tg4daC27epFBE", b"$2b$04$ahiTdwRXpUG2JLRcIznxc.", b"$2b$04$ahiTdwRXpUG2JLRcIznxc.s1.ydaPGD372bsGs8NqyYjLY1inG5n2", ), ( b"xhQPMmwh5ALzW", b"$2b$04$nQn78dV0hGHf5wUBe0zOFu", b"$2b$04$nQn78dV0hGHf5wUBe0zOFu8n07ZbWWOKoGasZKRspZxtt.vBRNMIy", ), ( b"59je8h5Gj71tg", b"$2b$04$cvXudZ5ugTg95W.rOjMITu", b"$2b$04$cvXudZ5ugTg95W.rOjMITuM1jC0piCl3zF5cmGhzCibHZrNHkmckG", ), ( b"wT4fHJa2N9WSW", b"$2b$04$YYjtiq4Uh88yUsExO0RNTu", b"$2b$04$YYjtiq4Uh88yUsExO0RNTuEJ.tZlsONac16A8OcLHleWFjVawfGvO", ), ( b"uSgFRnQdOgm4S", b"$2b$04$WLTjgY/pZSyqX/fbMbJzf.", b"$2b$04$WLTjgY/pZSyqX/fbMbJzf.qxCeTMQOzgL.CimRjMHtMxd/VGKojMu", ), ( b"tEPtJZXur16Vg", b"$2b$04$2moPs/x/wnCfeQ5pCheMcu", b"$2b$04$2moPs/x/wnCfeQ5pCheMcuSJQ/KYjOZG780UjA/SiR.KsYWNrC7SG", ), ( b"vvho8C6nlVf9K", b"$2b$04$HrEYC/AQ2HS77G78cQDZQ.", b"$2b$04$HrEYC/AQ2HS77G78cQDZQ.r44WGcruKw03KHlnp71yVQEwpsi3xl2", ), ( b"5auCCY9by0Ruf", b"$2b$04$vVYgSTfB8KVbmhbZE/k3R.", b"$2b$04$vVYgSTfB8KVbmhbZE/k3R.ux9A0lJUM4CZwCkHI9fifke2.rTF7MG", ), ( b"GtTkR6qn2QOZW", b"$2b$04$JfoNrR8.doieoI8..F.C1O", b"$2b$04$JfoNrR8.doieoI8..F.C1OQgwE3uTeuardy6lw0AjALUzOARoyf2m", ), ( b"zKo8vdFSnjX0f", b"$2b$04$HP3I0PUs7KBEzMBNFw7o3O", b"$2b$04$HP3I0PUs7KBEzMBNFw7o3O7f/uxaZU7aaDot1quHMgB2yrwBXsgyy", ), ( b"I9VfYlacJiwiK", b"$2b$04$xnFVhJsTzsFBTeP3PpgbMe", b"$2b$04$xnFVhJsTzsFBTeP3PpgbMeMREb6rdKV9faW54Sx.yg9plf4jY8qT6", ), ( b"VFPO7YXnHQbQO", b"$2b$04$WQp9.igoLqVr6Qk70mz6xu", b"$2b$04$WQp9.igoLqVr6Qk70mz6xuRxE0RttVXXdukpR9N54x17ecad34ZF6", ), ( b"VDx5BdxfxstYk", b"$2b$04$xgZtlonpAHSU/njOCdKztO", b"$2b$04$xgZtlonpAHSU/njOCdKztOPuPFzCNVpB4LGicO4/OGgHv.uKHkwsS", ), ( b"dEe6XfVGrrfSH", b"$2b$04$2Siw3Nv3Q/gTOIPetAyPr.", b"$2b$04$2Siw3Nv3Q/gTOIPetAyPr.GNj3aO0lb1E5E9UumYGKjP9BYqlNWJe", ), ( b"cTT0EAFdwJiLn", b"$2b$04$7/Qj7Kd8BcSahPO4khB8me", b"$2b$04$7/Qj7Kd8BcSahPO4khB8me4ssDJCW3r4OGYqPF87jxtrSyPj5cS5m", ), ( b"J8eHUDuxBB520", b"$2b$04$VvlCUKbTMjaxaYJ.k5juoe", b"$2b$04$VvlCUKbTMjaxaYJ.k5juoecpG/7IzcH1AkmqKi.lIZMVIOLClWAk.", ), ( b"U*U", b"$2a$05$CCCCCCCCCCCCCCCCCCCCC.", b"$2a$05$CCCCCCCCCCCCCCCCCCCCC.E5YPO9kmyuRGyh0XouQYb4YMJKvyOeW", ), ( b"U*U*", b"$2a$05$CCCCCCCCCCCCCCCCCCCCC.", b"$2a$05$CCCCCCCCCCCCCCCCCCCCC.VGOzA784oUp/Z0DY336zx7pLYAy0lwK", ), ( b"U*U*U", b"$2a$05$XXXXXXXXXXXXXXXXXXXXXO", b"$2a$05$XXXXXXXXXXXXXXXXXXXXXOAcXxm9kjPGEMsLznoKqmqw7tc8WCx4a", ), ( b"0123456789abcdefghijklmnopqrstuvwxyz" b"ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" b"chars after 72 are ignored", b"$2a$05$abcdefghijklmnopqrstuu", b"$2a$05$abcdefghijklmnopqrstuu5s2v8.iXieOjg/.AySBTTZIIVFJeBui", ), ( b"\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" b"\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" b"\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" b"\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" b"\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" b"\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" b"chars after 72 are ignored as usual", b"$2a$05$/OK.fbVrR/bpIqNJ5ianF.", b"$2a$05$/OK.fbVrR/bpIqNJ5ianF.swQOIzjOiJ9GHEPuhEkvqrUyvWhEMx6", ), ( b"\xa3", b"$2a$05$/OK.fbVrR/bpIqNJ5ianF.", b"$2a$05$/OK.fbVrR/bpIqNJ5ianF.Sa7shbm4.OzKpvFnX1pQLmQW96oUlCq", ), ] _2y_test_vectors = [ ( b"\xa3", b"$2y$05$/OK.fbVrR/bpIqNJ5ianF.Sa7shbm4.OzKpvFnX1pQLmQW96oUlCq", b"$2y$05$/OK.fbVrR/bpIqNJ5ianF.Sa7shbm4.OzKpvFnX1pQLmQW96oUlCq", ), ( b"\xff\xff\xa3", b"$2y$05$/OK.fbVrR/bpIqNJ5ianF.CE5elHaaO4EbggVDjb8P19RukzXSM3e", b"$2y$05$/OK.fbVrR/bpIqNJ5ianF.CE5elHaaO4EbggVDjb8P19RukzXSM3e", ), ] def test_gensalt_basic(monkeypatch): monkeypatch.setattr(os, "urandom", lambda n: b"0000000000000000") assert bcrypt.gensalt() == b"$2b$12$KB.uKB.uKB.uKB.uKB.uK." @pytest.mark.parametrize( ("rounds", "expected"), [ (4, b"$2b$04$KB.uKB.uKB.uKB.uKB.uK."), (5, b"$2b$05$KB.uKB.uKB.uKB.uKB.uK."), (6, b"$2b$06$KB.uKB.uKB.uKB.uKB.uK."), (7, b"$2b$07$KB.uKB.uKB.uKB.uKB.uK."), (8, b"$2b$08$KB.uKB.uKB.uKB.uKB.uK."), (9, b"$2b$09$KB.uKB.uKB.uKB.uKB.uK."), (10, b"$2b$10$KB.uKB.uKB.uKB.uKB.uK."), (11, b"$2b$11$KB.uKB.uKB.uKB.uKB.uK."), (12, b"$2b$12$KB.uKB.uKB.uKB.uKB.uK."), (13, b"$2b$13$KB.uKB.uKB.uKB.uKB.uK."), (14, b"$2b$14$KB.uKB.uKB.uKB.uKB.uK."), (15, b"$2b$15$KB.uKB.uKB.uKB.uKB.uK."), (16, b"$2b$16$KB.uKB.uKB.uKB.uKB.uK."), (17, b"$2b$17$KB.uKB.uKB.uKB.uKB.uK."), (18, b"$2b$18$KB.uKB.uKB.uKB.uKB.uK."), (19, b"$2b$19$KB.uKB.uKB.uKB.uKB.uK."), (20, b"$2b$20$KB.uKB.uKB.uKB.uKB.uK."), (21, b"$2b$21$KB.uKB.uKB.uKB.uKB.uK."), (22, b"$2b$22$KB.uKB.uKB.uKB.uKB.uK."), (23, b"$2b$23$KB.uKB.uKB.uKB.uKB.uK."), (24, b"$2b$24$KB.uKB.uKB.uKB.uKB.uK."), ], ) def test_gensalt_rounds_valid(rounds, expected, monkeypatch): monkeypatch.setattr(os, "urandom", lambda n: b"0000000000000000") assert bcrypt.gensalt(rounds) == expected @pytest.mark.parametrize("rounds", list(range(1, 4))) def test_gensalt_rounds_invalid(rounds): with pytest.raises(ValueError): bcrypt.gensalt(rounds) def test_gensalt_bad_prefix(): with pytest.raises(ValueError): bcrypt.gensalt(prefix="bad") def test_gensalt_2a_prefix(monkeypatch): monkeypatch.setattr(os, "urandom", lambda n: b"0000000000000000") assert bcrypt.gensalt(prefix=b"2a") == b"$2a$12$KB.uKB.uKB.uKB.uKB.uK." @pytest.mark.parametrize(("password", "salt", "hashed"), _test_vectors) def test_hashpw_new(password, salt, hashed): assert bcrypt.hashpw(password, salt) == hashed @pytest.mark.parametrize(("password", "salt", "hashed"), _test_vectors) def test_checkpw(password, salt, hashed): assert bcrypt.checkpw(password, hashed) is True @pytest.mark.parametrize(("password", "salt", "hashed"), _test_vectors) def test_hashpw_existing(password, salt, hashed): assert bcrypt.hashpw(password, hashed) == hashed @pytest.mark.parametrize(("password", "hashed", "expected"), _2y_test_vectors) def test_hashpw_2y_prefix(password, hashed, expected): assert bcrypt.hashpw(password, hashed) == expected @pytest.mark.parametrize(("password", "hashed", "expected"), _2y_test_vectors) def test_checkpw_2y_prefix(password, hashed, expected): assert bcrypt.checkpw(password, hashed) is True def test_hashpw_invalid(): with pytest.raises(ValueError): bcrypt.hashpw(b"password", b"$2z$04$cVWp4XaNU8a4v1uMRum2SO") def test_checkpw_wrong_password(): assert ( bcrypt.checkpw( b"badpass", b"$2b$04$2Siw3Nv3Q/gTOIPetAyPr.GNj3aO0lb1E5E9UumYGKjP9BYqlNWJe", ) is False ) def test_checkpw_bad_salt(): with pytest.raises(ValueError): bcrypt.checkpw( b"badpass", b"$2b$04$?Siw3Nv3Q/gTOIPetAyPr.GNj3aO0lb1E5E9UumYGKjP9BYqlNWJe", ) def test_checkpw_str_password(): with pytest.raises(TypeError): bcrypt.checkpw("password", b"$2b$04$cVWp4XaNU8a4v1uMRum2SO") def test_checkpw_str_salt(): with pytest.raises(TypeError): bcrypt.checkpw(b"password", "$2b$04$cVWp4XaNU8a4v1uMRum2SO") def test_hashpw_str_password(): with pytest.raises(TypeError): bcrypt.hashpw("password", b"$2b$04$cVWp4XaNU8a4v1uMRum2SO") def test_hashpw_str_salt(): with pytest.raises(TypeError): bcrypt.hashpw(b"password", "$2b$04$cVWp4XaNU8a4v1uMRum2SO") def test_checkpw_nul_byte(): with pytest.raises(ValueError): bcrypt.checkpw( b"abc\0def", b"$2b$04$2Siw3Nv3Q/gTOIPetAyPr.GNj3aO0lb1E5E9UumYGKjP9BYqlNWJe", ) with pytest.raises(ValueError): bcrypt.checkpw( b"abcdef", b"$2b$04$2S\0w3Nv3Q/gTOIPetAyPr.GNj3aO0lb1E5E9UumYGKjP9BYqlNWJe", ) def test_hashpw_nul_byte(): salt = bcrypt.gensalt(4) with pytest.raises(ValueError): bcrypt.hashpw(b"abc\0def", salt) def test_checkpw_extra_data(): salt = bcrypt.gensalt(4) hashed = bcrypt.hashpw(b"abc", salt) assert bcrypt.checkpw(b"abc", hashed) assert bcrypt.checkpw(b"abc", hashed + b"extra") is False assert bcrypt.checkpw(b"abc", hashed[:-10]) is False @pytest.mark.parametrize( ("rounds", "password", "salt", "expected"), [ [ 4, b"password", b"salt", b"\x5b\xbf\x0c\xc2\x93\x58\x7f\x1c\x36\x35\x55\x5c\x27\x79\x65\x98" b"\xd4\x7e\x57\x90\x71\xbf\x42\x7e\x9d\x8f\xbe\x84\x2a\xba\x34\xd9", ], [ 4, b"password", b"\x00", b"\xc1\x2b\x56\x62\x35\xee\xe0\x4c\x21\x25\x98\x97\x0a\x57\x9a\x67", ], [ 4, b"\x00", b"salt", b"\x60\x51\xbe\x18\xc2\xf4\xf8\x2c\xbf\x0e\xfe\xe5\x47\x1b\x4b\xb9", ], [ # nul bytes in password and string 4, b"password\x00", b"salt\x00", b"\x74\x10\xe4\x4c\xf4\xfa\x07\xbf\xaa\xc8\xa9\x28\xb1\x72\x7f\xac" b"\x00\x13\x75\xe7\xbf\x73\x84\x37\x0f\x48\xef\xd1\x21\x74\x30\x50", ], [ 4, b"pass\x00wor", b"sa\0l", b"\xc2\xbf\xfd\x9d\xb3\x8f\x65\x69\xef\xef\x43\x72\xf4\xde\x83\xc0", ], [ 4, b"pass\x00word", b"sa\0lt", b"\x4b\xa4\xac\x39\x25\xc0\xe8\xd7\xf0\xcd\xb6\xbb\x16\x84\xa5\x6f", ], [ # bigger key 8, b"password", b"salt", b"\xe1\x36\x7e\xc5\x15\x1a\x33\xfa\xac\x4c\xc1\xc1\x44\xcd\x23\xfa" b"\x15\xd5\x54\x84\x93\xec\xc9\x9b\x9b\x5d\x9c\x0d\x3b\x27\xbe\xc7" b"\x62\x27\xea\x66\x08\x8b\x84\x9b\x20\xab\x7a\xa4\x78\x01\x02\x46" b"\xe7\x4b\xba\x51\x72\x3f\xef\xa9\xf9\x47\x4d\x65\x08\x84\x5e\x8d", ], [ # more rounds 42, b"password", b"salt", b"\x83\x3c\xf0\xdc\xf5\x6d\xb6\x56\x08\xe8\xf0\xdc\x0c\xe8\x82\xbd", ], [ # longer password 8, b"Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do " b"eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut " b"enim ad minim veniam, quis nostrud exercitation ullamco laboris " b"nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor " b"in reprehenderit in voluptate velit esse cillum dolore eu fugiat " b"nulla pariatur. Excepteur sint occaecat cupidatat non proident, " b"sunt in culpa qui officia deserunt mollit anim id est laborum.", b"salis\x00", b"\x10\x97\x8b\x07\x25\x3d\xf5\x7f\x71\xa1\x62\xeb\x0e\x8a\xd3\x0a", ], [ # "unicode" 8, b"\x0d\xb3\xac\x94\xb3\xee\x53\x28\x4f\x4a\x22\x89\x3b\x3c\x24\xae", b"\x3a\x62\xf0\xf0\xdb\xce\xf8\x23\xcf\xcc\x85\x48\x56\xea\x10\x28", b"\x20\x44\x38\x17\x5e\xee\x7c\xe1\x36\xc9\x1b\x49\xa6\x79\x23\xff", ], [ # very large key 8, b"\x0d\xb3\xac\x94\xb3\xee\x53\x28\x4f\x4a\x22\x89\x3b\x3c\x24\xae", b"\x3a\x62\xf0\xf0\xdb\xce\xf8\x23\xcf\xcc\x85\x48\x56\xea\x10\x28", b"\x20\x54\xb9\xff\xf3\x4e\x37\x21\x44\x03\x34\x74\x68\x28\xe9\xed" b"\x38\xde\x4b\x72\xe0\xa6\x9a\xdc\x17\x0a\x13\xb5\xe8\xd6\x46\x38" b"\x5e\xa4\x03\x4a\xe6\xd2\x66\x00\xee\x23\x32\xc5\xed\x40\xad\x55" b"\x7c\x86\xe3\x40\x3f\xbb\x30\xe4\xe1\xdc\x1a\xe0\x6b\x99\xa0\x71" b"\x36\x8f\x51\x8d\x2c\x42\x66\x51\xc9\xe7\xe4\x37\xfd\x6c\x91\x5b" b"\x1b\xbf\xc3\xa4\xce\xa7\x14\x91\x49\x0e\xa7\xaf\xb7\xdd\x02\x90" b"\xa6\x78\xa4\xf4\x41\x12\x8d\xb1\x79\x2e\xab\x27\x76\xb2\x1e\xb4" b"\x23\x8e\x07\x15\xad\xd4\x12\x7d\xff\x44\xe4\xb3\xe4\xcc\x4c\x4f" b"\x99\x70\x08\x3f\x3f\x74\xbd\x69\x88\x73\xfd\xf6\x48\x84\x4f\x75" b"\xc9\xbf\x7f\x9e\x0c\x4d\x9e\x5d\x89\xa7\x78\x39\x97\x49\x29\x66" b"\x61\x67\x07\x61\x1c\xb9\x01\xde\x31\xa1\x97\x26\xb6\xe0\x8c\x3a" b"\x80\x01\x66\x1f\x2d\x5c\x9d\xcc\x33\xb4\xaa\x07\x2f\x90\xdd\x0b" b"\x3f\x54\x8d\x5e\xeb\xa4\x21\x13\x97\xe2\xfb\x06\x2e\x52\x6e\x1d" b"\x68\xf4\x6a\x4c\xe2\x56\x18\x5b\x4b\xad\xc2\x68\x5f\xbe\x78\xe1" b"\xc7\x65\x7b\x59\xf8\x3a\xb9\xab\x80\xcf\x93\x18\xd6\xad\xd1\xf5" b"\x93\x3f\x12\xd6\xf3\x61\x82\xc8\xe8\x11\x5f\x68\x03\x0a\x12\x44", ], [ # UTF-8 Greek characters "odysseus" / "telemachos" 8, b"\xe1\xbd\x88\xce\xb4\xcf\x85\xcf\x83\xcf\x83\xce\xb5\xcf\x8d\xcf" b"\x82", b"\xce\xa4\xce\xb7\xce\xbb\xce\xad\xce\xbc\xce\xb1\xcf\x87\xce\xbf" b"\xcf\x82", b"\x43\x66\x6c\x9b\x09\xef\x33\xed\x8c\x27\xe8\xe8\xf3\xe2\xd8\xe6", ], ], ) def test_kdf(rounds, password, salt, expected): derived = bcrypt.kdf( password, salt, len(expected), rounds, ignore_few_rounds=True ) assert derived == expected def test_kdf_str_password(): with pytest.raises(TypeError): bcrypt.kdf("password", b"$2b$04$cVWp4XaNU8a4v1uMRum2SO", 10, 10) def test_kdf_str_salt(): with pytest.raises(TypeError): bcrypt.kdf(b"password", "salt", 10, 10) def test_kdf_no_warn_rounds(): bcrypt.kdf(b"password", b"salt", 10, 10, True) def test_kdf_warn_rounds(): with pytest.warns(UserWarning): bcrypt.kdf(b"password", b"salt", 10, 10) @pytest.mark.parametrize( ("password", "salt", "desired_key_bytes", "rounds", "error"), [ ("pass", b"$2b$04$cVWp4XaNU8a4v1uMRum2SO", 10, 10, TypeError), (b"password", "salt", 10, 10, TypeError), (b"", b"$2b$04$cVWp4XaNU8a4v1uMRum2SO", 10, 10, ValueError), (b"password", b"", 10, 10, ValueError), (b"password", b"$2b$04$cVWp4XaNU8a4v1uMRum2SO", 0, 10, ValueError), (b"password", b"$2b$04$cVWp4XaNU8a4v1uMRum2SO", -3, 10, ValueError), (b"password", b"$2b$04$cVWp4XaNU8a4v1uMRum2SO", 513, 10, ValueError), (b"password", b"$2b$04$cVWp4XaNU8a4v1uMRum2SO", 20, 0, ValueError), ], ) def test_invalid_params(password, salt, desired_key_bytes, rounds, error): with pytest.raises(error): bcrypt.kdf(password, salt, desired_key_bytes, rounds) def test_bcrypt_assert(): with pytest.raises(SystemError): bcrypt._bcrypt_assert(False) def test_2a_wraparound_bug(): assert ( bcrypt.hashpw( (b"0123456789" * 26)[:255], b"$2a$04$R1lJ2gkNaoPGdafE.H.16." ) == b"$2a$04$R1lJ2gkNaoPGdafE.H.16.1MKHPvmKwryeulRe225LKProWYwt9Oi" )
apache-2.0
armyofevilrobots/reticulatus
reticulatus/gui/reticulate_main.py
1
13375
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'reticulate_main.ui' # # Created: Thu Oct 25 21:48:45 2012 # by: pyside-uic 0.2.13 running on PySide 1.1.0 # # WARNING! All changes made in this file will be lost! from PySide import QtCore, QtGui class Ui_main_window(object): def setupUi(self, main_window): main_window.setObjectName("main_window") main_window.resize(925, 633) sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Preferred, QtGui.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(main_window.sizePolicy().hasHeightForWidth()) main_window.setSizePolicy(sizePolicy) main_window.setMinimumSize(QtCore.QSize(512, 384)) main_window.setAutoFillBackground(False) self.centralwidget = QtGui.QWidget(main_window) self.centralwidget.setObjectName("centralwidget") self.horizontalLayout = QtGui.QHBoxLayout(self.centralwidget) self.horizontalLayout.setObjectName("horizontalLayout") self.object_tabs = QtGui.QTabWidget(self.centralwidget) sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Expanding) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.object_tabs.sizePolicy().hasHeightForWidth()) self.object_tabs.setSizePolicy(sizePolicy) self.object_tabs.setObjectName("object_tabs") self.object_3d = QtGui.QWidget() self.object_3d.setCursor(QtCore.Qt.CrossCursor) self.object_3d.setLayoutDirection(QtCore.Qt.RightToLeft) self.object_3d.setObjectName("object_3d") self.object_3d_layout = QtGui.QHBoxLayout(self.object_3d) self.object_3d_layout.setObjectName("object_3d_layout") self.frame = QtGui.QFrame(self.object_3d) sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.frame.sizePolicy().hasHeightForWidth()) self.frame.setSizePolicy(sizePolicy) self.frame.setMaximumSize(QtCore.QSize(50, 16777215)) self.frame.setLayoutDirection(QtCore.Qt.RightToLeft) self.frame.setFrameShape(QtGui.QFrame.NoFrame) self.frame.setFrameShadow(QtGui.QFrame.Raised) self.frame.setLineWidth(0) self.frame.setObjectName("frame") self.slider_container_layout = QtGui.QVBoxLayout(self.frame) self.slider_container_layout.setSizeConstraint(QtGui.QLayout.SetDefaultConstraint) self.slider_container_layout.setObjectName("slider_container_layout") self.layer_slider = QtGui.QSlider(self.frame) sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Expanding) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.layer_slider.sizePolicy().hasHeightForWidth()) self.layer_slider.setSizePolicy(sizePolicy) self.layer_slider.setMaximumSize(QtCore.QSize(50, 16777215)) self.layer_slider.setMinimum(0) self.layer_slider.setMaximum(9999) self.layer_slider.setProperty("value", 0) self.layer_slider.setOrientation(QtCore.Qt.Vertical) self.layer_slider.setInvertedAppearance(False) self.layer_slider.setObjectName("layer_slider") self.slider_container_layout.addWidget(self.layer_slider) self.layer_lcd = QtGui.QLCDNumber(self.frame) self.layer_lcd.setMaximumSize(QtCore.QSize(100, 16777215)) font = QtGui.QFont() font.setWeight(75) font.setBold(True) self.layer_lcd.setFont(font) self.layer_lcd.setNumDigits(4) self.layer_lcd.setObjectName("layer_lcd") self.slider_container_layout.addWidget(self.layer_lcd) self.object_3d_layout.addWidget(self.frame) self.object_tabs.addTab(self.object_3d, "") self.gcode = QtGui.QWidget() sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Expanding) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.gcode.sizePolicy().hasHeightForWidth()) self.gcode.setSizePolicy(sizePolicy) self.gcode.setObjectName("gcode") self.gcode_hlayout = QtGui.QHBoxLayout(self.gcode) self.gcode_hlayout.setObjectName("gcode_hlayout") self.gcode_editor = QtGui.QTextEdit(self.gcode) self.gcode_editor.setObjectName("gcode_editor") self.gcode_hlayout.addWidget(self.gcode_editor) self.object_tabs.addTab(self.gcode, "") self.horizontalLayout.addWidget(self.object_tabs) main_window.setCentralWidget(self.centralwidget) self.menubar = QtGui.QMenuBar(main_window) self.menubar.setGeometry(QtCore.QRect(0, 0, 925, 23)) self.menubar.setObjectName("menubar") self.menuFile = QtGui.QMenu(self.menubar) self.menuFile.setObjectName("menuFile") self.menu_edit = QtGui.QMenu(self.menubar) self.menu_edit.setObjectName("menu_edit") self.menu_Settings = QtGui.QMenu(self.menubar) self.menu_Settings.setObjectName("menu_Settings") self.menu_Help = QtGui.QMenu(self.menubar) self.menu_Help.setObjectName("menu_Help") self.menuActions = QtGui.QMenu(self.menubar) self.menuActions.setObjectName("menuActions") self.menu_Windows = QtGui.QMenu(self.menubar) self.menu_Windows.setObjectName("menu_Windows") main_window.setMenuBar(self.menubar) self.statusbar = QtGui.QStatusBar(main_window) self.statusbar.setEnabled(True) self.statusbar.setSizeGripEnabled(True) self.statusbar.setObjectName("statusbar") main_window.setStatusBar(self.statusbar) self.layers_dock = QtGui.QDockWidget(main_window) self.layers_dock.setMinimumSize(QtCore.QSize(120, 160)) self.layers_dock.setMaximumSize(QtCore.QSize(1024, 1024)) self.layers_dock.setObjectName("layers_dock") self.dock_contents = QtGui.QWidget() self.dock_contents.setObjectName("dock_contents") self.verticalLayout = QtGui.QVBoxLayout(self.dock_contents) self.verticalLayout.setObjectName("verticalLayout") self.label = QtGui.QLabel(self.dock_contents) self.label.setObjectName("label") self.verticalLayout.addWidget(self.label) self.layer_list_widget = QtGui.QListWidget(self.dock_contents) self.layer_list_widget.setObjectName("layer_list_widget") self.verticalLayout.addWidget(self.layer_list_widget) self.layers_dock.setWidget(self.dock_contents) main_window.addDockWidget(QtCore.Qt.DockWidgetArea(2), self.layers_dock) self.tools_dock = QtGui.QDockWidget(main_window) self.tools_dock.setMinimumSize(QtCore.QSize(120, 160)) self.tools_dock.setObjectName("tools_dock") self.dockWidgetContents = QtGui.QWidget() self.dockWidgetContents.setObjectName("dockWidgetContents") self.tools_dock.setWidget(self.dockWidgetContents) main_window.addDockWidget(QtCore.Qt.DockWidgetArea(2), self.tools_dock) self.action_file = QtGui.QAction(main_window) self.action_file.setObjectName("action_file") self.action_new = QtGui.QAction(main_window) self.action_new.setObjectName("action_new") self.action_open = QtGui.QAction(main_window) self.action_open.setObjectName("action_open") self.action_save = QtGui.QAction(main_window) self.action_save.setObjectName("action_save") self.action_quit = QtGui.QAction(main_window) self.action_quit.setObjectName("action_quit") self.action_print_settings = QtGui.QAction(main_window) self.action_print_settings.setObjectName("action_print_settings") self.action_slice_settings = QtGui.QAction(main_window) self.action_slice_settings.setObjectName("action_slice_settings") self.action_help = QtGui.QAction(main_window) self.action_help.setObjectName("action_help") self.action_about = QtGui.QAction(main_window) self.action_about.setObjectName("action_about") self.action_display_settings = QtGui.QAction(main_window) self.action_display_settings.setObjectName("action_display_settings") self.action_slice = QtGui.QAction(main_window) self.action_slice.setObjectName("action_slice") self.action_Layers = QtGui.QAction(main_window) self.action_Layers.setObjectName("action_Layers") self.action_Toolbox = QtGui.QAction(main_window) self.action_Toolbox.setObjectName("action_Toolbox") self.menuFile.addAction(self.action_new) self.menuFile.addAction(self.action_open) self.menuFile.addAction(self.action_save) self.menuFile.addSeparator() self.menuFile.addAction(self.action_quit) self.menu_Settings.addAction(self.action_print_settings) self.menu_Settings.addAction(self.action_slice_settings) self.menu_Settings.addAction(self.action_display_settings) self.menu_Help.addAction(self.action_help) self.menu_Help.addSeparator() self.menu_Help.addAction(self.action_about) self.menuActions.addAction(self.action_slice) self.menu_Windows.addAction(self.action_Layers) self.menu_Windows.addAction(self.action_Toolbox) self.menubar.addAction(self.menuFile.menuAction()) self.menubar.addAction(self.menu_edit.menuAction()) self.menubar.addAction(self.menuActions.menuAction()) self.menubar.addAction(self.menu_Settings.menuAction()) self.menubar.addAction(self.menu_Windows.menuAction()) self.menubar.addAction(self.menu_Help.menuAction()) self.retranslateUi(main_window) self.object_tabs.setCurrentIndex(0) QtCore.QMetaObject.connectSlotsByName(main_window) def retranslateUi(self, main_window): main_window.setWindowTitle(QtGui.QApplication.translate("main_window", "Reticulatus", None, QtGui.QApplication.UnicodeUTF8)) self.layer_slider.setToolTip(QtGui.QApplication.translate("main_window", "Layer clip plane", None, QtGui.QApplication.UnicodeUTF8)) self.object_tabs.setTabText(self.object_tabs.indexOf(self.object_3d), QtGui.QApplication.translate("main_window", "3D Object", None, QtGui.QApplication.UnicodeUTF8)) self.object_tabs.setTabText(self.object_tabs.indexOf(self.gcode), QtGui.QApplication.translate("main_window", "GCode", None, QtGui.QApplication.UnicodeUTF8)) self.menuFile.setTitle(QtGui.QApplication.translate("main_window", "&File", None, QtGui.QApplication.UnicodeUTF8)) self.menu_edit.setTitle(QtGui.QApplication.translate("main_window", "&Edit", None, QtGui.QApplication.UnicodeUTF8)) self.menu_Settings.setTitle(QtGui.QApplication.translate("main_window", "&Settings", None, QtGui.QApplication.UnicodeUTF8)) self.menu_Help.setTitle(QtGui.QApplication.translate("main_window", "&Help", None, QtGui.QApplication.UnicodeUTF8)) self.menuActions.setTitle(QtGui.QApplication.translate("main_window", "&Actions", None, QtGui.QApplication.UnicodeUTF8)) self.menu_Windows.setTitle(QtGui.QApplication.translate("main_window", "&Windows", None, QtGui.QApplication.UnicodeUTF8)) self.label.setText(QtGui.QApplication.translate("main_window", "Layers", None, QtGui.QApplication.UnicodeUTF8)) self.action_file.setText(QtGui.QApplication.translate("main_window", "&file", None, QtGui.QApplication.UnicodeUTF8)) self.action_new.setText(QtGui.QApplication.translate("main_window", "&New", None, QtGui.QApplication.UnicodeUTF8)) self.action_open.setText(QtGui.QApplication.translate("main_window", "&Open", None, QtGui.QApplication.UnicodeUTF8)) self.action_save.setText(QtGui.QApplication.translate("main_window", "&Save", None, QtGui.QApplication.UnicodeUTF8)) self.action_quit.setText(QtGui.QApplication.translate("main_window", "&Quit", None, QtGui.QApplication.UnicodeUTF8)) self.action_print_settings.setText(QtGui.QApplication.translate("main_window", "&Printer", None, QtGui.QApplication.UnicodeUTF8)) self.action_slice_settings.setText(QtGui.QApplication.translate("main_window", "S&licing", None, QtGui.QApplication.UnicodeUTF8)) self.action_help.setText(QtGui.QApplication.translate("main_window", "&Help", None, QtGui.QApplication.UnicodeUTF8)) self.action_about.setText(QtGui.QApplication.translate("main_window", "&About", None, QtGui.QApplication.UnicodeUTF8)) self.action_display_settings.setText(QtGui.QApplication.translate("main_window", "&Display", None, QtGui.QApplication.UnicodeUTF8)) self.action_slice.setText(QtGui.QApplication.translate("main_window", "&Slice", None, QtGui.QApplication.UnicodeUTF8)) self.action_Layers.setText(QtGui.QApplication.translate("main_window", "&Layers", None, QtGui.QApplication.UnicodeUTF8)) self.action_Toolbox.setText(QtGui.QApplication.translate("main_window", "&Toolbox", None, QtGui.QApplication.UnicodeUTF8))
gpl-3.0
darklordIN/android_kernel_sony_nicki-1
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
Ichimonji10/robottelo
robottelo/ui/container.py
1
8490
# -*- encoding: utf-8 -*- from robottelo.constants import FILTER from robottelo.ui.base import Base, UINoSuchElementError, UIError from robottelo.ui.locators import common_locators, locators, tab_locators from robottelo.ui.navigator import Navigator class Container(Base): """Provides the CRUD functionality for Docker Containers.""" def navigate_to_entity(self): """Navigate to All Containers page""" Navigator(self.browser).go_to_all_containers() def _search_locator(self): """Specify locator for Container entity search procedure""" return locators['container.search_entity'] def _configure_orgs(self, orgs, org_select): """Provides configuration capabilities for docker container organization. The following format should be used:: orgs=['Aoes6V', 'JIFNPC'], org_select=True """ self.configure_entity( orgs, FILTER['container_org'], tab_locator=tab_locators['tab_org'], entity_select=org_select, ) def _configure_locations(self, locations, loc_select): """Provides configuration capabilities for docker container location The following format should be used:: locations=['Default Location'], loc_select=True """ self.configure_entity( locations, FILTER['container_loc'], tab_locator=tab_locators['tab_loc'], entity_select=loc_select, ) def _form_locator_name(self, partial_locator): """Form locator using provided friendly UI name, e.g. 'Content View'""" return '.'.join(( 'container', (partial_locator.lower()).replace(' ', '_') )) def create(self, resource_name, name, command, parameter_list): """Creates a docker container. All values should be passed in absolute correspondence to UI. Parameters names created in self-descriptive manner. Of course, we can easily expand list of parameters and create custom flows for specific situations. Here are some examples of parameter_list values from each main tab:: [ {'main_tab_name': 'Preliminary', 'sub_tab_name': 'Location', 'name': ['Default Location']}, {'main_tab_name': 'Image', 'sub_tab_name': 'Content View', 'name': 'Lifecycle Environment', 'value': self.lce.name}, {'main_tab_name': 'Image', 'sub_tab_name': 'Docker Hub', 'name': 'Docker Hub Tag', 'value': 'latest'}, {'main_tab_name': 'Configuration', 'name': 'Memory', 'value': '512m'}, {'main_tab_name': 'Environment', 'name': 'TTY', 'value': True}, ] """ # send_keys() can't send left parenthesis (see SeleniumHQ/selenium#674) # which is used in compute resource name (e.g. 'test (Docker)') if ' (' in resource_name: self.click(locators['container.resource_name']) # typing compute resource name without parenthesis part self.text_field_update( common_locators['select_list_search_box'], resource_name.split(' (')[0] ) strategy, value = common_locators['entity_select_list'] # selecting compute resource by its full name (with parenthesis # part) self.click((strategy, value % resource_name)) else: self.assign_value( locators['container.resource_name'], resource_name) for parameter in parameter_list: if parameter['main_tab_name'] == 'Preliminary': if parameter['sub_tab_name'] == 'Organization': self._configure_orgs(parameter['name'], True) elif parameter['sub_tab_name'] == 'Location': self._configure_locations(parameter['name'], True) self.click(locators['container.next_section']) current_tab = self._form_locator_name('Content View Tab') for parameter in parameter_list: if parameter['main_tab_name'] == 'Image': current_tab = self._form_locator_name( parameter['sub_tab_name'] + ' Tab') self.click(locators[current_tab]) self.assign_value( locators[ self._form_locator_name( 'registry.' + parameter['name']) ] if parameter['sub_tab_name'] == 'External registry' else locators[self._form_locator_name(parameter['name'])], parameter['value'] ) self.click(locators[current_tab + '_next']) self.assign_value(locators['container.name'], name) self.assign_value(locators['container.command'], command) for parameter in parameter_list: if parameter['main_tab_name'] == 'Configuration': self.assign_value( locators[self._form_locator_name(parameter['name'])], parameter['value'] ) self.click(locators['container.next_section']) self.browser.refresh() for parameter in parameter_list: if parameter['main_tab_name'] == 'Environment': self.assign_value( locators[self._form_locator_name(parameter['name'])], parameter['value'] ) self.click(locators['container.next_section']) strategy, value = locators['container.created_container_name'] element = self.wait_until_element((strategy, value % name)) if element is None: raise UINoSuchElementError( 'Container with name {0} was not created successfully' .format(name) ) def search(self, resource_name, container_name): """Searches for existing container from particular compute resource. It is necessary to use custom search here as we need to select compute resource tab before searching for particular container and also, there is no search button to click """ self.navigate_to_entity() strategy, value = locators['container.resource_search_tab'] self.click((strategy, value % resource_name)) self.text_field_update( locators['container.search_filter'], container_name) strategy, value = self._search_locator() return self.wait_until_element((strategy, value % container_name)) def delete(self, resource_name, container_name, really=True): """Removes the container entity""" element = self.search(resource_name, container_name) if element is None: raise UIError( 'Could not find container "{0}"'.format(container_name)) element.click() self.wait_for_ajax() self.click(locators['container.delete'], wait_for_ajax=False) self.handle_alert(really) def set_power_status(self, resource_name, cont_name, power_on): """Perform power on or power off for container :param bool power_on: True - for On, False - for Off """ status = None locator_on = (locators['container.power_on'][0], locators['container.power_on'][1] % cont_name) locator_off = (locators['container.power_off'][0], locators['container.power_off'][1] % cont_name) locator_status = (locators['container.power_status'][0], locators['container.power_status'][1] % cont_name) element = self.search(resource_name, cont_name) if element is None: raise UIError( 'Could not find container "{0}"'.format(cont_name)) self.wait_for_ajax() if power_on is True: self.click(locator_on) self.search(resource_name, cont_name) if self.wait_until_element(locator_off): status = self.wait_until_element(locator_status).text elif power_on is False: self.click(locator_off, wait_for_ajax=False) self.handle_alert(True) self.search(resource_name, cont_name) if self.wait_until_element(locator_on): status = self.wait_until_element(locator_status).text return status
gpl-3.0
b-me/django
tests/null_fk_ordering/tests.py
381
2012
from __future__ import unicode_literals from django.test import TestCase from .models import Article, Author, Comment, Forum, Post, SystemInfo class NullFkOrderingTests(TestCase): def test_ordering_across_null_fk(self): """ Regression test for #7512 ordering across nullable Foreign Keys shouldn't exclude results """ author_1 = Author.objects.create(name='Tom Jones') author_2 = Author.objects.create(name='Bob Smith') Article.objects.create(title='No author on this article') Article.objects.create(author=author_1, title='This article written by Tom Jones') Article.objects.create(author=author_2, title='This article written by Bob Smith') # We can't compare results directly (since different databases sort NULLs to # different ends of the ordering), but we can check that all results are # returned. self.assertEqual(len(list(Article.objects.all())), 3) s = SystemInfo.objects.create(system_name='System Info') f = Forum.objects.create(system_info=s, forum_name='First forum') p = Post.objects.create(forum=f, title='First Post') Comment.objects.create(post=p, comment_text='My first comment') Comment.objects.create(comment_text='My second comment') s2 = SystemInfo.objects.create(system_name='More System Info') f2 = Forum.objects.create(system_info=s2, forum_name='Second forum') p2 = Post.objects.create(forum=f2, title='Second Post') Comment.objects.create(comment_text='Another first comment') Comment.objects.create(post=p2, comment_text='Another second comment') # We have to test this carefully. Some databases sort NULL values before # everything else, some sort them afterwards. So we extract the ordered list # and check the length. Before the fix, this list was too short (some values # were omitted). self.assertEqual(len(list(Comment.objects.all())), 4)
bsd-3-clause
Maximilian-Reuter/SickRage-1
lib/unidecode/x05e.py
250
4668
data = ( 'Za ', # 0x00 'Bi ', # 0x01 'Shi ', # 0x02 'Bu ', # 0x03 'Ding ', # 0x04 'Shuai ', # 0x05 'Fan ', # 0x06 'Nie ', # 0x07 'Shi ', # 0x08 'Fen ', # 0x09 'Pa ', # 0x0a 'Zhi ', # 0x0b 'Xi ', # 0x0c 'Hu ', # 0x0d 'Dan ', # 0x0e 'Wei ', # 0x0f 'Zhang ', # 0x10 'Tang ', # 0x11 'Dai ', # 0x12 'Ma ', # 0x13 'Pei ', # 0x14 'Pa ', # 0x15 'Tie ', # 0x16 'Fu ', # 0x17 'Lian ', # 0x18 'Zhi ', # 0x19 'Zhou ', # 0x1a 'Bo ', # 0x1b 'Zhi ', # 0x1c 'Di ', # 0x1d 'Mo ', # 0x1e 'Yi ', # 0x1f 'Yi ', # 0x20 'Ping ', # 0x21 'Qia ', # 0x22 'Juan ', # 0x23 'Ru ', # 0x24 'Shuai ', # 0x25 'Dai ', # 0x26 'Zheng ', # 0x27 'Shui ', # 0x28 'Qiao ', # 0x29 'Zhen ', # 0x2a 'Shi ', # 0x2b 'Qun ', # 0x2c 'Xi ', # 0x2d 'Bang ', # 0x2e 'Dai ', # 0x2f 'Gui ', # 0x30 'Chou ', # 0x31 'Ping ', # 0x32 'Zhang ', # 0x33 'Sha ', # 0x34 'Wan ', # 0x35 'Dai ', # 0x36 'Wei ', # 0x37 'Chang ', # 0x38 'Sha ', # 0x39 'Qi ', # 0x3a 'Ze ', # 0x3b 'Guo ', # 0x3c 'Mao ', # 0x3d 'Du ', # 0x3e 'Hou ', # 0x3f 'Zheng ', # 0x40 'Xu ', # 0x41 'Mi ', # 0x42 'Wei ', # 0x43 'Wo ', # 0x44 'Fu ', # 0x45 'Yi ', # 0x46 'Bang ', # 0x47 'Ping ', # 0x48 'Tazuna ', # 0x49 'Gong ', # 0x4a 'Pan ', # 0x4b 'Huang ', # 0x4c 'Dao ', # 0x4d 'Mi ', # 0x4e 'Jia ', # 0x4f 'Teng ', # 0x50 'Hui ', # 0x51 'Zhong ', # 0x52 'Shan ', # 0x53 'Man ', # 0x54 'Mu ', # 0x55 'Biao ', # 0x56 'Guo ', # 0x57 'Ze ', # 0x58 'Mu ', # 0x59 'Bang ', # 0x5a 'Zhang ', # 0x5b 'Jiong ', # 0x5c 'Chan ', # 0x5d 'Fu ', # 0x5e 'Zhi ', # 0x5f 'Hu ', # 0x60 'Fan ', # 0x61 'Chuang ', # 0x62 'Bi ', # 0x63 'Hei ', # 0x64 '[?] ', # 0x65 'Mi ', # 0x66 'Qiao ', # 0x67 'Chan ', # 0x68 'Fen ', # 0x69 'Meng ', # 0x6a 'Bang ', # 0x6b 'Chou ', # 0x6c 'Mie ', # 0x6d 'Chu ', # 0x6e 'Jie ', # 0x6f 'Xian ', # 0x70 'Lan ', # 0x71 'Gan ', # 0x72 'Ping ', # 0x73 'Nian ', # 0x74 'Qian ', # 0x75 'Bing ', # 0x76 'Bing ', # 0x77 'Xing ', # 0x78 'Gan ', # 0x79 'Yao ', # 0x7a 'Huan ', # 0x7b 'You ', # 0x7c 'You ', # 0x7d 'Ji ', # 0x7e 'Yan ', # 0x7f 'Pi ', # 0x80 'Ting ', # 0x81 'Ze ', # 0x82 'Guang ', # 0x83 'Zhuang ', # 0x84 'Mo ', # 0x85 'Qing ', # 0x86 'Bi ', # 0x87 'Qin ', # 0x88 'Dun ', # 0x89 'Chuang ', # 0x8a 'Gui ', # 0x8b 'Ya ', # 0x8c 'Bai ', # 0x8d 'Jie ', # 0x8e 'Xu ', # 0x8f 'Lu ', # 0x90 'Wu ', # 0x91 '[?] ', # 0x92 'Ku ', # 0x93 'Ying ', # 0x94 'Di ', # 0x95 'Pao ', # 0x96 'Dian ', # 0x97 'Ya ', # 0x98 'Miao ', # 0x99 'Geng ', # 0x9a 'Ci ', # 0x9b 'Fu ', # 0x9c 'Tong ', # 0x9d 'Pang ', # 0x9e 'Fei ', # 0x9f 'Xiang ', # 0xa0 'Yi ', # 0xa1 'Zhi ', # 0xa2 'Tiao ', # 0xa3 'Zhi ', # 0xa4 'Xiu ', # 0xa5 'Du ', # 0xa6 'Zuo ', # 0xa7 'Xiao ', # 0xa8 'Tu ', # 0xa9 'Gui ', # 0xaa 'Ku ', # 0xab 'Pang ', # 0xac 'Ting ', # 0xad 'You ', # 0xae 'Bu ', # 0xaf 'Ding ', # 0xb0 'Cheng ', # 0xb1 'Lai ', # 0xb2 'Bei ', # 0xb3 'Ji ', # 0xb4 'An ', # 0xb5 'Shu ', # 0xb6 'Kang ', # 0xb7 'Yong ', # 0xb8 'Tuo ', # 0xb9 'Song ', # 0xba 'Shu ', # 0xbb 'Qing ', # 0xbc 'Yu ', # 0xbd 'Yu ', # 0xbe 'Miao ', # 0xbf 'Sou ', # 0xc0 'Ce ', # 0xc1 'Xiang ', # 0xc2 'Fei ', # 0xc3 'Jiu ', # 0xc4 'He ', # 0xc5 'Hui ', # 0xc6 'Liu ', # 0xc7 'Sha ', # 0xc8 'Lian ', # 0xc9 'Lang ', # 0xca 'Sou ', # 0xcb 'Jian ', # 0xcc 'Pou ', # 0xcd 'Qing ', # 0xce 'Jiu ', # 0xcf 'Jiu ', # 0xd0 'Qin ', # 0xd1 'Ao ', # 0xd2 'Kuo ', # 0xd3 'Lou ', # 0xd4 'Yin ', # 0xd5 'Liao ', # 0xd6 'Dai ', # 0xd7 'Lu ', # 0xd8 'Yi ', # 0xd9 'Chu ', # 0xda 'Chan ', # 0xdb 'Tu ', # 0xdc 'Si ', # 0xdd 'Xin ', # 0xde 'Miao ', # 0xdf 'Chang ', # 0xe0 'Wu ', # 0xe1 'Fei ', # 0xe2 'Guang ', # 0xe3 'Koc ', # 0xe4 'Kuai ', # 0xe5 'Bi ', # 0xe6 'Qiang ', # 0xe7 'Xie ', # 0xe8 'Lin ', # 0xe9 'Lin ', # 0xea 'Liao ', # 0xeb 'Lu ', # 0xec '[?] ', # 0xed 'Ying ', # 0xee 'Xian ', # 0xef 'Ting ', # 0xf0 'Yong ', # 0xf1 'Li ', # 0xf2 'Ting ', # 0xf3 'Yin ', # 0xf4 'Xun ', # 0xf5 'Yan ', # 0xf6 'Ting ', # 0xf7 'Di ', # 0xf8 'Po ', # 0xf9 'Jian ', # 0xfa 'Hui ', # 0xfb 'Nai ', # 0xfc 'Hui ', # 0xfd 'Gong ', # 0xfe 'Nian ', # 0xff )
gpl-3.0
Atlas-Sailed-Co/oppia
extensions/interactions/MultipleChoiceInput/MultipleChoiceInput.py
9
1636
# coding: utf-8 # # Copyright 2014 The Oppia 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, softwar # 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 extensions.interactions import base class MultipleChoiceInput(base.BaseInteraction): """Interaction for multiple choice input.""" name = 'Multiple Choice' description = ( 'Allows learners to select one of a list of multiple-choice options.') display_mode = base.DISPLAY_MODE_INLINE _dependency_ids = [] answer_type = 'NonnegativeInt' _customization_arg_specs = [{ 'name': 'choices', 'description': 'Multiple Choice options', 'schema': { 'type': 'list', 'validators': [{ 'id': 'has_length_at_least', 'min_value': 1, }], 'items': { 'type': 'html', 'ui_config': { 'hide_complex_extensions': True, }, }, 'ui_config': { 'add_element_text': 'Add multiple choice option', } }, 'default_value': ['Sample multiple-choice answer'], }]
apache-2.0
umars/npyscreen
build/lib/npyscreen/fmActionFormV2.py
15
3791
import operator import weakref from . import wgwidget as widget from . import wgbutton from . import fmForm class ActionFormV2(fmForm.FormBaseNew): class OK_Button(wgbutton.MiniButtonPress): def whenPressed(self): return self.parent._on_ok() class Cancel_Button(wgbutton.MiniButtonPress): def whenPressed(self): return self.parent._on_cancel() OKBUTTON_TYPE = OK_Button CANCELBUTTON_TYPE = Cancel_Button CANCEL_BUTTON_BR_OFFSET = (2, 12) OK_BUTTON_TEXT = "OK" CANCEL_BUTTON_TEXT = "Cancel" def __init__(self, *args, **keywords): super(ActionFormV2, self).__init__(*args, **keywords) self._added_buttons = {} self.create_control_buttons() def create_control_buttons(self): self._add_button('ok_button', self.__class__.OKBUTTON_TYPE, self.__class__.OK_BUTTON_TEXT, 0 - self.__class__.OK_BUTTON_BR_OFFSET[0], 0 - self.__class__.OK_BUTTON_BR_OFFSET[1] - len(self.__class__.OK_BUTTON_TEXT), None ) self._add_button('cancel_button', self.__class__.CANCELBUTTON_TYPE, self.__class__.CANCEL_BUTTON_TEXT, 0 - self.__class__.CANCEL_BUTTON_BR_OFFSET[0], 0 - self.__class__.CANCEL_BUTTON_BR_OFFSET[1] - len(self.__class__.CANCEL_BUTTON_TEXT), None ) def on_cancel(self): pass def on_ok(self): pass def _on_ok(self): self.editing = self.on_ok() def _on_cancel(self): self.editing = self.on_cancel() def set_up_exit_condition_handlers(self): super(ActionFormV2, self).set_up_exit_condition_handlers() self.how_exited_handers.update({ widget.EXITED_ESCAPE: self.find_cancel_button }) def find_cancel_button(self): self.editw = len(self._widgets__)-2 def _add_button(self, button_name, button_type, button_text, button_rely, button_relx, button_function): tmp_rely, tmp_relx = self.nextrely, self.nextrelx this_button = self.add_widget( button_type, name=button_text, rely=button_rely, relx=button_relx, when_pressed_function = button_function, use_max_space=True, ) self._added_buttons[button_name] = this_button self.nextrely, self.nextrelx = tmp_rely, tmp_relx def pre_edit_loop(self): self._widgets__.sort(key=operator.attrgetter('relx')) self._widgets__.sort(key=operator.attrgetter('rely')) if not self.preserve_selected_widget: self.editw = 0 if not self._widgets__[self.editw].editable: self.find_next_editable() def post_edit_loop(self): pass def _during_edit_loop(self): pass class ActionFormExpandedV2(ActionFormV2): BLANK_LINES_BASE = 1 OK_BUTTON_BR_OFFSET = (1,6) CANCEL_BUTTON_BR_OFFSET = (1, 12) class ActionFormMinimal(ActionFormV2): def create_control_buttons(self): self._add_button('ok_button', self.__class__.OKBUTTON_TYPE, self.__class__.OK_BUTTON_TEXT, 0 - self.__class__.OK_BUTTON_BR_OFFSET[0], 0 - self.__class__.OK_BUTTON_BR_OFFSET[1] - len(self.__class__.OK_BUTTON_TEXT), None )
bsd-2-clause
tomsilver/nupic
tests/integration/nupic/engine/network_testnode_interchangeability.py
17
6158
#!/usr/bin/env python # ---------------------------------------------------------------------- # Numenta Platform for Intelligent Computing (NuPIC) # Copyright (C) 2014, Numenta, Inc. Unless you have an agreement # with Numenta, Inc., for a separate license for this software code, the # following terms and conditions apply: # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License version 3 as # published by the Free Software Foundation. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. # See the GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see http://www.gnu.org/licenses. # # http://numenta.org/licenses/ # ---------------------------------------------------------------------- """This test verifies that the C++ test node and py.TestNode It creates the same two node network with all four combinations of TestNode and py.TestNode: 1. TestNode, TestNode 2. TestNode, py.TestNode 3. py.TestNode, TestNode 4. py.TestNode, py.TestNode Then it performs the same tests as the twonode_network demo (except the error messages tests for the three node network): - Can add regions to network and set dimensions - Linking induces dimensions correctly - Network computation happens in correct order - Direct (zero-copy) access to outputs - Linking correctly maps outputs to inputs """ import logging import unittest2 as unittest from nupic.engine import Network, Dimensions LOGGER = logging.getLogger(__name__) class NetworkTestNodeInterchangeabilityTest(unittest.TestCase): def testNodesPyTestNodeAndTestNode(self): self.runNodesTest('py.TestNode', 'TestNode') def testNodesTestNodeAndPyTestNode(self): self.runNodesTest('TestNode', 'py.TestNode') def testNodesTestNodeAndTestNode(self): self.runNodesTest('TestNode', 'TestNode') def testNodesPyTestNodeAndPyTestNode(self): self.runNodesTest('py.TestNode', 'py.TestNode') def runNodesTest(self, nodeType1, nodeType2): # ===================================================== # Build and run the network # ===================================================== LOGGER.info('test(level1: %s, level2: %s)', nodeType1, nodeType2) net = Network() level1 = net.addRegion("level1", nodeType1, "{int32Param: 15}") dims = Dimensions([6, 4]) level1.setDimensions(dims) level2 = net.addRegion("level2", nodeType2, "{real64Param: 128.23}") net.link("level1", "level2", "TestFanIn2", "") # Could call initialize here, but not necessary as net.run() # initializes implicitly. # net.initialize() net.run(1) LOGGER.info("Successfully created network and ran for one iteration") # ===================================================== # Check everything # ===================================================== dims = level1.getDimensions() self.assertEqual(len(dims), 2) self.assertEqual(dims[0], 6) self.assertEqual(dims[1], 4) dims = level2.getDimensions() self.assertEqual(len(dims), 2) self.assertEqual(dims[0], 3) self.assertEqual(dims[1], 2) # Check L1 output. "False" means don't copy, i.e. # get a pointer to the actual output # Actual output values are determined by the TestNode # compute() behavior. l1output = level1.getOutputData("bottomUpOut") self.assertEqual(len(l1output), 48) # 24 nodes; 2 values per node for i in xrange(24): self.assertEqual(l1output[2*i], 0) # size of input to each node is 0 self.assertEqual(l1output[2*i+1], i) # node number # check L2 output. l2output = level2.getOutputData("bottomUpOut") self.assertEqual(len(l2output), 12) # 6 nodes; 2 values per node # Output val = node number + sum(inputs) # Can compute from knowing L1 layout # # 00 01 | 02 03 | 04 05 # 06 07 | 08 09 | 10 11 # --------------------- # 12 13 | 14 15 | 16 17 # 18 19 | 20 21 | 22 23 outputVals = [] outputVals.append(0 + (0 + 1 + 6 + 7)) outputVals.append(1 + (2 + 3 + 8 + 9)) outputVals.append(2 + (4 + 5 + 10 + 11)) outputVals.append(3 + (12 + 13 + 18 + 19)) outputVals.append(4 + (14 + 15 + 20 + 21)) outputVals.append(5 + (16 + 17 + 22 + 23)) for i in xrange(6): if l2output[2*i] != 8: LOGGER.info(l2output[2*i]) # from dbgp.client import brk; brk(port=9019) self.assertEqual(l2output[2*i], 8) # size of input for each node is 8 self.assertEqual(l2output[2*i+1], outputVals[i]) # ===================================================== # Run for one more iteration # ===================================================== LOGGER.info("Running for a second iteration") net.run(1) # ===================================================== # Check everything again # ===================================================== # Outputs are all the same except that the first output is # incremented by the iteration number for i in xrange(24): self.assertEqual(l1output[2*i], 1) self.assertEqual(l1output[2*i+1], i) for i in xrange(6): self.assertEqual(l2output[2*i], 9) self.assertEqual(l2output[2*i+1], outputVals[i] + 4) # ===================================================== # Demonstrate a few other features # ===================================================== # # Linking can induce dimensions downward # net = Network() level1 = net.addRegion("level1", nodeType1, "") level2 = net.addRegion("level2", nodeType2, "") dims = Dimensions([3, 2]) level2.setDimensions(dims) net.link("level1", "level2", "TestFanIn2", "") net.initialize() # Level1 should now have dimensions [6, 4] self.assertEqual(level1.getDimensions()[0], 6) self.assertEqual(level1.getDimensions()[1], 4) if __name__ == "__main__": unittest.main()
gpl-3.0
TonnyXu/Zxing
cpp/scons/scons-local-2.0.0.final.0/SCons/Tool/javac.py
34
8563
"""SCons.Tool.javac Tool-specific initialization for javac. There normally shouldn't be any need to import this module directly. It will usually be imported through the generic SCons.Tool.Tool() selection method. """ # # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010 The SCons Foundation # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY # KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE # WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. __revision__ = "src/engine/SCons/Tool/javac.py 5023 2010/06/14 22:05:46 scons" import os import os.path import SCons.Action import SCons.Builder from SCons.Node.FS import _my_normcase from SCons.Tool.JavaCommon import parse_java_file import SCons.Util def classname(path): """Turn a string (path name) into a Java class name.""" return os.path.normpath(path).replace(os.sep, '.') def emit_java_classes(target, source, env): """Create and return lists of source java files and their corresponding target class files. """ java_suffix = env.get('JAVASUFFIX', '.java') class_suffix = env.get('JAVACLASSSUFFIX', '.class') target[0].must_be_same(SCons.Node.FS.Dir) classdir = target[0] s = source[0].rentry().disambiguate() if isinstance(s, SCons.Node.FS.File): sourcedir = s.dir.rdir() elif isinstance(s, SCons.Node.FS.Dir): sourcedir = s.rdir() else: raise SCons.Errors.UserError("Java source must be File or Dir, not '%s'" % s.__class__) slist = [] js = _my_normcase(java_suffix) for entry in source: entry = entry.rentry().disambiguate() if isinstance(entry, SCons.Node.FS.File): slist.append(entry) elif isinstance(entry, SCons.Node.FS.Dir): result = SCons.Util.OrderedDict() dirnode = entry.rdir() def find_java_files(arg, dirpath, filenames): java_files = sorted([n for n in filenames if _my_normcase(n).endswith(js)]) mydir = dirnode.Dir(dirpath) java_paths = [mydir.File(f) for f in java_files] for jp in java_paths: arg[jp] = True for dirpath, dirnames, filenames in os.walk(dirnode.get_abspath()): find_java_files(result, dirpath, filenames) entry.walk(find_java_files, result) slist.extend(list(result.keys())) else: raise SCons.Errors.UserError("Java source must be File or Dir, not '%s'" % entry.__class__) version = env.get('JAVAVERSION', '1.4') full_tlist = [] for f in slist: tlist = [] source_file_based = True pkg_dir = None if not f.is_derived(): pkg_dir, classes = parse_java_file(f.rfile().get_abspath(), version) if classes: source_file_based = False if pkg_dir: d = target[0].Dir(pkg_dir) p = pkg_dir + os.sep else: d = target[0] p = '' for c in classes: t = d.File(c + class_suffix) t.attributes.java_classdir = classdir t.attributes.java_sourcedir = sourcedir t.attributes.java_classname = classname(p + c) tlist.append(t) if source_file_based: base = f.name[:-len(java_suffix)] if pkg_dir: t = target[0].Dir(pkg_dir).File(base + class_suffix) else: t = target[0].File(base + class_suffix) t.attributes.java_classdir = classdir t.attributes.java_sourcedir = f.dir t.attributes.java_classname = classname(base) tlist.append(t) for t in tlist: t.set_specific_source([f]) full_tlist.extend(tlist) return full_tlist, slist JavaAction = SCons.Action.Action('$JAVACCOM', '$JAVACCOMSTR') JavaBuilder = SCons.Builder.Builder(action = JavaAction, emitter = emit_java_classes, target_factory = SCons.Node.FS.Entry, source_factory = SCons.Node.FS.Entry) class pathopt(object): """ Callable object for generating javac-style path options from a construction variable (e.g. -classpath, -sourcepath). """ def __init__(self, opt, var, default=None): self.opt = opt self.var = var self.default = default def __call__(self, target, source, env, for_signature): path = env[self.var] if path and not SCons.Util.is_List(path): path = [path] if self.default: path = path + [ env[self.default] ] if path: return [self.opt, os.pathsep.join(path)] #return self.opt + " " + os.pathsep.join(path) else: return [] #return "" def Java(env, target, source, *args, **kw): """ A pseudo-Builder wrapper around the separate JavaClass{File,Dir} Builders. """ if not SCons.Util.is_List(target): target = [target] if not SCons.Util.is_List(source): source = [source] # Pad the target list with repetitions of the last element in the # list so we have a target for every source element. target = target + ([target[-1]] * (len(source) - len(target))) java_suffix = env.subst('$JAVASUFFIX') result = [] for t, s in zip(target, source): if isinstance(s, SCons.Node.FS.Base): if isinstance(s, SCons.Node.FS.File): b = env.JavaClassFile else: b = env.JavaClassDir else: if os.path.isfile(s): b = env.JavaClassFile elif os.path.isdir(s): b = env.JavaClassDir elif s[-len(java_suffix):] == java_suffix: b = env.JavaClassFile else: b = env.JavaClassDir result.extend(b(t, s, *args, **kw)) return result def generate(env): """Add Builders and construction variables for javac to an Environment.""" java_file = SCons.Tool.CreateJavaFileBuilder(env) java_class = SCons.Tool.CreateJavaClassFileBuilder(env) java_class_dir = SCons.Tool.CreateJavaClassDirBuilder(env) java_class.add_emitter(None, emit_java_classes) java_class.add_emitter(env.subst('$JAVASUFFIX'), emit_java_classes) java_class_dir.emitter = emit_java_classes env.AddMethod(Java) env['JAVAC'] = 'javac' env['JAVACFLAGS'] = SCons.Util.CLVar('') env['JAVABOOTCLASSPATH'] = [] env['JAVACLASSPATH'] = [] env['JAVASOURCEPATH'] = [] env['_javapathopt'] = pathopt env['_JAVABOOTCLASSPATH'] = '${_javapathopt("-bootclasspath", "JAVABOOTCLASSPATH")} ' env['_JAVACLASSPATH'] = '${_javapathopt("-classpath", "JAVACLASSPATH")} ' env['_JAVASOURCEPATH'] = '${_javapathopt("-sourcepath", "JAVASOURCEPATH", "_JAVASOURCEPATHDEFAULT")} ' env['_JAVASOURCEPATHDEFAULT'] = '${TARGET.attributes.java_sourcedir}' env['_JAVACCOM'] = '$JAVAC $JAVACFLAGS $_JAVABOOTCLASSPATH $_JAVACLASSPATH -d ${TARGET.attributes.java_classdir} $_JAVASOURCEPATH $SOURCES' env['JAVACCOM'] = "${TEMPFILE('$_JAVACCOM')}" env['JAVACLASSSUFFIX'] = '.class' env['JAVASUFFIX'] = '.java' def exists(env): return 1 # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
apache-2.0
caseyrygt/osf.io
tests/test_identifiers.py
33
8807
# -*- coding: utf-8 -*- import httpretty from factory import SubFactory from nose.tools import * # noqa from tests.base import OsfTestCase from tests.factories import AuthUserFactory from tests.factories import ModularOdmFactory from tests.factories import RegistrationFactory from tests.test_addons import assert_urls_equal import furl import lxml.etree from modularodm.storage.base import KeyExistsException from website import settings from website.identifiers.utils import to_anvl from website.identifiers.model import Identifier from website.identifiers.metadata import datacite_metadata_for_node from website.identifiers import metadata class IdentifierFactory(ModularOdmFactory): FACTORY_FOR = Identifier referent = SubFactory(RegistrationFactory) category = 'carpid' value = 'carp:/24601' class TestMetadataGeneration(OsfTestCase): def setUp(self): OsfTestCase.setUp(self) self.visible_contrib = AuthUserFactory() visible_contrib2 = AuthUserFactory(given_name=u'ヽ༼ ಠ益ಠ ༽ノ', family_name=u'ლ(´◉❥◉`ლ)') self.invisible_contrib = AuthUserFactory() self.node = RegistrationFactory(is_public=True) self.identifier = Identifier(referent=self.node, category='catid', value='cat:7') self.node.add_contributor(self.visible_contrib, visible=True) self.node.add_contributor(self.invisible_contrib, visible=False) self.node.add_contributor(visible_contrib2, visible=True) self.node.save() def test_metadata_for_node_only_includes_visible_contribs(self): metadata_xml = datacite_metadata_for_node(self.node, doi=self.identifier.value) # includes visible contrib name assert_in(u'{}, {}'.format( self.visible_contrib.family_name, self.visible_contrib.given_name), metadata_xml) # doesn't include invisible contrib name assert_not_in(self.invisible_contrib.family_name, metadata_xml) assert_in(self.identifier.value, metadata_xml) def test_metadata_for_node_has_correct_structure(self): metadata_xml = datacite_metadata_for_node(self.node, doi=self.identifier.value) root = lxml.etree.fromstring(metadata_xml) xsi_location = '{http://www.w3.org/2001/XMLSchema-instance}schemaLocation' expected_location = 'http://datacite.org/schema/kernel-3 http://schema.datacite.org/meta/kernel-3/metadata.xsd' assert_equal(root.attrib[xsi_location], expected_location) identifier = root.find('{%s}identifier' % metadata.NAMESPACE) assert_equal(identifier.attrib['identifierType'], 'DOI') assert_equal(identifier.text, self.identifier.value) creators = root.find('{%s}creators' % metadata.NAMESPACE) assert_equal(len(creators.getchildren()), len(self.node.visible_contributors)) publisher = root.find('{%s}publisher' % metadata.NAMESPACE) assert_equal(publisher.text, 'Open Science Framework') pub_year = root.find('{%s}publicationYear' % metadata.NAMESPACE) assert_equal(pub_year.text, str(self.node.registered_date.year)) class TestIdentifierModel(OsfTestCase): def test_fields(self): node = RegistrationFactory() identifier = Identifier(referent=node, category='catid', value='cat:7') assert_equal(identifier.referent, node) assert_equal(identifier.category, 'catid') assert_equal(identifier.value, 'cat:7') def test_unique_constraint(self): node = RegistrationFactory() IdentifierFactory(referent=node) with assert_raises(KeyExistsException): IdentifierFactory(referent=node) def test_mixin_get(self): identifier = IdentifierFactory() node = identifier.referent assert_equal(node.get_identifier(identifier.category), identifier) def test_mixin_get_value(self): identifier = IdentifierFactory() node = identifier.referent assert_equal(node.get_identifier_value(identifier.category), identifier.value) def test_mixin_set_create(self): node = RegistrationFactory() assert_is_none(node.get_identifier('dogid')) node.set_identifier_value('dogid', 'dog:1') assert_equal(node.get_identifier_value('dogid'), 'dog:1') def test_mixin_set_update(self): identifier = IdentifierFactory(category='dogid', value='dog:1') node = identifier.referent assert_equal(node.get_identifier_value('dogid'), 'dog:1') node.set_identifier_value('dogid', 'dog:2') assert_equal(node.get_identifier_value('dogid'), 'dog:2') def test_node_csl(self): node = RegistrationFactory() node.set_identifier_value('doi', 'FK424601') assert_equal(node.csl['DOI'], 'FK424601') class TestIdentifierViews(OsfTestCase): def setUp(self): super(TestIdentifierViews, self).setUp() self.user = AuthUserFactory() self.node = RegistrationFactory(creator=self.user, is_public=True) def test_get_identifiers(self): self.node.set_identifier_value('doi', 'FK424601') self.node.set_identifier_value('ark', 'fk224601') res = self.app.get(self.node.api_url_for('node_identifiers_get')) assert_equal(res.json['doi'], 'FK424601') assert_equal(res.json['ark'], 'fk224601') @httpretty.activate def test_create_identifiers_not_exists(self): identifier = self.node._id url = furl.furl('https://ezid.cdlib.org/id') doi = settings.EZID_FORMAT.format(namespace=settings.DOI_NAMESPACE, guid=identifier) url.path.segments.append(doi) httpretty.register_uri( httpretty.PUT, url.url, body=to_anvl({ 'success': '{doi}osf.io/{ident} | {ark}osf.io/{ident}'.format( doi=settings.DOI_NAMESPACE, ark=settings.ARK_NAMESPACE, ident=identifier, ), }), status=201, priority=1, ) res = self.app.post( self.node.api_url_for('node_identifiers_post'), auth=self.user.auth, ) self.node.reload() assert_equal( res.json['doi'], self.node.get_identifier_value('doi') ) assert_equal( res.json['ark'], self.node.get_identifier_value('ark') ) assert_equal(res.status_code, 201) @httpretty.activate def test_create_identifiers_exists(self): identifier = self.node._id doi = settings.EZID_FORMAT.format(namespace=settings.DOI_NAMESPACE, guid=identifier) url = furl.furl('https://ezid.cdlib.org/id') url.path.segments.append(doi) httpretty.register_uri( httpretty.PUT, url.url, body='identifier already exists', status=400, ) httpretty.register_uri( httpretty.GET, url.url, body=to_anvl({ 'success': doi, }), status=200, ) res = self.app.post( self.node.api_url_for('node_identifiers_post'), auth=self.user.auth, ) self.node.reload() assert_equal( res.json['doi'], self.node.get_identifier_value('doi') ) assert_equal( res.json['ark'], self.node.get_identifier_value('ark') ) assert_equal(res.status_code, 201) def test_get_by_identifier(self): self.node.set_identifier_value('doi', 'FK424601') self.node.set_identifier_value('ark', 'fk224601') res_doi = self.app.get( self.node.web_url_for( 'get_referent_by_identifier', category='doi', value=self.node.get_identifier_value('doi'), ), ) assert_equal(res_doi.status_code, 302) assert_urls_equal(res_doi.headers['Location'], self.node.absolute_url) res_ark = self.app.get( self.node.web_url_for( 'get_referent_by_identifier', category='ark', value=self.node.get_identifier_value('ark'), ), ) assert_equal(res_ark.status_code, 302) assert_urls_equal(res_ark.headers['Location'], self.node.absolute_url) def test_get_by_identifier_not_found(self): self.node.set_identifier_value('doi', 'FK424601') res = self.app.get( self.node.web_url_for( 'get_referent_by_identifier', category='doi', value='fakedoi', ), expect_errors=True, ) assert_equal(res.status_code, 404)
apache-2.0
pvinis/gitxu
sign.py
8
2521
#!/usr/bin/env python # Original work by Rowan James at https://gist.github.com/rowanj/5475988 # This is free and unencumbered software released into the public domain. # http://unlicense.org import argparse import subprocess import os import glob import stat def sign(target, key, verbose=0): print('Signing ' + os.path.basename(target)) codesign = ['codesign', '--force', '--verify'] if verbose: for i in range(verbose): codesign.append('--verbose') codesign = codesign + ['--sign', key] subprocess.call(codesign + [target]) def sign_frameworks_in_app(app_path, key, verbose=0): frameworkDir = os.path.join(app_path, 'Contents/Frameworks') for framework in glob.glob(frameworkDir + '/*.framework'): sign(framework, key, verbose=verbose) def sign_resources_in_app(app_path, key, verbose=0): executableFlags = stat.S_IEXEC | stat.S_IXGRP | stat.S_IXOTH resourcesDir = os.path.join(app_path, 'Contents/Resources') for filename in os.listdir(resourcesDir): filename = os.path.join(resourcesDir, filename) if os.path.isfile(filename): st = os.stat(filename) mode = st.st_mode if mode & executableFlags: sign(filename, key, verbose) def sign_everything_in_app(app_path, key, verbose=0): sign_frameworks_in_app(app_path, key, verbose=verbose) sign_resources_in_app(app_path, key, verbose=verbose) sign(app_path, key, verbose=verbose) if __name__ == "__main__": parser = argparse.ArgumentParser(description='Sign an app and all frameworks therein') parser.add_argument('--app', required=True, help='the app bundle to sign') parser.add_argument('--key', help='the key ID to sign with', default='Developer ID Application') parser.add_argument('--frameworks','-f', help='sign embedded frameworks', action='store_const',const=True) parser.add_argument('--resources','-r', help='sign embedded executable resources', action='store_const',const=True) parser.add_argument('--verbose','-v', help='show details of signing process', action='count') args = parser.parse_args() verbose = args.verbose if verbose: print('Signing configuration:') print('APP = ' + args.app) print('ID = ' + args.key) print('FRAMEWORKS = %r' % (args.frameworks)) print('RESOURCES = %r' % (args.resources)) print('VERBOSE = %r' % (args.verbose)) sign_everything_in_app(args.app, args.key, verbose=verbose)
gpl-2.0
Health123/ansible
plugins/inventory/ssh_config.py
108
3198
#!/usr/bin/env python # (c) 2014, Tomas Karasek <tomas.karasek@digile.fi> # # 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/>. # Dynamic inventory script which lets you use aliases from ~/.ssh/config. # # It prints inventory based on parsed ~/.ssh/config. You can refer to hosts # with their alias, rather than with the IP or hostname. It takes advantage # of the ansible_ssh_{host,port,user,private_key_file}. # # If you have in your .ssh/config: # Host git # HostName git.domain.org # User tkarasek # IdentityFile /home/tomk/keys/thekey # # You can do # $ ansible git -m ping # # Example invocation: # ssh_config.py --list # ssh_config.py --host <alias> import argparse import os.path import sys import paramiko try: import json except ImportError: import simplejson as json _key = 'ssh_config' _ssh_to_ansible = [('user', 'ansible_ssh_user'), ('hostname', 'ansible_ssh_host'), ('identityfile', 'ansible_ssh_private_key_file'), ('port', 'ansible_ssh_port')] def get_config(): with open(os.path.expanduser('~/.ssh/config')) as f: cfg = paramiko.SSHConfig() cfg.parse(f) ret_dict = {} for d in cfg._config: _copy = dict(d) del _copy['host'] for host in d['host']: ret_dict[host] = _copy['config'] return ret_dict def print_list(): cfg = get_config() meta = {'hostvars': {}} for alias, attributes in cfg.items(): tmp_dict = {} for ssh_opt, ans_opt in _ssh_to_ansible: if ssh_opt in attributes: tmp_dict[ans_opt] = attributes[ssh_opt] if tmp_dict: meta['hostvars'][alias] = tmp_dict print json.dumps({_key: list(set(meta['hostvars'].keys())), '_meta': meta}) def print_host(host): cfg = get_config() print json.dumps(cfg[host]) def get_args(args_list): parser = argparse.ArgumentParser( description='ansible inventory script parsing .ssh/config') mutex_group = parser.add_mutually_exclusive_group(required=True) help_list = 'list all hosts from .ssh/config inventory' mutex_group.add_argument('--list', action='store_true', help=help_list) help_host = 'display variables for a host' mutex_group.add_argument('--host', help=help_host) return parser.parse_args(args_list) def main(args_list): args = get_args(args_list) if args.list: print_list() if args.host: print_host(args.host) if __name__ == '__main__': main(sys.argv[1:])
gpl-3.0
yugui/grpc
tools/gcp/stress_test/stress_test_utils.py
34
8833
#!/usr/bin/env python2.7 # Copyright 2015, Google Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following disclaimer # in the documentation and/or other materials provided with the # distribution. # * Neither the name of Google Inc. nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import datetime import json import os import re import select import subprocess import sys import time # Import big_query_utils module bq_utils_dir = os.path.abspath(os.path.join( os.path.dirname(__file__), '../utils')) sys.path.append(bq_utils_dir) import big_query_utils as bq_utils class EventType: STARTING = 'STARTING' RUNNING = 'RUNNING' SUCCESS = 'SUCCESS' FAILURE = 'FAILURE' class BigQueryHelper: """Helper class for the stress test wrappers to interact with BigQuery. """ def __init__(self, run_id, image_type, pod_name, project_id, dataset_id, summary_table_id, qps_table_id): self.run_id = run_id self.image_type = image_type self.pod_name = pod_name self.project_id = project_id self.dataset_id = dataset_id self.summary_table_id = summary_table_id self.qps_table_id = qps_table_id def initialize(self): self.bq = bq_utils.create_big_query() def setup_tables(self): return bq_utils.create_dataset(self.bq, self.project_id, self.dataset_id) \ and self.__create_summary_table() \ and self.__create_qps_table() def insert_summary_row(self, event_type, details): row_values_dict = { 'run_id': self.run_id, 'image_type': self.image_type, 'pod_name': self.pod_name, 'event_date': datetime.datetime.now().isoformat(), 'event_type': event_type, 'details': details } # row_unique_id is something that uniquely identifies the row (BigQuery uses # it for duplicate detection). row_unique_id = '%s_%s_%s' % (self.run_id, self.pod_name, event_type) row = bq_utils.make_row(row_unique_id, row_values_dict) return bq_utils.insert_rows(self.bq, self.project_id, self.dataset_id, self.summary_table_id, [row]) def insert_qps_row(self, qps, recorded_at): row_values_dict = { 'run_id': self.run_id, 'pod_name': self.pod_name, 'recorded_at': recorded_at, 'qps': qps } # row_unique_id is something that uniquely identifies the row (BigQuery uses # it for duplicate detection). row_unique_id = '%s_%s_%s' % (self.run_id, self.pod_name, recorded_at) row = bq_utils.make_row(row_unique_id, row_values_dict) return bq_utils.insert_rows(self.bq, self.project_id, self.dataset_id, self.qps_table_id, [row]) def check_if_any_tests_failed(self, num_query_retries=3, timeout_msec=30000): query = ('SELECT event_type FROM %s.%s WHERE run_id = \'%s\' AND ' 'event_type="%s"') % (self.dataset_id, self.summary_table_id, self.run_id, EventType.FAILURE) page = None try: query_job = bq_utils.sync_query_job(self.bq, self.project_id, query) job_id = query_job['jobReference']['jobId'] project_id = query_job['jobReference']['projectId'] page = self.bq.jobs().getQueryResults( projectId=project_id, jobId=job_id, timeoutMs=timeout_msec).execute(num_retries=num_query_retries) if not page['jobComplete']: print('TIMEOUT ERROR: The query %s timed out. Current timeout value is' ' %d msec. Returning False (i.e assuming there are no failures)' ) % (query, timeout_msec) return False num_failures = int(page['totalRows']) print 'num rows: ', num_failures return num_failures > 0 except: print 'Exception in check_if_any_tests_failed(). Info: ', sys.exc_info() print 'Query: ', query def print_summary_records(self, num_query_retries=3): line = '-' * 120 print line print 'Summary records' print 'Run Id: ', self.run_id print 'Dataset Id: ', self.dataset_id print line query = ('SELECT pod_name, image_type, event_type, event_date, details' ' FROM %s.%s WHERE run_id = \'%s\' ORDER by event_date;') % ( self.dataset_id, self.summary_table_id, self.run_id) query_job = bq_utils.sync_query_job(self.bq, self.project_id, query) print '{:<25} {:<12} {:<12} {:<30} {}'.format('Pod name', 'Image type', 'Event type', 'Date', 'Details') print line page_token = None while True: page = self.bq.jobs().getQueryResults( pageToken=page_token, **query_job['jobReference']).execute(num_retries=num_query_retries) rows = page.get('rows', []) for row in rows: print '{:<25} {:<12} {:<12} {:<30} {}'.format(row['f'][0]['v'], row['f'][1]['v'], row['f'][2]['v'], row['f'][3]['v'], row['f'][4]['v']) page_token = page.get('pageToken') if not page_token: break def print_qps_records(self, num_query_retries=3): line = '-' * 80 print line print 'QPS Summary' print 'Run Id: ', self.run_id print 'Dataset Id: ', self.dataset_id print line query = ( 'SELECT pod_name, recorded_at, qps FROM %s.%s WHERE run_id = \'%s\' ' 'ORDER by recorded_at;') % (self.dataset_id, self.qps_table_id, self.run_id) query_job = bq_utils.sync_query_job(self.bq, self.project_id, query) print '{:<25} {:30} {}'.format('Pod name', 'Recorded at', 'Qps') print line page_token = None while True: page = self.bq.jobs().getQueryResults( pageToken=page_token, **query_job['jobReference']).execute(num_retries=num_query_retries) rows = page.get('rows', []) for row in rows: print '{:<25} {:30} {}'.format(row['f'][0]['v'], row['f'][1]['v'], row['f'][2]['v']) page_token = page.get('pageToken') if not page_token: break def __create_summary_table(self): summary_table_schema = [ ('run_id', 'STRING', 'Test run id'), ('image_type', 'STRING', 'Client or Server?'), ('pod_name', 'STRING', 'GKE pod hosting this image'), ('event_date', 'STRING', 'The date of this event'), ('event_type', 'STRING', 'STARTING/RUNNING/SUCCESS/FAILURE'), ('details', 'STRING', 'Any other relevant details') ] desc = ('The table that contains STARTING/RUNNING/SUCCESS/FAILURE events ' 'for the stress test clients and servers') return bq_utils.create_table(self.bq, self.project_id, self.dataset_id, self.summary_table_id, summary_table_schema, desc) def __create_qps_table(self): qps_table_schema = [ ('run_id', 'STRING', 'Test run id'), ('pod_name', 'STRING', 'GKE pod hosting this image'), ('recorded_at', 'STRING', 'Metrics recorded at time'), ('qps', 'INTEGER', 'Queries per second') ] desc = 'The table that cointains the qps recorded at various intervals' return bq_utils.create_table(self.bq, self.project_id, self.dataset_id, self.qps_table_id, qps_table_schema, desc)
bsd-3-clause
mitodl/micromasters
cms/migrations/0025_infolinks.py
1
1226
# -*- coding: utf-8 -*- # Generated by Django 1.10.3 on 2016-12-05 22:18 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion import modelcluster.fields class Migration(migrations.Migration): dependencies = [ ('cms', '0024_programtabpage'), ] operations = [ migrations.CreateModel( name='InfoLinks', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('sort_order', models.IntegerField(blank=True, editable=False, null=True)), ('url', models.URLField(blank=True, help_text='A url for an external page. There will be a link to this url from the program page.', null=True)), ('title_url', models.TextField(blank=True, help_text='The text for the link to an external homepage.')), ('program_page', modelcluster.fields.ParentalKey(on_delete=django.db.models.deletion.CASCADE, related_name='info_links', to='cms.ProgramPage')), ], options={ 'ordering': ['sort_order'], 'abstract': False, }, ), ]
bsd-3-clause
tinchoss/Python_Android
python-build/python-libs/gdata/src/gdata/service.py
136
67387
#!/usr/bin/python # # Copyright (C) 2006,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. """GDataService provides CRUD ops. and programmatic login for GData services. Error: A base exception class for all exceptions in the gdata_client module. CaptchaRequired: This exception is thrown when a login attempt results in a captcha challenge from the ClientLogin service. When this exception is thrown, the captcha_token and captcha_url are set to the values provided in the server's response. BadAuthentication: Raised when a login attempt is made with an incorrect username or password. NotAuthenticated: Raised if an operation requiring authentication is called before a user has authenticated. NonAuthSubToken: Raised if a method to modify an AuthSub token is used when the user is either not authenticated or is authenticated through another authentication mechanism. NonOAuthToken: Raised if a method to modify an OAuth token is used when the user is either not authenticated or is authenticated through another authentication mechanism. RequestError: Raised if a CRUD request returned a non-success code. UnexpectedReturnType: Raised if the response from the server was not of the desired type. For example, this would be raised if the server sent a feed when the client requested an entry. GDataService: Encapsulates user credentials needed to perform insert, update and delete operations with the GData API. An instance can perform user authentication, query, insertion, deletion, and update. Query: Eases query URI creation by allowing URI parameters to be set as dictionary attributes. For example a query with a feed of '/base/feeds/snippets' and ['bq'] set to 'digital camera' will produce '/base/feeds/snippets?bq=digital+camera' when .ToUri() is called on it. """ __author__ = 'api.jscudder (Jeffrey Scudder)' import re import urllib import urlparse try: from xml.etree import cElementTree as ElementTree except ImportError: try: import cElementTree as ElementTree except ImportError: try: from xml.etree import ElementTree except ImportError: from elementtree import ElementTree import atom.service import gdata import atom import atom.http_interface import atom.token_store import gdata.auth AUTH_SERVER_HOST = 'https://www.google.com' # When requesting an AuthSub token, it is often helpful to track the scope # which is being requested. One way to accomplish this is to add a URL # parameter to the 'next' URL which contains the requested scope. This # constant is the default name (AKA key) for the URL parameter. SCOPE_URL_PARAM_NAME = 'authsub_token_scope' # When requesting an OAuth access token or authorization of an existing OAuth # request token, it is often helpful to track the scope(s) which is/are being # requested. One way to accomplish this is to add a URL parameter to the # 'callback' URL which contains the requested scope. This constant is the # default name (AKA key) for the URL parameter. OAUTH_SCOPE_URL_PARAM_NAME = 'oauth_token_scope' # Maps the service names used in ClientLogin to scope URLs. CLIENT_LOGIN_SCOPES = { 'cl': [ # Google Calendar 'https://www.google.com/calendar/feeds/', 'http://www.google.com/calendar/feeds/'], 'gbase': [ # Google Base 'http://base.google.com/base/feeds/', 'http://www.google.com/base/feeds/'], 'blogger': [ # Blogger 'http://www.blogger.com/feeds/'], 'codesearch': [ # Google Code Search 'http://www.google.com/codesearch/feeds/'], 'cp': [ # Contacts API 'https://www.google.com/m8/feeds/', 'http://www.google.com/m8/feeds/'], 'finance': [ # Google Finance 'http://finance.google.com/finance/feeds/'], 'health': [ # Google Health 'https://www.google.com/health/feeds/'], 'writely': [ # Documents List API 'https://docs.google.com/feeds/', 'http://docs.google.com/feeds/'], 'lh2': [ # Picasa Web Albums 'http://picasaweb.google.com/data/'], 'apps': [ # Google Apps Provisioning API 'http://www.google.com/a/feeds/', 'https://www.google.com/a/feeds/', 'http://apps-apis.google.com/a/feeds/', 'https://apps-apis.google.com/a/feeds/'], 'weaver': [ # Health H9 Sandbox 'https://www.google.com/h9/feeds/'], 'wise': [ # Spreadsheets Data API 'https://spreadsheets.google.com/feeds/', 'http://spreadsheets.google.com/feeds/'], 'sitemaps': [ # Google Webmaster Tools 'https://www.google.com/webmasters/tools/feeds/'], 'youtube': [ # YouTube 'http://gdata.youtube.com/feeds/api/', 'http://uploads.gdata.youtube.com/feeds/api', 'http://gdata.youtube.com/action/GetUploadToken'], 'books': ['http://www.google.com/books/feeds/'], 'analytics': ['https://www.google.com/analytics/feeds/']} def lookup_scopes(service_name): """Finds the scope URLs for the desired service. In some cases, an unknown service may be used, and in those cases this function will return None. """ if service_name in CLIENT_LOGIN_SCOPES: return CLIENT_LOGIN_SCOPES[service_name] return None # Module level variable specifies which module should be used by GDataService # objects to make HttpRequests. This setting can be overridden on each # instance of GDataService. # This module level variable is deprecated. Reassign the http_client member # of a GDataService object instead. http_request_handler = atom.service class Error(Exception): pass class CaptchaRequired(Error): pass class BadAuthentication(Error): pass class NotAuthenticated(Error): pass class NonAuthSubToken(Error): pass class NonOAuthToken(Error): pass class RequestError(Error): pass class UnexpectedReturnType(Error): pass class BadAuthenticationServiceURL(Error): pass class FetchingOAuthRequestTokenFailed(RequestError): pass class TokenUpgradeFailed(RequestError): pass class RevokingOAuthTokenFailed(RequestError): pass class AuthorizationRequired(Error): pass class TokenHadNoScope(Error): pass class GDataService(atom.service.AtomService): """Contains elements needed for GData login and CRUD request headers. Maintains additional headers (tokens for example) needed for the GData services to allow a user to perform inserts, updates, and deletes. """ # The hander member is deprecated, use http_client instead. handler = None # The auth_token member is deprecated, use the token_store instead. auth_token = None # The tokens dict is deprecated in favor of the token_store. tokens = None def __init__(self, email=None, password=None, account_type='HOSTED_OR_GOOGLE', service=None, auth_service_url=None, source=None, server=None, additional_headers=None, handler=None, tokens=None, http_client=None, token_store=None): """Creates an object of type GDataService. Args: email: string (optional) The user's email address, used for authentication. password: string (optional) The user's password. account_type: string (optional) The type of account to use. Use 'GOOGLE' for regular Google accounts or 'HOSTED' for Google Apps accounts, or 'HOSTED_OR_GOOGLE' to try finding a HOSTED account first and, if it doesn't exist, try finding a regular GOOGLE account. Default value: 'HOSTED_OR_GOOGLE'. service: string (optional) The desired service for which credentials will be obtained. auth_service_url: string (optional) User-defined auth token request URL allows users to explicitly specify where to send auth token requests. source: string (optional) The name of the user's application. server: string (optional) The name of the server to which a connection will be opened. Default value: 'base.google.com'. additional_headers: dictionary (optional) Any additional headers which should be included with CRUD operations. handler: module (optional) This parameter is deprecated and has been replaced by http_client. tokens: This parameter is deprecated, calls should be made to token_store instead. http_client: An object responsible for making HTTP requests using a request method. If none is provided, a new instance of atom.http.ProxiedHttpClient will be used. token_store: Keeps a collection of authorization tokens which can be applied to requests for a specific URLs. Critical methods are find_token based on a URL (atom.url.Url or a string), add_token, and remove_token. """ atom.service.AtomService.__init__(self, http_client=http_client, token_store=token_store) self.email = email self.password = password self.account_type = account_type self.service = service self.auth_service_url = auth_service_url self.server = server self.additional_headers = additional_headers or {} self._oauth_input_params = None self.__SetSource(source) self.__captcha_token = None self.__captcha_url = None self.__gsessionid = None if http_request_handler.__name__ == 'gdata.urlfetch': import gdata.alt.appengine self.http_client = gdata.alt.appengine.AppEngineHttpClient() def _SetSessionId(self, session_id): """Used in unit tests to simulate a 302 which sets a gsessionid.""" self.__gsessionid = session_id # Define properties for GDataService def _SetAuthSubToken(self, auth_token, scopes=None): """Deprecated, use SetAuthSubToken instead.""" self.SetAuthSubToken(auth_token, scopes=scopes) def __SetAuthSubToken(self, auth_token, scopes=None): """Deprecated, use SetAuthSubToken instead.""" self._SetAuthSubToken(auth_token, scopes=scopes) def _GetAuthToken(self): """Returns the auth token used for authenticating requests. Returns: string """ current_scopes = lookup_scopes(self.service) if current_scopes: token = self.token_store.find_token(current_scopes[0]) if hasattr(token, 'auth_header'): return token.auth_header return None def _GetCaptchaToken(self): """Returns a captcha token if the most recent login attempt generated one. The captcha token is only set if the Programmatic Login attempt failed because the Google service issued a captcha challenge. Returns: string """ return self.__captcha_token def __GetCaptchaToken(self): return self._GetCaptchaToken() captcha_token = property(__GetCaptchaToken, doc="""Get the captcha token for a login request.""") def _GetCaptchaURL(self): """Returns the URL of the captcha image if a login attempt generated one. The captcha URL is only set if the Programmatic Login attempt failed because the Google service issued a captcha challenge. Returns: string """ return self.__captcha_url def __GetCaptchaURL(self): return self._GetCaptchaURL() captcha_url = property(__GetCaptchaURL, doc="""Get the captcha URL for a login request.""") def GetOAuthInputParameters(self): return self._oauth_input_params def SetOAuthInputParameters(self, signature_method, consumer_key, consumer_secret=None, rsa_key=None, two_legged_oauth=False, requestor_id=None): """Sets parameters required for using OAuth authentication mechanism. NOTE: Though consumer_secret and rsa_key are optional, either of the two is required depending on the value of the signature_method. Args: signature_method: class which provides implementation for strategy class oauth.oauth.OAuthSignatureMethod. Signature method to be used for signing each request. Valid implementations are provided as the constants defined by gdata.auth.OAuthSignatureMethod. Currently they are gdata.auth.OAuthSignatureMethod.RSA_SHA1 and gdata.auth.OAuthSignatureMethod.HMAC_SHA1 consumer_key: string Domain identifying third_party web application. consumer_secret: string (optional) Secret generated during registration. Required only for HMAC_SHA1 signature method. rsa_key: string (optional) Private key required for RSA_SHA1 signature method. two_legged_oauth: boolean (optional) Enables two-legged OAuth process. requestor_id: string (optional) User email adress to make requests on their behalf. This parameter should only be set when two_legged_oauth is True. """ self._oauth_input_params = gdata.auth.OAuthInputParams( signature_method, consumer_key, consumer_secret=consumer_secret, rsa_key=rsa_key, requestor_id=requestor_id) if two_legged_oauth: oauth_token = gdata.auth.OAuthToken( oauth_input_params=self._oauth_input_params) self.SetOAuthToken(oauth_token) def FetchOAuthRequestToken(self, scopes=None, extra_parameters=None, request_url='%s/accounts/OAuthGetRequestToken' % \ AUTH_SERVER_HOST, oauth_callback=None): """Fetches and sets the OAuth request token and returns it. Args: scopes: string or list of string base URL(s) of the service(s) to be accessed. If None, then this method tries to determine the scope(s) from the current service. extra_parameters: dict (optional) key-value pairs as any additional parameters to be included in the URL and signature while making a request for fetching an OAuth request token. All the OAuth parameters are added by default. But if provided through this argument, any default parameters will be overwritten. For e.g. a default parameter oauth_version 1.0 can be overwritten if extra_parameters = {'oauth_version': '2.0'} request_url: Request token URL. The default is 'https://www.google.com/accounts/OAuthGetRequestToken'. oauth_callback: str (optional) If set, it is assume the client is using the OAuth v1.0a protocol where the callback url is sent in the request token step. If the oauth_callback is also set in extra_params, this value will override that one. Returns: The fetched request token as a gdata.auth.OAuthToken object. Raises: FetchingOAuthRequestTokenFailed if the server responded to the request with an error. """ if scopes is None: scopes = lookup_scopes(self.service) if not isinstance(scopes, (list, tuple)): scopes = [scopes,] if oauth_callback: if extra_parameters is not None: extra_parameters['oauth_callback'] = oauth_callback else: extra_parameters = {'oauth_callback': oauth_callback} request_token_url = gdata.auth.GenerateOAuthRequestTokenUrl( self._oauth_input_params, scopes, request_token_url=request_url, extra_parameters=extra_parameters) response = self.http_client.request('GET', str(request_token_url)) if response.status == 200: token = gdata.auth.OAuthToken() token.set_token_string(response.read()) token.scopes = scopes token.oauth_input_params = self._oauth_input_params self.SetOAuthToken(token) return token error = { 'status': response.status, 'reason': 'Non 200 response on fetch request token', 'body': response.read() } raise FetchingOAuthRequestTokenFailed(error) def SetOAuthToken(self, oauth_token): """Attempts to set the current token and add it to the token store. The oauth_token can be any OAuth token i.e. unauthorized request token, authorized request token or access token. This method also attempts to add the token to the token store. Use this method any time you want the current token to point to the oauth_token passed. For e.g. call this method with the request token you receive from FetchOAuthRequestToken. Args: request_token: gdata.auth.OAuthToken OAuth request token. """ if self.auto_set_current_token: self.current_token = oauth_token if self.auto_store_tokens: self.token_store.add_token(oauth_token) def GenerateOAuthAuthorizationURL( self, request_token=None, callback_url=None, extra_params=None, include_scopes_in_callback=False, scopes_param_prefix=OAUTH_SCOPE_URL_PARAM_NAME, request_url='%s/accounts/OAuthAuthorizeToken' % AUTH_SERVER_HOST): """Generates URL at which user will login to authorize the request token. Args: request_token: gdata.auth.OAuthToken (optional) OAuth request token. If not specified, then the current token will be used if it is of type <gdata.auth.OAuthToken>, else it is found by looking in the token_store by looking for a token for the current scope. callback_url: string (optional) The URL user will be sent to after logging in and granting access. extra_params: dict (optional) Additional parameters to be sent. include_scopes_in_callback: Boolean (default=False) if set to True, and if 'callback_url' is present, the 'callback_url' will be modified to include the scope(s) from the request token as a URL parameter. The key for the 'callback' URL's scope parameter will be OAUTH_SCOPE_URL_PARAM_NAME. The benefit of including the scope URL as a parameter to the 'callback' URL, is that the page which receives the OAuth token will be able to tell which URLs the token grants access to. scopes_param_prefix: string (default='oauth_token_scope') The URL parameter key which maps to the list of valid scopes for the token. This URL parameter will be included in the callback URL along with the scopes of the token as value if include_scopes_in_callback=True. request_url: Authorization URL. The default is 'https://www.google.com/accounts/OAuthAuthorizeToken'. Returns: A string URL at which the user is required to login. Raises: NonOAuthToken if the user's request token is not an OAuth token or if a request token was not available. """ if request_token and not isinstance(request_token, gdata.auth.OAuthToken): raise NonOAuthToken if not request_token: if isinstance(self.current_token, gdata.auth.OAuthToken): request_token = self.current_token else: current_scopes = lookup_scopes(self.service) if current_scopes: token = self.token_store.find_token(current_scopes[0]) if isinstance(token, gdata.auth.OAuthToken): request_token = token if not request_token: raise NonOAuthToken return str(gdata.auth.GenerateOAuthAuthorizationUrl( request_token, authorization_url=request_url, callback_url=callback_url, extra_params=extra_params, include_scopes_in_callback=include_scopes_in_callback, scopes_param_prefix=scopes_param_prefix)) def UpgradeToOAuthAccessToken(self, authorized_request_token=None, request_url='%s/accounts/OAuthGetAccessToken' \ % AUTH_SERVER_HOST, oauth_version='1.0', oauth_verifier=None): """Upgrades the authorized request token to an access token and returns it Args: authorized_request_token: gdata.auth.OAuthToken (optional) OAuth request token. If not specified, then the current token will be used if it is of type <gdata.auth.OAuthToken>, else it is found by looking in the token_store by looking for a token for the current scope. request_url: Access token URL. The default is 'https://www.google.com/accounts/OAuthGetAccessToken'. oauth_version: str (default='1.0') oauth_version parameter. All other 'oauth_' parameters are added by default. This parameter too, is added by default but here you can override it's value. oauth_verifier: str (optional) If present, it is assumed that the client will use the OAuth v1.0a protocol which includes passing the oauth_verifier (as returned by the SP) in the access token step. Returns: Access token Raises: NonOAuthToken if the user's authorized request token is not an OAuth token or if an authorized request token was not available. TokenUpgradeFailed if the server responded to the request with an error. """ if (authorized_request_token and not isinstance(authorized_request_token, gdata.auth.OAuthToken)): raise NonOAuthToken if not authorized_request_token: if isinstance(self.current_token, gdata.auth.OAuthToken): authorized_request_token = self.current_token else: current_scopes = lookup_scopes(self.service) if current_scopes: token = self.token_store.find_token(current_scopes[0]) if isinstance(token, gdata.auth.OAuthToken): authorized_request_token = token if not authorized_request_token: raise NonOAuthToken access_token_url = gdata.auth.GenerateOAuthAccessTokenUrl( authorized_request_token, self._oauth_input_params, access_token_url=request_url, oauth_version=oauth_version, oauth_verifier=oauth_verifier) response = self.http_client.request('GET', str(access_token_url)) if response.status == 200: token = gdata.auth.OAuthTokenFromHttpBody(response.read()) token.scopes = authorized_request_token.scopes token.oauth_input_params = authorized_request_token.oauth_input_params self.SetOAuthToken(token) return token else: raise TokenUpgradeFailed({'status': response.status, 'reason': 'Non 200 response on upgrade', 'body': response.read()}) def RevokeOAuthToken(self, request_url='%s/accounts/AuthSubRevokeToken' % \ AUTH_SERVER_HOST): """Revokes an existing OAuth token. request_url: Token revoke URL. The default is 'https://www.google.com/accounts/AuthSubRevokeToken'. Raises: NonOAuthToken if the user's auth token is not an OAuth token. RevokingOAuthTokenFailed if request for revoking an OAuth token failed. """ scopes = lookup_scopes(self.service) token = self.token_store.find_token(scopes[0]) if not isinstance(token, gdata.auth.OAuthToken): raise NonOAuthToken response = token.perform_request(self.http_client, 'GET', request_url, headers={'Content-Type':'application/x-www-form-urlencoded'}) if response.status == 200: self.token_store.remove_token(token) else: raise RevokingOAuthTokenFailed def GetAuthSubToken(self): """Returns the AuthSub token as a string. If the token is an gdta.auth.AuthSubToken, the Authorization Label ("AuthSub token") is removed. This method examines the current_token to see if it is an AuthSubToken or SecureAuthSubToken. If not, it searches the token_store for a token which matches the current scope. The current scope is determined by the service name string member. Returns: If the current_token is set to an AuthSubToken/SecureAuthSubToken, return the token string. If there is no current_token, a token string for a token which matches the service object's default scope is returned. If there are no tokens valid for the scope, returns None. """ if isinstance(self.current_token, gdata.auth.AuthSubToken): return self.current_token.get_token_string() current_scopes = lookup_scopes(self.service) if current_scopes: token = self.token_store.find_token(current_scopes[0]) if isinstance(token, gdata.auth.AuthSubToken): return token.get_token_string() else: token = self.token_store.find_token(atom.token_store.SCOPE_ALL) if isinstance(token, gdata.auth.ClientLoginToken): return token.get_token_string() return None def SetAuthSubToken(self, token, scopes=None, rsa_key=None): """Sets the token sent in requests to an AuthSub token. Sets the current_token and attempts to add the token to the token_store. Only use this method if you have received a token from the AuthSub service. The auth token is set automatically when UpgradeToSessionToken() is used. See documentation for Google AuthSub here: http://code.google.com/apis/accounts/AuthForWebApps.html Args: token: gdata.auth.AuthSubToken or gdata.auth.SecureAuthSubToken or string The token returned by the AuthSub service. If the token is an AuthSubToken or SecureAuthSubToken, the scope information stored in the token is used. If the token is a string, the scopes parameter is used to determine the valid scopes. scopes: list of URLs for which the token is valid. This is only used if the token parameter is a string. rsa_key: string (optional) Private key required for RSA_SHA1 signature method. This parameter is necessary if the token is a string representing a secure token. """ if not isinstance(token, gdata.auth.AuthSubToken): token_string = token if rsa_key: token = gdata.auth.SecureAuthSubToken(rsa_key) else: token = gdata.auth.AuthSubToken() token.set_token_string(token_string) # If no scopes were set for the token, use the scopes passed in, or # try to determine the scopes based on the current service name. If # all else fails, set the token to match all requests. if not token.scopes: if scopes is None: scopes = lookup_scopes(self.service) if scopes is None: scopes = [atom.token_store.SCOPE_ALL] token.scopes = scopes if self.auto_set_current_token: self.current_token = token if self.auto_store_tokens: self.token_store.add_token(token) def GetClientLoginToken(self): """Returns the token string for the current token or a token matching the service scope. If the current_token is a ClientLoginToken, the token string for the current token is returned. If the current_token is not set, this method searches for a token in the token_store which is valid for the service object's current scope. The current scope is determined by the service name string member. The token string is the end of the Authorization header, it doesn not include the ClientLogin label. """ if isinstance(self.current_token, gdata.auth.ClientLoginToken): return self.current_token.get_token_string() current_scopes = lookup_scopes(self.service) if current_scopes: token = self.token_store.find_token(current_scopes[0]) if isinstance(token, gdata.auth.ClientLoginToken): return token.get_token_string() else: token = self.token_store.find_token(atom.token_store.SCOPE_ALL) if isinstance(token, gdata.auth.ClientLoginToken): return token.get_token_string() return None def SetClientLoginToken(self, token, scopes=None): """Sets the token sent in requests to a ClientLogin token. This method sets the current_token to a new ClientLoginToken and it also attempts to add the ClientLoginToken to the token_store. Only use this method if you have received a token from the ClientLogin service. The auth_token is set automatically when ProgrammaticLogin() is used. See documentation for Google ClientLogin here: http://code.google.com/apis/accounts/docs/AuthForInstalledApps.html Args: token: string or instance of a ClientLoginToken. """ if not isinstance(token, gdata.auth.ClientLoginToken): token_string = token token = gdata.auth.ClientLoginToken() token.set_token_string(token_string) if not token.scopes: if scopes is None: scopes = lookup_scopes(self.service) if scopes is None: scopes = [atom.token_store.SCOPE_ALL] token.scopes = scopes if self.auto_set_current_token: self.current_token = token if self.auto_store_tokens: self.token_store.add_token(token) # Private methods to create the source property. def __GetSource(self): return self.__source def __SetSource(self, new_source): self.__source = new_source # Update the UserAgent header to include the new application name. self.additional_headers['User-Agent'] = atom.http_interface.USER_AGENT % ( self.__source,) source = property(__GetSource, __SetSource, doc="""The source is the name of the application making the request. It should be in the form company_id-app_name-app_version""") # Authentication operations def ProgrammaticLogin(self, captcha_token=None, captcha_response=None): """Authenticates the user and sets the GData Auth token. Login retreives a temporary auth token which must be used with all requests to GData services. The auth token is stored in the GData client object. Login is also used to respond to a captcha challenge. If the user's login attempt failed with a CaptchaRequired error, the user can respond by calling Login with the captcha token and the answer to the challenge. Args: captcha_token: string (optional) The identifier for the captcha challenge which was presented to the user. captcha_response: string (optional) The user's answer to the captch challenge. Raises: CaptchaRequired if the login service will require a captcha response BadAuthentication if the login service rejected the username or password Error if the login service responded with a 403 different from the above """ request_body = gdata.auth.generate_client_login_request_body(self.email, self.password, self.service, self.source, self.account_type, captcha_token, captcha_response) # If the user has defined their own authentication service URL, # send the ClientLogin requests to this URL: if not self.auth_service_url: auth_request_url = AUTH_SERVER_HOST + '/accounts/ClientLogin' else: auth_request_url = self.auth_service_url auth_response = self.http_client.request('POST', auth_request_url, data=request_body, headers={'Content-Type':'application/x-www-form-urlencoded'}) response_body = auth_response.read() if auth_response.status == 200: # TODO: insert the token into the token_store directly. self.SetClientLoginToken( gdata.auth.get_client_login_token(response_body)) self.__captcha_token = None self.__captcha_url = None elif auth_response.status == 403: # Examine each line to find the error type and the captcha token and # captch URL if they are present. captcha_parameters = gdata.auth.get_captcha_challenge(response_body, captcha_base_url='%s/accounts/' % AUTH_SERVER_HOST) if captcha_parameters: self.__captcha_token = captcha_parameters['token'] self.__captcha_url = captcha_parameters['url'] raise CaptchaRequired, 'Captcha Required' elif response_body.splitlines()[0] == 'Error=BadAuthentication': self.__captcha_token = None self.__captcha_url = None raise BadAuthentication, 'Incorrect username or password' else: self.__captcha_token = None self.__captcha_url = None raise Error, 'Server responded with a 403 code' elif auth_response.status == 302: self.__captcha_token = None self.__captcha_url = None # Google tries to redirect all bad URLs back to # http://www.google.<locale>. If a redirect # attempt is made, assume the user has supplied an incorrect authentication URL raise BadAuthenticationServiceURL, 'Server responded with a 302 code.' def ClientLogin(self, username, password, account_type=None, service=None, auth_service_url=None, source=None, captcha_token=None, captcha_response=None): """Convenience method for authenticating using ProgrammaticLogin. Sets values for email, password, and other optional members. Args: username: password: account_type: string (optional) service: string (optional) auth_service_url: string (optional) captcha_token: string (optional) captcha_response: string (optional) """ self.email = username self.password = password if account_type: self.account_type = account_type if service: self.service = service if source: self.source = source if auth_service_url: self.auth_service_url = auth_service_url self.ProgrammaticLogin(captcha_token, captcha_response) def GenerateAuthSubURL(self, next, scope, secure=False, session=True, domain='default'): """Generate a URL at which the user will login and be redirected back. Users enter their credentials on a Google login page and a token is sent to the URL specified in next. See documentation for AuthSub login at: http://code.google.com/apis/accounts/docs/AuthSub.html Args: next: string The URL user will be sent to after logging in. scope: string or list of strings. The URLs of the services to be accessed. secure: boolean (optional) Determines whether or not the issued token is a secure token. session: boolean (optional) Determines whether or not the issued token can be upgraded to a session token. """ if not isinstance(scope, (list, tuple)): scope = (scope,) return gdata.auth.generate_auth_sub_url(next, scope, secure=secure, session=session, request_url='%s/accounts/AuthSubRequest' % AUTH_SERVER_HOST, domain=domain) def UpgradeToSessionToken(self, token=None): """Upgrades a single use AuthSub token to a session token. Args: token: A gdata.auth.AuthSubToken or gdata.auth.SecureAuthSubToken (optional) which is good for a single use but can be upgraded to a session token. If no token is passed in, the token is found by looking in the token_store by looking for a token for the current scope. Raises: NonAuthSubToken if the user's auth token is not an AuthSub token TokenUpgradeFailed if the server responded to the request with an error. """ if token is None: scopes = lookup_scopes(self.service) if scopes: token = self.token_store.find_token(scopes[0]) else: token = self.token_store.find_token(atom.token_store.SCOPE_ALL) if not isinstance(token, gdata.auth.AuthSubToken): raise NonAuthSubToken self.SetAuthSubToken(self.upgrade_to_session_token(token)) def upgrade_to_session_token(self, token): """Upgrades a single use AuthSub token to a session token. Args: token: A gdata.auth.AuthSubToken or gdata.auth.SecureAuthSubToken which is good for a single use but can be upgraded to a session token. Returns: The upgraded token as a gdata.auth.AuthSubToken object. Raises: TokenUpgradeFailed if the server responded to the request with an error. """ response = token.perform_request(self.http_client, 'GET', AUTH_SERVER_HOST + '/accounts/AuthSubSessionToken', headers={'Content-Type':'application/x-www-form-urlencoded'}) response_body = response.read() if response.status == 200: token.set_token_string( gdata.auth.token_from_http_body(response_body)) return token else: raise TokenUpgradeFailed({'status': response.status, 'reason': 'Non 200 response on upgrade', 'body': response_body}) def RevokeAuthSubToken(self): """Revokes an existing AuthSub token. Raises: NonAuthSubToken if the user's auth token is not an AuthSub token """ scopes = lookup_scopes(self.service) token = self.token_store.find_token(scopes[0]) if not isinstance(token, gdata.auth.AuthSubToken): raise NonAuthSubToken response = token.perform_request(self.http_client, 'GET', AUTH_SERVER_HOST + '/accounts/AuthSubRevokeToken', headers={'Content-Type':'application/x-www-form-urlencoded'}) if response.status == 200: self.token_store.remove_token(token) def AuthSubTokenInfo(self): """Fetches the AuthSub token's metadata from the server. Raises: NonAuthSubToken if the user's auth token is not an AuthSub token """ scopes = lookup_scopes(self.service) token = self.token_store.find_token(scopes[0]) if not isinstance(token, gdata.auth.AuthSubToken): raise NonAuthSubToken response = token.perform_request(self.http_client, 'GET', AUTH_SERVER_HOST + '/accounts/AuthSubTokenInfo', headers={'Content-Type':'application/x-www-form-urlencoded'}) result_body = response.read() if response.status == 200: return result_body else: raise RequestError, {'status': response.status, 'body': result_body} # CRUD operations def Get(self, uri, extra_headers=None, redirects_remaining=4, encoding='UTF-8', converter=None): """Query the GData API with the given URI The uri is the portion of the URI after the server value (ex: www.google.com). To perform a query against Google Base, set the server to 'base.google.com' and set the uri to '/base/feeds/...', where ... is your query. For example, to find snippets for all digital cameras uri should be set to: '/base/feeds/snippets?bq=digital+camera' Args: uri: string The query in the form of a URI. Example: '/base/feeds/snippets?bq=digital+camera'. extra_headers: dictionary (optional) Extra HTTP headers to be included in the GET request. These headers are in addition to those stored in the client's additional_headers property. The client automatically sets the Content-Type and Authorization headers. redirects_remaining: int (optional) Tracks the number of additional redirects this method will allow. If the service object receives a redirect and remaining is 0, it will not follow the redirect. This was added to avoid infinite redirect loops. encoding: string (optional) The character encoding for the server's response. Default is UTF-8 converter: func (optional) A function which will transform the server's results before it is returned. Example: use GDataFeedFromString to parse the server response as if it were a GDataFeed. Returns: If there is no ResultsTransformer specified in the call, a GDataFeed or GDataEntry depending on which is sent from the server. If the response is niether a feed or entry and there is no ResultsTransformer, return a string. If there is a ResultsTransformer, the returned value will be that of the ResultsTransformer function. """ if extra_headers is None: extra_headers = {} if self.__gsessionid is not None: if uri.find('gsessionid=') < 0: if uri.find('?') > -1: uri += '&gsessionid=%s' % (self.__gsessionid,) else: uri += '?gsessionid=%s' % (self.__gsessionid,) server_response = self.request('GET', uri, headers=extra_headers) result_body = server_response.read() if server_response.status == 200: if converter: return converter(result_body) # There was no ResultsTransformer specified, so try to convert the # server's response into a GDataFeed. feed = gdata.GDataFeedFromString(result_body) if not feed: # If conversion to a GDataFeed failed, try to convert the server's # response to a GDataEntry. entry = gdata.GDataEntryFromString(result_body) if not entry: # The server's response wasn't a feed, or an entry, so return the # response body as a string. return result_body return entry return feed elif server_response.status == 302: if redirects_remaining > 0: location = server_response.getheader('Location') if location is not None: m = re.compile('[\?\&]gsessionid=(\w*)').search(location) if m is not None: self.__gsessionid = m.group(1) return GDataService.Get(self, location, extra_headers, redirects_remaining - 1, encoding=encoding, converter=converter) else: raise RequestError, {'status': server_response.status, 'reason': '302 received without Location header', 'body': result_body} else: raise RequestError, {'status': server_response.status, 'reason': 'Redirect received, but redirects_remaining <= 0', 'body': result_body} else: raise RequestError, {'status': server_response.status, 'reason': server_response.reason, 'body': result_body} def GetMedia(self, uri, extra_headers=None): """Returns a MediaSource containing media and its metadata from the given URI string. """ response_handle = self.request('GET', uri, headers=extra_headers) return gdata.MediaSource(response_handle, response_handle.getheader( 'Content-Type'), response_handle.getheader('Content-Length')) def GetEntry(self, uri, extra_headers=None): """Query the GData API with the given URI and receive an Entry. See also documentation for gdata.service.Get Args: uri: string The query in the form of a URI. Example: '/base/feeds/snippets?bq=digital+camera'. extra_headers: dictionary (optional) Extra HTTP headers to be included in the GET request. These headers are in addition to those stored in the client's additional_headers property. The client automatically sets the Content-Type and Authorization headers. Returns: A GDataEntry built from the XML in the server's response. """ result = GDataService.Get(self, uri, extra_headers, converter=atom.EntryFromString) if isinstance(result, atom.Entry): return result else: raise UnexpectedReturnType, 'Server did not send an entry' def GetFeed(self, uri, extra_headers=None, converter=gdata.GDataFeedFromString): """Query the GData API with the given URI and receive a Feed. See also documentation for gdata.service.Get Args: uri: string The query in the form of a URI. Example: '/base/feeds/snippets?bq=digital+camera'. extra_headers: dictionary (optional) Extra HTTP headers to be included in the GET request. These headers are in addition to those stored in the client's additional_headers property. The client automatically sets the Content-Type and Authorization headers. Returns: A GDataFeed built from the XML in the server's response. """ result = GDataService.Get(self, uri, extra_headers, converter=converter) if isinstance(result, atom.Feed): return result else: raise UnexpectedReturnType, 'Server did not send a feed' def GetNext(self, feed): """Requests the next 'page' of results in the feed. This method uses the feed's next link to request an additional feed and uses the class of the feed to convert the results of the GET request. Args: feed: atom.Feed or a subclass. The feed should contain a next link and the type of the feed will be applied to the results from the server. The new feed which is returned will be of the same class as this feed which was passed in. Returns: A new feed representing the next set of results in the server's feed. The type of this feed will match that of the feed argument. """ next_link = feed.GetNextLink() # Create a closure which will convert an XML string to the class of # the feed object passed in. def ConvertToFeedClass(xml_string): return atom.CreateClassFromXMLString(feed.__class__, xml_string) # Make a GET request on the next link and use the above closure for the # converted which processes the XML string from the server. if next_link and next_link.href: return GDataService.Get(self, next_link.href, converter=ConvertToFeedClass) else: return None def Post(self, data, uri, extra_headers=None, url_params=None, escape_params=True, redirects_remaining=4, media_source=None, converter=None): """Insert or update data into a GData service at the given URI. Args: data: string, ElementTree._Element, atom.Entry, or gdata.GDataEntry The XML to be sent to the uri. uri: string The location (feed) to which the data should be inserted. Example: '/base/feeds/items'. extra_headers: dict (optional) HTTP headers which are to be included. The client automatically sets the Content-Type, Authorization, and Content-Length headers. url_params: dict (optional) Additional URL parameters to be included in the URI. These are translated into query arguments in the form '&dict_key=value&...'. Example: {'max-results': '250'} becomes &max-results=250 escape_params: boolean (optional) If false, the calling code has already ensured that the query will form a valid URL (all reserved characters have been escaped). If true, this method will escape the query and any URL parameters provided. media_source: MediaSource (optional) Container for the media to be sent along with the entry, if provided. converter: func (optional) A function which will be executed on the server's response. Often this is a function like GDataEntryFromString which will parse the body of the server's response and return a GDataEntry. Returns: If the post succeeded, this method will return a GDataFeed, GDataEntry, or the results of running converter on the server's result body (if converter was specified). """ return GDataService.PostOrPut(self, 'POST', data, uri, extra_headers=extra_headers, url_params=url_params, escape_params=escape_params, redirects_remaining=redirects_remaining, media_source=media_source, converter=converter) def PostOrPut(self, verb, data, uri, extra_headers=None, url_params=None, escape_params=True, redirects_remaining=4, media_source=None, converter=None): """Insert data into a GData service at the given URI. Args: verb: string, either 'POST' or 'PUT' data: string, ElementTree._Element, atom.Entry, or gdata.GDataEntry The XML to be sent to the uri. uri: string The location (feed) to which the data should be inserted. Example: '/base/feeds/items'. extra_headers: dict (optional) HTTP headers which are to be included. The client automatically sets the Content-Type, Authorization, and Content-Length headers. url_params: dict (optional) Additional URL parameters to be included in the URI. These are translated into query arguments in the form '&dict_key=value&...'. Example: {'max-results': '250'} becomes &max-results=250 escape_params: boolean (optional) If false, the calling code has already ensured that the query will form a valid URL (all reserved characters have been escaped). If true, this method will escape the query and any URL parameters provided. media_source: MediaSource (optional) Container for the media to be sent along with the entry, if provided. converter: func (optional) A function which will be executed on the server's response. Often this is a function like GDataEntryFromString which will parse the body of the server's response and return a GDataEntry. Returns: If the post succeeded, this method will return a GDataFeed, GDataEntry, or the results of running converter on the server's result body (if converter was specified). """ if extra_headers is None: extra_headers = {} if self.__gsessionid is not None: if uri.find('gsessionid=') < 0: if url_params is None: url_params = {} url_params['gsessionid'] = self.__gsessionid if data and media_source: if ElementTree.iselement(data): data_str = ElementTree.tostring(data) else: data_str = str(data) multipart = [] multipart.append('Media multipart posting\r\n--END_OF_PART\r\n' + \ 'Content-Type: application/atom+xml\r\n\r\n') multipart.append('\r\n--END_OF_PART\r\nContent-Type: ' + \ media_source.content_type+'\r\n\r\n') multipart.append('\r\n--END_OF_PART--\r\n') extra_headers['MIME-version'] = '1.0' extra_headers['Content-Length'] = str(len(multipart[0]) + len(multipart[1]) + len(multipart[2]) + len(data_str) + media_source.content_length) extra_headers['Content-Type'] = 'multipart/related; boundary=END_OF_PART' server_response = self.request(verb, uri, data=[multipart[0], data_str, multipart[1], media_source.file_handle, multipart[2]], headers=extra_headers, url_params=url_params) result_body = server_response.read() elif media_source or isinstance(data, gdata.MediaSource): if isinstance(data, gdata.MediaSource): media_source = data extra_headers['Content-Length'] = str(media_source.content_length) extra_headers['Content-Type'] = media_source.content_type server_response = self.request(verb, uri, data=media_source.file_handle, headers=extra_headers, url_params=url_params) result_body = server_response.read() else: http_data = data content_type = 'application/atom+xml' extra_headers['Content-Type'] = content_type server_response = self.request(verb, uri, data=http_data, headers=extra_headers, url_params=url_params) result_body = server_response.read() # Server returns 201 for most post requests, but when performing a batch # request the server responds with a 200 on success. if server_response.status == 201 or server_response.status == 200: if converter: return converter(result_body) feed = gdata.GDataFeedFromString(result_body) if not feed: entry = gdata.GDataEntryFromString(result_body) if not entry: return result_body return entry return feed elif server_response.status == 302: if redirects_remaining > 0: location = server_response.getheader('Location') if location is not None: m = re.compile('[\?\&]gsessionid=(\w*)').search(location) if m is not None: self.__gsessionid = m.group(1) return GDataService.PostOrPut(self, verb, data, location, extra_headers, url_params, escape_params, redirects_remaining - 1, media_source, converter=converter) else: raise RequestError, {'status': server_response.status, 'reason': '302 received without Location header', 'body': result_body} else: raise RequestError, {'status': server_response.status, 'reason': 'Redirect received, but redirects_remaining <= 0', 'body': result_body} else: raise RequestError, {'status': server_response.status, 'reason': server_response.reason, 'body': result_body} def Put(self, data, uri, extra_headers=None, url_params=None, escape_params=True, redirects_remaining=3, media_source=None, converter=None): """Updates an entry at the given URI. Args: data: string, ElementTree._Element, or xml_wrapper.ElementWrapper The XML containing the updated data. uri: string A URI indicating entry to which the update will be applied. Example: '/base/feeds/items/ITEM-ID' extra_headers: dict (optional) HTTP headers which are to be included. The client automatically sets the Content-Type, Authorization, and Content-Length headers. url_params: dict (optional) Additional URL parameters to be included in the URI. These are translated into query arguments in the form '&dict_key=value&...'. Example: {'max-results': '250'} becomes &max-results=250 escape_params: boolean (optional) If false, the calling code has already ensured that the query will form a valid URL (all reserved characters have been escaped). If true, this method will escape the query and any URL parameters provided. converter: func (optional) A function which will be executed on the server's response. Often this is a function like GDataEntryFromString which will parse the body of the server's response and return a GDataEntry. Returns: If the put succeeded, this method will return a GDataFeed, GDataEntry, or the results of running converter on the server's result body (if converter was specified). """ return GDataService.PostOrPut(self, 'PUT', data, uri, extra_headers=extra_headers, url_params=url_params, escape_params=escape_params, redirects_remaining=redirects_remaining, media_source=media_source, converter=converter) def Delete(self, uri, extra_headers=None, url_params=None, escape_params=True, redirects_remaining=4): """Deletes the entry at the given URI. Args: uri: string The URI of the entry to be deleted. Example: '/base/feeds/items/ITEM-ID' extra_headers: dict (optional) HTTP headers which are to be included. The client automatically sets the Content-Type and Authorization headers. url_params: dict (optional) Additional URL parameters to be included in the URI. These are translated into query arguments in the form '&dict_key=value&...'. Example: {'max-results': '250'} becomes &max-results=250 escape_params: boolean (optional) If false, the calling code has already ensured that the query will form a valid URL (all reserved characters have been escaped). If true, this method will escape the query and any URL parameters provided. Returns: True if the entry was deleted. """ if extra_headers is None: extra_headers = {} if self.__gsessionid is not None: if uri.find('gsessionid=') < 0: if url_params is None: url_params = {} url_params['gsessionid'] = self.__gsessionid server_response = self.request('DELETE', uri, headers=extra_headers, url_params=url_params) result_body = server_response.read() if server_response.status == 200: return True elif server_response.status == 302: if redirects_remaining > 0: location = server_response.getheader('Location') if location is not None: m = re.compile('[\?\&]gsessionid=(\w*)').search(location) if m is not None: self.__gsessionid = m.group(1) return GDataService.Delete(self, location, extra_headers, url_params, escape_params, redirects_remaining - 1) else: raise RequestError, {'status': server_response.status, 'reason': '302 received without Location header', 'body': result_body} else: raise RequestError, {'status': server_response.status, 'reason': 'Redirect received, but redirects_remaining <= 0', 'body': result_body} else: raise RequestError, {'status': server_response.status, 'reason': server_response.reason, 'body': result_body} def ExtractToken(url, scopes_included_in_next=True): """Gets the AuthSub token from the current page's URL. Designed to be used on the URL that the browser is sent to after the user authorizes this application at the page given by GenerateAuthSubRequestUrl. Args: url: The current page's URL. It should contain the token as a URL parameter. Example: 'http://example.com/?...&token=abcd435' scopes_included_in_next: If True, this function looks for a scope value associated with the token. The scope is a URL parameter with the key set to SCOPE_URL_PARAM_NAME. This parameter should be present if the AuthSub request URL was generated using GenerateAuthSubRequestUrl with include_scope_in_next set to True. Returns: A tuple containing the token string and a list of scope strings for which this token should be valid. If the scope was not included in the URL, the tuple will contain (token, None). """ parsed = urlparse.urlparse(url) token = gdata.auth.AuthSubTokenFromUrl(parsed[4]) scopes = '' if scopes_included_in_next: for pair in parsed[4].split('&'): if pair.startswith('%s=' % SCOPE_URL_PARAM_NAME): scopes = urllib.unquote_plus(pair.split('=')[1]) return (token, scopes.split(' ')) def GenerateAuthSubRequestUrl(next, scopes, hd='default', secure=False, session=True, request_url='https://www.google.com/accounts/AuthSubRequest', include_scopes_in_next=True): """Creates a URL to request an AuthSub token to access Google services. For more details on AuthSub, see the documentation here: http://code.google.com/apis/accounts/docs/AuthSub.html Args: next: The URL where the browser should be sent after the user authorizes the application. This page is responsible for receiving the token which is embeded in the URL as a parameter. scopes: The base URL to which access will be granted. Example: 'http://www.google.com/calendar/feeds' will grant access to all URLs in the Google Calendar data API. If you would like a token for multiple scopes, pass in a list of URL strings. hd: The domain to which the user's account belongs. This is set to the domain name if you are using Google Apps. Example: 'example.org' Defaults to 'default' secure: If set to True, all requests should be signed. The default is False. session: If set to True, the token received by the 'next' URL can be upgraded to a multiuse session token. If session is set to False, the token may only be used once and cannot be upgraded. Default is True. request_url: The base of the URL to which the user will be sent to authorize this application to access their data. The default is 'https://www.google.com/accounts/AuthSubRequest'. include_scopes_in_next: Boolean if set to true, the 'next' parameter will be modified to include the requested scope as a URL parameter. The key for the next's scope parameter will be SCOPE_URL_PARAM_NAME. The benefit of including the scope URL as a parameter to the next URL, is that the page which receives the AuthSub token will be able to tell which URLs the token grants access to. Returns: A URL string to which the browser should be sent. """ if isinstance(scopes, list): scope = ' '.join(scopes) else: scope = scopes if include_scopes_in_next: if next.find('?') > -1: next += '&%s' % urllib.urlencode({SCOPE_URL_PARAM_NAME:scope}) else: next += '?%s' % urllib.urlencode({SCOPE_URL_PARAM_NAME:scope}) return gdata.auth.GenerateAuthSubUrl(next=next, scope=scope, secure=secure, session=session, request_url=request_url, domain=hd) class Query(dict): """Constructs a query URL to be used in GET requests Url parameters are created by adding key-value pairs to this object as a dict. For example, to add &max-results=25 to the URL do my_query['max-results'] = 25 Category queries are created by adding category strings to the categories member. All items in the categories list will be concatenated with the / symbol (symbolizing a category x AND y restriction). If you would like to OR 2 categories, append them as one string with a | between the categories. For example, do query.categories.append('Fritz|Laurie') to create a query like this feed/-/Fritz%7CLaurie . This query will look for results in both categories. """ def __init__(self, feed=None, text_query=None, params=None, categories=None): """Constructor for Query Args: feed: str (optional) The path for the feed (Examples: '/base/feeds/snippets' or 'calendar/feeds/jo@gmail.com/private/full' text_query: str (optional) The contents of the q query parameter. The contents of the text_query are URL escaped upon conversion to a URI. params: dict (optional) Parameter value string pairs which become URL params when translated to a URI. These parameters are added to the query's items (key-value pairs). categories: list (optional) List of category strings which should be included as query categories. See http://code.google.com/apis/gdata/reference.html#Queries for details. If you want to get results from category A or B (both categories), specify a single list item 'A|B'. """ self.feed = feed self.categories = [] if text_query: self.text_query = text_query if isinstance(params, dict): for param in params: self[param] = params[param] if isinstance(categories, list): for category in categories: self.categories.append(category) def _GetTextQuery(self): if 'q' in self.keys(): return self['q'] else: return None def _SetTextQuery(self, query): self['q'] = query text_query = property(_GetTextQuery, _SetTextQuery, doc="""The feed query's q parameter""") def _GetAuthor(self): if 'author' in self.keys(): return self['author'] else: return None def _SetAuthor(self, query): self['author'] = query author = property(_GetAuthor, _SetAuthor, doc="""The feed query's author parameter""") def _GetAlt(self): if 'alt' in self.keys(): return self['alt'] else: return None def _SetAlt(self, query): self['alt'] = query alt = property(_GetAlt, _SetAlt, doc="""The feed query's alt parameter""") def _GetUpdatedMin(self): if 'updated-min' in self.keys(): return self['updated-min'] else: return None def _SetUpdatedMin(self, query): self['updated-min'] = query updated_min = property(_GetUpdatedMin, _SetUpdatedMin, doc="""The feed query's updated-min parameter""") def _GetUpdatedMax(self): if 'updated-max' in self.keys(): return self['updated-max'] else: return None def _SetUpdatedMax(self, query): self['updated-max'] = query updated_max = property(_GetUpdatedMax, _SetUpdatedMax, doc="""The feed query's updated-max parameter""") def _GetPublishedMin(self): if 'published-min' in self.keys(): return self['published-min'] else: return None def _SetPublishedMin(self, query): self['published-min'] = query published_min = property(_GetPublishedMin, _SetPublishedMin, doc="""The feed query's published-min parameter""") def _GetPublishedMax(self): if 'published-max' in self.keys(): return self['published-max'] else: return None def _SetPublishedMax(self, query): self['published-max'] = query published_max = property(_GetPublishedMax, _SetPublishedMax, doc="""The feed query's published-max parameter""") def _GetStartIndex(self): if 'start-index' in self.keys(): return self['start-index'] else: return None def _SetStartIndex(self, query): if not isinstance(query, str): query = str(query) self['start-index'] = query start_index = property(_GetStartIndex, _SetStartIndex, doc="""The feed query's start-index parameter""") def _GetMaxResults(self): if 'max-results' in self.keys(): return self['max-results'] else: return None def _SetMaxResults(self, query): if not isinstance(query, str): query = str(query) self['max-results'] = query max_results = property(_GetMaxResults, _SetMaxResults, doc="""The feed query's max-results parameter""") def _GetOrderBy(self): if 'orderby' in self.keys(): return self['orderby'] else: return None def _SetOrderBy(self, query): self['orderby'] = query orderby = property(_GetOrderBy, _SetOrderBy, doc="""The feed query's orderby parameter""") def ToUri(self): q_feed = self.feed or '' category_string = '/'.join( [urllib.quote_plus(c) for c in self.categories]) # Add categories to the feed if there are any. if len(self.categories) > 0: q_feed = q_feed + '/-/' + category_string return atom.service.BuildUri(q_feed, self) def __str__(self): return self.ToUri()
apache-2.0
lidiamcfreitas/FenixScheduleMaker
ScheduleMaker/brython/www/src/Lib/test/test_contains.py
173
2641
from collections import deque from test.support import run_unittest import unittest class base_set: def __init__(self, el): self.el = el class myset(base_set): def __contains__(self, el): return self.el == el class seq(base_set): def __getitem__(self, n): return [self.el][n] class TestContains(unittest.TestCase): def test_common_tests(self): a = base_set(1) b = myset(1) c = seq(1) self.assertIn(1, b) self.assertNotIn(0, b) self.assertIn(1, c) self.assertNotIn(0, c) self.assertRaises(TypeError, lambda: 1 in a) self.assertRaises(TypeError, lambda: 1 not in a) # test char in string self.assertIn('c', 'abc') self.assertNotIn('d', 'abc') self.assertIn('', '') self.assertIn('', 'abc') self.assertRaises(TypeError, lambda: None in 'abc') def test_builtin_sequence_types(self): # a collection of tests on builtin sequence types a = range(10) for i in a: self.assertIn(i, a) self.assertNotIn(16, a) self.assertNotIn(a, a) a = tuple(a) for i in a: self.assertIn(i, a) self.assertNotIn(16, a) self.assertNotIn(a, a) class Deviant1: """Behaves strangely when compared This class is designed to make sure that the contains code works when the list is modified during the check. """ aList = list(range(15)) def __eq__(self, other): if other == 12: self.aList.remove(12) self.aList.remove(13) self.aList.remove(14) return 0 self.assertNotIn(Deviant1(), Deviant1.aList) def test_nonreflexive(self): # containment and equality tests involving elements that are # not necessarily equal to themselves class MyNonReflexive(object): def __eq__(self, other): return False def __hash__(self): return 28 values = float('nan'), 1, None, 'abc', MyNonReflexive() constructors = list, tuple, dict.fromkeys, set, frozenset, deque for constructor in constructors: container = constructor(values) for elem in container: self.assertIn(elem, container) self.assertTrue(container == constructor(values)) self.assertTrue(container == container) def test_main(): run_unittest(TestContains) if __name__ == '__main__': test_main()
bsd-2-clause
0jpq0/kbengine
kbe/src/lib/python/Lib/encodings/cp1253.py
272
13094
""" Python Character Mapping Codec cp1253 generated from 'MAPPINGS/VENDORS/MICSFT/WINDOWS/CP1253.TXT' with gencodec.py. """#" import codecs ### Codec APIs class Codec(codecs.Codec): def encode(self,input,errors='strict'): return codecs.charmap_encode(input,errors,encoding_table) def decode(self,input,errors='strict'): return codecs.charmap_decode(input,errors,decoding_table) class IncrementalEncoder(codecs.IncrementalEncoder): def encode(self, input, final=False): return codecs.charmap_encode(input,self.errors,encoding_table)[0] class IncrementalDecoder(codecs.IncrementalDecoder): def decode(self, input, final=False): return codecs.charmap_decode(input,self.errors,decoding_table)[0] class StreamWriter(Codec,codecs.StreamWriter): pass class StreamReader(Codec,codecs.StreamReader): pass ### encodings module API def getregentry(): return codecs.CodecInfo( name='cp1253', encode=Codec().encode, decode=Codec().decode, incrementalencoder=IncrementalEncoder, incrementaldecoder=IncrementalDecoder, streamreader=StreamReader, streamwriter=StreamWriter, ) ### Decoding Table decoding_table = ( '\x00' # 0x00 -> NULL '\x01' # 0x01 -> START OF HEADING '\x02' # 0x02 -> START OF TEXT '\x03' # 0x03 -> END OF TEXT '\x04' # 0x04 -> END OF TRANSMISSION '\x05' # 0x05 -> ENQUIRY '\x06' # 0x06 -> ACKNOWLEDGE '\x07' # 0x07 -> BELL '\x08' # 0x08 -> BACKSPACE '\t' # 0x09 -> HORIZONTAL TABULATION '\n' # 0x0A -> LINE FEED '\x0b' # 0x0B -> VERTICAL TABULATION '\x0c' # 0x0C -> FORM FEED '\r' # 0x0D -> CARRIAGE RETURN '\x0e' # 0x0E -> SHIFT OUT '\x0f' # 0x0F -> SHIFT IN '\x10' # 0x10 -> DATA LINK ESCAPE '\x11' # 0x11 -> DEVICE CONTROL ONE '\x12' # 0x12 -> DEVICE CONTROL TWO '\x13' # 0x13 -> DEVICE CONTROL THREE '\x14' # 0x14 -> DEVICE CONTROL FOUR '\x15' # 0x15 -> NEGATIVE ACKNOWLEDGE '\x16' # 0x16 -> SYNCHRONOUS IDLE '\x17' # 0x17 -> END OF TRANSMISSION BLOCK '\x18' # 0x18 -> CANCEL '\x19' # 0x19 -> END OF MEDIUM '\x1a' # 0x1A -> SUBSTITUTE '\x1b' # 0x1B -> ESCAPE '\x1c' # 0x1C -> FILE SEPARATOR '\x1d' # 0x1D -> GROUP SEPARATOR '\x1e' # 0x1E -> RECORD SEPARATOR '\x1f' # 0x1F -> UNIT SEPARATOR ' ' # 0x20 -> SPACE '!' # 0x21 -> EXCLAMATION MARK '"' # 0x22 -> QUOTATION MARK '#' # 0x23 -> NUMBER SIGN '$' # 0x24 -> DOLLAR SIGN '%' # 0x25 -> PERCENT SIGN '&' # 0x26 -> AMPERSAND "'" # 0x27 -> APOSTROPHE '(' # 0x28 -> LEFT PARENTHESIS ')' # 0x29 -> RIGHT PARENTHESIS '*' # 0x2A -> ASTERISK '+' # 0x2B -> PLUS SIGN ',' # 0x2C -> COMMA '-' # 0x2D -> HYPHEN-MINUS '.' # 0x2E -> FULL STOP '/' # 0x2F -> SOLIDUS '0' # 0x30 -> DIGIT ZERO '1' # 0x31 -> DIGIT ONE '2' # 0x32 -> DIGIT TWO '3' # 0x33 -> DIGIT THREE '4' # 0x34 -> DIGIT FOUR '5' # 0x35 -> DIGIT FIVE '6' # 0x36 -> DIGIT SIX '7' # 0x37 -> DIGIT SEVEN '8' # 0x38 -> DIGIT EIGHT '9' # 0x39 -> DIGIT NINE ':' # 0x3A -> COLON ';' # 0x3B -> SEMICOLON '<' # 0x3C -> LESS-THAN SIGN '=' # 0x3D -> EQUALS SIGN '>' # 0x3E -> GREATER-THAN SIGN '?' # 0x3F -> QUESTION MARK '@' # 0x40 -> COMMERCIAL AT 'A' # 0x41 -> LATIN CAPITAL LETTER A 'B' # 0x42 -> LATIN CAPITAL LETTER B 'C' # 0x43 -> LATIN CAPITAL LETTER C 'D' # 0x44 -> LATIN CAPITAL LETTER D 'E' # 0x45 -> LATIN CAPITAL LETTER E 'F' # 0x46 -> LATIN CAPITAL LETTER F 'G' # 0x47 -> LATIN CAPITAL LETTER G 'H' # 0x48 -> LATIN CAPITAL LETTER H 'I' # 0x49 -> LATIN CAPITAL LETTER I 'J' # 0x4A -> LATIN CAPITAL LETTER J 'K' # 0x4B -> LATIN CAPITAL LETTER K 'L' # 0x4C -> LATIN CAPITAL LETTER L 'M' # 0x4D -> LATIN CAPITAL LETTER M 'N' # 0x4E -> LATIN CAPITAL LETTER N 'O' # 0x4F -> LATIN CAPITAL LETTER O 'P' # 0x50 -> LATIN CAPITAL LETTER P 'Q' # 0x51 -> LATIN CAPITAL LETTER Q 'R' # 0x52 -> LATIN CAPITAL LETTER R 'S' # 0x53 -> LATIN CAPITAL LETTER S 'T' # 0x54 -> LATIN CAPITAL LETTER T 'U' # 0x55 -> LATIN CAPITAL LETTER U 'V' # 0x56 -> LATIN CAPITAL LETTER V 'W' # 0x57 -> LATIN CAPITAL LETTER W 'X' # 0x58 -> LATIN CAPITAL LETTER X 'Y' # 0x59 -> LATIN CAPITAL LETTER Y 'Z' # 0x5A -> LATIN CAPITAL LETTER Z '[' # 0x5B -> LEFT SQUARE BRACKET '\\' # 0x5C -> REVERSE SOLIDUS ']' # 0x5D -> RIGHT SQUARE BRACKET '^' # 0x5E -> CIRCUMFLEX ACCENT '_' # 0x5F -> LOW LINE '`' # 0x60 -> GRAVE ACCENT 'a' # 0x61 -> LATIN SMALL LETTER A 'b' # 0x62 -> LATIN SMALL LETTER B 'c' # 0x63 -> LATIN SMALL LETTER C 'd' # 0x64 -> LATIN SMALL LETTER D 'e' # 0x65 -> LATIN SMALL LETTER E 'f' # 0x66 -> LATIN SMALL LETTER F 'g' # 0x67 -> LATIN SMALL LETTER G 'h' # 0x68 -> LATIN SMALL LETTER H 'i' # 0x69 -> LATIN SMALL LETTER I 'j' # 0x6A -> LATIN SMALL LETTER J 'k' # 0x6B -> LATIN SMALL LETTER K 'l' # 0x6C -> LATIN SMALL LETTER L 'm' # 0x6D -> LATIN SMALL LETTER M 'n' # 0x6E -> LATIN SMALL LETTER N 'o' # 0x6F -> LATIN SMALL LETTER O 'p' # 0x70 -> LATIN SMALL LETTER P 'q' # 0x71 -> LATIN SMALL LETTER Q 'r' # 0x72 -> LATIN SMALL LETTER R 's' # 0x73 -> LATIN SMALL LETTER S 't' # 0x74 -> LATIN SMALL LETTER T 'u' # 0x75 -> LATIN SMALL LETTER U 'v' # 0x76 -> LATIN SMALL LETTER V 'w' # 0x77 -> LATIN SMALL LETTER W 'x' # 0x78 -> LATIN SMALL LETTER X 'y' # 0x79 -> LATIN SMALL LETTER Y 'z' # 0x7A -> LATIN SMALL LETTER Z '{' # 0x7B -> LEFT CURLY BRACKET '|' # 0x7C -> VERTICAL LINE '}' # 0x7D -> RIGHT CURLY BRACKET '~' # 0x7E -> TILDE '\x7f' # 0x7F -> DELETE '\u20ac' # 0x80 -> EURO SIGN '\ufffe' # 0x81 -> UNDEFINED '\u201a' # 0x82 -> SINGLE LOW-9 QUOTATION MARK '\u0192' # 0x83 -> LATIN SMALL LETTER F WITH HOOK '\u201e' # 0x84 -> DOUBLE LOW-9 QUOTATION MARK '\u2026' # 0x85 -> HORIZONTAL ELLIPSIS '\u2020' # 0x86 -> DAGGER '\u2021' # 0x87 -> DOUBLE DAGGER '\ufffe' # 0x88 -> UNDEFINED '\u2030' # 0x89 -> PER MILLE SIGN '\ufffe' # 0x8A -> UNDEFINED '\u2039' # 0x8B -> SINGLE LEFT-POINTING ANGLE QUOTATION MARK '\ufffe' # 0x8C -> UNDEFINED '\ufffe' # 0x8D -> UNDEFINED '\ufffe' # 0x8E -> UNDEFINED '\ufffe' # 0x8F -> UNDEFINED '\ufffe' # 0x90 -> UNDEFINED '\u2018' # 0x91 -> LEFT SINGLE QUOTATION MARK '\u2019' # 0x92 -> RIGHT SINGLE QUOTATION MARK '\u201c' # 0x93 -> LEFT DOUBLE QUOTATION MARK '\u201d' # 0x94 -> RIGHT DOUBLE QUOTATION MARK '\u2022' # 0x95 -> BULLET '\u2013' # 0x96 -> EN DASH '\u2014' # 0x97 -> EM DASH '\ufffe' # 0x98 -> UNDEFINED '\u2122' # 0x99 -> TRADE MARK SIGN '\ufffe' # 0x9A -> UNDEFINED '\u203a' # 0x9B -> SINGLE RIGHT-POINTING ANGLE QUOTATION MARK '\ufffe' # 0x9C -> UNDEFINED '\ufffe' # 0x9D -> UNDEFINED '\ufffe' # 0x9E -> UNDEFINED '\ufffe' # 0x9F -> UNDEFINED '\xa0' # 0xA0 -> NO-BREAK SPACE '\u0385' # 0xA1 -> GREEK DIALYTIKA TONOS '\u0386' # 0xA2 -> GREEK CAPITAL LETTER ALPHA WITH TONOS '\xa3' # 0xA3 -> POUND SIGN '\xa4' # 0xA4 -> CURRENCY SIGN '\xa5' # 0xA5 -> YEN SIGN '\xa6' # 0xA6 -> BROKEN BAR '\xa7' # 0xA7 -> SECTION SIGN '\xa8' # 0xA8 -> DIAERESIS '\xa9' # 0xA9 -> COPYRIGHT SIGN '\ufffe' # 0xAA -> UNDEFINED '\xab' # 0xAB -> LEFT-POINTING DOUBLE ANGLE QUOTATION MARK '\xac' # 0xAC -> NOT SIGN '\xad' # 0xAD -> SOFT HYPHEN '\xae' # 0xAE -> REGISTERED SIGN '\u2015' # 0xAF -> HORIZONTAL BAR '\xb0' # 0xB0 -> DEGREE SIGN '\xb1' # 0xB1 -> PLUS-MINUS SIGN '\xb2' # 0xB2 -> SUPERSCRIPT TWO '\xb3' # 0xB3 -> SUPERSCRIPT THREE '\u0384' # 0xB4 -> GREEK TONOS '\xb5' # 0xB5 -> MICRO SIGN '\xb6' # 0xB6 -> PILCROW SIGN '\xb7' # 0xB7 -> MIDDLE DOT '\u0388' # 0xB8 -> GREEK CAPITAL LETTER EPSILON WITH TONOS '\u0389' # 0xB9 -> GREEK CAPITAL LETTER ETA WITH TONOS '\u038a' # 0xBA -> GREEK CAPITAL LETTER IOTA WITH TONOS '\xbb' # 0xBB -> RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK '\u038c' # 0xBC -> GREEK CAPITAL LETTER OMICRON WITH TONOS '\xbd' # 0xBD -> VULGAR FRACTION ONE HALF '\u038e' # 0xBE -> GREEK CAPITAL LETTER UPSILON WITH TONOS '\u038f' # 0xBF -> GREEK CAPITAL LETTER OMEGA WITH TONOS '\u0390' # 0xC0 -> GREEK SMALL LETTER IOTA WITH DIALYTIKA AND TONOS '\u0391' # 0xC1 -> GREEK CAPITAL LETTER ALPHA '\u0392' # 0xC2 -> GREEK CAPITAL LETTER BETA '\u0393' # 0xC3 -> GREEK CAPITAL LETTER GAMMA '\u0394' # 0xC4 -> GREEK CAPITAL LETTER DELTA '\u0395' # 0xC5 -> GREEK CAPITAL LETTER EPSILON '\u0396' # 0xC6 -> GREEK CAPITAL LETTER ZETA '\u0397' # 0xC7 -> GREEK CAPITAL LETTER ETA '\u0398' # 0xC8 -> GREEK CAPITAL LETTER THETA '\u0399' # 0xC9 -> GREEK CAPITAL LETTER IOTA '\u039a' # 0xCA -> GREEK CAPITAL LETTER KAPPA '\u039b' # 0xCB -> GREEK CAPITAL LETTER LAMDA '\u039c' # 0xCC -> GREEK CAPITAL LETTER MU '\u039d' # 0xCD -> GREEK CAPITAL LETTER NU '\u039e' # 0xCE -> GREEK CAPITAL LETTER XI '\u039f' # 0xCF -> GREEK CAPITAL LETTER OMICRON '\u03a0' # 0xD0 -> GREEK CAPITAL LETTER PI '\u03a1' # 0xD1 -> GREEK CAPITAL LETTER RHO '\ufffe' # 0xD2 -> UNDEFINED '\u03a3' # 0xD3 -> GREEK CAPITAL LETTER SIGMA '\u03a4' # 0xD4 -> GREEK CAPITAL LETTER TAU '\u03a5' # 0xD5 -> GREEK CAPITAL LETTER UPSILON '\u03a6' # 0xD6 -> GREEK CAPITAL LETTER PHI '\u03a7' # 0xD7 -> GREEK CAPITAL LETTER CHI '\u03a8' # 0xD8 -> GREEK CAPITAL LETTER PSI '\u03a9' # 0xD9 -> GREEK CAPITAL LETTER OMEGA '\u03aa' # 0xDA -> GREEK CAPITAL LETTER IOTA WITH DIALYTIKA '\u03ab' # 0xDB -> GREEK CAPITAL LETTER UPSILON WITH DIALYTIKA '\u03ac' # 0xDC -> GREEK SMALL LETTER ALPHA WITH TONOS '\u03ad' # 0xDD -> GREEK SMALL LETTER EPSILON WITH TONOS '\u03ae' # 0xDE -> GREEK SMALL LETTER ETA WITH TONOS '\u03af' # 0xDF -> GREEK SMALL LETTER IOTA WITH TONOS '\u03b0' # 0xE0 -> GREEK SMALL LETTER UPSILON WITH DIALYTIKA AND TONOS '\u03b1' # 0xE1 -> GREEK SMALL LETTER ALPHA '\u03b2' # 0xE2 -> GREEK SMALL LETTER BETA '\u03b3' # 0xE3 -> GREEK SMALL LETTER GAMMA '\u03b4' # 0xE4 -> GREEK SMALL LETTER DELTA '\u03b5' # 0xE5 -> GREEK SMALL LETTER EPSILON '\u03b6' # 0xE6 -> GREEK SMALL LETTER ZETA '\u03b7' # 0xE7 -> GREEK SMALL LETTER ETA '\u03b8' # 0xE8 -> GREEK SMALL LETTER THETA '\u03b9' # 0xE9 -> GREEK SMALL LETTER IOTA '\u03ba' # 0xEA -> GREEK SMALL LETTER KAPPA '\u03bb' # 0xEB -> GREEK SMALL LETTER LAMDA '\u03bc' # 0xEC -> GREEK SMALL LETTER MU '\u03bd' # 0xED -> GREEK SMALL LETTER NU '\u03be' # 0xEE -> GREEK SMALL LETTER XI '\u03bf' # 0xEF -> GREEK SMALL LETTER OMICRON '\u03c0' # 0xF0 -> GREEK SMALL LETTER PI '\u03c1' # 0xF1 -> GREEK SMALL LETTER RHO '\u03c2' # 0xF2 -> GREEK SMALL LETTER FINAL SIGMA '\u03c3' # 0xF3 -> GREEK SMALL LETTER SIGMA '\u03c4' # 0xF4 -> GREEK SMALL LETTER TAU '\u03c5' # 0xF5 -> GREEK SMALL LETTER UPSILON '\u03c6' # 0xF6 -> GREEK SMALL LETTER PHI '\u03c7' # 0xF7 -> GREEK SMALL LETTER CHI '\u03c8' # 0xF8 -> GREEK SMALL LETTER PSI '\u03c9' # 0xF9 -> GREEK SMALL LETTER OMEGA '\u03ca' # 0xFA -> GREEK SMALL LETTER IOTA WITH DIALYTIKA '\u03cb' # 0xFB -> GREEK SMALL LETTER UPSILON WITH DIALYTIKA '\u03cc' # 0xFC -> GREEK SMALL LETTER OMICRON WITH TONOS '\u03cd' # 0xFD -> GREEK SMALL LETTER UPSILON WITH TONOS '\u03ce' # 0xFE -> GREEK SMALL LETTER OMEGA WITH TONOS '\ufffe' # 0xFF -> UNDEFINED ) ### Encoding table encoding_table=codecs.charmap_build(decoding_table)
lgpl-3.0
sniemi/SamPy
sandbox/src1/examples/font_indexing.py
4
1299
""" A little example that shows how the various indexing into the font tables relate to one another. Mainly for mpl developers.... """ import matplotlib from matplotlib.ft2font import FT2Font, KERNING_DEFAULT, KERNING_UNFITTED, KERNING_UNSCALED #fname = '/usr/share/fonts/sfd/FreeSans.ttf' fname = matplotlib.get_data_path() + '/fonts/ttf/Vera.ttf' font = FT2Font(fname) font.set_charmap(0) codes = font.get_charmap().items() #dsu = [(ccode, glyphind) for ccode, glyphind in codes] #dsu.sort() #for ccode, glyphind in dsu: # try: name = font.get_glyph_name(glyphind) # except RuntimeError: pass # else: print '% 4d % 4d %s %s'%(glyphind, ccode, hex(int(ccode)), name) # make a charname to charcode and glyphind dictionary coded = {} glyphd = {} for ccode, glyphind in codes: name = font.get_glyph_name(glyphind) coded[name] = ccode glyphd[name] = glyphind code = coded['A'] glyph = font.load_char(code) #print glyph.bbox print glyphd['A'], glyphd['V'], coded['A'], coded['V'] print 'AV', font.get_kerning(glyphd['A'], glyphd['V'], KERNING_DEFAULT) print 'AV', font.get_kerning(glyphd['A'], glyphd['V'], KERNING_UNFITTED) print 'AV', font.get_kerning(glyphd['A'], glyphd['V'], KERNING_UNSCALED) print 'AV', font.get_kerning(glyphd['A'], glyphd['T'], KERNING_UNSCALED)
bsd-2-clause
soldag/home-assistant
tests/components/light/test_device_trigger.py
6
8220
"""The test for light device automation.""" from datetime import timedelta import pytest import homeassistant.components.automation as automation from homeassistant.components.light import DOMAIN from homeassistant.const import CONF_PLATFORM, STATE_OFF, STATE_ON from homeassistant.helpers import device_registry from homeassistant.setup import async_setup_component import homeassistant.util.dt as dt_util from tests.common import ( MockConfigEntry, async_fire_time_changed, async_get_device_automation_capabilities, async_get_device_automations, async_mock_service, mock_device_registry, mock_registry, ) @pytest.fixture def device_reg(hass): """Return an empty, loaded, registry.""" return mock_device_registry(hass) @pytest.fixture def entity_reg(hass): """Return an empty, loaded, registry.""" return mock_registry(hass) @pytest.fixture def calls(hass): """Track calls to a mock service.""" return async_mock_service(hass, "test", "automation") async def test_get_triggers(hass, device_reg, entity_reg): """Test we get the expected triggers from a light.""" config_entry = MockConfigEntry(domain="test", data={}) config_entry.add_to_hass(hass) device_entry = device_reg.async_get_or_create( config_entry_id=config_entry.entry_id, connections={(device_registry.CONNECTION_NETWORK_MAC, "12:34:56:AB:CD:EF")}, ) entity_reg.async_get_or_create(DOMAIN, "test", "5678", device_id=device_entry.id) expected_triggers = [ { "platform": "device", "domain": DOMAIN, "type": "turned_off", "device_id": device_entry.id, "entity_id": f"{DOMAIN}.test_5678", }, { "platform": "device", "domain": DOMAIN, "type": "turned_on", "device_id": device_entry.id, "entity_id": f"{DOMAIN}.test_5678", }, ] triggers = await async_get_device_automations(hass, "trigger", device_entry.id) assert triggers == expected_triggers async def test_get_trigger_capabilities(hass, device_reg, entity_reg): """Test we get the expected capabilities from a light trigger.""" config_entry = MockConfigEntry(domain="test", data={}) config_entry.add_to_hass(hass) device_entry = device_reg.async_get_or_create( config_entry_id=config_entry.entry_id, connections={(device_registry.CONNECTION_NETWORK_MAC, "12:34:56:AB:CD:EF")}, ) entity_reg.async_get_or_create(DOMAIN, "test", "5678", device_id=device_entry.id) expected_capabilities = { "extra_fields": [ {"name": "for", "optional": True, "type": "positive_time_period_dict"} ] } triggers = await async_get_device_automations(hass, "trigger", device_entry.id) for trigger in triggers: capabilities = await async_get_device_automation_capabilities( hass, "trigger", trigger ) assert capabilities == expected_capabilities async def test_if_fires_on_state_change(hass, calls): """Test for turn_on and turn_off triggers firing.""" platform = getattr(hass.components, f"test.{DOMAIN}") platform.init() await hass.async_block_till_done() assert await async_setup_component(hass, DOMAIN, {DOMAIN: {CONF_PLATFORM: "test"}}) await hass.async_block_till_done() ent1, ent2, ent3 = platform.ENTITIES assert await async_setup_component( hass, automation.DOMAIN, { automation.DOMAIN: [ { "trigger": { "platform": "device", "domain": DOMAIN, "device_id": "", "entity_id": ent1.entity_id, "type": "turned_on", }, "action": { "service": "test.automation", "data_template": { "some": "turn_on {{ trigger.%s }}" % "}} - {{ trigger.".join( ( "platform", "entity_id", "from_state.state", "to_state.state", "for", ) ) }, }, }, { "trigger": { "platform": "device", "domain": DOMAIN, "device_id": "", "entity_id": ent1.entity_id, "type": "turned_off", }, "action": { "service": "test.automation", "data_template": { "some": "turn_off {{ trigger.%s }}" % "}} - {{ trigger.".join( ( "platform", "entity_id", "from_state.state", "to_state.state", "for", ) ) }, }, }, ] }, ) await hass.async_block_till_done() assert hass.states.get(ent1.entity_id).state == STATE_ON assert len(calls) == 0 hass.states.async_set(ent1.entity_id, STATE_OFF) await hass.async_block_till_done() assert len(calls) == 1 assert calls[0].data["some"] == "turn_off device - {} - on - off - None".format( ent1.entity_id ) hass.states.async_set(ent1.entity_id, STATE_ON) await hass.async_block_till_done() assert len(calls) == 2 assert calls[1].data["some"] == "turn_on device - {} - off - on - None".format( ent1.entity_id ) async def test_if_fires_on_state_change_with_for(hass, calls): """Test for triggers firing with delay.""" platform = getattr(hass.components, f"test.{DOMAIN}") platform.init() await hass.async_block_till_done() assert await async_setup_component(hass, DOMAIN, {DOMAIN: {CONF_PLATFORM: "test"}}) await hass.async_block_till_done() ent1, ent2, ent3 = platform.ENTITIES assert await async_setup_component( hass, automation.DOMAIN, { automation.DOMAIN: [ { "trigger": { "platform": "device", "domain": DOMAIN, "device_id": "", "entity_id": ent1.entity_id, "type": "turned_off", "for": {"seconds": 5}, }, "action": { "service": "test.automation", "data_template": { "some": "turn_off {{ trigger.%s }}" % "}} - {{ trigger.".join( ( "platform", "entity_id", "from_state.state", "to_state.state", "for", ) ) }, }, } ] }, ) await hass.async_block_till_done() assert hass.states.get(ent1.entity_id).state == STATE_ON assert len(calls) == 0 hass.states.async_set(ent1.entity_id, STATE_OFF) await hass.async_block_till_done() assert len(calls) == 0 async_fire_time_changed(hass, dt_util.utcnow() + timedelta(seconds=10)) await hass.async_block_till_done() assert len(calls) == 1 await hass.async_block_till_done() assert calls[0].data["some"] == "turn_off device - {} - on - off - 0:00:05".format( ent1.entity_id )
apache-2.0
innotechsoftware/Quantum-GIS
python/console/console_editor.py
2
56306
# -*- coding:utf-8 -*- """ /*************************************************************************** Python Console for QGIS ------------------- begin : 2012-09-10 copyright : (C) 2012 by Salvatore Larosa email : lrssvtml (at) gmail (dot) com ***************************************************************************/ /*************************************************************************** * * * 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. * * * ***************************************************************************/ Some portions of code were taken from https://code.google.com/p/pydee/ """ from PyQt4.QtCore import * from PyQt4.QtGui import * from PyQt4.Qsci import (QsciScintilla, QsciScintillaBase, QsciLexerPython, QsciAPIs, QsciStyle) from qgis.core import QgsApplication from qgis.gui import QgsMessageBar import sys import os import subprocess import datetime import pyclbr from operator import itemgetter import traceback class KeyFilter(QObject): SHORTCUTS = { ("Control", "T"): lambda w, t: w.newTabEditor(), ("Control", "M"): lambda w, t: t.save(), ("Control", "W"): lambda w, t: t.close() } def __init__(self, window, tab, *args): QObject.__init__(self, *args) self.window = window self.tab = tab self._handlers = {} for shortcut, handler in KeyFilter.SHORTCUTS.iteritems(): modifiers = shortcut[0] if not isinstance(modifiers, list): modifiers = [modifiers] qt_mod_code = Qt.NoModifier for each in modifiers: qt_mod_code |= getattr(Qt, each + "Modifier") qt_keycode = getattr(Qt, "Key_" + shortcut[1].upper()) handlers = self._handlers.get(qt_keycode, []) handlers.append((qt_mod_code, handler)) self._handlers[qt_keycode] = handlers def get_handler(self, key, modifier): if self.window.count() > 1: for modifiers, handler in self._handlers.get(key, []): if modifiers == modifier: return handler return None def eventFilter(self, obj, event): if event.type() == QEvent.KeyPress and event.key() < 256: handler = self.get_handler(event.key(), event.modifiers()) if handler: handler(self.window, self.tab) return QObject.eventFilter(self, obj, event) class Editor(QsciScintilla): MARKER_NUM = 6 def __init__(self, parent=None): super(Editor,self).__init__(parent) self.parent = parent ## recent modification time self.lastModified = 0 self.opening = ['(', '{', '[', "'", '"'] self.closing = [')', '}', ']', "'", '"'] ## List of marker line to be deleted from check syntax self.bufferMarkerLine = [] self.settings = QSettings() # Enable non-ascii chars for editor self.setUtf8(True) # Set the default font font = QFont() font.setFamily('Courier') font.setFixedPitch(True) font.setPointSize(10) self.setFont(font) self.setMarginsFont(font) # Margin 0 is used for line numbers #fm = QFontMetrics(font) fontmetrics = QFontMetrics(font) self.setMarginsFont(font) self.setMarginWidth(0, fontmetrics.width("0000") + 5) self.setMarginLineNumbers(0, True) self.setMarginsForegroundColor(QColor("#3E3EE3")) self.setMarginsBackgroundColor(QColor("#f9f9f9")) self.setCaretLineVisible(True) self.setCaretLineBackgroundColor(QColor("#fcf3ed")) self.markerDefine(QgsApplication.getThemePixmap("console/iconSyntaxErrorConsole.png"), self.MARKER_NUM) self.setMinimumHeight(120) #self.setMinimumWidth(300) self.setBraceMatching(QsciScintilla.SloppyBraceMatch) self.setMatchedBraceBackgroundColor(QColor("#b7f907")) # Folding self.setFolding(QsciScintilla.PlainFoldStyle) self.setFoldMarginColors(QColor("#f4f4f4"),QColor("#f4f4f4")) #self.setWrapMode(QsciScintilla.WrapWord) ## Edge Mode self.setEdgeMode(QsciScintilla.EdgeLine) self.setEdgeColumn(80) self.setEdgeColor(QColor("#FF0000")) #self.setWrapMode(QsciScintilla.WrapCharacter) self.setWhitespaceVisibility(QsciScintilla.WsVisibleAfterIndent) #self.SendScintilla(QsciScintilla.SCI_SETHSCROLLBAR, 0) self.setVerticalScrollBarPolicy(Qt.ScrollBarAsNeeded) self.settingsEditor() # Annotations self.setAnnotationDisplay(QsciScintilla.ANNOTATION_BOXED) # Indentation self.setAutoIndent(True) self.setIndentationsUseTabs(False) self.setIndentationWidth(4) self.setTabIndents(True) self.setBackspaceUnindents(True) self.setTabWidth(4) self.setIndentationGuides(True) ## Disable command key ctrl, shift = self.SCMOD_CTRL<<16, self.SCMOD_SHIFT<<16 self.SendScintilla(QsciScintilla.SCI_CLEARCMDKEY, ord('L')+ ctrl) self.SendScintilla(QsciScintilla.SCI_CLEARCMDKEY, ord('T')+ ctrl) self.SendScintilla(QsciScintilla.SCI_CLEARCMDKEY, ord('D')+ ctrl) self.SendScintilla(QsciScintilla.SCI_CLEARCMDKEY, ord('L')+ ctrl+shift) ## New QShortcut = ctrl+space/ctrl+alt+space for Autocomplete self.newShortcutCS = QShortcut(QKeySequence(Qt.CTRL + Qt.Key_Space), self) self.newShortcutCS.setContext(Qt.WidgetShortcut) self.redoScut = QShortcut(QKeySequence(Qt.CTRL + Qt.SHIFT + Qt.Key_Z), self) self.redoScut.setContext(Qt.WidgetShortcut) self.redoScut.activated.connect(self.redo) self.newShortcutCS.activated.connect(self.autoCompleteKeyBinding) self.runScut = QShortcut(QKeySequence(Qt.CTRL + Qt.Key_E), self) self.runScut.setContext(Qt.WidgetShortcut) self.runScut.activated.connect(self.runSelectedCode) self.runScriptScut = QShortcut(QKeySequence(Qt.SHIFT + Qt.CTRL + Qt.Key_E), self) self.runScriptScut.setContext(Qt.WidgetShortcut) self.runScriptScut.activated.connect(self.runScriptCode) self.syntaxCheckScut = QShortcut(QKeySequence(Qt.CTRL + Qt.Key_4), self) self.syntaxCheckScut.setContext(Qt.WidgetShortcut) self.syntaxCheckScut.activated.connect(self.syntaxCheck) self.commentScut = QShortcut(QKeySequence(Qt.CTRL + Qt.Key_3), self) self.commentScut.setContext(Qt.WidgetShortcut) self.commentScut.activated.connect(self.parent.pc.commentCode) self.uncommentScut = QShortcut(QKeySequence(Qt.SHIFT + Qt.CTRL + Qt.Key_3), self) self.uncommentScut.setContext(Qt.WidgetShortcut) self.uncommentScut.activated.connect(self.parent.pc.uncommentCode) self.modificationChanged.connect(self.parent.modified) self.modificationAttempted.connect(self.fileReadOnly) def settingsEditor(self): # Set Python lexer self.setLexers() threshold = self.settings.value("pythonConsole/autoCompThresholdEditor", 2, type=int) radioButtonSource = self.settings.value("pythonConsole/autoCompleteSourceEditor", 'fromAPI') autoCompEnabled = self.settings.value("pythonConsole/autoCompleteEnabledEditor", True, type=bool) self.setAutoCompletionThreshold(threshold) if autoCompEnabled: if radioButtonSource == 'fromDoc': self.setAutoCompletionSource(self.AcsDocument) elif radioButtonSource == 'fromAPI': self.setAutoCompletionSource(self.AcsAPIs) elif radioButtonSource == 'fromDocAPI': self.setAutoCompletionSource(self.AcsAll) else: self.setAutoCompletionSource(self.AcsNone) def autoCompleteKeyBinding(self): radioButtonSource = self.settings.value("pythonConsole/autoCompleteSourceEditor", 'fromAPI') autoCompEnabled = self.settings.value("pythonConsole/autoCompleteEnabledEditor", True, type=bool) if autoCompEnabled: if radioButtonSource == 'fromDoc': self.autoCompleteFromDocument() elif radioButtonSource == 'fromAPI': self.autoCompleteFromAPIs() elif radioButtonSource == 'fromDocAPI': self.autoCompleteFromAll() def setLexers(self): from qgis.core import QgsApplication self.lexer = QsciLexerPython() self.lexer.setIndentationWarning(QsciLexerPython.Inconsistent) self.lexer.setFoldComments(True) self.lexer.setFoldQuotes(True) loadFont = self.settings.value("pythonConsole/fontfamilytextEditor", "Monospace") fontSize = self.settings.value("pythonConsole/fontsizeEditor", 10, type=int) font = QFont(loadFont) font.setFixedPitch(True) font.setPointSize(fontSize) font.setStyleHint(QFont.TypeWriter) font.setStretch(QFont.SemiCondensed) font.setLetterSpacing(QFont.PercentageSpacing, 87.0) font.setBold(False) self.lexer.setDefaultFont(font) self.lexer.setColor(Qt.red, 1) self.lexer.setColor(Qt.darkGreen, 5) self.lexer.setColor(Qt.darkBlue, 15) self.lexer.setFont(font, 1) self.lexer.setFont(font, 3) self.lexer.setFont(font, 4) self.api = QsciAPIs(self.lexer) chekBoxAPI = self.settings.value("pythonConsole/preloadAPI", True, type=bool) chekBoxPreparedAPI = self.settings.value("pythonConsole/usePreparedAPIFile", False, type=bool) if chekBoxAPI: self.api.loadPrepared(QgsApplication.pkgDataPath() + "/python/qsci_apis/pyqgis_master.pap") elif chekBoxPreparedAPI: self.api.loadPrepared(self.settings.value("pythonConsole/preparedAPIFile")) else: apiPath = self.settings.value("pythonConsole/userAPI", []) for i in range(0, len(apiPath)): self.api.load(unicode(apiPath[i])) self.api.prepare() self.lexer.setAPIs(self.api) self.setLexer(self.lexer) def move_cursor_to_end(self): """Move cursor to end of text""" line, index = self.get_end_pos() self.setCursorPosition(line, index) self.ensureCursorVisible() self.ensureLineVisible(line) def get_end_pos(self): """Return (line, index) position of the last character""" line = self.lines() - 1 return (line, len(self.text(line))) def contextMenuEvent(self, e): menu = QMenu(self) iconRun = QgsApplication.getThemeIcon("console/iconRunConsole.png") iconRunScript = QgsApplication.getThemeIcon("console/iconRunScriptConsole.png") iconCodePad = QgsApplication.getThemeIcon("console/iconCodepadConsole.png") iconCommentEditor = QgsApplication.getThemeIcon("console/iconCommentEditorConsole.png") iconUncommentEditor = QgsApplication.getThemeIcon("console/iconUncommentEditorConsole.png") iconSettings = QgsApplication.getThemeIcon("console/iconSettingsConsole.png") iconFind = QgsApplication.getThemeIcon("console/iconSearchEditorConsole.png") iconSyntaxCk = QgsApplication.getThemeIcon("console/iconSyntaxErrorConsole.png") iconObjInsp = QgsApplication.getThemeIcon("console/iconClassBrowserConsole.png") iconCut = QgsApplication.getThemeIcon("console/iconCutEditorConsole.png") iconCopy = QgsApplication.getThemeIcon("console/iconCopyEditorConsole.png") iconPaste = QgsApplication.getThemeIcon("console/iconPasteEditorConsole.png") hideEditorAction = menu.addAction(QCoreApplication.translate("PythonConsole", "Hide Editor"), self.hideEditor) menu.addSeparator() syntaxCheck = menu.addAction(iconSyntaxCk, QCoreApplication.translate("PythonConsole", "Check Syntax"), self.syntaxCheck, 'Ctrl+4') menu.addSeparator() runSelected = menu.addAction(iconRun, QCoreApplication.translate("PythonConsole", "Run selected"), self.runSelectedCode, 'Ctrl+E') runScript = menu.addAction(iconRunScript, QCoreApplication.translate("PythonConsole", "Run Script"), self.runScriptCode, 'Shift+Ctrl+E') menu.addSeparator() undoAction = menu.addAction(QCoreApplication.translate("PythonConsole", "Undo"), self.undo, QKeySequence.Undo) redoAction = menu.addAction(QCoreApplication.translate("PythonConsole", "Redo"), self.redo, 'Ctrl+Shift+Z') menu.addSeparator() findAction = menu.addAction(iconFind, QCoreApplication.translate("PythonConsole", "Find Text"), self.showFindWidget) menu.addSeparator() cutAction = menu.addAction(iconCut, QCoreApplication.translate("PythonConsole", "Cut"), self.cut, QKeySequence.Cut) copyAction = menu.addAction(iconCopy, QCoreApplication.translate("PythonConsole", "Copy"), self.copy, QKeySequence.Copy) pasteAction = menu.addAction(iconPaste, QCoreApplication.translate("PythonConsole", "Paste"), self.paste, QKeySequence.Paste) menu.addSeparator() commentCodeAction = menu.addAction(iconCommentEditor, QCoreApplication.translate("PythonConsole", "Comment"), self.parent.pc.commentCode, 'Ctrl+3') uncommentCodeAction = menu.addAction(iconUncommentEditor, QCoreApplication.translate("PythonConsole", "Uncomment"), self.parent.pc.uncommentCode, 'Shift+Ctrl+3') menu.addSeparator() codePadAction = menu.addAction(iconCodePad, QCoreApplication.translate("PythonConsole", "Share on codepad"), self.codepad) menu.addSeparator() showCodeInspection = menu.addAction(iconObjInsp, QCoreApplication.translate("PythonConsole", "Hide/Show Object Inspector"), self.objectListEditor) menu.addSeparator() selectAllAction = menu.addAction(QCoreApplication.translate("PythonConsole", "Select All"), self.selectAll, QKeySequence.SelectAll) menu.addSeparator() settingsDialog = menu.addAction(iconSettings, QCoreApplication.translate("PythonConsole", "Settings"), self.parent.pc.openSettings) syntaxCheck.setEnabled(False) pasteAction.setEnabled(False) codePadAction.setEnabled(False) cutAction.setEnabled(False) runSelected.setEnabled(False) copyAction.setEnabled(False) selectAllAction.setEnabled(False) undoAction.setEnabled(False) redoAction.setEnabled(False) showCodeInspection.setEnabled(False) if self.hasSelectedText(): runSelected.setEnabled(True) copyAction.setEnabled(True) cutAction.setEnabled(True) codePadAction.setEnabled(True) if not self.text() == '': selectAllAction.setEnabled(True) syntaxCheck.setEnabled(True) if self.isUndoAvailable(): undoAction.setEnabled(True) if self.isRedoAvailable(): redoAction.setEnabled(True) if QApplication.clipboard().text(): pasteAction.setEnabled(True) if self.settings.value("pythonConsole/enableObjectInsp", False, type=bool): showCodeInspection.setEnabled(True) action = menu.exec_(self.mapToGlobal(e.pos())) def findText(self, forward): lineFrom, indexFrom, lineTo, indexTo = self.getSelection() line, index = self.getCursorPosition() text = self.parent.pc.lineEditFind.text() re = False wrap = self.parent.pc.wrapAround.isChecked() cs = self.parent.pc.caseSensitive.isChecked() wo = self.parent.pc.wholeWord.isChecked() notFound = False if text: if not forward: line = lineFrom index = indexFrom ## findFirst(QString(), re bool, cs bool, wo bool, wrap, bool, forward=True) ## re = Regular Expression, cs = Case Sensitive, wo = Whole Word, wrap = Wrap Around if not self.findFirst(text, re, cs, wo, wrap, forward, line, index): notFound = True if notFound: styleError = 'QLineEdit {background-color: #d65253; \ color: #ffffff;}' msgText = QCoreApplication.translate('PythonConsole', '<b>"{}"</b> was not found.'.format(text)) self.parent.pc.callWidgetMessageBarEditor(msgText, 0, True) else: styleError = '' self.parent.pc.lineEditFind.setStyleSheet(styleError) def objectListEditor(self): listObj = self.parent.pc.listClassMethod if listObj.isVisible(): listObj.hide() self.parent.pc.objectListButton.setChecked(False) else: listObj.show() self.parent.pc.objectListButton.setChecked(True) def codepad(self): import urllib2, urllib listText = self.selectedText().split('\n') getCmd = [] for strLine in listText: getCmd.append(unicode(strLine)) pasteText= u"\n".join(getCmd) url = 'http://codepad.org' values = {'lang' : 'Python', 'code' : pasteText, 'submit':'Submit'} try: response = urllib2.urlopen(url, urllib.urlencode(values)) url = response.read() for href in url.split("</a>"): if "Link:" in href: ind=href.index('Link:') found = href[ind+5:] for i in found.split('">'): if '<a href=' in i: link = i.replace('<a href="',"").strip() if link: QApplication.clipboard().setText(link) msgText = QCoreApplication.translate('PythonConsole', 'URL copied to clipboard.') self.parent.pc.callWidgetMessageBarEditor(msgText, 0, True) except urllib2.URLError, e: msgText = QCoreApplication.translate('PythonConsole', 'Connection error: ') self.parent.pc.callWidgetMessageBarEditor(msgText + str(e.args), 0, True) def hideEditor(self): self.parent.pc.splitterObj.hide() self.parent.pc.showEditorButton.setChecked(False) def showFindWidget(self): wF = self.parent.pc.widgetFind if wF.isVisible(): wF.hide() self.parent.pc.findTextButton.setChecked(False) else: wF.show() self.parent.pc.findTextButton.setChecked(True) def commentEditorCode(self, commentCheck): self.beginUndoAction() if self.hasSelectedText(): startLine, _, endLine, _ = self.getSelection() for line in range(startLine, endLine + 1): if commentCheck: self.insertAt('#', line, 0) else: if not self.text(line).strip().startswith('#'): continue self.setSelection(line, self.indentation(line), line, self.indentation(line) + 1) self.removeSelectedText() else: line, pos = self.getCursorPosition() if commentCheck: self.insertAt('#', line, 0) else: if not self.text(line).strip().startswith('#'): return self.setSelection(line, self.indentation(line), line, self.indentation(line) + 1) self.removeSelectedText() self.endUndoAction() def createTempFile(self): import tempfile fd, path = tempfile.mkstemp() tmpFileName = path + '.py' with open(path, "w") as f: f.write(self.text()) os.close(fd) os.rename(path, tmpFileName) return tmpFileName def _runSubProcess(self, filename, tmp=False): dir = QFileInfo(filename).path() file = QFileInfo(filename).fileName() name = QFileInfo(filename).baseName() if dir not in sys.path: sys.path.append(dir) if name in sys.modules: reload(sys.modules[name]) try: ## set creationflags for running command without shell window if sys.platform.startswith('win'): p = subprocess.Popen(['python', unicode(filename)], shell=False, stdin=subprocess.PIPE, stderr=subprocess.PIPE, stdout=subprocess.PIPE, creationflags=0x08000000) else: p = subprocess.Popen(['python', unicode(filename)], shell=False, stdin=subprocess.PIPE, stderr=subprocess.PIPE, stdout=subprocess.PIPE) out, _traceback = p.communicate() ## Fix interrupted system call on OSX if sys.platform == 'darwin': status = None while status is None: try: status = p.wait() except OSError, e: if e.errno == 4: pass else: raise e if tmp: tmpFileTr = QCoreApplication.translate('PythonConsole', ' [Temporary file saved in {}]'.format(dir)) file = file + tmpFileTr if _traceback: msgTraceTr = QCoreApplication.translate('PythonConsole', '## Script error: {}'.format(file)) print "## %s" % datetime.datetime.now() print unicode(msgTraceTr) sys.stderr.write(_traceback) p.stderr.close() else: msgSuccessTr = QCoreApplication.translate('PythonConsole', '## Script executed successfully: {}'.format(file)) print "## %s" % datetime.datetime.now() print unicode(msgSuccessTr) sys.stdout.write(out) p.stdout.close() del p if tmp: os.remove(filename) except IOError, error: IOErrorTr = QCoreApplication.translate('PythonConsole', 'Cannot execute file {}. Error: {}\n'.format(unicode(filename), error.strerror)) print '## Error: ' + IOErrorTr except: s = traceback.format_exc() print '## Error: ' sys.stderr.write(s) def runScriptCode(self): autoSave = self.settings.value("pythonConsole/autoSaveScript", False, type=bool) tabWidget = self.parent.tw.currentWidget() filename = tabWidget.path msgEditorBlank = QCoreApplication.translate('PythonConsole', 'Hey, type something to run!') msgEditorUnsaved = QCoreApplication.translate('PythonConsole', 'You have to save the file before running it.') if filename is None: if not self.isModified(): self.parent.pc.callWidgetMessageBarEditor(msgEditorBlank, 0, True) return if self.isModified() and not autoSave: self.parent.pc.callWidgetMessageBarEditor(msgEditorUnsaved, 0, True) return if self.syntaxCheck(fromContextMenu=False): if autoSave: tmpFile = self.createTempFile() self._runSubProcess(tmpFile, True) else: self._runSubProcess(filename) def runSelectedCode(self): cmd = self.selectedText() self.parent.pc.shell.insertFromDropPaste(cmd) self.parent.pc.shell.entered() self.setFocus() def getTextFromEditor(self): text = self.text() textList = text.split("\n") return textList def goToLine(self, objName, linenr): self.SendScintilla(QsciScintilla.SCI_GOTOLINE, linenr-1) self.SendScintilla(QsciScintilla.SCI_SETTARGETSTART, self.SendScintilla(QsciScintilla.SCI_GETCURRENTPOS)) self.SendScintilla(QsciScintilla.SCI_SETTARGETEND, len(self.text())) pos = self.SendScintilla(QsciScintilla.SCI_SEARCHINTARGET, len(objName), objName) index = pos - self.SendScintilla(QsciScintilla.SCI_GETCURRENTPOS) #line, _ = self.getCursorPosition() self.setSelection(linenr - 1, index, linenr - 1, index + len(objName)) self.ensureLineVisible(linenr) self.setFocus() def syntaxCheck(self, filename=None, fromContextMenu=True): eline = None ecolumn = 0 edescr = '' source = unicode(self.text()) try: if not filename: filename = self.parent.tw.currentWidget().path #source = open(filename, 'r').read() + '\n' if type(source) == type(u""): source = source.encode('utf-8') if type(filename) == type(u""): filename = filename.encode('utf-8') compile(source, str(filename), 'exec') except SyntaxError, detail: s = traceback.format_exception_only(SyntaxError, detail) fn = detail.filename eline = detail.lineno and detail.lineno or 1 ecolumn = detail.offset and detail.offset or 1 edescr = detail.msg if eline != None: eline -= 1 for markerLine in self.bufferMarkerLine: self.markerDelete(markerLine) self.clearAnnotations(markerLine) self.bufferMarkerLine.remove(markerLine) if (eline) not in self.bufferMarkerLine: self.bufferMarkerLine.append(eline) self.markerAdd(eline, self.MARKER_NUM) loadFont = self.settings.value("pythonConsole/fontfamilytextEditor", "Monospace") styleAnn = QsciStyle(-1,"Annotation", QColor(255,0,0), QColor(255,200,0), QFont(loadFont, 8,-1,True), True) self.annotate(eline, edescr, styleAnn) self.setCursorPosition(eline, ecolumn-1) #self.setSelection(eline, ecolumn, eline, self.lineLength(eline)-1) self.ensureLineVisible(eline) #self.ensureCursorVisible() return False else: self.markerDeleteAll() self.clearAnnotations() if fromContextMenu: msgText = QCoreApplication.translate('PythonConsole', 'Syntax ok') self.parent.pc.callWidgetMessageBarEditor(msgText, 0, True) return True def keyPressEvent(self, e): if self.settings.value("pythonConsole/autoCloseBracketEditor", True, type=bool): startLine, _, endLine, _ = self.getSelection() t = unicode(e.text()) ## Close bracket automatically if t in self.opening: i = self.opening.index(t) if self.hasSelectedText(): self.beginUndoAction() selText = self.selectedText() self.removeSelectedText() if startLine == endLine: self.insert(self.opening[i] + selText + self.closing[i]) return elif startLine < endLine and self.opening[i] in ("'", '"'): self.insert("'''" + selText + "'''") return else: self.insert(self.closing[i]) self.endUndoAction() else: self.insert(self.closing[i]) QsciScintilla.keyPressEvent(self, e) else: QsciScintilla.keyPressEvent(self, e) def focusInEvent(self, e): pathfile = self.parent.path if pathfile: if not QFileInfo(pathfile).exists(): msgText = QCoreApplication.translate('PythonConsole', 'The file <b>"{}"</b> has been deleted or is not accessible'.format(unicode(pathfile))) self.parent.pc.callWidgetMessageBarEditor(msgText, 2, False) return if pathfile and self.lastModified != QFileInfo(pathfile).lastModified(): self.beginUndoAction() self.selectAll() #fileReplaced = self.selectedText() self.removeSelectedText() file = open(pathfile, "r") fileLines = file.readlines() file.close() QApplication.setOverrideCursor(Qt.WaitCursor) for line in reversed(fileLines): self.insert(line) QApplication.restoreOverrideCursor() self.setModified(False) self.endUndoAction() self.parent.tw.listObject(self.parent.tw.currentWidget()) self.lastModified = QFileInfo(pathfile).lastModified() msgText = QCoreApplication.translate('PythonConsole', 'The file <b>"{}"</b> has been changed and reloaded'.format(unicode(pathfile))) self.parent.pc.callWidgetMessageBarEditor(msgText, 1, False) QsciScintilla.focusInEvent(self, e) def fileReadOnly(self): tabWidget = self.parent.tw.currentWidget() msgText = QCoreApplication.translate('PythonConsole', 'The file <b>"{}"</b> is read only, please save to different file first.'.format(unicode(tabWidget.path))) self.parent.pc.callWidgetMessageBarEditor(msgText, 1, False) class EditorTab(QWidget): def __init__(self, parent, parentConsole, filename, readOnly): super(EditorTab, self).__init__(parent) self.tw = parent self.pc = parentConsole self.path = None self.readOnly = readOnly self.fileExcuteList = {} self.fileExcuteList = dict() self.newEditor = Editor(self) if filename: self.path = filename if QFileInfo(filename).exists(): self.loadFile(filename, False) # Creates layout for message bar self.layout = QGridLayout(self.newEditor) self.layout.setContentsMargins(0, 0, 0, 0) spacerItem = QSpacerItem(20, 40, QSizePolicy.Minimum, QSizePolicy.Expanding) self.layout.addItem(spacerItem, 1, 0, 1, 1) # messageBar instance self.infoBar = QgsMessageBar() sizePolicy = QSizePolicy(QSizePolicy.Minimum, QSizePolicy.Fixed) self.infoBar.setSizePolicy(sizePolicy) self.layout.addWidget(self.infoBar, 0, 0, 1, 1) self.tabLayout = QGridLayout(self) self.tabLayout.setContentsMargins(0, 0, 0, 0) self.tabLayout.addWidget(self.newEditor) self.keyFilter = KeyFilter(parent, self) self.setEventFilter(self.keyFilter) def loadFile(self, filename, modified): self.newEditor.lastModified = QFileInfo(filename).lastModified() fn = open(unicode(filename), "rb") txt = fn.read() fn.close() QApplication.setOverrideCursor(QCursor(Qt.WaitCursor)) self.newEditor.setText(txt) if self.readOnly: self.newEditor.setReadOnly(self.readOnly) QApplication.restoreOverrideCursor() self.newEditor.setModified(modified) self.newEditor.recolor() def save(self, fileName=None): index = self.tw.indexOf(self) if fileName: self.path = fileName if self.path is None: saveTr = QCoreApplication.translate('PythonConsole', 'Python Console: Save file') self.path = str(QFileDialog().getSaveFileName(self, saveTr, self.tw.tabText(index) + '.py', "Script file (*.py)")) # If the user didn't select a file, abort the save operation if len(self.path) == 0: self.path = None return self.tw.setCurrentWidget(self) msgText = QCoreApplication.translate('PythonConsole', 'Script was correctly saved.') self.pc.callWidgetMessageBarEditor(msgText, 0, True) # Rename the original file, if it exists path = unicode(self.path) overwrite = QFileInfo(path).exists() if overwrite: try: permis = os.stat(path).st_mode #self.newEditor.lastModified = QFileInfo(path).lastModified() os.chmod(path, permis) except: raise temp_path = path + "~" if QFileInfo(temp_path).exists(): os.remove(temp_path) os.rename(path, temp_path) # Save the new contents with open(path, "w") as f: f.write(self.newEditor.text()) if overwrite: os.remove(temp_path) if self.newEditor.isReadOnly(): self.newEditor.setReadOnly(False) fN = path.split('/')[-1] self.tw.setTabTitle(index, fN) self.tw.setTabToolTip(index, path) self.newEditor.setModified(False) self.pc.saveFileButton.setEnabled(False) self.newEditor.lastModified = QFileInfo(path).lastModified() self.pc.updateTabListScript(path, action='append') self.tw.listObject(self) def modified(self, modified): self.tw.tabModified(self, modified) def close(self): self.tw._removeTab(self, tab2index=True) def setEventFilter(self, filter): self.newEditor.installEventFilter(filter) def newTab(self): self.tw.newTabEditor() class EditorTabWidget(QTabWidget): def __init__(self, parent): QTabWidget.__init__(self, parent=None) self.parent = parent self.idx = -1 # Layout for top frame (restore tabs) self.layoutTopFrame = QGridLayout(self) self.layoutTopFrame.setContentsMargins(0, 0, 0, 0) spacerItem = QSpacerItem(20, 40, QSizePolicy.Minimum, QSizePolicy.Expanding) self.layoutTopFrame.addItem(spacerItem, 1, 0, 1, 1) self.topFrame = QFrame(self) self.topFrame.setStyleSheet('background-color: rgb(255, 255, 230);') self.topFrame.setFrameShape(QFrame.StyledPanel) self.topFrame.setMinimumHeight(24) self.layoutTopFrame2 = QGridLayout(self.topFrame) self.layoutTopFrame2.setContentsMargins(0, 0, 0, 0) label = QCoreApplication.translate("PythonConsole", "Click on button to restore all tabs from last session.") self.label = QLabel(label) self.restoreTabsButton = QToolButton() toolTipRestore = QCoreApplication.translate("PythonConsole", "Restore tabs") self.restoreTabsButton.setToolTip(toolTipRestore) self.restoreTabsButton.setIcon(QgsApplication.getThemeIcon("console/iconRestoreTabsConsole.png")) self.restoreTabsButton.setIconSize(QSize(24, 24)) self.restoreTabsButton.setAutoRaise(True) self.restoreTabsButton.setCursor(Qt.PointingHandCursor) self.restoreTabsButton.setStyleSheet('QToolButton:hover{border: none } \ QToolButton:pressed{border: none}') self.clButton = QToolButton() toolTipClose = QCoreApplication.translate("PythonConsole", "Close") self.clButton.setToolTip(toolTipClose) self.clButton.setIcon(QgsApplication.getThemeIcon("mIconClose.png")) self.clButton.setIconSize(QSize(18, 18)) self.clButton.setCursor(Qt.PointingHandCursor) self.clButton.setStyleSheet('QToolButton:hover{border: none } \ QToolButton:pressed{border: none}') self.clButton.setAutoRaise(True) sizePolicy = QSizePolicy(QSizePolicy.Minimum, QSizePolicy.Fixed) self.topFrame.setSizePolicy(sizePolicy) self.layoutTopFrame.addWidget(self.topFrame, 0, 0, 1, 1) self.layoutTopFrame2.addWidget(self.label, 0, 1, 1, 1) self.layoutTopFrame2.addWidget(self.restoreTabsButton, 0, 0, 1, 1) self.layoutTopFrame2.addWidget(self.clButton, 0, 2, 1, 1) self.topFrame.hide() self.connect(self.restoreTabsButton, SIGNAL('clicked()'), self.restoreTabs) self.connect(self.clButton, SIGNAL('clicked()'), self.closeRestore) # Restore script of the previuos session self.settings = QSettings() tabScripts = self.settings.value("pythonConsole/tabScripts", []) self.restoreTabList = tabScripts if self.restoreTabList: self.topFrame.show() else: self.newTabEditor(filename=None) ## Fixes #7653 if sys.platform != 'darwin': self.setDocumentMode(True) self.setMovable(True) self.setTabsClosable(True) self.setTabPosition(QTabWidget.North) # Menu button list tabs self.fileTabMenu = QMenu() self.connect(self.fileTabMenu, SIGNAL("aboutToShow()"), self.showFileTabMenu) self.connect(self.fileTabMenu, SIGNAL("triggered(QAction*)"), self.showFileTabMenuTriggered) self.fileTabButton = QToolButton() txtToolTipMenuFile = QCoreApplication.translate("PythonConsole", "List all tabs") self.fileTabButton.setToolTip(txtToolTipMenuFile) self.fileTabButton.setIcon(QgsApplication.getThemeIcon("console/iconFileTabsMenuConsole.png")) self.fileTabButton.setIconSize(QSize(24, 24)) self.fileTabButton.setAutoRaise(True) self.fileTabButton.setPopupMode(QToolButton.InstantPopup) self.fileTabButton.setMenu(self.fileTabMenu) self.setCornerWidget(self.fileTabButton, Qt.TopRightCorner) self.connect(self, SIGNAL("tabCloseRequested(int)"), self._removeTab) self.connect(self, SIGNAL('currentChanged(int)'), self._currentWidgetChanged) # New Editor button self.newTabButton = QToolButton() txtToolTipNewTab = QCoreApplication.translate("PythonConsole", "New Editor") self.newTabButton.setToolTip(txtToolTipNewTab) self.newTabButton.setAutoRaise(True) self.newTabButton.setIcon(QgsApplication.getThemeIcon("console/iconNewTabEditorConsole.png")) self.newTabButton.setIconSize(QSize(24, 24)) self.setCornerWidget(self.newTabButton, Qt.TopLeftCorner) self.connect(self.newTabButton, SIGNAL('clicked()'), self.newTabEditor) def _currentWidgetChanged(self, tab): if self.settings.value("pythonConsole/enableObjectInsp", False, type=bool): self.listObject(tab) self.changeLastDirPath(tab) self.enableSaveIfModified(tab) def contextMenuEvent(self, e): tabBar = self.tabBar() self.idx = tabBar.tabAt(e.pos()) if self.widget(self.idx): cW = self.widget(self.idx) menu = QMenu(self) menu.addSeparator() newTabAction = menu.addAction("New Editor", self.newTabEditor) menu.addSeparator() closeTabAction = menu.addAction("Close Tab", cW.close) closeAllTabAction = menu.addAction("Close All", self.closeAll) closeOthersTabAction = menu.addAction("Close Others", self.closeOthers) menu.addSeparator() saveAction = menu.addAction("Save", cW.save) saveAsAction = menu.addAction("Save As", self.saveAs) closeTabAction.setEnabled(False) closeAllTabAction.setEnabled(False) closeOthersTabAction.setEnabled(False) saveAction.setEnabled(False) if self.count() > 1: closeTabAction.setEnabled(True) closeAllTabAction.setEnabled(True) closeOthersTabAction.setEnabled(True) if self.widget(self.idx).newEditor.isModified(): saveAction.setEnabled(True) action = menu.exec_(self.mapToGlobal(e.pos())) def closeOthers(self): idx = self.idx countTab = self.count() for i in range(countTab - 1, idx, -1) + range(idx - 1, -1, -1): self._removeTab(i) def closeAll(self): countTab = self.count() cI = self.currentIndex() for i in range(countTab - 1, 0, -1): self._removeTab(i) self.newTabEditor(tabName='Untitled-0') self._removeTab(0) def saveAs(self): idx = self.idx self.parent.saveAsScriptFile(idx) self.setCurrentWidget(self.widget(idx)) def enableSaveIfModified(self, tab): tabWidget = self.widget(tab) if tabWidget: self.parent.saveFileButton.setEnabled(tabWidget.newEditor.isModified()) def enableToolBarEditor(self, enable): if self.topFrame.isVisible(): enable = False self.parent.toolBarEditor.setEnabled(enable) def newTabEditor(self, tabName=None, filename=None): readOnly = False if filename: readOnly = not QFileInfo(filename).isWritable() try: fn = open(unicode(filename), "rb") txt = fn.read() fn.close() except IOError, error: IOErrorTr = QCoreApplication.translate('PythonConsole', 'The file {} could not be opened. Error: {}\n'.format(unicode(filename), error.strerror)) print '## Error: ' sys.stderr.write(IOErrorTr) return nr = self.count() if not tabName: tabName = QCoreApplication.translate('PythonConsole', 'Untitled-{}'.format(nr)) self.tab = EditorTab(self, self.parent, filename, readOnly) self.iconTab = QgsApplication.getThemeIcon('console/iconTabEditorConsole.png') self.addTab(self.tab, self.iconTab, tabName + ' (ro)' if readOnly else tabName) self.setCurrentWidget(self.tab) if filename: self.setTabToolTip(self.currentIndex(), unicode(filename)) else: self.setTabToolTip(self.currentIndex(), tabName) def tabModified(self, tab, modified): index = self.indexOf(tab) color = Qt.darkGray if modified else Qt.black self.tabBar().setTabTextColor(index, color) self.parent.saveFileButton.setEnabled(modified) def closeTab(self, tab): if self.count() < 2: self.removeTab(self.indexOf(tab)) self.newTabEditor() else: self.removeTab(self.indexOf(tab)) self.currentWidget().setFocus(Qt.TabFocusReason) def setTabTitle(self, tab, title): self.setTabText(tab, title) def _removeTab(self, tab, tab2index=False): if tab2index: tab = self.indexOf(tab) tabWidget = self.widget(tab) if tabWidget.newEditor.isModified(): txtSaveOnRemove = QCoreApplication.translate("PythonConsole", "Python Console: Save File") txtMsgSaveOnRemove = QCoreApplication.translate("PythonConsole", "The file <b>'{}'</b> has been modified, save changes?".format(self.tabText(tab))) res = QMessageBox.question( self, txtSaveOnRemove, txtMsgSaveOnRemove, QMessageBox.Save | QMessageBox.Discard | QMessageBox.Cancel ) if res == QMessageBox.Save: tabWidget.save() elif res == QMessageBox.Cancel: return if tabWidget.path: self.parent.updateTabListScript(tabWidget.path, action='remove') self.removeTab(tab) if self.count() < 1: self.newTabEditor() else: if tabWidget.path: self.parent.updateTabListScript(tabWidget.path, action='remove') if self.count() <= 1: self.removeTab(tab) self.newTabEditor() else: self.removeTab(tab) self.currentWidget().newEditor.setFocus(Qt.TabFocusReason) def buttonClosePressed(self): self.closeCurrentWidget() def closeCurrentWidget(self): currWidget = self.currentWidget() if currWidget and currWidget.close(): self.removeTab( self.currentIndex() ) currWidget = self.currentWidget() if currWidget: currWidget.setFocus(Qt.TabFocusReason) if currWidget.path in self.restoreTabList: self.parent.updateTabListScript(currWidget.path, action='remove') def restoreTabs(self): for script in self.restoreTabList: pathFile = unicode(script) if QFileInfo(pathFile).exists(): tabName = pathFile.split('/')[-1] self.newTabEditor(tabName, pathFile) else: errOnRestore = QCoreApplication.translate("PythonConsole", "Unable to restore the file: \n{}\n".format(unicode(pathFile))) print '## Error: ' s = errOnRestore sys.stderr.write(s) self.parent.updateTabListScript(pathFile, action='remove') if self.count() < 1: self.newTabEditor(filename=None) self.topFrame.close() self.enableToolBarEditor(True) self.currentWidget().newEditor.setFocus(Qt.TabFocusReason) def closeRestore(self): self.parent.updateTabListScript(None) self.topFrame.close() self.newTabEditor(filename=None) self.enableToolBarEditor(True) def showFileTabMenu(self): self.fileTabMenu.clear() for index in range(self.count()): action = self.fileTabMenu.addAction(self.tabIcon(index), self.tabText(index)) action.setData(index) def showFileTabMenuTriggered(self, action): index = action.data() if index is not None: self.setCurrentIndex(index) def listObject(self, tab): self.parent.listClassMethod.clear() if isinstance(tab, EditorTab): tabWidget = self.widget(self.indexOf(tab)) else: tabWidget = self.widget(tab) if tabWidget: if tabWidget.path: pathFile, file = os.path.split(unicode(tabWidget.path)) module, ext = os.path.splitext(file) found = False if pathFile not in sys.path: sys.path.append(pathFile) found = True try: reload(pyclbr) dictObject = {} readModule = pyclbr.readmodule(module) readModuleFunction = pyclbr.readmodule_ex(module) for name, class_data in sorted(readModule.items(), key=lambda x:x[1].lineno): if os.path.normpath(str(class_data.file)) == os.path.normpath(str(tabWidget.path)): superClassName = [] for superClass in class_data.super: if superClass == 'object': continue if isinstance(superClass, basestring): superClassName.append(superClass) else: superClassName.append(superClass.name) classItem = QTreeWidgetItem() if superClassName: super = ', '.join([i for i in superClassName]) classItem.setText(0, name + ' [' + super + ']') classItem.setToolTip(0, name + ' [' + super + ']') else: classItem.setText(0, name) classItem.setToolTip(0, name) if sys.platform.startswith('win'): classItem.setSizeHint(0, QSize(18, 18)) classItem.setText(1, str(class_data.lineno)) iconClass = QgsApplication.getThemeIcon("console/iconClassTreeWidgetConsole.png") classItem.setIcon(0, iconClass) dictObject[name] = class_data.lineno for meth, lineno in sorted(class_data.methods.items(), key=itemgetter(1)): methodItem = QTreeWidgetItem() methodItem.setText(0, meth + ' ') methodItem.setText(1, str(lineno)) methodItem.setToolTip(0, meth) iconMeth = QgsApplication.getThemeIcon("console/iconMethodTreeWidgetConsole.png") methodItem.setIcon(0, iconMeth) if sys.platform.startswith('win'): methodItem.setSizeHint(0, QSize(18, 18)) classItem.addChild(methodItem) dictObject[meth] = lineno self.parent.listClassMethod.addTopLevelItem(classItem) for func_name, data in sorted(readModuleFunction.items(), key=lambda x:x[1].lineno): if isinstance(data, pyclbr.Function) and \ os.path.normpath(str(data.file)) == os.path.normpath(str(tabWidget.path)): funcItem = QTreeWidgetItem() funcItem.setText(0, func_name + ' ') funcItem.setText(1, str(data.lineno)) funcItem.setToolTip(0, func_name) iconFunc = QgsApplication.getThemeIcon("console/iconFunctionTreeWidgetConsole.png") funcItem.setIcon(0, iconFunc) if sys.platform.startswith('win'): funcItem.setSizeHint(0, QSize(18, 18)) dictObject[func_name] = data.lineno self.parent.listClassMethod.addTopLevelItem(funcItem) if found: sys.path.remove(pathFile) except: msgItem = QTreeWidgetItem() msgItem.setText(0, QCoreApplication.translate("PythonConsole", "Check Syntax")) msgItem.setText(1, 'syntaxError') iconWarning = QgsApplication.getThemeIcon("console/iconSyntaxErrorConsole.png") msgItem.setIcon(0, iconWarning) self.parent.listClassMethod.addTopLevelItem(msgItem) # s = traceback.format_exc() # print '## Error: ' # sys.stderr.write(s) # pass def refreshSettingsEditor(self): countTab = self.count() for i in range(countTab): self.widget(i).newEditor.settingsEditor() objInspectorEnabled = self.settings.value("pythonConsole/enableObjectInsp", False, type=bool) listObj = self.parent.objectListButton if self.parent.listClassMethod.isVisible(): listObj.setChecked(objInspectorEnabled) listObj.setEnabled(objInspectorEnabled) if objInspectorEnabled: cW = self.currentWidget() if cW and not self.parent.listClassMethod.isVisible(): QApplication.setOverrideCursor(QCursor(Qt.WaitCursor)) self.listObject(cW) QApplication.restoreOverrideCursor() def changeLastDirPath(self, tab): tabWidget = self.widget(tab) if tabWidget: self.settings.setValue("pythonConsole/lastDirPath", tabWidget.path) def widgetMessageBar(self, iface, text, level, timed=True): messageLevel = [QgsMessageBar.INFO, QgsMessageBar.WARNING, QgsMessageBar.CRITICAL] if timed: timeout = iface.messageTimeout() else: timeout = 0 currWidget = self.currentWidget() currWidget.infoBar.pushMessage(text, messageLevel[level], timeout)
gpl-2.0
eagle00789/PythonMiniProbe
test_sensors.py
1
3294
#!/usr/bin/env python from nose.tools import * from sensors import nmap,adns,apt,cpuload,cputemp def test_nmap_get_kind(): """nmap returns the correct kind""" test_nmap = nmap.NMAP() assert_equal(test_nmap.get_kind(), 'mpnmap') def test_nmap_icmp_echo_request(): """nmap const ICMP_ECHO_REQUEST is set correct""" test_nmap = nmap.NMAP() assert_equal(test_nmap.ICMP_ECHO_REQUEST, 8) def test_nmap_dec2bin(): """nmap dec2bin results""" test_nmap = nmap.NMAP() assert_equal(test_nmap.dec2bin(255,8),'11111111') assert_equal(test_nmap.dec2bin(254,8),'11111110') assert_equal(test_nmap.dec2bin(128,8),'10000000') assert_equal(test_nmap.dec2bin(127,8),'01111111') assert_equal(test_nmap.dec2bin(0,8),'00000000') def test_nmap_ip2bin(): """nmap ip2bin results""" test_nmap = nmap.NMAP() assert_equal(test_nmap.ip2bin('255.255.255.255'),'11111111111111111111111111111111') assert_equal(test_nmap.ip2bin('254.254.254.254'),'11111110111111101111111011111110') assert_equal(test_nmap.ip2bin('128.128.128.128'),'10000000100000001000000010000000') assert_equal(test_nmap.ip2bin('127.127.127.127'),'01111111011111110111111101111111') assert_equal(test_nmap.ip2bin('0.0.0.0'),'00000000000000000000000000000000') def test_nmap_bin2ip(): """nmap bin2ip results""" test_nmap = nmap.NMAP() assert_equal(test_nmap.bin2ip('11111111111111111111111111111111'),'255.255.255.255') assert_equal(test_nmap.bin2ip('11111110111111101111111011111110'),'254.254.254.254') assert_equal(test_nmap.bin2ip('10000000100000001000000010000000'),'128.128.128.128') assert_equal(test_nmap.bin2ip('01111111011111110111111101111111'),'127.127.127.127') assert_equal(test_nmap.bin2ip('00000000000000000000000000000000'),'0.0.0.0') def test_nmap_validateCIDRBlock(): """nmap validateCIDRBlock results""" test_nmap = nmap.NMAP() assert_equal(test_nmap.validateCIDRBlock('127.0.0.0'),'Error: Invalid CIDR format!') assert_equal(test_nmap.validateCIDRBlock('256.256.256.256/8'),'Error: quad 256 wrong size.') assert_equal(test_nmap.validateCIDRBlock('127.0.0.0/33'),'Error: subnet 33 wrong size.') assert_true(test_nmap.validateCIDRBlock('127.0.0.0/8')) def test_nmap_returnCIDR(): """nmap returnCIDR results""" test_nmap = nmap.NMAP() assert_equal(test_nmap.returnCIDR('127.0.0.0/30'),['127.0.0.0', '127.0.0.1', '127.0.0.2', '127.0.0.3']) def test_nmap_checksum(): """nmap checksum results""" test_nmap = nmap.NMAP() assert_equal(test_nmap.checksum('test'),6182) assert_equal(test_nmap.checksum('python'),43951) assert_equal(test_nmap.checksum('prtg'),6950) def test_adns_get_kind(): """dns returns the correct kind""" test_adns = adns.aDNS() assert_equal(test_adns.get_kind(), 'mpdns') def test_apt_get_kind(): """apt returns the correct kind""" test_apt = apt.APT() assert_equal(test_apt.get_kind(), 'mpapt') def test_cpuload_get_kind(): """cpuload returns the correct kind""" test_cpuload = cpuload.CPULoad() assert_equal(test_cpuload.get_kind(), 'mpcpuload') def test_cputemp_get_kind(): """cputemp returns the correct kind""" test_cputemp = cputemp.CPUTemp() assert_equal(test_cputemp.get_kind(), 'mpcputemp')
bsd-3-clause
hurrinico/sale-workflow
sale_order_type/models/sale_order.py
6
2083
# -*- encoding: utf-8 -*- ############################################################################## # For copyright and license notices, see __openerp__.py file in root directory ############################################################################## from openerp import api, fields, models class SaleOrder(models.Model): _inherit = 'sale.order' def _get_order_type(self): return self.env['sale.order.type'].search([])[:1] type_id = fields.Many2one( comodel_name='sale.order.type', string='Type', default=_get_order_type) @api.multi def onchange_partner_id(self, part): res = super(SaleOrder, self).onchange_partner_id(part) if part: partner = self.env['res.partner'].browse(part) res['value'].update({ 'type_id': partner.sale_type.id or self._get_order_type().id, }) return res @api.one @api.onchange('type_id') def onchange_type_id(self): self.warehouse_id = self.type_id.warehouse_id self.picking_policy = self.type_id.picking_policy self.order_policy = self.type_id.order_policy @api.model def create(self, vals): if vals.get('name', '/') == '/'and vals.get('type_id'): type = self.env['sale.order.type'].browse(vals['type_id']) if type.sequence_id: sequence_obj = self.env['ir.sequence'] vals['name'] = sequence_obj.next_by_id(type.sequence_id.id) return super(SaleOrder, self).create(vals) @api.model def _prepare_order_line_procurement(self, order, line, group_id=False): vals = super(SaleOrder, self)._prepare_order_line_procurement( order, line, group_id=group_id) vals['invoice_state'] = order.type_id.invoice_state return vals @api.model def _prepare_invoice(self, order, line_ids): res = super(SaleOrder, self)._prepare_invoice(order, line_ids) if order.type_id.journal_id: res['journal_id'] = order.type_id.journal_id.id return res
agpl-3.0
vpelletier/neoppod
neo/master/backup_app.py
1
16200
# # Copyright (C) 2012-2016 Nexedi SA # # 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, see <http://www.gnu.org/licenses/>. import random, weakref from bisect import bisect from collections import defaultdict from neo.lib import logging from neo.lib.bootstrap import BootstrapManager from neo.lib.exception import PrimaryFailure from neo.lib.handler import EventHandler from neo.lib.node import NodeManager from neo.lib.protocol import CellStates, ClusterStates, \ NodeStates, NodeTypes, Packets, uuid_str, INVALID_TID, ZERO_TID from neo.lib.util import add64, dump from .app import StateChangedException from .pt import PartitionTable from .handlers.backup import BackupHandler """ Backup algorithm This implementation relies on normal storage replication. Storage nodes that are specialised for backup are not in the same NEO cluster, but are managed by another master in a different cluster. When the cluster is in BACKINGUP state, its master acts like a client to the master of the main cluster. It gets notified of new data thanks to invalidation, and notifies in turn its storage nodes what/when to replicate. Storages stay in UP_TO_DATE state, even if partitions are synchronized up to different tids. Storage nodes remember they are in such state and when switching into RUNNING state, the cluster cuts the DB at the "backup TID", which is the last TID for which we have all data. This TID can't be guessed from 'trans' and 'obj' tables, like it is done in normal mode, so: - The master must even notify storages of transactions that don't modify their partitions: see Replicate packets without any source. - 'backup_tid' properties exist in many places, on the master and the storages, so that the DB can be made consistent again at any moment, without losing any (or little) data. Out of backup storage nodes assigned to a partition, one is chosen as primary for that partition. It means only this node will fetch data from the upstream cluster, to minimize bandwidth between clusters. Other replicas will synchronize from the primary node. There is no UUID conflict between the 2 clusters: - Storage nodes connect anonymously to upstream. - Master node receives a new from upstream master and uses it only when communicating with it. """ class BackupApplication(object): pt = None def __init__(self, app, name, master_addresses): self.app = weakref.proxy(app) self.name = name self.nm = NodeManager() for master_address in master_addresses: self.nm.createMaster(address=master_address) em = property(lambda self: self.app.em) ssl = property(lambda self: self.app.ssl) def close(self): self.nm.close() del self.__dict__ def log(self): self.nm.log() if self.pt is not None: self.pt.log() def provideService(self): logging.info('provide backup') poll = self.em.poll app = self.app pt = app.pt while True: app.changeClusterState(ClusterStates.STARTING_BACKUP) bootstrap = BootstrapManager(self, self.name, NodeTypes.CLIENT) # {offset -> node} self.primary_partition_dict = {} # [[tid]] self.tid_list = tuple([] for _ in xrange(pt.getPartitions())) try: while True: for node in pt.getNodeSet(readable=True): if not app.isStorageReady(node.getUUID()): break else: break poll(1) node, conn, uuid, num_partitions, num_replicas = \ bootstrap.getPrimaryConnection() try: app.changeClusterState(ClusterStates.BACKINGUP) del bootstrap, node if num_partitions != pt.getPartitions(): raise RuntimeError("inconsistent number of partitions") self.pt = PartitionTable(num_partitions, num_replicas) conn.setHandler(BackupHandler(self)) conn.ask(Packets.AskNodeInformation()) conn.ask(Packets.AskPartitionTable()) conn.ask(Packets.AskLastTransaction()) # debug variable to log how big 'tid_list' can be. self.debug_tid_count = 0 while True: poll(1) except PrimaryFailure, msg: logging.error('upstream master is down: %s', msg) finally: app.backup_tid = pt.getBackupTid() try: conn.close() except PrimaryFailure: pass try: del self.pt except AttributeError: pass except StateChangedException, e: if e.args[0] != ClusterStates.STOPPING_BACKUP: raise app.changeClusterState(*e.args) tid = app.backup_tid # Wait for non-primary partitions to catch up, # so that all UP_TO_DATE cells are really UP_TO_DATE. # XXX: Another possibility could be to outdate such cells, and # they would be quickly updated at the beginning of the # RUNNING phase. This may simplify code. # Any unfinished replication from upstream will be truncated. while pt.getBackupTid(min) < tid: poll(1) last_tid = app.getLastTransaction() handler = EventHandler(app) if tid < last_tid: assert tid != ZERO_TID logging.warning("Truncating at %s (last_tid was %s)", dump(app.backup_tid), dump(last_tid)) else: # We will do a dummy truncation, just to leave backup mode, # so it's fine to start automatically if there's any # missing storage. # XXX: Consider using another method to leave backup mode, # at least when there's nothing to truncate. Because # in case of StoppedOperation during VERIFYING state, # this flag will be wrongly set to False. app._startup_allowed = True # If any error happened before reaching this line, we'd go back # to backup mode, which is the right mode to recover. del app.backup_tid # Now back to RECOVERY... return tid finally: del self.primary_partition_dict, self.tid_list pt.clearReplicating() def nodeLost(self, node): getCellList = self.app.pt.getCellList trigger_set = set() for offset, primary_node in self.primary_partition_dict.items(): if primary_node is not node: continue cell_list = getCellList(offset, readable=True) cell = max(cell_list, key=lambda cell: cell.backup_tid) tid = cell.backup_tid self.primary_partition_dict[offset] = primary_node = cell.getNode() p = Packets.Replicate(tid, '', {offset: primary_node.getAddress()}) for cell in cell_list: cell.replicating = tid if cell.backup_tid < tid: logging.debug( "ask %s to replicate partition %u up to %s from %s", uuid_str(cell.getUUID()), offset, dump(tid), uuid_str(primary_node.getUUID())) cell.getNode().getConnection().notify(p) trigger_set.add(primary_node) for node in trigger_set: self.triggerBackup(node) def invalidatePartitions(self, tid, partition_set): app = self.app prev_tid = app.getLastTransaction() app.setLastTransaction(tid) pt = app.pt trigger_set = set() untouched_dict = defaultdict(dict) for offset in xrange(pt.getPartitions()): try: last_max_tid = self.tid_list[offset][-1] except IndexError: last_max_tid = prev_tid if offset in partition_set: self.tid_list[offset].append(tid) node_list = [] for cell in pt.getCellList(offset, readable=True): node = cell.getNode() assert node.isConnected(), node if cell.backup_tid == prev_tid: # Let's given 4 TID t0,t1,t2,t3: if a cell is only # modified by t0 & t3 and has all data for t0, 4 values # are possible for its 'backup_tid' until it replicates # up to t3: t0, t1, t2 or t3 - 1 # Choosing the smallest one (t0) is easier to implement # but when leaving backup mode, we would always lose # data if the last full transaction does not modify # all partitions. t1 is wrong for the same reason. # So we have chosen the highest one (t3 - 1). # t2 should also work but maybe harder to implement. cell.backup_tid = add64(tid, -1) logging.debug( "partition %u: updating backup_tid of %r to %s", offset, cell, dump(cell.backup_tid)) else: assert cell.backup_tid < last_max_tid, ( cell.backup_tid, last_max_tid, prev_tid, tid) if app.isStorageReady(node.getUUID()): node_list.append(node) assert node_list trigger_set.update(node_list) # Make sure we have a primary storage for this partition. if offset not in self.primary_partition_dict: self.primary_partition_dict[offset] = \ random.choice(node_list) else: # Partition not touched, so increase 'backup_tid' of all # "up-to-date" replicas, without having to replicate. for cell in pt.getCellList(offset, readable=True): if last_max_tid <= cell.backup_tid: cell.backup_tid = tid untouched_dict[cell.getNode()][offset] = None elif last_max_tid <= cell.replicating: # Same for 'replicating' to avoid useless orders. logging.debug("silently update replicating order" " of %s for partition %u, up to %s", uuid_str(cell.getUUID()), offset, dump(tid)) cell.replicating = tid for node, untouched_dict in untouched_dict.iteritems(): if app.isStorageReady(node.getUUID()): node.notify(Packets.Replicate(tid, '', untouched_dict)) for node in trigger_set: self.triggerBackup(node) count = sum(map(len, self.tid_list)) if self.debug_tid_count < count: logging.debug("Maximum number of tracked tids: %u", count) self.debug_tid_count = count def triggerBackup(self, node): tid_list = self.tid_list tid = self.app.getLastTransaction() replicate_list = [] for offset, cell in self.app.pt.iterNodeCell(node): max_tid = tid_list[offset] if max_tid and self.primary_partition_dict[offset] is node and \ max(cell.backup_tid, cell.replicating) < max_tid[-1]: cell.replicating = tid replicate_list.append(offset) if not replicate_list: return getCellList = self.pt.getCellList source_dict = {} address_set = set() for offset in replicate_list: cell_list = getCellList(offset, readable=True) random.shuffle(cell_list) assert cell_list, offset for cell in cell_list: addr = cell.getAddress() if addr in address_set: break else: address_set.add(addr) source_dict[offset] = addr logging.debug("ask %s to replicate partition %u up to %s from %r", uuid_str(node.getUUID()), offset, dump(tid), addr) node.getConnection().notify(Packets.Replicate( tid, self.name, source_dict)) def notifyReplicationDone(self, node, offset, tid): app = self.app cell = app.pt.getCell(offset, node.getUUID()) tid_list = self.tid_list[offset] if tid_list: # may be empty if the cell is out-of-date # or if we're not fully initialized if tid < tid_list[0]: cell.replicating = tid else: try: tid = add64(tid_list[bisect(tid_list, tid)], -1) except IndexError: last_tid = app.getLastTransaction() if tid < last_tid: tid = last_tid node.notify(Packets.Replicate(tid, '', {offset: None})) logging.debug("partition %u: updating backup_tid of %r to %s", offset, cell, dump(tid)) cell.backup_tid = tid # Forget tids we won't need anymore. cell_list = app.pt.getCellList(offset, readable=True) del tid_list[:bisect(tid_list, min(x.backup_tid for x in cell_list))] primary_node = self.primary_partition_dict.get(offset) primary = primary_node is node result = None if primary else app.pt.setUpToDate(node, offset) assert cell.isReadable() if result: # was out-of-date if primary_node is not None: max_tid, = [x.backup_tid for x in cell_list if x.getNode() is primary_node] if tid < max_tid: cell.replicating = max_tid logging.debug( "ask %s to replicate partition %u up to %s from %s", uuid_str(node.getUUID()), offset, dump(max_tid), uuid_str(primary_node.getUUID())) node.notify(Packets.Replicate(max_tid, '', {offset: primary_node.getAddress()})) else: if app.getClusterState() == ClusterStates.BACKINGUP: self.triggerBackup(node) if primary: # Notify secondary storages that they can replicate from # primary ones, even if they are already replicating. p = Packets.Replicate(tid, '', {offset: node.getAddress()}) for cell in cell_list: if max(cell.backup_tid, cell.replicating) < tid: cell.replicating = tid logging.debug( "ask %s to replicate partition %u up to %s from %s", uuid_str(cell.getUUID()), offset, dump(tid), uuid_str(node.getUUID())) cell.getNode().notify(p) return result
gpl-2.0
redhat-openstack/glance
glance/cmd/registry.py
1
2664
#!/usr/bin/env python # Copyright 2010 United States Government as represented by the # Administrator of the National Aeronautics and Space Administration. # 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. """ Reference implementation server for Glance Registry """ import eventlet import os import sys # Monkey patch socket and time eventlet.patcher.monkey_patch(all=False, socket=True, time=True, thread=True) # If ../glance/__init__.py exists, add ../ to Python search path, so that # it will override what happens to be installed in /usr/(local/)lib/python... possible_topdir = os.path.normpath(os.path.join(os.path.abspath(sys.argv[0]), os.pardir, os.pardir)) if os.path.exists(os.path.join(possible_topdir, 'glance', '__init__.py')): sys.path.insert(0, possible_topdir) from oslo.config import cfg import osprofiler.notifier import osprofiler.web from glance.common import config from glance.common import wsgi from glance import notifier from glance.openstack.common import log from glance.openstack.common import systemd CONF = cfg.CONF CONF.import_group("profiler", "glance.common.wsgi") def main(): try: config.parse_args() wsgi.set_eventlet_hub() log.setup('glance') if cfg.CONF.profiler.enabled: _notifier = osprofiler.notifier.create("Messaging", notifier.messaging, {}, notifier.get_transport(), "glance", "registry", cfg.CONF.bind_host) osprofiler.notifier.set(_notifier) else: osprofiler.web.disable() server = wsgi.Server() server.start(config.load_paste_app('glance-registry'), default_port=9191) systemd.notify_once() server.wait() except RuntimeError as e: sys.exit("ERROR: %s" % e) if __name__ == '__main__': main()
apache-2.0
abomyi/django
tests/file_uploads/tests.py
118
23513
#! -*- coding: utf-8 -*- from __future__ import unicode_literals import base64 import errno import hashlib import json import os import shutil import tempfile as sys_tempfile import unittest from io import BytesIO from django.core.files import temp as tempfile from django.core.files.uploadedfile import SimpleUploadedFile from django.http.multipartparser import MultiPartParser, parse_header from django.test import SimpleTestCase, TestCase, client, override_settings from django.utils.encoding import force_bytes from django.utils.http import urlquote from django.utils.six import PY2, StringIO from . import uploadhandler from .models import FileModel UNICODE_FILENAME = 'test-0123456789_中文_Orléans.jpg' MEDIA_ROOT = sys_tempfile.mkdtemp() UPLOAD_TO = os.path.join(MEDIA_ROOT, 'test_upload') @override_settings(MEDIA_ROOT=MEDIA_ROOT, ROOT_URLCONF='file_uploads.urls', MIDDLEWARE_CLASSES=[]) class FileUploadTests(TestCase): @classmethod def setUpClass(cls): super(FileUploadTests, cls).setUpClass() if not os.path.isdir(MEDIA_ROOT): os.makedirs(MEDIA_ROOT) @classmethod def tearDownClass(cls): shutil.rmtree(MEDIA_ROOT) super(FileUploadTests, cls).tearDownClass() def test_simple_upload(self): with open(__file__, 'rb') as fp: post_data = { 'name': 'Ringo', 'file_field': fp, } response = self.client.post('/upload/', post_data) self.assertEqual(response.status_code, 200) def test_large_upload(self): file = tempfile.NamedTemporaryFile with file(suffix=".file1") as file1, file(suffix=".file2") as file2: file1.write(b'a' * (2 ** 21)) file1.seek(0) file2.write(b'a' * (10 * 2 ** 20)) file2.seek(0) post_data = { 'name': 'Ringo', 'file_field1': file1, 'file_field2': file2, } for key in list(post_data): try: post_data[key + '_hash'] = hashlib.sha1(post_data[key].read()).hexdigest() post_data[key].seek(0) except AttributeError: post_data[key + '_hash'] = hashlib.sha1(force_bytes(post_data[key])).hexdigest() response = self.client.post('/verify/', post_data) self.assertEqual(response.status_code, 200) def _test_base64_upload(self, content, encode=base64.b64encode): payload = client.FakePayload("\r\n".join([ '--' + client.BOUNDARY, 'Content-Disposition: form-data; name="file"; filename="test.txt"', 'Content-Type: application/octet-stream', 'Content-Transfer-Encoding: base64', ''])) payload.write(b"\r\n" + encode(force_bytes(content)) + b"\r\n") payload.write('--' + client.BOUNDARY + '--\r\n') r = { 'CONTENT_LENGTH': len(payload), 'CONTENT_TYPE': client.MULTIPART_CONTENT, 'PATH_INFO': "/echo_content/", 'REQUEST_METHOD': 'POST', 'wsgi.input': payload, } response = self.client.request(**r) received = json.loads(response.content.decode('utf-8')) self.assertEqual(received['file'], content) def test_base64_upload(self): self._test_base64_upload("This data will be transmitted base64-encoded.") def test_big_base64_upload(self): self._test_base64_upload("Big data" * 68000) # > 512Kb def test_big_base64_newlines_upload(self): self._test_base64_upload( # encodestring is a deprecated alias on Python 3 "Big data" * 68000, encode=base64.encodestring if PY2 else base64.encodebytes) def test_unicode_file_name(self): tdir = sys_tempfile.mkdtemp() self.addCleanup(shutil.rmtree, tdir, True) # This file contains chinese symbols and an accented char in the name. with open(os.path.join(tdir, UNICODE_FILENAME), 'w+b') as file1: file1.write(b'b' * (2 ** 10)) file1.seek(0) post_data = { 'file_unicode': file1, } response = self.client.post('/unicode_name/', post_data) self.assertEqual(response.status_code, 200) def test_unicode_file_name_rfc2231(self): """ Test receiving file upload when filename is encoded with RFC2231 (#22971). """ payload = client.FakePayload() payload.write('\r\n'.join([ '--' + client.BOUNDARY, 'Content-Disposition: form-data; name="file_unicode"; filename*=UTF-8\'\'%s' % urlquote(UNICODE_FILENAME), 'Content-Type: application/octet-stream', '', 'You got pwnd.\r\n', '\r\n--' + client.BOUNDARY + '--\r\n' ])) r = { 'CONTENT_LENGTH': len(payload), 'CONTENT_TYPE': client.MULTIPART_CONTENT, 'PATH_INFO': "/unicode_name/", 'REQUEST_METHOD': 'POST', 'wsgi.input': payload, } response = self.client.request(**r) self.assertEqual(response.status_code, 200) def test_unicode_name_rfc2231(self): """ Test receiving file upload when filename is encoded with RFC2231 (#22971). """ payload = client.FakePayload() payload.write( '\r\n'.join([ '--' + client.BOUNDARY, 'Content-Disposition: form-data; name*=UTF-8\'\'file_unicode; filename*=UTF-8\'\'%s' % urlquote( UNICODE_FILENAME ), 'Content-Type: application/octet-stream', '', 'You got pwnd.\r\n', '\r\n--' + client.BOUNDARY + '--\r\n' ]) ) r = { 'CONTENT_LENGTH': len(payload), 'CONTENT_TYPE': client.MULTIPART_CONTENT, 'PATH_INFO': "/unicode_name/", 'REQUEST_METHOD': 'POST', 'wsgi.input': payload, } response = self.client.request(**r) self.assertEqual(response.status_code, 200) def test_dangerous_file_names(self): """Uploaded file names should be sanitized before ever reaching the view.""" # This test simulates possible directory traversal attacks by a # malicious uploader We have to do some monkeybusiness here to construct # a malicious payload with an invalid file name (containing os.sep or # os.pardir). This similar to what an attacker would need to do when # trying such an attack. scary_file_names = [ "/tmp/hax0rd.txt", # Absolute path, *nix-style. "C:\\Windows\\hax0rd.txt", # Absolute path, win-style. "C:/Windows/hax0rd.txt", # Absolute path, broken-style. "\\tmp\\hax0rd.txt", # Absolute path, broken in a different way. "/tmp\\hax0rd.txt", # Absolute path, broken by mixing. "subdir/hax0rd.txt", # Descendant path, *nix-style. "subdir\\hax0rd.txt", # Descendant path, win-style. "sub/dir\\hax0rd.txt", # Descendant path, mixed. "../../hax0rd.txt", # Relative path, *nix-style. "..\\..\\hax0rd.txt", # Relative path, win-style. "../..\\hax0rd.txt" # Relative path, mixed. ] payload = client.FakePayload() for i, name in enumerate(scary_file_names): payload.write('\r\n'.join([ '--' + client.BOUNDARY, 'Content-Disposition: form-data; name="file%s"; filename="%s"' % (i, name), 'Content-Type: application/octet-stream', '', 'You got pwnd.\r\n' ])) payload.write('\r\n--' + client.BOUNDARY + '--\r\n') r = { 'CONTENT_LENGTH': len(payload), 'CONTENT_TYPE': client.MULTIPART_CONTENT, 'PATH_INFO': "/echo/", 'REQUEST_METHOD': 'POST', 'wsgi.input': payload, } response = self.client.request(**r) # The filenames should have been sanitized by the time it got to the view. received = json.loads(response.content.decode('utf-8')) for i, name in enumerate(scary_file_names): got = received["file%s" % i] self.assertEqual(got, "hax0rd.txt") def test_filename_overflow(self): """File names over 256 characters (dangerous on some platforms) get fixed up.""" long_str = 'f' * 300 cases = [ # field name, filename, expected ('long_filename', '%s.txt' % long_str, '%s.txt' % long_str[:251]), ('long_extension', 'foo.%s' % long_str, '.%s' % long_str[:254]), ('no_extension', long_str, long_str[:255]), ('no_filename', '.%s' % long_str, '.%s' % long_str[:254]), ('long_everything', '%s.%s' % (long_str, long_str), '.%s' % long_str[:254]), ] payload = client.FakePayload() for name, filename, _ in cases: payload.write("\r\n".join([ '--' + client.BOUNDARY, 'Content-Disposition: form-data; name="{}"; filename="{}"', 'Content-Type: application/octet-stream', '', 'Oops.', '' ]).format(name, filename)) payload.write('\r\n--' + client.BOUNDARY + '--\r\n') r = { 'CONTENT_LENGTH': len(payload), 'CONTENT_TYPE': client.MULTIPART_CONTENT, 'PATH_INFO': "/echo/", 'REQUEST_METHOD': 'POST', 'wsgi.input': payload, } response = self.client.request(**r) result = json.loads(response.content.decode('utf-8')) for name, _, expected in cases: got = result[name] self.assertEqual(expected, got, 'Mismatch for {}'.format(name)) self.assertLess(len(got), 256, "Got a long file name (%s characters)." % len(got)) def test_file_content(self): file = tempfile.NamedTemporaryFile with file(suffix=".ctype_extra") as no_content_type, file(suffix=".ctype_extra") as simple_file: no_content_type.write(b'no content') no_content_type.seek(0) simple_file.write(b'text content') simple_file.seek(0) simple_file.content_type = 'text/plain' string_io = StringIO('string content') bytes_io = BytesIO(b'binary content') response = self.client.post('/echo_content/', { 'no_content_type': no_content_type, 'simple_file': simple_file, 'string': string_io, 'binary': bytes_io, }) received = json.loads(response.content.decode('utf-8')) self.assertEqual(received['no_content_type'], 'no content') self.assertEqual(received['simple_file'], 'text content') self.assertEqual(received['string'], 'string content') self.assertEqual(received['binary'], 'binary content') def test_content_type_extra(self): """Uploaded files may have content type parameters available.""" file = tempfile.NamedTemporaryFile with file(suffix=".ctype_extra") as no_content_type, file(suffix=".ctype_extra") as simple_file: no_content_type.write(b'something') no_content_type.seek(0) simple_file.write(b'something') simple_file.seek(0) simple_file.content_type = 'text/plain; test-key=test_value' response = self.client.post('/echo_content_type_extra/', { 'no_content_type': no_content_type, 'simple_file': simple_file, }) received = json.loads(response.content.decode('utf-8')) self.assertEqual(received['no_content_type'], {}) self.assertEqual(received['simple_file'], {'test-key': 'test_value'}) def test_truncated_multipart_handled_gracefully(self): """ If passed an incomplete multipart message, MultiPartParser does not attempt to read beyond the end of the stream, and simply will handle the part that can be parsed gracefully. """ payload_str = "\r\n".join([ '--' + client.BOUNDARY, 'Content-Disposition: form-data; name="file"; filename="foo.txt"', 'Content-Type: application/octet-stream', '', 'file contents' '--' + client.BOUNDARY + '--', '', ]) payload = client.FakePayload(payload_str[:-10]) r = { 'CONTENT_LENGTH': len(payload), 'CONTENT_TYPE': client.MULTIPART_CONTENT, 'PATH_INFO': '/echo/', 'REQUEST_METHOD': 'POST', 'wsgi.input': payload, } got = json.loads(self.client.request(**r).content.decode('utf-8')) self.assertEqual(got, {}) def test_empty_multipart_handled_gracefully(self): """ If passed an empty multipart message, MultiPartParser will return an empty QueryDict. """ r = { 'CONTENT_LENGTH': 0, 'CONTENT_TYPE': client.MULTIPART_CONTENT, 'PATH_INFO': '/echo/', 'REQUEST_METHOD': 'POST', 'wsgi.input': client.FakePayload(b''), } got = json.loads(self.client.request(**r).content.decode('utf-8')) self.assertEqual(got, {}) def test_custom_upload_handler(self): file = tempfile.NamedTemporaryFile with file() as smallfile, file() as bigfile: # A small file (under the 5M quota) smallfile.write(b'a' * (2 ** 21)) smallfile.seek(0) # A big file (over the quota) bigfile.write(b'a' * (10 * 2 ** 20)) bigfile.seek(0) # Small file posting should work. response = self.client.post('/quota/', {'f': smallfile}) got = json.loads(response.content.decode('utf-8')) self.assertIn('f', got) # Large files don't go through. response = self.client.post("/quota/", {'f': bigfile}) got = json.loads(response.content.decode('utf-8')) self.assertNotIn('f', got) def test_broken_custom_upload_handler(self): with tempfile.NamedTemporaryFile() as file: file.write(b'a' * (2 ** 21)) file.seek(0) # AttributeError: You cannot alter upload handlers after the upload has been processed. self.assertRaises( AttributeError, self.client.post, '/quota/broken/', {'f': file} ) def test_fileupload_getlist(self): file = tempfile.NamedTemporaryFile with file() as file1, file() as file2, file() as file2a: file1.write(b'a' * (2 ** 23)) file1.seek(0) file2.write(b'a' * (2 * 2 ** 18)) file2.seek(0) file2a.write(b'a' * (5 * 2 ** 20)) file2a.seek(0) response = self.client.post('/getlist_count/', { 'file1': file1, 'field1': 'test', 'field2': 'test3', 'field3': 'test5', 'field4': 'test6', 'field5': 'test7', 'file2': (file2, file2a) }) got = json.loads(response.content.decode('utf-8')) self.assertEqual(got.get('file1'), 1) self.assertEqual(got.get('file2'), 2) def test_fileuploads_closed_at_request_end(self): file = tempfile.NamedTemporaryFile with file() as f1, file() as f2a, file() as f2b: response = self.client.post('/fd_closing/t/', { 'file': f1, 'file2': (f2a, f2b), }) request = response.wsgi_request # Check that the files got actually parsed. self.assertTrue(hasattr(request, '_files')) file = request._files['file'] self.assertTrue(file.closed) files = request._files.getlist('file2') self.assertTrue(files[0].closed) self.assertTrue(files[1].closed) def test_no_parsing_triggered_by_fd_closing(self): file = tempfile.NamedTemporaryFile with file() as f1, file() as f2a, file() as f2b: response = self.client.post('/fd_closing/f/', { 'file': f1, 'file2': (f2a, f2b), }) request = response.wsgi_request # Check that the fd closing logic doesn't trigger parsing of the stream self.assertFalse(hasattr(request, '_files')) def test_file_error_blocking(self): """ The server should not block when there are upload errors (bug #8622). This can happen if something -- i.e. an exception handler -- tries to access POST while handling an error in parsing POST. This shouldn't cause an infinite loop! """ class POSTAccessingHandler(client.ClientHandler): """A handler that'll access POST during an exception.""" def handle_uncaught_exception(self, request, resolver, exc_info): ret = super(POSTAccessingHandler, self).handle_uncaught_exception(request, resolver, exc_info) request.POST # evaluate return ret # Maybe this is a little more complicated that it needs to be; but if # the django.test.client.FakePayload.read() implementation changes then # this test would fail. So we need to know exactly what kind of error # it raises when there is an attempt to read more than the available bytes: try: client.FakePayload(b'a').read(2) except Exception as err: reference_error = err # install the custom handler that tries to access request.POST self.client.handler = POSTAccessingHandler() with open(__file__, 'rb') as fp: post_data = { 'name': 'Ringo', 'file_field': fp, } try: self.client.post('/upload_errors/', post_data) except reference_error.__class__ as err: self.assertFalse( str(err) == str(reference_error), "Caught a repeated exception that'll cause an infinite loop in file uploads." ) except Exception as err: # CustomUploadError is the error that should have been raised self.assertEqual(err.__class__, uploadhandler.CustomUploadError) def test_filename_case_preservation(self): """ The storage backend shouldn't mess with the case of the filenames uploaded. """ # Synthesize the contents of a file upload with a mixed case filename # so we don't have to carry such a file in the Django tests source code # tree. vars = {'boundary': 'oUrBoUnDaRyStRiNg'} post_data = [ '--%(boundary)s', 'Content-Disposition: form-data; name="file_field"; filename="MiXeD_cAsE.txt"', 'Content-Type: application/octet-stream', '', 'file contents\n' '', '--%(boundary)s--\r\n', ] response = self.client.post( '/filename_case/', '\r\n'.join(post_data) % vars, 'multipart/form-data; boundary=%(boundary)s' % vars ) self.assertEqual(response.status_code, 200) id = int(response.content) obj = FileModel.objects.get(pk=id) # The name of the file uploaded and the file stored in the server-side # shouldn't differ. self.assertEqual(os.path.basename(obj.testfile.path), 'MiXeD_cAsE.txt') @override_settings(MEDIA_ROOT=MEDIA_ROOT) class DirectoryCreationTests(SimpleTestCase): """ Tests for error handling during directory creation via _save_FIELD_file (ticket #6450) """ @classmethod def setUpClass(cls): super(DirectoryCreationTests, cls).setUpClass() if not os.path.isdir(MEDIA_ROOT): os.makedirs(MEDIA_ROOT) @classmethod def tearDownClass(cls): shutil.rmtree(MEDIA_ROOT) super(DirectoryCreationTests, cls).tearDownClass() def setUp(self): self.obj = FileModel() def test_readonly_root(self): """Permission errors are not swallowed""" os.chmod(MEDIA_ROOT, 0o500) self.addCleanup(os.chmod, MEDIA_ROOT, 0o700) try: self.obj.testfile.save('foo.txt', SimpleUploadedFile('foo.txt', b'x'), save=False) except OSError as err: self.assertEqual(err.errno, errno.EACCES) except Exception: self.fail("OSError [Errno %s] not raised." % errno.EACCES) def test_not_a_directory(self): """The correct IOError is raised when the upload directory name exists but isn't a directory""" # Create a file with the upload directory name open(UPLOAD_TO, 'wb').close() self.addCleanup(os.remove, UPLOAD_TO) with self.assertRaises(IOError) as exc_info: with SimpleUploadedFile('foo.txt', b'x') as file: self.obj.testfile.save('foo.txt', file, save=False) # The test needs to be done on a specific string as IOError # is raised even without the patch (just not early enough) self.assertEqual(exc_info.exception.args[0], "%s exists and is not a directory." % UPLOAD_TO) class MultiParserTests(unittest.TestCase): def test_empty_upload_handlers(self): # We're not actually parsing here; just checking if the parser properly # instantiates with empty upload handlers. MultiPartParser({ 'CONTENT_TYPE': 'multipart/form-data; boundary=_foo', 'CONTENT_LENGTH': '1' }, StringIO('x'), [], 'utf-8') def test_rfc2231_parsing(self): test_data = ( (b"Content-Type: application/x-stuff; title*=us-ascii'en-us'This%20is%20%2A%2A%2Afun%2A%2A%2A", "This is ***fun***"), (b"Content-Type: application/x-stuff; title*=UTF-8''foo-%c3%a4.html", "foo-ä.html"), (b"Content-Type: application/x-stuff; title*=iso-8859-1''foo-%E4.html", "foo-ä.html"), ) for raw_line, expected_title in test_data: parsed = parse_header(raw_line) self.assertEqual(parsed[1]['title'], expected_title) def test_rfc2231_wrong_title(self): """ Test wrongly formatted RFC 2231 headers (missing double single quotes). Parsing should not crash (#24209). """ test_data = ( (b"Content-Type: application/x-stuff; title*='This%20is%20%2A%2A%2Afun%2A%2A%2A", b"'This%20is%20%2A%2A%2Afun%2A%2A%2A"), (b"Content-Type: application/x-stuff; title*='foo.html", b"'foo.html"), (b"Content-Type: application/x-stuff; title*=bar.html", b"bar.html"), ) for raw_line, expected_title in test_data: parsed = parse_header(raw_line) self.assertEqual(parsed[1]['title'], expected_title)
bsd-3-clause
askeing/servo
tests/wpt/web-platform-tests/webdriver/tests/element_send_keys/form_controls.py
3
3067
import pytest from tests.support.asserts import assert_error, assert_same_element, assert_success from tests.support.inline import inline def element_send_keys(session, element, text): return session.transport.send( "POST", "/session/{session_id}/element/{element_id}/value".format( session_id=session.session_id, element_id=element.id), {"text": text}) def add_event_listeners(element): element.session.execute_script(""" let [target] = arguments; window.events = []; for (let expected of ["focus", "blur", "change", "keypress", "keydown", "keyup", "input"]) { target.addEventListener(expected, ({type}) => window.events.push(type)); } """, args=(element,)) def get_events(session): return session.execute_script("return window.events") def test_input(session): session.url = inline("<input>") element = session.find.css("input", all=False) assert element.property("value") == "" element_send_keys(session, element, "foo") assert element.property("value") == "foo" def test_textarea(session): session.url = inline("<textarea>") element = session.find.css("textarea", all=False) assert element.property("value") == "" element_send_keys(session, element, "foo") assert element.property("value") == "foo" def test_input_append(session): session.url = inline("<input value=a>") element = session.find.css("input", all=False) assert element.property("value") == "a" element_send_keys(session, element, "b") assert element.property("value") == "ab" element_send_keys(session, element, "c") assert element.property("value") == "abc" def test_textarea_append(session): session.url = inline("<textarea>a</textarea>") element = session.find.css("textarea", all=False) assert element.property("value") == "a" element_send_keys(session, element, "b") assert element.property("value") == "ab" element_send_keys(session, element, "c") assert element.property("value") == "abc" @pytest.mark.parametrize("tag", ["input", "textarea"]) def test_events(session, tag): session.url = inline("<%s>" % tag) element = session.find.css(tag, all=False) add_event_listeners(element) element_send_keys(session, element, "foo") assert element.property("value") == "foo" assert get_events(session) == ["focus", "keydown", "keypress", "input", "keyup", "keydown", "keypress", "input", "keyup", "keydown", "keypress", "input", "keyup", "change", "blur"]
mpl-2.0
WarrenWeckesser/numpy
numpy/core/tests/test_records.py
6
19694
import collections.abc import textwrap from os import path from pathlib import Path import pytest import numpy as np from numpy.testing import ( assert_, assert_equal, assert_array_equal, assert_array_almost_equal, assert_raises, temppath, ) from numpy.compat import pickle class TestFromrecords: def test_fromrecords(self): r = np.rec.fromrecords([[456, 'dbe', 1.2], [2, 'de', 1.3]], names='col1,col2,col3') assert_equal(r[0].item(), (456, 'dbe', 1.2)) assert_equal(r['col1'].dtype.kind, 'i') assert_equal(r['col2'].dtype.kind, 'U') assert_equal(r['col2'].dtype.itemsize, 12) assert_equal(r['col3'].dtype.kind, 'f') def test_fromrecords_0len(self): """ Verify fromrecords works with a 0-length input """ dtype = [('a', float), ('b', float)] r = np.rec.fromrecords([], dtype=dtype) assert_equal(r.shape, (0,)) def test_fromrecords_2d(self): data = [ [(1, 2), (3, 4), (5, 6)], [(6, 5), (4, 3), (2, 1)] ] expected_a = [[1, 3, 5], [6, 4, 2]] expected_b = [[2, 4, 6], [5, 3, 1]] # try with dtype r1 = np.rec.fromrecords(data, dtype=[('a', int), ('b', int)]) assert_equal(r1['a'], expected_a) assert_equal(r1['b'], expected_b) # try with names r2 = np.rec.fromrecords(data, names=['a', 'b']) assert_equal(r2['a'], expected_a) assert_equal(r2['b'], expected_b) assert_equal(r1, r2) def test_method_array(self): r = np.rec.array(b'abcdefg' * 100, formats='i2,a3,i4', shape=3, byteorder='big') assert_equal(r[1].item(), (25444, b'efg', 1633837924)) def test_method_array2(self): r = np.rec.array([(1, 11, 'a'), (2, 22, 'b'), (3, 33, 'c'), (4, 44, 'd'), (5, 55, 'ex'), (6, 66, 'f'), (7, 77, 'g')], formats='u1,f4,a1') assert_equal(r[1].item(), (2, 22.0, b'b')) def test_recarray_slices(self): r = np.rec.array([(1, 11, 'a'), (2, 22, 'b'), (3, 33, 'c'), (4, 44, 'd'), (5, 55, 'ex'), (6, 66, 'f'), (7, 77, 'g')], formats='u1,f4,a1') assert_equal(r[1::2][1].item(), (4, 44.0, b'd')) def test_recarray_fromarrays(self): x1 = np.array([1, 2, 3, 4]) x2 = np.array(['a', 'dd', 'xyz', '12']) x3 = np.array([1.1, 2, 3, 4]) r = np.rec.fromarrays([x1, x2, x3], names='a,b,c') assert_equal(r[1].item(), (2, 'dd', 2.0)) x1[1] = 34 assert_equal(r.a, np.array([1, 2, 3, 4])) def test_recarray_fromfile(self): data_dir = path.join(path.dirname(__file__), 'data') filename = path.join(data_dir, 'recarray_from_file.fits') fd = open(filename, 'rb') fd.seek(2880 * 2) r1 = np.rec.fromfile(fd, formats='f8,i4,a5', shape=3, byteorder='big') fd.seek(2880 * 2) r2 = np.rec.array(fd, formats='f8,i4,a5', shape=3, byteorder='big') fd.close() assert_equal(r1, r2) def test_recarray_from_obj(self): count = 10 a = np.zeros(count, dtype='O') b = np.zeros(count, dtype='f8') c = np.zeros(count, dtype='f8') for i in range(len(a)): a[i] = list(range(1, 10)) mine = np.rec.fromarrays([a, b, c], names='date,data1,data2') for i in range(len(a)): assert_((mine.date[i] == list(range(1, 10)))) assert_((mine.data1[i] == 0.0)) assert_((mine.data2[i] == 0.0)) def test_recarray_repr(self): a = np.array([(1, 0.1), (2, 0.2)], dtype=[('foo', '<i4'), ('bar', '<f8')]) a = np.rec.array(a) assert_equal( repr(a), textwrap.dedent("""\ rec.array([(1, 0.1), (2, 0.2)], dtype=[('foo', '<i4'), ('bar', '<f8')])""") ) # make sure non-structured dtypes also show up as rec.array a = np.array(np.ones(4, dtype='f8')) assert_(repr(np.rec.array(a)).startswith('rec.array')) # check that the 'np.record' part of the dtype isn't shown a = np.rec.array(np.ones(3, dtype='i4,i4')) assert_equal(repr(a).find('numpy.record'), -1) a = np.rec.array(np.ones(3, dtype='i4')) assert_(repr(a).find('dtype=int32') != -1) def test_0d_recarray_repr(self): arr_0d = np.rec.array((1, 2.0, '2003'), dtype='<i4,<f8,<M8[Y]') assert_equal(repr(arr_0d), textwrap.dedent("""\ rec.array((1, 2., '2003'), dtype=[('f0', '<i4'), ('f1', '<f8'), ('f2', '<M8[Y]')])""")) record = arr_0d[()] assert_equal(repr(record), "(1, 2., '2003')") # 1.13 converted to python scalars before the repr try: np.set_printoptions(legacy='1.13') assert_equal(repr(record), '(1, 2.0, datetime.date(2003, 1, 1))') finally: np.set_printoptions(legacy=False) def test_recarray_from_repr(self): a = np.array([(1,'ABC'), (2, "DEF")], dtype=[('foo', int), ('bar', 'S4')]) recordarr = np.rec.array(a) recarr = a.view(np.recarray) recordview = a.view(np.dtype((np.record, a.dtype))) recordarr_r = eval("numpy." + repr(recordarr), {'numpy': np}) recarr_r = eval("numpy." + repr(recarr), {'numpy': np}) recordview_r = eval("numpy." + repr(recordview), {'numpy': np}) assert_equal(type(recordarr_r), np.recarray) assert_equal(recordarr_r.dtype.type, np.record) assert_equal(recordarr, recordarr_r) assert_equal(type(recarr_r), np.recarray) assert_equal(recarr_r.dtype.type, np.record) assert_equal(recarr, recarr_r) assert_equal(type(recordview_r), np.ndarray) assert_equal(recordview.dtype.type, np.record) assert_equal(recordview, recordview_r) def test_recarray_views(self): a = np.array([(1,'ABC'), (2, "DEF")], dtype=[('foo', int), ('bar', 'S4')]) b = np.array([1,2,3,4,5], dtype=np.int64) #check that np.rec.array gives right dtypes assert_equal(np.rec.array(a).dtype.type, np.record) assert_equal(type(np.rec.array(a)), np.recarray) assert_equal(np.rec.array(b).dtype.type, np.int64) assert_equal(type(np.rec.array(b)), np.recarray) #check that viewing as recarray does the same assert_equal(a.view(np.recarray).dtype.type, np.record) assert_equal(type(a.view(np.recarray)), np.recarray) assert_equal(b.view(np.recarray).dtype.type, np.int64) assert_equal(type(b.view(np.recarray)), np.recarray) #check that view to non-structured dtype preserves type=np.recarray r = np.rec.array(np.ones(4, dtype="f4,i4")) rv = r.view('f8').view('f4,i4') assert_equal(type(rv), np.recarray) assert_equal(rv.dtype.type, np.record) #check that getitem also preserves np.recarray and np.record r = np.rec.array(np.ones(4, dtype=[('a', 'i4'), ('b', 'i4'), ('c', 'i4,i4')])) assert_equal(r['c'].dtype.type, np.record) assert_equal(type(r['c']), np.recarray) #and that it preserves subclasses (gh-6949) class C(np.recarray): pass c = r.view(C) assert_equal(type(c['c']), C) # check that accessing nested structures keep record type, but # not for subarrays, non-void structures, non-structured voids test_dtype = [('a', 'f4,f4'), ('b', 'V8'), ('c', ('f4',2)), ('d', ('i8', 'i4,i4'))] r = np.rec.array([((1,1), b'11111111', [1,1], 1), ((1,1), b'11111111', [1,1], 1)], dtype=test_dtype) assert_equal(r.a.dtype.type, np.record) assert_equal(r.b.dtype.type, np.void) assert_equal(r.c.dtype.type, np.float32) assert_equal(r.d.dtype.type, np.int64) # check the same, but for views r = np.rec.array(np.ones(4, dtype='i4,i4')) assert_equal(r.view('f4,f4').dtype.type, np.record) assert_equal(r.view(('i4',2)).dtype.type, np.int32) assert_equal(r.view('V8').dtype.type, np.void) assert_equal(r.view(('i8', 'i4,i4')).dtype.type, np.int64) #check that we can undo the view arrs = [np.ones(4, dtype='f4,i4'), np.ones(4, dtype='f8')] for arr in arrs: rec = np.rec.array(arr) # recommended way to view as an ndarray: arr2 = rec.view(rec.dtype.fields or rec.dtype, np.ndarray) assert_equal(arr2.dtype.type, arr.dtype.type) assert_equal(type(arr2), type(arr)) def test_recarray_from_names(self): ra = np.rec.array([ (1, 'abc', 3.7000002861022949, 0), (2, 'xy', 6.6999998092651367, 1), (0, ' ', 0.40000000596046448, 0)], names='c1, c2, c3, c4') pa = np.rec.fromrecords([ (1, 'abc', 3.7000002861022949, 0), (2, 'xy', 6.6999998092651367, 1), (0, ' ', 0.40000000596046448, 0)], names='c1, c2, c3, c4') assert_(ra.dtype == pa.dtype) assert_(ra.shape == pa.shape) for k in range(len(ra)): assert_(ra[k].item() == pa[k].item()) def test_recarray_conflict_fields(self): ra = np.rec.array([(1, 'abc', 2.3), (2, 'xyz', 4.2), (3, 'wrs', 1.3)], names='field, shape, mean') ra.mean = [1.1, 2.2, 3.3] assert_array_almost_equal(ra['mean'], [1.1, 2.2, 3.3]) assert_(type(ra.mean) is type(ra.var)) ra.shape = (1, 3) assert_(ra.shape == (1, 3)) ra.shape = ['A', 'B', 'C'] assert_array_equal(ra['shape'], [['A', 'B', 'C']]) ra.field = 5 assert_array_equal(ra['field'], [[5, 5, 5]]) assert_(isinstance(ra.field, collections.abc.Callable)) def test_fromrecords_with_explicit_dtype(self): a = np.rec.fromrecords([(1, 'a'), (2, 'bbb')], dtype=[('a', int), ('b', object)]) assert_equal(a.a, [1, 2]) assert_equal(a[0].a, 1) assert_equal(a.b, ['a', 'bbb']) assert_equal(a[-1].b, 'bbb') # ndtype = np.dtype([('a', int), ('b', object)]) a = np.rec.fromrecords([(1, 'a'), (2, 'bbb')], dtype=ndtype) assert_equal(a.a, [1, 2]) assert_equal(a[0].a, 1) assert_equal(a.b, ['a', 'bbb']) assert_equal(a[-1].b, 'bbb') def test_recarray_stringtypes(self): # Issue #3993 a = np.array([('abc ', 1), ('abc', 2)], dtype=[('foo', 'S4'), ('bar', int)]) a = a.view(np.recarray) assert_equal(a.foo[0] == a.foo[1], False) def test_recarray_returntypes(self): qux_fields = {'C': (np.dtype('S5'), 0), 'D': (np.dtype('S5'), 6)} a = np.rec.array([('abc ', (1,1), 1, ('abcde', 'fgehi')), ('abc', (2,3), 1, ('abcde', 'jklmn'))], dtype=[('foo', 'S4'), ('bar', [('A', int), ('B', int)]), ('baz', int), ('qux', qux_fields)]) assert_equal(type(a.foo), np.ndarray) assert_equal(type(a['foo']), np.ndarray) assert_equal(type(a.bar), np.recarray) assert_equal(type(a['bar']), np.recarray) assert_equal(a.bar.dtype.type, np.record) assert_equal(type(a['qux']), np.recarray) assert_equal(a.qux.dtype.type, np.record) assert_equal(dict(a.qux.dtype.fields), qux_fields) assert_equal(type(a.baz), np.ndarray) assert_equal(type(a['baz']), np.ndarray) assert_equal(type(a[0].bar), np.record) assert_equal(type(a[0]['bar']), np.record) assert_equal(a[0].bar.A, 1) assert_equal(a[0].bar['A'], 1) assert_equal(a[0]['bar'].A, 1) assert_equal(a[0]['bar']['A'], 1) assert_equal(a[0].qux.D, b'fgehi') assert_equal(a[0].qux['D'], b'fgehi') assert_equal(a[0]['qux'].D, b'fgehi') assert_equal(a[0]['qux']['D'], b'fgehi') def test_zero_width_strings(self): # Test for #6430, based on the test case from #1901 cols = [['test'] * 3, [''] * 3] rec = np.rec.fromarrays(cols) assert_equal(rec['f0'], ['test', 'test', 'test']) assert_equal(rec['f1'], ['', '', '']) dt = np.dtype([('f0', '|S4'), ('f1', '|S')]) rec = np.rec.fromarrays(cols, dtype=dt) assert_equal(rec.itemsize, 4) assert_equal(rec['f0'], [b'test', b'test', b'test']) assert_equal(rec['f1'], [b'', b'', b'']) class TestPathUsage: # Test that pathlib.Path can be used def test_tofile_fromfile(self): with temppath(suffix='.bin') as path: path = Path(path) np.random.seed(123) a = np.random.rand(10).astype('f8,i4,a5') a[5] = (0.5,10,'abcde') with path.open("wb") as fd: a.tofile(fd) x = np.core.records.fromfile(path, formats='f8,i4,a5', shape=10) assert_array_equal(x, a) class TestRecord: def setup(self): self.data = np.rec.fromrecords([(1, 2, 3), (4, 5, 6)], dtype=[("col1", "<i4"), ("col2", "<i4"), ("col3", "<i4")]) def test_assignment1(self): a = self.data assert_equal(a.col1[0], 1) a[0].col1 = 0 assert_equal(a.col1[0], 0) def test_assignment2(self): a = self.data assert_equal(a.col1[0], 1) a.col1[0] = 0 assert_equal(a.col1[0], 0) def test_invalid_assignment(self): a = self.data def assign_invalid_column(x): x[0].col5 = 1 assert_raises(AttributeError, assign_invalid_column, a) def test_nonwriteable_setfield(self): # gh-8171 r = np.rec.array([(0,), (1,)], dtype=[('f', 'i4')]) r.flags.writeable = False with assert_raises(ValueError): r.f = [2, 3] with assert_raises(ValueError): r.setfield([2,3], *r.dtype.fields['f']) def test_out_of_order_fields(self): # names in the same order, padding added to descr x = self.data[['col1', 'col2']] assert_equal(x.dtype.names, ('col1', 'col2')) assert_equal(x.dtype.descr, [('col1', '<i4'), ('col2', '<i4'), ('', '|V4')]) # names change order to match indexing, as of 1.14 - descr can't # represent that y = self.data[['col2', 'col1']] assert_equal(y.dtype.names, ('col2', 'col1')) assert_raises(ValueError, lambda: y.dtype.descr) def test_pickle_1(self): # Issue #1529 a = np.array([(1, [])], dtype=[('a', np.int32), ('b', np.int32, 0)]) for proto in range(2, pickle.HIGHEST_PROTOCOL + 1): assert_equal(a, pickle.loads(pickle.dumps(a, protocol=proto))) assert_equal(a[0], pickle.loads(pickle.dumps(a[0], protocol=proto))) def test_pickle_2(self): a = self.data for proto in range(2, pickle.HIGHEST_PROTOCOL + 1): assert_equal(a, pickle.loads(pickle.dumps(a, protocol=proto))) assert_equal(a[0], pickle.loads(pickle.dumps(a[0], protocol=proto))) def test_pickle_3(self): # Issue #7140 a = self.data for proto in range(2, pickle.HIGHEST_PROTOCOL + 1): pa = pickle.loads(pickle.dumps(a[0], protocol=proto)) assert_(pa.flags.c_contiguous) assert_(pa.flags.f_contiguous) assert_(pa.flags.writeable) assert_(pa.flags.aligned) def test_pickle_void(self): # issue gh-13593 dt = np.dtype([('obj', 'O'), ('int', 'i')]) a = np.empty(1, dtype=dt) data = (bytearray(b'eman'),) a['obj'] = data a['int'] = 42 ctor, args = a[0].__reduce__() # check the constructor is what we expect before interpreting the arguments assert ctor is np.core.multiarray.scalar dtype, obj = args # make sure we did not pickle the address assert not isinstance(obj, bytes) assert_raises(TypeError, ctor, dtype, 13) def test_objview_record(self): # https://github.com/numpy/numpy/issues/2599 dt = np.dtype([('foo', 'i8'), ('bar', 'O')]) r = np.zeros((1,3), dtype=dt).view(np.recarray) r.foo = np.array([1, 2, 3]) # TypeError? # https://github.com/numpy/numpy/issues/3256 ra = np.recarray((2,), dtype=[('x', object), ('y', float), ('z', int)]) ra[['x','y']] # TypeError? def test_record_scalar_setitem(self): # https://github.com/numpy/numpy/issues/3561 rec = np.recarray(1, dtype=[('x', float, 5)]) rec[0].x = 1 assert_equal(rec[0].x, np.ones(5)) def test_missing_field(self): # https://github.com/numpy/numpy/issues/4806 arr = np.zeros((3,), dtype=[('x', int), ('y', int)]) assert_raises(KeyError, lambda: arr[['nofield']]) def test_fromarrays_nested_structured_arrays(self): arrays = [ np.arange(10), np.ones(10, dtype=[('a', '<u2'), ('b', '<f4')]), ] arr = np.rec.fromarrays(arrays) # ValueError? @pytest.mark.parametrize('nfields', [0, 1, 2]) def test_assign_dtype_attribute(self, nfields): dt = np.dtype([('a', np.uint8), ('b', np.uint8), ('c', np.uint8)][:nfields]) data = np.zeros(3, dt).view(np.recarray) # the original and resulting dtypes differ on whether they are records assert data.dtype.type == np.record assert dt.type != np.record # ensure that the dtype remains a record even when assigned data.dtype = dt assert data.dtype.type == np.record @pytest.mark.parametrize('nfields', [0, 1, 2]) def test_nested_fields_are_records(self, nfields): """ Test that nested structured types are treated as records too """ dt = np.dtype([('a', np.uint8), ('b', np.uint8), ('c', np.uint8)][:nfields]) dt_outer = np.dtype([('inner', dt)]) data = np.zeros(3, dt_outer).view(np.recarray) assert isinstance(data, np.recarray) assert isinstance(data['inner'], np.recarray) data0 = data[0] assert isinstance(data0, np.record) assert isinstance(data0['inner'], np.record) def test_nested_dtype_padding(self): """ test that trailing padding is preserved """ # construct a dtype with padding at the end dt = np.dtype([('a', np.uint8), ('b', np.uint8), ('c', np.uint8)]) dt_padded_end = dt[['a', 'b']] assert dt_padded_end.itemsize == dt.itemsize dt_outer = np.dtype([('inner', dt_padded_end)]) data = np.zeros(3, dt_outer).view(np.recarray) assert_equal(data['inner'].dtype, dt_padded_end) data0 = data[0] assert_equal(data0['inner'].dtype, dt_padded_end) def test_find_duplicate(): l1 = [1, 2, 3, 4, 5, 6] assert_(np.rec.find_duplicate(l1) == []) l2 = [1, 2, 1, 4, 5, 6] assert_(np.rec.find_duplicate(l2) == [1]) l3 = [1, 2, 1, 4, 1, 6, 2, 3] assert_(np.rec.find_duplicate(l3) == [1, 2]) l3 = [2, 2, 1, 4, 1, 6, 2, 3] assert_(np.rec.find_duplicate(l3) == [2, 1])
bsd-3-clause
mapr/hue
desktop/core/ext-py/Django-1.6.10/django/shortcuts/__init__.py
116
5748
""" This module collects helper functions and classes that "span" multiple levels of MVC. In other words, these functions/classes introduce controlled coupling for convenience's sake. """ import warnings from django.template import loader, RequestContext from django.http import HttpResponse, Http404 from django.http import HttpResponseRedirect, HttpResponsePermanentRedirect from django.db.models.base import ModelBase from django.db.models.manager import Manager from django.db.models.query import QuerySet from django.core import urlresolvers def render_to_response(*args, **kwargs): """ Returns a HttpResponse whose content is filled with the result of calling django.template.loader.render_to_string() with the passed arguments. """ httpresponse_kwargs = {'content_type': kwargs.pop('content_type', None)} mimetype = kwargs.pop('mimetype', None) if mimetype: warnings.warn("The mimetype keyword argument is deprecated, use " "content_type instead", DeprecationWarning, stacklevel=2) httpresponse_kwargs['content_type'] = mimetype return HttpResponse(loader.render_to_string(*args, **kwargs), **httpresponse_kwargs) def render(request, *args, **kwargs): """ Returns a HttpResponse whose content is filled with the result of calling django.template.loader.render_to_string() with the passed arguments. Uses a RequestContext by default. """ httpresponse_kwargs = { 'content_type': kwargs.pop('content_type', None), 'status': kwargs.pop('status', None), } if 'context_instance' in kwargs: context_instance = kwargs.pop('context_instance') if kwargs.get('current_app', None): raise ValueError('If you provide a context_instance you must ' 'set its current_app before calling render()') else: current_app = kwargs.pop('current_app', None) context_instance = RequestContext(request, current_app=current_app) kwargs['context_instance'] = context_instance return HttpResponse(loader.render_to_string(*args, **kwargs), **httpresponse_kwargs) def redirect(to, *args, **kwargs): """ Returns an HttpResponseRedirect to the appropriate URL for the arguments passed. The arguments could be: * A model: the model's `get_absolute_url()` function will be called. * A view name, possibly with arguments: `urlresolvers.reverse()` will be used to reverse-resolve the name. * A URL, which will be used as-is for the redirect location. By default issues a temporary redirect; pass permanent=True to issue a permanent redirect """ if kwargs.pop('permanent', False): redirect_class = HttpResponsePermanentRedirect else: redirect_class = HttpResponseRedirect return redirect_class(resolve_url(to, *args, **kwargs)) def _get_queryset(klass): """ Returns a QuerySet from a Model, Manager, or QuerySet. Created to make get_object_or_404 and get_list_or_404 more DRY. Raises a ValueError if klass is not a Model, Manager, or QuerySet. """ if isinstance(klass, QuerySet): return klass elif isinstance(klass, Manager): manager = klass elif isinstance(klass, ModelBase): manager = klass._default_manager else: klass__name = klass.__name__ if isinstance(klass, type) \ else klass.__class__.__name__ raise ValueError("Object is of type '%s', but must be a Django Model, " "Manager, or QuerySet" % klass__name) return manager.all() def get_object_or_404(klass, *args, **kwargs): """ Uses get() to return an object, or raises a Http404 exception if the object does not exist. klass may be a Model, Manager, or QuerySet object. All other passed arguments and keyword arguments are used in the get() query. Note: Like with get(), an MultipleObjectsReturned will be raised if more than one object is found. """ queryset = _get_queryset(klass) try: return queryset.get(*args, **kwargs) except queryset.model.DoesNotExist: raise Http404('No %s matches the given query.' % queryset.model._meta.object_name) def get_list_or_404(klass, *args, **kwargs): """ Uses filter() to return a list of objects, or raise a Http404 exception if the list is empty. klass may be a Model, Manager, or QuerySet object. All other passed arguments and keyword arguments are used in the filter() query. """ queryset = _get_queryset(klass) obj_list = list(queryset.filter(*args, **kwargs)) if not obj_list: raise Http404('No %s matches the given query.' % queryset.model._meta.object_name) return obj_list def resolve_url(to, *args, **kwargs): """ Return a URL appropriate for the arguments passed. The arguments could be: * A model: the model's `get_absolute_url()` function will be called. * A view name, possibly with arguments: `urlresolvers.reverse()` will be used to reverse-resolve the name. * A URL, which will be returned as-is. """ # If it's a model, use get_absolute_url() if hasattr(to, 'get_absolute_url'): return to.get_absolute_url() # Next try a reverse URL resolution. try: return urlresolvers.reverse(to, args=args, kwargs=kwargs) except urlresolvers.NoReverseMatch: # If this is a callable, re-raise. if callable(to): raise # If this doesn't "feel" like a URL, re-raise. if '/' not in to and '.' not in to: raise # Finally, fall back and assume it's a URL return to
apache-2.0
noba3/KoTos
lib/libUPnP/Platinum/Build/Tools/Scripts/XCodeMake.py
262
2126
#! /usr/bin/env python """ XCode Build Script $Id: XCodeMake.py 655 2010-09-29 22:40:22Z soothe $ """ import os import sys import getopt import subprocess # ------------------------------------------------------------ # usage # ------------------------------------------------------------ def usage(errMsg): try: print 'Error: %s' % (errMsg) except NameError: pass print 'Usage: ' print ' %s -p <path to project> -b [Release|Debug|etc.] -t [All|Platinum|PlatinumFramework|etc.] -s [macosx|iphoneos]' % (sys.argv[0]) print '' print ' REQUIRED OPTIONS' print '\t-p <project>' print '\t-b <configuration>' print '\t-t <target>' print '\t-s <sdk>' print '' print ' BUILD OPTIONS' print '\t-c\tMake clean' # ------------------------------------------------------------ # main # ------------------------------------------------------------ try: opts, args = getopt.getopt(sys.argv[1:], "p:b:t:s:c") except getopt.GetoptError, (msg, opt): # print 'Error: invalid argument, %s: %s' % (opt, msg) usage('invalid argument, %s: %s' % (opt, msg)) sys.exit(2) # Build options doingBuild = False rebuildAll = False makeClean = False for opt, arg in opts: if opt == '-p': projectFile = arg doingBuild = True elif opt == '-b': buildName = arg doingBuild = True elif opt == '-t': targetName = arg elif opt == '-s': sdk = arg elif opt == '-c': makeClean = True try: buildSwitch = 'build' if makeClean: buildSwitch = 'clean' cmd_list = ['xcodebuild', '-project', '%s' % projectFile, '-target', '%s' % targetName, '-sdk', '%s' % sdk, '-configuration', '%s' % buildName, '%s' % buildSwitch] cmd = " ".join(cmd_list) print 'Executing:' print cmd retVal = subprocess.call(cmd_list) # only the least sig 8 bits are the real return value if retVal != 0: print cmd print '** BUILD FAILURE **' sys.exit(retVal) except NameError, (name): usage('missing argument %s' % (name)) sys.exit(2)
gpl-2.0
nolanliou/tensorflow
tensorflow/python/saved_model/tag_constants.py
7
1608
# 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. # ============================================================================== """Common tags used for graphs in SavedModel. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow.python.util.all_util import remove_undocumented from tensorflow.python.util.tf_export import tf_export # Tag for the `serving` graph. SERVING = "serve" tf_export("saved_model.tag_constants.SERVING").export_constant( __name__, "SERVING") # Tag for the `training` graph. TRAINING = "train" tf_export("saved_model.tag_constants.TRAINING").export_constant( __name__, "TRAINING") # Tag for the `gpu` graph. GPU = "gpu" tf_export("saved_model.tag_constants.GPU").export_constant(__name__, "GPU") # Tag for the `tpu` graph. TPU = "tpu" tf_export("saved_model.tag_constants.TPU").export_constant(__name__, "TPU") _allowed_symbols = [ "SERVING", "TRAINING", "GPU", "TPU" ] remove_undocumented(__name__, _allowed_symbols)
apache-2.0
timoschwarzer/blendworks
BlendWorks Server/python/Lib/site-packages/setuptools/__init__.py
219
3317
"""Extensions to the 'distutils' for large or complex distributions""" import os import sys import distutils.core import distutils.filelist from distutils.core import Command as _Command from distutils.util import convert_path import setuptools.version from setuptools.extension import Extension from setuptools.dist import Distribution, Feature, _get_unpatched from setuptools.depends import Require __all__ = [ 'setup', 'Distribution', 'Feature', 'Command', 'Extension', 'Require', 'find_packages' ] __version__ = setuptools.version.__version__ bootstrap_install_from = None # If we run 2to3 on .py files, should we also convert docstrings? # Default: yes; assume that we can detect doctests reliably run_2to3_on_doctests = True # Standard package names for fixer packages lib2to3_fixer_packages = ['lib2to3.fixes'] def find_packages(where='.', exclude=()): """Return a list all Python packages found within directory 'where' 'where' should be supplied as a "cross-platform" (i.e. URL-style) path; it will be converted to the appropriate local path syntax. 'exclude' is a sequence of package names to exclude; '*' can be used as a wildcard in the names, such that 'foo.*' will exclude all subpackages of 'foo' (but not 'foo' itself). """ out = [] stack=[(convert_path(where), '')] while stack: where,prefix = stack.pop(0) for name in os.listdir(where): fn = os.path.join(where,name) looks_like_package = ( '.' not in name and os.path.isdir(fn) and os.path.isfile(os.path.join(fn, '__init__.py')) ) if looks_like_package: out.append(prefix+name) stack.append((fn, prefix+name+'.')) for pat in list(exclude)+['ez_setup']: from fnmatch import fnmatchcase out = [item for item in out if not fnmatchcase(item,pat)] return out setup = distutils.core.setup _Command = _get_unpatched(_Command) class Command(_Command): __doc__ = _Command.__doc__ command_consumes_arguments = False def __init__(self, dist, **kw): # Add support for keyword arguments _Command.__init__(self,dist) for k,v in kw.items(): setattr(self,k,v) def reinitialize_command(self, command, reinit_subcommands=0, **kw): cmd = _Command.reinitialize_command(self, command, reinit_subcommands) for k,v in kw.items(): setattr(cmd,k,v) # update command with keywords return cmd distutils.core.Command = Command # we can't patch distutils.cmd, alas def findall(dir = os.curdir): """Find all files under 'dir' and return the list of full filenames (relative to 'dir'). """ all_files = [] for base, dirs, files in os.walk(dir): if base==os.curdir or base.startswith(os.curdir+os.sep): base = base[2:] if base: files = [os.path.join(base, f) for f in files] all_files.extend(filter(os.path.isfile, files)) return all_files distutils.filelist.findall = findall # fix findall bug in distutils. # sys.dont_write_bytecode was introduced in Python 2.6. _dont_write_bytecode = getattr(sys, 'dont_write_bytecode', bool(os.environ.get("PYTHONDONTWRITEBYTECODE")))
gpl-2.0
mrquim/mrquimrepo
script.module.youtube.dl/lib/youtube_dl/extractor/vodlocker.py
64
2796
# coding: utf-8 from __future__ import unicode_literals from .common import InfoExtractor from ..utils import ( ExtractorError, NO_DEFAULT, sanitized_Request, urlencode_postdata, ) class VodlockerIE(InfoExtractor): _VALID_URL = r'https?://(?:www\.)?vodlocker\.(?:com|city)/(?:embed-)?(?P<id>[0-9a-zA-Z]+)(?:\..*?)?' _TESTS = [{ 'url': 'http://vodlocker.com/e8wvyzz4sl42', 'md5': 'ce0c2d18fa0735f1bd91b69b0e54aacf', 'info_dict': { 'id': 'e8wvyzz4sl42', 'ext': 'mp4', 'title': 'Germany vs Brazil', 'thumbnail': r're:http://.*\.jpg', }, }] def _real_extract(self, url): video_id = self._match_id(url) webpage = self._download_webpage(url, video_id) if any(p in webpage for p in ( '>THIS FILE WAS DELETED<', '>File Not Found<', 'The file you were looking for could not be found, sorry for any inconvenience.<', '>The file was removed')): raise ExtractorError('Video %s does not exist' % video_id, expected=True) fields = self._hidden_inputs(webpage) if fields['op'] == 'download1': self._sleep(3, video_id) # they do detect when requests happen too fast! post = urlencode_postdata(fields) req = sanitized_Request(url, post) req.add_header('Content-type', 'application/x-www-form-urlencoded') webpage = self._download_webpage( req, video_id, 'Downloading video page') def extract_file_url(html, default=NO_DEFAULT): return self._search_regex( r'file:\s*"(http[^\"]+)",', html, 'file url', default=default) video_url = extract_file_url(webpage, default=None) if not video_url: embed_url = self._search_regex( r'<iframe[^>]+src=(["\'])(?P<url>(?:https?://)?vodlocker\.(?:com|city)/embed-.+?)\1', webpage, 'embed url', group='url') embed_webpage = self._download_webpage( embed_url, video_id, 'Downloading embed webpage') video_url = extract_file_url(embed_webpage) thumbnail_webpage = embed_webpage else: thumbnail_webpage = webpage title = self._search_regex( r'id="file_title".*?>\s*(.*?)\s*<(?:br|span)', webpage, 'title') thumbnail = self._search_regex( r'image:\s*"(http[^\"]+)",', thumbnail_webpage, 'thumbnail', fatal=False) formats = [{ 'format_id': 'sd', 'url': video_url, }] return { 'id': video_id, 'title': title, 'thumbnail': thumbnail, 'formats': formats, }
gpl-2.0
darnould/integrations-core
redisdb/check.py
2
15640
# (C) Datadog, Inc. 2010-2016 # All rights reserved # Licensed under Simplified BSD License (see LICENSE) ''' Redis checks ''' # stdlib from collections import defaultdict import re import time # 3rd party import redis # project from checks import AgentCheck DEFAULT_MAX_SLOW_ENTRIES = 128 MAX_SLOW_ENTRIES_KEY = "slowlog-max-len" REPL_KEY = 'master_link_status' LINK_DOWN_KEY = 'master_link_down_since_seconds' class Redis(AgentCheck): db_key_pattern = re.compile(r'^db\d+') slave_key_pattern = re.compile(r'^slave\d+') subkeys = ['keys', 'expires'] SOURCE_TYPE_NAME = 'redis' GAUGE_KEYS = { # Append-only metrics 'aof_last_rewrite_time_sec': 'redis.aof.last_rewrite_time', 'aof_rewrite_in_progress': 'redis.aof.rewrite', 'aof_current_size': 'redis.aof.size', 'aof_buffer_length': 'redis.aof.buffer_length', # Network 'connected_clients': 'redis.net.clients', 'connected_slaves': 'redis.net.slaves', 'rejected_connections': 'redis.net.rejected', # clients 'blocked_clients': 'redis.clients.blocked', 'client_biggest_input_buf': 'redis.clients.biggest_input_buf', 'client_longest_output_list': 'redis.clients.longest_output_list', # Keys 'evicted_keys': 'redis.keys.evicted', 'expired_keys': 'redis.keys.expired', # stats 'latest_fork_usec': 'redis.perf.latest_fork_usec', 'bytes_received_per_sec': 'redis.bytes_received_per_sec', 'bytes_sent_per_sec': 'redis.bytes_sent_per_sec', # Note: 'bytes_received_per_sec' and 'bytes_sent_per_sec' are only # available on Azure Redis # pubsub 'pubsub_channels': 'redis.pubsub.channels', 'pubsub_patterns': 'redis.pubsub.patterns', # rdb 'rdb_bgsave_in_progress': 'redis.rdb.bgsave', 'rdb_changes_since_last_save': 'redis.rdb.changes_since_last', 'rdb_last_bgsave_time_sec': 'redis.rdb.last_bgsave_time', # memory 'mem_fragmentation_ratio': 'redis.mem.fragmentation_ratio', 'used_memory': 'redis.mem.used', 'used_memory_lua': 'redis.mem.lua', 'used_memory_peak': 'redis.mem.peak', 'used_memory_rss': 'redis.mem.rss', # replication 'master_last_io_seconds_ago': 'redis.replication.last_io_seconds_ago', 'master_sync_in_progress': 'redis.replication.sync', 'master_sync_left_bytes': 'redis.replication.sync_left_bytes', 'repl_backlog_histlen': 'redis.replication.backlog_histlen', 'master_repl_offset': 'redis.replication.master_repl_offset', 'slave_repl_offset': 'redis.replication.slave_repl_offset', } RATE_KEYS = { # cpu 'used_cpu_sys': 'redis.cpu.sys', 'used_cpu_sys_children': 'redis.cpu.sys_children', 'used_cpu_user': 'redis.cpu.user', 'used_cpu_user_children': 'redis.cpu.user_children', # stats 'keyspace_hits': 'redis.stats.keyspace_hits', 'keyspace_misses': 'redis.stats.keyspace_misses', } def __init__(self, name, init_config, agentConfig, instances=None): AgentCheck.__init__(self, name, init_config, agentConfig, instances) self.connections = {} self.last_timestamp_seen = defaultdict(int) def get_library_versions(self): return {"redis": redis.__version__} def _parse_dict_string(self, string, key, default): """Take from a more recent redis.py, parse_info""" try: for item in string.split(','): k, v = item.rsplit('=', 1) if k == key: try: return int(v) except ValueError: return v return default except Exception: self.log.exception("Cannot parse dictionary string: %s" % string) return default def _generate_instance_key(self, instance): if 'unix_socket_path' in instance: return (instance.get('unix_socket_path'), instance.get('db')) else: return (instance.get('host'), instance.get('port'), instance.get('db')) def _get_conn(self, instance): key = self._generate_instance_key(instance) if key not in self.connections: try: # Only send useful parameters to the redis client constructor list_params = ['host', 'port', 'db', 'password', 'socket_timeout', 'connection_pool', 'charset', 'errors', 'unix_socket_path', 'ssl', 'ssl_certfile', 'ssl_keyfile', 'ssl_ca_certs', 'ssl_cert_reqs'] # Set a default timeout (in seconds) if no timeout is specified in the instance config instance['socket_timeout'] = instance.get('socket_timeout', 5) connection_params = dict((k, instance[k]) for k in list_params if k in instance) self.connections[key] = redis.Redis(**connection_params) except TypeError: raise Exception("You need a redis library that supports authenticated connections. Try sudo easy_install redis.") return self.connections[key] def _get_tags(self, custom_tags, instance): tags = set(custom_tags or []) if 'unix_socket_path' in instance: tags_to_add = [ "redis_host:%s" % instance.get("unix_socket_path"), "redis_port:unix_socket", ] else: tags_to_add = [ "redis_host:%s" % instance.get('host'), "redis_port:%s" % instance.get('port') ] tags = sorted(tags.union(tags_to_add)) return tags def _check_db(self, instance, custom_tags=None): conn = self._get_conn(instance) tags = self._get_tags(custom_tags, instance) # Ping the database for info, and track the latency. # Process the service check: the check passes if we can connect to Redis start = time.time() info = None try: info = conn.info() status = AgentCheck.OK self.service_check('redis.can_connect', status, tags=tags) self._collect_metadata(info) except ValueError: status = AgentCheck.CRITICAL self.service_check('redis.can_connect', status, tags=tags) raise except Exception: status = AgentCheck.CRITICAL self.service_check('redis.can_connect', status, tags=tags) raise latency_ms = round((time.time() - start) * 1000, 2) self.gauge('redis.info.latency_ms', latency_ms, tags=tags) # Save the database statistics. for key in info.keys(): if self.db_key_pattern.match(key): db_tags = list(tags) + ["redis_db:" + key] # allows tracking percentage of expired keys as DD does not # currently allow arithmetic on metric for monitoring expires_keys = info[key]["expires"] total_keys = info[key]["keys"] persist_keys = total_keys - expires_keys self.gauge("redis.persist", persist_keys, tags=db_tags) self.gauge("redis.persist.percent", 100.0 * persist_keys / total_keys, tags=db_tags) self.gauge("redis.expires.percent", 100.0 * expires_keys / total_keys, tags=db_tags) for subkey in self.subkeys: # Old redis module on ubuntu 10.04 (python-redis 0.6.1) does not # returns a dict for those key but a string: keys=3,expires=0 # Try to parse it (see lighthouse #46) val = -1 try: val = info[key].get(subkey, -1) except AttributeError: val = self._parse_dict_string(info[key], subkey, -1) metric = '.'.join(['redis', subkey]) self.gauge(metric, val, tags=db_tags) # Save a subset of db-wide statistics for info_name, value in info.iteritems(): if info_name in self.GAUGE_KEYS: self.gauge(self.GAUGE_KEYS[info_name], info[info_name], tags=tags) elif info_name in self.RATE_KEYS: self.rate(self.RATE_KEYS[info_name], info[info_name], tags=tags) # Save the number of commands. self.rate('redis.net.commands', info['total_commands_processed'], tags=tags) # Check some key lengths if asked key_list = instance.get('keys') if key_list is not None: if not isinstance(key_list, list) or len(key_list) == 0: self.warning("keys in redis configuration is either not a list or empty") else: l_tags = list(tags) for key in key_list: key_type = conn.type(key) key_tags = l_tags + ['key:' + key] if key_type == 'list': self.gauge('redis.key.length', conn.llen(key), tags=key_tags) elif key_type == 'set': self.gauge('redis.key.length', conn.scard(key), tags=key_tags) elif key_type == 'zset': self.gauge('redis.key.length', conn.zcard(key), tags=key_tags) elif key_type == 'hash': self.gauge('redis.key.length', conn.hlen(key), tags=key_tags) else: # If the type is unknown, it might be because the key doesn't exist, # which can be because the list is empty. So always send 0 in that case. if instance.get("warn_on_missing_keys", True): self.warning("{0} key not found in redis".format(key)) self.gauge('redis.key.length', 0, tags=key_tags) self._check_replication(info, tags) if instance.get("command_stats", False): self._check_command_stats(conn, tags) def _check_replication(self, info, tags): # Save the replication delay for each slave for key in info: if self.slave_key_pattern.match(key) and isinstance(info[key], dict): slave_offset = info[key].get('offset') master_offset = info.get('master_repl_offset') if slave_offset and master_offset and master_offset - slave_offset >= 0: delay = master_offset - slave_offset # Add id, ip, and port tags for the slave slave_tags = tags[:] for slave_tag in ('ip', 'port'): if slave_tag in info[key]: slave_tags.append('slave_{0}:{1}'.format(slave_tag, info[key][slave_tag])) slave_tags.append('slave_id:%s' % key.lstrip('slave')) self.gauge('redis.replication.delay', delay, tags=slave_tags) if REPL_KEY in info: if info[REPL_KEY] == 'up': status = AgentCheck.OK down_seconds = 0 else: status = AgentCheck.CRITICAL down_seconds = info[LINK_DOWN_KEY] self.service_check('redis.replication.master_link_status', status, tags=tags) self.gauge('redis.replication.master_link_down_since_seconds', down_seconds, tags=tags) def _check_slowlog(self, instance, custom_tags): """Retrieve length and entries from Redis' SLOWLOG This will parse through all entries of the SLOWLOG and select ones within the time range between the last seen entries and now """ conn = self._get_conn(instance) tags = self._get_tags(custom_tags, instance) if not instance.get(MAX_SLOW_ENTRIES_KEY): try: max_slow_entries = int(conn.config_get(MAX_SLOW_ENTRIES_KEY)[MAX_SLOW_ENTRIES_KEY]) if max_slow_entries > DEFAULT_MAX_SLOW_ENTRIES: self.warning("Redis {0} is higher than {1}. Defaulting to {1}." "If you need a higher value, please set {0} in your check config" .format(MAX_SLOW_ENTRIES_KEY, DEFAULT_MAX_SLOW_ENTRIES)) max_slow_entries = DEFAULT_MAX_SLOW_ENTRIES # No config on AWS Elasticache except redis.ResponseError: max_slow_entries = DEFAULT_MAX_SLOW_ENTRIES else: max_slow_entries = int(instance.get(MAX_SLOW_ENTRIES_KEY)) # Generate a unique id for this instance to be persisted across runs ts_key = self._generate_instance_key(instance) # Get all slowlog entries slowlogs = conn.slowlog_get(max_slow_entries) # Find slowlog entries between last timestamp and now using start_time slowlogs = [s for s in slowlogs if s['start_time'] > self.last_timestamp_seen[ts_key]] max_ts = 0 # Slowlog entry looks like: # {'command': 'LPOP somekey', # 'duration': 11238, # 'id': 496L, # 'start_time': 1422529869} for slowlog in slowlogs: if slowlog['start_time'] > max_ts: max_ts = slowlog['start_time'] slowlog_tags = list(tags) command = slowlog['command'].split() # When the "Garantia Data" custom Redis is used, redis-py returns # an empty `command` field # FIXME when https://github.com/andymccurdy/redis-py/pull/622 is released in redis-py if command: slowlog_tags.append('command:{0}'.format(command[0])) value = slowlog['duration'] self.histogram('redis.slowlog.micros', value, tags=slowlog_tags) self.last_timestamp_seen[ts_key] = max_ts def _check_command_stats(self, conn, tags): """Get command-specific statistics from redis' INFO COMMANDSTATS command """ try: command_stats = conn.info("commandstats") except Exception: self.warning("Could not retrieve command stats from Redis." "INFO COMMANDSTATS only works with Redis >= 2.6.") return for key, stats in command_stats.iteritems(): command = key.split('_', 1)[1] command_tags = tags + ['command:%s' % command] self.gauge('redis.command.calls', stats['calls'], tags=command_tags) self.gauge('redis.command.usec_per_call', stats['usec_per_call'], tags=command_tags) def check(self, instance): if ("host" not in instance or "port" not in instance) and "unix_socket_path" not in instance: raise Exception("You must specify a host/port couple or a unix_socket_path") custom_tags = instance.get('tags', []) self._check_db(instance, custom_tags) self._check_slowlog(instance, custom_tags) def _collect_metadata(self, info): if info and 'redis_version' in info: self.service_metadata('version', info['redis_version'])
bsd-3-clause
Distrotech/lxc
src/python-lxc/lxc/__init__.py
29
15796
# # -*- coding: utf-8 -*- # python-lxc: Python bindings for LXC # # (C) Copyright Canonical Ltd. 2012 # # Authors: # Stéphane Graber <stgraber@ubuntu.com> # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 # USA # import _lxc import os import subprocess import time default_config_path = _lxc.get_global_config_item("lxc.lxcpath") get_global_config_item = _lxc.get_global_config_item version = _lxc.get_version() class ContainerNetwork(object): props = {} def __init__(self, container, index): self.container = container self.index = index for key in self.container.get_keys("lxc.network.%s" % self.index): if "." in key: self.props[key.replace(".", "_")] = key else: self.props[key] = key if not self.props: return False def __delattr__(self, key): if key in ["container", "index", "props"]: return object.__delattr__(self, key) if key not in self.props: raise AttributeError("'%s' network has no attribute '%s'" % ( self.__get_network_item("type"), key)) return self.__clear_network_item(self.props[key]) def __dir__(self): return sorted(self.props.keys()) def __getattr__(self, key): if key in ["container", "index", "props"]: return object.__getattribute__(self, key) if key not in self.props: raise AttributeError("'%s' network has no attribute '%s'" % ( self.__get_network_item("type"), key)) return self.__get_network_item(self.props[key]) def __hasattr__(self, key): if key in ["container", "index", "props"]: return object.__hasattr__(self, key) if key not in self.props: raise AttributeError("'%s' network has no attribute '%s'" % ( self.__get_network_item("type"), key)) return True def __repr__(self): return "'%s' network at index '%s'" % ( self.__get_network_item("type"), self.index) def __setattr__(self, key, value): if key in ["container", "index", "props"]: return object.__setattr__(self, key, value) if key not in self.props: raise AttributeError("'%s' network has no attribute '%s'" % ( self.__get_network_item("type"), key)) return self.__set_network_item(self.props[key], value) def __clear_network_item(self, key): if key in ("ipv4", "ipv6"): return self.container.clear_config_item("lxc.network.%s.%s" % ( self.index, key)) else: return self.container.set_config_item("lxc.network.%s.%s" % ( self.index, key), "") def __get_network_item(self, key): return self.container.get_config_item("lxc.network.%s.%s" % ( self.index, key)) def __set_network_item(self, key, value): return self.container.set_config_item("lxc.network.%s.%s" % ( self.index, key), value) class ContainerNetworkList(): def __init__(self, container): self.container = container def __getitem__(self, index): if index >= len(self): raise IndexError("list index out of range") return ContainerNetwork(self.container, index) def __len__(self): values = self.container.get_config_item("lxc.network") if values: return len(values) else: return 0 def add(self, network_type): index = len(self) return self.container.set_config_item("lxc.network.%s.type" % index, network_type) def remove(self, index): count = len(self) if index >= count: raise IndexError("list index out of range") return self.container.clear_config_item("lxc.network.%s" % index) class Container(_lxc.Container): def __init__(self, name, config_path=None): """ Creates a new Container instance. """ if config_path: _lxc.Container.__init__(self, name, config_path) else: _lxc.Container.__init__(self, name) self.network = ContainerNetworkList(self) def add_device_net(self, name, destname=None): """ Add network device to running container. """ if not self.running: return False if os.path.exists("/sys/class/net/%s/phy80211/name" % name): with open("/sys/class/net/%s/phy80211/name" % name) as fd: phy = fd.read().strip() if subprocess.call(['iw', 'phy', phy, 'set', 'netns', str(self.init_pid)]) != 0: return False if destname: def rename_interface(args): old, new = args return subprocess.call(['ip', 'link', 'set', 'dev', old, 'name', new]) return self.attach_wait(rename_interface, (name, destname), namespaces=(CLONE_NEWNET)) == 0 return True if not destname: destname = name if not os.path.exists("/sys/class/net/%s/" % name): return False return subprocess.call(['ip', 'link', 'set', 'dev', name, 'netns', str(self.init_pid), 'name', destname]) == 0 def append_config_item(self, key, value): """ Append 'value' to 'key', assuming 'key' is a list. If 'key' isn't a list, 'value' will be set as the value of 'key'. """ return _lxc.Container.set_config_item(self, key, value) def create(self, template=None, flags=0, args=(), bdevtype=None): """ Create a new rootfs for the container. "template" if passed must be a valid template name. "flags" (optional) is an integer representing the optional create flags to be passed. "args" (optional) is a tuple of arguments to pass to the template. It can also be provided as a dict. """ if isinstance(args, dict): tmp_args = [] for item in args.items(): tmp_args.append("--%s" % item[0]) tmp_args.append("%s" % item[1]) template_args = {} if template: template_args['template'] = template template_args['flags'] = flags template_args['args'] = tuple(tmp_args) if bdevtype: template_args['bdevtype'] = bdevtype return _lxc.Container.create(self, **template_args) def clone(self, newname, config_path=None, flags=0, bdevtype=None, bdevdata=None, newsize=0, hookargs=()): """ Clone the current container. """ args = {} args['newname'] = newname args['flags'] = flags args['newsize'] = newsize args['hookargs'] = hookargs if config_path: args['config_path'] = config_path if bdevtype: args['bdevtype'] = bdevtype if bdevdata: args['bdevdata'] = bdevdata if _lxc.Container.clone(self, **args): return Container(newname, config_path=config_path) else: return False def console(self, ttynum=-1, stdinfd=0, stdoutfd=1, stderrfd=2, escape=1): """ Attach to console of running container. """ if not self.running: return False return _lxc.Container.console(self, ttynum, stdinfd, stdoutfd, stderrfd, escape) def console_getfd(self, ttynum=-1): """ Attach to console of running container. """ if not self.running: return False return _lxc.Container.console_getfd(self, ttynum) def get_cgroup_item(self, key): """ Returns the value for a given cgroup entry. A list is returned when multiple values are set. """ value = _lxc.Container.get_cgroup_item(self, key) if value is False: return False else: return value.rstrip("\n") def get_config_item(self, key): """ Returns the value for a given config key. A list is returned when multiple values are set. """ value = _lxc.Container.get_config_item(self, key) if value is False: return False elif value.endswith("\n"): return value.rstrip("\n").split("\n") else: return value def get_keys(self, key=None): """ Returns a list of valid sub-keys. """ if key: value = _lxc.Container.get_keys(self, key) else: value = _lxc.Container.get_keys(self) if value is False: return False elif value.endswith("\n"): return value.rstrip("\n").split("\n") else: return value def get_interfaces(self): """ Get a tuple of interfaces for the container. """ return _lxc.Container.get_interfaces(self) def get_ips(self, interface=None, family=None, scope=None, timeout=0): """ Get a tuple of IPs for the container. """ kwargs = {} if interface: kwargs['interface'] = interface if family: kwargs['family'] = family if scope: kwargs['scope'] = scope ips = None timeout = int(os.environ.get('LXC_GETIP_TIMEOUT', timeout)) while not ips: ips = _lxc.Container.get_ips(self, **kwargs) if timeout == 0: break timeout -= 1 time.sleep(1) return ips def rename(self, new_name): """ Rename the container. On success, returns the new Container object. On failure, returns False. """ if _lxc.Container.rename(self, new_name): return Container(new_name) return False def set_config_item(self, key, value): """ Set a config key to a provided value. The value can be a list for the keys supporting multiple values. """ try: old_value = self.get_config_item(key) except KeyError: old_value = None # Check if it's a list def set_key(key, value): self.clear_config_item(key) if isinstance(value, list): for entry in value: if not _lxc.Container.set_config_item(self, key, entry): return False else: _lxc.Container.set_config_item(self, key, value) set_key(key, value) new_value = self.get_config_item(key) # loglevel is special and won't match the string we set if key == "lxc.loglevel": new_value = value if (isinstance(value, str) and isinstance(new_value, str) and value == new_value): return True elif (isinstance(value, list) and isinstance(new_value, list) and set(value) == set(new_value)): return True elif (isinstance(value, str) and isinstance(new_value, list) and set([value]) == set(new_value)): return True elif old_value: set_key(key, old_value) return False else: self.clear_config_item(key) return False def wait(self, state, timeout=-1): """ Wait for the container to reach a given state or timeout. """ if isinstance(state, str): state = state.upper() return _lxc.Container.wait(self, state, timeout) def list_containers(active=True, defined=True, as_object=False, config_path=None): """ List the containers on the system. """ if config_path: if not os.path.exists(config_path): return tuple() try: entries = _lxc.list_containers(active=active, defined=defined, config_path=config_path) except ValueError: return tuple() else: try: entries = _lxc.list_containers(active=active, defined=defined) except ValueError: return tuple() if as_object: return tuple([Container(name, config_path) for name in entries]) else: return entries def attach_run_command(cmd): """ Run a command when attaching Please do not call directly, this will execvp the command. This is to be used in conjunction with the attach method of a container. """ if isinstance(cmd, tuple): return _lxc.attach_run_command(cmd) elif isinstance(cmd, list): return _lxc.attach_run_command((cmd[0], cmd)) else: return _lxc.attach_run_command((cmd, [cmd])) def attach_run_shell(): """ Run a shell when attaching Please do not call directly, this will execvp the shell. This is to be used in conjunction with the attach method of a container. """ return _lxc.attach_run_shell(None) def arch_to_personality(arch): """ Determine the process personality corresponding to the architecture """ if isinstance(arch, bytes): arch = str(arch, 'utf-8') return _lxc.arch_to_personality(arch) # namespace flags (no other python lib exports this) CLONE_NEWIPC = _lxc.CLONE_NEWIPC CLONE_NEWNET = _lxc.CLONE_NEWNET CLONE_NEWNS = _lxc.CLONE_NEWNS CLONE_NEWPID = _lxc.CLONE_NEWPID CLONE_NEWUSER = _lxc.CLONE_NEWUSER CLONE_NEWUTS = _lxc.CLONE_NEWUTS # attach: environment variable handling LXC_ATTACH_CLEAR_ENV = _lxc.LXC_ATTACH_CLEAR_ENV LXC_ATTACH_KEEP_ENV = _lxc.LXC_ATTACH_KEEP_ENV # attach: attach options LXC_ATTACH_DEFAULT = _lxc.LXC_ATTACH_DEFAULT LXC_ATTACH_DROP_CAPABILITIES = _lxc.LXC_ATTACH_DROP_CAPABILITIES LXC_ATTACH_LSM_EXEC = _lxc.LXC_ATTACH_LSM_EXEC LXC_ATTACH_LSM_NOW = _lxc.LXC_ATTACH_LSM_NOW LXC_ATTACH_MOVE_TO_CGROUP = _lxc.LXC_ATTACH_MOVE_TO_CGROUP LXC_ATTACH_REMOUNT_PROC_SYS = _lxc.LXC_ATTACH_REMOUNT_PROC_SYS LXC_ATTACH_SET_PERSONALITY = _lxc.LXC_ATTACH_SET_PERSONALITY # clone: clone flags LXC_CLONE_KEEPBDEVTYPE = _lxc.LXC_CLONE_KEEPBDEVTYPE LXC_CLONE_KEEPMACADDR = _lxc.LXC_CLONE_KEEPMACADDR LXC_CLONE_KEEPNAME = _lxc.LXC_CLONE_KEEPNAME LXC_CLONE_MAYBE_SNAPSHOT = _lxc.LXC_CLONE_MAYBE_SNAPSHOT LXC_CLONE_SNAPSHOT = _lxc.LXC_CLONE_SNAPSHOT # create: create flags LXC_CREATE_QUIET = _lxc.LXC_CREATE_QUIET
lgpl-2.1
gooddata/openstack-nova
nova/tests/functional/api_sample_tests/test_keypairs.py
3
12708
# Copyright 2012 Nebula, Inc. # Copyright 2013 IBM Corp. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from oslo_utils.fixture import uuidsentinel as uuids from oslo_utils import uuidutils from nova.objects import keypair as keypair_obj from nova.tests.functional.api_sample_tests import api_sample_base from nova.tests.unit import fake_crypto class KeyPairsSampleJsonTest(api_sample_base.ApiSampleTestBaseV21): microversion = None sample_dir = "keypairs" expected_delete_status_code = 202 expected_post_status_code = 200 def setUp(self): super(KeyPairsSampleJsonTest, self).setUp() self.api.microversion = self.microversion # TODO(sdague): this is only needed because we randomly choose the # uuid each time. def generalize_subs(self, subs, vanilla_regexes): subs['keypair_name'] = 'keypair-[0-9a-f-]+' return subs def test_keypairs_post(self): return self._check_keypairs_post() def _check_keypairs_post(self, **kwargs): """Get api sample of key pairs post request.""" key_name = kwargs.pop('kp_name', None) if not key_name: key_name = 'keypair-' + uuids.fake subs = dict(keypair_name=key_name, **kwargs) response = self._do_post('os-keypairs', 'keypairs-post-req', subs) subs = {'keypair_name': key_name} self._verify_response('keypairs-post-resp', subs, response, self.expected_post_status_code) # NOTE(maurosr): return the key_name is necessary cause the # verification returns the label of the last compared information in # the response, not necessarily the key name. return key_name def test_keypairs_import_key_post(self): public_key = fake_crypto.get_ssh_public_key() self._check_keypairs_import_key_post(public_key) def _check_keypairs_import_key_post(self, public_key, **kwargs): # Get api sample of key pairs post to import user's key. key_name = 'keypair-' + uuids.fake subs = { 'keypair_name': key_name, } params = subs.copy() params['public_key'] = public_key params.update(**kwargs) response = self._do_post('os-keypairs', 'keypairs-import-post-req', params) self._verify_response('keypairs-import-post-resp', subs, response, self.expected_post_status_code) def test_keypairs_list(self): # Get api sample of key pairs list request. key_name = self.test_keypairs_post() response = self._do_get('os-keypairs') subs = {'keypair_name': key_name} self._verify_response('keypairs-list-resp', subs, response, 200) def test_keypairs_get(self): # Get api sample of key pairs get request. key_name = self.test_keypairs_post() response = self._do_get('os-keypairs/%s' % key_name) subs = {'keypair_name': key_name} self._verify_response('keypairs-get-resp', subs, response, 200) def test_keypairs_delete(self): # Get api sample of key pairs delete request. key_name = self.test_keypairs_post() response = self._do_delete('os-keypairs/%s' % key_name) self.assertEqual(self.expected_delete_status_code, response.status_code) class KeyPairsV22SampleJsonTest(KeyPairsSampleJsonTest): microversion = '2.2' expected_post_status_code = 201 expected_delete_status_code = 204 # NOTE(gmann): microversion tests do not need to run for v2 API # so defining scenarios only for v2.2 which will run the original tests # by appending '(v2_2)' in test_id. scenarios = [('v2_2', {'api_major_version': 'v2.1'})] def test_keypairs_post(self): # NOTE(claudiub): overrides the method with the same name in # KeypairsSampleJsonTest, as it is used by other tests. return self._check_keypairs_post( keypair_type=keypair_obj.KEYPAIR_TYPE_SSH) def test_keypairs_post_x509(self): return self._check_keypairs_post( keypair_type=keypair_obj.KEYPAIR_TYPE_X509) def test_keypairs_post_invalid(self): key_name = 'keypair-' + uuids.fake subs = dict(keypair_name=key_name, keypair_type='fakey_type') response = self._do_post('os-keypairs', 'keypairs-post-req', subs) self.assertEqual(400, response.status_code) def test_keypairs_import_key_post(self): # NOTE(claudiub): overrides the method with the same name in # KeypairsSampleJsonTest, since the API sample expects a keypair_type. public_key = fake_crypto.get_ssh_public_key() self._check_keypairs_import_key_post( public_key, keypair_type=keypair_obj.KEYPAIR_TYPE_SSH) def test_keypairs_import_key_post_x509(self): public_key = fake_crypto.get_x509_cert_and_fingerprint()[0] public_key = public_key.replace('\n', '\\n') self._check_keypairs_import_key_post( public_key, keypair_type=keypair_obj.KEYPAIR_TYPE_X509) def _check_keypairs_import_key_post_invalid(self, keypair_type): key_name = 'keypair-' + uuids.fake subs = { 'keypair_name': key_name, 'keypair_type': keypair_type, 'public_key': fake_crypto.get_ssh_public_key() } response = self._do_post('os-keypairs', 'keypairs-import-post-req', subs) self.assertEqual(400, response.status_code) def test_keypairs_import_key_post_invalid_type(self): self._check_keypairs_import_key_post_invalid( keypair_type='fakey_type') def test_keypairs_import_key_post_invalid_combination(self): self._check_keypairs_import_key_post_invalid( keypair_type=keypair_obj.KEYPAIR_TYPE_X509) class KeyPairsV210SampleJsonTest(KeyPairsSampleJsonTest): ADMIN_API = True microversion = '2.10' expected_post_status_code = 201 expected_delete_status_code = 204 scenarios = [('v2_10', {'api_major_version': 'v2.1'})] def test_keypair_create_for_user(self): subs = { 'keypair_type': keypair_obj.KEYPAIR_TYPE_SSH, 'public_key': fake_crypto.get_ssh_public_key(), 'user_id': "fake" } self._check_keypairs_post(**subs) def test_keypairs_post(self): return self._check_keypairs_post( keypair_type=keypair_obj.KEYPAIR_TYPE_SSH, user_id="admin") def test_keypairs_import_key_post(self): # NOTE(claudiub): overrides the method with the same name in # KeypairsSampleJsonTest, since the API sample expects a keypair_type. public_key = fake_crypto.get_ssh_public_key() self._check_keypairs_import_key_post( public_key, keypair_type=keypair_obj.KEYPAIR_TYPE_SSH, user_id="fake") def test_keypairs_delete_for_user(self): # Delete a keypair on behalf of a user subs = { 'keypair_type': keypair_obj.KEYPAIR_TYPE_SSH, 'public_key': fake_crypto.get_ssh_public_key(), 'user_id': "fake" } key_name = self._check_keypairs_post(**subs) response = self._do_delete('os-keypairs/%s?user_id=fake' % key_name) self.assertEqual(self.expected_delete_status_code, response.status_code) def test_keypairs_list_for_different_users(self): # Get api sample of key pairs list request. # create common kp_name for two users kp_name = 'keypair-' + uuids.fake keypair_user1 = self._check_keypairs_post( keypair_type=keypair_obj.KEYPAIR_TYPE_SSH, user_id="user1", kp_name=kp_name) keypair_user2 = self._check_keypairs_post( keypair_type=keypair_obj.KEYPAIR_TYPE_SSH, user_id="user2", kp_name=kp_name) # get all keypairs for user1 (only one) response = self._do_get('os-keypairs?user_id=user1') subs = {'keypair_name': keypair_user1} self._verify_response('keypairs-list-resp', subs, response, 200) # get all keypairs for user2 (only one) response = self._do_get('os-keypairs?user_id=user2') subs = {'keypair_name': keypair_user2} self._verify_response('keypairs-list-resp', subs, response, 200) class KeyPairsV210SampleJsonTestNotAdmin(KeyPairsV210SampleJsonTest): ADMIN_API = False def test_keypairs_post(self): return self._check_keypairs_post( keypair_type=keypair_obj.KEYPAIR_TYPE_SSH, user_id="fake") def test_keypairs_post_for_other_user(self): key_name = 'keypair-' + uuids.fake subs = dict(keypair_name=key_name, keypair_type=keypair_obj.KEYPAIR_TYPE_SSH, user_id='fake1') response = self._do_post('os-keypairs', 'keypairs-post-req', subs) self.assertEqual(403, response.status_code) def test_keypairs_list_for_different_users(self): # get and post for other users is forbidden for non admin response = self._do_get('os-keypairs?user_id=fake1') self.assertEqual(403, response.status_code) class KeyPairsV235SampleJsonTest(api_sample_base.ApiSampleTestBaseV21): ADMIN_API = True sample_dir = "keypairs" microversion = '2.35' expected_post_status_code = 201 scenarios = [('v2_35', {'api_major_version': 'v2.1'})] def setUp(self): super(KeyPairsV235SampleJsonTest, self).setUp() self.api.microversion = self.microversion # TODO(pkholkin): this is only needed because we randomly choose the # uuid each time. def generalize_subs(self, subs, vanilla_regexes): subs['keypair_name'] = 'keypair-[0-9a-f-]+' return subs def test_keypairs_post(self, user="admin", kp_name=None): return self._check_keypairs_post( keypair_type=keypair_obj.KEYPAIR_TYPE_SSH, user_id=user, kp_name=kp_name) def _check_keypairs_post(self, **kwargs): """Get api sample of key pairs post request.""" key_name = kwargs.pop('kp_name', None) if not key_name: key_name = 'keypair-' + uuidutils.generate_uuid() subs = dict(keypair_name=key_name, **kwargs) response = self._do_post('os-keypairs', 'keypairs-post-req', subs) subs = {'keypair_name': key_name} self._verify_response('keypairs-post-resp', subs, response, self.expected_post_status_code) return key_name def test_keypairs_list(self): # Get api sample of key pairs list request. # sort key_pairs by name before paging keypairs = sorted([self.test_keypairs_post() for i in range(3)]) response = self._do_get('os-keypairs?marker=%s&limit=1' % keypairs[1]) subs = {'keypair_name': keypairs[2]} self._verify_response('keypairs-list-resp', subs, response, 200) def test_keypairs_list_for_different_users(self): # Get api sample of key pairs list request. # create common kp_names for two users kp_names = ['keypair-' + uuidutils.generate_uuid() for i in range(3)] # sort key_pairs by name before paging keypairs_user1 = sorted([self.test_keypairs_post( user="user1", kp_name=kp_name) for kp_name in kp_names]) keypairs_user2 = sorted([self.test_keypairs_post( user="user2", kp_name=kp_name) for kp_name in kp_names]) # get all keypairs after the second for user1 response = self._do_get('os-keypairs?user_id=user1&marker=%s' % keypairs_user1[1]) subs = {'keypair_name': keypairs_user1[2]} self._verify_response('keypairs-list-user1-resp', subs, response, 200) # get only one keypair after the second for user2 response = self._do_get('os-keypairs?user_id=user2&marker=%s&limit=1' % keypairs_user2[1]) subs = {'keypair_name': keypairs_user2[2]} self._verify_response('keypairs-list-user2-resp', subs, response, 200)
apache-2.0
wd5/jangr
djangoappengine/db/utils.py
4
1850
from google.appengine.datastore.datastore_query import Cursor from django.db import models, DEFAULT_DB_ALIAS try: from functools import wraps except ImportError: from django.utils.functional import wraps # Python 2.3, 2.4 fallback. class CursorQueryMixin(object): def clone(self, *args, **kwargs): kwargs['_gae_cursor'] = getattr(self, '_gae_cursor', None) kwargs['_gae_start_cursor'] = getattr(self, '_gae_start_cursor', None) kwargs['_gae_end_cursor'] = getattr(self, '_gae_end_cursor', None) return super(CursorQueryMixin, self).clone(*args, **kwargs) def get_cursor(queryset): # Evaluate QuerySet. len(queryset) cursor = getattr(queryset.query, '_gae_cursor', None) return Cursor.to_websafe_string(cursor) def set_cursor(queryset, start=None, end=None): queryset = queryset.all() class CursorQuery(CursorQueryMixin, queryset.query.__class__): pass queryset.query = queryset.query.clone(klass=CursorQuery) if start is not None: start = Cursor.from_websafe_string(start) queryset.query._gae_start_cursor = start if end is not None: end = Cursor.from_websafe_string(end) queryset.query._gae_end_cursor = end return queryset def commit_locked(func_or_using=None): """ Decorator that locks rows on DB reads. """ def inner_commit_locked(func, using=None): def _commit_locked(*args, **kw): from google.appengine.api.datastore import RunInTransaction return RunInTransaction(func, *args, **kw) return wraps(func)(_commit_locked) if func_or_using is None: func_or_using = DEFAULT_DB_ALIAS if callable(func_or_using): return inner_commit_locked(func_or_using, DEFAULT_DB_ALIAS) return lambda func: inner_commit_locked(func, func_or_using)
bsd-3-clause
Azure/azure-sdk-for-python
sdk/network/azure-mgmt-network/azure/mgmt/network/v2019_12_01/aio/operations/_vpn_server_configurations_operations.py
1
28218
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar, Union import warnings from azure.core.async_paging import AsyncItemPaged, AsyncList from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod from azure.mgmt.core.exceptions import ARMErrorFormat from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling from ... import models as _models T = TypeVar('T') ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] class VpnServerConfigurationsOperations: """VpnServerConfigurationsOperations async operations. You should not instantiate this class directly. Instead, you should create a Client instance that instantiates it for you and attaches it as an attribute. :ivar models: Alias to model classes used in this operation group. :type models: ~azure.mgmt.network.v2019_12_01.models :param client: Client for service requests. :param config: Configuration of service client. :param serializer: An object model serializer. :param deserializer: An object model deserializer. """ models = _models def __init__(self, client, config, serializer, deserializer) -> None: self._client = client self._serialize = serializer self._deserialize = deserializer self._config = config async def get( self, resource_group_name: str, vpn_server_configuration_name: str, **kwargs ) -> "_models.VpnServerConfiguration": """Retrieves the details of a VpnServerConfiguration. :param resource_group_name: The resource group name of the VpnServerConfiguration. :type resource_group_name: str :param vpn_server_configuration_name: The name of the VpnServerConfiguration being retrieved. :type vpn_server_configuration_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: VpnServerConfiguration, or the result of cls(response) :rtype: ~azure.mgmt.network.v2019_12_01.models.VpnServerConfiguration :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.VpnServerConfiguration"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2019-12-01" accept = "application/json" # Construct URL url = self.get.metadata['url'] # type: ignore path_format_arguments = { 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'vpnServerConfigurationName': self._serialize.url("vpn_server_configuration_name", vpn_server_configuration_name, 'str'), } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') request = self._client.get(url, query_parameters, header_parameters) pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) deserialized = self._deserialize('VpnServerConfiguration', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/vpnServerConfigurations/{vpnServerConfigurationName}'} # type: ignore async def _create_or_update_initial( self, resource_group_name: str, vpn_server_configuration_name: str, vpn_server_configuration_parameters: "_models.VpnServerConfiguration", **kwargs ) -> "_models.VpnServerConfiguration": cls = kwargs.pop('cls', None) # type: ClsType["_models.VpnServerConfiguration"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2019-12-01" content_type = kwargs.pop("content_type", "application/json") accept = "application/json" # Construct URL url = self._create_or_update_initial.metadata['url'] # type: ignore path_format_arguments = { 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'vpnServerConfigurationName': self._serialize.url("vpn_server_configuration_name", vpn_server_configuration_name, 'str'), } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') body_content_kwargs = {} # type: Dict[str, Any] body_content = self._serialize.body(vpn_server_configuration_parameters, 'VpnServerConfiguration') body_content_kwargs['content'] = body_content request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 201]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) if response.status_code == 200: deserialized = self._deserialize('VpnServerConfiguration', pipeline_response) if response.status_code == 201: deserialized = self._deserialize('VpnServerConfiguration', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized _create_or_update_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/vpnServerConfigurations/{vpnServerConfigurationName}'} # type: ignore async def begin_create_or_update( self, resource_group_name: str, vpn_server_configuration_name: str, vpn_server_configuration_parameters: "_models.VpnServerConfiguration", **kwargs ) -> AsyncLROPoller["_models.VpnServerConfiguration"]: """Creates a VpnServerConfiguration resource if it doesn't exist else updates the existing VpnServerConfiguration. :param resource_group_name: The resource group name of the VpnServerConfiguration. :type resource_group_name: str :param vpn_server_configuration_name: The name of the VpnServerConfiguration being created or updated. :type vpn_server_configuration_name: str :param vpn_server_configuration_parameters: Parameters supplied to create or update VpnServerConfiguration. :type vpn_server_configuration_parameters: ~azure.mgmt.network.v2019_12_01.models.VpnServerConfiguration :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: Pass in True if you'd like the AsyncARMPolling polling method, False for no polling, or your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of AsyncLROPoller that returns either VpnServerConfiguration or the result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.network.v2019_12_01.models.VpnServerConfiguration] :raises ~azure.core.exceptions.HttpResponseError: """ polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] cls = kwargs.pop('cls', None) # type: ClsType["_models.VpnServerConfiguration"] lro_delay = kwargs.pop( 'polling_interval', self._config.polling_interval ) cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] if cont_token is None: raw_result = await self._create_or_update_initial( resource_group_name=resource_group_name, vpn_server_configuration_name=vpn_server_configuration_name, vpn_server_configuration_parameters=vpn_server_configuration_parameters, cls=lambda x,y,z: x, **kwargs ) kwargs.pop('error_map', None) kwargs.pop('content_type', None) def get_long_running_output(pipeline_response): deserialized = self._deserialize('VpnServerConfiguration', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized path_format_arguments = { 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'vpnServerConfigurationName': self._serialize.url("vpn_server_configuration_name", vpn_server_configuration_name, 'str'), } if polling is True: polling_method = AsyncARMPolling(lro_delay, lro_options={'final-state-via': 'azure-async-operation'}, path_format_arguments=path_format_arguments, **kwargs) elif polling is False: polling_method = AsyncNoPolling() else: polling_method = polling if cont_token: return AsyncLROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output ) else: return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) begin_create_or_update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/vpnServerConfigurations/{vpnServerConfigurationName}'} # type: ignore async def update_tags( self, resource_group_name: str, vpn_server_configuration_name: str, vpn_server_configuration_parameters: "_models.TagsObject", **kwargs ) -> "_models.VpnServerConfiguration": """Updates VpnServerConfiguration tags. :param resource_group_name: The resource group name of the VpnServerConfiguration. :type resource_group_name: str :param vpn_server_configuration_name: The name of the VpnServerConfiguration being updated. :type vpn_server_configuration_name: str :param vpn_server_configuration_parameters: Parameters supplied to update VpnServerConfiguration tags. :type vpn_server_configuration_parameters: ~azure.mgmt.network.v2019_12_01.models.TagsObject :keyword callable cls: A custom type or function that will be passed the direct response :return: VpnServerConfiguration, or the result of cls(response) :rtype: ~azure.mgmt.network.v2019_12_01.models.VpnServerConfiguration :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.VpnServerConfiguration"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2019-12-01" content_type = kwargs.pop("content_type", "application/json") accept = "application/json" # Construct URL url = self.update_tags.metadata['url'] # type: ignore path_format_arguments = { 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'vpnServerConfigurationName': self._serialize.url("vpn_server_configuration_name", vpn_server_configuration_name, 'str'), } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') body_content_kwargs = {} # type: Dict[str, Any] body_content = self._serialize.body(vpn_server_configuration_parameters, 'TagsObject') body_content_kwargs['content'] = body_content request = self._client.patch(url, query_parameters, header_parameters, **body_content_kwargs) pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) deserialized = self._deserialize('VpnServerConfiguration', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized update_tags.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/vpnServerConfigurations/{vpnServerConfigurationName}'} # type: ignore async def _delete_initial( self, resource_group_name: str, vpn_server_configuration_name: str, **kwargs ) -> None: cls = kwargs.pop('cls', None) # type: ClsType[None] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2019-12-01" accept = "application/json" # Construct URL url = self._delete_initial.metadata['url'] # type: ignore path_format_arguments = { 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'vpnServerConfigurationName': self._serialize.url("vpn_server_configuration_name", vpn_server_configuration_name, 'str'), } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') request = self._client.delete(url, query_parameters, header_parameters) pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 202, 204]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) if cls: return cls(pipeline_response, None, {}) _delete_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/vpnServerConfigurations/{vpnServerConfigurationName}'} # type: ignore async def begin_delete( self, resource_group_name: str, vpn_server_configuration_name: str, **kwargs ) -> AsyncLROPoller[None]: """Deletes a VpnServerConfiguration. :param resource_group_name: The resource group name of the VpnServerConfiguration. :type resource_group_name: str :param vpn_server_configuration_name: The name of the VpnServerConfiguration being deleted. :type vpn_server_configuration_name: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: Pass in True if you'd like the AsyncARMPolling polling method, False for no polling, or your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[None] :raises ~azure.core.exceptions.HttpResponseError: """ polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] cls = kwargs.pop('cls', None) # type: ClsType[None] lro_delay = kwargs.pop( 'polling_interval', self._config.polling_interval ) cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] if cont_token is None: raw_result = await self._delete_initial( resource_group_name=resource_group_name, vpn_server_configuration_name=vpn_server_configuration_name, cls=lambda x,y,z: x, **kwargs ) kwargs.pop('error_map', None) kwargs.pop('content_type', None) def get_long_running_output(pipeline_response): if cls: return cls(pipeline_response, None, {}) path_format_arguments = { 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'vpnServerConfigurationName': self._serialize.url("vpn_server_configuration_name", vpn_server_configuration_name, 'str'), } if polling is True: polling_method = AsyncARMPolling(lro_delay, lro_options={'final-state-via': 'location'}, path_format_arguments=path_format_arguments, **kwargs) elif polling is False: polling_method = AsyncNoPolling() else: polling_method = polling if cont_token: return AsyncLROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output ) else: return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) begin_delete.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/vpnServerConfigurations/{vpnServerConfigurationName}'} # type: ignore def list_by_resource_group( self, resource_group_name: str, **kwargs ) -> AsyncIterable["_models.ListVpnServerConfigurationsResult"]: """Lists all the vpnServerConfigurations in a resource group. :param resource_group_name: The resource group name of the VpnServerConfiguration. :type resource_group_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either ListVpnServerConfigurationsResult or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.network.v2019_12_01.models.ListVpnServerConfigurationsResult] :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.ListVpnServerConfigurationsResult"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2019-12-01" accept = "application/json" def prepare_request(next_link=None): # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') if not next_link: # Construct URL url = self.list_by_resource_group.metadata['url'] # type: ignore path_format_arguments = { 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') request = self._client.get(url, query_parameters, header_parameters) else: url = next_link query_parameters = {} # type: Dict[str, Any] request = self._client.get(url, query_parameters, header_parameters) return request async def extract_data(pipeline_response): deserialized = self._deserialize('ListVpnServerConfigurationsResult', pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) return pipeline_response return AsyncItemPaged( get_next, extract_data ) list_by_resource_group.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/vpnServerConfigurations'} # type: ignore def list( self, **kwargs ) -> AsyncIterable["_models.ListVpnServerConfigurationsResult"]: """Lists all the VpnServerConfigurations in a subscription. :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either ListVpnServerConfigurationsResult or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.network.v2019_12_01.models.ListVpnServerConfigurationsResult] :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.ListVpnServerConfigurationsResult"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2019-12-01" accept = "application/json" def prepare_request(next_link=None): # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') if not next_link: # Construct URL url = self.list.metadata['url'] # type: ignore path_format_arguments = { 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') request = self._client.get(url, query_parameters, header_parameters) else: url = next_link query_parameters = {} # type: Dict[str, Any] request = self._client.get(url, query_parameters, header_parameters) return request async def extract_data(pipeline_response): deserialized = self._deserialize('ListVpnServerConfigurationsResult', pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) return pipeline_response return AsyncItemPaged( get_next, extract_data ) list.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.Network/vpnServerConfigurations'} # type: ignore
mit
EvanK/ansible
lib/ansible/modules/cloud/cloudscale/cloudscale_server.py
7
12775
#!/usr/bin/python # -*- coding: utf-8 -*- # # (c) 2017, Gaudenz Steinlin <gaudenz.steinlin@cloudscale.ch> # 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: cloudscale_server short_description: Manages servers on the cloudscale.ch IaaS service description: - Create, start, stop and delete servers on the cloudscale.ch IaaS service. notes: - To create a new server at least the C(name), C(ssh_key), C(image) and C(flavor) options are required. - If more than one server with the name given by the C(name) option exists, execution is aborted. - Once a server is created all parameters except C(state) are read-only. You can't change the name, flavor or any other property. This is a limitation of the cloudscale.ch API. The module will silently ignore differences between the configured parameters and the running server if a server with the correct name or UUID exists. Only state changes will be applied. version_added: 2.3 author: "Gaudenz Steinlin (@gaudenz) <gaudenz.steinlin@cloudscale.ch>" options: state: description: - State of the server default: running choices: [ running, stopped, absent ] name: description: - Name of the Server. - Either C(name) or C(uuid) are required. These options are mutually exclusive. uuid: description: - UUID of the server. - Either C(name) or C(uuid) are required. These options are mutually exclusive. flavor: description: - Flavor of the server. image: description: - Image used to create the server. volume_size_gb: description: - Size of the root volume in GB. default: 10 bulk_volume_size_gb: description: - Size of the bulk storage volume in GB. - No bulk storage volume if not set. ssh_keys: description: - List of SSH public keys. - Use the full content of your .pub file here. use_public_network: description: - Attach a public network interface to the server. default: True type: bool use_private_network: description: - Attach a private network interface to the server. default: False type: bool use_ipv6: description: - Enable IPv6 on the public network interface. default: True type: bool anti_affinity_with: description: - UUID of another server to create an anti-affinity group with. user_data: description: - Cloud-init configuration (cloud-config) data to use for the server. api_timeout: description: - Timeout in seconds for calls to the cloudscale.ch API. default: 30 version_added: "2.5" extends_documentation_fragment: cloudscale ''' EXAMPLES = ''' # Start a server (if it does not exist) and register the server details - name: Start cloudscale.ch server cloudscale_server: name: my-shiny-cloudscale-server image: debian-8 flavor: flex-4 ssh_keys: ssh-rsa XXXXXXXXXX...XXXX ansible@cloudscale use_private_network: True bulk_volume_size_gb: 100 api_token: xxxxxx register: server1 # Start another server in anti-affinity to the first one - name: Start second cloudscale.ch server cloudscale_server: name: my-other-shiny-server image: ubuntu-16.04 flavor: flex-8 ssh_keys: ssh-rsa XXXXXXXXXXX ansible@cloudscale anti_affinity_with: '{{ server1.uuid }}' api_token: xxxxxx # Stop the first server - name: Stop my first server cloudscale_server: uuid: '{{ server1.uuid }}' state: stopped api_token: xxxxxx # Delete my second server - name: Delete my second server cloudscale_server: name: my-other-shiny-server state: absent api_token: xxxxxx # Start a server and wait for the SSH host keys to be generated - name: Start server and wait for SSH host keys cloudscale_server: name: my-cloudscale-server-with-ssh-key image: debian-8 flavor: flex-4 ssh_keys: ssh-rsa XXXXXXXXXXX ansible@cloudscale api_token: xxxxxx register: server until: server.ssh_fingerprints retries: 60 delay: 2 ''' RETURN = ''' href: description: API URL to get details about this server returned: success when not state == absent type: str sample: https://api.cloudscale.ch/v1/servers/cfde831a-4e87-4a75-960f-89b0148aa2cc uuid: description: The unique identifier for this server returned: success type: str sample: cfde831a-4e87-4a75-960f-89b0148aa2cc name: description: The display name of the server returned: success type: str sample: its-a-me-mario.cloudscale.ch state: description: The current status of the server returned: success type: str sample: running flavor: description: The flavor that has been used for this server returned: success when not state == absent type: str sample: flex-8 image: description: The image used for booting this server returned: success when not state == absent type: str sample: debian-8 volumes: description: List of volumes attached to the server returned: success when not state == absent type: list sample: [ {"type": "ssd", "device": "/dev/vda", "size_gb": "50"} ] interfaces: description: List of network ports attached to the server returned: success when not state == absent type: list sample: [ { "type": "public", "addresses": [ ... ] } ] ssh_fingerprints: description: A list of SSH host key fingerprints. Will be null until the host keys could be retrieved from the server. returned: success when not state == absent type: list sample: ["ecdsa-sha2-nistp256 SHA256:XXXX", ... ] ssh_host_keys: description: A list of SSH host keys. Will be null until the host keys could be retrieved from the server. returned: success when not state == absent type: list sample: ["ecdsa-sha2-nistp256 XXXXX", ... ] anti_affinity_with: description: List of servers in the same anti-affinity group returned: success when not state == absent type: str sample: [] ''' import os from datetime import datetime, timedelta from time import sleep from copy import deepcopy from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.cloudscale import AnsibleCloudscaleBase, cloudscale_argument_spec ALLOWED_STATES = ('running', 'stopped', 'absent', ) class AnsibleCloudscaleServer(AnsibleCloudscaleBase): def __init__(self, module): super(AnsibleCloudscaleServer, self).__init__(module) # Check if server already exists and load properties uuid = self._module.params['uuid'] name = self._module.params['name'] # Initialize server dictionary self.info = {'uuid': uuid, 'name': name, 'state': 'absent'} servers = self.list_servers() matching_server = [] for s in servers: if uuid: # Look for server by UUID if given if s['uuid'] == uuid: self.info = self._transform_state(s) break else: # Look for server by name if s['name'] == name: matching_server.append(s) else: if len(matching_server) == 1: self.info = self._transform_state(matching_server[0]) elif len(matching_server) > 1: self._module.fail_json(msg="More than one server with name '%s' exists. " "Use the 'uuid' parameter to identify the server." % name) @staticmethod def _transform_state(server): if 'status' in server: server['state'] = server['status'] del server['status'] else: server['state'] = 'absent' return server def update_info(self): # If we don't have a UUID (yet) there is nothing to update if 'uuid' not in self.info: return url_path = 'servers/' + self.info['uuid'] resp = self._get(url_path) if resp: self.info = self._transform_state(resp) else: self.info = {'uuid': self.info['uuid'], 'name': self.info.get('name', None), 'state': 'absent'} def wait_for_state(self, states): start = datetime.now() timeout = self._module.params['api_timeout'] * 2 while datetime.now() - start < timedelta(seconds=timeout): self.update_info() if self.info['state'] in states: return True sleep(1) self._module.fail_json(msg='Timeout while waiting for a state change on server %s to states %s. Current state is %s.' % (self.info['name'], states, self.info['state'])) def create_server(self): data = self._module.params.copy() # check for required parameters to create a server missing_parameters = [] for p in ('name', 'ssh_keys', 'image', 'flavor'): if p not in data or not data[p]: missing_parameters.append(p) if len(missing_parameters) > 0: self._module.fail_json(msg='Missing required parameter(s) to create a new server: %s.' % ' '.join(missing_parameters)) # Deepcopy: Duplicate the data object for iteration, because # iterating an object and changing it at the same time is insecure # Sanitize data dictionary for k, v in deepcopy(data).items(): # Remove items not relevant to the create server call if k in ('api_token', 'api_timeout', 'uuid', 'state'): del data[k] continue # Remove None values, these don't get correctly translated by urlencode if v is None: del data[k] continue self.info = self._transform_state(self._post('servers', data)) self.wait_for_state(('running', )) def delete_server(self): self._delete('servers/%s' % self.info['uuid']) self.wait_for_state(('absent', )) def start_server(self): self._post('servers/%s/start' % self.info['uuid']) self.wait_for_state(('running', )) def stop_server(self): self._post('servers/%s/stop' % self.info['uuid']) self.wait_for_state(('stopped', )) def list_servers(self): return self._get('servers') or [] def main(): argument_spec = cloudscale_argument_spec() argument_spec.update(dict( state=dict(default='running', choices=ALLOWED_STATES), name=dict(), uuid=dict(), flavor=dict(), image=dict(), volume_size_gb=dict(type='int', default=10), bulk_volume_size_gb=dict(type='int'), ssh_keys=dict(type='list'), use_public_network=dict(type='bool', default=True), use_private_network=dict(type='bool', default=False), use_ipv6=dict(type='bool', default=True), anti_affinity_with=dict(), user_data=dict(), )) module = AnsibleModule( argument_spec=argument_spec, required_one_of=(('name', 'uuid'),), mutually_exclusive=(('name', 'uuid'),), supports_check_mode=True, ) target_state = module.params['state'] server = AnsibleCloudscaleServer(module) # The server could be in a changing or error state. # Wait for one of the allowed states before doing anything. # If an allowed state can't be reached, this module fails. if server.info['state'] not in ALLOWED_STATES: server.wait_for_state(ALLOWED_STATES) current_state = server.info['state'] if module.check_mode: module.exit_json(changed=not target_state == current_state, **server.info) changed = False if current_state == 'absent' and target_state == 'running': server.create_server() changed = True elif current_state == 'absent' and target_state == 'stopped': server.create_server() server.stop_server() changed = True elif current_state == 'stopped' and target_state == 'running': server.start_server() changed = True elif current_state in ('running', 'stopped') and target_state == 'absent': server.delete_server() changed = True elif current_state == 'running' and target_state == 'stopped': server.stop_server() changed = True module.exit_json(changed=changed, **server.info) if __name__ == '__main__': main()
gpl-3.0
edhuckle/statsmodels
statsmodels/examples/example_enhanced_boxplots.py
33
3179
from __future__ import print_function import numpy as np import matplotlib.pyplot as plt import statsmodels.api as sm # Necessary to make horizontal axis labels fit plt.rcParams['figure.subplot.bottom'] = 0.23 data = sm.datasets.anes96.load_pandas() party_ID = np.arange(7) labels = ["Strong Democrat", "Weak Democrat", "Independent-Democrat", "Independent-Independent", "Independent-Republican", "Weak Republican", "Strong Republican"] # Group age by party ID. age = [data.exog['age'][data.endog == id] for id in party_ID] # Create a violin plot. fig = plt.figure() ax = fig.add_subplot(111) sm.graphics.violinplot(age, ax=ax, labels=labels, plot_opts={'cutoff_val':5, 'cutoff_type':'abs', 'label_fontsize':'small', 'label_rotation':30}) ax.set_xlabel("Party identification of respondent.") ax.set_ylabel("Age") ax.set_title("US national election '96 - Age & Party Identification") # Create a bean plot. fig2 = plt.figure() ax = fig2.add_subplot(111) sm.graphics.beanplot(age, ax=ax, labels=labels, plot_opts={'cutoff_val':5, 'cutoff_type':'abs', 'label_fontsize':'small', 'label_rotation':30}) ax.set_xlabel("Party identification of respondent.") ax.set_ylabel("Age") ax.set_title("US national election '96 - Age & Party Identification") # Create a jitter plot. fig3 = plt.figure() ax = fig3.add_subplot(111) plot_opts={'cutoff_val':5, 'cutoff_type':'abs', 'label_fontsize':'small', 'label_rotation':30, 'violin_fc':(0.8, 0.8, 0.8), 'jitter_marker':'.', 'jitter_marker_size':3, 'bean_color':'#FF6F00', 'bean_mean_color':'#009D91'} sm.graphics.beanplot(age, ax=ax, labels=labels, jitter=True, plot_opts=plot_opts) ax.set_xlabel("Party identification of respondent.") ax.set_ylabel("Age") ax.set_title("US national election '96 - Age & Party Identification") # Create an asymmetrical jitter plot. ix = data.exog['income'] < 16 # incomes < $30k age = data.exog['age'][ix] endog = data.endog[ix] age_lower_income = [age[endog == id] for id in party_ID] ix = data.exog['income'] >= 20 # incomes > $50k age = data.exog['age'][ix] endog = data.endog[ix] age_higher_income = [age[endog == id] for id in party_ID] fig = plt.figure() ax = fig.add_subplot(111) plot_opts['violin_fc'] = (0.5, 0.5, 0.5) plot_opts['bean_show_mean'] = False plot_opts['bean_show_median'] = False plot_opts['bean_legend_text'] = 'Income < \$30k' plot_opts['cutoff_val'] = 10 sm.graphics.beanplot(age_lower_income, ax=ax, labels=labels, side='left', jitter=True, plot_opts=plot_opts) plot_opts['violin_fc'] = (0.7, 0.7, 0.7) plot_opts['bean_color'] = '#009D91' plot_opts['bean_legend_text'] = 'Income > \$50k' sm.graphics.beanplot(age_higher_income, ax=ax, labels=labels, side='right', jitter=True, plot_opts=plot_opts) ax.set_xlabel("Party identification of respondent.") ax.set_ylabel("Age") ax.set_title("US national election '96 - Age & Party Identification") # Show all plots. plt.show()
bsd-3-clause
TRESCLOUD/odoo
addons/lunch/wizard/__init__.py
440
1053
# -*- encoding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2012 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 lunch_validation import lunch_cancel import lunch_order
agpl-3.0
beyang/protobuf
python/google/protobuf/internal/encoder.py
484
25695
# Protocol Buffers - Google's data interchange format # Copyright 2008 Google Inc. All rights reserved. # http://code.google.com/p/protobuf/ # # 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. """Code for encoding protocol message primitives. Contains the logic for encoding every logical protocol field type into one of the 5 physical wire types. This code is designed to push the Python interpreter's performance to the limits. The basic idea is that at startup time, for every field (i.e. every FieldDescriptor) we construct two functions: a "sizer" and an "encoder". The sizer takes a value of this field's type and computes its byte size. The encoder takes a writer function and a value. It encodes the value into byte strings and invokes the writer function to write those strings. Typically the writer function is the write() method of a cStringIO. We try to do as much work as possible when constructing the writer and the sizer rather than when calling them. In particular: * We copy any needed global functions to local variables, so that we do not need to do costly global table lookups at runtime. * Similarly, we try to do any attribute lookups at startup time if possible. * Every field's tag is encoded to bytes at startup, since it can't change at runtime. * Whatever component of the field size we can compute at startup, we do. * We *avoid* sharing code if doing so would make the code slower and not sharing does not burden us too much. For example, encoders for repeated fields do not just call the encoders for singular fields in a loop because this would add an extra function call overhead for every loop iteration; instead, we manually inline the single-value encoder into the loop. * If a Python function lacks a return statement, Python actually generates instructions to pop the result of the last statement off the stack, push None onto the stack, and then return that. If we really don't care what value is returned, then we can save two instructions by returning the result of the last statement. It looks funny but it helps. * We assume that type and bounds checking has happened at a higher level. """ __author__ = 'kenton@google.com (Kenton Varda)' import struct from google.protobuf.internal import wire_format # This will overflow and thus become IEEE-754 "infinity". We would use # "float('inf')" but it doesn't work on Windows pre-Python-2.6. _POS_INF = 1e10000 _NEG_INF = -_POS_INF def _VarintSize(value): """Compute the size of a varint value.""" if value <= 0x7f: return 1 if value <= 0x3fff: return 2 if value <= 0x1fffff: return 3 if value <= 0xfffffff: return 4 if value <= 0x7ffffffff: return 5 if value <= 0x3ffffffffff: return 6 if value <= 0x1ffffffffffff: return 7 if value <= 0xffffffffffffff: return 8 if value <= 0x7fffffffffffffff: return 9 return 10 def _SignedVarintSize(value): """Compute the size of a signed varint value.""" if value < 0: return 10 if value <= 0x7f: return 1 if value <= 0x3fff: return 2 if value <= 0x1fffff: return 3 if value <= 0xfffffff: return 4 if value <= 0x7ffffffff: return 5 if value <= 0x3ffffffffff: return 6 if value <= 0x1ffffffffffff: return 7 if value <= 0xffffffffffffff: return 8 if value <= 0x7fffffffffffffff: return 9 return 10 def _TagSize(field_number): """Returns the number of bytes required to serialize a tag with this field number.""" # Just pass in type 0, since the type won't affect the tag+type size. return _VarintSize(wire_format.PackTag(field_number, 0)) # -------------------------------------------------------------------- # In this section we define some generic sizers. Each of these functions # takes parameters specific to a particular field type, e.g. int32 or fixed64. # It returns another function which in turn takes parameters specific to a # particular field, e.g. the field number and whether it is repeated or packed. # Look at the next section to see how these are used. def _SimpleSizer(compute_value_size): """A sizer which uses the function compute_value_size to compute the size of each value. Typically compute_value_size is _VarintSize.""" def SpecificSizer(field_number, is_repeated, is_packed): tag_size = _TagSize(field_number) if is_packed: local_VarintSize = _VarintSize def PackedFieldSize(value): result = 0 for element in value: result += compute_value_size(element) return result + local_VarintSize(result) + tag_size return PackedFieldSize elif is_repeated: def RepeatedFieldSize(value): result = tag_size * len(value) for element in value: result += compute_value_size(element) return result return RepeatedFieldSize else: def FieldSize(value): return tag_size + compute_value_size(value) return FieldSize return SpecificSizer def _ModifiedSizer(compute_value_size, modify_value): """Like SimpleSizer, but modify_value is invoked on each value before it is passed to compute_value_size. modify_value is typically ZigZagEncode.""" def SpecificSizer(field_number, is_repeated, is_packed): tag_size = _TagSize(field_number) if is_packed: local_VarintSize = _VarintSize def PackedFieldSize(value): result = 0 for element in value: result += compute_value_size(modify_value(element)) return result + local_VarintSize(result) + tag_size return PackedFieldSize elif is_repeated: def RepeatedFieldSize(value): result = tag_size * len(value) for element in value: result += compute_value_size(modify_value(element)) return result return RepeatedFieldSize else: def FieldSize(value): return tag_size + compute_value_size(modify_value(value)) return FieldSize return SpecificSizer def _FixedSizer(value_size): """Like _SimpleSizer except for a fixed-size field. The input is the size of one value.""" def SpecificSizer(field_number, is_repeated, is_packed): tag_size = _TagSize(field_number) if is_packed: local_VarintSize = _VarintSize def PackedFieldSize(value): result = len(value) * value_size return result + local_VarintSize(result) + tag_size return PackedFieldSize elif is_repeated: element_size = value_size + tag_size def RepeatedFieldSize(value): return len(value) * element_size return RepeatedFieldSize else: field_size = value_size + tag_size def FieldSize(value): return field_size return FieldSize return SpecificSizer # ==================================================================== # Here we declare a sizer constructor for each field type. Each "sizer # constructor" is a function that takes (field_number, is_repeated, is_packed) # as parameters and returns a sizer, which in turn takes a field value as # a parameter and returns its encoded size. Int32Sizer = Int64Sizer = EnumSizer = _SimpleSizer(_SignedVarintSize) UInt32Sizer = UInt64Sizer = _SimpleSizer(_VarintSize) SInt32Sizer = SInt64Sizer = _ModifiedSizer( _SignedVarintSize, wire_format.ZigZagEncode) Fixed32Sizer = SFixed32Sizer = FloatSizer = _FixedSizer(4) Fixed64Sizer = SFixed64Sizer = DoubleSizer = _FixedSizer(8) BoolSizer = _FixedSizer(1) def StringSizer(field_number, is_repeated, is_packed): """Returns a sizer for a string field.""" tag_size = _TagSize(field_number) local_VarintSize = _VarintSize local_len = len assert not is_packed if is_repeated: def RepeatedFieldSize(value): result = tag_size * len(value) for element in value: l = local_len(element.encode('utf-8')) result += local_VarintSize(l) + l return result return RepeatedFieldSize else: def FieldSize(value): l = local_len(value.encode('utf-8')) return tag_size + local_VarintSize(l) + l return FieldSize def BytesSizer(field_number, is_repeated, is_packed): """Returns a sizer for a bytes field.""" tag_size = _TagSize(field_number) local_VarintSize = _VarintSize local_len = len assert not is_packed if is_repeated: def RepeatedFieldSize(value): result = tag_size * len(value) for element in value: l = local_len(element) result += local_VarintSize(l) + l return result return RepeatedFieldSize else: def FieldSize(value): l = local_len(value) return tag_size + local_VarintSize(l) + l return FieldSize def GroupSizer(field_number, is_repeated, is_packed): """Returns a sizer for a group field.""" tag_size = _TagSize(field_number) * 2 assert not is_packed if is_repeated: def RepeatedFieldSize(value): result = tag_size * len(value) for element in value: result += element.ByteSize() return result return RepeatedFieldSize else: def FieldSize(value): return tag_size + value.ByteSize() return FieldSize def MessageSizer(field_number, is_repeated, is_packed): """Returns a sizer for a message field.""" tag_size = _TagSize(field_number) local_VarintSize = _VarintSize assert not is_packed if is_repeated: def RepeatedFieldSize(value): result = tag_size * len(value) for element in value: l = element.ByteSize() result += local_VarintSize(l) + l return result return RepeatedFieldSize else: def FieldSize(value): l = value.ByteSize() return tag_size + local_VarintSize(l) + l return FieldSize # -------------------------------------------------------------------- # MessageSet is special. def MessageSetItemSizer(field_number): """Returns a sizer for extensions of MessageSet. The message set message looks like this: message MessageSet { repeated group Item = 1 { required int32 type_id = 2; required string message = 3; } } """ static_size = (_TagSize(1) * 2 + _TagSize(2) + _VarintSize(field_number) + _TagSize(3)) local_VarintSize = _VarintSize def FieldSize(value): l = value.ByteSize() return static_size + local_VarintSize(l) + l return FieldSize # ==================================================================== # Encoders! def _VarintEncoder(): """Return an encoder for a basic varint value (does not include tag).""" local_chr = chr def EncodeVarint(write, value): bits = value & 0x7f value >>= 7 while value: write(local_chr(0x80|bits)) bits = value & 0x7f value >>= 7 return write(local_chr(bits)) return EncodeVarint def _SignedVarintEncoder(): """Return an encoder for a basic signed varint value (does not include tag).""" local_chr = chr def EncodeSignedVarint(write, value): if value < 0: value += (1 << 64) bits = value & 0x7f value >>= 7 while value: write(local_chr(0x80|bits)) bits = value & 0x7f value >>= 7 return write(local_chr(bits)) return EncodeSignedVarint _EncodeVarint = _VarintEncoder() _EncodeSignedVarint = _SignedVarintEncoder() def _VarintBytes(value): """Encode the given integer as a varint and return the bytes. This is only called at startup time so it doesn't need to be fast.""" pieces = [] _EncodeVarint(pieces.append, value) return "".join(pieces) def TagBytes(field_number, wire_type): """Encode the given tag and return the bytes. Only called at startup.""" return _VarintBytes(wire_format.PackTag(field_number, wire_type)) # -------------------------------------------------------------------- # As with sizers (see above), we have a number of common encoder # implementations. def _SimpleEncoder(wire_type, encode_value, compute_value_size): """Return a constructor for an encoder for fields of a particular type. Args: wire_type: The field's wire type, for encoding tags. encode_value: A function which encodes an individual value, e.g. _EncodeVarint(). compute_value_size: A function which computes the size of an individual value, e.g. _VarintSize(). """ def SpecificEncoder(field_number, is_repeated, is_packed): if is_packed: tag_bytes = TagBytes(field_number, wire_format.WIRETYPE_LENGTH_DELIMITED) local_EncodeVarint = _EncodeVarint def EncodePackedField(write, value): write(tag_bytes) size = 0 for element in value: size += compute_value_size(element) local_EncodeVarint(write, size) for element in value: encode_value(write, element) return EncodePackedField elif is_repeated: tag_bytes = TagBytes(field_number, wire_type) def EncodeRepeatedField(write, value): for element in value: write(tag_bytes) encode_value(write, element) return EncodeRepeatedField else: tag_bytes = TagBytes(field_number, wire_type) def EncodeField(write, value): write(tag_bytes) return encode_value(write, value) return EncodeField return SpecificEncoder def _ModifiedEncoder(wire_type, encode_value, compute_value_size, modify_value): """Like SimpleEncoder but additionally invokes modify_value on every value before passing it to encode_value. Usually modify_value is ZigZagEncode.""" def SpecificEncoder(field_number, is_repeated, is_packed): if is_packed: tag_bytes = TagBytes(field_number, wire_format.WIRETYPE_LENGTH_DELIMITED) local_EncodeVarint = _EncodeVarint def EncodePackedField(write, value): write(tag_bytes) size = 0 for element in value: size += compute_value_size(modify_value(element)) local_EncodeVarint(write, size) for element in value: encode_value(write, modify_value(element)) return EncodePackedField elif is_repeated: tag_bytes = TagBytes(field_number, wire_type) def EncodeRepeatedField(write, value): for element in value: write(tag_bytes) encode_value(write, modify_value(element)) return EncodeRepeatedField else: tag_bytes = TagBytes(field_number, wire_type) def EncodeField(write, value): write(tag_bytes) return encode_value(write, modify_value(value)) return EncodeField return SpecificEncoder def _StructPackEncoder(wire_type, format): """Return a constructor for an encoder for a fixed-width field. Args: wire_type: The field's wire type, for encoding tags. format: The format string to pass to struct.pack(). """ value_size = struct.calcsize(format) def SpecificEncoder(field_number, is_repeated, is_packed): local_struct_pack = struct.pack if is_packed: tag_bytes = TagBytes(field_number, wire_format.WIRETYPE_LENGTH_DELIMITED) local_EncodeVarint = _EncodeVarint def EncodePackedField(write, value): write(tag_bytes) local_EncodeVarint(write, len(value) * value_size) for element in value: write(local_struct_pack(format, element)) return EncodePackedField elif is_repeated: tag_bytes = TagBytes(field_number, wire_type) def EncodeRepeatedField(write, value): for element in value: write(tag_bytes) write(local_struct_pack(format, element)) return EncodeRepeatedField else: tag_bytes = TagBytes(field_number, wire_type) def EncodeField(write, value): write(tag_bytes) return write(local_struct_pack(format, value)) return EncodeField return SpecificEncoder def _FloatingPointEncoder(wire_type, format): """Return a constructor for an encoder for float fields. This is like StructPackEncoder, but catches errors that may be due to passing non-finite floating-point values to struct.pack, and makes a second attempt to encode those values. Args: wire_type: The field's wire type, for encoding tags. format: The format string to pass to struct.pack(). """ value_size = struct.calcsize(format) if value_size == 4: def EncodeNonFiniteOrRaise(write, value): # Remember that the serialized form uses little-endian byte order. if value == _POS_INF: write('\x00\x00\x80\x7F') elif value == _NEG_INF: write('\x00\x00\x80\xFF') elif value != value: # NaN write('\x00\x00\xC0\x7F') else: raise elif value_size == 8: def EncodeNonFiniteOrRaise(write, value): if value == _POS_INF: write('\x00\x00\x00\x00\x00\x00\xF0\x7F') elif value == _NEG_INF: write('\x00\x00\x00\x00\x00\x00\xF0\xFF') elif value != value: # NaN write('\x00\x00\x00\x00\x00\x00\xF8\x7F') else: raise else: raise ValueError('Can\'t encode floating-point values that are ' '%d bytes long (only 4 or 8)' % value_size) def SpecificEncoder(field_number, is_repeated, is_packed): local_struct_pack = struct.pack if is_packed: tag_bytes = TagBytes(field_number, wire_format.WIRETYPE_LENGTH_DELIMITED) local_EncodeVarint = _EncodeVarint def EncodePackedField(write, value): write(tag_bytes) local_EncodeVarint(write, len(value) * value_size) for element in value: # This try/except block is going to be faster than any code that # we could write to check whether element is finite. try: write(local_struct_pack(format, element)) except SystemError: EncodeNonFiniteOrRaise(write, element) return EncodePackedField elif is_repeated: tag_bytes = TagBytes(field_number, wire_type) def EncodeRepeatedField(write, value): for element in value: write(tag_bytes) try: write(local_struct_pack(format, element)) except SystemError: EncodeNonFiniteOrRaise(write, element) return EncodeRepeatedField else: tag_bytes = TagBytes(field_number, wire_type) def EncodeField(write, value): write(tag_bytes) try: write(local_struct_pack(format, value)) except SystemError: EncodeNonFiniteOrRaise(write, value) return EncodeField return SpecificEncoder # ==================================================================== # Here we declare an encoder constructor for each field type. These work # very similarly to sizer constructors, described earlier. Int32Encoder = Int64Encoder = EnumEncoder = _SimpleEncoder( wire_format.WIRETYPE_VARINT, _EncodeSignedVarint, _SignedVarintSize) UInt32Encoder = UInt64Encoder = _SimpleEncoder( wire_format.WIRETYPE_VARINT, _EncodeVarint, _VarintSize) SInt32Encoder = SInt64Encoder = _ModifiedEncoder( wire_format.WIRETYPE_VARINT, _EncodeVarint, _VarintSize, wire_format.ZigZagEncode) # Note that Python conveniently guarantees that when using the '<' prefix on # formats, they will also have the same size across all platforms (as opposed # to without the prefix, where their sizes depend on the C compiler's basic # type sizes). Fixed32Encoder = _StructPackEncoder(wire_format.WIRETYPE_FIXED32, '<I') Fixed64Encoder = _StructPackEncoder(wire_format.WIRETYPE_FIXED64, '<Q') SFixed32Encoder = _StructPackEncoder(wire_format.WIRETYPE_FIXED32, '<i') SFixed64Encoder = _StructPackEncoder(wire_format.WIRETYPE_FIXED64, '<q') FloatEncoder = _FloatingPointEncoder(wire_format.WIRETYPE_FIXED32, '<f') DoubleEncoder = _FloatingPointEncoder(wire_format.WIRETYPE_FIXED64, '<d') def BoolEncoder(field_number, is_repeated, is_packed): """Returns an encoder for a boolean field.""" false_byte = chr(0) true_byte = chr(1) if is_packed: tag_bytes = TagBytes(field_number, wire_format.WIRETYPE_LENGTH_DELIMITED) local_EncodeVarint = _EncodeVarint def EncodePackedField(write, value): write(tag_bytes) local_EncodeVarint(write, len(value)) for element in value: if element: write(true_byte) else: write(false_byte) return EncodePackedField elif is_repeated: tag_bytes = TagBytes(field_number, wire_format.WIRETYPE_VARINT) def EncodeRepeatedField(write, value): for element in value: write(tag_bytes) if element: write(true_byte) else: write(false_byte) return EncodeRepeatedField else: tag_bytes = TagBytes(field_number, wire_format.WIRETYPE_VARINT) def EncodeField(write, value): write(tag_bytes) if value: return write(true_byte) return write(false_byte) return EncodeField def StringEncoder(field_number, is_repeated, is_packed): """Returns an encoder for a string field.""" tag = TagBytes(field_number, wire_format.WIRETYPE_LENGTH_DELIMITED) local_EncodeVarint = _EncodeVarint local_len = len assert not is_packed if is_repeated: def EncodeRepeatedField(write, value): for element in value: encoded = element.encode('utf-8') write(tag) local_EncodeVarint(write, local_len(encoded)) write(encoded) return EncodeRepeatedField else: def EncodeField(write, value): encoded = value.encode('utf-8') write(tag) local_EncodeVarint(write, local_len(encoded)) return write(encoded) return EncodeField def BytesEncoder(field_number, is_repeated, is_packed): """Returns an encoder for a bytes field.""" tag = TagBytes(field_number, wire_format.WIRETYPE_LENGTH_DELIMITED) local_EncodeVarint = _EncodeVarint local_len = len assert not is_packed if is_repeated: def EncodeRepeatedField(write, value): for element in value: write(tag) local_EncodeVarint(write, local_len(element)) write(element) return EncodeRepeatedField else: def EncodeField(write, value): write(tag) local_EncodeVarint(write, local_len(value)) return write(value) return EncodeField def GroupEncoder(field_number, is_repeated, is_packed): """Returns an encoder for a group field.""" start_tag = TagBytes(field_number, wire_format.WIRETYPE_START_GROUP) end_tag = TagBytes(field_number, wire_format.WIRETYPE_END_GROUP) assert not is_packed if is_repeated: def EncodeRepeatedField(write, value): for element in value: write(start_tag) element._InternalSerialize(write) write(end_tag) return EncodeRepeatedField else: def EncodeField(write, value): write(start_tag) value._InternalSerialize(write) return write(end_tag) return EncodeField def MessageEncoder(field_number, is_repeated, is_packed): """Returns an encoder for a message field.""" tag = TagBytes(field_number, wire_format.WIRETYPE_LENGTH_DELIMITED) local_EncodeVarint = _EncodeVarint assert not is_packed if is_repeated: def EncodeRepeatedField(write, value): for element in value: write(tag) local_EncodeVarint(write, element.ByteSize()) element._InternalSerialize(write) return EncodeRepeatedField else: def EncodeField(write, value): write(tag) local_EncodeVarint(write, value.ByteSize()) return value._InternalSerialize(write) return EncodeField # -------------------------------------------------------------------- # As before, MessageSet is special. def MessageSetItemEncoder(field_number): """Encoder for extensions of MessageSet. The message set message looks like this: message MessageSet { repeated group Item = 1 { required int32 type_id = 2; required string message = 3; } } """ start_bytes = "".join([ TagBytes(1, wire_format.WIRETYPE_START_GROUP), TagBytes(2, wire_format.WIRETYPE_VARINT), _VarintBytes(field_number), TagBytes(3, wire_format.WIRETYPE_LENGTH_DELIMITED)]) end_bytes = TagBytes(1, wire_format.WIRETYPE_END_GROUP) local_EncodeVarint = _EncodeVarint def EncodeField(write, value): write(start_bytes) local_EncodeVarint(write, value.ByteSize()) value._InternalSerialize(write) return write(end_bytes) return EncodeField
bsd-3-clause
dago/ansible-modules-extras
cloud/cloudstack/cs_loadbalancer_rule.py
31
11531
#!/usr/bin/python # -*- coding: utf-8 -*- # # (c) 2015, Darren Worrall <darren@iweb.co.uk> # (c) 2015, René Moser <mail@renemoser.net> # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Ansible is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Ansible. If not, see <http://www.gnu.org/licenses/>. DOCUMENTATION = ''' --- module: cs_loadbalancer_rule short_description: Manages load balancer rules on Apache CloudStack based clouds. description: - Add, update and remove load balancer rules. version_added: '2.0' author: - "Darren Worrall (@dazworrall)" - "René Moser (@resmo)" options: name: description: - The name of the load balancer rule. required: true description: description: - The description of the load balancer rule. required: false default: null algorithm: description: - Load balancer algorithm - Required when using C(state=present). required: false choices: [ 'source', 'roundrobin', 'leastconn' ] default: 'source' private_port: description: - The private port of the private ip address/virtual machine where the network traffic will be load balanced to. - Required when using C(state=present). - Can not be changed once the rule exists due API limitation. required: false default: null public_port: description: - The public port from where the network traffic will be load balanced from. - Required when using C(state=present). - Can not be changed once the rule exists due API limitation. required: true default: null ip_address: description: - Public IP address from where the network traffic will be load balanced from. required: true aliases: [ 'public_ip' ] open_firewall: description: - Whether the firewall rule for public port should be created, while creating the new rule. - Use M(cs_firewall) for managing firewall rules. required: false default: false cidr: description: - CIDR (full notation) to be used for firewall rule if required. required: false default: null protocol: description: - The protocol to be used on the load balancer required: false default: null project: description: - Name of the project the load balancer IP address is related to. required: false default: null state: description: - State of the rule. required: true default: 'present' choices: [ 'present', 'absent' ] domain: description: - Domain the rule is related to. required: false default: null account: description: - Account the rule is related to. required: false default: null zone: description: - Name of the zone in which the rule shoud be created. - If not set, default zone is used. required: false default: null extends_documentation_fragment: cloudstack ''' EXAMPLES = ''' # Create a load balancer rule - local_action: module: cs_loadbalancer_rule name: balance_http public_ip: 1.2.3.4 algorithm: leastconn public_port: 80 private_port: 8080 # update algorithm of an existing load balancer rule - local_action: module: cs_loadbalancer_rule name: balance_http public_ip: 1.2.3.4 algorithm: roundrobin public_port: 80 private_port: 8080 # Delete a load balancer rule - local_action: module: cs_loadbalancer_rule name: balance_http public_ip: 1.2.3.4 state: absent ''' RETURN = ''' --- id: description: UUID of the rule. returned: success type: string sample: a6f7a5fc-43f8-11e5-a151-feff819cdc9f zone: description: Name of zone the rule is related to. returned: success type: string sample: ch-gva-2 project: description: Name of project the rule is related to. returned: success type: string sample: Production account: description: Account the rule is related to. returned: success type: string sample: example account domain: description: Domain the rule is related to. returned: success type: string sample: example domain algorithm: description: Load balancer algorithm used. returned: success type: string sample: "source" cidr: description: CIDR to forward traffic from. returned: success type: string sample: "" name: description: Name of the rule. returned: success type: string sample: "http-lb" description: description: Description of the rule. returned: success type: string sample: "http load balancer rule" protocol: description: Protocol of the rule. returned: success type: string sample: "tcp" public_port: description: Public port. returned: success type: string sample: 80 private_port: description: Private IP address. returned: success type: string sample: 80 public_ip: description: Public IP address. returned: success type: string sample: "1.2.3.4" tags: description: List of resource tags associated with the rule. returned: success type: dict sample: '[ { "key": "foo", "value": "bar" } ]' state: description: State of the rule. returned: success type: string sample: "Add" ''' try: from cs import CloudStack, CloudStackException, read_config has_lib_cs = True except ImportError: has_lib_cs = False # import cloudstack common from ansible.module_utils.cloudstack import * class AnsibleCloudStackLBRule(AnsibleCloudStack): def __init__(self, module): super(AnsibleCloudStackLBRule, self).__init__(module) self.returns = { 'publicip': 'public_ip', 'algorithm': 'algorithm', 'cidrlist': 'cidr', 'protocol': 'protocol', } # these values will be casted to int self.returns_to_int = { 'publicport': 'public_port', 'privateport': 'private_port', } def get_rule(self, **kwargs): rules = self.cs.listLoadBalancerRules(**kwargs) if rules: return rules['loadbalancerrule'][0] def _get_common_args(self): return { 'account': self.get_account(key='name'), 'domainid': self.get_domain(key='id'), 'projectid': self.get_project(key='id'), 'zoneid': self.get_zone(key='id'), 'publicipid': self.get_ip_address(key='id'), 'name': self.module.params.get('name'), } def present_lb_rule(self): missing_params = [] for required_params in [ 'algorithm', 'private_port', 'public_port', ]: if not self.module.params.get(required_params): missing_params.append(required_params) if missing_params: self.module.fail_json(msg="missing required arguments: %s" % ','.join(missing_params)) args = self._get_common_args() rule = self.get_rule(**args) if rule: rule = self._update_lb_rule(rule) else: rule = self._create_lb_rule(rule) if rule: rule = self.ensure_tags(resource=rule, resource_type='LoadBalancer') return rule def _create_lb_rule(self, rule): self.result['changed'] = True if not self.module.check_mode: args = self._get_common_args() args['algorithm'] = self.module.params.get('algorithm') args['privateport'] = self.module.params.get('private_port') args['publicport'] = self.module.params.get('public_port') args['cidrlist'] = self.module.params.get('cidr') args['description'] = self.module.params.get('description') args['protocol'] = self.module.params.get('protocol') res = self.cs.createLoadBalancerRule(**args) if 'errortext' in res: self.module.fail_json(msg="Failed: '%s'" % res['errortext']) poll_async = self.module.params.get('poll_async') if poll_async: rule = self.poll_job(res, 'loadbalancer') return rule def _update_lb_rule(self, rule): args = {} args['id'] = rule['id'] args['algorithm'] = self.module.params.get('algorithm') args['description'] = self.module.params.get('description') if self.has_changed(args, rule): self.result['changed'] = True if not self.module.check_mode: res = self.cs.updateLoadBalancerRule(**args) if 'errortext' in res: self.module.fail_json(msg="Failed: '%s'" % res['errortext']) poll_async = self.module.params.get('poll_async') if poll_async: rule = self.poll_job(res, 'loadbalancer') return rule def absent_lb_rule(self): args = self._get_common_args() rule = self.get_rule(**args) if rule: self.result['changed'] = True if rule and not self.module.check_mode: res = self.cs.deleteLoadBalancerRule(id=rule['id']) if 'errortext' in res: self.module.fail_json(msg="Failed: '%s'" % res['errortext']) poll_async = self.module.params.get('poll_async') if poll_async: res = self._poll_job(res, 'loadbalancer') return rule def main(): argument_spec = cs_argument_spec() argument_spec.update(dict( name = dict(required=True), description = dict(default=None), algorithm = dict(choices=['source', 'roundrobin', 'leastconn'], default='source'), private_port = dict(type='int', default=None), public_port = dict(type='int', default=None), protocol = dict(default=None), state = dict(choices=['present', 'absent'], default='present'), ip_address = dict(required=True, aliases=['public_ip']), cidr = dict(default=None), project = dict(default=None), open_firewall = dict(type='bool', default=False), tags = dict(type='list', aliases=['tag'], default=None), zone = dict(default=None), domain = dict(default=None), account = dict(default=None), poll_async = dict(type='bool', default=True), )) module = AnsibleModule( argument_spec=argument_spec, required_together=cs_required_together(), supports_check_mode=True ) if not has_lib_cs: module.fail_json(msg="python library cs required: pip install cs") try: acs_lb_rule = AnsibleCloudStackLBRule(module) state = module.params.get('state') if state in ['absent']: rule = acs_lb_rule.absent_lb_rule() else: rule = acs_lb_rule.present_lb_rule() result = acs_lb_rule.get_result(rule) except CloudStackException as e: module.fail_json(msg='CloudStackException: %s' % str(e)) module.exit_json(**result) # import module snippets from ansible.module_utils.basic import * if __name__ == '__main__': main()
gpl-3.0
adusca/treeherder
treeherder/perf/models.py
1
2417
from django.core.validators import MinLengthValidator from django.db import models from django.utils.encoding import python_2_unicode_compatible from jsonfield import JSONField from treeherder.model.models import (MachinePlatform, OptionCollection, Repository) SIGNATURE_HASH_LENGTH = 40L @python_2_unicode_compatible class PerformanceFramework(models.Model): name = models.SlugField(max_length=255L, unique=True) class Meta: db_table = 'performance_framework' def __str__(self): return self.name @python_2_unicode_compatible class PerformanceSignature(models.Model): signature_hash = models.CharField(max_length=SIGNATURE_HASH_LENGTH, validators=[ MinLengthValidator(SIGNATURE_HASH_LENGTH) ], unique=True, db_index=True) framework = models.ForeignKey(PerformanceFramework) platform = models.ForeignKey(MachinePlatform) option_collection = models.ForeignKey(OptionCollection) suite = models.CharField(max_length=80L) test = models.CharField(max_length=80L, blank=True) # extra properties to distinguish the test (that don't fit into # option collection for whatever reason) extra_properties = JSONField(max_length=1024) class Meta: db_table = 'performance_signature' def __str__(self): return self.signature_hash @python_2_unicode_compatible class PerformanceDatum(models.Model): repository = models.ForeignKey(Repository) job_id = models.PositiveIntegerField(db_index=True) result_set_id = models.PositiveIntegerField(db_index=True) signature = models.ForeignKey(PerformanceSignature) value = models.FloatField() push_timestamp = models.DateTimeField(db_index=True) class Meta: db_table = 'performance_datum' index_together = [('repository', 'signature', 'push_timestamp'), ('repository', 'job_id'), ('repository', 'result_set_id')] unique_together = ('repository', 'job_id', 'result_set_id', 'signature', 'push_timestamp') def __str__(self): return "{} {}".format(self.value, self.push_timestamp)
mpl-2.0
Lh4cKg/brython
www/src/Lib/test/unittests/test_netrc.py
123
4607
import netrc, os, unittest, sys, textwrap from test import support temp_filename = support.TESTFN class NetrcTestCase(unittest.TestCase): def make_nrc(self, test_data): test_data = textwrap.dedent(test_data) mode = 'w' if sys.platform != 'cygwin': mode += 't' with open(temp_filename, mode) as fp: fp.write(test_data) self.addCleanup(os.unlink, temp_filename) return netrc.netrc(temp_filename) def test_default(self): nrc = self.make_nrc("""\ machine host1.domain.com login log1 password pass1 account acct1 default login log2 password pass2 """) self.assertEqual(nrc.hosts['host1.domain.com'], ('log1', 'acct1', 'pass1')) self.assertEqual(nrc.hosts['default'], ('log2', None, 'pass2')) def test_macros(self): nrc = self.make_nrc("""\ macdef macro1 line1 line2 macdef macro2 line3 line4 """) self.assertEqual(nrc.macros, {'macro1': ['line1\n', 'line2\n'], 'macro2': ['line3\n', 'line4\n']}) def _test_passwords(self, nrc, passwd): nrc = self.make_nrc(nrc) self.assertEqual(nrc.hosts['host.domain.com'], ('log', 'acct', passwd)) def test_password_with_leading_hash(self): self._test_passwords("""\ machine host.domain.com login log password #pass account acct """, '#pass') def test_password_with_trailing_hash(self): self._test_passwords("""\ machine host.domain.com login log password pass# account acct """, 'pass#') def test_password_with_internal_hash(self): self._test_passwords("""\ machine host.domain.com login log password pa#ss account acct """, 'pa#ss') def _test_comment(self, nrc, passwd='pass'): nrc = self.make_nrc(nrc) self.assertEqual(nrc.hosts['foo.domain.com'], ('bar', None, passwd)) self.assertEqual(nrc.hosts['bar.domain.com'], ('foo', None, 'pass')) def test_comment_before_machine_line(self): self._test_comment("""\ # comment machine foo.domain.com login bar password pass machine bar.domain.com login foo password pass """) def test_comment_before_machine_line_no_space(self): self._test_comment("""\ #comment machine foo.domain.com login bar password pass machine bar.domain.com login foo password pass """) def test_comment_before_machine_line_hash_only(self): self._test_comment("""\ # machine foo.domain.com login bar password pass machine bar.domain.com login foo password pass """) def test_comment_at_end_of_machine_line(self): self._test_comment("""\ machine foo.domain.com login bar password pass # comment machine bar.domain.com login foo password pass """) def test_comment_at_end_of_machine_line_no_space(self): self._test_comment("""\ machine foo.domain.com login bar password pass #comment machine bar.domain.com login foo password pass """) def test_comment_at_end_of_machine_line_pass_has_hash(self): self._test_comment("""\ machine foo.domain.com login bar password #pass #comment machine bar.domain.com login foo password pass """, '#pass') @unittest.skipUnless(os.name == 'posix', 'POSIX only test') def test_security(self): # This test is incomplete since we are normally not run as root and # therefore can't test the file ownership being wrong. d = support.TESTFN os.mkdir(d) self.addCleanup(support.rmtree, d) fn = os.path.join(d, '.netrc') with open(fn, 'wt') as f: f.write("""\ machine foo.domain.com login bar password pass default login foo password pass """) with support.EnvironmentVarGuard() as environ: environ.set('HOME', d) os.chmod(fn, 0o600) nrc = netrc.netrc() self.assertEqual(nrc.hosts['foo.domain.com'], ('bar', None, 'pass')) os.chmod(fn, 0o622) self.assertRaises(netrc.NetrcParseError, netrc.netrc) def test_main(): support.run_unittest(NetrcTestCase) if __name__ == "__main__": test_main()
bsd-3-clause
lovetox/gajim
src/common/crypto.py
1
4823
# common crypto functions (mostly specific to XEP-0116, but useful elsewhere) # -*- coding:utf-8 -*- ## src/common/crypto.py ## ## Copyright (C) 2007 Brendan Taylor <whateley AT gmail.com> ## ## This file is part of Gajim. ## ## Gajim 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; version 3 only. ## ## Gajim 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 Gajim. If not, see <http://www.gnu.org/licenses/>. ## import sys import os import math from hashlib import sha256 as SHA256 # convert a large integer to a big-endian bitstring def encode_mpi(n): if n >= 256: return encode_mpi(n // 256) + bytes([n % 256]) else: return bytes([n]) # convert a large integer to a big-endian bitstring, padded with \x00s to # a multiple of 16 bytes def encode_mpi_with_padding(n): return pad_to_multiple(encode_mpi(n), 16, '\x00', True) # pad 'string' to a multiple of 'multiple_of' with 'char'. # pad on the left if 'left', otherwise pad on the right. def pad_to_multiple(string, multiple_of, char, left): mod = len(string) % multiple_of if mod == 0: return string else: padding = (multiple_of - mod) * char if left: return padding + string else: return string + padding # convert a big-endian bitstring to an integer def decode_mpi(s): if len(s) == 0: return 0 else: return 256 * decode_mpi(s[:-1]) + s[-1] def sha256(string): sh = SHA256() sh.update(string) return sh.digest() base28_chr = "acdefghikmopqruvwxy123456789" def sas_28x5(m_a, form_b): sha = sha256(m_a + form_b + b'Short Authentication String') lsb24 = decode_mpi(sha[-3:]) return base28(lsb24) def base28(n): if n >= 28: return base28(n // 28) + base28_chr[n % 28] else: return base28_chr[n] def add_entropy_sources_OpenSSL(): # Other possibly variable data. This are very low quality sources of # entropy, but some of them are installation dependent and can be hard # to guess for the attacker. # Data available on all platforms Unix, Windows sources = [sys.argv, sys.builtin_module_names, sys.copyright, sys.getfilesystemencoding(), sys.hexversion, sys.modules, sys.path, sys.version, sys.api_version, os.environ, os.getcwd(), os.getpid()] for s in sources: OpenSSL.rand.add(str(s).encode('utf-8'), 1) # On Windows add the current contents of the screen to the PRNG state. # if os.name == 'nt': # OpenSSL.rand.screen() # The /proc filesystem on POSIX systems contains many random variables: # memory statistics, interrupt counts, network packet counts if os.name == 'posix': dirs = ['/proc', '/proc/net', '/proc/self'] for d in dirs: if os.access(d, os.R_OK): for filename in os.listdir(d): OpenSSL.rand.add(filename.encode('utf-8'), 0) try: with open(d + os.sep + filename, "r") as fp: # Limit the ammount of read bytes, in case a memory # file was opened OpenSSL.rand.add(str(fp.read(5000)).encode('utf-8'), 1) except: # Ignore all read and access errors pass PYOPENSSL_PRNG_PRESENT = False try: import OpenSSL.rand PYOPENSSL_PRNG_PRESENT = True except ImportError: # PyOpenSSL PRNG not available pass def random_bytes(bytes_): if PYOPENSSL_PRNG_PRESENT: OpenSSL.rand.add(os.urandom(bytes_), bytes_) return OpenSSL.rand.bytes(bytes_) else: return os.urandom(bytes_) def generate_nonce(): return random_bytes(8) # generate a random number between 'bottom' and 'top' def srand(bottom, top): # minimum number of bytes needed to represent that range bytes = int(math.ceil(math.log(top - bottom, 256))) # in retrospect, this is horribly inadequate. return (decode_mpi(random_bytes(bytes)) % (top - bottom)) + bottom # a faster version of (base ** exp) % mod # taken from <http://lists.danga.com/pipermail/yadis/2005-September/001445.html> def powmod(base, exp, mod): square = base % mod result = 1 while exp > 0: if exp & 1: # exponent is odd result = (result * square) % mod square = (square * square) % mod exp //= 2 return result
gpl-3.0
timj/scons
bin/time-scons.py
6
12346
#!/usr/bin/env python # # time-scons.py: a wrapper script for running SCons timings # # This script exists to: # # 1) Wrap the invocation of runtest.py to run the actual TimeSCons # timings consistently. It does this specifically by building # SCons first, so .pyc compilation is not part of the timing. # # 2) Provide an interface for running TimeSCons timings against # earlier revisions, before the whole TimeSCons infrastructure # was "frozen" to provide consistent timings. This is done # by updating the specific pieces containing the TimeSCons # infrastructure to the earliest revision at which those pieces # were "stable enough." # # By encapsulating all the logic in this script, our Buildbot # infrastructure only needs to call this script, and we should be able # to change what we need to in this script and have it affect the build # automatically when the source code is updated, without having to # restart either master or slave. import optparse import os import shutil import subprocess import sys import tempfile import xml.sax.handler SubversionURL = 'http://scons.tigris.org/svn/scons' # This is the baseline revision when the TimeSCons scripts first # stabilized and collected "real," consistent timings. If we're timing # a revision prior to this, we'll forcibly update the TimeSCons pieces # of the tree to this revision to collect consistent timings for earlier # revisions. TimeSCons_revision = 4569 # The pieces of the TimeSCons infrastructure that are necessary to # produce consistent timings, even when the rest of the tree is from # an earlier revision that doesn't have these pieces. TimeSCons_pieces = ['QMTest', 'timings', 'runtest.py'] class CommandRunner(object): """ Executor class for commands, including "commands" implemented by Python functions. """ verbose = True active = True def __init__(self, dictionary={}): self.subst_dictionary(dictionary) def subst_dictionary(self, dictionary): self._subst_dictionary = dictionary def subst(self, string, dictionary=None): """ Substitutes (via the format operator) the values in the specified dictionary into the specified command. The command can be an (action, string) tuple. In all cases, we perform substitution on strings and don't worry if something isn't a string. (It's probably a Python function to be executed.) """ if dictionary is None: dictionary = self._subst_dictionary if dictionary: try: string = string % dictionary except TypeError: pass return string def display(self, command, stdout=None, stderr=None): if not self.verbose: return if isinstance(command, tuple): func = command[0] args = command[1:] s = '%s(%s)' % (func.__name__, ', '.join(map(repr, args))) if isinstance(command, list): # TODO: quote arguments containing spaces # TODO: handle meta characters? s = ' '.join(command) else: s = self.subst(command) if not s.endswith('\n'): s += '\n' sys.stdout.write(s) sys.stdout.flush() def execute(self, command, stdout=None, stderr=None): """ Executes a single command. """ if not self.active: return 0 if isinstance(command, str): command = self.subst(command) cmdargs = shlex.split(command) if cmdargs[0] == 'cd': command = (os.chdir,) + tuple(cmdargs[1:]) if isinstance(command, tuple): func = command[0] args = command[1:] return func(*args) else: if stdout is sys.stdout: # Same as passing sys.stdout, except works with python2.4. subout = None elif stdout is None: # Open pipe for anything else so Popen works on python2.4. subout = subprocess.PIPE else: subout = stdout if stderr is sys.stderr: # Same as passing sys.stdout, except works with python2.4. suberr = None elif stderr is None: # Merge with stdout if stderr isn't specified. suberr = subprocess.STDOUT else: suberr = stderr p = subprocess.Popen(command, shell=(sys.platform == 'win32'), stdout=subout, stderr=suberr) p.wait() return p.returncode def run(self, command, display=None, stdout=None, stderr=None): """ Runs a single command, displaying it first. """ if display is None: display = command self.display(display) return self.execute(command, stdout, stderr) def run_list(self, command_list, **kw): """ Runs a list of commands, stopping with the first error. Returns the exit status of the first failed command, or 0 on success. """ status = 0 for command in command_list: s = self.run(command, **kw) if s and status == 0: status = s return 0 def get_svn_revisions(branch, revisions=None): """ Fetch the actual SVN revisions for the given branch querying "svn log." A string specifying a range of revisions can be supplied to restrict the output to a subset of the entire log. """ command = ['svn', 'log', '--xml'] if revisions: command.extend(['-r', revisions]) command.append(branch) p = subprocess.Popen(command, stdout=subprocess.PIPE) class SVNLogHandler(xml.sax.handler.ContentHandler): def __init__(self): self.revisions = [] def startElement(self, name, attributes): if name == 'logentry': self.revisions.append(int(attributes['revision'])) parser = xml.sax.make_parser() handler = SVNLogHandler() parser.setContentHandler(handler) parser.parse(p.stdout) return sorted(handler.revisions) def prepare_commands(): """ Returns a list of the commands to be executed to prepare the tree for testing. This involves building SCons, specifically the build/scons subdirectory where our packaging build is staged, and then running setup.py to create a local installed copy with compiled *.pyc files. The build directory gets removed first. """ commands = [] if os.path.exists('build'): commands.extend([ ['mv', 'build', 'build.OLD'], ['rm', '-rf', 'build.OLD'], ]) commands.append([sys.executable, 'bootstrap.py', 'build/scons']) commands.append([sys.executable, 'build/scons/setup.py', 'install', '--prefix=' + os.path.abspath('build/usr')]) return commands def script_command(script): """Returns the command to actually invoke the specified timing script using our "built" scons.""" return [sys.executable, 'runtest.py', '-x', 'build/usr/bin/scons', script] def do_revisions(cr, opts, branch, revisions, scripts): """ Time the SCons branch specified scripts through a list of revisions. We assume we're in a (temporary) directory in which we can check out the source for the specified revisions. """ stdout = sys.stdout stderr = sys.stderr status = 0 if opts.logsdir and not opts.no_exec and len(scripts) > 1: for script in scripts: subdir = os.path.basename(os.path.dirname(script)) logsubdir = os.path.join(opts.origin, opts.logsdir, subdir) if not os.path.exists(logsubdir): os.makedirs(logsubdir) for this_revision in revisions: if opts.logsdir and not opts.no_exec: log_name = '%s.log' % this_revision log_file = os.path.join(opts.origin, opts.logsdir, log_name) stdout = open(log_file, 'w') stderr = None commands = [ ['svn', 'co', '-q', '-r', str(this_revision), branch, '.'], ] if int(this_revision) < int(TimeSCons_revision): commands.append(['svn', 'up', '-q', '-r', str(TimeSCons_revision)] + TimeSCons_pieces) commands.extend(prepare_commands()) s = cr.run_list(commands, stdout=stdout, stderr=stderr) if s: if status == 0: status = s continue for script in scripts: if opts.logsdir and not opts.no_exec and len(scripts) > 1: subdir = os.path.basename(os.path.dirname(script)) lf = os.path.join(opts.origin, opts.logsdir, subdir, log_name) out = open(lf, 'w') err = None close_out = True else: out = stdout err = stderr close_out = False s = cr.run(script_command(script), stdout=out, stderr=err) if s and status == 0: status = s if close_out: out.close() out = None if int(this_revision) < int(TimeSCons_revision): # "Revert" the pieces that we previously updated to the # TimeSCons_revision, so the update to the next revision # works cleanly. command = (['svn', 'up', '-q', '-r', str(this_revision)] + TimeSCons_pieces) s = cr.run(command, stdout=stdout, stderr=stderr) if s: if status == 0: status = s continue if stdout not in (sys.stdout, None): stdout.close() stdout = None return status Usage = """\ time-scons.py [-hnq] [-r REVISION ...] [--branch BRANCH] [--logsdir DIR] [--svn] SCRIPT ...""" def main(argv=None): if argv is None: argv = sys.argv parser = optparse.OptionParser(usage=Usage) parser.add_option("--branch", metavar="BRANCH", default="trunk", help="time revision on BRANCH") parser.add_option("--logsdir", metavar="DIR", default='.', help="generate separate log files for each revision") parser.add_option("-n", "--no-exec", action="store_true", help="no execute, just print the command line") parser.add_option("-q", "--quiet", action="store_true", help="quiet, don't print the command line") parser.add_option("-r", "--revision", metavar="REVISION", help="time specified revisions") parser.add_option("--svn", action="store_true", help="fetch actual revisions for BRANCH") opts, scripts = parser.parse_args(argv[1:]) if not scripts: sys.stderr.write('No scripts specified.\n') sys.exit(1) CommandRunner.verbose = not opts.quiet CommandRunner.active = not opts.no_exec cr = CommandRunner() os.environ['TESTSCONS_SCONSFLAGS'] = '' branch = SubversionURL + '/' + opts.branch if opts.svn: revisions = get_svn_revisions(branch, opts.revision) elif opts.revision: # TODO(sgk): parse this for SVN-style revision strings revisions = [opts.revision] else: revisions = None if opts.logsdir and not os.path.exists(opts.logsdir): os.makedirs(opts.logsdir) if revisions: opts.origin = os.getcwd() tempdir = tempfile.mkdtemp(prefix='time-scons-') try: os.chdir(tempdir) status = do_revisions(cr, opts, branch, revisions, scripts) finally: os.chdir(opts.origin) shutil.rmtree(tempdir) else: commands = prepare_commands() commands.extend([ script_command(script) for script in scripts ]) status = cr.run_list(commands, stdout=sys.stdout, stderr=sys.stderr) return status if __name__ == "__main__": sys.exit(main())
mit
vipulroxx/sympy
sympy/series/acceleration.py
98
3314
""" Convergence acceleration / extrapolation methods for series and sequences. References: Carl M. Bender & Steven A. Orszag, "Advanced Mathematical Methods for Scientists and Engineers: Asymptotic Methods and Perturbation Theory", Springer 1999. (Shanks transformation: pp. 368-375, Richardson extrapolation: pp. 375-377.) """ from __future__ import print_function, division from sympy import factorial, Integer, S from sympy.core.compatibility import range def richardson(A, k, n, N): """ Calculate an approximation for lim k->oo A(k) using Richardson extrapolation with the terms A(n), A(n+1), ..., A(n+N+1). Choosing N ~= 2*n often gives good results. A simple example is to calculate exp(1) using the limit definition. This limit converges slowly; n = 100 only produces two accurate digits: >>> from sympy.abc import n >>> e = (1 + 1/n)**n >>> print(round(e.subs(n, 100).evalf(), 10)) 2.7048138294 Richardson extrapolation with 11 appropriately chosen terms gives a value that is accurate to the indicated precision: >>> from sympy import E >>> from sympy.series.acceleration import richardson >>> print(round(richardson(e, n, 10, 20).evalf(), 10)) 2.7182818285 >>> print(round(E.evalf(), 10)) 2.7182818285 Another useful application is to speed up convergence of series. Computing 100 terms of the zeta(2) series 1/k**2 yields only two accurate digits: >>> from sympy.abc import k, n >>> from sympy import Sum >>> A = Sum(k**-2, (k, 1, n)) >>> print(round(A.subs(n, 100).evalf(), 10)) 1.6349839002 Richardson extrapolation performs much better: >>> from sympy import pi >>> print(round(richardson(A, n, 10, 20).evalf(), 10)) 1.6449340668 >>> print(round(((pi**2)/6).evalf(), 10)) # Exact value 1.6449340668 """ s = S.Zero for j in range(0, N + 1): s += A.subs(k, Integer(n + j)).doit() * (n + j)**N * (-1)**(j + N) / \ (factorial(j) * factorial(N - j)) return s def shanks(A, k, n, m=1): """ Calculate an approximation for lim k->oo A(k) using the n-term Shanks transformation S(A)(n). With m > 1, calculate the m-fold recursive Shanks transformation S(S(...S(A)...))(n). The Shanks transformation is useful for summing Taylor series that converge slowly near a pole or singularity, e.g. for log(2): >>> from sympy.abc import k, n >>> from sympy import Sum, Integer >>> from sympy.series.acceleration import shanks >>> A = Sum(Integer(-1)**(k+1) / k, (k, 1, n)) >>> print(round(A.subs(n, 100).doit().evalf(), 10)) 0.6881721793 >>> print(round(shanks(A, n, 25).evalf(), 10)) 0.6931396564 >>> print(round(shanks(A, n, 25, 5).evalf(), 10)) 0.6931471806 The correct value is 0.6931471805599453094172321215. """ table = [A.subs(k, Integer(j)).doit() for j in range(n + m + 2)] table2 = table[:] for i in range(1, m + 1): for j in range(i, n + m + 1): x, y, z = table[j - 1], table[j], table[j + 1] table2[j] = (z*x - y**2) / (z + x - 2*y) table = table2[:] return table[n]
bsd-3-clause
python-dirbtuves/it-brandos-egzaminai
exams/E2018/pagrindinis/u2/u2.py
1
1377
from itertools import islice from pathlib import Path from typing import Dict def seconds(v: int, m: int, s: int) -> int: # Ši funkcija verčia valandas, minutes ir sekundes į sekundes. return v * 3600 + m * 60 + s def save_results(path: Path, pabaiga: Dict[str, int]) -> None: with path.open('w') as f: # Rūšiuojame slidininkus pagal laiką ir vardus. for laikas, slidininkas in sorted((v, k) for k, v in pabaiga.items()): # Sekundes verčiame į minutes ir sekundes. m, s = divmod(laikas, 60) print(f'{slidininkas:<20}{m} {s}', file=f) def main(path: Path) -> None: startas: Dict[str, int] = {} pabaiga: Dict[str, int] = {} with open(path / 'U2.txt') as f: # Skaitome starto duomenis. n = int(next(f)) for eilute in islice(f, n): slidininkas = eilute[:20] laikas = map(int, eilute[20:].split()) startas[slidininkas] = seconds(*laikas) # Skaitome finišo duomenis. m = int(next(f)) for eilute in islice(f, m): slidininkas = eilute[:20] laikas = map(int, eilute[20:].split()) # Įsimename per kiek laiko sekundėmis slidininkas pasiekė finišą. pabaiga[slidininkas] = seconds(*laikas) - startas[slidininkas] save_results(path / 'U2rez.txt', pabaiga)
agpl-3.0
Woraufhin/logic
formula.py
1
1112
import itertools import string from abc import ABCMeta, abstractproperty import attr def is_valid_formula(inst, attr, value): if not isinstance(value, (Formula, str)): raise ValueError('{} is not a valid formula type.'.format(value)) class Formula(object): __metaclass__ = ABCMeta group = {'open': '(', 'close': ')'} @abstractproperty def token(self): pass @attr.s class Atomic(Formula): token = list(itertools.chain.from_iterable( [string.uppercase, string.lowercase])) exp = attr.ib(validator=is_valid_formula) @attr.s class And(Formula): token = ['^', '&'] left = attr.ib(validator=is_valid_formula) right = attr.ib(validator=is_valid_formula) @attr.s class Or(Formula): token = ['|'] left = attr.ib(validator=is_valid_formula) right = attr.ib(validator=is_valid_formula) @attr.s class Imply(Formula): token = ['>'] left = attr.ib(validator=is_valid_formula) right = attr.ib(validator=is_valid_formula) @attr.s class Not(Formula): token = ['~'] exp = attr.ib(validator=is_valid_formula)
mit
googleapis/python-dataflow-client
google/cloud/dataflow_v1beta3/types/snapshots.py
1
5677
# -*- 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. # import proto # type: ignore from google.protobuf import duration_pb2 # type: ignore from google.protobuf import timestamp_pb2 # type: ignore __protobuf__ = proto.module( package="google.dataflow.v1beta3", manifest={ "SnapshotState", "PubsubSnapshotMetadata", "Snapshot", "GetSnapshotRequest", "DeleteSnapshotRequest", "DeleteSnapshotResponse", "ListSnapshotsRequest", "ListSnapshotsResponse", }, ) class SnapshotState(proto.Enum): r"""Snapshot state.""" UNKNOWN_SNAPSHOT_STATE = 0 PENDING = 1 RUNNING = 2 READY = 3 FAILED = 4 DELETED = 5 class PubsubSnapshotMetadata(proto.Message): r"""Represents a Pubsub snapshot. Attributes: topic_name (str): The name of the Pubsub topic. snapshot_name (str): The name of the Pubsub snapshot. expire_time (google.protobuf.timestamp_pb2.Timestamp): The expire time of the Pubsub snapshot. """ topic_name = proto.Field(proto.STRING, number=1,) snapshot_name = proto.Field(proto.STRING, number=2,) expire_time = proto.Field(proto.MESSAGE, number=3, message=timestamp_pb2.Timestamp,) class Snapshot(proto.Message): r"""Represents a snapshot of a job. Attributes: id (str): The unique ID of this snapshot. project_id (str): The project this snapshot belongs to. source_job_id (str): The job this snapshot was created from. creation_time (google.protobuf.timestamp_pb2.Timestamp): The time this snapshot was created. ttl (google.protobuf.duration_pb2.Duration): The time after which this snapshot will be automatically deleted. state (google.cloud.dataflow_v1beta3.types.SnapshotState): State of the snapshot. pubsub_metadata (Sequence[google.cloud.dataflow_v1beta3.types.PubsubSnapshotMetadata]): PubSub snapshot metadata. description (str): User specified description of the snapshot. Maybe empty. disk_size_bytes (int): The disk byte size of the snapshot. Only available for snapshots in READY state. region (str): Cloud region where this snapshot lives in, e.g., "us-central1". """ id = proto.Field(proto.STRING, number=1,) project_id = proto.Field(proto.STRING, number=2,) source_job_id = proto.Field(proto.STRING, number=3,) creation_time = proto.Field( proto.MESSAGE, number=4, message=timestamp_pb2.Timestamp, ) ttl = proto.Field(proto.MESSAGE, number=5, message=duration_pb2.Duration,) state = proto.Field(proto.ENUM, number=6, enum="SnapshotState",) pubsub_metadata = proto.RepeatedField( proto.MESSAGE, number=7, message="PubsubSnapshotMetadata", ) description = proto.Field(proto.STRING, number=8,) disk_size_bytes = proto.Field(proto.INT64, number=9,) region = proto.Field(proto.STRING, number=10,) class GetSnapshotRequest(proto.Message): r"""Request to get information about a snapshot Attributes: project_id (str): The ID of the Cloud Platform project that the snapshot belongs to. snapshot_id (str): The ID of the snapshot. location (str): The location that contains this snapshot. """ project_id = proto.Field(proto.STRING, number=1,) snapshot_id = proto.Field(proto.STRING, number=2,) location = proto.Field(proto.STRING, number=3,) class DeleteSnapshotRequest(proto.Message): r"""Request to delete a snapshot. Attributes: project_id (str): The ID of the Cloud Platform project that the snapshot belongs to. snapshot_id (str): The ID of the snapshot. location (str): The location that contains this snapshot. """ project_id = proto.Field(proto.STRING, number=1,) snapshot_id = proto.Field(proto.STRING, number=2,) location = proto.Field(proto.STRING, number=3,) class DeleteSnapshotResponse(proto.Message): r"""Response from deleting a snapshot. """ class ListSnapshotsRequest(proto.Message): r"""Request to list snapshots. Attributes: project_id (str): The project ID to list snapshots for. job_id (str): If specified, list snapshots created from this job. location (str): The location to list snapshots in. """ project_id = proto.Field(proto.STRING, number=1,) job_id = proto.Field(proto.STRING, number=3,) location = proto.Field(proto.STRING, number=2,) class ListSnapshotsResponse(proto.Message): r"""List of snapshots. Attributes: snapshots (Sequence[google.cloud.dataflow_v1beta3.types.Snapshot]): Returned snapshots. """ snapshots = proto.RepeatedField(proto.MESSAGE, number=1, message="Snapshot",) __all__ = tuple(sorted(__protobuf__.manifest))
apache-2.0
bradleypj823/swift
test/unit/common/middleware/test_slo.py
9
83414
# -*- coding: utf-8 -*- # Copyright (c) 2013 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. from six.moves import range import hashlib import time import unittest from contextlib import nested from mock import patch from hashlib import md5 from swift.common import swob, utils from swift.common.exceptions import ListingIterError, SegmentError from swift.common.middleware import slo from swift.common.swob import Request, Response, HTTPException from swift.common.utils import quote, json, closing_if_possible from test.unit.common.middleware.helpers import FakeSwift test_xml_data = '''<?xml version="1.0" encoding="UTF-8"?> <static_large_object> <object_segment> <path>/cont/object</path> <etag>etagoftheobjectsegment</etag> <size_bytes>100</size_bytes> </object_segment> </static_large_object> ''' test_json_data = json.dumps([{'path': '/cont/object', 'etag': 'etagoftheobjectsegment', 'size_bytes': 100}]) def fake_start_response(*args, **kwargs): pass def md5hex(s): return hashlib.md5(s).hexdigest() class SloTestCase(unittest.TestCase): def setUp(self): self.app = FakeSwift() self.slo = slo.filter_factory({})(self.app) self.slo.min_segment_size = 1 self.slo.logger = self.app.logger def call_app(self, req, app=None, expect_exception=False): if app is None: app = self.app req.headers.setdefault("User-Agent", "Mozzarella Foxfire") status = [None] headers = [None] def start_response(s, h, ei=None): status[0] = s headers[0] = h body_iter = app(req.environ, start_response) body = '' caught_exc = None try: # appease the close-checker with closing_if_possible(body_iter): for chunk in body_iter: body += chunk except Exception as exc: if expect_exception: caught_exc = exc else: raise if expect_exception: return status[0], headers[0], body, caught_exc else: return status[0], headers[0], body def call_slo(self, req, **kwargs): return self.call_app(req, app=self.slo, **kwargs) class TestSloMiddleware(SloTestCase): def setUp(self): super(TestSloMiddleware, self).setUp() self.app.register( 'GET', '/', swob.HTTPOk, {}, 'passed') self.app.register( 'PUT', '/', swob.HTTPOk, {}, 'passed') def test_handle_multipart_no_obj(self): req = Request.blank('/') resp_iter = self.slo(req.environ, fake_start_response) self.assertEquals(self.app.calls, [('GET', '/')]) self.assertEquals(''.join(resp_iter), 'passed') def test_slo_header_assigned(self): req = Request.blank( '/v1/a/c/o', headers={'x-static-large-object': "true"}, environ={'REQUEST_METHOD': 'PUT'}) resp = ''.join(self.slo(req.environ, fake_start_response)) self.assertTrue( resp.startswith('X-Static-Large-Object is a reserved header')) def test_parse_input(self): self.assertRaises(HTTPException, slo.parse_input, 'some non json') data = json.dumps( [{'path': '/cont/object', 'etag': 'etagoftheobjecitsegment', 'size_bytes': 100}]) self.assertEquals('/cont/object', slo.parse_input(data)[0]['path']) class TestSloPutManifest(SloTestCase): def setUp(self): super(TestSloPutManifest, self).setUp() self.app.register( 'GET', '/', swob.HTTPOk, {}, 'passed') self.app.register( 'PUT', '/', swob.HTTPOk, {}, 'passed') self.app.register( 'HEAD', '/v1/AUTH_test/cont/object', swob.HTTPOk, {'Content-Length': '100', 'Etag': 'etagoftheobjectsegment'}, None) self.app.register( 'HEAD', '/v1/AUTH_test/cont/object2', swob.HTTPOk, {'Content-Length': '100', 'Etag': 'etagoftheobjectsegment'}, None) self.app.register( 'HEAD', '/v1/AUTH_test/cont/object\xe2\x99\xa1', swob.HTTPOk, {'Content-Length': '100', 'Etag': 'etagoftheobjectsegment'}, None) self.app.register( 'HEAD', '/v1/AUTH_test/cont/small_object', swob.HTTPOk, {'Content-Length': '10', 'Etag': 'etagoftheobjectsegment'}, None) self.app.register( 'HEAD', u'/v1/AUTH_test/cont/あ_1', swob.HTTPOk, {'Content-Length': '1', 'Etag': 'a'}, None) self.app.register( 'PUT', '/v1/AUTH_test/c/man', swob.HTTPCreated, {}, None) self.app.register( 'DELETE', '/v1/AUTH_test/c/man', swob.HTTPNoContent, {}, None) self.app.register( 'HEAD', '/v1/AUTH_test/checktest/a_1', swob.HTTPOk, {'Content-Length': '1', 'Etag': 'a'}, None) self.app.register( 'HEAD', '/v1/AUTH_test/checktest/badreq', swob.HTTPBadRequest, {}, None) self.app.register( 'HEAD', '/v1/AUTH_test/checktest/b_2', swob.HTTPOk, {'Content-Length': '2', 'Etag': 'b', 'Last-Modified': 'Fri, 01 Feb 2012 20:38:36 GMT'}, None) self.app.register( 'GET', '/v1/AUTH_test/checktest/slob', swob.HTTPOk, {'X-Static-Large-Object': 'true', 'Etag': 'slob-etag'}, None) self.app.register( 'PUT', '/v1/AUTH_test/checktest/man_3', swob.HTTPCreated, {}, None) def test_put_manifest_too_quick_fail(self): req = Request.blank('/v1/a/c/o') req.content_length = self.slo.max_manifest_size + 1 try: self.slo.handle_multipart_put(req, fake_start_response) except HTTPException as e: pass self.assertEquals(e.status_int, 413) with patch.object(self.slo, 'max_manifest_segments', 0): req = Request.blank('/v1/a/c/o', body=test_json_data) e = None try: self.slo.handle_multipart_put(req, fake_start_response) except HTTPException as e: pass self.assertEquals(e.status_int, 413) with patch.object(self.slo, 'min_segment_size', 1000): test_json_data_2obj = json.dumps( [{'path': '/cont/small_object1', 'etag': 'etagoftheobjectsegment', 'size_bytes': 10}, {'path': '/cont/small_object2', 'etag': 'etagoftheobjectsegment', 'size_bytes': 10}]) req = Request.blank('/v1/a/c/o', body=test_json_data_2obj) try: self.slo.handle_multipart_put(req, fake_start_response) except HTTPException as e: pass self.assertEquals(e.status_int, 400) req = Request.blank('/v1/a/c/o', headers={'X-Copy-From': 'lala'}) try: self.slo.handle_multipart_put(req, fake_start_response) except HTTPException as e: pass self.assertEquals(e.status_int, 405) # ignores requests to / req = Request.blank( '/?multipart-manifest=put', environ={'REQUEST_METHOD': 'PUT'}, body=test_json_data) self.assertEquals( list(self.slo.handle_multipart_put(req, fake_start_response)), ['passed']) def test_handle_multipart_put_success(self): req = Request.blank( '/v1/AUTH_test/c/man?multipart-manifest=put', environ={'REQUEST_METHOD': 'PUT'}, headers={'Accept': 'test'}, body=test_json_data) self.assertTrue('X-Static-Large-Object' not in req.headers) def my_fake_start_response(*args, **kwargs): gen_etag = '"' + md5('etagoftheobjectsegment').hexdigest() + '"' self.assertTrue(('Etag', gen_etag) in args[1]) self.slo(req.environ, my_fake_start_response) self.assertTrue('X-Static-Large-Object' in req.headers) def test_handle_multipart_put_success_allow_small_last_segment(self): with patch.object(self.slo, 'min_segment_size', 50): test_json_data = json.dumps([{'path': '/cont/object', 'etag': 'etagoftheobjectsegment', 'size_bytes': 100}, {'path': '/cont/small_object', 'etag': 'etagoftheobjectsegment', 'size_bytes': 10}]) req = Request.blank( '/v1/AUTH_test/c/man?multipart-manifest=put', environ={'REQUEST_METHOD': 'PUT'}, headers={'Accept': 'test'}, body=test_json_data) self.assertTrue('X-Static-Large-Object' not in req.headers) self.slo(req.environ, fake_start_response) self.assertTrue('X-Static-Large-Object' in req.headers) def test_handle_multipart_put_success_allow_only_one_small_segment(self): with patch.object(self.slo, 'min_segment_size', 50): test_json_data = json.dumps([{'path': '/cont/small_object', 'etag': 'etagoftheobjectsegment', 'size_bytes': 10}]) req = Request.blank( '/v1/AUTH_test/c/man?multipart-manifest=put', environ={'REQUEST_METHOD': 'PUT'}, headers={'Accept': 'test'}, body=test_json_data) self.assertTrue('X-Static-Large-Object' not in req.headers) self.slo(req.environ, fake_start_response) self.assertTrue('X-Static-Large-Object' in req.headers) def test_handle_multipart_put_disallow_small_first_segment(self): with patch.object(self.slo, 'min_segment_size', 50): test_json_data = json.dumps([{'path': '/cont/object', 'etag': 'etagoftheobjectsegment', 'size_bytes': 10}, {'path': '/cont/small_object', 'etag': 'etagoftheobjectsegment', 'size_bytes': 100}]) req = Request.blank('/v1/a/c/o', body=test_json_data) try: self.slo.handle_multipart_put(req, fake_start_response) except HTTPException as e: pass self.assertEquals(e.status_int, 400) def test_handle_multipart_put_success_unicode(self): test_json_data = json.dumps([{'path': u'/cont/object\u2661', 'etag': 'etagoftheobjectsegment', 'size_bytes': 100}]) req = Request.blank( '/v1/AUTH_test/c/man?multipart-manifest=put', environ={'REQUEST_METHOD': 'PUT'}, headers={'Accept': 'test'}, body=test_json_data) self.assertTrue('X-Static-Large-Object' not in req.headers) self.slo(req.environ, fake_start_response) self.assertTrue('X-Static-Large-Object' in req.headers) self.assertTrue(req.environ['PATH_INFO'], '/cont/object\xe2\x99\xa1') def test_handle_multipart_put_no_xml(self): req = Request.blank( '/test_good/AUTH_test/c/man?multipart-manifest=put', environ={'REQUEST_METHOD': 'PUT'}, headers={'Accept': 'test'}, body=test_xml_data) no_xml = self.slo(req.environ, fake_start_response) self.assertEquals(no_xml, ['Manifest must be valid json.']) def test_handle_multipart_put_bad_data(self): bad_data = json.dumps([{'path': '/cont/object', 'etag': 'etagoftheobj', 'size_bytes': 'lala'}]) req = Request.blank( '/test_good/AUTH_test/c/man?multipart-manifest=put', environ={'REQUEST_METHOD': 'PUT'}, body=bad_data) self.assertRaises(HTTPException, self.slo.handle_multipart_put, req, fake_start_response) for bad_data in [ json.dumps([{'path': '/cont', 'etag': 'etagoftheobj', 'size_bytes': 100}]), json.dumps('asdf'), json.dumps(None), json.dumps(5), 'not json', '1234', None, '', json.dumps({'path': None}), json.dumps([{'path': '/cont/object', 'etag': None, 'size_bytes': 12}]), json.dumps([{'path': '/cont/object', 'etag': 'asdf', 'size_bytes': 'sd'}]), json.dumps([{'path': 12, 'etag': 'etagoftheobj', 'size_bytes': 100}]), json.dumps([{'path': u'/cont/object\u2661', 'etag': 'etagoftheobj', 'size_bytes': 100}]), json.dumps([{'path': 12, 'size_bytes': 100}]), json.dumps([{'path': 12, 'size_bytes': 100}]), json.dumps([{'path': None, 'etag': 'etagoftheobj', 'size_bytes': 100}])]: req = Request.blank( '/v1/AUTH_test/c/man?multipart-manifest=put', environ={'REQUEST_METHOD': 'PUT'}, body=bad_data) self.assertRaises(HTTPException, self.slo.handle_multipart_put, req, fake_start_response) def test_handle_multipart_put_check_data(self): good_data = json.dumps( [{'path': '/checktest/a_1', 'etag': 'a', 'size_bytes': '1'}, {'path': '/checktest/b_2', 'etag': 'b', 'size_bytes': '2'}]) req = Request.blank( '/v1/AUTH_test/checktest/man_3?multipart-manifest=put', environ={'REQUEST_METHOD': 'PUT'}, body=good_data) status, headers, body = self.call_slo(req) self.assertEquals(self.app.call_count, 3) # go behind SLO's back and see what actually got stored req = Request.blank( # this string looks weird, but it's just an artifact # of FakeSwift '/v1/AUTH_test/checktest/man_3?multipart-manifest=put', environ={'REQUEST_METHOD': 'GET'}) status, headers, body = self.call_app(req) headers = dict(headers) manifest_data = json.loads(body) self.assertTrue(headers['Content-Type'].endswith(';swift_bytes=3')) self.assertEquals(len(manifest_data), 2) self.assertEquals(manifest_data[0]['hash'], 'a') self.assertEquals(manifest_data[0]['bytes'], 1) self.assertTrue( not manifest_data[0]['last_modified'].startswith('2012')) self.assertTrue(manifest_data[1]['last_modified'].startswith('2012')) def test_handle_multipart_put_check_data_bad(self): bad_data = json.dumps( [{'path': '/checktest/a_1', 'etag': 'a', 'size_bytes': '2'}, {'path': '/checktest/badreq', 'etag': 'a', 'size_bytes': '1'}, {'path': '/checktest/b_2', 'etag': 'not-b', 'size_bytes': '2'}, {'path': '/checktest/slob', 'etag': 'not-slob', 'size_bytes': '2'}]) req = Request.blank( '/v1/AUTH_test/checktest/man?multipart-manifest=put', environ={'REQUEST_METHOD': 'PUT'}, headers={'Accept': 'application/json'}, body=bad_data) status, headers, body = self.call_slo(req) self.assertEquals(self.app.call_count, 5) errors = json.loads(body)['Errors'] self.assertEquals(len(errors), 5) self.assertEquals(errors[0][0], '/checktest/a_1') self.assertEquals(errors[0][1], 'Size Mismatch') self.assertEquals(errors[1][0], '/checktest/badreq') self.assertEquals(errors[1][1], '400 Bad Request') self.assertEquals(errors[2][0], '/checktest/b_2') self.assertEquals(errors[2][1], 'Etag Mismatch') self.assertEquals(errors[3][0], '/checktest/slob') self.assertEquals(errors[3][1], 'Size Mismatch') self.assertEquals(errors[4][0], '/checktest/slob') self.assertEquals(errors[4][1], 'Etag Mismatch') def test_handle_multipart_put_manifest_equal_slo(self): test_json_data = json.dumps([{'path': '/cont/object', 'etag': 'etagoftheobjectsegment', 'size_bytes': 100}]) req = Request.blank( '/v1/AUTH_test/cont/object?multipart-manifest=put', environ={'REQUEST_METHOD': 'PUT'}, headers={'Accept': 'test'}, body=test_json_data) status, headers, body = self.call_slo(req) self.assertEqual(status, '409 Conflict') self.assertEqual(self.app.call_count, 0) def test_handle_multipart_put_manifest_equal_slo_non_ascii(self): test_json_data = json.dumps([{'path': u'/cont/あ_1', 'etag': 'a', 'size_bytes': 1}]) path = quote(u'/v1/AUTH_test/cont/あ_1') req = Request.blank( path + '?multipart-manifest=put', environ={'REQUEST_METHOD': 'PUT'}, headers={'Accept': 'test'}, body=test_json_data) status, headers, body = self.call_slo(req) self.assertEqual(status, '409 Conflict') self.assertEqual(self.app.call_count, 0) def test_handle_multipart_put_manifest_equal_last_segment(self): test_json_data = json.dumps([{'path': '/cont/object', 'etag': 'etagoftheobjectsegment', 'size_bytes': 100}, {'path': '/cont/object2', 'etag': 'etagoftheobjectsegment', 'size_bytes': 100}]) req = Request.blank( '/v1/AUTH_test/cont/object2?multipart-manifest=put', environ={'REQUEST_METHOD': 'PUT'}, headers={'Accept': 'test'}, body=test_json_data) status, headers, body = self.call_slo(req) self.assertEqual(status, '409 Conflict') self.assertEqual(self.app.call_count, 1) def test_handle_multipart_put_skip_size_check(self): good_data = json.dumps( [{'path': '/checktest/a_1', 'etag': 'a', 'size_bytes': None}, {'path': '/checktest/b_2', 'etag': 'b', 'size_bytes': None}]) req = Request.blank( '/v1/AUTH_test/checktest/man_3?multipart-manifest=put', environ={'REQUEST_METHOD': 'PUT'}, body=good_data) status, headers, body = self.call_slo(req) self.assertEquals(self.app.call_count, 3) # Check that we still populated the manifest properly from our HEADs req = Request.blank( # this string looks weird, but it's just an artifact # of FakeSwift '/v1/AUTH_test/checktest/man_3?multipart-manifest=put', environ={'REQUEST_METHOD': 'GET'}) status, headers, body = self.call_app(req) manifest_data = json.loads(body) self.assertEquals(1, manifest_data[0]['bytes']) self.assertEquals(2, manifest_data[1]['bytes']) def test_handle_multipart_put_skip_size_check_still_uses_min_size(self): with patch.object(self.slo, 'min_segment_size', 50): test_json_data = json.dumps([{'path': '/cont/small_object', 'etag': 'etagoftheobjectsegment', 'size_bytes': None}, {'path': '/cont/small_object', 'etag': 'etagoftheobjectsegment', 'size_bytes': 100}]) req = Request.blank('/v1/AUTH_test/c/o', body=test_json_data) with self.assertRaises(HTTPException) as cm: self.slo.handle_multipart_put(req, fake_start_response) self.assertEquals(cm.exception.status_int, 400) def test_handle_multipart_put_skip_etag_check(self): good_data = json.dumps( [{'path': '/checktest/a_1', 'etag': None, 'size_bytes': 1}, {'path': '/checktest/b_2', 'etag': None, 'size_bytes': 2}]) req = Request.blank( '/v1/AUTH_test/checktest/man_3?multipart-manifest=put', environ={'REQUEST_METHOD': 'PUT'}, body=good_data) status, headers, body = self.call_slo(req) self.assertEquals(self.app.call_count, 3) # Check that we still populated the manifest properly from our HEADs req = Request.blank( # this string looks weird, but it's just an artifact # of FakeSwift '/v1/AUTH_test/checktest/man_3?multipart-manifest=put', environ={'REQUEST_METHOD': 'GET'}) status, headers, body = self.call_app(req) manifest_data = json.loads(body) self.assertEquals('a', manifest_data[0]['hash']) self.assertEquals('b', manifest_data[1]['hash']) class TestSloDeleteManifest(SloTestCase): def setUp(self): super(TestSloDeleteManifest, self).setUp() _submanifest_data = json.dumps( [{'name': '/deltest/b_2', 'hash': 'a', 'bytes': '1'}, {'name': '/deltest/c_3', 'hash': 'b', 'bytes': '2'}]) self.app.register( 'GET', '/v1/AUTH_test/deltest/man_404', swob.HTTPNotFound, {}, None) self.app.register( 'GET', '/v1/AUTH_test/deltest/man', swob.HTTPOk, {'Content-Type': 'application/json', 'X-Static-Large-Object': 'true'}, json.dumps([{'name': '/deltest/gone', 'hash': 'a', 'bytes': '1'}, {'name': '/deltest/b_2', 'hash': 'b', 'bytes': '2'}])) self.app.register( 'DELETE', '/v1/AUTH_test/deltest/man', swob.HTTPNoContent, {}, None) self.app.register( 'GET', '/v1/AUTH_test/deltest/man-all-there', swob.HTTPOk, {'Content-Type': 'application/json', 'X-Static-Large-Object': 'true'}, json.dumps([{'name': '/deltest/b_2', 'hash': 'a', 'bytes': '1'}, {'name': '/deltest/c_3', 'hash': 'b', 'bytes': '2'}])) self.app.register( 'DELETE', '/v1/AUTH_test/deltest/man-all-there', swob.HTTPNoContent, {}, None) self.app.register( 'DELETE', '/v1/AUTH_test/deltest/gone', swob.HTTPNotFound, {}, None) self.app.register( 'GET', '/v1/AUTH_test/deltest/a_1', swob.HTTPOk, {'Content-Length': '1'}, 'a') self.app.register( 'DELETE', '/v1/AUTH_test/deltest/a_1', swob.HTTPNoContent, {}, None) self.app.register( 'DELETE', '/v1/AUTH_test/deltest/b_2', swob.HTTPNoContent, {}, None) self.app.register( 'DELETE', '/v1/AUTH_test/deltest/c_3', swob.HTTPNoContent, {}, None) self.app.register( 'DELETE', '/v1/AUTH_test/deltest/d_3', swob.HTTPNoContent, {}, None) self.app.register( 'GET', '/v1/AUTH_test/deltest/manifest-with-submanifest', swob.HTTPOk, {'Content-Type': 'application/json', 'X-Static-Large-Object': 'true'}, json.dumps([{'name': '/deltest/a_1', 'hash': 'a', 'bytes': '1'}, {'name': '/deltest/submanifest', 'sub_slo': True, 'hash': 'submanifest-etag', 'bytes': len(_submanifest_data)}, {'name': '/deltest/d_3', 'hash': 'd', 'bytes': '3'}])) self.app.register( 'DELETE', '/v1/AUTH_test/deltest/manifest-with-submanifest', swob.HTTPNoContent, {}, None) self.app.register( 'GET', '/v1/AUTH_test/deltest/submanifest', swob.HTTPOk, {'Content-Type': 'application/json', 'X-Static-Large-Object': 'true'}, _submanifest_data) self.app.register( 'DELETE', '/v1/AUTH_test/deltest/submanifest', swob.HTTPNoContent, {}, None) self.app.register( 'GET', '/v1/AUTH_test/deltest/manifest-missing-submanifest', swob.HTTPOk, {'Content-Type': 'application/json', 'X-Static-Large-Object': 'true'}, json.dumps([{'name': '/deltest/a_1', 'hash': 'a', 'bytes': '1'}, {'name': '/deltest/missing-submanifest', 'hash': 'a', 'bytes': '2', 'sub_slo': True}, {'name': '/deltest/d_3', 'hash': 'd', 'bytes': '3'}])) self.app.register( 'DELETE', '/v1/AUTH_test/deltest/manifest-missing-submanifest', swob.HTTPNoContent, {}, None) self.app.register( 'GET', '/v1/AUTH_test/deltest/missing-submanifest', swob.HTTPNotFound, {}, None) self.app.register( 'GET', '/v1/AUTH_test/deltest/manifest-badjson', swob.HTTPOk, {'Content-Type': 'application/json', 'X-Static-Large-Object': 'true'}, "[not {json (at ++++all") self.app.register( 'GET', '/v1/AUTH_test/deltest/manifest-with-unauth-segment', swob.HTTPOk, {'Content-Type': 'application/json', 'X-Static-Large-Object': 'true'}, json.dumps([{'name': '/deltest/a_1', 'hash': 'a', 'bytes': '1'}, {'name': '/deltest-unauth/q_17', 'hash': '11', 'bytes': '17'}])) self.app.register( 'DELETE', '/v1/AUTH_test/deltest/manifest-with-unauth-segment', swob.HTTPNoContent, {}, None) self.app.register( 'DELETE', '/v1/AUTH_test/deltest-unauth/q_17', swob.HTTPUnauthorized, {}, None) def test_handle_multipart_delete_man(self): req = Request.blank( '/v1/AUTH_test/deltest/man', environ={'REQUEST_METHOD': 'DELETE'}) self.slo(req.environ, fake_start_response) self.assertEquals(self.app.call_count, 1) def test_handle_multipart_delete_bad_utf8(self): req = Request.blank( '/v1/AUTH_test/deltest/man\xff\xfe?multipart-manifest=delete', environ={'REQUEST_METHOD': 'DELETE', 'HTTP_ACCEPT': 'application/json'}) status, headers, body = self.call_slo(req) self.assertEquals(status, '200 OK') resp_data = json.loads(body) self.assertEquals(resp_data['Response Status'], '412 Precondition Failed') def test_handle_multipart_delete_whole_404(self): req = Request.blank( '/v1/AUTH_test/deltest/man_404?multipart-manifest=delete', environ={'REQUEST_METHOD': 'DELETE', 'HTTP_ACCEPT': 'application/json'}) status, headers, body = self.call_slo(req) resp_data = json.loads(body) self.assertEquals( self.app.calls, [('GET', '/v1/AUTH_test/deltest/man_404?multipart-manifest=get')]) self.assertEquals(resp_data['Response Status'], '200 OK') self.assertEquals(resp_data['Response Body'], '') self.assertEquals(resp_data['Number Deleted'], 0) self.assertEquals(resp_data['Number Not Found'], 1) self.assertEquals(resp_data['Errors'], []) def test_handle_multipart_delete_segment_404(self): req = Request.blank( '/v1/AUTH_test/deltest/man?multipart-manifest=delete', environ={'REQUEST_METHOD': 'DELETE', 'HTTP_ACCEPT': 'application/json'}) status, headers, body = self.call_slo(req) resp_data = json.loads(body) self.assertEquals( self.app.calls, [('GET', '/v1/AUTH_test/deltest/man?multipart-manifest=get'), ('DELETE', '/v1/AUTH_test/deltest/gone?multipart-manifest=delete'), ('DELETE', '/v1/AUTH_test/deltest/b_2?multipart-manifest=delete'), ('DELETE', '/v1/AUTH_test/deltest/man?multipart-manifest=delete')]) self.assertEquals(resp_data['Response Status'], '200 OK') self.assertEquals(resp_data['Number Deleted'], 2) self.assertEquals(resp_data['Number Not Found'], 1) def test_handle_multipart_delete_whole(self): req = Request.blank( '/v1/AUTH_test/deltest/man-all-there?multipart-manifest=delete', environ={'REQUEST_METHOD': 'DELETE'}) self.call_slo(req) self.assertEquals( self.app.calls, [('GET', '/v1/AUTH_test/deltest/man-all-there?multipart-manifest=get'), ('DELETE', '/v1/AUTH_test/deltest/b_2?multipart-manifest=delete'), ('DELETE', '/v1/AUTH_test/deltest/c_3?multipart-manifest=delete'), ('DELETE', ('/v1/AUTH_test/deltest/' + 'man-all-there?multipart-manifest=delete'))]) def test_handle_multipart_delete_nested(self): req = Request.blank( '/v1/AUTH_test/deltest/manifest-with-submanifest?' + 'multipart-manifest=delete', environ={'REQUEST_METHOD': 'DELETE'}) self.call_slo(req) self.assertEquals( set(self.app.calls), set([('GET', '/v1/AUTH_test/deltest/' + 'manifest-with-submanifest?multipart-manifest=get'), ('GET', '/v1/AUTH_test/deltest/' + 'submanifest?multipart-manifest=get'), ('DELETE', '/v1/AUTH_test/deltest/a_1?multipart-manifest=delete'), ('DELETE', '/v1/AUTH_test/deltest/b_2?multipart-manifest=delete'), ('DELETE', '/v1/AUTH_test/deltest/c_3?multipart-manifest=delete'), ('DELETE', '/v1/AUTH_test/deltest/' + 'submanifest?multipart-manifest=delete'), ('DELETE', '/v1/AUTH_test/deltest/d_3?multipart-manifest=delete'), ('DELETE', '/v1/AUTH_test/deltest/' + 'manifest-with-submanifest?multipart-manifest=delete')])) def test_handle_multipart_delete_nested_too_many_segments(self): req = Request.blank( '/v1/AUTH_test/deltest/manifest-with-submanifest?' + 'multipart-manifest=delete', environ={'REQUEST_METHOD': 'DELETE', 'HTTP_ACCEPT': 'application/json'}) with patch.object(slo, 'MAX_BUFFERED_SLO_SEGMENTS', 1): status, headers, body = self.call_slo(req) self.assertEquals(status, '200 OK') resp_data = json.loads(body) self.assertEquals(resp_data['Response Status'], '400 Bad Request') self.assertEquals(resp_data['Response Body'], 'Too many buffered slo segments to delete.') def test_handle_multipart_delete_nested_404(self): req = Request.blank( '/v1/AUTH_test/deltest/manifest-missing-submanifest' + '?multipart-manifest=delete', environ={'REQUEST_METHOD': 'DELETE', 'HTTP_ACCEPT': 'application/json'}) status, headers, body = self.call_slo(req) resp_data = json.loads(body) self.assertEquals( self.app.calls, [('GET', '/v1/AUTH_test/deltest/' + 'manifest-missing-submanifest?multipart-manifest=get'), ('DELETE', '/v1/AUTH_test/deltest/a_1?multipart-manifest=delete'), ('GET', '/v1/AUTH_test/deltest/' + 'missing-submanifest?multipart-manifest=get'), ('DELETE', '/v1/AUTH_test/deltest/d_3?multipart-manifest=delete'), ('DELETE', '/v1/AUTH_test/deltest/' + 'manifest-missing-submanifest?multipart-manifest=delete')]) self.assertEquals(resp_data['Response Status'], '200 OK') self.assertEquals(resp_data['Response Body'], '') self.assertEquals(resp_data['Number Deleted'], 3) self.assertEquals(resp_data['Number Not Found'], 1) self.assertEquals(resp_data['Errors'], []) def test_handle_multipart_delete_nested_401(self): self.app.register( 'GET', '/v1/AUTH_test/deltest/submanifest', swob.HTTPUnauthorized, {}, None) req = Request.blank( ('/v1/AUTH_test/deltest/manifest-with-submanifest' + '?multipart-manifest=delete'), environ={'REQUEST_METHOD': 'DELETE', 'HTTP_ACCEPT': 'application/json'}) status, headers, body = self.call_slo(req) self.assertEquals(status, '200 OK') resp_data = json.loads(body) self.assertEquals(resp_data['Response Status'], '400 Bad Request') self.assertEquals(resp_data['Errors'], [['/deltest/submanifest', '401 Unauthorized']]) def test_handle_multipart_delete_nested_500(self): self.app.register( 'GET', '/v1/AUTH_test/deltest/submanifest', swob.HTTPServerError, {}, None) req = Request.blank( ('/v1/AUTH_test/deltest/manifest-with-submanifest' + '?multipart-manifest=delete'), environ={'REQUEST_METHOD': 'DELETE', 'HTTP_ACCEPT': 'application/json'}) status, headers, body = self.call_slo(req) self.assertEquals(status, '200 OK') resp_data = json.loads(body) self.assertEquals(resp_data['Response Status'], '400 Bad Request') self.assertEquals(resp_data['Errors'], [['/deltest/submanifest', 'Unable to load SLO manifest or segment.']]) def test_handle_multipart_delete_not_a_manifest(self): req = Request.blank( '/v1/AUTH_test/deltest/a_1?multipart-manifest=delete', environ={'REQUEST_METHOD': 'DELETE', 'HTTP_ACCEPT': 'application/json'}) status, headers, body = self.call_slo(req) resp_data = json.loads(body) self.assertEquals( self.app.calls, [('GET', '/v1/AUTH_test/deltest/a_1?multipart-manifest=get')]) self.assertEquals(resp_data['Response Status'], '400 Bad Request') self.assertEquals(resp_data['Response Body'], '') self.assertEquals(resp_data['Number Deleted'], 0) self.assertEquals(resp_data['Number Not Found'], 0) self.assertEquals(resp_data['Errors'], [['/deltest/a_1', 'Not an SLO manifest']]) def test_handle_multipart_delete_bad_json(self): req = Request.blank( '/v1/AUTH_test/deltest/manifest-badjson?multipart-manifest=delete', environ={'REQUEST_METHOD': 'DELETE', 'HTTP_ACCEPT': 'application/json'}) status, headers, body = self.call_slo(req) resp_data = json.loads(body) self.assertEquals(self.app.calls, [('GET', '/v1/AUTH_test/deltest/' + 'manifest-badjson?multipart-manifest=get')]) self.assertEquals(resp_data['Response Status'], '400 Bad Request') self.assertEquals(resp_data['Response Body'], '') self.assertEquals(resp_data['Number Deleted'], 0) self.assertEquals(resp_data['Number Not Found'], 0) self.assertEquals(resp_data['Errors'], [['/deltest/manifest-badjson', 'Unable to load SLO manifest']]) def test_handle_multipart_delete_401(self): req = Request.blank( '/v1/AUTH_test/deltest/manifest-with-unauth-segment' + '?multipart-manifest=delete', environ={'REQUEST_METHOD': 'DELETE', 'HTTP_ACCEPT': 'application/json'}) status, headers, body = self.call_slo(req) resp_data = json.loads(body) self.assertEquals( self.app.calls, [('GET', '/v1/AUTH_test/deltest/' + 'manifest-with-unauth-segment?multipart-manifest=get'), ('DELETE', '/v1/AUTH_test/deltest/a_1?multipart-manifest=delete'), ('DELETE', '/v1/AUTH_test/deltest-unauth/' + 'q_17?multipart-manifest=delete'), ('DELETE', '/v1/AUTH_test/deltest/' + 'manifest-with-unauth-segment?multipart-manifest=delete')]) self.assertEquals(resp_data['Response Status'], '400 Bad Request') self.assertEquals(resp_data['Response Body'], '') self.assertEquals(resp_data['Number Deleted'], 2) self.assertEquals(resp_data['Number Not Found'], 0) self.assertEquals(resp_data['Errors'], [['/deltest-unauth/q_17', '401 Unauthorized']]) class TestSloHeadManifest(SloTestCase): def setUp(self): super(TestSloHeadManifest, self).setUp() self._manifest_json = json.dumps([ {'name': '/gettest/seg01', 'bytes': '100', 'hash': 'seg01-hash', 'content_type': 'text/plain', 'last_modified': '2013-11-19T11:33:45.137446'}, {'name': '/gettest/seg02', 'bytes': '200', 'hash': 'seg02-hash', 'content_type': 'text/plain', 'last_modified': '2013-11-19T11:33:45.137447'}]) self.app.register( 'GET', '/v1/AUTH_test/headtest/man', swob.HTTPOk, {'Content-Length': str(len(self._manifest_json)), 'X-Static-Large-Object': 'true', 'Etag': md5(self._manifest_json).hexdigest()}, self._manifest_json) def test_etag_is_hash_of_segment_etags(self): req = Request.blank( '/v1/AUTH_test/headtest/man', environ={'REQUEST_METHOD': 'HEAD'}) status, headers, body = self.call_slo(req) headers = swob.HeaderKeyDict(headers) self.assertEqual(status, '200 OK') self.assertEqual(headers.get('Etag', '').strip("'\""), md5("seg01-hashseg02-hash").hexdigest()) self.assertEqual(body, '') # it's a HEAD request, after all def test_etag_matching(self): etag = md5("seg01-hashseg02-hash").hexdigest() req = Request.blank( '/v1/AUTH_test/headtest/man', environ={'REQUEST_METHOD': 'HEAD'}, headers={'If-None-Match': etag}) status, headers, body = self.call_slo(req) self.assertEqual(status, '304 Not Modified') class TestSloGetManifest(SloTestCase): def setUp(self): super(TestSloGetManifest, self).setUp() _bc_manifest_json = json.dumps( [{'name': '/gettest/b_10', 'hash': md5hex('b' * 10), 'bytes': '10', 'content_type': 'text/plain'}, {'name': '/gettest/c_15', 'hash': md5hex('c' * 15), 'bytes': '15', 'content_type': 'text/plain'}]) # some plain old objects self.app.register( 'GET', '/v1/AUTH_test/gettest/a_5', swob.HTTPOk, {'Content-Length': '5', 'Etag': md5hex('a' * 5)}, 'a' * 5) self.app.register( 'GET', '/v1/AUTH_test/gettest/b_10', swob.HTTPOk, {'Content-Length': '10', 'Etag': md5hex('b' * 10)}, 'b' * 10) self.app.register( 'GET', '/v1/AUTH_test/gettest/c_15', swob.HTTPOk, {'Content-Length': '15', 'Etag': md5hex('c' * 15)}, 'c' * 15) self.app.register( 'GET', '/v1/AUTH_test/gettest/d_20', swob.HTTPOk, {'Content-Length': '20', 'Etag': md5hex('d' * 20)}, 'd' * 20) self.app.register( 'GET', '/v1/AUTH_test/gettest/manifest-bc', swob.HTTPOk, {'Content-Type': 'application/json;swift_bytes=25', 'X-Static-Large-Object': 'true', 'X-Object-Meta-Plant': 'Ficus', 'Etag': md5hex(_bc_manifest_json)}, _bc_manifest_json) _abcd_manifest_json = json.dumps( [{'name': '/gettest/a_5', 'hash': md5hex("a" * 5), 'content_type': 'text/plain', 'bytes': '5'}, {'name': '/gettest/manifest-bc', 'sub_slo': True, 'content_type': 'application/json;swift_bytes=25', 'hash': md5hex(md5hex("b" * 10) + md5hex("c" * 15)), 'bytes': len(_bc_manifest_json)}, {'name': '/gettest/d_20', 'hash': md5hex("d" * 20), 'content_type': 'text/plain', 'bytes': '20'}]) self.app.register( 'GET', '/v1/AUTH_test/gettest/manifest-abcd', swob.HTTPOk, {'Content-Type': 'application/json', 'X-Static-Large-Object': 'true', 'Etag': md5(_abcd_manifest_json).hexdigest()}, _abcd_manifest_json) self.manifest_abcd_etag = md5hex( md5hex("a" * 5) + md5hex(md5hex("b" * 10) + md5hex("c" * 15)) + md5hex("d" * 20)) self.app.register( 'GET', '/v1/AUTH_test/gettest/manifest-badjson', swob.HTTPOk, {'Content-Type': 'application/json', 'X-Static-Large-Object': 'true', 'X-Object-Meta-Fish': 'Bass'}, "[not {json (at ++++all") def tearDown(self): self.assertEqual(self.app.unclosed_requests, {}) def test_get_manifest_passthrough(self): req = Request.blank( '/v1/AUTH_test/gettest/manifest-bc?multipart-manifest=get', environ={'REQUEST_METHOD': 'GET', 'HTTP_ACCEPT': 'application/json'}) status, headers, body = self.call_slo(req) self.assertEqual(status, '200 OK') self.assertTrue( ('Content-Type', 'application/json; charset=utf-8') in headers, headers) try: resp_data = json.loads(body) except ValueError: self.fail("Invalid JSON in manifest GET: %r" % body) self.assertEqual( resp_data, [{'hash': md5hex('b' * 10), 'bytes': '10', 'name': '/gettest/b_10', 'content_type': 'text/plain'}, {'hash': md5hex('c' * 15), 'bytes': '15', 'name': '/gettest/c_15', 'content_type': 'text/plain'}], body) def test_get_nonmanifest_passthrough(self): req = Request.blank( '/v1/AUTH_test/gettest/a_5', environ={'REQUEST_METHOD': 'GET'}) status, headers, body = self.call_slo(req) self.assertEqual(status, '200 OK') self.assertEqual(body, 'aaaaa') def test_get_manifest(self): req = Request.blank( '/v1/AUTH_test/gettest/manifest-bc', environ={'REQUEST_METHOD': 'GET'}) status, headers, body = self.call_slo(req) headers = swob.HeaderKeyDict(headers) manifest_etag = md5hex(md5hex("b" * 10) + md5hex("c" * 15)) self.assertEqual(status, '200 OK') self.assertEqual(headers['Content-Length'], '25') self.assertEqual(headers['Etag'], '"%s"' % manifest_etag) self.assertEqual(headers['X-Object-Meta-Plant'], 'Ficus') self.assertEqual(body, 'bbbbbbbbbbccccccccccccccc') for _, _, hdrs in self.app.calls_with_headers[1:]: ua = hdrs.get("User-Agent", "") self.assertTrue("SLO MultipartGET" in ua) self.assertFalse("SLO MultipartGET SLO MultipartGET" in ua) # the first request goes through unaltered first_ua = self.app.calls_with_headers[0][2].get("User-Agent") self.assertFalse( "SLO MultipartGET" in first_ua) def test_if_none_match_matches(self): req = Request.blank( '/v1/AUTH_test/gettest/manifest-abcd', environ={'REQUEST_METHOD': 'GET'}, headers={'If-None-Match': self.manifest_abcd_etag}) status, headers, body = self.call_slo(req) headers = swob.HeaderKeyDict(headers) self.assertEqual(status, '304 Not Modified') self.assertEqual(headers['Content-Length'], '0') self.assertEqual(body, '') def test_if_none_match_does_not_match(self): req = Request.blank( '/v1/AUTH_test/gettest/manifest-abcd', environ={'REQUEST_METHOD': 'GET'}, headers={'If-None-Match': "not-%s" % self.manifest_abcd_etag}) status, headers, body = self.call_slo(req) headers = swob.HeaderKeyDict(headers) self.assertEqual(status, '200 OK') self.assertEqual( body, 'aaaaabbbbbbbbbbcccccccccccccccdddddddddddddddddddd') def test_if_match_matches(self): req = Request.blank( '/v1/AUTH_test/gettest/manifest-abcd', environ={'REQUEST_METHOD': 'GET'}, headers={'If-Match': self.manifest_abcd_etag}) status, headers, body = self.call_slo(req) headers = swob.HeaderKeyDict(headers) self.assertEqual(status, '200 OK') self.assertEqual( body, 'aaaaabbbbbbbbbbcccccccccccccccdddddddddddddddddddd') def test_if_match_does_not_match(self): req = Request.blank( '/v1/AUTH_test/gettest/manifest-abcd', environ={'REQUEST_METHOD': 'GET'}, headers={'If-Match': "not-%s" % self.manifest_abcd_etag}) status, headers, body = self.call_slo(req) headers = swob.HeaderKeyDict(headers) self.assertEqual(status, '412 Precondition Failed') self.assertEqual(headers['Content-Length'], '0') self.assertEqual(body, '') def test_if_match_matches_and_range(self): req = Request.blank( '/v1/AUTH_test/gettest/manifest-abcd', environ={'REQUEST_METHOD': 'GET'}, headers={'If-Match': self.manifest_abcd_etag, 'Range': 'bytes=3-6'}) status, headers, body = self.call_slo(req) headers = swob.HeaderKeyDict(headers) self.assertEqual(status, '206 Partial Content') self.assertEqual(headers['Content-Length'], '4') self.assertEqual(body, 'aabb') def test_get_manifest_with_submanifest(self): req = Request.blank( '/v1/AUTH_test/gettest/manifest-abcd', environ={'REQUEST_METHOD': 'GET'}) status, headers, body = self.call_slo(req) headers = swob.HeaderKeyDict(headers) self.assertEqual(status, '200 OK') self.assertEqual(headers['Content-Length'], '50') self.assertEqual(headers['Etag'], '"%s"' % self.manifest_abcd_etag) self.assertEqual( body, 'aaaaabbbbbbbbbbcccccccccccccccdddddddddddddddddddd') def test_range_get_manifest(self): req = Request.blank( '/v1/AUTH_test/gettest/manifest-abcd', environ={'REQUEST_METHOD': 'GET'}, headers={'Range': 'bytes=3-17'}) status, headers, body = self.call_slo(req) headers = swob.HeaderKeyDict(headers) self.assertEqual(status, '206 Partial Content') self.assertEqual(headers['Content-Length'], '15') self.assertTrue('Etag' not in headers) self.assertEqual(body, 'aabbbbbbbbbbccc') self.assertEqual( self.app.calls, [('GET', '/v1/AUTH_test/gettest/manifest-abcd'), ('GET', '/v1/AUTH_test/gettest/manifest-abcd'), ('GET', '/v1/AUTH_test/gettest/a_5?multipart-manifest=get'), ('GET', '/v1/AUTH_test/gettest/manifest-bc'), ('GET', '/v1/AUTH_test/gettest/b_10?multipart-manifest=get'), ('GET', '/v1/AUTH_test/gettest/c_15?multipart-manifest=get')]) headers = [c[2] for c in self.app.calls_with_headers] self.assertEqual(headers[0].get('Range'), 'bytes=3-17') self.assertEqual(headers[1].get('Range'), None) self.assertEqual(headers[2].get('Range'), 'bytes=3-') self.assertEqual(headers[3].get('Range'), None) self.assertEqual(headers[4].get('Range'), None) self.assertEqual(headers[5].get('Range'), 'bytes=0-2') # we set swift.source for everything but the first request self.assertEqual(self.app.swift_sources, [None, 'SLO', 'SLO', 'SLO', 'SLO', 'SLO']) def test_range_get_includes_whole_manifest(self): # If the first range GET results in retrieval of the entire manifest # body (which we can detect by looking at Content-Range), then we # should not go make a second, non-ranged request just to retrieve the # same bytes again. req = Request.blank( '/v1/AUTH_test/gettest/manifest-abcd', environ={'REQUEST_METHOD': 'GET'}, headers={'Range': 'bytes=0-999999999'}) status, headers, body = self.call_slo(req) headers = swob.HeaderKeyDict(headers) self.assertEqual(status, '206 Partial Content') self.assertEqual( body, 'aaaaabbbbbbbbbbcccccccccccccccdddddddddddddddddddd') self.assertEqual( self.app.calls, [('GET', '/v1/AUTH_test/gettest/manifest-abcd'), ('GET', '/v1/AUTH_test/gettest/a_5?multipart-manifest=get'), ('GET', '/v1/AUTH_test/gettest/manifest-bc'), ('GET', '/v1/AUTH_test/gettest/b_10?multipart-manifest=get'), ('GET', '/v1/AUTH_test/gettest/c_15?multipart-manifest=get'), ('GET', '/v1/AUTH_test/gettest/d_20?multipart-manifest=get')]) def test_range_get_beyond_manifest(self): big = 'e' * 1024 * 1024 big_etag = md5hex(big) self.app.register( 'GET', '/v1/AUTH_test/gettest/big_seg', swob.HTTPOk, {'Content-Type': 'application/foo', 'Etag': big_etag}, big) big_manifest = json.dumps( [{'name': '/gettest/big_seg', 'hash': big_etag, 'bytes': 1024 * 1024, 'content_type': 'application/foo'}]) self.app.register( 'GET', '/v1/AUTH_test/gettest/big_manifest', swob.HTTPOk, {'Content-Type': 'application/octet-stream', 'X-Static-Large-Object': 'true', 'Etag': md5(big_manifest).hexdigest()}, big_manifest) req = Request.blank( '/v1/AUTH_test/gettest/big_manifest', environ={'REQUEST_METHOD': 'GET'}, headers={'Range': 'bytes=100000-199999'}) status, headers, body = self.call_slo(req) headers = swob.HeaderKeyDict(headers) self.assertEqual(status, '206 Partial Content') self.assertEqual(body, 'e' * 100000) self.assertEqual( self.app.calls, [ # has Range header, gets 416 ('GET', '/v1/AUTH_test/gettest/big_manifest'), # retry the first one ('GET', '/v1/AUTH_test/gettest/big_manifest'), ('GET', '/v1/AUTH_test/gettest/big_seg?multipart-manifest=get')]) def test_range_get_bogus_content_range(self): # Just a little paranoia; Swift currently sends back valid # Content-Range headers, but if somehow someone sneaks an invalid one # in there, we'll ignore it. def content_range_breaker_factory(app): def content_range_breaker(env, start_response): req = swob.Request(env) resp = req.get_response(app) resp.headers['Content-Range'] = 'triscuits' return resp(env, start_response) return content_range_breaker self.slo = slo.filter_factory({})( content_range_breaker_factory(self.app)) req = Request.blank( '/v1/AUTH_test/gettest/manifest-abcd', environ={'REQUEST_METHOD': 'GET'}, headers={'Range': 'bytes=0-999999999'}) status, headers, body = self.call_slo(req) headers = swob.HeaderKeyDict(headers) self.assertEqual(status, '206 Partial Content') self.assertEqual( body, 'aaaaabbbbbbbbbbcccccccccccccccdddddddddddddddddddd') self.assertEqual( self.app.calls, [('GET', '/v1/AUTH_test/gettest/manifest-abcd'), ('GET', '/v1/AUTH_test/gettest/manifest-abcd'), ('GET', '/v1/AUTH_test/gettest/a_5?multipart-manifest=get'), ('GET', '/v1/AUTH_test/gettest/manifest-bc'), ('GET', '/v1/AUTH_test/gettest/b_10?multipart-manifest=get'), ('GET', '/v1/AUTH_test/gettest/c_15?multipart-manifest=get'), ('GET', '/v1/AUTH_test/gettest/d_20?multipart-manifest=get')]) def test_range_get_manifest_on_segment_boundaries(self): req = Request.blank( '/v1/AUTH_test/gettest/manifest-abcd', environ={'REQUEST_METHOD': 'GET'}, headers={'Range': 'bytes=5-29'}) status, headers, body = self.call_slo(req) headers = swob.HeaderKeyDict(headers) self.assertEqual(status, '206 Partial Content') self.assertEqual(headers['Content-Length'], '25') self.assertTrue('Etag' not in headers) self.assertEqual(body, 'bbbbbbbbbbccccccccccccccc') self.assertEqual( self.app.calls, [('GET', '/v1/AUTH_test/gettest/manifest-abcd'), ('GET', '/v1/AUTH_test/gettest/manifest-abcd'), ('GET', '/v1/AUTH_test/gettest/manifest-bc'), ('GET', '/v1/AUTH_test/gettest/b_10?multipart-manifest=get'), ('GET', '/v1/AUTH_test/gettest/c_15?multipart-manifest=get')]) headers = [c[2] for c in self.app.calls_with_headers] self.assertEqual(headers[0].get('Range'), 'bytes=5-29') self.assertEqual(headers[1].get('Range'), None) self.assertEqual(headers[2].get('Range'), None) self.assertEqual(headers[3].get('Range'), None) self.assertEqual(headers[4].get('Range'), None) def test_range_get_manifest_first_byte(self): req = Request.blank( '/v1/AUTH_test/gettest/manifest-abcd', environ={'REQUEST_METHOD': 'GET'}, headers={'Range': 'bytes=0-0'}) status, headers, body = self.call_slo(req) headers = swob.HeaderKeyDict(headers) self.assertEqual(status, '206 Partial Content') self.assertEqual(headers['Content-Length'], '1') self.assertEqual(body, 'a') # Make sure we don't get any objects we don't need, including # submanifests. self.assertEqual( self.app.calls, [('GET', '/v1/AUTH_test/gettest/manifest-abcd'), ('GET', '/v1/AUTH_test/gettest/manifest-abcd'), ('GET', '/v1/AUTH_test/gettest/a_5?multipart-manifest=get')]) def test_range_get_manifest_sub_slo(self): req = Request.blank( '/v1/AUTH_test/gettest/manifest-abcd', environ={'REQUEST_METHOD': 'GET'}, headers={'Range': 'bytes=25-30'}) status, headers, body = self.call_slo(req) headers = swob.HeaderKeyDict(headers) self.assertEqual(status, '206 Partial Content') self.assertEqual(headers['Content-Length'], '6') self.assertEqual(body, 'cccccd') # Make sure we don't get any objects we don't need, including # submanifests. self.assertEqual( self.app.calls, [('GET', '/v1/AUTH_test/gettest/manifest-abcd'), ('GET', '/v1/AUTH_test/gettest/manifest-abcd'), ('GET', '/v1/AUTH_test/gettest/manifest-bc'), ('GET', '/v1/AUTH_test/gettest/c_15?multipart-manifest=get'), ('GET', '/v1/AUTH_test/gettest/d_20?multipart-manifest=get')]) def test_range_get_manifest_overlapping_end(self): req = Request.blank( '/v1/AUTH_test/gettest/manifest-abcd', environ={'REQUEST_METHOD': 'GET'}, headers={'Range': 'bytes=45-55'}) status, headers, body = self.call_slo(req) headers = swob.HeaderKeyDict(headers) self.assertEqual(status, '206 Partial Content') self.assertEqual(headers['Content-Length'], '5') self.assertEqual(body, 'ddddd') def test_range_get_manifest_unsatisfiable(self): req = Request.blank( '/v1/AUTH_test/gettest/manifest-abcd', environ={'REQUEST_METHOD': 'GET'}, headers={'Range': 'bytes=100-200'}) status, headers, body = self.call_slo(req) self.assertEqual(status, '416 Requested Range Not Satisfiable') def test_multi_range_get_manifest(self): # SLO doesn't support multi-range GETs. The way that you express # "unsupported" in HTTP is to return a 200 and the whole entity. req = Request.blank( '/v1/AUTH_test/gettest/manifest-abcd', environ={'REQUEST_METHOD': 'GET'}, headers={'Range': 'bytes=0-0,2-2'}) status, headers, body = self.call_slo(req) headers = swob.HeaderKeyDict(headers) self.assertEqual(status, '200 OK') self.assertEqual(headers['Content-Length'], '50') self.assertEqual( body, 'aaaaabbbbbbbbbbcccccccccccccccdddddddddddddddddddd') def test_get_segment_with_non_ascii_name(self): segment_body = u"a møøse once bit my sister".encode("utf-8") self.app.register( 'GET', u'/v1/AUTH_test/ünicode/öbject-segment'.encode('utf-8'), swob.HTTPOk, {'Content-Length': str(len(segment_body)), 'Etag': md5hex(segment_body)}, segment_body) manifest_json = json.dumps([{'name': u'/ünicode/öbject-segment', 'hash': md5hex(segment_body), 'content_type': 'text/plain', 'bytes': len(segment_body)}]) self.app.register( 'GET', u'/v1/AUTH_test/ünicode/manifest'.encode('utf-8'), swob.HTTPOk, {'Content-Type': 'application/json', 'Content-Length': str(len(manifest_json)), 'X-Static-Large-Object': 'true'}, manifest_json) req = Request.blank( '/v1/AUTH_test/ünicode/manifest', environ={'REQUEST_METHOD': 'GET'}) status, headers, body = self.call_slo(req) headers = swob.HeaderKeyDict(headers) self.assertEqual(status, '200 OK') self.assertEqual(body, segment_body) def test_get_bogus_manifest(self): req = Request.blank( '/v1/AUTH_test/gettest/manifest-badjson', environ={'REQUEST_METHOD': 'GET'}) status, headers, body = self.call_slo(req) headers = swob.HeaderKeyDict(headers) self.assertEqual(status, '200 OK') self.assertEqual(headers['Content-Length'], '0') self.assertEqual(headers['X-Object-Meta-Fish'], 'Bass') self.assertEqual(body, '') def test_head_manifest_is_efficient(self): req = Request.blank( '/v1/AUTH_test/gettest/manifest-abcd', environ={'REQUEST_METHOD': 'HEAD'}) status, headers, body = self.call_slo(req) headers = swob.HeaderKeyDict(headers) self.assertEqual(status, '200 OK') self.assertEqual(headers['Content-Length'], '50') self.assertEqual(headers['Etag'], '"%s"' % self.manifest_abcd_etag) self.assertEqual(body, '') # Note the lack of recursive descent into manifest-bc. We know the # content-length from the outer manifest, so there's no need for any # submanifest fetching here, but a naïve implementation might do it # anyway. self.assertEqual(self.app.calls, [ ('HEAD', '/v1/AUTH_test/gettest/manifest-abcd'), ('GET', '/v1/AUTH_test/gettest/manifest-abcd')]) def test_recursion_limit(self): # man1 points to obj1 and man2, man2 points to obj2 and man3... for i in range(20): self.app.register('GET', '/v1/AUTH_test/gettest/obj%d' % i, swob.HTTPOk, {'Content-Type': 'text/plain', 'Etag': md5hex('body%02d' % i)}, 'body%02d' % i) manifest_json = json.dumps([{'name': '/gettest/obj20', 'hash': md5hex('body20'), 'content_type': 'text/plain', 'bytes': '6'}]) self.app.register( 'GET', '/v1/AUTH_test/gettest/man%d' % i, swob.HTTPOk, {'Content-Type': 'application/json', 'X-Static-Large-Object': 'true', 'Etag': 'man%d' % i}, manifest_json) for i in range(19, 0, -1): manifest_data = [ {'name': '/gettest/obj%d' % i, 'hash': md5hex('body%02d' % i), 'bytes': '6', 'content_type': 'text/plain'}, {'name': '/gettest/man%d' % (i + 1), 'hash': 'man%d' % (i + 1), 'sub_slo': True, 'bytes': len(manifest_json), 'content_type': 'application/json;swift_bytes=%d' % ((21 - i) * 6)}] manifest_json = json.dumps(manifest_data) self.app.register( 'GET', '/v1/AUTH_test/gettest/man%d' % i, swob.HTTPOk, {'Content-Type': 'application/json', 'X-Static-Large-Object': 'true', 'Etag': 'man%d' % i}, manifest_json) req = Request.blank( '/v1/AUTH_test/gettest/man1', environ={'REQUEST_METHOD': 'GET'}) status, headers, body, exc = self.call_slo(req, expect_exception=True) headers = swob.HeaderKeyDict(headers) self.assertTrue(isinstance(exc, ListingIterError)) # we don't know at header-sending time that things are going to go # wrong, so we end up with a 200 and a truncated body self.assertEqual(status, '200 OK') self.assertEqual(body, ('body01body02body03body04body05' + 'body06body07body08body09body10')) # make sure we didn't keep asking for segments self.assertEqual(self.app.call_count, 20) def test_sub_slo_recursion(self): # man1 points to man2 and obj1, man2 points to man3 and obj2... for i in range(11): self.app.register('GET', '/v1/AUTH_test/gettest/obj%d' % i, swob.HTTPOk, {'Content-Type': 'text/plain', 'Content-Length': '6', 'Etag': md5hex('body%02d' % i)}, 'body%02d' % i) manifest_json = json.dumps([{'name': '/gettest/obj%d' % i, 'hash': md5hex('body%2d' % i), 'content_type': 'text/plain', 'bytes': '6'}]) self.app.register( 'GET', '/v1/AUTH_test/gettest/man%d' % i, swob.HTTPOk, {'Content-Type': 'application/json', 'X-Static-Large-Object': 'true', 'Etag': 'man%d' % i}, manifest_json) self.app.register( 'HEAD', '/v1/AUTH_test/gettest/obj%d' % i, swob.HTTPOk, {'Content-Length': '6', 'Etag': md5hex('body%2d' % i)}, None) for i in range(9, 0, -1): manifest_data = [ {'name': '/gettest/man%d' % (i + 1), 'hash': 'man%d' % (i + 1), 'sub_slo': True, 'bytes': len(manifest_json), 'content_type': 'application/json;swift_bytes=%d' % ((10 - i) * 6)}, {'name': '/gettest/obj%d' % i, 'hash': md5hex('body%02d' % i), 'bytes': '6', 'content_type': 'text/plain'}] manifest_json = json.dumps(manifest_data) self.app.register( 'GET', '/v1/AUTH_test/gettest/man%d' % i, swob.HTTPOk, {'Content-Type': 'application/json', 'X-Static-Large-Object': 'true', 'Etag': 'man%d' % i}, manifest_json) req = Request.blank( '/v1/AUTH_test/gettest/man1', environ={'REQUEST_METHOD': 'GET'}) status, headers, body = self.call_slo(req) self.assertEqual(status, '200 OK') self.assertEqual(body, ('body10body09body08body07body06' + 'body05body04body03body02body01')) self.assertEqual(self.app.call_count, 20) def test_sub_slo_recursion_limit(self): # man1 points to man2 and obj1, man2 points to man3 and obj2... for i in range(12): self.app.register('GET', '/v1/AUTH_test/gettest/obj%d' % i, swob.HTTPOk, {'Content-Type': 'text/plain', 'Content-Length': '6', 'Etag': md5hex('body%02d' % i)}, 'body%02d' % i) manifest_json = json.dumps([{'name': '/gettest/obj%d' % i, 'hash': md5hex('body%2d' % i), 'content_type': 'text/plain', 'bytes': '6'}]) self.app.register( 'GET', '/v1/AUTH_test/gettest/man%d' % i, swob.HTTPOk, {'Content-Type': 'application/json', 'X-Static-Large-Object': 'true', 'Etag': 'man%d' % i}, manifest_json) self.app.register( 'HEAD', '/v1/AUTH_test/gettest/obj%d' % i, swob.HTTPOk, {'Content-Length': '6', 'Etag': md5hex('body%2d' % i)}, None) for i in range(11, 0, -1): manifest_data = [ {'name': '/gettest/man%d' % (i + 1), 'hash': 'man%d' % (i + 1), 'sub_slo': True, 'bytes': len(manifest_json), 'content_type': 'application/json;swift_bytes=%d' % ((12 - i) * 6)}, {'name': '/gettest/obj%d' % i, 'hash': md5hex('body%02d' % i), 'bytes': '6', 'content_type': 'text/plain'}] manifest_json = json.dumps(manifest_data) self.app.register('GET', '/v1/AUTH_test/gettest/man%d' % i, swob.HTTPOk, {'Content-Type': 'application/json', 'X-Static-Large-Object': 'true', 'Etag': 'man%d' % i}, manifest_json) req = Request.blank( '/v1/AUTH_test/gettest/man1', environ={'REQUEST_METHOD': 'GET'}) status, headers, body = self.call_slo(req) self.assertEqual(status, '409 Conflict') self.assertEqual(self.app.call_count, 10) error_lines = self.slo.logger.get_lines_for_level('error') self.assertEqual(len(error_lines), 1) self.assertTrue(error_lines[0].startswith( 'ERROR: An error occurred while retrieving segments')) def test_get_with_if_modified_since(self): # It's important not to pass the If-[Un]Modified-Since header to the # proxy for segment or submanifest GET requests, as it may result in # 304 Not Modified responses, and those don't contain any useful data. req = swob.Request.blank( '/v1/AUTH_test/gettest/manifest-abcd', environ={'REQUEST_METHOD': 'GET'}, headers={'If-Modified-Since': 'Wed, 12 Feb 2014 22:24:52 GMT', 'If-Unmodified-Since': 'Thu, 13 Feb 2014 23:25:53 GMT'}) status, headers, body, exc = self.call_slo(req, expect_exception=True) for _, _, hdrs in self.app.calls_with_headers[1:]: self.assertFalse('If-Modified-Since' in hdrs) self.assertFalse('If-Unmodified-Since' in hdrs) def test_error_fetching_segment(self): self.app.register('GET', '/v1/AUTH_test/gettest/c_15', swob.HTTPUnauthorized, {}, None) req = Request.blank( '/v1/AUTH_test/gettest/manifest-abcd', environ={'REQUEST_METHOD': 'GET'}) status, headers, body, exc = self.call_slo(req, expect_exception=True) headers = swob.HeaderKeyDict(headers) self.assertTrue(isinstance(exc, SegmentError)) self.assertEqual(status, '200 OK') self.assertEqual(self.app.calls, [ ('GET', '/v1/AUTH_test/gettest/manifest-abcd'), ('GET', '/v1/AUTH_test/gettest/a_5?multipart-manifest=get'), ('GET', '/v1/AUTH_test/gettest/manifest-bc'), ('GET', '/v1/AUTH_test/gettest/b_10?multipart-manifest=get'), # This one has the error, and so is the last one we fetch. ('GET', '/v1/AUTH_test/gettest/c_15?multipart-manifest=get')]) def test_error_fetching_submanifest(self): self.app.register('GET', '/v1/AUTH_test/gettest/manifest-bc', swob.HTTPUnauthorized, {}, None) req = Request.blank( '/v1/AUTH_test/gettest/manifest-abcd', environ={'REQUEST_METHOD': 'GET'}) status, headers, body, exc = self.call_slo(req, expect_exception=True) self.assertTrue(isinstance(exc, ListingIterError)) self.assertEqual("200 OK", status) self.assertEqual("aaaaa", body) self.assertEqual(self.app.calls, [ ('GET', '/v1/AUTH_test/gettest/manifest-abcd'), ('GET', '/v1/AUTH_test/gettest/a_5?multipart-manifest=get'), # This one has the error, and so is the last one we fetch. ('GET', '/v1/AUTH_test/gettest/manifest-bc')]) def test_error_fetching_first_segment_submanifest(self): # This differs from the normal submanifest error because this one # happens before we've actually sent any response body. self.app.register( 'GET', '/v1/AUTH_test/gettest/manifest-a', swob.HTTPForbidden, {}, None) self.app.register( 'GET', '/v1/AUTH_test/gettest/manifest-manifest-a', swob.HTTPOk, {'Content-Type': 'application/json', 'X-Static-Large-Object': 'true'}, json.dumps([{'name': '/gettest/manifest-a', 'sub_slo': True, 'content_type': 'application/json;swift_bytes=5', 'hash': 'manifest-a', 'bytes': '12345'}])) req = Request.blank( '/v1/AUTH_test/gettest/manifest-manifest-a', environ={'REQUEST_METHOD': 'GET'}) status, headers, body = self.call_slo(req) self.assertEqual('409 Conflict', status) error_lines = self.slo.logger.get_lines_for_level('error') self.assertEqual(len(error_lines), 1) self.assertTrue(error_lines[0].startswith( 'ERROR: An error occurred while retrieving segments')) def test_invalid_json_submanifest(self): self.app.register( 'GET', '/v1/AUTH_test/gettest/manifest-bc', swob.HTTPOk, {'Content-Type': 'application/json;swift_bytes=25', 'X-Static-Large-Object': 'true', 'X-Object-Meta-Plant': 'Ficus'}, "[this {isn't (JSON") req = Request.blank( '/v1/AUTH_test/gettest/manifest-abcd', environ={'REQUEST_METHOD': 'GET'}) status, headers, body, exc = self.call_slo(req, expect_exception=True) self.assertTrue(isinstance(exc, ListingIterError)) self.assertEqual('200 OK', status) self.assertEqual(body, 'aaaaa') def test_mismatched_etag(self): self.app.register( 'GET', '/v1/AUTH_test/gettest/manifest-a-b-badetag-c', swob.HTTPOk, {'Content-Type': 'application/json', 'X-Static-Large-Object': 'true'}, json.dumps([{'name': '/gettest/a_5', 'hash': md5hex('a' * 5), 'content_type': 'text/plain', 'bytes': '5'}, {'name': '/gettest/b_10', 'hash': 'wrong!', 'content_type': 'text/plain', 'bytes': '10'}, {'name': '/gettest/c_15', 'hash': md5hex('c' * 15), 'content_type': 'text/plain', 'bytes': '15'}])) req = Request.blank( '/v1/AUTH_test/gettest/manifest-a-b-badetag-c', environ={'REQUEST_METHOD': 'GET'}) status, headers, body, exc = self.call_slo(req, expect_exception=True) self.assertTrue(isinstance(exc, SegmentError)) self.assertEqual('200 OK', status) self.assertEqual(body, 'aaaaa') def test_mismatched_size(self): self.app.register( 'GET', '/v1/AUTH_test/gettest/manifest-a-b-badsize-c', swob.HTTPOk, {'Content-Type': 'application/json', 'X-Static-Large-Object': 'true'}, json.dumps([{'name': '/gettest/a_5', 'hash': md5hex('a' * 5), 'content_type': 'text/plain', 'bytes': '5'}, {'name': '/gettest/b_10', 'hash': md5hex('b' * 10), 'content_type': 'text/plain', 'bytes': '999999'}, {'name': '/gettest/c_15', 'hash': md5hex('c' * 15), 'content_type': 'text/plain', 'bytes': '15'}])) req = Request.blank( '/v1/AUTH_test/gettest/manifest-a-b-badsize-c', environ={'REQUEST_METHOD': 'GET'}) status, headers, body, exc = self.call_slo(req, expect_exception=True) self.assertTrue(isinstance(exc, SegmentError)) self.assertEqual('200 OK', status) self.assertEqual(body, 'aaaaa') def test_first_segment_mismatched_etag(self): self.app.register('GET', '/v1/AUTH_test/gettest/manifest-badetag', swob.HTTPOk, {'Content-Type': 'application/json', 'X-Static-Large-Object': 'true'}, json.dumps([{'name': '/gettest/a_5', 'hash': 'wrong!', 'content_type': 'text/plain', 'bytes': '5'}])) req = Request.blank('/v1/AUTH_test/gettest/manifest-badetag', environ={'REQUEST_METHOD': 'GET'}) status, headers, body = self.call_slo(req) self.assertEqual('409 Conflict', status) error_lines = self.slo.logger.get_lines_for_level('error') self.assertEqual(len(error_lines), 1) self.assertTrue(error_lines[0].startswith( 'ERROR: An error occurred while retrieving segments')) def test_first_segment_mismatched_size(self): self.app.register('GET', '/v1/AUTH_test/gettest/manifest-badsize', swob.HTTPOk, {'Content-Type': 'application/json', 'X-Static-Large-Object': 'true'}, json.dumps([{'name': '/gettest/a_5', 'hash': md5hex('a' * 5), 'content_type': 'text/plain', 'bytes': '999999'}])) req = Request.blank('/v1/AUTH_test/gettest/manifest-badsize', environ={'REQUEST_METHOD': 'GET'}) status, headers, body = self.call_slo(req) self.assertEqual('409 Conflict', status) error_lines = self.slo.logger.get_lines_for_level('error') self.assertEqual(len(error_lines), 1) self.assertTrue(error_lines[0].startswith( 'ERROR: An error occurred while retrieving segments')) def test_download_takes_too_long(self): the_time = [time.time()] def mock_time(): return the_time[0] # this is just a convenient place to hang a time jump; there's nothing # special about the choice of is_success(). def mock_is_success(status_int): the_time[0] += 7 * 3600 return status_int // 100 == 2 req = Request.blank( '/v1/AUTH_test/gettest/manifest-abcd', environ={'REQUEST_METHOD': 'GET'}) with nested(patch.object(slo, 'is_success', mock_is_success), patch('swift.common.request_helpers.time.time', mock_time), patch('swift.common.request_helpers.is_success', mock_is_success)): status, headers, body, exc = self.call_slo( req, expect_exception=True) self.assertTrue(isinstance(exc, SegmentError)) self.assertEqual(status, '200 OK') self.assertEqual(self.app.calls, [ ('GET', '/v1/AUTH_test/gettest/manifest-abcd'), ('GET', '/v1/AUTH_test/gettest/a_5?multipart-manifest=get'), ('GET', '/v1/AUTH_test/gettest/manifest-bc'), ('GET', '/v1/AUTH_test/gettest/b_10?multipart-manifest=get'), ('GET', '/v1/AUTH_test/gettest/c_15?multipart-manifest=get')]) def test_first_segment_not_exists(self): self.app.register('GET', '/v1/AUTH_test/gettest/not_exists_obj', swob.HTTPNotFound, {}, None) self.app.register('GET', '/v1/AUTH_test/gettest/manifest-not-exists', swob.HTTPOk, {'Content-Type': 'application/json', 'X-Static-Large-Object': 'true'}, json.dumps([{'name': '/gettest/not_exists_obj', 'hash': md5hex('not_exists_obj'), 'content_type': 'text/plain', 'bytes': '%d' % len('not_exists_obj') }])) req = Request.blank('/v1/AUTH_test/gettest/manifest-not-exists', environ={'REQUEST_METHOD': 'GET'}) status, headers, body = self.call_slo(req) self.assertEqual('409 Conflict', status) error_lines = self.slo.logger.get_lines_for_level('error') self.assertEqual(len(error_lines), 1) self.assertTrue(error_lines[0].startswith( 'ERROR: An error occurred while retrieving segments')) class TestSloBulkLogger(unittest.TestCase): def test_reused_logger(self): slo_mware = slo.filter_factory({})('fake app') self.assertTrue(slo_mware.logger is slo_mware.bulk_deleter.logger) class TestSloCopyHook(SloTestCase): def setUp(self): super(TestSloCopyHook, self).setUp() self.app.register( 'GET', '/v1/AUTH_test/c/o', swob.HTTPOk, {'Content-Length': '3', 'Etag': md5hex("obj")}, "obj") self.app.register( 'GET', '/v1/AUTH_test/c/man', swob.HTTPOk, {'Content-Type': 'application/json', 'X-Static-Large-Object': 'true'}, json.dumps([{'name': '/c/o', 'hash': md5hex("obj"), 'bytes': '3'}])) self.app.register( 'COPY', '/v1/AUTH_test/c/o', swob.HTTPCreated, {}) copy_hook = [None] # slip this guy in there to pull out the hook def extract_copy_hook(env, sr): if env['REQUEST_METHOD'] == 'COPY': copy_hook[0] = env['swift.copy_hook'] return self.app(env, sr) self.slo = slo.filter_factory({})(extract_copy_hook) req = Request.blank('/v1/AUTH_test/c/o', environ={'REQUEST_METHOD': 'COPY'}) self.slo(req.environ, fake_start_response) self.copy_hook = copy_hook[0] self.assertTrue(self.copy_hook is not None) # sanity check def test_copy_hook_passthrough(self): source_req = Request.blank( '/v1/AUTH_test/c/o', environ={'REQUEST_METHOD': 'GET'}) sink_req = Request.blank( '/v1/AUTH_test/c/o', environ={'REQUEST_METHOD': 'PUT'}) # no X-Static-Large-Object header, so do nothing source_resp = Response(request=source_req, status=200) modified_resp = self.copy_hook(source_req, source_resp, sink_req) self.assertTrue(modified_resp is source_resp) def test_copy_hook_manifest(self): source_req = Request.blank( '/v1/AUTH_test/c/o', environ={'REQUEST_METHOD': 'GET'}) sink_req = Request.blank( '/v1/AUTH_test/c/o', environ={'REQUEST_METHOD': 'PUT'}) source_resp = Response(request=source_req, status=200, headers={"X-Static-Large-Object": "true"}, app_iter=[json.dumps([{'name': '/c/o', 'hash': md5hex("obj"), 'bytes': '3'}])]) modified_resp = self.copy_hook(source_req, source_resp, sink_req) self.assertTrue(modified_resp is not source_resp) self.assertEqual(modified_resp.etag, md5hex(md5hex("obj"))) class TestSwiftInfo(unittest.TestCase): def setUp(self): utils._swift_info = {} utils._swift_admin_info = {} def test_registered_defaults(self): mware = slo.filter_factory({})('have to pass in an app') swift_info = utils.get_swift_info() self.assertTrue('slo' in swift_info) self.assertEqual(swift_info['slo'].get('max_manifest_segments'), mware.max_manifest_segments) self.assertEqual(swift_info['slo'].get('min_segment_size'), mware.min_segment_size) self.assertEqual(swift_info['slo'].get('max_manifest_size'), mware.max_manifest_size) if __name__ == '__main__': unittest.main()
apache-2.0
habibiefaried/ryu
ryu/contrib/ovs/stream.py
46
12200
# Copyright (c) 2010, 2011, 2012 Nicira, 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 errno import os import socket import ovs.poller import ovs.socket_util import ovs.vlog vlog = ovs.vlog.Vlog("stream") def stream_or_pstream_needs_probes(name): """ 1 if the stream or pstream specified by 'name' needs periodic probes to verify connectivity. For [p]streams which need probes, it can take a long time to notice the connection was dropped. Returns 0 if probes aren't needed, and -1 if 'name' is invalid""" if PassiveStream.is_valid_name(name) or Stream.is_valid_name(name): # Only unix and punix are supported currently. return 0 else: return -1 class Stream(object): """Bidirectional byte stream. Currently only Unix domain sockets are implemented.""" # States. __S_CONNECTING = 0 __S_CONNECTED = 1 __S_DISCONNECTED = 2 # Kinds of events that one might wait for. W_CONNECT = 0 # Connect complete (success or failure). W_RECV = 1 # Data received. W_SEND = 2 # Send buffer room available. _SOCKET_METHODS = {} @staticmethod def register_method(method, cls): Stream._SOCKET_METHODS[method + ":"] = cls @staticmethod def _find_method(name): for method, cls in Stream._SOCKET_METHODS.items(): if name.startswith(method): return cls return None @staticmethod def is_valid_name(name): """Returns True if 'name' is a stream name in the form "TYPE:ARGS" and TYPE is a supported stream type (currently only "unix:" and "tcp:"), otherwise False.""" return bool(Stream._find_method(name)) def __init__(self, socket, name, status): self.socket = socket self.name = name if status == errno.EAGAIN: self.state = Stream.__S_CONNECTING elif status == 0: self.state = Stream.__S_CONNECTED else: self.state = Stream.__S_DISCONNECTED self.error = 0 # Default value of dscp bits for connection between controller and manager. # Value of IPTOS_PREC_INTERNETCONTROL = 0xc0 which is defined # in <netinet/ip.h> is used. IPTOS_PREC_INTERNETCONTROL = 0xc0 DSCP_DEFAULT = IPTOS_PREC_INTERNETCONTROL >> 2 @staticmethod def open(name, dscp=DSCP_DEFAULT): """Attempts to connect a stream to a remote peer. 'name' is a connection name in the form "TYPE:ARGS", where TYPE is an active stream class's name and ARGS are stream class-specific. Currently the only supported TYPEs are "unix" and "tcp". Returns (error, stream): on success 'error' is 0 and 'stream' is the new Stream, on failure 'error' is a positive errno value and 'stream' is None. Never returns errno.EAGAIN or errno.EINPROGRESS. Instead, returns 0 and a new Stream. The connect() method can be used to check for successful connection completion.""" cls = Stream._find_method(name) if not cls: return errno.EAFNOSUPPORT, None suffix = name.split(":", 1)[1] error, sock = cls._open(suffix, dscp) if error: return error, None else: status = ovs.socket_util.check_connection_completion(sock) return 0, Stream(sock, name, status) @staticmethod def _open(suffix, dscp): raise NotImplementedError("This method must be overrided by subclass") @staticmethod def open_block((error, stream)): """Blocks until a Stream completes its connection attempt, either succeeding or failing. (error, stream) should be the tuple returned by Stream.open(). Returns a tuple of the same form. Typical usage: error, stream = Stream.open_block(Stream.open("unix:/tmp/socket"))""" if not error: while True: error = stream.connect() if error != errno.EAGAIN: break stream.run() poller = ovs.poller.Poller() stream.run_wait(poller) stream.connect_wait(poller) poller.block() assert error != errno.EINPROGRESS if error and stream: stream.close() stream = None return error, stream def close(self): self.socket.close() def __scs_connecting(self): retval = ovs.socket_util.check_connection_completion(self.socket) assert retval != errno.EINPROGRESS if retval == 0: self.state = Stream.__S_CONNECTED elif retval != errno.EAGAIN: self.state = Stream.__S_DISCONNECTED self.error = retval def connect(self): """Tries to complete the connection on this stream. If the connection is complete, returns 0 if the connection was successful or a positive errno value if it failed. If the connection is still in progress, returns errno.EAGAIN.""" if self.state == Stream.__S_CONNECTING: self.__scs_connecting() if self.state == Stream.__S_CONNECTING: return errno.EAGAIN elif self.state == Stream.__S_CONNECTED: return 0 else: assert self.state == Stream.__S_DISCONNECTED return self.error def recv(self, n): """Tries to receive up to 'n' bytes from this stream. Returns a (error, string) tuple: - If successful, 'error' is zero and 'string' contains between 1 and 'n' bytes of data. - On error, 'error' is a positive errno value. - If the connection has been closed in the normal fashion or if 'n' is 0, the tuple is (0, ""). The recv function will not block waiting for data to arrive. If no data have been received, it returns (errno.EAGAIN, "") immediately.""" retval = self.connect() if retval != 0: return (retval, "") elif n == 0: return (0, "") try: return (0, self.socket.recv(n)) except socket.error, e: return (ovs.socket_util.get_exception_errno(e), "") def send(self, buf): """Tries to send 'buf' on this stream. If successful, returns the number of bytes sent, between 1 and len(buf). 0 is only a valid return value if len(buf) is 0. On error, returns a negative errno value. Will not block. If no bytes can be immediately accepted for transmission, returns -errno.EAGAIN immediately.""" retval = self.connect() if retval != 0: return -retval elif len(buf) == 0: return 0 try: return self.socket.send(buf) except socket.error, e: return -ovs.socket_util.get_exception_errno(e) def run(self): pass def run_wait(self, poller): pass def wait(self, poller, wait): assert wait in (Stream.W_CONNECT, Stream.W_RECV, Stream.W_SEND) if self.state == Stream.__S_DISCONNECTED: poller.immediate_wake() return if self.state == Stream.__S_CONNECTING: wait = Stream.W_CONNECT if wait == Stream.W_RECV: poller.fd_wait(self.socket, ovs.poller.POLLIN) else: poller.fd_wait(self.socket, ovs.poller.POLLOUT) def connect_wait(self, poller): self.wait(poller, Stream.W_CONNECT) def recv_wait(self, poller): self.wait(poller, Stream.W_RECV) def send_wait(self, poller): self.wait(poller, Stream.W_SEND) def __del__(self): # Don't delete the file: we might have forked. self.socket.close() class PassiveStream(object): @staticmethod def is_valid_name(name): """Returns True if 'name' is a passive stream name in the form "TYPE:ARGS" and TYPE is a supported passive stream type (currently only "punix:"), otherwise False.""" return name.startswith("punix:") def __init__(self, sock, name, bind_path): self.name = name self.socket = sock self.bind_path = bind_path @staticmethod def open(name): """Attempts to start listening for remote stream connections. 'name' is a connection name in the form "TYPE:ARGS", where TYPE is an passive stream class's name and ARGS are stream class-specific. Currently the only supported TYPE is "punix". Returns (error, pstream): on success 'error' is 0 and 'pstream' is the new PassiveStream, on failure 'error' is a positive errno value and 'pstream' is None.""" if not PassiveStream.is_valid_name(name): return errno.EAFNOSUPPORT, None bind_path = name[6:] error, sock = ovs.socket_util.make_unix_socket(socket.SOCK_STREAM, True, bind_path, None) if error: return error, None try: sock.listen(10) except socket.error, e: vlog.err("%s: listen: %s" % (name, os.strerror(e.error))) sock.close() return e.error, None return 0, PassiveStream(sock, name, bind_path) def close(self): """Closes this PassiveStream.""" self.socket.close() if self.bind_path is not None: ovs.fatal_signal.unlink_file_now(self.bind_path) self.bind_path = None def accept(self): """Tries to accept a new connection on this passive stream. Returns (error, stream): if successful, 'error' is 0 and 'stream' is the new Stream object, and on failure 'error' is a positive errno value and 'stream' is None. Will not block waiting for a connection. If no connection is ready to be accepted, returns (errno.EAGAIN, None) immediately.""" while True: try: sock, addr = self.socket.accept() ovs.socket_util.set_nonblocking(sock) return 0, Stream(sock, "unix:%s" % addr, 0) except socket.error, e: error = ovs.socket_util.get_exception_errno(e) if error != errno.EAGAIN: # XXX rate-limit vlog.dbg("accept: %s" % os.strerror(error)) return error, None def wait(self, poller): poller.fd_wait(self.socket, ovs.poller.POLLIN) def __del__(self): # Don't delete the file: we might have forked. self.socket.close() def usage(name): return """ Active %s connection methods: unix:FILE Unix domain socket named FILE tcp:IP:PORT TCP socket to IP with port no of PORT Passive %s connection methods: punix:FILE Listen on Unix domain socket FILE""" % (name, name) class UnixStream(Stream): @staticmethod def _open(suffix, dscp): connect_path = suffix return ovs.socket_util.make_unix_socket(socket.SOCK_STREAM, True, None, connect_path) Stream.register_method("unix", UnixStream) class TCPStream(Stream): @staticmethod def _open(suffix, dscp): error, sock = ovs.socket_util.inet_open_active(socket.SOCK_STREAM, suffix, 0, dscp) if not error: sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1) return error, sock Stream.register_method("tcp", TCPStream)
apache-2.0
invariantor/ImageSplit-Classification
image split and classification/image_split.py
1
6276
import numpy as np import pylab import mahotas as mh import types # constants upper_distance = 100 #the start searching approxWidth = 40 threshold = 300 border = 1 def pre_process(image): """ pre_process will return black_white image, given a colorful image as input. """ T = mh.thresholding.otsu(image) image1 =image > T image2 = [[0]* image1.shape[1] for i in range(image1.shape[0])] for i in range(image1.shape[0]): for j in range(image1.shape[1]): if (image1[i][j] != [0,0,0]).any(): image2[i][j] = 1 image2 = np.array(image2, dtype = np.uint8) return image2 def locate(image): """ Given an screenshot as input, return the position of the matching game as well as the size of the game(num_x,num_y) and the size of each grids(size_x,size_y). """ image = pre_process(image) height,width = image.shape # stop going down when a grid is found up = upper_distance while True: num_white =0 for j in range(width): num_white+=image[up][j] if num_white>(approxWidth/2): break up +=1 # stop going up when a grid is found down = height-1 pre_num_white =0 #the number of white pixels in the last step for j in range(width): pre_num_white+=image[down][j] while True: num_white =0 for j in range(width): num_white+=image[down][j] if num_white-pre_num_white>(approxWidth/2): break pre_num_white = num_white down -=1 current_image = image[up:] """cut the top part(including the time bar, all sorts of buttons) away which will interfere with our searching process""" current_image = np.array(current_image) c_height,c_width = current_image.shape # stop going right when a grid is found left = 0 pre_num_white =0 for i in range(c_height): pre_num_white+=current_image[i][left] while True: num_white =0 for i in range(c_height): num_white+=current_image[i][left] if num_white-pre_num_white>(approxWidth/2): break pre_num_white = num_white left +=1 # stop going left when a grid is found right = c_width-1 pre_num_white =0 for i in range(c_height): pre_num_white+=current_image[i][right] while True: num_white =0 for i in range(c_height): num_white+=current_image[i][right] if num_white-pre_num_white>(approxWidth/2): break pre_num_white = num_white right -=1 temp = [0]*(down+1-up) for i in range(len(temp)): temp[i] = current_image[i][left:right+1] current_image = np.array(temp) height,width = current_image.shape divd_x = [] for i in range(height): num_white = sum(current_image[i]) if num_white < approxWidth/2: divd_x.append(i) temp_x = [divd_x[i] for i in range(len(divd_x)) if ((i==0) or (i==len(divd_x)-1)) or not (divd_x[i-1]+1==divd_x[i] and divd_x[i+1]-1==divd_x[i])] # only keep the truly dividing lines, namely those marginal lines. divd_x =temp_x divd_y = [] for j in range(width): num_white = 0 for i in range(height): num_white += current_image[i][j] if num_white < approxWidth/2: divd_y.append(j) temp_y = [divd_y[i] for i in range(len(divd_y)) if ((i==0) or (i==len(divd_y)-1)) or not (divd_y[i-1]+1==divd_y[i] and divd_y[i+1]-1==divd_y[i])] # only keep the truly dividing lines, namely those marginal lines. divd_y = temp_y #print divd_x #print divd_y """ This part needs further refinement. """ if len(divd_x): size_x = divd_x[0] num_x = divd_x[-1] / size_x +1 else: size_x = height - 1 num_x = 1 if len(divd_y): size_y = divd_y[0] num_y = divd_y[-1] / size_y +1 else: size_y = height - 1 num_y = 1 position = (up,down,left,right) info = (size_x,size_y,num_x,num_y) return position, info def split(image,position,info): """ Return a 2d matrix label, which labels different kinds of grids using natural numbers. (By convention, the empty grid is labeled 0) """ size_x, size_y, num_x, num_y = info up, down, left, right = position T = mh.thresholding.otsu(image) image = image >T temp = [0]* (down+1-up) for i in range(len(temp)): temp[i] = image[up+i][left:right+1] temp = np.array(temp) image = temp game = [[0]* num_y for j in range(num_x)] for i in range(num_x): for j in range(num_y): grid = [0]* size_x for k in range(size_x): grid[k] = image[i*(size_x+1)+k][j*(size_y+1):(j+1)*(size_y+1)-1] game[i][j] = grid # using a quite naive method -- calculating the statistical distance between two grids # improvement is needed here, to speed up the program black = [[[0]*3]*size_y]*size_x records = [black] label = [[0]* num_y for j in range(num_x)] for i in range(num_x): for j in range(num_y): find = False for index in range(len(records)): if distance(records[index],game[i][j])< threshold: label[i][j] = index find =True break if not find: records.append(game[i][j]) label[i][j] = len(records)-1 return label def distance(a1,a2): """ recursively calculate the distance between a1 and a2 """ if (type(a1)== np.uint8) or (type(a1) == types.IntType) or (type(a1)==np.bool_): return abs(int(a1)-int(a2)) if len(a1)!= len(a2): print "Wrong Format","len(a1)=",len(a1),"len(a2)=",len(a2) return dis =0 for i in range(len(a1)): dis += distance(a1[i],a2[i]) return dis
mit
dancingdan/tensorflow
tensorflow/contrib/checkpoint/python/python_state_test.py
16
4059
# Copyright 2018 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== from __future__ import absolute_import from __future__ import division from __future__ import print_function import os import numpy from tensorflow.contrib.checkpoint.python import python_state from tensorflow.python.client import session from tensorflow.python.eager import test from tensorflow.python.framework import ops from tensorflow.python.framework import test_util from tensorflow.python.ops import variables from tensorflow.python.training.checkpointable import util class NumpyStateTests(test.TestCase): @test_util.run_in_graph_and_eager_modes def testSaveRestoreNumpyState(self): directory = self.get_temp_dir() prefix = os.path.join(directory, "ckpt") save_state = python_state.NumpyState() saver = util.Checkpoint(numpy=save_state) save_state.a = numpy.ones([2, 2]) save_state.b = numpy.ones([2, 2]) save_state.b = numpy.zeros([2, 2]) save_state.c = numpy.int64(3) self.assertAllEqual(numpy.ones([2, 2]), save_state.a) self.assertAllEqual(numpy.zeros([2, 2]), save_state.b) self.assertEqual(3, save_state.c) first_save_path = saver.save(prefix) save_state.a[1, 1] = 2. save_state.c = numpy.int64(4) second_save_path = saver.save(prefix) load_state = python_state.NumpyState() loader = util.Checkpoint(numpy=load_state) loader.restore(first_save_path).initialize_or_restore() self.assertAllEqual(numpy.ones([2, 2]), load_state.a) self.assertAllEqual(numpy.zeros([2, 2]), load_state.b) self.assertEqual(3, load_state.c) load_state.a[0, 0] = 42. self.assertAllEqual([[42., 1.], [1., 1.]], load_state.a) loader.restore(first_save_path).run_restore_ops() self.assertAllEqual(numpy.ones([2, 2]), load_state.a) loader.restore(second_save_path).run_restore_ops() self.assertAllEqual([[1., 1.], [1., 2.]], load_state.a) self.assertAllEqual(numpy.zeros([2, 2]), load_state.b) self.assertEqual(4, load_state.c) def testNoGraphPollution(self): graph = ops.Graph() with graph.as_default(), session.Session(): directory = self.get_temp_dir() prefix = os.path.join(directory, "ckpt") save_state = python_state.NumpyState() saver = util.Checkpoint(numpy=save_state) save_state.a = numpy.ones([2, 2]) save_path = saver.save(prefix) saver.restore(save_path) graph.finalize() saver.save(prefix) save_state.a = numpy.zeros([2, 2]) saver.save(prefix) saver.restore(save_path) @test_util.run_in_graph_and_eager_modes def testNoMixedNumpyStateTF(self): save_state = python_state.NumpyState() save_state.a = numpy.ones([2, 2]) with self.assertRaises(NotImplementedError): save_state.v = variables.Variable(1.) @test_util.run_in_graph_and_eager_modes def testDocstringExample(self): arrays = python_state.NumpyState() checkpoint = util.Checkpoint(numpy_arrays=arrays) arrays.x = numpy.zeros([3, 4]) save_path = checkpoint.save(os.path.join(self.get_temp_dir(), "ckpt")) arrays.x[1, 1] = 4. checkpoint.restore(save_path) self.assertAllEqual(numpy.zeros([3, 4]), arrays.x) second_checkpoint = util.Checkpoint(numpy_arrays=python_state.NumpyState()) second_checkpoint.restore(save_path) self.assertAllEqual(numpy.zeros([3, 4]), second_checkpoint.numpy_arrays.x) if __name__ == "__main__": test.main()
apache-2.0
JulienMcJay/eclock
windows/Python27/Lib/hashlib.py
84
5011
# $Id$ # # Copyright (C) 2005 Gregory P. Smith (greg@krypto.org) # Licensed to PSF under a Contributor Agreement. # __doc__ = """hashlib module - A common interface to many hash functions. new(name, string='') - returns a new hash object implementing the given hash function; initializing the hash using the given string data. Named constructor functions are also available, these are much faster than using new(): md5(), sha1(), sha224(), sha256(), sha384(), and sha512() More algorithms may be available on your platform but the above are guaranteed to exist. NOTE: If you want the adler32 or crc32 hash functions they are available in the zlib module. Choose your hash function wisely. Some have known collision weaknesses. sha384 and sha512 will be slow on 32 bit platforms. Hash objects have these methods: - update(arg): Update the hash object with the string arg. Repeated calls are equivalent to a single call with the concatenation of all the arguments. - digest(): Return the digest of the strings passed to the update() method so far. This may contain non-ASCII characters, including NUL bytes. - hexdigest(): Like digest() except the digest is returned as a string of double length, containing only hexadecimal digits. - copy(): Return a copy (clone) of the hash object. This can be used to efficiently compute the digests of strings that share a common initial substring. For example, to obtain the digest of the string 'Nobody inspects the spammish repetition': >>> import hashlib >>> m = hashlib.md5() >>> m.update("Nobody inspects") >>> m.update(" the spammish repetition") >>> m.digest() '\\xbbd\\x9c\\x83\\xdd\\x1e\\xa5\\xc9\\xd9\\xde\\xc9\\xa1\\x8d\\xf0\\xff\\xe9' More condensed: >>> hashlib.sha224("Nobody inspects the spammish repetition").hexdigest() 'a4337bc45a8fc544c03f52dc550cd6e1e87021bc896588bd79e901e2' """ # This tuple and __get_builtin_constructor() must be modified if a new # always available algorithm is added. __always_supported = ('md5', 'sha1', 'sha224', 'sha256', 'sha384', 'sha512') algorithms = __always_supported __all__ = __always_supported + ('new', 'algorithms') def __get_builtin_constructor(name): try: if name in ('SHA1', 'sha1'): import _sha return _sha.new elif name in ('MD5', 'md5'): import _md5 return _md5.new elif name in ('SHA256', 'sha256', 'SHA224', 'sha224'): import _sha256 bs = name[3:] if bs == '256': return _sha256.sha256 elif bs == '224': return _sha256.sha224 elif name in ('SHA512', 'sha512', 'SHA384', 'sha384'): import _sha512 bs = name[3:] if bs == '512': return _sha512.sha512 elif bs == '384': return _sha512.sha384 except ImportError: pass # no extension module, this hash is unsupported. raise ValueError('unsupported hash type ' + name) def __get_openssl_constructor(name): try: f = getattr(_hashlib, 'openssl_' + name) # Allow the C module to raise ValueError. The function will be # defined but the hash not actually available thanks to OpenSSL. f() # Use the C function directly (very fast) return f except (AttributeError, ValueError): return __get_builtin_constructor(name) def __py_new(name, string=''): """new(name, string='') - Return a new hashing object using the named algorithm; optionally initialized with a string. """ return __get_builtin_constructor(name)(string) def __hash_new(name, string=''): """new(name, string='') - Return a new hashing object using the named algorithm; optionally initialized with a string. """ try: return _hashlib.new(name, string) except ValueError: # If the _hashlib module (OpenSSL) doesn't support the named # hash, try using our builtin implementations. # This allows for SHA224/256 and SHA384/512 support even though # the OpenSSL library prior to 0.9.8 doesn't provide them. return __get_builtin_constructor(name)(string) try: import _hashlib new = __hash_new __get_hash = __get_openssl_constructor except ImportError: new = __py_new __get_hash = __get_builtin_constructor for __func_name in __always_supported: # try them all, some may not work due to the OpenSSL # version not supporting that algorithm. try: globals()[__func_name] = __get_hash(__func_name) except ValueError: import logging logging.exception('code for hash %s was not found.', __func_name) # Cleanup locals() del __always_supported, __func_name, __get_hash del __py_new, __hash_new, __get_openssl_constructor
gpl-2.0
spaceof7/QGIS
python/plugins/processing/algs/grass7/ext/r_li_edgedensity.py
5
1321
# -*- coding: utf-8 -*- """ *************************************************************************** r_li_edgedensity.py ------------------- Date : February 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__ = 'February 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$' from .r_li import checkMovingWindow, configFile def checkParameterValuesBeforeExecuting(alg): return checkMovingWindow(alg) def processCommand(alg, parameters): configFile(alg, parameters)
gpl-2.0
Maselkov/GW2Bot
guildwars2/evtc.py
1
12990
import datetime import aiohttp import discord from discord.ext import commands from discord.ext.commands.cooldowns import BucketType from .exceptions import APIError from .utils.chat import (embed_list_lines, en_space, magic_space, zero_width_space) UTC_TZ = datetime.timezone.utc BASE_URL = "https://dps.report/" UPLOAD_URL = BASE_URL + "uploadContent" JSON_URL = BASE_URL + "getJson" TOKEN_URL = BASE_URL + "getUserToken" ALLOWED_FORMATS = (".evtc", ".zevtc", ".zip") class EvtcMixin: async def get_dpsreport_usertoken(self, user): doc = await self.bot.database.get(user, self) token = doc.get("dpsreport_token") if not token: try: async with self.session.get(TOKEN_URL) as r: data = await r.json() token = data["userToken"] await self.bot.database.set( user, {"dpsreport_token": token}, self) return token except: return None async def upload_log(self, file, user): params = {"json": 1} token = await self.get_dpsreport_usertoken(user) if token: params["userToken"] = token data = aiohttp.FormData() data.add_field("file", await file.read(), filename=file.filename) async with self.session.post( UPLOAD_URL, data=data, params=params) as r: resp = await r.json() error = resp["error"] if error: raise APIError(error) return resp async def find_duplicate_dps_report(self, doc): margin_of_error = datetime.timedelta(seconds=10) doc = await self.db.encounters.find_one({ "boss_id": doc["boss_id"], "players": { "$eq": doc["players"] }, "date": { "$gte": doc["date"] - margin_of_error, "$lt": doc["date"] + margin_of_error }, "start_date": { "$gte": doc["start_date"] - margin_of_error, "$lt": doc["start_date"] + margin_of_error }, }) return True if doc else False async def upload_embed(self, ctx, result): if not result["encounter"]["jsonAvailable"]: return None async with self.session.get( JSON_URL, params={"id": result["id"]}) as r: data = await r.json() lines = [] targets = data["phases"][0]["targets"] group_dps = 0 for target in targets: group_dps += sum( p["dpsTargets"][target][0]["dps"] for p in data["players"]) def get_graph(percentage): bar_count = round(percentage / 5) bars = "" bars += "▀" * bar_count bars += "━" * (20 - bar_count) return bars def get_dps(player): bars = "" dps = player["dps"] if not group_dps or not dps: percentage = 0 else: percentage = round(100 / group_dps * dps) bars = get_graph(percentage) bars += f"` **{dps}** DPS | **{percentage}%** of group DPS" return bars players = [] for player in data["players"]: dps = 0 for target in targets: dps += player["dpsTargets"][target][0]["dps"] player["dps"] = dps players.append(player) players.sort(key=lambda p: p["dps"], reverse=True) for player in players: down_count = player["defenses"][0]["downCount"] prof = self.get_emoji(ctx, player["profession"]) line = f"{prof} **{player['name']}** *({player['account']})*" if down_count: line += (f" | {self.get_emoji(ctx, 'downed')}Downed " f"count: **{down_count}**") lines.append(line) dpses = [] charater_name_max_length = 19 for player in players: line = self.get_emoji(ctx, player["profession"]) align = (charater_name_max_length - len(player["name"])) * " " line += "`" + player["name"] + align + get_dps(player) dpses.append(line) dpses.append(f"> Group DPS: **{group_dps}**") color = discord.Color.green( ) if data["success"] else discord.Color.red() minutes, seconds = data["duration"].split()[:2] minutes = int(minutes[:-1]) seconds = int(seconds[:-1]) duration_time = (minutes * 60) + seconds duration = f"**{minutes}** minutes, **{seconds}** seconds" embed = discord.Embed( title="DPS Report", description="Encounter duration: " + duration, url=result["permalink"], color=color) boss_lines = [] for target in targets: target = data["targets"][target] if data["success"]: health_left = 0 else: percent_burned = target["healthPercentBurned"] health_left = 100 - percent_burned health_left = round(health_left, 2) if len(targets) > 1: boss_lines.append(f"**{target['name']}**") boss_lines.append(f"Health: **{health_left}%**") boss_lines.append(get_graph(health_left)) embed.add_field(name="> **BOSS**", value="\n".join(boss_lines)) buff_lines = [] sought_buffs = ["Might", "Fury", "Quickness", "Alacrity"] buffs = [] for buff in sought_buffs: for key, value in data["buffMap"].items(): if value["name"] == buff: buffs.append({ "name": value["name"], "id": int(key[1:]), "stacking": value["stacking"] }) break separator = 2 * en_space line = zero_width_space + (en_space * (charater_name_max_length + 6)) for buff in sought_buffs: line += self.get_emoji( ctx, buff, fallback=True, fallback_fmt="{:1.1}") + f"{separator}{2 * en_space}" buff_lines.append(line) groups = [] for player in players: if player["group"] not in groups: groups.append(player["group"]) if len(groups) > 1: players.sort(key=lambda p: p["group"]) current_group = None for player in players: if "buffUptimes" not in player: continue if len(groups) > 1: if not current_group or player["group"] != current_group: current_group = player["group"] buff_lines.append(f"> **GROUP {current_group}**") line = "`" line = self.get_emoji(ctx, player["profession"]) align = (3 + charater_name_max_length - len(player["name"])) * " " line += "`" + player["name"] + align for buff in buffs: for buff_uptime in player["buffUptimes"]: if buff["id"] == buff_uptime["id"]: uptime = str(buff_uptime["buffData"][0]["uptime"]) break else: uptime = "0" if not buff["stacking"]: uptime += "%" line += uptime line += separator + ((6 - len(uptime)) * magic_space) line += '`' buff_lines.append(line) embed = embed_list_lines(embed, lines, "> **PLAYERS**") embed = embed_list_lines(embed, dpses, "> **DPS**") embed = embed_list_lines(embed, buff_lines, "> **BUFFS**") boss = self.gamedata["bosses"].get(str(result["encounter"]["bossId"])) date_format = "%Y-%m-%d %H:%M:%S %z" date = datetime.datetime.strptime(data["timeEnd"] + "00", date_format) start_date = datetime.datetime.strptime(data["timeStart"] + "00", date_format) date = date.astimezone(datetime.timezone.utc) start_date = start_date.astimezone(datetime.timezone.utc) doc = { "boss_id": result["encounter"]["bossId"], "start_date": start_date, "date": date, "players": sorted([player["account"] for player in data["players"]]), "permalink": result["permalink"], "success": data["success"], "duration": duration_time } duplicate = await self.find_duplicate_dps_report(doc) if not duplicate: await self.db.encounters.insert_one(doc) embed.timestamp = date embed.set_footer(text="Recorded at", icon_url=self.bot.user.avatar_url) if boss: embed.set_author(name=data["fightName"], icon_url=boss["icon"]) return embed @commands.group(case_insensitive=True) async def evtc(self, ctx): """Process an EVTC combat log or enable automatic processing Simply upload your file and in the "add a comment" field type $evtc, in other words invoke this command while uploading a file. Use this command ($evtc) without uploading a file to see other commands Accepted formats are: .evtc, .zevtc, .zip It's highly recommended to enable compression in your Arc settings. With the setting enabled logs sized will rarely, if ever, be higher than the Discord upload limit """ if ctx.invoked_subcommand is None and not ctx.message.attachments: return await ctx.send_help(ctx.command) for attachment in ctx.message.attachments: if attachment.filename.endswith(ALLOWED_FORMATS): break else: return await ctx.send_help(ctx.command) if ctx.guild: doc = await self.bot.database.get(ctx.channel, self) settings = doc.get("evtc", {}) enabled = settings.get("enabled") if not ctx.channel.permissions_for(ctx.me).embed_links: return await ctx.send( "I need embed links permission to process logs.") if enabled: return await self.process_evtc(ctx.message) @commands.cooldown(1, 5, BucketType.guild) @commands.guild_only() @commands.has_permissions(manage_guild=True) @evtc.command(name="channel") async def evtc_channel(self, ctx): """Sets this channel to be automatically used to process logs""" doc = await self.bot.database.get(ctx.channel, self) enabled = not doc.get("evtc.enabled", False) await self.bot.database.set(ctx.channel, {"evtc.enabled": enabled}, self) if enabled: msg = ("Automatic EVTC processing enabled. Simply upload the file " "wish to be processed in this channel. Accepted " "formats: `.evtc`, `.zevtc`, `.zip` ") if not ctx.channel.permissions_for(ctx.me).embed_links: await ctx.send("I won't be able to process logs without Embed " "Links permission.") else: msg = ("Automatic EVTC processing diasbled") await ctx.send(msg) async def process_evtc(self, message): embeds = [] prompt = await message.channel.send("Processing logs... " + self.get_emoji(message, "loading")) for attachment in message.attachments: if attachment.filename.endswith(ALLOWED_FORMATS): try: resp = await self.upload_log(attachment, message.author) embeds.append(await self.upload_embed(message, resp)) except Exception as e: self.log.exception( "Exception processing EVTC log ", exc_info=e) return await prompt.edit( content="Error processing your log! :x:") for embed in embeds: await message.channel.send(embed=embed) try: await prompt.delete() await message.delete() except discord.HTTPException: pass @commands.Cog.listener() async def on_message(self, message): if not message.attachments: return if not message.guild: return for attachment in message.attachments: if attachment.filename.endswith(ALLOWED_FORMATS): break else: return doc = await self.bot.database.get(message.channel, self) settings = doc.get("evtc", {}) enabled = settings.get("enabled") if not enabled: return await self.process_evtc(message)
mit
cloudbase/nova-virtualbox
nova/openstack/common/uuidutils.py
9
1077
# Copyright (c) 2012 Intel Corporation. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. """ UUID related utilities and helper functions. """ import uuid def generate_uuid(): return str(uuid.uuid4()) def is_uuid_like(val): """Returns validation of a value as a UUID. For our purposes, a UUID is a canonical form string: aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa """ try: return str(uuid.UUID(val)).lower() == val.lower() except (TypeError, ValueError, AttributeError): return False
apache-2.0
AcalephStorage/ceph-docker
examples/kubernetes/rgw_s3_client.py
5
1326
#!/usr/bin/env python import boto import boto.s3.connection access_key = 'XXXXXXXXXXXXXXXXXXXX' secret_key = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX' conn = boto.connect_s3( aws_access_key_id = access_key, aws_secret_access_key = secret_key, host = '0.0.0.0', port = None, # Leave as None to use default port 80 or 443 is_secure=False, # comment out or set to True if you are using ssl calling_format = boto.s3.connection.OrdinaryCallingFormat(), ) bucket = conn.create_bucket('my-s3-test-bucket') for bucket in conn.get_all_buckets(): print "{name}\t{created}".format( name = bucket.name, created = bucket.creation_date, ) key = bucket.new_key('hello.txt') key.set_contents_from_string('Hello World!\n') hello_key = bucket.get_key('hello.txt') hello_key.set_canned_acl('public-read') key = bucket.new_key('secret_plans.txt') key.set_contents_from_string('My secret plans!\n') plans_key = bucket.get_key('secret_plans.txt') plans_key.set_canned_acl('private') hello_key = bucket.get_key('hello.txt') hello_url = hello_key.generate_url(0, query_auth=False, force_http=False) print hello_url plans_key = bucket.get_key('secret_plans.txt') plans_url = plans_key.generate_url(3600, query_auth=True, force_http=False) print plans_url
apache-2.0
DhashS/scala_comp_robo_sign_detection
src/main/venv/lib/python3.5/site-packages/setuptools/dist.py
79
37481
__all__ = ['Distribution'] import re import os import warnings import numbers import distutils.log import distutils.core import distutils.cmd import distutils.dist from distutils.errors import (DistutilsOptionError, DistutilsPlatformError, DistutilsSetupError) from distutils.util import rfc822_escape import six from six.moves import map import packaging from setuptools.depends import Require from setuptools import windows_support from setuptools.monkey import get_unpatched from setuptools.config import parse_configuration import pkg_resources from .py36compat import Distribution_parse_config_files def _get_unpatched(cls): warnings.warn("Do not call this function", DeprecationWarning) return get_unpatched(cls) # Based on Python 3.5 version def write_pkg_file(self, file): """Write the PKG-INFO format data to a file object. """ version = '1.0' if (self.provides or self.requires or self.obsoletes or self.classifiers or self.download_url): version = '1.1' # Setuptools specific for PEP 345 if hasattr(self, 'python_requires'): version = '1.2' file.write('Metadata-Version: %s\n' % version) file.write('Name: %s\n' % self.get_name()) file.write('Version: %s\n' % self.get_version()) file.write('Summary: %s\n' % self.get_description()) file.write('Home-page: %s\n' % self.get_url()) file.write('Author: %s\n' % self.get_contact()) file.write('Author-email: %s\n' % self.get_contact_email()) file.write('License: %s\n' % self.get_license()) if self.download_url: file.write('Download-URL: %s\n' % self.download_url) long_desc = rfc822_escape(self.get_long_description()) file.write('Description: %s\n' % long_desc) keywords = ','.join(self.get_keywords()) if keywords: file.write('Keywords: %s\n' % keywords) self._write_list(file, 'Platform', self.get_platforms()) self._write_list(file, 'Classifier', self.get_classifiers()) # PEP 314 self._write_list(file, 'Requires', self.get_requires()) self._write_list(file, 'Provides', self.get_provides()) self._write_list(file, 'Obsoletes', self.get_obsoletes()) # Setuptools specific for PEP 345 if hasattr(self, 'python_requires'): file.write('Requires-Python: %s\n' % self.python_requires) # from Python 3.4 def write_pkg_info(self, base_dir): """Write the PKG-INFO file into the release tree. """ with open(os.path.join(base_dir, 'PKG-INFO'), 'w', encoding='UTF-8') as pkg_info: self.write_pkg_file(pkg_info) sequence = tuple, list def check_importable(dist, attr, value): try: ep = pkg_resources.EntryPoint.parse('x=' + value) assert not ep.extras except (TypeError, ValueError, AttributeError, AssertionError): raise DistutilsSetupError( "%r must be importable 'module:attrs' string (got %r)" % (attr, value) ) def assert_string_list(dist, attr, value): """Verify that value is a string list or None""" try: assert ''.join(value) != value except (TypeError, ValueError, AttributeError, AssertionError): raise DistutilsSetupError( "%r must be a list of strings (got %r)" % (attr, value) ) def check_nsp(dist, attr, value): """Verify that namespace packages are valid""" ns_packages = value assert_string_list(dist, attr, ns_packages) for nsp in ns_packages: if not dist.has_contents_for(nsp): raise DistutilsSetupError( "Distribution contains no modules or packages for " + "namespace package %r" % nsp ) parent, sep, child = nsp.rpartition('.') if parent and parent not in ns_packages: distutils.log.warn( "WARNING: %r is declared as a package namespace, but %r" " is not: please correct this in setup.py", nsp, parent ) def check_extras(dist, attr, value): """Verify that extras_require mapping is valid""" try: for k, v in value.items(): if ':' in k: k, m = k.split(':', 1) if pkg_resources.invalid_marker(m): raise DistutilsSetupError("Invalid environment marker: " + m) list(pkg_resources.parse_requirements(v)) except (TypeError, ValueError, AttributeError): raise DistutilsSetupError( "'extras_require' must be a dictionary whose values are " "strings or lists of strings containing valid project/version " "requirement specifiers." ) def assert_bool(dist, attr, value): """Verify that value is True, False, 0, or 1""" if bool(value) != value: tmpl = "{attr!r} must be a boolean value (got {value!r})" raise DistutilsSetupError(tmpl.format(attr=attr, value=value)) def check_requirements(dist, attr, value): """Verify that install_requires is a valid requirements list""" try: list(pkg_resources.parse_requirements(value)) except (TypeError, ValueError) as error: tmpl = ( "{attr!r} must be a string or list of strings " "containing valid project/version requirement specifiers; {error}" ) raise DistutilsSetupError(tmpl.format(attr=attr, error=error)) def check_specifier(dist, attr, value): """Verify that value is a valid version specifier""" try: packaging.specifiers.SpecifierSet(value) except packaging.specifiers.InvalidSpecifier as error: tmpl = ( "{attr!r} must be a string or list of strings " "containing valid version specifiers; {error}" ) raise DistutilsSetupError(tmpl.format(attr=attr, error=error)) def check_entry_points(dist, attr, value): """Verify that entry_points map is parseable""" try: pkg_resources.EntryPoint.parse_map(value) except ValueError as e: raise DistutilsSetupError(e) def check_test_suite(dist, attr, value): if not isinstance(value, six.string_types): raise DistutilsSetupError("test_suite must be a string") def check_package_data(dist, attr, value): """Verify that value is a dictionary of package names to glob lists""" if isinstance(value, dict): for k, v in value.items(): if not isinstance(k, str): break try: iter(v) except TypeError: break else: return raise DistutilsSetupError( attr + " must be a dictionary mapping package names to lists of " "wildcard patterns" ) def check_packages(dist, attr, value): for pkgname in value: if not re.match(r'\w+(\.\w+)*', pkgname): distutils.log.warn( "WARNING: %r not a valid package name; please use only " ".-separated package names in setup.py", pkgname ) _Distribution = get_unpatched(distutils.core.Distribution) class Distribution(Distribution_parse_config_files, _Distribution): """Distribution with support for features, tests, and package data This is an enhanced version of 'distutils.dist.Distribution' that effectively adds the following new optional keyword arguments to 'setup()': 'install_requires' -- a string or sequence of strings specifying project versions that the distribution requires when installed, in the format used by 'pkg_resources.require()'. They will be installed automatically when the package is installed. If you wish to use packages that are not available in PyPI, or want to give your users an alternate download location, you can add a 'find_links' option to the '[easy_install]' section of your project's 'setup.cfg' file, and then setuptools will scan the listed web pages for links that satisfy the requirements. 'extras_require' -- a dictionary mapping names of optional "extras" to the additional requirement(s) that using those extras incurs. For example, this:: extras_require = dict(reST = ["docutils>=0.3", "reSTedit"]) indicates that the distribution can optionally provide an extra capability called "reST", but it can only be used if docutils and reSTedit are installed. If the user installs your package using EasyInstall and requests one of your extras, the corresponding additional requirements will be installed if needed. 'features' **deprecated** -- a dictionary mapping option names to 'setuptools.Feature' objects. Features are a portion of the distribution that can be included or excluded based on user options, inter-feature dependencies, and availability on the current system. Excluded features are omitted from all setup commands, including source and binary distributions, so you can create multiple distributions from the same source tree. Feature names should be valid Python identifiers, except that they may contain the '-' (minus) sign. Features can be included or excluded via the command line options '--with-X' and '--without-X', where 'X' is the name of the feature. Whether a feature is included by default, and whether you are allowed to control this from the command line, is determined by the Feature object. See the 'Feature' class for more information. 'test_suite' -- the name of a test suite to run for the 'test' command. If the user runs 'python setup.py test', the package will be installed, and the named test suite will be run. The format is the same as would be used on a 'unittest.py' command line. That is, it is the dotted name of an object to import and call to generate a test suite. 'package_data' -- a dictionary mapping package names to lists of filenames or globs to use to find data files contained in the named packages. If the dictionary has filenames or globs listed under '""' (the empty string), those names will be searched for in every package, in addition to any names for the specific package. Data files found using these names/globs will be installed along with the package, in the same location as the package. Note that globs are allowed to reference the contents of non-package subdirectories, as long as you use '/' as a path separator. (Globs are automatically converted to platform-specific paths at runtime.) In addition to these new keywords, this class also has several new methods for manipulating the distribution's contents. For example, the 'include()' and 'exclude()' methods can be thought of as in-place add and subtract commands that add or remove packages, modules, extensions, and so on from the distribution. They are used by the feature subsystem to configure the distribution for the included and excluded features. """ _patched_dist = None def patch_missing_pkg_info(self, attrs): # Fake up a replacement for the data that would normally come from # PKG-INFO, but which might not yet be built if this is a fresh # checkout. # if not attrs or 'name' not in attrs or 'version' not in attrs: return key = pkg_resources.safe_name(str(attrs['name'])).lower() dist = pkg_resources.working_set.by_key.get(key) if dist is not None and not dist.has_metadata('PKG-INFO'): dist._version = pkg_resources.safe_version(str(attrs['version'])) self._patched_dist = dist def __init__(self, attrs=None): have_package_data = hasattr(self, "package_data") if not have_package_data: self.package_data = {} _attrs_dict = attrs or {} if 'features' in _attrs_dict or 'require_features' in _attrs_dict: Feature.warn_deprecated() self.require_features = [] self.features = {} self.dist_files = [] self.src_root = attrs and attrs.pop("src_root", None) self.patch_missing_pkg_info(attrs) # Make sure we have any eggs needed to interpret 'attrs' if attrs is not None: self.dependency_links = attrs.pop('dependency_links', []) assert_string_list(self, 'dependency_links', self.dependency_links) if attrs and 'setup_requires' in attrs: self.fetch_build_eggs(attrs['setup_requires']) for ep in pkg_resources.iter_entry_points('distutils.setup_keywords'): vars(self).setdefault(ep.name, None) _Distribution.__init__(self, attrs) if isinstance(self.metadata.version, numbers.Number): # Some people apparently take "version number" too literally :) self.metadata.version = str(self.metadata.version) if self.metadata.version is not None: try: ver = packaging.version.Version(self.metadata.version) normalized_version = str(ver) if self.metadata.version != normalized_version: warnings.warn( "Normalizing '%s' to '%s'" % ( self.metadata.version, normalized_version, ) ) self.metadata.version = normalized_version except (packaging.version.InvalidVersion, TypeError): warnings.warn( "The version specified (%r) is an invalid version, this " "may not work as expected with newer versions of " "setuptools, pip, and PyPI. Please see PEP 440 for more " "details." % self.metadata.version ) if getattr(self, 'python_requires', None): self.metadata.python_requires = self.python_requires def parse_config_files(self, filenames=None): """Parses configuration files from various levels and loads configuration. """ _Distribution.parse_config_files(self, filenames=filenames) parse_configuration(self, self.command_options) def parse_command_line(self): """Process features after parsing command line options""" result = _Distribution.parse_command_line(self) if self.features: self._finalize_features() return result def _feature_attrname(self, name): """Convert feature name to corresponding option attribute name""" return 'with_' + name.replace('-', '_') def fetch_build_eggs(self, requires): """Resolve pre-setup requirements""" resolved_dists = pkg_resources.working_set.resolve( pkg_resources.parse_requirements(requires), installer=self.fetch_build_egg, replace_conflicting=True, ) for dist in resolved_dists: pkg_resources.working_set.add(dist, replace=True) return resolved_dists def finalize_options(self): _Distribution.finalize_options(self) if self.features: self._set_global_opts_from_features() for ep in pkg_resources.iter_entry_points('distutils.setup_keywords'): value = getattr(self, ep.name, None) if value is not None: ep.require(installer=self.fetch_build_egg) ep.load()(self, ep.name, value) if getattr(self, 'convert_2to3_doctests', None): # XXX may convert to set here when we can rely on set being builtin self.convert_2to3_doctests = [os.path.abspath(p) for p in self.convert_2to3_doctests] else: self.convert_2to3_doctests = [] def get_egg_cache_dir(self): egg_cache_dir = os.path.join(os.curdir, '.eggs') if not os.path.exists(egg_cache_dir): os.mkdir(egg_cache_dir) windows_support.hide_file(egg_cache_dir) readme_txt_filename = os.path.join(egg_cache_dir, 'README.txt') with open(readme_txt_filename, 'w') as f: f.write('This directory contains eggs that were downloaded ' 'by setuptools to build, test, and run plug-ins.\n\n') f.write('This directory caches those eggs to prevent ' 'repeated downloads.\n\n') f.write('However, it is safe to delete this directory.\n\n') return egg_cache_dir def fetch_build_egg(self, req): """Fetch an egg needed for building""" try: cmd = self._egg_fetcher cmd.package_index.to_scan = [] except AttributeError: from setuptools.command.easy_install import easy_install dist = self.__class__({'script_args': ['easy_install']}) dist.parse_config_files() opts = dist.get_option_dict('easy_install') keep = ( 'find_links', 'site_dirs', 'index_url', 'optimize', 'site_dirs', 'allow_hosts' ) for key in list(opts): if key not in keep: del opts[key] # don't use any other settings if self.dependency_links: links = self.dependency_links[:] if 'find_links' in opts: links = opts['find_links'][1].split() + links opts['find_links'] = ('setup', links) install_dir = self.get_egg_cache_dir() cmd = easy_install( dist, args=["x"], install_dir=install_dir, exclude_scripts=True, always_copy=False, build_directory=None, editable=False, upgrade=False, multi_version=True, no_report=True, user=False ) cmd.ensure_finalized() self._egg_fetcher = cmd return cmd.easy_install(req) def _set_global_opts_from_features(self): """Add --with-X/--without-X options based on optional features""" go = [] no = self.negative_opt.copy() for name, feature in self.features.items(): self._set_feature(name, None) feature.validate(self) if feature.optional: descr = feature.description incdef = ' (default)' excdef = '' if not feature.include_by_default(): excdef, incdef = incdef, excdef go.append(('with-' + name, None, 'include ' + descr + incdef)) go.append(('without-' + name, None, 'exclude ' + descr + excdef)) no['without-' + name] = 'with-' + name self.global_options = self.feature_options = go + self.global_options self.negative_opt = self.feature_negopt = no def _finalize_features(self): """Add/remove features and resolve dependencies between them""" # First, flag all the enabled items (and thus their dependencies) for name, feature in self.features.items(): enabled = self.feature_is_included(name) if enabled or (enabled is None and feature.include_by_default()): feature.include_in(self) self._set_feature(name, 1) # Then disable the rest, so that off-by-default features don't # get flagged as errors when they're required by an enabled feature for name, feature in self.features.items(): if not self.feature_is_included(name): feature.exclude_from(self) self._set_feature(name, 0) def get_command_class(self, command): """Pluggable version of get_command_class()""" if command in self.cmdclass: return self.cmdclass[command] for ep in pkg_resources.iter_entry_points('distutils.commands', command): ep.require(installer=self.fetch_build_egg) self.cmdclass[command] = cmdclass = ep.load() return cmdclass else: return _Distribution.get_command_class(self, command) def print_commands(self): for ep in pkg_resources.iter_entry_points('distutils.commands'): if ep.name not in self.cmdclass: # don't require extras as the commands won't be invoked cmdclass = ep.resolve() self.cmdclass[ep.name] = cmdclass return _Distribution.print_commands(self) def get_command_list(self): for ep in pkg_resources.iter_entry_points('distutils.commands'): if ep.name not in self.cmdclass: # don't require extras as the commands won't be invoked cmdclass = ep.resolve() self.cmdclass[ep.name] = cmdclass return _Distribution.get_command_list(self) def _set_feature(self, name, status): """Set feature's inclusion status""" setattr(self, self._feature_attrname(name), status) def feature_is_included(self, name): """Return 1 if feature is included, 0 if excluded, 'None' if unknown""" return getattr(self, self._feature_attrname(name)) def include_feature(self, name): """Request inclusion of feature named 'name'""" if self.feature_is_included(name) == 0: descr = self.features[name].description raise DistutilsOptionError( descr + " is required, but was excluded or is not available" ) self.features[name].include_in(self) self._set_feature(name, 1) def include(self, **attrs): """Add items to distribution that are named in keyword arguments For example, 'dist.exclude(py_modules=["x"])' would add 'x' to the distribution's 'py_modules' attribute, if it was not already there. Currently, this method only supports inclusion for attributes that are lists or tuples. If you need to add support for adding to other attributes in this or a subclass, you can add an '_include_X' method, where 'X' is the name of the attribute. The method will be called with the value passed to 'include()'. So, 'dist.include(foo={"bar":"baz"})' will try to call 'dist._include_foo({"bar":"baz"})', which can then handle whatever special inclusion logic is needed. """ for k, v in attrs.items(): include = getattr(self, '_include_' + k, None) if include: include(v) else: self._include_misc(k, v) def exclude_package(self, package): """Remove packages, modules, and extensions in named package""" pfx = package + '.' if self.packages: self.packages = [ p for p in self.packages if p != package and not p.startswith(pfx) ] if self.py_modules: self.py_modules = [ p for p in self.py_modules if p != package and not p.startswith(pfx) ] if self.ext_modules: self.ext_modules = [ p for p in self.ext_modules if p.name != package and not p.name.startswith(pfx) ] def has_contents_for(self, package): """Return true if 'exclude_package(package)' would do something""" pfx = package + '.' for p in self.iter_distribution_names(): if p == package or p.startswith(pfx): return True def _exclude_misc(self, name, value): """Handle 'exclude()' for list/tuple attrs without a special handler""" if not isinstance(value, sequence): raise DistutilsSetupError( "%s: setting must be a list or tuple (%r)" % (name, value) ) try: old = getattr(self, name) except AttributeError: raise DistutilsSetupError( "%s: No such distribution setting" % name ) if old is not None and not isinstance(old, sequence): raise DistutilsSetupError( name + ": this setting cannot be changed via include/exclude" ) elif old: setattr(self, name, [item for item in old if item not in value]) def _include_misc(self, name, value): """Handle 'include()' for list/tuple attrs without a special handler""" if not isinstance(value, sequence): raise DistutilsSetupError( "%s: setting must be a list (%r)" % (name, value) ) try: old = getattr(self, name) except AttributeError: raise DistutilsSetupError( "%s: No such distribution setting" % name ) if old is None: setattr(self, name, value) elif not isinstance(old, sequence): raise DistutilsSetupError( name + ": this setting cannot be changed via include/exclude" ) else: setattr(self, name, old + [item for item in value if item not in old]) def exclude(self, **attrs): """Remove items from distribution that are named in keyword arguments For example, 'dist.exclude(py_modules=["x"])' would remove 'x' from the distribution's 'py_modules' attribute. Excluding packages uses the 'exclude_package()' method, so all of the package's contained packages, modules, and extensions are also excluded. Currently, this method only supports exclusion from attributes that are lists or tuples. If you need to add support for excluding from other attributes in this or a subclass, you can add an '_exclude_X' method, where 'X' is the name of the attribute. The method will be called with the value passed to 'exclude()'. So, 'dist.exclude(foo={"bar":"baz"})' will try to call 'dist._exclude_foo({"bar":"baz"})', which can then handle whatever special exclusion logic is needed. """ for k, v in attrs.items(): exclude = getattr(self, '_exclude_' + k, None) if exclude: exclude(v) else: self._exclude_misc(k, v) def _exclude_packages(self, packages): if not isinstance(packages, sequence): raise DistutilsSetupError( "packages: setting must be a list or tuple (%r)" % (packages,) ) list(map(self.exclude_package, packages)) def _parse_command_opts(self, parser, args): # Remove --with-X/--without-X options when processing command args self.global_options = self.__class__.global_options self.negative_opt = self.__class__.negative_opt # First, expand any aliases command = args[0] aliases = self.get_option_dict('aliases') while command in aliases: src, alias = aliases[command] del aliases[command] # ensure each alias can expand only once! import shlex args[:1] = shlex.split(alias, True) command = args[0] nargs = _Distribution._parse_command_opts(self, parser, args) # Handle commands that want to consume all remaining arguments cmd_class = self.get_command_class(command) if getattr(cmd_class, 'command_consumes_arguments', None): self.get_option_dict(command)['args'] = ("command line", nargs) if nargs is not None: return [] return nargs def get_cmdline_options(self): """Return a '{cmd: {opt:val}}' map of all command-line options Option names are all long, but do not include the leading '--', and contain dashes rather than underscores. If the option doesn't take an argument (e.g. '--quiet'), the 'val' is 'None'. Note that options provided by config files are intentionally excluded. """ d = {} for cmd, opts in self.command_options.items(): for opt, (src, val) in opts.items(): if src != "command line": continue opt = opt.replace('_', '-') if val == 0: cmdobj = self.get_command_obj(cmd) neg_opt = self.negative_opt.copy() neg_opt.update(getattr(cmdobj, 'negative_opt', {})) for neg, pos in neg_opt.items(): if pos == opt: opt = neg val = None break else: raise AssertionError("Shouldn't be able to get here") elif val == 1: val = None d.setdefault(cmd, {})[opt] = val return d def iter_distribution_names(self): """Yield all packages, modules, and extension names in distribution""" for pkg in self.packages or (): yield pkg for module in self.py_modules or (): yield module for ext in self.ext_modules or (): if isinstance(ext, tuple): name, buildinfo = ext else: name = ext.name if name.endswith('module'): name = name[:-6] yield name def handle_display_options(self, option_order): """If there were any non-global "display-only" options (--help-commands or the metadata display options) on the command line, display the requested info and return true; else return false. """ import sys if six.PY2 or self.help_commands: return _Distribution.handle_display_options(self, option_order) # Stdout may be StringIO (e.g. in tests) import io if not isinstance(sys.stdout, io.TextIOWrapper): return _Distribution.handle_display_options(self, option_order) # Don't wrap stdout if utf-8 is already the encoding. Provides # workaround for #334. if sys.stdout.encoding.lower() in ('utf-8', 'utf8'): return _Distribution.handle_display_options(self, option_order) # Print metadata in UTF-8 no matter the platform encoding = sys.stdout.encoding errors = sys.stdout.errors newline = sys.platform != 'win32' and '\n' or None line_buffering = sys.stdout.line_buffering sys.stdout = io.TextIOWrapper( sys.stdout.detach(), 'utf-8', errors, newline, line_buffering) try: return _Distribution.handle_display_options(self, option_order) finally: sys.stdout = io.TextIOWrapper( sys.stdout.detach(), encoding, errors, newline, line_buffering) class Feature: """ **deprecated** -- The `Feature` facility was never completely implemented or supported, `has reported issues <https://github.com/pypa/setuptools/issues/58>`_ and will be removed in a future version. A subset of the distribution that can be excluded if unneeded/wanted Features are created using these keyword arguments: 'description' -- a short, human readable description of the feature, to be used in error messages, and option help messages. 'standard' -- if true, the feature is included by default if it is available on the current system. Otherwise, the feature is only included if requested via a command line '--with-X' option, or if another included feature requires it. The default setting is 'False'. 'available' -- if true, the feature is available for installation on the current system. The default setting is 'True'. 'optional' -- if true, the feature's inclusion can be controlled from the command line, using the '--with-X' or '--without-X' options. If false, the feature's inclusion status is determined automatically, based on 'availabile', 'standard', and whether any other feature requires it. The default setting is 'True'. 'require_features' -- a string or sequence of strings naming features that should also be included if this feature is included. Defaults to empty list. May also contain 'Require' objects that should be added/removed from the distribution. 'remove' -- a string or list of strings naming packages to be removed from the distribution if this feature is *not* included. If the feature *is* included, this argument is ignored. This argument exists to support removing features that "crosscut" a distribution, such as defining a 'tests' feature that removes all the 'tests' subpackages provided by other features. The default for this argument is an empty list. (Note: the named package(s) or modules must exist in the base distribution when the 'setup()' function is initially called.) other keywords -- any other keyword arguments are saved, and passed to the distribution's 'include()' and 'exclude()' methods when the feature is included or excluded, respectively. So, for example, you could pass 'packages=["a","b"]' to cause packages 'a' and 'b' to be added or removed from the distribution as appropriate. A feature must include at least one 'requires', 'remove', or other keyword argument. Otherwise, it can't affect the distribution in any way. Note also that you can subclass 'Feature' to create your own specialized feature types that modify the distribution in other ways when included or excluded. See the docstrings for the various methods here for more detail. Aside from the methods, the only feature attributes that distributions look at are 'description' and 'optional'. """ @staticmethod def warn_deprecated(): warnings.warn( "Features are deprecated and will be removed in a future " "version. See https://github.com/pypa/setuptools/issues/65.", DeprecationWarning, stacklevel=3, ) def __init__(self, description, standard=False, available=True, optional=True, require_features=(), remove=(), **extras): self.warn_deprecated() self.description = description self.standard = standard self.available = available self.optional = optional if isinstance(require_features, (str, Require)): require_features = require_features, self.require_features = [ r for r in require_features if isinstance(r, str) ] er = [r for r in require_features if not isinstance(r, str)] if er: extras['require_features'] = er if isinstance(remove, str): remove = remove, self.remove = remove self.extras = extras if not remove and not require_features and not extras: raise DistutilsSetupError( "Feature %s: must define 'require_features', 'remove', or at least one" " of 'packages', 'py_modules', etc." ) def include_by_default(self): """Should this feature be included by default?""" return self.available and self.standard def include_in(self, dist): """Ensure feature and its requirements are included in distribution You may override this in a subclass to perform additional operations on the distribution. Note that this method may be called more than once per feature, and so should be idempotent. """ if not self.available: raise DistutilsPlatformError( self.description + " is required, " "but is not available on this platform" ) dist.include(**self.extras) for f in self.require_features: dist.include_feature(f) def exclude_from(self, dist): """Ensure feature is excluded from distribution You may override this in a subclass to perform additional operations on the distribution. This method will be called at most once per feature, and only after all included features have been asked to include themselves. """ dist.exclude(**self.extras) if self.remove: for item in self.remove: dist.exclude_package(item) def validate(self, dist): """Verify that feature makes sense in context of distribution This method is called by the distribution just before it parses its command line. It checks to ensure that the 'remove' attribute, if any, contains only valid package/module names that are present in the base distribution when 'setup()' is called. You may override it in a subclass to perform any other required validation of the feature against a target distribution. """ for item in self.remove: if not dist.has_contents_for(item): raise DistutilsSetupError( "%s wants to be able to remove %s, but the distribution" " doesn't contain any packages or modules under %s" % (self.description, item, item) )
gpl-3.0
juhnowski/FishingRod
production/pygsl-0.9.5/tests/block_test.py
1
60228
#!/usr/bin/env python # Author : Pierre Schnizer import types import tempfile import pygsl import pygsl._numobj as nummodule from pygsl import vector, ArrayType from pygsl import matrix_pierre matrix = matrix_pierre from pygsl import _block, get_typecode from array_check import myord, myorda, array_check import unittest import sys sys.stderr = sys.stdout #pygsl.set_debug_level(10) def getopentmpfile(mode='rb'): file = tempfile.TemporaryFile(mode) assert(type(file.file) == types.FileType) return file.file class _DefaultTestCase(unittest.TestCase): _type = '' _base = None _reference_value = 137 #_retrieve = None def setUp(self): #print "Testing class ", self.__class__.__name__ sys.stdout.flush() sys.stderr.flush() self._mysetUp() def _get_reference_value(self): return self._reference_value def _get_format(self): return self._format def _get_function_direct(self, suffix=None): """ translate some prefix to the full qualified name of the block """ if suffix == None: suffix = self.function if self._type == '': tmp = '_' else: tmp = '_' + self._type + '_' # base is matrix or vector or ..... assert self._base != None, 'Use a derived class!' base = self._base function = eval('_block.gsl_' + base + tmp + suffix) return function def _get_function_ui(self, suffix=None): """ Get the method to the underlying function from the UI. """ if suffix == None: suffix = self.function if self._type == '': tmp = '.' else: tmp = '.' + self._type + '.' # base is matrix or vector or ..... assert self._base != None, 'Use a derived class!' base = self._base function = eval(base + tmp + suffix) return function def _get_function(self, suffix=None): if self._retrieve == 'direct': return self._get_function_direct(suffix) elif self._retrieve == 'UI': return self._get_function_ui(suffix) else: tmp = str(self._retrieve) raise ValueError, "Unknown switch for _retrieve: " + tmp def test_0_matrixtype(self): test = 0 try: assert type(self.array) == ArrayType, "Not an array type" test = 1 finally: if test == 0: print "Expected a type of %s but got a type of %s" %(ArrayType, type(self.array)) def tearDown(self): self._mytearDown() class _DirectAccess: _retrieve = 'direct' class _UIAccess: _retrieve = 'UI' class _DefaultMatrixTestCase(_DefaultTestCase): _base = 'matrix' class _DefaultVectorTestCase(_DefaultTestCase): _base = 'vector' class _DoubleMatrixTestCase(_DefaultMatrixTestCase): _type = '' _format = '%f' class _FloatMatrixTestCase(_DefaultMatrixTestCase): _type = 'float' _format = '%f' class _ComplexMatrixTestCase(_DefaultMatrixTestCase): _type = 'complex' _format = '%f' class _ComplexFloatMatrixTestCase(_DefaultMatrixTestCase): _type = 'complex_float' _format = '%f' class _LongMatrixTestCase(_DefaultMatrixTestCase): _type = 'long' _format = '%ld' class _IntMatrixTestCase(_DefaultMatrixTestCase): _type = 'int' _format = '%d' class _ShortMatrixTestCase(_DefaultMatrixTestCase): _type = 'short' _format = '%d' class _CharMatrixTestCase(_DefaultMatrixTestCase): _type = 'char' _format = '%c' class _DoubleVectorTestCase(_DefaultVectorTestCase): _type = '' _format = '%f' class _FloatVectorTestCase(_DefaultVectorTestCase): _type = 'float' _format = '%f' class _ComplexVectorTestCase(_DefaultVectorTestCase): _type = 'complex' _format = '%f' class _ComplexFloatVectorTestCase(_DefaultVectorTestCase): _type = 'complex_float' _format = '%f' class _LongVectorTestCase(_DefaultVectorTestCase): _type = 'long' _format = '%ld' class _IntVectorTestCase(_DefaultVectorTestCase): _type = 'int' _format = '%d' class _ShortVectorTestCase(_DefaultVectorTestCase): _type = 'short' _format = '%d' class _CharVectorTestCase(_DefaultVectorTestCase): _type = 'char' _format = '%c' _reference_value = chr(137) class _SetIdentityMatrixTestCase(_DefaultMatrixTestCase): function = 'set_identity' size = 10 def _mysetUp(self): tmp = self._get_function() self.array = tmp((self.size, self.size)) def test_1_matrixsize(self): array_check(self.array, None, (self.size, self.size)) def test_2_diagonale(self): for i in range(self.size): assert self.array[i,i] == 1, "Diagonale not one !" def test_3_diagonale(self): for i in range(self.size): for j in range(self.size): if i == j : continue assert self.array[i,j] == 0, "Of Diagonale not zero!" def _mytearDown(self): del self.array self.array = None class SetIdentityMatrixTestCase(_DoubleMatrixTestCase, _DirectAccess, _SetIdentityMatrixTestCase, ): pass class SetIdentityMatrixUITestCase(_DoubleMatrixTestCase, _UIAccess, _SetIdentityMatrixTestCase, ): pass class SetIdentityFloatMatrixTestCase(_FloatMatrixTestCase, _DirectAccess, _SetIdentityMatrixTestCase, ): pass class SetIdentityComplexMatrixTestCase(_ComplexMatrixTestCase, _DirectAccess, _SetIdentityMatrixTestCase, ): pass class SetIdentityComplexFloatMatrixTestCase(_ComplexFloatMatrixTestCase, _DirectAccess, _SetIdentityMatrixTestCase, ): pass class SetIdentityLongMatrixTestCase(_LongMatrixTestCase, _DirectAccess, _SetIdentityMatrixTestCase, ): pass class SetIdentityIntMatrixTestCase(_IntMatrixTestCase, _DirectAccess, _SetIdentityMatrixTestCase, ): pass class SetIdentityShortMatrixTestCase(_ShortMatrixTestCase, _DirectAccess, _SetIdentityMatrixTestCase, ): pass class SetIdentityFloatMatrixUITestCase(_FloatMatrixTestCase, _UIAccess, _SetIdentityMatrixTestCase, ): pass class SetIdentityComplexMatrixUITestCase(_ComplexMatrixTestCase, _UIAccess, _SetIdentityMatrixTestCase, ): pass class SetIdentityComplexFloatMatrixUITestCase(_ComplexFloatMatrixTestCase, _UIAccess, _SetIdentityMatrixTestCase, ): pass class SetIdentityLongMatrixUITestCase(_LongMatrixTestCase, _UIAccess, _SetIdentityMatrixTestCase, ): pass class SetIdentityIntMatrixUITestCase(_IntMatrixTestCase, _UIAccess, _SetIdentityMatrixTestCase, ): pass class SetIdentityShortMatrixUITestCase(_ShortMatrixTestCase, _UIAccess, _SetIdentityMatrixTestCase, ): pass class SetIdentityCharMatrixTestCase(_CharMatrixTestCase, _UIAccess, _SetIdentityMatrixTestCase, ): def test_2_diagonale(self): for i in range(self.size): assert myord(self.array[i,i][0]) == 1, "Diagonale not one !" def test_3_diagonale(self): for i in range(self.size): for j in range(self.size): if i == j : continue test = 0 try: assert myord(self.array[i,j][0]) == 0, "Of Diagonale not zero!" test = 1 finally: if test == 0: print self.array print self.array[i,j] class SetIdentityCharMatrixTestCase(_CharMatrixTestCase, _DirectAccess, _SetIdentityMatrixTestCase, ): def test_2_diagonale(self): for i in range(self.size): assert myorda(self.array[i,i]) == 1, "Diagonale not one !" def test_3_diagonale(self): for i in range(self.size): for j in range(self.size): if i == j : continue assert myorda(self.array[i,j]) == 0, "Of Diagonale not zero!" class _SetZeroMatrixTestCase(_DefaultMatrixTestCase): function = 'set_zero' size = 10 def _mysetUp(self): tmp = self._get_function() self.array = tmp((self.size, self.size)) def test_1_matrixsize(self): array_check(self.array, None, (self.size, self.size)) def test_2_all(self): for i in range(self.size): for j in range(self.size): assert self.array[i,j] == 0, "Off Diagonale not zero!" def test_2_isnull(self): tmp = self._get_function('isnull') test = 0 try: a = tmp(self.array) test = 1 finally: if test == 0: print self, tmp assert tmp(self.array) def _mytearDown(self): del self.array self.array = None class SetZeroMatrixTestCase(_DoubleMatrixTestCase, _DirectAccess, _SetZeroMatrixTestCase, ): pass class SetZeroFloatMatrixTestCase(_FloatMatrixTestCase, _DirectAccess, _SetZeroMatrixTestCase, ): pass class SetZeroComplexMatrixTestCase(_ComplexMatrixTestCase, _DirectAccess, _SetZeroMatrixTestCase, ): pass class SetZeroComplexFloatMatrixTestCase(_ComplexFloatMatrixTestCase, _DirectAccess, _SetZeroMatrixTestCase, ): pass class SetZeroLongMatrixTestCase(_LongMatrixTestCase, _DirectAccess, _SetZeroMatrixTestCase, ): pass class SetZeroIntMatrixTestCase(_IntMatrixTestCase, _DirectAccess, _SetZeroMatrixTestCase, ): pass class SetZeroShortMatrixTestCase(_ShortMatrixTestCase, _DirectAccess, _SetZeroMatrixTestCase, ): pass class SetZeroMatrixUITestCase(_DoubleMatrixTestCase, _UIAccess, _SetZeroMatrixTestCase, ): pass class SetZeroFloatMatrixUITestCase(_FloatMatrixTestCase, _UIAccess, _SetZeroMatrixTestCase, ): pass class SetZeroComplexMatrixUITestCase(_ComplexMatrixTestCase, _UIAccess, _SetZeroMatrixTestCase, ): pass class SetZeroComplexFloatMatrixUITestCase(_ComplexFloatMatrixTestCase, _UIAccess, _SetZeroMatrixTestCase, ): pass class SetZeroLongMatrixUITestCase(_LongMatrixTestCase, _UIAccess, _SetZeroMatrixTestCase, ): pass class SetZeroIntMatrixUITestCase(_IntMatrixTestCase, _UIAccess, _SetZeroMatrixTestCase, ): pass class SetZeroShortMatrixUITestCase(_ShortMatrixTestCase, _UIAccess, _SetZeroMatrixTestCase, ): pass class SetZeroCharMatrixTestCase(_CharMatrixTestCase, _DirectAccess, _SetZeroMatrixTestCase, ): def test_2_all(self): for i in range(self.size): for j in range(self.size): test = 0 try: assert myorda(self.array[i,j]) == 0, "Of Diagonale not zero!" test = 1 finally: if test == 0: print repr(self.array[i,j]) class SetZeroCharMatrixUITestCase(_CharMatrixTestCase, _UIAccess, _SetZeroMatrixTestCase, ): def test_2_all(self): for i in range(self.size): for j in range(self.size): test = 0 try: assert myorda(self.array[i,j]) == 0, "Of Diagonale not zero!" test = 1 finally: if test == 0: print repr(self.array[i,j]) class _SetAllMatrixTestCase(_DefaultMatrixTestCase): function = 'set_all' size = 10 def _mysetUp(self): tmp = self._get_function() self.array = tmp((self.size, self.size), self._get_reference_value()) def test_1_matrixsize(self): array_check(self.array, None, (self.size, self.size)) def test_2_all(self): for i in range(self.size): for j in range(self.size): assert self.array[i,j] == self._get_reference_value(), "Value not 137!" def _mytearDown(self): del self.array self.array = None class SetAllFloatMatrixTestCase(_FloatMatrixTestCase, _DirectAccess, _SetAllMatrixTestCase, ): pass class SetAllComplexMatrixTestCase(_ComplexMatrixTestCase, _DirectAccess, _SetAllMatrixTestCase, ): def _mysetUp(self): tmp = self._get_function() self.array = tmp((self.size, self.size), self._get_reference_value()+0j) class SetAllComplexFloatMatrixTestCase(_ComplexFloatMatrixTestCase, _DirectAccess, _SetAllMatrixTestCase, ): def _mysetUp(self): tmp = self._get_function() self.array = tmp((self.size, self.size), 137+0j) class SetAllLongMatrixTestCase(_LongMatrixTestCase, _DirectAccess, _SetAllMatrixTestCase, ): pass class SetAllIntMatrixTestCase(_IntMatrixTestCase, _DirectAccess, _SetAllMatrixTestCase, ): pass class SetAllShortMatrixTestCase(_ShortMatrixTestCase, _DirectAccess, _SetAllMatrixTestCase, ): pass class SetAllFloatMatrixUITestCase(_FloatMatrixTestCase, _UIAccess, _SetAllMatrixTestCase, ): pass class SetAllComplexMatrixUITestCase(_ComplexMatrixTestCase, _UIAccess, _SetAllMatrixTestCase, ): def _mysetUp(self): tmp = self._get_function() self.array = tmp((self.size, self.size), 137+0j) class SetAllComplexFloatMatrixUITestCase(_ComplexFloatMatrixTestCase, _UIAccess, _SetAllMatrixTestCase, ): def _mysetUp(self): tmp = self._get_function() self.array = tmp((self.size, self.size), 137+0j) class SetAllLongMatrixUITestCase(_LongMatrixTestCase, _UIAccess, _SetAllMatrixTestCase, ): pass class SetAllIntMatrixUITestCase(_IntMatrixTestCase, _UIAccess, _SetAllMatrixTestCase, ): pass class SetAllShortMatrixUITestCase(_ShortMatrixTestCase, _UIAccess, _SetAllMatrixTestCase, ): pass class _MatrixSetup: def _mysetUp(self): tmp = self._get_function() self.array = tmp((self.size, self.size), chr(137)) def test_2_all(self): for i in range(self.size): for j in range(self.size): assert myorda(self.array[i,j]) == 137, "Of Diagonale not zero!" class SetAllCharMatrixTestCase(_CharMatrixTestCase, _DirectAccess, _MatrixSetup, _SetAllMatrixTestCase, ): pass class SetAllCharMatrixUITestCase(_CharMatrixTestCase, _UIAccess, _MatrixSetup, _SetAllMatrixTestCase, ): pass class _DiagonalMatrixTestCase(_DefaultMatrixTestCase): size = 4 def _mysetUp(self): tmp = self._get_function('set_zero') array = tmp((self.size, self.size)) type = get_typecode(array) array = nummodule.zeros((self.size,self.size)).astype(type) for i in range(self.size): for j in range(self.size): if i < j: array[i,j] = -i else: array[i,j] = i self.array = array def test_1_matrixsize(self): array_check(self.array, None, (self.size, self.size)) def _gettranspose(self): function = self._get_function('transpose') tmp = function(self.array) assert(tmp[0] == 0) return tmp[1] def test_2_matrixsizetranspose(self): tmp = self._gettranspose() assert tmp.shape == (self.size, self.size), "Not of size 10, 10" def test_3_diagonal(self): function = self._get_function('diagonal') tmp = function(self.array) for i in range(self.size): msg = "Error in getting diagonal! tmp[+"+`i`+"] = " + `tmp` #assert tmp[i] == i, msg def test_4_diagonaltranspose(self): tmp = self._gettranspose() for i in range(self.size): msg = "Error in getting diagonal! tmp[+"+`i`+"] = " + `tmp` #assert tmp[i,i] == i, msg def test_5_super_diagonal(self): function = self._get_function('superdiagonal') for j in range(1,self.size): tmp = function(self.array, j) for i in range(self.size - j): #assert tmp[i,j] == i*-1, "Error in getting super diagonal!" pass def test_6_super_diagonaltranspose(self): function = self._get_function('superdiagonal') array = self._gettranspose() for j in range(1,self.size): tmp = function(array, j) for i in range(self.size - j): msg = "Error in getting super diagonal! tmp[+"+`i`+"] = " + `tmp` #assert tmp[i,j] == i*1+j, msg def test_7_sub_diagonal(self): function = self._get_function('subdiagonal') for j in range(1,self.size): tmp = function(self.array, j) for i in range(self.size - j): assert tmp[i] == i+j, "Error in getting sub diagonal!" def _mytearDown(self): del self.array self.array = None class DiagonaMatrixTestCase(_DoubleMatrixTestCase, _DirectAccess, _DiagonalMatrixTestCase, ): pass class DiagonalFloatMatrixTestCase(_FloatMatrixTestCase, _DirectAccess, _DiagonalMatrixTestCase, ): pass class DiagonalComplexMatrixTestCase(_ComplexMatrixTestCase, _DirectAccess, _DiagonalMatrixTestCase, ): pass class DiagonalComplexFloatMatrixTestCase(_ComplexFloatMatrixTestCase, _DirectAccess, _DiagonalMatrixTestCase, ): pass class DiagonalLongMatrixTestCase(_LongMatrixTestCase, _DirectAccess, _DiagonalMatrixTestCase, ): pass class DiagonalIntMatrixTestCase(_IntMatrixTestCase, _DirectAccess, _DiagonalMatrixTestCase, ): pass class DiagonalShortMatrixTestCase(_ShortMatrixTestCase, _DirectAccess, _DiagonalMatrixTestCase, ): pass class DiagonaMatrixUITestCase(_DoubleMatrixTestCase, _UIAccess, _DiagonalMatrixTestCase, ): pass class DiagonalFloatMatrixUITestCase(_FloatMatrixTestCase, _UIAccess, _DiagonalMatrixTestCase, ): pass class DiagonalComplexMatrixUITestCase(_ComplexMatrixTestCase, _UIAccess, _DiagonalMatrixTestCase, ): pass class DiagonalComplexFloatMatrixUITestCase(_ComplexFloatMatrixTestCase, _UIAccess, _DiagonalMatrixTestCase, ): pass class DiagonalLongMatrixUITestCase(_LongMatrixTestCase, _UIAccess, _DiagonalMatrixTestCase, ): pass class DiagonalIntMatrixUITestCase(_IntMatrixTestCase, _UIAccess, _DiagonalMatrixTestCase, ): pass class DiagonalShortMatrixUITestCase(_ShortMatrixTestCase, _UIAccess, _DiagonalMatrixTestCase, ): pass class _MinMaxMatrixTestCase(_DefaultMatrixTestCase): size = 10 def _mysetUp(self): tmp = self._get_function('set_zero') array = tmp((self.size, self.size)) type = get_typecode(array) array = nummodule.zeros((self.size,self.size)).astype(type) array[5,4] = -1 array[8,7] = 1 self.array = array def test_max(self): function = self._get_function('max') assert(function(self.array)== 1) def test_min(self): function = self._get_function('min') assert(function(self.array)== -1) def test_minmax(self): function = self._get_function('minmax') tmp = function(self.array) assert(tmp[0] == -1) assert(tmp[1] == 1) def test_minmax(self): function = self._get_function('minmax') tmp = function(self.array) assert(tmp[0] == -1) assert(tmp[1] == 1) def test_maxindex(self): function = self._get_function('max_index') tmp = function(self.array) assert(tmp[0] == 8) assert(tmp[1] == 7) def test_minindex(self): function = self._get_function('min_index') tmp = function(self.array) assert(tmp[0] == 5) assert(tmp[1] == 4) def test_minmaxindex(self): function = self._get_function('minmax_index') tmp = function(self.array) assert(tmp[0] == 5) assert(tmp[1] == 4) assert(tmp[2] == 8) assert(tmp[3] == 7) def _mytearDown(self): pass class MinMaxMatrixTestCase(_DoubleMatrixTestCase, _DirectAccess, _MinMaxMatrixTestCase, ): pass class MinMaxFloatMatrixTestCase(_FloatMatrixTestCase, _DirectAccess, _MinMaxMatrixTestCase, ): pass class MinMaxLongMatrixTestCase(_LongMatrixTestCase, _DirectAccess, _MinMaxMatrixTestCase, ): pass class MinMaxIntMatrixTestCase(_IntMatrixTestCase, _DirectAccess, _MinMaxMatrixTestCase, ): pass class MinMaxShortMatrixTestCase(_ShortMatrixTestCase, _DirectAccess, _MinMaxMatrixTestCase, ): pass class MinMaxMatrixUITestCase(_DoubleMatrixTestCase, _UIAccess, _MinMaxMatrixTestCase, ): pass class MinMaxFloatMatrixUITestCase(_FloatMatrixTestCase, _UIAccess, _MinMaxMatrixTestCase, ): pass class MinMaxLongMatrixUITestCase(_LongMatrixTestCase, _UIAccess, _MinMaxMatrixTestCase, ): pass class MinMaxIntMatrixUITestCase(_IntMatrixTestCase, _UIAccess, _MinMaxMatrixTestCase, ): pass class MinMaxShortMatrixUITestCase(_ShortMatrixTestCase, _UIAccess, _MinMaxMatrixTestCase, ): pass class _SwapMatrixTestCase(_DefaultMatrixTestCase): size = 10 def _mysetUp(self): tmp = self._get_function('set_zero') array = tmp((self.size, self.size)) type = get_typecode(array) array = nummodule.fromfunction(lambda x,y,size=self.size : x*size + y, (self.size, self.size)) self.array = array.astype(type) self.array1 = (array*10).astype(type) def test_1_swap(self): function = self._get_function('swap') type = get_typecode(self.array) tmp = function(self.array, self.array1) function = self._get_function('isnull') assert(function((tmp[1]/10).astype(type) - tmp[2])) def test_2_swap_columns(self): function = self._get_function('swap_columns') tmp = function(self.array, 3, 5) assert(tmp[0] == 0) for i in range(self.size): assert(tmp[1][i,3]==10*i+5) assert(tmp[1][i,5]==10*i+3) def test_3_swap_rows(self): function = self._get_function('swap_rows') tmp = function(self.array, 3, 5) assert(tmp[0] == 0) for i in range(self.size): assert(tmp[1][3,i]==i+50) assert(tmp[1][5,i]==i+30) def test_4_swap_rowcol(self): function = self._get_function('swap_rowcol') tmp = function(self.array, 3, 5) assert(tmp[0] == 0) for i in range(self.size): assert(tmp[1][3,i]==10*i+5) for i in range(self.size): if i == 3: assert(tmp[1][3,5] == 55) elif i == 5: assert(tmp[1][5,5] == 33) else: assert(tmp[1][i,5]==30+i) # def test_5_fwrite(self): # print "Seek finished " # file = getopentmpfile('w') # function = self._get_function('fwrite') # tmp = function(file, self.array) # # def test_6_fread(self): # # file = getopentmpfile('w+') # function = self._get_function('fwrite') # tmp = function(file, (self.array * 2).astype(self.get_typecode(array))) # assert(tmp == 0) # file.seek(0) # # function = self._get_function('fread') # tmp = function(file, self.array.shape) # assert(tmp[0] == 0) # for i in range(self.size): # for j in range(self.size): # assert(tmp[1][i,j] == self.array[i,j] * 2) # # # def test_7_fprintf(self): # file = getopentmpfile('w') # function = self._get_function('fprintf') # tmp = function(file, self.array, self._get_format()) # assert(tmp == 0) # # def test_8_fscanf(self): # file = getopentmpfile('w+') # function = self._get_function('fprintf') # ttype = self.get_typecode(array) # tmp = function(file, (self.array*2).astype(ttype), self._get_format()) # # function = self._get_function('fscanf') # file.seek(0) # # tmp = function(file, self.array.shape) # assert(tmp[0] == 0) # for i in range(self.size): # for j in range(self.size): # assert(tmp[1][i,j] == self.array[i,j] * 2) def _mytearDown(self): pass class SwapMatrixTestCase(_DoubleMatrixTestCase, _DirectAccess, _SwapMatrixTestCase, ): pass class SwapFloatMatrixTestCase(_FloatMatrixTestCase, _DirectAccess, _SwapMatrixTestCase, ): pass class SwapComplexMatrixTestCase(_ComplexMatrixTestCase, _DirectAccess, _SwapMatrixTestCase, ): pass class SwapComplexFloatMatrixTestCase(_ComplexFloatMatrixTestCase, _DirectAccess, _SwapMatrixTestCase, ): pass class SwapLongMatrixTestCase(_LongMatrixTestCase, _DirectAccess, _SwapMatrixTestCase, ): pass class SwapIntMatrixTestCase(_IntMatrixTestCase, _DirectAccess, _SwapMatrixTestCase, ): pass class SwapShortMatrixTestCase(_ShortMatrixTestCase, _DirectAccess, _SwapMatrixTestCase, ): pass class SwapMatrixUITestCase(_DoubleMatrixTestCase, _UIAccess, _SwapMatrixTestCase, ): pass class SwapFloatMatrixUITestCase(_FloatMatrixTestCase, _UIAccess, _SwapMatrixTestCase, ): pass class SwapComplexMatrixUITestCase(_ComplexMatrixTestCase, _UIAccess, _SwapMatrixTestCase, ): pass class SwapComplexFloatMatrixUITestCase(_ComplexFloatMatrixTestCase, _UIAccess, _SwapMatrixTestCase, ): pass class SwapLongMatrixUITestCase(_LongMatrixTestCase, _UIAccess, _SwapMatrixTestCase, ): pass class SwapIntMatrixUITestCase(_IntMatrixTestCase, _UIAccess, _SwapMatrixTestCase, ): pass class SwapShortMatrixUITestCase(_ShortMatrixTestCase, _UIAccess, _SwapMatrixTestCase, ): pass # ---------------------------------------------------------------------------- # ---------------------------------------------------------------------------- # Vectors # ---------------------------------------------------------------------------- # ---------------------------------------------------------------------------- class _SetBasisVectorTestCase(_DefaultVectorTestCase): function = 'set_basis' size = 10 basis = 5 def _mysetUp(self): tmp = self._get_function() basis = self.basis tmp1 = tmp(self.size, basis) assert(tmp1[0] == 0) self.array = tmp1[1] def test_1_matrixsize(self): array_check(self.array, None, (self.size,)) def test_2_diagonale(self): assert self.array[self.basis] == 1, "Basis not one !" def test_3_diagonale(self): for i in range(self.size): if i == self.basis : continue assert self.array[i] == 0, "Basis not zero!" def _mytearDown(self): del self.array self.array = None class SetBasisVectorTestCase(_DoubleVectorTestCase, _DirectAccess, _SetBasisVectorTestCase, ): pass class SetBasisVectorUITestCase(_DoubleVectorTestCase, _UIAccess, _SetBasisVectorTestCase, ): pass class SetBasisFloatVectorTestCase(_FloatVectorTestCase, _DirectAccess, _SetBasisVectorTestCase, ): pass class SetBasisComplexVectorTestCase(_ComplexVectorTestCase, _DirectAccess, _SetBasisVectorTestCase, ): pass class SetBasisComplexFloatVectorTestCase(_ComplexFloatVectorTestCase, _DirectAccess, _SetBasisVectorTestCase, ): pass class SetBasisLongVectorTestCase(_LongVectorTestCase, _DirectAccess, _SetBasisVectorTestCase, ): pass class SetBasisIntVectorTestCase(_IntVectorTestCase, _DirectAccess, _SetBasisVectorTestCase, ): pass class SetBasisShortVectorTestCase(_ShortVectorTestCase, _DirectAccess, _SetBasisVectorTestCase, ): pass class SetBasisFloatVectorUITestCase(_FloatVectorTestCase, _UIAccess, _SetBasisVectorTestCase, ): pass class SetBasisComplexVectorUITestCase(_ComplexVectorTestCase, _UIAccess, _SetBasisVectorTestCase, ): pass class SetBasisComplexFloatVectorUITestCase(_ComplexFloatVectorTestCase, _UIAccess, _SetBasisVectorTestCase, ): pass class SetBasisLongVectorUITestCase(_LongVectorTestCase, _UIAccess, _SetBasisVectorTestCase, ): pass class SetBasisIntVectorUITestCase(_IntVectorTestCase, _UIAccess, _SetBasisVectorTestCase, ): pass class SetBasisShortVectorUITestCase(_ShortVectorTestCase, _UIAccess, _SetBasisVectorTestCase, ): pass class _CharVectorSetup: def _mysetup(self): self.array = tmp(self.size, myord(137)) #def test_2_diagonale(self): # assert ord(self.array[self.basis][0]) == 1, "Diagonale not one !" #def test_3_diagonale(self): # for i in range(self.size): # if i == self.basis : # continue # assert ord(self.array[i][0]) == 0, \ # "Off Diagonale not zero!" class SetBasisCharVectorUITestCase(_CharVectorTestCase, _UIAccess, _CharVectorSetup, _SetBasisVectorTestCase, ): def test_2_diagonale(self): assert myord(self.array[self.basis]) == 1, "Basis not one !" def test_3_diagonale(self): for i in range(self.size): if i == self.basis : continue assert myord(self.array[i]) == 0, "Basis not zero!" class SetBasisCharVectorTestCase(_CharVectorTestCase, _DirectAccess, _CharVectorSetup, _SetBasisVectorTestCase, ): def test_2_diagonale(self): assert myord(self.array[self.basis]) == 1, "Basis not one !" def test_3_diagonale(self): for i in range(self.size): if i == self.basis : continue assert myord(self.array[i]) == 0, "Basis not zero!" class _SetZeroVectorTestCase(_DefaultVectorTestCase): function = 'set_zero' size = 10 def _mysetUp(self): tmp = self._get_function() self.array = tmp(self.size) def test_1_matrixsize(self): assert self.array.shape == (self.size,), "Not of size 10, 10" def test_2_all(self): for i in range(self.size): assert self.array[i] == 0, "Off Diagonale not zero!" def test_2_isnull(self): tmp = self._get_function('isnull') assert tmp(self.array) def _mytearDown(self): del self.array self.array = None class SetZeroVectorTestCase(_DoubleVectorTestCase, _DirectAccess, _SetZeroVectorTestCase, ): pass class SetZeroFloatVectorTestCase(_FloatVectorTestCase, _DirectAccess, _SetZeroVectorTestCase, ): pass class SetZeroComplexVectorTestCase(_ComplexVectorTestCase, _DirectAccess, _SetZeroVectorTestCase, ): pass class SetZeroComplexFloatVectorTestCase(_ComplexFloatVectorTestCase, _DirectAccess, _SetZeroVectorTestCase, ): pass class SetZeroLongVectorTestCase(_LongVectorTestCase, _DirectAccess, _SetZeroVectorTestCase, ): pass class SetZeroIntVectorTestCase(_IntVectorTestCase, _DirectAccess, _SetZeroVectorTestCase, ): pass class SetZeroShortVectorTestCase(_ShortVectorTestCase, _DirectAccess, _SetZeroVectorTestCase, ): pass class SetZeroVectorUITestCase(_DoubleVectorTestCase, _UIAccess, _SetZeroVectorTestCase, ): pass class SetZeroFloatVectorUITestCase(_FloatVectorTestCase, _UIAccess, _SetZeroVectorTestCase, ): pass class SetZeroComplexVectorUITestCase(_ComplexVectorTestCase, _UIAccess, _SetZeroVectorTestCase, ): pass class SetZeroComplexFloatVectorUITestCase(_ComplexFloatVectorTestCase, _UIAccess, _SetZeroVectorTestCase, ): pass class SetZeroLongVectorUITestCase(_LongVectorTestCase, _UIAccess, _SetZeroVectorTestCase, ): pass class SetZeroIntVectorUITestCase(_IntVectorTestCase, _UIAccess, _SetZeroVectorTestCase, ): pass class SetZeroShortVectorUITestCase(_ShortVectorTestCase, _UIAccess, _SetZeroVectorTestCase, ): pass class SetZeroCharVectorTestCase(_CharVectorTestCase, _DirectAccess, _SetZeroVectorTestCase, ): def test_2_all(self): for i in range(self.size): test = 0 cztmp = myorda(self.array[i]) try: assert cztmp == 0, "Of Diagonale not zero!" test = 1 finally: if test == 0: print "Of Diagonale not zero (but %s) for class %s !" (cztmp, self) class SetZeroCharVectorUITestCase(_CharVectorTestCase, _UIAccess, _SetZeroVectorTestCase, ): def test_2_all(self): for i in range(self.size): assert myorda(self.array[i]) == 0, "Of Diagonale not zero!" class _SetAllVectorTestCase(_DefaultVectorTestCase): function = 'set_all' size = 10 def _mysetUp(self): tmp = self._get_function() self.array = tmp(self.size, self._get_reference_value()) def test_1_matrixsize(self): array_check(self.array, None, (self.size,)) def test_2_all(self): for i in range(self.size): tmp = self.array[i] try: test = 0 assert tmp == self._get_reference_value(), "Value not 137!" test = 1 finally: if test == 0: print type(self.array), get_typecode(self.array) print "self.array[%d] was %s" %(i, tmp) def _mytearDown(self): del self.array self.array = None class SetAllFloatVectorTestCase(_FloatVectorTestCase, _DirectAccess, _SetAllVectorTestCase, ): pass class _ComplexVectorSetup: def _mysetUp(self): tmp = self._get_function() self.array = tmp(self.size, 137+0j) class SetAllComplexVectorTestCase(_ComplexVectorTestCase, _DirectAccess, _ComplexVectorSetup, _SetAllVectorTestCase, ): pass class SetAllComplexFloatVectorTestCase(_ComplexFloatVectorTestCase, _DirectAccess, _ComplexVectorSetup, _SetAllVectorTestCase, ): pass class SetAllLongVectorTestCase(_LongVectorTestCase, _DirectAccess, _SetAllVectorTestCase, ): pass class SetAllIntVectorTestCase(_IntVectorTestCase, _DirectAccess, _SetAllVectorTestCase, ): pass class SetAllShortVectorTestCase(_ShortVectorTestCase, _DirectAccess, _SetAllVectorTestCase, ): pass class SetAllFloatVectorUITestCase(_FloatVectorTestCase, _UIAccess, _SetAllVectorTestCase, ): pass class SetAllComplexVectorUITestCase(_ComplexVectorTestCase, _UIAccess, _ComplexVectorSetup, _SetAllVectorTestCase, ): pass class SetAllComplexFloatVectorUITestCase(_ComplexFloatVectorTestCase, _UIAccess, _ComplexVectorSetup, _SetAllVectorTestCase, ): pass class SetAllLongVectorUITestCase(_LongVectorTestCase, _UIAccess, _SetAllVectorTestCase, ): pass class SetAllIntVectorUITestCase(_IntVectorTestCase, _UIAccess, _SetAllVectorTestCase, ): pass class SetAllShortVectorUITestCase(_ShortVectorTestCase, _UIAccess, _SetAllVectorTestCase, ): pass class SetAllCharVectorTestCase(_CharVectorTestCase, _DirectAccess, _CharVectorSetup, _SetAllVectorTestCase, ): pass class SetAllCharVectorUITestCase(_CharVectorTestCase, _UIAccess, _CharVectorSetup, _SetAllVectorTestCase, ): pass class _MinMaxVectorTestCase(_DefaultVectorTestCase): size = 10 def _mysetUp(self): tmp = self._get_function('set_zero') array = tmp((self.size)) type = get_typecode(array) array = nummodule.zeros((self.size,)).astype(type) array[5] = -1 array[8] = 1 self.array = array def test_max(self): function = self._get_function('max') assert(function(self.array)== 1) def test_min(self): function = self._get_function('min') assert(function(self.array)== -1) def test_minmax(self): function = self._get_function('minmax') tmp = function(self.array) assert(tmp[0] == -1) assert(tmp[1] == 1) def test_maxindex(self): function = self._get_function('max_index') tmp = function(self.array) assert(tmp == 8) def test_minindex(self): function = self._get_function('min_index') tmp = function(self.array) assert(tmp == 5) def test_minmaxindex(self): function = self._get_function('minmax_index') tmp = function(self.array) assert(tmp[0] == 5) assert(tmp[1] == 8) def _mytearDown(self): pass class MinMaxVectorTestCase(_DoubleVectorTestCase, _DirectAccess, _MinMaxVectorTestCase, ): pass class MinMaxFloatVectorTestCase(_FloatVectorTestCase, _DirectAccess, _MinMaxVectorTestCase, ): pass class MinMaxLongVectorTestCase(_LongVectorTestCase, _DirectAccess, _MinMaxVectorTestCase, ): pass class MinMaxIntVectorTestCase(_IntVectorTestCase, _DirectAccess, _MinMaxVectorTestCase, ): pass class MinMaxShortVectorTestCase(_ShortVectorTestCase, _DirectAccess, _MinMaxVectorTestCase, ): pass class MinMaxVectorUITestCase(_DoubleVectorTestCase, _UIAccess, _MinMaxVectorTestCase, ): pass class MinMaxFloatVectorUITestCase(_FloatVectorTestCase, _UIAccess, _MinMaxVectorTestCase, ): pass class MinMaxLongVectorUITestCase(_LongVectorTestCase, _UIAccess, _MinMaxVectorTestCase, ): pass class MinMaxIntVectorUITestCase(_IntVectorTestCase, _UIAccess, _MinMaxVectorTestCase, ): pass class MinMaxShortVectorUITestCase(_ShortVectorTestCase, _UIAccess, _MinMaxVectorTestCase, ): pass class _SwapVectorTestCase(_DefaultVectorTestCase): size = 10 def _mysetUp(self): tmp = self._get_function('set_zero') array = tmp(self.size) type = get_typecode(array) array = nummodule.arange(self.size) self.array = array.astype(type) self.array1 = (array*10).astype(type) def testswap(self): function = self._get_function('swap') type = get_typecode(self.array) tmp = function(self.array, self.array1) function = self._get_function('isnull') assert(function((tmp[1]/10).astype(type) - tmp[2])) def testswap_elements(self): function = self._get_function('swap_elements') tmp = function(self.array, 3, 5) assert(tmp[0] == 0) for i in range(self.size): if i == 3: assert(tmp[1][3] == 5) elif i == 5: assert(tmp[1][5] == 3) else: assert(tmp[1][i]==i) def test_reverse(self): function = self._get_function('reverse') tmp = function(self.array) assert(tmp[0] == 0) for i in range(self.size): assert(tmp[1][-(i+1)]==i) # def test_fwrite(self): # file = getopentmpfile('w') # function = self._get_function('fwrite') # #print "Testing fwrite!" # tmp = function(file, self.array) # # def test_fread(self): # file = getopentmpfile('w+') # function = self._get_function('fwrite') # tmp = function(file, (self.array * 2).astype(self.get_typecode(array))) # assert(tmp == 0) # file.seek(0) # function = self._get_function('fread') # tmp = function(file, self.array.shape[0]) # assert(tmp[0] == 0) # for i in range(self.size): # assert(tmp[1][i] == self.array[i] * 2) # # def test_fprintf(self): # file = getopentmpfile('w') # function = self._get_function('fprintf') # tmp = function(file, self.array, self._get_format()) # assert(tmp == 0) # # def test_fscanf(self): # file = getopentmpfile('w+') # function = self._get_function('fprintf') # ttype = self.get_typecode(array) # tmp = function(file, (self.array*2).astype(ttype), self._get_format()) # # function = self._get_function('fscanf') # file.seek(0) # # tmp = function(file, self.array.shape[0]) # assert(tmp[0] == 0) # for i in range(self.size): # assert(tmp[1][i] == self.array[i] * 2) def _mytearDown(self): pass class SwapVectorTestCase(_DoubleVectorTestCase, _DirectAccess, _SwapVectorTestCase, ): pass class SwapFloatVectorTestCase(_FloatVectorTestCase, _DirectAccess, _SwapVectorTestCase, ): pass class SwapComplexVectorTestCase(_ComplexVectorTestCase, _DirectAccess, _SwapVectorTestCase, ): pass class SwapComplexFloatVectorTestCase(_ComplexFloatVectorTestCase, _DirectAccess, _SwapVectorTestCase, ): pass class SwapLongVectorTestCase(_LongVectorTestCase, _DirectAccess, _SwapVectorTestCase, ): pass class SwapIntVectorTestCase(_IntVectorTestCase, _DirectAccess, _SwapVectorTestCase, ): pass class SwapShortVectorTestCase(_ShortVectorTestCase, _DirectAccess, _SwapVectorTestCase, ): pass class SwapVectorUITestCase(_DoubleVectorTestCase, _UIAccess, _SwapVectorTestCase, ): pass class SwapFloatVectorUITestCase(_FloatVectorTestCase, _UIAccess, _SwapVectorTestCase, ): pass class SwapComplexVectorUITestCase(_ComplexVectorTestCase, _UIAccess, _SwapVectorTestCase, ): pass class SwapComplexFloatVectorUITestCase(_ComplexFloatVectorTestCase, _UIAccess, _SwapVectorTestCase, ): pass class SwapLongVectorUITestCase(_LongVectorTestCase, _UIAccess, _SwapVectorTestCase, ): pass class SwapIntVectorUITestCase(_IntVectorTestCase, _UIAccess, _SwapVectorTestCase, ): pass class SwapShortVectorUITestCase(_ShortVectorTestCase, _UIAccess, _SwapVectorTestCase, ): pass #del DiagonalComplexFloatMatrixTestCase #del DiagonalComplexFloatMatrixUITestCase # del SwapComplexFloatMatrixTestCase # del SwapComplexFloatMatrixUITestCase # del SwapComplexFloatVectorTestCase # del SwapComplexFloatVectorUITestCase # del SwapComplexMatrixTestCase # del SwapComplexMatrixUITestCase # del SwapComplexVectorTestCase # del SwapComplexVectorUITestCase # del SwapFloatMatrixTestCase # del SwapFloatMatrixUITestCase # del SwapFloatVectorTestCase # del SwapFloatVectorUITestCase # del SwapIntMatrixTestCase # del SwapIntMatrixUITestCase # del SwapIntVectorTestCase # del SwapIntVectorUITestCase # del SwapLongMatrixTestCase # del SwapLongMatrixUITestCase # del SwapLongVectorTestCase # del SwapLongVectorUITestCase # del SwapMatrixTestCase # del SwapMatrixUITestCase # del SwapVectorTestCase # del SwapVectorUITestCase # del SwapShortMatrixTestCase # del SwapShortMatrixUITestCase # del SwapShortVectorTestCase # del SwapShortVectorUITestCase # del SetZeroComplexFloatVectorUITestCase # del SetZeroComplexFloatVectorTestCase # del SetZeroComplexVectorUITestCase # del SetZeroComplexVectorTestCase # del SetZeroComplexFloatMatrixUITestCase # del SetZeroComplexFloatMatrixTestCase # del SetZeroComplexMatrixUITestCase # del SetZeroComplexMatrixTestCase # del SetZeroIntMatrixTestCase # del SetZeroIntMatrixUITestCase # del SetZeroIntVectorTestCase # del SetZeroIntVectorUITestCase # del SetZeroLongMatrixTestCase # del SetZeroLongMatrixUITestCase # del SetZeroLongVectorTestCase # del SetZeroLongVectorUITestCase # del SetZeroMatrixTestCase # del SetZeroMatrixUITestCase # ---------------------------------------------------------------------------- # ---------------------------------------------------------------------------- # Remove .. # ---------------------------------------------------------------------------- # ---------------------------------------------------------------------------- # These just provide a few values..... del _DefaultTestCase del _DefaultVectorTestCase del _DefaultMatrixTestCase del _DoubleMatrixTestCase del _FloatMatrixTestCase del _ComplexMatrixTestCase del _ComplexFloatMatrixTestCase del _LongMatrixTestCase del _ShortMatrixTestCase del _IntMatrixTestCase del _CharMatrixTestCase del _DoubleVectorTestCase del _FloatVectorTestCase del _ComplexVectorTestCase del _ComplexFloatVectorTestCase del _LongVectorTestCase del _ShortVectorTestCase del _IntVectorTestCase del _CharVectorTestCase del _DirectAccess del _UIAccess del _SetIdentityMatrixTestCase del _MinMaxMatrixTestCase del _DiagonalMatrixTestCase del _SetZeroMatrixTestCase del _SetAllMatrixTestCase del _SwapMatrixTestCase del _SetBasisVectorTestCase del _MinMaxVectorTestCase del _SetZeroVectorTestCase del _SetAllVectorTestCase del _SwapVectorTestCase if __name__ == '__main__': unittest.main()
mit
rawodb/bitcoin
test/functional/interface_bitcoin_cli.py
1
4196
#!/usr/bin/env python3 # Copyright (c) 2017 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test bitcoin-cli""" from test_framework.test_framework import BitcoinTestFramework from test_framework.util import assert_equal, assert_raises_process_error, get_auth_cookie class TestBitcoinCli(BitcoinTestFramework): def set_test_params(self): self.setup_clean_chain = True self.num_nodes = 1 def run_test(self): """Main test logic""" cli_response = self.nodes[0].cli("-version").send_cli() assert("Bitcoin Core RPC client version" in cli_response) self.log.info("Compare responses from gewalletinfo RPC and `bitcoin-cli getwalletinfo`") cli_response = self.nodes[0].cli.getwalletinfo() rpc_response = self.nodes[0].getwalletinfo() assert_equal(cli_response, rpc_response) self.log.info("Compare responses from getblockchaininfo RPC and `bitcoin-cli getblockchaininfo`") cli_response = self.nodes[0].cli.getblockchaininfo() rpc_response = self.nodes[0].getblockchaininfo() assert_equal(cli_response, rpc_response) user, password = get_auth_cookie(self.nodes[0].datadir) self.log.info("Test -stdinrpcpass option") assert_equal(0, self.nodes[0].cli('-rpcuser=%s' % user, '-stdinrpcpass', input=password).getblockcount()) assert_raises_process_error(1, "Incorrect rpcuser or rpcpassword", self.nodes[0].cli('-rpcuser=%s' % user, '-stdinrpcpass', input="foo").echo) self.log.info("Test -stdin and -stdinrpcpass") assert_equal(["foo", "bar"], self.nodes[0].cli('-rpcuser=%s' % user, '-stdin', '-stdinrpcpass', input=password + "\nfoo\nbar").echo()) assert_raises_process_error(1, "Incorrect rpcuser or rpcpassword", self.nodes[0].cli('-rpcuser=%s' % user, '-stdin', '-stdinrpcpass', input="foo").echo) self.log.info("Test connecting to a non-existing server") assert_raises_process_error(1, "Could not connect to the server", self.nodes[0].cli('-rpcport=1').echo) self.log.info("Test connecting with non-existing RPC cookie file") assert_raises_process_error(1, "Could not locate RPC credentials", self.nodes[0].cli('-rpccookiefile=does-not-exist', '-rpcpassword=').echo) self.log.info("Make sure that -getinfo with arguments fails") assert_raises_process_error(1, "-getinfo takes no arguments", self.nodes[0].cli('-getinfo').help) self.log.info("Compare responses from `bitcoin-cli -getinfo` and the RPCs data is retrieved from.") cli_get_info = self.nodes[0].cli('-getinfo').send_cli() wallet_info = self.nodes[0].getwalletinfo() network_info = self.nodes[0].getnetworkinfo() blockchain_info = self.nodes[0].getblockchaininfo() assert_equal(cli_get_info['version'], network_info['version']) assert_equal(cli_get_info['protocolversion'], network_info['protocolversion']) assert_equal(cli_get_info['walletversion'], wallet_info['walletversion']) assert_equal(cli_get_info['balance'], wallet_info['balance']) assert_equal(cli_get_info['blocks'], blockchain_info['blocks']) assert_equal(cli_get_info['timeoffset'], network_info['timeoffset']) assert_equal(cli_get_info['connections'], network_info['connections']) assert_equal(cli_get_info['proxy'], network_info['networks'][0]['proxy']) assert_equal(cli_get_info['difficulty'], blockchain_info['difficulty']) assert_equal(cli_get_info['testnet'], blockchain_info['chain'] == "test") assert_equal(cli_get_info['balance'], wallet_info['balance']) assert_equal(cli_get_info['keypoololdest'], wallet_info['keypoololdest']) assert_equal(cli_get_info['keypoolsize'], wallet_info['keypoolsize']) assert_equal(cli_get_info['paytxfee'], wallet_info['paytxfee']) assert_equal(cli_get_info['relayfee'], network_info['relayfee']) # unlocked_until is not tested because the wallet is not encrypted if __name__ == '__main__': TestBitcoinCli().main()
mit
wong2/sentry
src/sentry/migrations/0126_auto__add_field_option_last_updated.py
36
25153
# -*- coding: utf-8 -*- import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding field 'Option.last_updated' db.add_column('sentry_option', 'last_updated', self.gf('django.db.models.fields.DateTimeField')(default=datetime.datetime.now), keep_default=False) def backwards(self, orm): # Deleting field 'Option.last_updated' db.delete_column('sentry_option', 'last_updated') models = { 'sentry.accessgroup': { 'Meta': {'unique_together': "(('team', 'name'),)", 'object_name': 'AccessGroup'}, 'data': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'date_added': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}), 'managed': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'members': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['sentry.User']", 'symmetrical': 'False'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '64'}), 'projects': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['sentry.Project']", 'symmetrical': 'False'}), 'team': ('sentry.db.models.fields.FlexibleForeignKey', [], {'to': "orm['sentry.Team']"}), 'type': ('django.db.models.fields.IntegerField', [], {'default': '50'}) }, 'sentry.activity': { 'Meta': {'object_name': 'Activity'}, 'data': ('django.db.models.fields.TextField', [], {'null': 'True'}), 'datetime': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'event': ('sentry.db.models.fields.FlexibleForeignKey', [], {'to': "orm['sentry.Event']", 'null': 'True'}), 'group': ('sentry.db.models.fields.FlexibleForeignKey', [], {'to': "orm['sentry.Group']", 'null': 'True'}), 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}), 'ident': ('django.db.models.fields.CharField', [], {'max_length': '64', 'null': 'True'}), 'project': ('sentry.db.models.fields.FlexibleForeignKey', [], {'to': "orm['sentry.Project']"}), 'type': ('django.db.models.fields.PositiveIntegerField', [], {}), 'user': ('sentry.db.models.fields.FlexibleForeignKey', [], {'to': "orm['sentry.User']", 'null': 'True'}) }, 'sentry.alert': { 'Meta': {'object_name': 'Alert'}, 'data': ('django.db.models.fields.TextField', [], {'null': 'True'}), 'datetime': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'group': ('sentry.db.models.fields.FlexibleForeignKey', [], {'to': "orm['sentry.Group']", 'null': 'True'}), 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}), 'message': ('django.db.models.fields.TextField', [], {}), 'project': ('sentry.db.models.fields.FlexibleForeignKey', [], {'to': "orm['sentry.Project']"}), 'related_groups': ('django.db.models.fields.related.ManyToManyField', [], {'related_name': "'related_alerts'", 'symmetrical': 'False', 'through': "orm['sentry.AlertRelatedGroup']", 'to': "orm['sentry.Group']"}), 'status': ('django.db.models.fields.PositiveIntegerField', [], {'default': '0', 'db_index': 'True'}) }, 'sentry.alertrelatedgroup': { 'Meta': {'unique_together': "(('group', 'alert'),)", 'object_name': 'AlertRelatedGroup'}, 'alert': ('sentry.db.models.fields.FlexibleForeignKey', [], {'to': "orm['sentry.Alert']"}), 'data': ('django.db.models.fields.TextField', [], {'null': 'True'}), 'group': ('sentry.db.models.fields.FlexibleForeignKey', [], {'to': "orm['sentry.Group']"}), 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}) }, 'sentry.event': { 'Meta': {'unique_together': "(('project', 'event_id'),)", 'object_name': 'Event', 'db_table': "'sentry_message'", 'index_together': "(('group', 'datetime'),)"}, 'checksum': ('django.db.models.fields.CharField', [], {'max_length': '32', 'db_index': 'True'}), 'data': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'datetime': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'db_index': 'True'}), 'event_id': ('django.db.models.fields.CharField', [], {'max_length': '32', 'null': 'True', 'db_column': "'message_id'"}), 'group': ('sentry.db.models.fields.FlexibleForeignKey', [], {'blank': 'True', 'related_name': "'event_set'", 'null': 'True', 'to': "orm['sentry.Group']"}), 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}), 'message': ('django.db.models.fields.TextField', [], {}), 'num_comments': ('django.db.models.fields.PositiveIntegerField', [], {'default': '0', 'null': 'True'}), 'platform': ('django.db.models.fields.CharField', [], {'max_length': '64', 'null': 'True'}), 'project': ('sentry.db.models.fields.FlexibleForeignKey', [], {'to': "orm['sentry.Project']", 'null': 'True'}), 'time_spent': ('django.db.models.fields.IntegerField', [], {'null': 'True'}) }, 'sentry.eventmapping': { 'Meta': {'unique_together': "(('project', 'event_id'),)", 'object_name': 'EventMapping'}, 'date_added': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'event_id': ('django.db.models.fields.CharField', [], {'max_length': '32'}), 'group': ('sentry.db.models.fields.FlexibleForeignKey', [], {'to': "orm['sentry.Group']"}), 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}), 'project': ('sentry.db.models.fields.FlexibleForeignKey', [], {'to': "orm['sentry.Project']"}) }, 'sentry.group': { 'Meta': {'unique_together': "(('project', 'checksum'),)", 'object_name': 'Group', 'db_table': "'sentry_groupedmessage'"}, 'active_at': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'db_index': 'True'}), 'checksum': ('django.db.models.fields.CharField', [], {'max_length': '32', 'db_index': 'True'}), 'culprit': ('django.db.models.fields.CharField', [], {'max_length': '200', 'null': 'True', 'db_column': "'view'", 'blank': 'True'}), 'data': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'first_seen': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'db_index': 'True'}), 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}), 'is_public': ('django.db.models.fields.NullBooleanField', [], {'default': 'False', 'null': 'True', 'blank': 'True'}), 'last_seen': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'db_index': 'True'}), 'level': ('django.db.models.fields.PositiveIntegerField', [], {'default': '40', 'db_index': 'True', 'blank': 'True'}), 'logger': ('django.db.models.fields.CharField', [], {'default': "'root'", 'max_length': '64', 'db_index': 'True', 'blank': 'True'}), 'message': ('django.db.models.fields.TextField', [], {}), 'num_comments': ('django.db.models.fields.PositiveIntegerField', [], {'default': '0', 'null': 'True'}), 'platform': ('django.db.models.fields.CharField', [], {'max_length': '64', 'null': 'True'}), 'project': ('sentry.db.models.fields.FlexibleForeignKey', [], {'to': "orm['sentry.Project']", 'null': 'True'}), 'resolved_at': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'db_index': 'True'}), 'score': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'status': ('django.db.models.fields.PositiveIntegerField', [], {'default': '0', 'db_index': 'True'}), 'time_spent_count': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'time_spent_total': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'times_seen': ('django.db.models.fields.PositiveIntegerField', [], {'default': '1', 'db_index': 'True'}) }, 'sentry.groupassignee': { 'Meta': {'object_name': 'GroupAssignee', 'db_table': "'sentry_groupasignee'"}, 'date_added': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'group': ('sentry.db.models.fields.FlexibleForeignKey', [], {'related_name': "'assignee_set'", 'unique': 'True', 'to': "orm['sentry.Group']"}), 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}), 'project': ('sentry.db.models.fields.FlexibleForeignKey', [], {'related_name': "'assignee_set'", 'to': "orm['sentry.Project']"}), 'user': ('sentry.db.models.fields.FlexibleForeignKey', [], {'related_name': "'sentry_assignee_set'", 'to': "orm['sentry.User']"}) }, 'sentry.groupbookmark': { 'Meta': {'unique_together': "(('project', 'user', 'group'),)", 'object_name': 'GroupBookmark'}, 'group': ('sentry.db.models.fields.FlexibleForeignKey', [], {'related_name': "'bookmark_set'", 'to': "orm['sentry.Group']"}), 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}), 'project': ('sentry.db.models.fields.FlexibleForeignKey', [], {'related_name': "'bookmark_set'", 'to': "orm['sentry.Project']"}), 'user': ('sentry.db.models.fields.FlexibleForeignKey', [], {'related_name': "'sentry_bookmark_set'", 'to': "orm['sentry.User']"}) }, 'sentry.grouphash': { 'Meta': {'unique_together': "(('project', 'hash'),)", 'object_name': 'GroupHash'}, 'group': ('sentry.db.models.fields.FlexibleForeignKey', [], {'to': "orm['sentry.Group']", 'null': 'True'}), 'hash': ('django.db.models.fields.CharField', [], {'max_length': '32', 'db_index': 'True'}), 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}), 'project': ('sentry.db.models.fields.FlexibleForeignKey', [], {'to': "orm['sentry.Project']", 'null': 'True'}) }, 'sentry.groupmeta': { 'Meta': {'unique_together': "(('group', 'key'),)", 'object_name': 'GroupMeta'}, 'group': ('sentry.db.models.fields.FlexibleForeignKey', [], {'to': "orm['sentry.Group']"}), 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}), 'key': ('django.db.models.fields.CharField', [], {'max_length': '64'}), 'value': ('django.db.models.fields.TextField', [], {}) }, 'sentry.grouprulestatus': { 'Meta': {'unique_together': "(('rule', 'group'),)", 'object_name': 'GroupRuleStatus'}, 'date_added': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'group': ('sentry.db.models.fields.FlexibleForeignKey', [], {'to': "orm['sentry.Group']"}), 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}), 'project': ('sentry.db.models.fields.FlexibleForeignKey', [], {'to': "orm['sentry.Project']"}), 'rule': ('sentry.db.models.fields.FlexibleForeignKey', [], {'to': "orm['sentry.Rule']"}), 'status': ('django.db.models.fields.PositiveSmallIntegerField', [], {'default': '0'}) }, 'sentry.groupseen': { 'Meta': {'unique_together': "(('user', 'group'),)", 'object_name': 'GroupSeen'}, 'group': ('sentry.db.models.fields.FlexibleForeignKey', [], {'to': "orm['sentry.Group']"}), 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}), 'last_seen': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'project': ('sentry.db.models.fields.FlexibleForeignKey', [], {'to': "orm['sentry.Project']"}), 'user': ('sentry.db.models.fields.FlexibleForeignKey', [], {'to': "orm['sentry.User']", 'db_index': 'False'}) }, 'sentry.grouptagkey': { 'Meta': {'unique_together': "(('project', 'group', 'key'),)", 'object_name': 'GroupTagKey'}, 'group': ('sentry.db.models.fields.FlexibleForeignKey', [], {'to': "orm['sentry.Group']"}), 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}), 'key': ('django.db.models.fields.CharField', [], {'max_length': '32'}), 'project': ('sentry.db.models.fields.FlexibleForeignKey', [], {'to': "orm['sentry.Project']", 'null': 'True'}), 'values_seen': ('django.db.models.fields.PositiveIntegerField', [], {'default': '0'}) }, 'sentry.grouptagvalue': { 'Meta': {'unique_together': "(('project', 'key', 'value', 'group'),)", 'object_name': 'GroupTagValue', 'db_table': "'sentry_messagefiltervalue'"}, 'first_seen': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'null': 'True', 'db_index': 'True'}), 'group': ('sentry.db.models.fields.FlexibleForeignKey', [], {'related_name': "'grouptag'", 'to': "orm['sentry.Group']"}), 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}), 'key': ('django.db.models.fields.CharField', [], {'max_length': '32'}), 'last_seen': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'null': 'True', 'db_index': 'True'}), 'project': ('sentry.db.models.fields.FlexibleForeignKey', [], {'related_name': "'grouptag'", 'null': 'True', 'to': "orm['sentry.Project']"}), 'times_seen': ('django.db.models.fields.PositiveIntegerField', [], {'default': '0'}), 'value': ('django.db.models.fields.CharField', [], {'max_length': '200'}) }, 'sentry.lostpasswordhash': { 'Meta': {'object_name': 'LostPasswordHash'}, 'date_added': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'hash': ('django.db.models.fields.CharField', [], {'max_length': '32'}), 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}), 'user': ('sentry.db.models.fields.FlexibleForeignKey', [], {'to': "orm['sentry.User']", 'unique': 'True'}) }, 'sentry.option': { 'Meta': {'object_name': 'Option'}, 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}), 'key': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '64'}), 'last_updated': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'value': ('sentry.db.models.fields.pickle.UnicodePickledObjectField', [], {}) }, 'sentry.pendingteammember': { 'Meta': {'unique_together': "(('team', 'email'),)", 'object_name': 'PendingTeamMember'}, 'date_added': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'email': ('django.db.models.fields.EmailField', [], {'max_length': '75'}), 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}), 'team': ('sentry.db.models.fields.FlexibleForeignKey', [], {'related_name': "'pending_member_set'", 'to': "orm['sentry.Team']"}), 'type': ('django.db.models.fields.IntegerField', [], {'default': '50'}) }, 'sentry.project': { 'Meta': {'unique_together': "(('team', 'slug'),)", 'object_name': 'Project'}, 'date_added': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '200'}), 'owner': ('sentry.db.models.fields.FlexibleForeignKey', [], {'related_name': "'sentry_owned_project_set'", 'null': 'True', 'to': "orm['sentry.User']"}), 'platform': ('django.db.models.fields.CharField', [], {'max_length': '32', 'null': 'True'}), 'public': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'slug': ('django.db.models.fields.SlugField', [], {'max_length': '50', 'null': 'True'}), 'status': ('django.db.models.fields.PositiveIntegerField', [], {'default': '0', 'db_index': 'True'}), 'team': ('sentry.db.models.fields.FlexibleForeignKey', [], {'to': "orm['sentry.Team']", 'null': 'True'}) }, 'sentry.projectkey': { 'Meta': {'object_name': 'ProjectKey'}, 'date_added': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'null': 'True'}), 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}), 'label': ('django.db.models.fields.CharField', [], {'max_length': '64', 'null': 'True', 'blank': 'True'}), 'project': ('sentry.db.models.fields.FlexibleForeignKey', [], {'related_name': "'key_set'", 'to': "orm['sentry.Project']"}), 'public_key': ('django.db.models.fields.CharField', [], {'max_length': '32', 'unique': 'True', 'null': 'True'}), 'roles': ('django.db.models.fields.BigIntegerField', [], {'default': '1'}), 'secret_key': ('django.db.models.fields.CharField', [], {'max_length': '32', 'unique': 'True', 'null': 'True'}), 'user': ('sentry.db.models.fields.FlexibleForeignKey', [], {'to': "orm['sentry.User']", 'null': 'True'}), 'user_added': ('sentry.db.models.fields.FlexibleForeignKey', [], {'related_name': "'keys_added_set'", 'null': 'True', 'to': "orm['sentry.User']"}) }, 'sentry.projectoption': { 'Meta': {'unique_together': "(('project', 'key'),)", 'object_name': 'ProjectOption', 'db_table': "'sentry_projectoptions'"}, 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}), 'key': ('django.db.models.fields.CharField', [], {'max_length': '64'}), 'project': ('sentry.db.models.fields.FlexibleForeignKey', [], {'to': "orm['sentry.Project']"}), 'value': ('sentry.db.models.fields.pickle.UnicodePickledObjectField', [], {}) }, 'sentry.rule': { 'Meta': {'object_name': 'Rule'}, 'data': ('sentry.db.models.fields.gzippeddict.GzippedDictField', [], {}), 'date_added': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}), 'label': ('django.db.models.fields.CharField', [], {'max_length': '64'}), 'project': ('sentry.db.models.fields.FlexibleForeignKey', [], {'to': "orm['sentry.Project']"}) }, 'sentry.tagkey': { 'Meta': {'unique_together': "(('project', 'key'),)", 'object_name': 'TagKey', 'db_table': "'sentry_filterkey'"}, 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}), 'key': ('django.db.models.fields.CharField', [], {'max_length': '32'}), 'label': ('django.db.models.fields.CharField', [], {'max_length': '64', 'null': 'True'}), 'project': ('sentry.db.models.fields.FlexibleForeignKey', [], {'to': "orm['sentry.Project']"}), 'values_seen': ('django.db.models.fields.PositiveIntegerField', [], {'default': '0'}) }, 'sentry.tagvalue': { 'Meta': {'unique_together': "(('project', 'key', 'value'),)", 'object_name': 'TagValue', 'db_table': "'sentry_filtervalue'"}, 'data': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'first_seen': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'null': 'True', 'db_index': 'True'}), 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}), 'key': ('django.db.models.fields.CharField', [], {'max_length': '32'}), 'last_seen': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'null': 'True', 'db_index': 'True'}), 'project': ('sentry.db.models.fields.FlexibleForeignKey', [], {'to': "orm['sentry.Project']", 'null': 'True'}), 'times_seen': ('django.db.models.fields.PositiveIntegerField', [], {'default': '0'}), 'value': ('django.db.models.fields.CharField', [], {'max_length': '200'}) }, 'sentry.team': { 'Meta': {'object_name': 'Team'}, 'date_added': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'null': 'True'}), 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}), 'members': ('django.db.models.fields.related.ManyToManyField', [], {'related_name': "'team_memberships'", 'symmetrical': 'False', 'through': "orm['sentry.TeamMember']", 'to': "orm['sentry.User']"}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '64'}), 'owner': ('sentry.db.models.fields.FlexibleForeignKey', [], {'to': "orm['sentry.User']"}), 'slug': ('django.db.models.fields.SlugField', [], {'unique': 'True', 'max_length': '50'}), 'status': ('django.db.models.fields.PositiveIntegerField', [], {'default': '0'}) }, 'sentry.teammember': { 'Meta': {'unique_together': "(('team', 'user'),)", 'object_name': 'TeamMember'}, 'date_added': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}), 'team': ('sentry.db.models.fields.FlexibleForeignKey', [], {'related_name': "'member_set'", 'to': "orm['sentry.Team']"}), 'type': ('django.db.models.fields.IntegerField', [], {'default': '50'}), 'user': ('sentry.db.models.fields.FlexibleForeignKey', [], {'related_name': "'sentry_teammember_set'", 'to': "orm['sentry.User']"}) }, 'sentry.user': { 'Meta': {'object_name': 'User', 'db_table': "'auth_user'"}, 'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}), 'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}), 'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'is_managed': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}), 'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '128'}) }, 'sentry.useroption': { 'Meta': {'unique_together': "(('user', 'project', 'key'),)", 'object_name': 'UserOption'}, 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}), 'key': ('django.db.models.fields.CharField', [], {'max_length': '64'}), 'project': ('sentry.db.models.fields.FlexibleForeignKey', [], {'to': "orm['sentry.Project']", 'null': 'True'}), 'user': ('sentry.db.models.fields.FlexibleForeignKey', [], {'to': "orm['sentry.User']"}), 'value': ('sentry.db.models.fields.pickle.UnicodePickledObjectField', [], {}) } } complete_apps = ['sentry']
bsd-3-clause
fanghuaqi/mbed
tools/host_tests/tcpecho_server_loop.py
73
1349
""" mbed SDK Copyright (c) 2011-2013 ARM Limited Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ # Be sure that the tools directory is in the search path import sys from os.path import join, abspath, dirname ROOT = abspath(join(dirname(__file__), "..", "..")) sys.path.insert(0, ROOT) from mbed_settings import LOCALHOST from SocketServer import BaseRequestHandler, TCPServer class TCP_EchoHandler(BaseRequestHandler): def handle(self): print "\nHandle connection from:", self.client_address while True: data = self.request.recv(1024) if not data: break self.request.sendall(data) self.request.close() print "socket closed" if __name__ == '__main__': server = TCPServer((LOCALHOST, 7), TCP_EchoHandler) print "listening for connections on:", (LOCALHOST, 7) server.serve_forever()
apache-2.0
blokweb/androguard
tests/test_analysis_offset.py
38
4153
#!/usr/bin/env python import sys, re PATH_INSTALL = "./" sys.path.append(PATH_INSTALL) from androguard.core.androgen import AndroguardS from androguard.core.analysis import analysis from androguard.core.bytecodes.jvm import BRANCH2_JVM_OPCODES, determineNext TEST_CASE = 'examples/java/TC/orig/TCE.class' VALUES = { "TCE <init> ()V" : [ ("if_icmpge", [116]), ("if_icmpge", [19]), ("goto", [-18]), ("lookupswitch", [22, 19]), ("lookupswitch", [47, 40, 34, 37]), ("goto", [-123]), ("return", [-1]), ], } ############################################### MODIF = { "TCE <init> ()V" : [ ("remove_at", 28), ] } ############################################### ############################################### MODIF2 = { "TCE <init> ()V" : [ ("insert_at", 28, [ "aload_0"]), ] } ############################################### ############################################### MODIF3 = { "TCE <init> ()V" : [ ("remove_at", 88), ] } VALUES3 = { "TCE <init> ()V" : [ ("if_icmpge", [113]), ("if_icmpge", [16]), ("goto", [-15]), ("lookupswitch", [22, 19]), ("lookupswitch", [47, 40, 34, 37]), ("goto", [-120]), ("return", [-1]), ], } ############################################### ############################################### MODIF4 = { "TCE <init> ()V" : [ ("insert_at", 88, [ "sipush", 400 ]), ] } ############################################### ############################################### MODIF4 = { "TCE <init> ()V" : [ ("insert_at", 88, [ "sipush", 400 ]), ] } ############################################### def test(got, expected): if got == expected: prefix = ' OK ' else: prefix = ' X ' print '\t%s got: %s expected: %s' % (prefix, repr(got), repr(expected)) def getVal(i) : op = i.get_operands() if isinstance(op, int) : return [ op ] elif i.get_name() == "lookupswitch" : x = [] x.append( i.get_operands().default ) for idx in range(0, i.get_operands().npairs) : off = getattr(i.get_operands(), "offset%d" % idx) x.append( off ) return x return [-1] def check(a, values, branch) : b = [] for i in branch : b.append( re.compile( i ) ) for method in a.get_methods() : key = method.get_class_name() + " " + method.get_name() + " " + method.get_descriptor() if key not in values : continue print "CHECKING ...", method.get_class_name(), method.get_name(), method.get_descriptor() code = method.get_code() bc = code.get_bc() idx = 0 v = 0 for i in bc.get() : # print "\t", "%x(%d)" % (idx, idx), i.get_name(), i.get_operands() for j in b : if j.match(i.get_name()) != None : elem = values[key][v] test("%s %s" % (elem[0], elem[1]), "%s %s" % (i.get_name(), getVal(i))) v += 1 break idx += i.get_length() def modify(a, modif) : for method in a.get_methods() : key = method.get_class_name() + " " + method.get_name() + " " + method.get_descriptor() if key not in modif : continue print "MODIFYING ...", method.get_class_name(), method.get_name(), method.get_descriptor() code = method.get_code() for i in modif[key] : getattr( code, i[0] )( *i[1:] ) a = AndroguardS( TEST_CASE ) ### INIT CHECK ### check( a, VALUES, BRANCH2_JVM_OPCODES ) ### APPLY MODIFICATION ### modify( a, MODIF ) ### CHECK IF MODIFICATION IS OK ### check( a, VALUES, BRANCH2_JVM_OPCODES ) modify( a, MODIF2 ) check( a, VALUES, BRANCH2_JVM_OPCODES ) modify( a, MODIF3 ) check( a, VALUES3, BRANCH2_JVM_OPCODES ) modify( a, MODIF4 ) check( a, VALUES, BRANCH2_JVM_OPCODES )
apache-2.0
CitoEngine/cito_engine
app/tests/test_comments_view.py
1
2629
"""Copyright 2014 Cyrus Dasadia 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 django.test import TestCase, Client from django.contrib.auth.models import User from appauth.models import Perms from . import factories class TestCommentsView(TestCase): def setUp(self): self.client = Client() self.user = User.objects.create_user(username='hodor', password='hodor', first_name='Hodor', last_name='HodorHodor', email='hodor@hodor.hodor') def test_add_comments_without_login(self): """Testing adding comments without login""" response = self.client.post('/comments/add/') self.assertRedirects(response, '/login/?next=/comments/add/') def login(self): self.client.login(username='hodor', password='hodor') def test_add_comments_without_perms(self): """Testing adding comments without login""" Perms.objects.create(user=self.user, access_level=5).save() self.login() response = self.client.post('/comments/add/') self.assertTemplateUsed(response, 'unauthorized.html') def test_doing_get_to_comments_add_view(self): """Doing an HTTP get instead of POST to comments view should silently fail to /incidents/ """ Perms.objects.create(user=self.user, access_level=4).save() self.login() response = self.client.get('/comments/add/') self.assertRedirects(response, '/incidents/') def test_post_a_comment(self): """Actual comments post""" incident = factories.IncidentFactory() Perms.objects.create(user=self.user, access_level=4).save() self.login() response = self.client.post('/comments/add/', data={'incident': incident.id, 'user': self.user.id, 'text': 'Do you remember bo2k?'}, follow=True) self.assertRedirects(response, '/incidents/view/%s/' % incident.id) self.assertContains(response, 'Do you remember bo2k?')
apache-2.0
mit-ll/LO-PHI
lophi-automation/lophi_automation/dataconsumers/logudp.py
1
1294
""" Class to handle logging over UDP (c) 2015 Massachusetts Institute of Technology """ # Native import socket import logging logger = logging.getLogger(__name__) class LogUDP: def __init__(self,address,port): """ Intialize our UDP logger @param address: Address of remote server @param port: port of listening server """ self.address = address self.port = port self.SOCK = None self.connected = False def _connect(self): """ Create our socket """ if self.connected: return True try: self.SOCK = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) self.connected = True return True except: logger.error("Could not open UDP socket") return False def append(self, data): """ Write raw data to the UDP socket @param data: Data to be written to the UDP socket """ assert self._connect() try: self.SOCK.sendto(data,(self.address,self.port)) except: logger.error("Could not send UDP packet")
bsd-3-clause
2014cdag11/2014cadg11
wsgi/static/Brython2.1.0-20140419-113919/Lib/importlib/__init__.py
102
3309
"""A pure Python implementation of import.""" __all__ = ['__import__', 'import_module', 'invalidate_caches'] # Bootstrap help ##################################################### # Until bootstrapping is complete, DO NOT import any modules that attempt # to import importlib._bootstrap (directly or indirectly). Since this # partially initialised package would be present in sys.modules, those # modules would get an uninitialised copy of the source version, instead # of a fully initialised version (either the frozen one or the one # initialised below if the frozen one is not available). import _imp # Just the builtin component, NOT the full Python module import sys try: import _frozen_importlib as _bootstrap except ImportError: from . import _bootstrap _bootstrap._setup(sys, _imp) else: # importlib._bootstrap is the built-in import, ensure we don't create # a second copy of the module. _bootstrap.__name__ = 'importlib._bootstrap' _bootstrap.__package__ = 'importlib' _bootstrap.__file__ = __file__.replace('__init__.py', '_bootstrap.py') sys.modules['importlib._bootstrap'] = _bootstrap # To simplify imports in test code _w_long = _bootstrap._w_long _r_long = _bootstrap._r_long # Fully bootstrapped at this point, import whatever you like, circular # dependencies and startup overhead minimisation permitting :) # Public API ######################################################### from ._bootstrap import __import__ def invalidate_caches(): """Call the invalidate_caches() method on all meta path finders stored in sys.meta_path (where implemented).""" for finder in sys.meta_path: if hasattr(finder, 'invalidate_caches'): finder.invalidate_caches() def find_loader(name, path=None): """Find the loader for the specified module. First, sys.modules is checked to see if the module was already imported. If so, then sys.modules[name].__loader__ is returned. If that happens to be set to None, then ValueError is raised. If the module is not in sys.modules, then sys.meta_path is searched for a suitable loader with the value of 'path' given to the finders. None is returned if no loader could be found. Dotted names do not have their parent packages implicitly imported. You will most likely need to explicitly import all parent packages in the proper order for a submodule to get the correct loader. """ try: loader = sys.modules[name].__loader__ if loader is None: raise ValueError('{}.__loader__ is None'.format(name)) else: return loader except KeyError: pass return _bootstrap._find_module(name, path) def import_module(name, package=None): """Import a module. The 'package' argument is required when performing a relative import. It specifies the package to use as the anchor point from which to resolve the relative import to an absolute import. """ level = 0 if name.startswith('.'): if not package: raise TypeError("relative imports require the 'package' argument") for character in name: if character != '.': break level += 1 return _bootstrap._gcd_import(name[level:], package, level)
gpl-2.0
patrickwind/My_Blog
venv/lib/python2.7/site-packages/werkzeug/testsuite/contrib/wrappers.py
146
3291
# -*- coding: utf-8 -*- """ werkzeug.testsuite.contrib.wrappers ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Added tests for the sessions. :copyright: (c) 2014 by Armin Ronacher. :license: BSD, see LICENSE for more details. """ from __future__ import with_statement import unittest from werkzeug.testsuite import WerkzeugTestCase from werkzeug.contrib import wrappers from werkzeug import routing from werkzeug.wrappers import Request, Response class WrappersTestCase(WerkzeugTestCase): def test_reverse_slash_behavior(self): class MyRequest(wrappers.ReverseSlashBehaviorRequestMixin, Request): pass req = MyRequest.from_values('/foo/bar', 'http://example.com/test') assert req.url == 'http://example.com/test/foo/bar' assert req.path == 'foo/bar' assert req.script_root == '/test/' # make sure the routing system works with the slashes in # reverse order as well. map = routing.Map([routing.Rule('/foo/bar', endpoint='foo')]) adapter = map.bind_to_environ(req.environ) assert adapter.match() == ('foo', {}) adapter = map.bind(req.host, req.script_root) assert adapter.match(req.path) == ('foo', {}) def test_dynamic_charset_request_mixin(self): class MyRequest(wrappers.DynamicCharsetRequestMixin, Request): pass env = {'CONTENT_TYPE': 'text/html'} req = MyRequest(env) assert req.charset == 'latin1' env = {'CONTENT_TYPE': 'text/html; charset=utf-8'} req = MyRequest(env) assert req.charset == 'utf-8' env = {'CONTENT_TYPE': 'application/octet-stream'} req = MyRequest(env) assert req.charset == 'latin1' assert req.url_charset == 'latin1' MyRequest.url_charset = 'utf-8' env = {'CONTENT_TYPE': 'application/octet-stream'} req = MyRequest(env) assert req.charset == 'latin1' assert req.url_charset == 'utf-8' def return_ascii(x): return "ascii" env = {'CONTENT_TYPE': 'text/plain; charset=x-weird-charset'} req = MyRequest(env) req.unknown_charset = return_ascii assert req.charset == 'ascii' assert req.url_charset == 'utf-8' def test_dynamic_charset_response_mixin(self): class MyResponse(wrappers.DynamicCharsetResponseMixin, Response): default_charset = 'utf-7' resp = MyResponse(mimetype='text/html') assert resp.charset == 'utf-7' resp.charset = 'utf-8' assert resp.charset == 'utf-8' assert resp.mimetype == 'text/html' assert resp.mimetype_params == {'charset': 'utf-8'} resp.mimetype_params['charset'] = 'iso-8859-15' assert resp.charset == 'iso-8859-15' resp.set_data(u'Hällo Wörld') assert b''.join(resp.iter_encoded()) == \ u'Hällo Wörld'.encode('iso-8859-15') del resp.headers['content-type'] try: resp.charset = 'utf-8' except TypeError as e: pass else: assert False, 'expected type error on charset setting without ct' def suite(): suite = unittest.TestSuite() suite.addTest(unittest.makeSuite(WrappersTestCase)) return suite
gpl-2.0
xuegang/gpdb
src/test/tinc/tincrepo/mpp/gpdb/tests/package/gphdfs/lib/phd_rpm_util.py
21
16341
""" Copyright (C) 2004-2015 Pivotal Software, Inc. All rights reserved. This program and the accompanying materials are made available under the terms of the under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ import os import re import tinctest from rpm_util import RPMUtil from tinctest.lib import local_path, run_shell_command from hadoop_util import HadoopUtil class PHDRpmUtil(HadoopUtil): """Utility for installing PHD Single node clusters using RPMs""" def __init__( self, hadoop_artifact_url, hadoop_install_dir, hadoop_data_dir, template_conf_dir, hostname = 'localhost', secure_hadoop = False ): HadoopUtil.__init__(self, hadoop_artifact_url, hadoop_install_dir, hadoop_data_dir, hostname) self.rpmutil = RPMUtil() self.hostname = hostname self.hadoop_artifact_url = hadoop_artifact_url self.hadoop_install_dir = hadoop_install_dir self.hadoop_binary_loc = '' self.hadoop_data_dir = hadoop_data_dir self.template_conf_dir = template_conf_dir self.secure_hadoop = secure_hadoop # Constants # under the hadoop template configuration directory # both the below directories should be present self.SECURE_DIR_NAME = "conf.secure" # secure configuration files location self.NON_SECURE_DIR_NAME = "conf.pseudo" # non-secure configuration files location self.DEPENDENCY_PKGS = [ "fuse-", # eg. fuse-2.8.3-4.el6.x86_64 "fuse-libs", # eg. fuse-libs-2.8.3-4.el6.x86_6 "nc-" # eg. 1.84-22.el6.x86_64" ] self.HADOOP_UTILITY_RPMS = "utility/rpm/" self.ZOOKEEPER_RPMS = "zookeeper/rpm/" self.HADOOP_RPMS = "hadoop/rpm/" self.HADOOP_ENVS = { "HADOOP_HOME" : "/usr/lib/gphd/hadoop/", "HADOOP_COMMON_HOME" : "/usr/lib/gphd/hadoop/", "HADOOP_HDFS_HOME" : "/usr/lib/gphd/hadoop-hdfs/", "HADOOP_MAPRED_HOME" : "/usr/lib/gphd/hadoop-mapreduce/", "YARN_HOME" : "/usr/lib/gphd/hadoop-yarn/", "HADOOP_TMP_DIR" : "%s/hadoop-hdfs/cache/" %self.hadoop_data_dir, "MAPRED_TMP_DIR" : "%s/hadoop-mapreduce/cache/" %self.hadoop_data_dir, "YARN_TMP_DIR" : "%s/hadoop-yarn/cache/" %self.hadoop_data_dir, "HADOOP_CONF_DIR" : "/etc/hadoop/conf", "HADOOP_LOG_DIR" : "%s/hadoop-logs/hadoop-hdfs" %self.hadoop_data_dir, "MAPRED_LOG_DIR" : "%s/hadoop-logs/hadoop-mapreduce" %self.hadoop_data_dir, "YARN_LOG_DIR" : "%s/hadoop-logs/hadoop-yarn" %self.hadoop_data_dir } self.PKGS_TO_REMOVE = "^hadoop-*|^bigtop-*|^zookeeper-*|^parquet-*" def _get_hadoop_conf_dir(self): """ Gets the hadoop configuration directory location """ cmd_str = "find /etc/gphd/ -name conf | egrep -v \"zookeeper|httpfs\"" res = {} if run_shell_command(cmd_str, "Find HADOOP_CONF_DIR", res): return res['stdout'].split('\n')[0] def _remove_installed_pkgs(self): self.rpmutil.erase_all_packages(self.PKGS_TO_REMOVE) def _install_dependency_pkgs(self): for pkg in self.DEPENDENCY_PKGS: if not self.rpmutil.is_pkg_installed("^" + pkg): self.rpmutil.install_package_using_yum(pkg, is_regex_pkg_name = True) def cleanup(self): """ Clean-up process to: 1. kill all the hadoop daemon process from previous runs if any 2. Remove the contents from the hadoop installation & configuration locations """ self.stop_hadoop() cmd_str = "ps aux | awk '/\-Dhadoop/{print $2}' | xargs sudo kill -9" run_shell_command(cmd_str, "Kill zombie hadoop daemons") cmd_str = "sudo rm -rf " for key,value in self.HADOOP_ENVS.iteritems(): cmd_str = cmd_str + value +"* " cmd_str = cmd_str + "/etc/gphd" run_shell_command(cmd_str,"Clean up HDFS files") self._remove_installed_pkgs() def _create_symlinks(self, lib_dir, symlink): res = {} cmd_str = "sudo find %s -name \"%s*\"" % (lib_dir,symlink) run_shell_command(cmd_str, "Check for %s symlink" %symlink, res) result = res['stdout'] if result: result = result.splitlines() if len(result) == 1: cmd_str = "cd %s; sudo ln -s %s %s" %(lib_dir, result[0], symlink) run_shell_command(cmd_str, "Create %s symlink" %symlink) def install_binary(self): """ Installs RPM binaries of: 1. utility eg. bigtop utils 2. zookeeper 3. hadoop """ self._install_dependency_pkgs() # install utility rpms hadoop_utility_rpms_loc = os.path.join(self.hadoop_binary_loc, self.HADOOP_UTILITY_RPMS) self.rpmutil.install_rpms_from(hadoop_utility_rpms_loc) # install zookeeper rpms zookeeper_rpms_loc = os.path.join(self.hadoop_binary_loc, self.ZOOKEEPER_RPMS) self.rpmutil.install_rpms_from(zookeeper_rpms_loc) # install hadoop rpms hadoop_rpms_loc = os.path.join(self.hadoop_binary_loc, self.HADOOP_RPMS) self.rpmutil.install_rpms_from(hadoop_rpms_loc) # create hadoop sym links inside /var/lib/gphd lib_dir = "/var/lib/gphd" self._create_symlinks(lib_dir, "hadoop-hdfs") self._create_symlinks(lib_dir, "hadoop-yarn") self._create_symlinks(lib_dir, "hadoop-mapreduce") self._create_symlinks(lib_dir, "zookeeper") def install_hadoop_configurations(self): """ Based on type of installation secure or non-secure, installs the updated template configuration files and makes required changes to the env files. """ ##TODO: Create separate directories for secure & non-secure ## in the hadoop conf dir and copy the update configs in respective directories self.HADOOP_ENVS['HADOOP_CONF_DIR'] = self._get_hadoop_conf_dir() # check the type of hadoop installation - secure or non secure if self.secure_hadoop: # SECURE_DIR_NAME is expected to be present under template configuration directory secure_conf = os.path.join(self.template_conf_dir, self.SECURE_DIR_NAME) super(PHDRpmUtil,self).install_hadoop_configurations(secure_conf, self.HADOOP_ENVS['HADOOP_CONF_DIR']) # update env files in /etc/default/hadoop* if self.hadoop_data_dir.endswith('/'): self.hadoop_data_dir = self.hadoop_data_dir[:-1] cmd_str = "for env_file in `ls /etc/default/hadoop*`;" \ "do " \ "sudo sed -r -i 's:\/var\/log(\/gphd)?:\%s\/hadoop-logs:g' ${env_file};" \ "done" %self.hadoop_data_dir run_shell_command(cmd_str, "Update env files in /etc/default/hadoop*") # update hadoop-env.sh file hadoop_env_file = os.path.join( self.HADOOP_ENVS['HADOOP_CONF_DIR'], "hadoop-env.sh" ) if not os.path.exists(hadoop_env_file): tinctest.logger.info("hadoop-env.sh not found..creating a new one!") run_shell_command("sudo touch %s" %hadoop_env_file, "Create hadoop-env.sh file") # give write permissions on the file self.give_others_write_perm(hadoop_env_file) text = "\n### Added env variables\n" \ "export JAVA_HOME=%s\n" \ "export HADOOP_OPTS=\"-Djava.net.preferIPv4Stack=true " \ "-Djava.library.path=$HADOOP_HOME/lib/native/\"\n" %self.get_java_home() self.append_text_to_file(hadoop_env_file,text) # revert back to old permissions self.remove_others_write_perm(hadoop_env_file) # update env files hadoop-hdfs-datanode & hadoop hdfs_datanode_env = "/etc/default/hadoop-hdfs-datanode" hdfs_hadoop_env = "/etc/default/hadoop" self.give_others_write_perm(hdfs_datanode_env) text = "\n### Secure env variables\n" \ "export HADOOP_SECURE_DN_USER=hdfs\n" \ "export HADOOP_SECURE_DN_LOG_DIR=${HADOOP_LOG_DIR}/hdfs\n" \ "export HADOOP_PID_DIR=/var/run/gphd/hadoop-hdfs/\n" \ "export HADOOP_SECURE_DN_PID_DIR=${HADOOP_PID_DIR}\n" self.append_text_to_file(hdfs_datanode_env, text) self.remove_others_write_perm(hdfs_datanode_env) self.give_others_write_perm(hdfs_hadoop_env) self.append_text_to_file(hdfs_hadoop_env, "export JSVC_HOME=/usr/libexec/bigtop-utils\n") self.remove_others_write_perm(hdfs_hadoop_env) # change the permissions of container-executor container_bin_path = os.path.join(self.HADOOP_ENVS['YARN_HOME'],'bin/container-executor') cmd_str = "sudo chown root:yarn %s" %container_bin_path run_shell_command(cmd_str) cmd_str = "sudo chmod 050 %s" %container_bin_path run_shell_command(cmd_str) cmd_str = "sudo chmod u+s %s" %container_bin_path run_shell_command(cmd_str) cmd_str = "sudo chmod g+s %s" %container_bin_path run_shell_command(cmd_str) else: # NON_SECURE_DIR_NAME is expected to be present under template configuration directory non_secure_conf = os.path.join(self.template_conf_dir, self.NON_SECURE_DIR_NAME) super(PHDRpmUtil, self).install_hadoop_configurations(non_secure_conf, self.HADOOP_ENVS['HADOOP_CONF_DIR']) def start_hdfs(self): # format namenode cmd_str = "sudo -u hdfs hdfs --config %s namenode -format" %self.HADOOP_ENVS['HADOOP_CONF_DIR'] namenode_formatted = run_shell_command(cmd_str) if not namenode_formatted: raise Exception("Exception in namnode formatting") # start namenode cmd_str = "sudo /etc/init.d/hadoop-hdfs-namenode start" namenode_started = run_shell_command(cmd_str) if not namenode_started: raise Exception("Namenode not started") cmd_str = "sudo /etc/init.d/hadoop-hdfs-datanode start" namenode_started = run_shell_command(cmd_str) if not namenode_started: raise Exception("Namenode not started") cmd_str = "sudo /etc/init.d/hadoop-hdfs-secondarynamenode start" namenode_started = run_shell_command(cmd_str) if not namenode_started: raise Exception("Secondary namenode not started") def set_hdfs_permissions(self): if self.secure_hadoop: hdfs_cmd = "sudo hdfs dfs" else: hdfs_cmd = "sudo -u hdfs hdfs dfs" # set hdfs permissions cmd_str = "%s -chmod -R 777 /" %hdfs_cmd run_shell_command(cmd_str) cmd_str = "%s -mkdir /tmp" %hdfs_cmd run_shell_command(cmd_str) cmd_str = "%s -chmod 1777 /tmp" %hdfs_cmd run_shell_command(cmd_str) # cmd_str = "%s -mkdir -p /var/log/gphd/hadoop-yarn" %hdfs_cmd # run_shell_command(cmd_str) cmd_str = "%s -mkdir /user" %hdfs_cmd run_shell_command(cmd_str) cmd_str = "%s -chmod 777 /user" %hdfs_cmd run_shell_command(cmd_str) cmd_str = "%s -mkdir /user/history" %hdfs_cmd run_shell_command(cmd_str) cmd_str = "%s -chown mapred:hadoop /user/history" %hdfs_cmd run_shell_command(cmd_str) cmd_str = "%s -chmod 1777 -R /user/history" %hdfs_cmd run_shell_command(cmd_str) cmd_str = "%s -ls -R /" %hdfs_cmd run_shell_command(cmd_str) def put_file_in_hdfs(self, input_path, hdfs_path): if hdfs_path.rfind('/') > 0: hdfs_dir = hdfs_path[:hdfs_path.rfind('/')] cmd_str = "hdfs dfs -mkdir -p %s" %hdfs_dir run_shell_command(cmd_str, "Creating parent HDFS dir for path %s" %input_path) cmd_str = "hdfs dfs -put %s %s" %(input_path, hdfs_path) run_shell_command(cmd_str, "Copy to HDFS : file %s" %input_path) def remove_file_from_hdfs(self, hdfs_path): cmd_str = "hdfs dfs -rm -r %s" %hdfs_path run_shell_command(cmd_str, "Remove %s from HDFS" %hdfs_path) def start_yarn(self): # start yarn daemons # start resource manager self.set_hdfs_permissions() cmd_str = "sudo /etc/init.d/hadoop-yarn-resourcemanager start" namenode_started = run_shell_command(cmd_str) if not namenode_started: raise Exception("Resource manager not started") # start node manager cmd_str = "sudo /etc/init.d/hadoop-yarn-nodemanager start" namenode_started = run_shell_command(cmd_str) if not namenode_started: raise Exception("Node manager not started") # start history server cmd_str = "sudo /etc/init.d/hadoop-mapreduce-historyserver start" namenode_started = run_shell_command(cmd_str) if not namenode_started: raise Exception("History server not started") def start_hadoop(self): """ Starts the PHD cluster and checks the JPS status """ self.start_hdfs() self.start_yarn() res = {} # run jps command & check for hadoop daemons cmd_str = "sudo jps" run_shell_command(cmd_str, "Check Hadoop Daemons", res) result = res['stdout'] tinctest.logger.info("\n**** Following Hadoop Daemons started **** \n%s" %result) tinctest.logger.info("*** Hadoop Started Successfully!!") def stop_hadoop(self): """ Stops the PHD cluster """ run_shell_command("sudo /etc/init.d/hadoop-mapreduce-historyserver stop", "Stop history-server") run_shell_command("sudo /etc/init.d/hadoop-yarn-nodemanager stop", "Stop Node manager") run_shell_command("sudo /etc/init.d/hadoop-yarn-resourcemanager stop", "Stop resourcemanager") run_shell_command("sudo /etc/init.d/hadoop-hdfs-secondarynamenode stop", "Stop secondarynamenode") run_shell_command("sudo /etc/init.d/hadoop-hdfs-datanode stop", "Stop datanode") run_shell_command("sudo /etc/init.d/hadoop-hdfs-namenode stop", "Stop namenode") def get_hadoop_env(self): """ Returns a dictionary of hadoop environment variables like: 1. HADOOP_HOME 2. HADOOP_CONF_DIR 3. HADOOP_COMMON_HOME 4. HADOOP_HDFS_HOME 5. YARN_HOME 6. HADOOP_MAPRED_HOME """ return self.HADOOP_ENVS def init_cluster(self): """ Init point for starting up the PHD cluster """ self.download_binary_and_untar() self.cleanup() self.install_binary() self.install_hadoop_configurations() self.start_hadoop() if __name__ == '__main__': hdfs_util = PHDRpmUtil("http://build-prod.sanmateo.greenplum.com/releases/pivotal-hd/1.1.1/PHD-1.1.1.0-82.tar.gz","/data/gpadmin/hadoop_test","../configs/rpm/","localhost") hdfs_util.init_cluster()
apache-2.0
willingc/oh-mainline
vendor/packages/Pygments/pygments/lexers/dotnet.py
71
24916
# -*- coding: utf-8 -*- """ pygments.lexers.dotnet ~~~~~~~~~~~~~~~~~~~~~~ Lexers for .net languages. :copyright: Copyright 2006-2013 by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details. """ import re from pygments.lexer import RegexLexer, DelegatingLexer, bygroups, include, \ using, this from pygments.token import Punctuation, \ Text, Comment, Operator, Keyword, Name, String, Number, Literal, Other from pygments.util import get_choice_opt from pygments import unistring as uni from pygments.lexers.web import XmlLexer __all__ = ['CSharpLexer', 'NemerleLexer', 'BooLexer', 'VbNetLexer', 'CSharpAspxLexer', 'VbNetAspxLexer', 'FSharpLexer'] class CSharpLexer(RegexLexer): """ For `C# <http://msdn2.microsoft.com/en-us/vcsharp/default.aspx>`_ source code. Additional options accepted: `unicodelevel` Determines which Unicode characters this lexer allows for identifiers. The possible values are: * ``none`` -- only the ASCII letters and numbers are allowed. This is the fastest selection. * ``basic`` -- all Unicode characters from the specification except category ``Lo`` are allowed. * ``full`` -- all Unicode characters as specified in the C# specs are allowed. Note that this means a considerable slowdown since the ``Lo`` category has more than 40,000 characters in it! The default value is ``basic``. *New in Pygments 0.8.* """ name = 'C#' aliases = ['csharp', 'c#'] filenames = ['*.cs'] mimetypes = ['text/x-csharp'] # inferred flags = re.MULTILINE | re.DOTALL | re.UNICODE # for the range of allowed unicode characters in identifiers, # see http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-334.pdf levels = { 'none': '@?[_a-zA-Z][a-zA-Z0-9_]*', 'basic': ('@?[_' + uni.Lu + uni.Ll + uni.Lt + uni.Lm + uni.Nl + ']' + '[' + uni.Lu + uni.Ll + uni.Lt + uni.Lm + uni.Nl + uni.Nd + uni.Pc + uni.Cf + uni.Mn + uni.Mc + ']*'), 'full': ('@?(?:_|[^' + uni.allexcept('Lu', 'Ll', 'Lt', 'Lm', 'Lo', 'Nl') + '])' + '[^' + uni.allexcept('Lu', 'Ll', 'Lt', 'Lm', 'Lo', 'Nl', 'Nd', 'Pc', 'Cf', 'Mn', 'Mc') + ']*'), } tokens = {} token_variants = True for levelname, cs_ident in levels.items(): tokens[levelname] = { 'root': [ # method names (r'^([ \t]*(?:' + cs_ident + r'(?:\[\])?\s+)+?)' # return type r'(' + cs_ident + ')' # method name r'(\s*)(\()', # signature start bygroups(using(this), Name.Function, Text, Punctuation)), (r'^\s*\[.*?\]', Name.Attribute), (r'[^\S\n]+', Text), (r'\\\n', Text), # line continuation (r'//.*?\n', Comment.Single), (r'/[*].*?[*]/', Comment.Multiline), (r'\n', Text), (r'[~!%^&*()+=|\[\]:;,.<>/?-]', Punctuation), (r'[{}]', Punctuation), (r'@"(""|[^"])*"', String), (r'"(\\\\|\\"|[^"\n])*["\n]', String), (r"'\\.'|'[^\\]'", String.Char), (r"[0-9](\.[0-9]*)?([eE][+-][0-9]+)?" r"[flFLdD]?|0[xX][0-9a-fA-F]+[Ll]?", Number), (r'#[ \t]*(if|endif|else|elif|define|undef|' r'line|error|warning|region|endregion|pragma)\b.*?\n', Comment.Preproc), (r'\b(extern)(\s+)(alias)\b', bygroups(Keyword, Text, Keyword)), (r'(abstract|as|async|await|base|break|case|catch|' r'checked|const|continue|default|delegate|' r'do|else|enum|event|explicit|extern|false|finally|' r'fixed|for|foreach|goto|if|implicit|in|interface|' r'internal|is|lock|new|null|operator|' r'out|override|params|private|protected|public|readonly|' r'ref|return|sealed|sizeof|stackalloc|static|' r'switch|this|throw|true|try|typeof|' r'unchecked|unsafe|virtual|void|while|' r'get|set|new|partial|yield|add|remove|value|alias|ascending|' r'descending|from|group|into|orderby|select|where|' r'join|equals)\b', Keyword), (r'(global)(::)', bygroups(Keyword, Punctuation)), (r'(bool|byte|char|decimal|double|dynamic|float|int|long|object|' r'sbyte|short|string|uint|ulong|ushort|var)\b\??', Keyword.Type), (r'(class|struct)(\s+)', bygroups(Keyword, Text), 'class'), (r'(namespace|using)(\s+)', bygroups(Keyword, Text), 'namespace'), (cs_ident, Name), ], 'class': [ (cs_ident, Name.Class, '#pop') ], 'namespace': [ (r'(?=\()', Text, '#pop'), # using (resource) ('(' + cs_ident + r'|\.)+', Name.Namespace, '#pop') ] } def __init__(self, **options): level = get_choice_opt(options, 'unicodelevel', self.tokens.keys(), 'basic') if level not in self._all_tokens: # compile the regexes now self._tokens = self.__class__.process_tokendef(level) else: self._tokens = self._all_tokens[level] RegexLexer.__init__(self, **options) class NemerleLexer(RegexLexer): """ For `Nemerle <http://nemerle.org>`_ source code. Additional options accepted: `unicodelevel` Determines which Unicode characters this lexer allows for identifiers. The possible values are: * ``none`` -- only the ASCII letters and numbers are allowed. This is the fastest selection. * ``basic`` -- all Unicode characters from the specification except category ``Lo`` are allowed. * ``full`` -- all Unicode characters as specified in the C# specs are allowed. Note that this means a considerable slowdown since the ``Lo`` category has more than 40,000 characters in it! The default value is ``basic``. *New in Pygments 1.5.* """ name = 'Nemerle' aliases = ['nemerle'] filenames = ['*.n'] mimetypes = ['text/x-nemerle'] # inferred flags = re.MULTILINE | re.DOTALL | re.UNICODE # for the range of allowed unicode characters in identifiers, see # http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-334.pdf levels = dict( none = '@?[_a-zA-Z][a-zA-Z0-9_]*', basic = ('@?[_' + uni.Lu + uni.Ll + uni.Lt + uni.Lm + uni.Nl + ']' + '[' + uni.Lu + uni.Ll + uni.Lt + uni.Lm + uni.Nl + uni.Nd + uni.Pc + uni.Cf + uni.Mn + uni.Mc + ']*'), full = ('@?(?:_|[^' + uni.allexcept('Lu', 'Ll', 'Lt', 'Lm', 'Lo', 'Nl') + '])' + '[^' + uni.allexcept('Lu', 'Ll', 'Lt', 'Lm', 'Lo', 'Nl', 'Nd', 'Pc', 'Cf', 'Mn', 'Mc') + ']*'), ) tokens = {} token_variants = True for levelname, cs_ident in levels.items(): tokens[levelname] = { 'root': [ # method names (r'^([ \t]*(?:' + cs_ident + r'(?:\[\])?\s+)+?)' # return type r'(' + cs_ident + ')' # method name r'(\s*)(\()', # signature start bygroups(using(this), Name.Function, Text, Punctuation)), (r'^\s*\[.*?\]', Name.Attribute), (r'[^\S\n]+', Text), (r'\\\n', Text), # line continuation (r'//.*?\n', Comment.Single), (r'/[*].*?[*]/', Comment.Multiline), (r'\n', Text), (r'\$\s*"', String, 'splice-string'), (r'\$\s*<#', String, 'splice-string2'), (r'<#', String, 'recursive-string'), (r'(<\[)\s*(' + cs_ident + ':)?', Keyword), (r'\]\>', Keyword), # quasiquotation only (r'\$' + cs_ident, Name), (r'(\$)(\()', bygroups(Name, Punctuation), 'splice-string-content'), (r'[~!%^&*()+=|\[\]:;,.<>/?-]', Punctuation), (r'[{}]', Punctuation), (r'@"(""|[^"])*"', String), (r'"(\\\\|\\"|[^"\n])*["\n]', String), (r"'\\.'|'[^\\]'", String.Char), (r"0[xX][0-9a-fA-F]+[Ll]?", Number), (r"[0-9](\.[0-9]*)?([eE][+-][0-9]+)?[flFLdD]?", Number), (r'#[ \t]*(if|endif|else|elif|define|undef|' r'line|error|warning|region|endregion|pragma)\b.*?\n', Comment.Preproc), (r'\b(extern)(\s+)(alias)\b', bygroups(Keyword, Text, Keyword)), (r'(abstract|and|as|base|catch|def|delegate|' r'enum|event|extern|false|finally|' r'fun|implements|interface|internal|' r'is|macro|match|matches|module|mutable|new|' r'null|out|override|params|partial|private|' r'protected|public|ref|sealed|static|' r'syntax|this|throw|true|try|type|typeof|' r'virtual|volatile|when|where|with|' r'assert|assert2|async|break|checked|continue|do|else|' r'ensures|for|foreach|if|late|lock|new|nolate|' r'otherwise|regexp|repeat|requires|return|surroundwith|' r'unchecked|unless|using|while|yield)\b', Keyword), (r'(global)(::)', bygroups(Keyword, Punctuation)), (r'(bool|byte|char|decimal|double|float|int|long|object|sbyte|' r'short|string|uint|ulong|ushort|void|array|list)\b\??', Keyword.Type), (r'(:>?)\s*(' + cs_ident + r'\??)', bygroups(Punctuation, Keyword.Type)), (r'(class|struct|variant|module)(\s+)', bygroups(Keyword, Text), 'class'), (r'(namespace|using)(\s+)', bygroups(Keyword, Text), 'namespace'), (cs_ident, Name), ], 'class': [ (cs_ident, Name.Class, '#pop') ], 'namespace': [ (r'(?=\()', Text, '#pop'), # using (resource) ('(' + cs_ident + r'|\.)+', Name.Namespace, '#pop') ], 'splice-string': [ (r'[^"$]', String), (r'\$' + cs_ident, Name), (r'(\$)(\()', bygroups(Name, Punctuation), 'splice-string-content'), (r'\\"', String), (r'"', String, '#pop') ], 'splice-string2': [ (r'[^#<>$]', String), (r'\$' + cs_ident, Name), (r'(\$)(\()', bygroups(Name, Punctuation), 'splice-string-content'), (r'<#', String, '#push'), (r'#>', String, '#pop') ], 'recursive-string': [ (r'[^#<>]', String), (r'<#', String, '#push'), (r'#>', String, '#pop') ], 'splice-string-content': [ (r'if|match', Keyword), (r'[~!%^&*+=|\[\]:;,.<>/?-\\"$ ]', Punctuation), (cs_ident, Name), (r'\d+', Number), (r'\(', Punctuation, '#push'), (r'\)', Punctuation, '#pop') ] } def __init__(self, **options): level = get_choice_opt(options, 'unicodelevel', self.tokens.keys(), 'basic') if level not in self._all_tokens: # compile the regexes now self._tokens = self.__class__.process_tokendef(level) else: self._tokens = self._all_tokens[level] RegexLexer.__init__(self, **options) class BooLexer(RegexLexer): """ For `Boo <http://boo.codehaus.org/>`_ source code. """ name = 'Boo' aliases = ['boo'] filenames = ['*.boo'] mimetypes = ['text/x-boo'] tokens = { 'root': [ (r'\s+', Text), (r'(#|//).*$', Comment.Single), (r'/[*]', Comment.Multiline, 'comment'), (r'[]{}:(),.;[]', Punctuation), (r'\\\n', Text), (r'\\', Text), (r'(in|is|and|or|not)\b', Operator.Word), (r'/(\\\\|\\/|[^/\s])/', String.Regex), (r'@/(\\\\|\\/|[^/])*/', String.Regex), (r'=~|!=|==|<<|>>|[-+/*%=<>&^|]', Operator), (r'(as|abstract|callable|constructor|destructor|do|import|' r'enum|event|final|get|interface|internal|of|override|' r'partial|private|protected|public|return|set|static|' r'struct|transient|virtual|yield|super|and|break|cast|' r'continue|elif|else|ensure|except|for|given|goto|if|in|' r'is|isa|not|or|otherwise|pass|raise|ref|try|unless|when|' r'while|from|as)\b', Keyword), (r'def(?=\s+\(.*?\))', Keyword), (r'(def)(\s+)', bygroups(Keyword, Text), 'funcname'), (r'(class)(\s+)', bygroups(Keyword, Text), 'classname'), (r'(namespace)(\s+)', bygroups(Keyword, Text), 'namespace'), (r'(?<!\.)(true|false|null|self|__eval__|__switch__|array|' r'assert|checked|enumerate|filter|getter|len|lock|map|' r'matrix|max|min|normalArrayIndexing|print|property|range|' r'rawArrayIndexing|required|typeof|unchecked|using|' r'yieldAll|zip)\b', Name.Builtin), (r'"""(\\\\|\\"|.*?)"""', String.Double), (r'"(\\\\|\\"|[^"]*?)"', String.Double), (r"'(\\\\|\\'|[^']*?)'", String.Single), (r'[a-zA-Z_][a-zA-Z0-9_]*', Name), (r'(\d+\.\d*|\d*\.\d+)([fF][+-]?[0-9]+)?', Number.Float), (r'[0-9][0-9\.]*(ms?|d|h|s)', Number), (r'0\d+', Number.Oct), (r'0x[a-fA-F0-9]+', Number.Hex), (r'\d+L', Number.Integer.Long), (r'\d+', Number.Integer), ], 'comment': [ ('/[*]', Comment.Multiline, '#push'), ('[*]/', Comment.Multiline, '#pop'), ('[^/*]', Comment.Multiline), ('[*/]', Comment.Multiline) ], 'funcname': [ ('[a-zA-Z_][a-zA-Z0-9_]*', Name.Function, '#pop') ], 'classname': [ ('[a-zA-Z_][a-zA-Z0-9_]*', Name.Class, '#pop') ], 'namespace': [ ('[a-zA-Z_][a-zA-Z0-9_.]*', Name.Namespace, '#pop') ] } class VbNetLexer(RegexLexer): """ For `Visual Basic.NET <http://msdn2.microsoft.com/en-us/vbasic/default.aspx>`_ source code. """ name = 'VB.net' aliases = ['vb.net', 'vbnet'] filenames = ['*.vb', '*.bas'] mimetypes = ['text/x-vbnet', 'text/x-vba'] # (?) flags = re.MULTILINE | re.IGNORECASE tokens = { 'root': [ (r'^\s*<.*?>', Name.Attribute), (r'\s+', Text), (r'\n', Text), (r'rem\b.*?\n', Comment), (r"'.*?\n", Comment), (r'#If\s.*?\sThen|#ElseIf\s.*?\sThen|#End\s+If|#Const|' r'#ExternalSource.*?\n|#End\s+ExternalSource|' r'#Region.*?\n|#End\s+Region|#ExternalChecksum', Comment.Preproc), (r'[\(\){}!#,.:]', Punctuation), (r'Option\s+(Strict|Explicit|Compare)\s+' r'(On|Off|Binary|Text)', Keyword.Declaration), (r'(?<!\.)(AddHandler|Alias|' r'ByRef|ByVal|Call|Case|Catch|CBool|CByte|CChar|CDate|' r'CDec|CDbl|CInt|CLng|CObj|Continue|CSByte|CShort|' r'CSng|CStr|CType|CUInt|CULng|CUShort|Declare|' r'Default|Delegate|DirectCast|Do|Each|Else|ElseIf|' r'EndIf|Erase|Error|Event|Exit|False|Finally|For|' r'Friend|Get|Global|GoSub|GoTo|Handles|If|' r'Implements|Inherits|Interface|' r'Let|Lib|Loop|Me|MustInherit|' r'MustOverride|MyBase|MyClass|Narrowing|New|Next|' r'Not|Nothing|NotInheritable|NotOverridable|Of|On|' r'Operator|Option|Optional|Overloads|Overridable|' r'Overrides|ParamArray|Partial|Private|Protected|' r'Public|RaiseEvent|ReadOnly|ReDim|RemoveHandler|Resume|' r'Return|Select|Set|Shadows|Shared|Single|' r'Static|Step|Stop|SyncLock|Then|' r'Throw|To|True|Try|TryCast|Wend|' r'Using|When|While|Widening|With|WithEvents|' r'WriteOnly)\b', Keyword), (r'(?<!\.)End\b', Keyword, 'end'), (r'(?<!\.)(Dim|Const)\b', Keyword, 'dim'), (r'(?<!\.)(Function|Sub|Property)(\s+)', bygroups(Keyword, Text), 'funcname'), (r'(?<!\.)(Class|Structure|Enum)(\s+)', bygroups(Keyword, Text), 'classname'), (r'(?<!\.)(Module|Namespace|Imports)(\s+)', bygroups(Keyword, Text), 'namespace'), (r'(?<!\.)(Boolean|Byte|Char|Date|Decimal|Double|Integer|Long|' r'Object|SByte|Short|Single|String|Variant|UInteger|ULong|' r'UShort)\b', Keyword.Type), (r'(?<!\.)(AddressOf|And|AndAlso|As|GetType|In|Is|IsNot|Like|Mod|' r'Or|OrElse|TypeOf|Xor)\b', Operator.Word), (r'&=|[*]=|/=|\\=|\^=|\+=|-=|<<=|>>=|<<|>>|:=|' r'<=|>=|<>|[-&*/\\^+=<>]', Operator), ('"', String, 'string'), ('[a-zA-Z_][a-zA-Z0-9_]*[%&@!#$]?', Name), ('#.*?#', Literal.Date), (r'(\d+\.\d*|\d*\.\d+)([fF][+-]?[0-9]+)?', Number.Float), (r'\d+([SILDFR]|US|UI|UL)?', Number.Integer), (r'&H[0-9a-f]+([SILDFR]|US|UI|UL)?', Number.Integer), (r'&O[0-7]+([SILDFR]|US|UI|UL)?', Number.Integer), (r'_\n', Text), # Line continuation ], 'string': [ (r'""', String), (r'"C?', String, '#pop'), (r'[^"]+', String), ], 'dim': [ (r'[a-z_][a-z0-9_]*', Name.Variable, '#pop'), (r'', Text, '#pop'), # any other syntax ], 'funcname': [ (r'[a-z_][a-z0-9_]*', Name.Function, '#pop'), ], 'classname': [ (r'[a-z_][a-z0-9_]*', Name.Class, '#pop'), ], 'namespace': [ (r'[a-z_][a-z0-9_.]*', Name.Namespace, '#pop'), ], 'end': [ (r'\s+', Text), (r'(Function|Sub|Property|Class|Structure|Enum|Module|Namespace)\b', Keyword, '#pop'), (r'', Text, '#pop'), ] } class GenericAspxLexer(RegexLexer): """ Lexer for ASP.NET pages. """ name = 'aspx-gen' filenames = [] mimetypes = [] flags = re.DOTALL tokens = { 'root': [ (r'(<%[@=#]?)(.*?)(%>)', bygroups(Name.Tag, Other, Name.Tag)), (r'(<script.*?>)(.*?)(</script>)', bygroups(using(XmlLexer), Other, using(XmlLexer))), (r'(.+?)(?=<)', using(XmlLexer)), (r'.+', using(XmlLexer)), ], } #TODO support multiple languages within the same source file class CSharpAspxLexer(DelegatingLexer): """ Lexer for highligting C# within ASP.NET pages. """ name = 'aspx-cs' aliases = ['aspx-cs'] filenames = ['*.aspx', '*.asax', '*.ascx', '*.ashx', '*.asmx', '*.axd'] mimetypes = [] def __init__(self, **options): super(CSharpAspxLexer, self).__init__(CSharpLexer,GenericAspxLexer, **options) def analyse_text(text): if re.search(r'Page\s*Language="C#"', text, re.I) is not None: return 0.2 elif re.search(r'script[^>]+language=["\']C#', text, re.I) is not None: return 0.15 class VbNetAspxLexer(DelegatingLexer): """ Lexer for highligting Visual Basic.net within ASP.NET pages. """ name = 'aspx-vb' aliases = ['aspx-vb'] filenames = ['*.aspx', '*.asax', '*.ascx', '*.ashx', '*.asmx', '*.axd'] mimetypes = [] def __init__(self, **options): super(VbNetAspxLexer, self).__init__(VbNetLexer,GenericAspxLexer, **options) def analyse_text(text): if re.search(r'Page\s*Language="Vb"', text, re.I) is not None: return 0.2 elif re.search(r'script[^>]+language=["\']vb', text, re.I) is not None: return 0.15 # Very close to functional.OcamlLexer class FSharpLexer(RegexLexer): """ For the F# language. *New in Pygments 1.5.* """ name = 'FSharp' aliases = ['fsharp'] filenames = ['*.fs', '*.fsi'] mimetypes = ['text/x-fsharp'] keywords = [ 'abstract', 'and', 'as', 'assert', 'base', 'begin', 'class', 'default', 'delegate', 'do', 'do!', 'done', 'downcast', 'downto', 'elif', 'else', 'end', 'exception', 'extern', 'false', 'finally', 'for', 'fun', 'function', 'global', 'if', 'in', 'inherit', 'inline', 'interface', 'internal', 'lazy', 'let', 'let!', 'match', 'member', 'module', 'mutable', 'namespace', 'new', 'null', 'of', 'open', 'or', 'override', 'private', 'public', 'rec', 'return', 'return!', 'sig', 'static', 'struct', 'then', 'to', 'true', 'try', 'type', 'upcast', 'use', 'use!', 'val', 'void', 'when', 'while', 'with', 'yield', 'yield!' ] keyopts = [ '!=','#','&&','&','\(','\)','\*','\+',',','-\.', '->','-','\.\.','\.','::',':=',':>',':',';;',';','<-', '<','>]','>','\?\?','\?','\[<','\[>','\[\|','\[', ']','_','`','{','\|\]','\|','}','~','<@','=','@>' ] operators = r'[!$%&*+\./:<=>?@^|~-]' word_operators = ['and', 'asr', 'land', 'lor', 'lsl', 'lxor', 'mod', 'not', 'or'] prefix_syms = r'[!?~]' infix_syms = r'[=<>@^|&+\*/$%-]' primitives = ['unit', 'int', 'float', 'bool', 'string', 'char', 'list', 'array', 'byte', 'sbyte', 'int16', 'uint16', 'uint32', 'int64', 'uint64' 'nativeint', 'unativeint', 'decimal', 'void', 'float32', 'single', 'double'] tokens = { 'escape-sequence': [ (r'\\[\\\"\'ntbr]', String.Escape), (r'\\[0-9]{3}', String.Escape), (r'\\x[0-9a-fA-F]{2}', String.Escape), ], 'root': [ (r'\s+', Text), (r'false|true|\(\)|\[\]', Name.Builtin.Pseudo), (r'\b([A-Z][A-Za-z0-9_\']*)(?=\s*\.)', Name.Namespace, 'dotted'), (r'\b([A-Z][A-Za-z0-9_\']*)', Name.Class), (r'//.*?\n', Comment.Single), (r'\(\*(?!\))', Comment, 'comment'), (r'\b(%s)\b' % '|'.join(keywords), Keyword), (r'(%s)' % '|'.join(keyopts), Operator), (r'(%s|%s)?%s' % (infix_syms, prefix_syms, operators), Operator), (r'\b(%s)\b' % '|'.join(word_operators), Operator.Word), (r'\b(%s)\b' % '|'.join(primitives), Keyword.Type), (r'#[ \t]*(if|endif|else|line|nowarn|light)\b.*?\n', Comment.Preproc), (r"[^\W\d][\w']*", Name), (r'\d[\d_]*', Number.Integer), (r'0[xX][\da-fA-F][\da-fA-F_]*', Number.Hex), (r'0[oO][0-7][0-7_]*', Number.Oct), (r'0[bB][01][01_]*', Number.Binary), (r'-?\d[\d_]*(.[\d_]*)?([eE][+\-]?\d[\d_]*)', Number.Float), (r"'(?:(\\[\\\"'ntbr ])|(\\[0-9]{3})|(\\x[0-9a-fA-F]{2}))'", String.Char), (r"'.'", String.Char), (r"'", Keyword), # a stray quote is another syntax element (r'"', String.Double, 'string'), (r'[~?][a-z][\w\']*:', Name.Variable), ], 'comment': [ (r'[^(*)]+', Comment), (r'\(\*', Comment, '#push'), (r'\*\)', Comment, '#pop'), (r'[(*)]', Comment), ], 'string': [ (r'[^\\"]+', String.Double), include('escape-sequence'), (r'\\\n', String.Double), (r'"', String.Double, '#pop'), ], 'dotted': [ (r'\s+', Text), (r'\.', Punctuation), (r'[A-Z][A-Za-z0-9_\']*(?=\s*\.)', Name.Namespace), (r'[A-Z][A-Za-z0-9_\']*', Name.Class, '#pop'), (r'[a-z_][A-Za-z0-9_\']*', Name, '#pop'), ], }
agpl-3.0