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
timduru/platform-external-chromium_org
third_party/python_gflags/gflags2man.py
407
18864
#!/usr/bin/env python # Copyright (c) 2006, Google Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following disclaimer # in the documentation and/or other materials provided with the # distribution. # * Neither the name of Google Inc. nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """gflags2man runs a Google flags base program and generates a man page. Run the program, parse the output, and then format that into a man page. Usage: gflags2man <program> [program] ... """ # TODO(csilvers): work with windows paths (\) as well as unix (/) # This may seem a bit of an end run, but it: doesn't bloat flags, can # support python/java/C++, supports older executables, and can be # extended to other document formats. # Inspired by help2man. import os import re import sys import stat import time import gflags _VERSION = '0.1' def _GetDefaultDestDir(): home = os.environ.get('HOME', '') homeman = os.path.join(home, 'man', 'man1') if home and os.path.exists(homeman): return homeman else: return os.environ.get('TMPDIR', '/tmp') FLAGS = gflags.FLAGS gflags.DEFINE_string('dest_dir', _GetDefaultDestDir(), 'Directory to write resulting manpage to.' ' Specify \'-\' for stdout') gflags.DEFINE_string('help_flag', '--help', 'Option to pass to target program in to get help') gflags.DEFINE_integer('v', 0, 'verbosity level to use for output') _MIN_VALID_USAGE_MSG = 9 # if fewer lines than this, help is suspect class Logging: """A super-simple logging class""" def error(self, msg): print >>sys.stderr, "ERROR: ", msg def warn(self, msg): print >>sys.stderr, "WARNING: ", msg def info(self, msg): print msg def debug(self, msg): self.vlog(1, msg) def vlog(self, level, msg): if FLAGS.v >= level: print msg logging = Logging() class App: def usage(self, shorthelp=0): print >>sys.stderr, __doc__ print >>sys.stderr, "flags:" print >>sys.stderr, str(FLAGS) def run(self): main(sys.argv) app = App() def GetRealPath(filename): """Given an executable filename, find in the PATH or find absolute path. Args: filename An executable filename (string) Returns: Absolute version of filename. None if filename could not be found locally, absolutely, or in PATH """ if os.path.isabs(filename): # already absolute return filename if filename.startswith('./') or filename.startswith('../'): # relative return os.path.abspath(filename) path = os.getenv('PATH', '') for directory in path.split(':'): tryname = os.path.join(directory, filename) if os.path.exists(tryname): if not os.path.isabs(directory): # relative directory return os.path.abspath(tryname) return tryname if os.path.exists(filename): return os.path.abspath(filename) return None # could not determine class Flag(object): """The information about a single flag.""" def __init__(self, flag_desc, help): """Create the flag object. Args: flag_desc The command line forms this could take. (string) help The help text (string) """ self.desc = flag_desc # the command line forms self.help = help # the help text self.default = '' # default value self.tips = '' # parsing/syntax tips class ProgramInfo(object): """All the information gleaned from running a program with --help.""" # Match a module block start, for python scripts --help # "goopy.logging:" module_py_re = re.compile(r'(\S.+):$') # match the start of a flag listing # " -v,--verbosity: Logging verbosity" flag_py_re = re.compile(r'\s+(-\S+):\s+(.*)$') # " (default: '0')" flag_default_py_re = re.compile(r'\s+\(default:\s+\'(.*)\'\)$') # " (an integer)" flag_tips_py_re = re.compile(r'\s+\((.*)\)$') # Match a module block start, for c++ programs --help # "google/base/commandlineflags": module_c_re = re.compile(r'\s+Flags from (\S.+):$') # match the start of a flag listing # " -v,--verbosity: Logging verbosity" flag_c_re = re.compile(r'\s+(-\S+)\s+(.*)$') # Match a module block start, for java programs --help # "com.google.common.flags" module_java_re = re.compile(r'\s+Flags for (\S.+):$') # match the start of a flag listing # " -v,--verbosity: Logging verbosity" flag_java_re = re.compile(r'\s+(-\S+)\s+(.*)$') def __init__(self, executable): """Create object with executable. Args: executable Program to execute (string) """ self.long_name = executable self.name = os.path.basename(executable) # name # Get name without extension (PAR files) (self.short_name, self.ext) = os.path.splitext(self.name) self.executable = GetRealPath(executable) # name of the program self.output = [] # output from the program. List of lines. self.desc = [] # top level description. List of lines self.modules = {} # { section_name(string), [ flags ] } self.module_list = [] # list of module names in their original order self.date = time.localtime(time.time()) # default date info def Run(self): """Run it and collect output. Returns: 1 (true) If everything went well. 0 (false) If there were problems. """ if not self.executable: logging.error('Could not locate "%s"' % self.long_name) return 0 finfo = os.stat(self.executable) self.date = time.localtime(finfo[stat.ST_MTIME]) logging.info('Running: %s %s </dev/null 2>&1' % (self.executable, FLAGS.help_flag)) # --help output is often routed to stderr, so we combine with stdout. # Re-direct stdin to /dev/null to encourage programs that # don't understand --help to exit. (child_stdin, child_stdout_and_stderr) = os.popen4( [self.executable, FLAGS.help_flag]) child_stdin.close() # '</dev/null' self.output = child_stdout_and_stderr.readlines() child_stdout_and_stderr.close() if len(self.output) < _MIN_VALID_USAGE_MSG: logging.error('Error: "%s %s" returned only %d lines: %s' % (self.name, FLAGS.help_flag, len(self.output), self.output)) return 0 return 1 def Parse(self): """Parse program output.""" (start_line, lang) = self.ParseDesc() if start_line < 0: return if 'python' == lang: self.ParsePythonFlags(start_line) elif 'c' == lang: self.ParseCFlags(start_line) elif 'java' == lang: self.ParseJavaFlags(start_line) def ParseDesc(self, start_line=0): """Parse the initial description. This could be Python or C++. Returns: (start_line, lang_type) start_line Line to start parsing flags on (int) lang_type Either 'python' or 'c' (-1, '') if the flags start could not be found """ exec_mod_start = self.executable + ':' after_blank = 0 start_line = 0 # ignore the passed-in arg for now (?) for start_line in range(start_line, len(self.output)): # collect top description line = self.output[start_line].rstrip() # Python flags start with 'flags:\n' if ('flags:' == line and len(self.output) > start_line+1 and '' == self.output[start_line+1].rstrip()): start_line += 2 logging.debug('Flags start (python): %s' % line) return (start_line, 'python') # SWIG flags just have the module name followed by colon. if exec_mod_start == line: logging.debug('Flags start (swig): %s' % line) return (start_line, 'python') # C++ flags begin after a blank line and with a constant string if after_blank and line.startswith(' Flags from '): logging.debug('Flags start (c): %s' % line) return (start_line, 'c') # java flags begin with a constant string if line == 'where flags are': logging.debug('Flags start (java): %s' % line) start_line += 2 # skip "Standard flags:" return (start_line, 'java') logging.debug('Desc: %s' % line) self.desc.append(line) after_blank = (line == '') else: logging.warn('Never found the start of the flags section for "%s"!' % self.long_name) return (-1, '') def ParsePythonFlags(self, start_line=0): """Parse python/swig style flags.""" modname = None # name of current module modlist = [] flag = None for line_num in range(start_line, len(self.output)): # collect flags line = self.output[line_num].rstrip() if not line: # blank continue mobj = self.module_py_re.match(line) if mobj: # start of a new module modname = mobj.group(1) logging.debug('Module: %s' % line) if flag: modlist.append(flag) self.module_list.append(modname) self.modules.setdefault(modname, []) modlist = self.modules[modname] flag = None continue mobj = self.flag_py_re.match(line) if mobj: # start of a new flag if flag: modlist.append(flag) logging.debug('Flag: %s' % line) flag = Flag(mobj.group(1), mobj.group(2)) continue if not flag: # continuation of a flag logging.error('Flag info, but no current flag "%s"' % line) mobj = self.flag_default_py_re.match(line) if mobj: # (default: '...') flag.default = mobj.group(1) logging.debug('Fdef: %s' % line) continue mobj = self.flag_tips_py_re.match(line) if mobj: # (tips) flag.tips = mobj.group(1) logging.debug('Ftip: %s' % line) continue if flag and flag.help: flag.help += line # multiflags tack on an extra line else: logging.info('Extra: %s' % line) if flag: modlist.append(flag) def ParseCFlags(self, start_line=0): """Parse C style flags.""" modname = None # name of current module modlist = [] flag = None for line_num in range(start_line, len(self.output)): # collect flags line = self.output[line_num].rstrip() if not line: # blank lines terminate flags if flag: # save last flag modlist.append(flag) flag = None continue mobj = self.module_c_re.match(line) if mobj: # start of a new module modname = mobj.group(1) logging.debug('Module: %s' % line) if flag: modlist.append(flag) self.module_list.append(modname) self.modules.setdefault(modname, []) modlist = self.modules[modname] flag = None continue mobj = self.flag_c_re.match(line) if mobj: # start of a new flag if flag: # save last flag modlist.append(flag) logging.debug('Flag: %s' % line) flag = Flag(mobj.group(1), mobj.group(2)) continue # append to flag help. type and default are part of the main text if flag: flag.help += ' ' + line.strip() else: logging.info('Extra: %s' % line) if flag: modlist.append(flag) def ParseJavaFlags(self, start_line=0): """Parse Java style flags (com.google.common.flags).""" # The java flags prints starts with a "Standard flags" "module" # that doesn't follow the standard module syntax. modname = 'Standard flags' # name of current module self.module_list.append(modname) self.modules.setdefault(modname, []) modlist = self.modules[modname] flag = None for line_num in range(start_line, len(self.output)): # collect flags line = self.output[line_num].rstrip() logging.vlog(2, 'Line: "%s"' % line) if not line: # blank lines terminate module if flag: # save last flag modlist.append(flag) flag = None continue mobj = self.module_java_re.match(line) if mobj: # start of a new module modname = mobj.group(1) logging.debug('Module: %s' % line) if flag: modlist.append(flag) self.module_list.append(modname) self.modules.setdefault(modname, []) modlist = self.modules[modname] flag = None continue mobj = self.flag_java_re.match(line) if mobj: # start of a new flag if flag: # save last flag modlist.append(flag) logging.debug('Flag: %s' % line) flag = Flag(mobj.group(1), mobj.group(2)) continue # append to flag help. type and default are part of the main text if flag: flag.help += ' ' + line.strip() else: logging.info('Extra: %s' % line) if flag: modlist.append(flag) def Filter(self): """Filter parsed data to create derived fields.""" if not self.desc: self.short_desc = '' return for i in range(len(self.desc)): # replace full path with name if self.desc[i].find(self.executable) >= 0: self.desc[i] = self.desc[i].replace(self.executable, self.name) self.short_desc = self.desc[0] word_list = self.short_desc.split(' ') all_names = [ self.name, self.short_name, ] # Since the short_desc is always listed right after the name, # trim it from the short_desc while word_list and (word_list[0] in all_names or word_list[0].lower() in all_names): del word_list[0] self.short_desc = '' # signal need to reconstruct if not self.short_desc and word_list: self.short_desc = ' '.join(word_list) class GenerateDoc(object): """Base class to output flags information.""" def __init__(self, proginfo, directory='.'): """Create base object. Args: proginfo A ProgramInfo object directory Directory to write output into """ self.info = proginfo self.dirname = directory def Output(self): """Output all sections of the page.""" self.Open() self.Header() self.Body() self.Footer() def Open(self): raise NotImplementedError # define in subclass def Header(self): raise NotImplementedError # define in subclass def Body(self): raise NotImplementedError # define in subclass def Footer(self): raise NotImplementedError # define in subclass class GenerateMan(GenerateDoc): """Output a man page.""" def __init__(self, proginfo, directory='.'): """Create base object. Args: proginfo A ProgramInfo object directory Directory to write output into """ GenerateDoc.__init__(self, proginfo, directory) def Open(self): if self.dirname == '-': logging.info('Writing to stdout') self.fp = sys.stdout else: self.file_path = '%s.1' % os.path.join(self.dirname, self.info.name) logging.info('Writing: %s' % self.file_path) self.fp = open(self.file_path, 'w') def Header(self): self.fp.write( '.\\" DO NOT MODIFY THIS FILE! It was generated by gflags2man %s\n' % _VERSION) self.fp.write( '.TH %s "1" "%s" "%s" "User Commands"\n' % (self.info.name, time.strftime('%x', self.info.date), self.info.name)) self.fp.write( '.SH NAME\n%s \\- %s\n' % (self.info.name, self.info.short_desc)) self.fp.write( '.SH SYNOPSIS\n.B %s\n[\\fIFLAGS\\fR]...\n' % self.info.name) def Body(self): self.fp.write( '.SH DESCRIPTION\n.\\" Add any additional description here\n.PP\n') for ln in self.info.desc: self.fp.write('%s\n' % ln) self.fp.write( '.SH OPTIONS\n') # This shows flags in the original order for modname in self.info.module_list: if modname.find(self.info.executable) >= 0: mod = modname.replace(self.info.executable, self.info.name) else: mod = modname self.fp.write('\n.P\n.I %s\n' % mod) for flag in self.info.modules[modname]: help_string = flag.help if flag.default or flag.tips: help_string += '\n.br\n' if flag.default: help_string += ' (default: \'%s\')' % flag.default if flag.tips: help_string += ' (%s)' % flag.tips self.fp.write( '.TP\n%s\n%s\n' % (flag.desc, help_string)) def Footer(self): self.fp.write( '.SH COPYRIGHT\nCopyright \(co %s Google.\n' % time.strftime('%Y', self.info.date)) self.fp.write('Gflags2man created this page from "%s %s" output.\n' % (self.info.name, FLAGS.help_flag)) self.fp.write('\nGflags2man was written by Dan Christian. ' ' Note that the date on this' ' page is the modification date of %s.\n' % self.info.name) def main(argv): argv = FLAGS(argv) # handles help as well if len(argv) <= 1: app.usage(shorthelp=1) return 1 for arg in argv[1:]: prog = ProgramInfo(arg) if not prog.Run(): continue prog.Parse() prog.Filter() doc = GenerateMan(prog, FLAGS.dest_dir) doc.Output() return 0 if __name__ == '__main__': app.run()
bsd-3-clause
ckishimo/napalm-junos
test/unit/TestJunOSDriver.py
4
5191
# -*- coding: utf-8 -*- # Copyright 2015 Spotify AB. All rights reserved. # # The contents of this file are licensed under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with the # License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations under # the License. import unittest from napalm_junos.junos import JunOSDriver from napalm_base.test.base import TestConfigNetworkDriver, TestGettersNetworkDriver import lxml class TestConfigJunOSDriver(unittest.TestCase, TestConfigNetworkDriver): @classmethod def setUpClass(cls): hostname = '127.0.0.1' username = 'vagrant' password = 'vagrant123' cls.vendor = 'junos' optional_args = {'port': 12203, } cls.device = JunOSDriver(hostname, username, password, timeout=60, optional_args=optional_args) cls.device.open() class TestGetterJunOSDriver(unittest.TestCase, TestGettersNetworkDriver): @classmethod def setUpClass(cls): cls.mock = True hostname = '192.168.56.203' username = 'vagrant' password = 'vagrant123' cls.vendor = 'junos' cls.device = JunOSDriver(hostname, username, password, timeout=60) if cls.mock: cls.device.device = FakeJunOSDevice() else: cls.device.open() class FakeJunOSDevice: def __init__(self): self.rpc = FakeRPCObject(self) self._conn = FakeConnection(self.rpc) self.ON_JUNOS = True # necessary for fake devices self.facts = { 'domain': None, 'hostname': 'vsrx', 'ifd_style': 'CLASSIC', '2RE': False, 'serialnumber': 'beb914a9cca3', 'fqdn': 'vsrx', 'virtual': True, 'switch_style': 'NONE', 'version': '12.1X47-D20.7', 'HOME': '/cf/var/home/vagrant', 'srx_cluster': False, 'model': 'FIREFLY-PERIMETER', 'RE0': { 'status': 'Testing', 'last_reboot_reason': 'Router rebooted after a normal shutdown.', 'model': 'FIREFLY-PERIMETER RE', 'up_time': '1 hour, 13 minutes, 37 seconds' }, 'vc_capable': False, 'personality': 'SRX_BRANCH' } def read_txt_file(self, filename): with open(filename) as data_file: return data_file.read() def cli(self, command=''): return self.read_txt_file( 'junos/mock_data/{parsed_command}.txt'.format( parsed_command=command.replace(' ', '_') ) ) class FakeRPCObject: """ Fake RPC caller. """ def __init__(self, device): self._device = device def __getattr__(self, item): self.item = item return self def response(self, **rpc_args): instance = rpc_args.pop('instance', '') xml_string = self._device.read_txt_file( 'junos/mock_data/{}{}.txt'.format(self.item, instance)) return lxml.etree.fromstring(xml_string) def get_config(self, get_cmd=None, filter_xml=None, options={}): # get_cmd is an XML tree that requests a specific part of the config # E.g.: <configuration><protocols><bgp><group/></bgp></protocols></configuration> if get_cmd is not None: get_cmd_str = lxml.etree.tostring(get_cmd) filename = get_cmd_str.replace('<', '_')\ .replace('>', '_')\ .replace('/', '_')\ .replace('\n', '')\ .replace(' ', '') # no get_cmd means it should mock the eznc get_config else: filename = 'get_config__' + '__'.join( ['{0}_{1}'.format(k, v) for k, v in sorted(options.items())] ) xml_string = self._device.read_txt_file( 'junos/mock_data/{filename}.txt'.format( filename=filename[0:150] ) ) return lxml.etree.fromstring(xml_string) __call__ = response class FakeConnectionRPCObject: """ Will make fake RPC requests that usually are directly made via netconf. """ def __init__(self, rpc): self._rpc = rpc def response(self, non_std_command=None): class RPCReply: def __init__(self, reply): self._NCElement__doc = reply rpc_reply = RPCReply(self._rpc.get_config(get_cmd=non_std_command)) return rpc_reply __call__ = response class FakeConnection: def __init__(self, rpc): self.rpc = FakeConnectionRPCObject(rpc)
apache-2.0
UCSD-AUVSI/Heimdall
Recognition/ColorClassifier/PythonColorClassifier/ColorClassifier/Python/main.py
1
3405
import cv2 import math import numpy as np import pickle import sys import os import platform def getColor(color, testCode): print "starting Get Color" try: PATH = "Recognition/ColorClassifier/PythonColorClassifier/ColorClassifier/Python/" color_db=pickle.load(open(PATH+"color_db.p","rb")) except : print "Exception "+ str(sys.exc_info()[0]) raise BaseException cielab_output = [] name = [] check=[] for dictionary in color_db: cielab=dictionary["lab"] cielab_output.append(cielab) #add name to names array name.append(dictionary["name"]) check.append({"cielab":cielab,"name":dictionary["name"]}) #put cielab data into matrix trainData=np.matrix(cielab_output, dtype=np.float32) #put names which are numbers right now into a matrix responses = np.matrix(name, dtype=np.float32) #turn test point into matrix newcomer=np.matrix(color, dtype=np.float32) knn = cv2.KNearest() # train the data knn.train(trainData,responses) # find nearest ret, results, neighbours ,dist = knn.find_nearest(newcomer, 3) output = "" #get results if testCode == 1 or testCode == 2: print "result: ", results,"\n" print "neighbours: ", neighbours,"\n" print "distance: ", dist for name,val in COLOR_TO_NUMBER.iteritems(): if val==int(results[0][0]): output = name if testCode == 2: print output #Check Answer blank_image=np.zeros((100,100,3),np.uint8) blank_image[:]=newcomer blank_image = cv2.cvtColor(blank_image,cv2.COLOR_LAB2BGR) cv2.imshow("test",blank_image) cv2.waitKey(0) print "Color: "+output print "" return output COLOR_TO_NUMBER = {"White":1,"Black":2,"Red":3,"Orange":4,"Yellow":5,"Blue":6,"Green":7,"Purple":8,"Pink":9,"Brown":10,"Grey":11,"Teal":12} def bgr_to_lab(bgr): #create blank image 1x1 pixel blank_image=np.zeros((1,1,3),np.uint8) #set image pixels to bgr input blank_image[:]= bgr #turn into LAB try: cielab = cv2.cvtColor(blank_image,cv2.COLOR_BGR2LAB) except : print "Exception "+ str(sys.exc_info()[0]) raise BaseException return cielab[0][0] def lab_to_bgr(lab): #create blank image 1x1 pixel blank_image=np.zeros((1,1,3),np.uint8) #set image pixels to bgr input blank_image[:]= lab #turn into LAB bgr = cv2.cvtColor(blank_image,cv2.COLOR_LAB2BGR) return bgr[0][0] def rgb_to_bgr(rgb): return tuple(reversed(rgb)) def doColorClassification(givenSColor, givenCColor, optionalArgs): print "Python Color Classification (this is the Python)\n" #print sys.version #print platform.python_version() #print cv2.__version__ #print [method for method in dir(cv2) if callable(getattr(cv2, method))] print givenSColor if len(givenSColor) != 3: print "WARNING: SColor wasn't a 3-element list!!!" if len(givenCColor) != 3: print "WARNING: CColor wasn't a 3-element list!!!" bgrS = rgb_to_bgr(givenSColor) bgrC = rgb_to_bgr(givenCColor) labS = bgr_to_lab(bgrS) labC = bgr_to_lab(bgrC) print "----------------------------------------" print "RGB SColor: "+str(givenSColor) print "BGR SColor: "+str(bgrS) print "Lab SColor: "+ str(labS) returnedSColor = getColor(labS, 0) print "----------------------------------------" print "RGB CColor: "+str(givenCColor) print "BGR SColor: "+str(bgrS) print "Lab CColor: "+ str(labC) returnedCColor = getColor(labC, 0) print "----------------------------------------" return (returnedSColor, returnedCColor) #doColorClassification([0,0,0],[0,0,0],1)
gpl-3.0
catroot/rethinkdb
external/gtest_1.7.0/test/gtest_xml_output_unittest.py
1815
14580
#!/usr/bin/env python # # Copyright 2006, Google Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following disclaimer # in the documentation and/or other materials provided with the # distribution. # * Neither the name of Google Inc. nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """Unit test for the gtest_xml_output module""" __author__ = 'eefacm@gmail.com (Sean Mcafee)' import datetime import errno import os import re import sys from xml.dom import minidom, Node import gtest_test_utils import gtest_xml_test_utils GTEST_FILTER_FLAG = '--gtest_filter' GTEST_LIST_TESTS_FLAG = '--gtest_list_tests' GTEST_OUTPUT_FLAG = "--gtest_output" GTEST_DEFAULT_OUTPUT_FILE = "test_detail.xml" GTEST_PROGRAM_NAME = "gtest_xml_output_unittest_" SUPPORTS_STACK_TRACES = False if SUPPORTS_STACK_TRACES: STACK_TRACE_TEMPLATE = '\nStack trace:\n*' else: STACK_TRACE_TEMPLATE = '' EXPECTED_NON_EMPTY_XML = """<?xml version="1.0" encoding="UTF-8"?> <testsuites tests="23" failures="4" disabled="2" errors="0" time="*" timestamp="*" name="AllTests" ad_hoc_property="42"> <testsuite name="SuccessfulTest" tests="1" failures="0" disabled="0" errors="0" time="*"> <testcase name="Succeeds" status="run" time="*" classname="SuccessfulTest"/> </testsuite> <testsuite name="FailedTest" tests="1" failures="1" disabled="0" errors="0" time="*"> <testcase name="Fails" status="run" time="*" classname="FailedTest"> <failure message="gtest_xml_output_unittest_.cc:*&#x0A;Value of: 2&#x0A;Expected: 1" type=""><![CDATA[gtest_xml_output_unittest_.cc:* Value of: 2 Expected: 1%(stack)s]]></failure> </testcase> </testsuite> <testsuite name="MixedResultTest" tests="3" failures="1" disabled="1" errors="0" time="*"> <testcase name="Succeeds" status="run" time="*" classname="MixedResultTest"/> <testcase name="Fails" status="run" time="*" classname="MixedResultTest"> <failure message="gtest_xml_output_unittest_.cc:*&#x0A;Value of: 2&#x0A;Expected: 1" type=""><![CDATA[gtest_xml_output_unittest_.cc:* Value of: 2 Expected: 1%(stack)s]]></failure> <failure message="gtest_xml_output_unittest_.cc:*&#x0A;Value of: 3&#x0A;Expected: 2" type=""><![CDATA[gtest_xml_output_unittest_.cc:* Value of: 3 Expected: 2%(stack)s]]></failure> </testcase> <testcase name="DISABLED_test" status="notrun" time="*" classname="MixedResultTest"/> </testsuite> <testsuite name="XmlQuotingTest" tests="1" failures="1" disabled="0" errors="0" time="*"> <testcase name="OutputsCData" status="run" time="*" classname="XmlQuotingTest"> <failure message="gtest_xml_output_unittest_.cc:*&#x0A;Failed&#x0A;XML output: &lt;?xml encoding=&quot;utf-8&quot;&gt;&lt;top&gt;&lt;![CDATA[cdata text]]&gt;&lt;/top&gt;" type=""><![CDATA[gtest_xml_output_unittest_.cc:* Failed XML output: <?xml encoding="utf-8"><top><![CDATA[cdata text]]>]]&gt;<![CDATA[</top>%(stack)s]]></failure> </testcase> </testsuite> <testsuite name="InvalidCharactersTest" tests="1" failures="1" disabled="0" errors="0" time="*"> <testcase name="InvalidCharactersInMessage" status="run" time="*" classname="InvalidCharactersTest"> <failure message="gtest_xml_output_unittest_.cc:*&#x0A;Failed&#x0A;Invalid characters in brackets []" type=""><![CDATA[gtest_xml_output_unittest_.cc:* Failed Invalid characters in brackets []%(stack)s]]></failure> </testcase> </testsuite> <testsuite name="DisabledTest" tests="1" failures="0" disabled="1" errors="0" time="*"> <testcase name="DISABLED_test_not_run" status="notrun" time="*" classname="DisabledTest"/> </testsuite> <testsuite name="PropertyRecordingTest" tests="4" failures="0" disabled="0" errors="0" time="*" SetUpTestCase="yes" TearDownTestCase="aye"> <testcase name="OneProperty" status="run" time="*" classname="PropertyRecordingTest" key_1="1"/> <testcase name="IntValuedProperty" status="run" time="*" classname="PropertyRecordingTest" key_int="1"/> <testcase name="ThreeProperties" status="run" time="*" classname="PropertyRecordingTest" key_1="1" key_2="2" key_3="3"/> <testcase name="TwoValuesForOneKeyUsesLastValue" status="run" time="*" classname="PropertyRecordingTest" key_1="2"/> </testsuite> <testsuite name="NoFixtureTest" tests="3" failures="0" disabled="0" errors="0" time="*"> <testcase name="RecordProperty" status="run" time="*" classname="NoFixtureTest" key="1"/> <testcase name="ExternalUtilityThatCallsRecordIntValuedProperty" status="run" time="*" classname="NoFixtureTest" key_for_utility_int="1"/> <testcase name="ExternalUtilityThatCallsRecordStringValuedProperty" status="run" time="*" classname="NoFixtureTest" key_for_utility_string="1"/> </testsuite> <testsuite name="Single/ValueParamTest" tests="4" failures="0" disabled="0" errors="0" time="*"> <testcase name="HasValueParamAttribute/0" value_param="33" status="run" time="*" classname="Single/ValueParamTest" /> <testcase name="HasValueParamAttribute/1" value_param="42" status="run" time="*" classname="Single/ValueParamTest" /> <testcase name="AnotherTestThatHasValueParamAttribute/0" value_param="33" status="run" time="*" classname="Single/ValueParamTest" /> <testcase name="AnotherTestThatHasValueParamAttribute/1" value_param="42" status="run" time="*" classname="Single/ValueParamTest" /> </testsuite> <testsuite name="TypedTest/0" tests="1" failures="0" disabled="0" errors="0" time="*"> <testcase name="HasTypeParamAttribute" type_param="*" status="run" time="*" classname="TypedTest/0" /> </testsuite> <testsuite name="TypedTest/1" tests="1" failures="0" disabled="0" errors="0" time="*"> <testcase name="HasTypeParamAttribute" type_param="*" status="run" time="*" classname="TypedTest/1" /> </testsuite> <testsuite name="Single/TypeParameterizedTestCase/0" tests="1" failures="0" disabled="0" errors="0" time="*"> <testcase name="HasTypeParamAttribute" type_param="*" status="run" time="*" classname="Single/TypeParameterizedTestCase/0" /> </testsuite> <testsuite name="Single/TypeParameterizedTestCase/1" tests="1" failures="0" disabled="0" errors="0" time="*"> <testcase name="HasTypeParamAttribute" type_param="*" status="run" time="*" classname="Single/TypeParameterizedTestCase/1" /> </testsuite> </testsuites>""" % {'stack': STACK_TRACE_TEMPLATE} EXPECTED_FILTERED_TEST_XML = """<?xml version="1.0" encoding="UTF-8"?> <testsuites tests="1" failures="0" disabled="0" errors="0" time="*" timestamp="*" name="AllTests" ad_hoc_property="42"> <testsuite name="SuccessfulTest" tests="1" failures="0" disabled="0" errors="0" time="*"> <testcase name="Succeeds" status="run" time="*" classname="SuccessfulTest"/> </testsuite> </testsuites>""" EXPECTED_EMPTY_XML = """<?xml version="1.0" encoding="UTF-8"?> <testsuites tests="0" failures="0" disabled="0" errors="0" time="*" timestamp="*" name="AllTests"> </testsuites>""" GTEST_PROGRAM_PATH = gtest_test_utils.GetTestExecutablePath(GTEST_PROGRAM_NAME) SUPPORTS_TYPED_TESTS = 'TypedTest' in gtest_test_utils.Subprocess( [GTEST_PROGRAM_PATH, GTEST_LIST_TESTS_FLAG], capture_stderr=False).output class GTestXMLOutputUnitTest(gtest_xml_test_utils.GTestXMLTestCase): """ Unit test for Google Test's XML output functionality. """ # This test currently breaks on platforms that do not support typed and # type-parameterized tests, so we don't run it under them. if SUPPORTS_TYPED_TESTS: def testNonEmptyXmlOutput(self): """ Runs a test program that generates a non-empty XML output, and tests that the XML output is expected. """ self._TestXmlOutput(GTEST_PROGRAM_NAME, EXPECTED_NON_EMPTY_XML, 1) def testEmptyXmlOutput(self): """Verifies XML output for a Google Test binary without actual tests. Runs a test program that generates an empty XML output, and tests that the XML output is expected. """ self._TestXmlOutput('gtest_no_test_unittest', EXPECTED_EMPTY_XML, 0) def testTimestampValue(self): """Checks whether the timestamp attribute in the XML output is valid. Runs a test program that generates an empty XML output, and checks if the timestamp attribute in the testsuites tag is valid. """ actual = self._GetXmlOutput('gtest_no_test_unittest', [], 0) date_time_str = actual.documentElement.getAttributeNode('timestamp').value # datetime.strptime() is only available in Python 2.5+ so we have to # parse the expected datetime manually. match = re.match(r'(\d+)-(\d\d)-(\d\d)T(\d\d):(\d\d):(\d\d)', date_time_str) self.assertTrue( re.match, 'XML datettime string %s has incorrect format' % date_time_str) date_time_from_xml = datetime.datetime( year=int(match.group(1)), month=int(match.group(2)), day=int(match.group(3)), hour=int(match.group(4)), minute=int(match.group(5)), second=int(match.group(6))) time_delta = abs(datetime.datetime.now() - date_time_from_xml) # timestamp value should be near the current local time self.assertTrue(time_delta < datetime.timedelta(seconds=600), 'time_delta is %s' % time_delta) actual.unlink() def testDefaultOutputFile(self): """ Confirms that Google Test produces an XML output file with the expected default name if no name is explicitly specified. """ output_file = os.path.join(gtest_test_utils.GetTempDir(), GTEST_DEFAULT_OUTPUT_FILE) gtest_prog_path = gtest_test_utils.GetTestExecutablePath( 'gtest_no_test_unittest') try: os.remove(output_file) except OSError, e: if e.errno != errno.ENOENT: raise p = gtest_test_utils.Subprocess( [gtest_prog_path, '%s=xml' % GTEST_OUTPUT_FLAG], working_dir=gtest_test_utils.GetTempDir()) self.assert_(p.exited) self.assertEquals(0, p.exit_code) self.assert_(os.path.isfile(output_file)) def testSuppressedXmlOutput(self): """ Tests that no XML file is generated if the default XML listener is shut down before RUN_ALL_TESTS is invoked. """ xml_path = os.path.join(gtest_test_utils.GetTempDir(), GTEST_PROGRAM_NAME + 'out.xml') if os.path.isfile(xml_path): os.remove(xml_path) command = [GTEST_PROGRAM_PATH, '%s=xml:%s' % (GTEST_OUTPUT_FLAG, xml_path), '--shut_down_xml'] p = gtest_test_utils.Subprocess(command) if p.terminated_by_signal: # p.signal is avalable only if p.terminated_by_signal is True. self.assertFalse( p.terminated_by_signal, '%s was killed by signal %d' % (GTEST_PROGRAM_NAME, p.signal)) else: self.assert_(p.exited) self.assertEquals(1, p.exit_code, "'%s' exited with code %s, which doesn't match " 'the expected exit code %s.' % (command, p.exit_code, 1)) self.assert_(not os.path.isfile(xml_path)) def testFilteredTestXmlOutput(self): """Verifies XML output when a filter is applied. Runs a test program that executes only some tests and verifies that non-selected tests do not show up in the XML output. """ self._TestXmlOutput(GTEST_PROGRAM_NAME, EXPECTED_FILTERED_TEST_XML, 0, extra_args=['%s=SuccessfulTest.*' % GTEST_FILTER_FLAG]) def _GetXmlOutput(self, gtest_prog_name, extra_args, expected_exit_code): """ Returns the xml output generated by running the program gtest_prog_name. Furthermore, the program's exit code must be expected_exit_code. """ xml_path = os.path.join(gtest_test_utils.GetTempDir(), gtest_prog_name + 'out.xml') gtest_prog_path = gtest_test_utils.GetTestExecutablePath(gtest_prog_name) command = ([gtest_prog_path, '%s=xml:%s' % (GTEST_OUTPUT_FLAG, xml_path)] + extra_args) p = gtest_test_utils.Subprocess(command) if p.terminated_by_signal: self.assert_(False, '%s was killed by signal %d' % (gtest_prog_name, p.signal)) else: self.assert_(p.exited) self.assertEquals(expected_exit_code, p.exit_code, "'%s' exited with code %s, which doesn't match " 'the expected exit code %s.' % (command, p.exit_code, expected_exit_code)) actual = minidom.parse(xml_path) return actual def _TestXmlOutput(self, gtest_prog_name, expected_xml, expected_exit_code, extra_args=None): """ Asserts that the XML document generated by running the program gtest_prog_name matches expected_xml, a string containing another XML document. Furthermore, the program's exit code must be expected_exit_code. """ actual = self._GetXmlOutput(gtest_prog_name, extra_args or [], expected_exit_code) expected = minidom.parseString(expected_xml) self.NormalizeXml(actual.documentElement) self.AssertEquivalentNodes(expected.documentElement, actual.documentElement) expected.unlink() actual.unlink() if __name__ == '__main__': os.environ['GTEST_STACK_TRACE_DEPTH'] = '1' gtest_test_utils.Main()
agpl-3.0
Antiun/bank-statement-reconcile
account_statement_base_import/__openerp__.py
14
3018
# -*- coding: utf-8 -*- ############################################################################## # # Author: Joel Grand-Guillaume # Copyright 2011-2012 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/>. # ############################################################################## {'name': "Bank statement base import", 'version': '1.2', 'author': "Camptocamp,Odoo Community Association (OCA)", 'maintainer': 'Camptocamp', 'category': 'Finance', 'complexity': 'normal', 'depends': [ 'account_statement_ext', 'account_statement_base_completion' ], 'description': """ This module brings basic methods and fields on bank statement to deal with the importation of different bank and offices. A generic abstract method is defined and an example that gives you a basic way of importing bank statement through a standard file is provided. This module improves the bank statement and allows you to import your bank transactions with a standard .csv or .xls file (you'll find it in the 'data' folder). It respects the profile (provided by the accouhnt_statement_ext module) to pass the entries. That means, you'll have to choose a file format for each profile. In order to achieve this it uses the `xlrd` Python module which you will need to install separately in your environment. This module can handle a commission taken by the payment office and has the following format: * __ref__: the SO number, INV number or any matching ref found. It'll be used as reference in the generated entries and will be useful for reconciliation process * __date__: date of the payment * __amount__: amount paid in the currency of the journal used in the importation profile * __label__: the comunication given by the payment office, used as communication in the generated entries. The goal is here to populate the statement lines of a bank statement with the infos that the bank or office give you. Fell free to inherit from this module to add your own format. Then, if you need to complete data from there, add your own account_statement_*_completion module and implement the needed rules. """, 'website': 'http://www.camptocamp.com', 'data': [ "wizard/import_statement_view.xml", "statement_view.xml", ], 'test': [], 'installable': False, 'images': [], 'auto_install': False, 'license': 'AGPL-3', }
agpl-3.0
p0psicles/SickRage
lib/feedparser/__init__.py
41
2011
# Copyright 2010-2015 Kurt McKee <contactme@kurtmckee.org> # Copyright 2002-2008 Mark Pilgrim # All rights reserved. # # This file is part of feedparser. # # Redistribution and use in source and binary forms, with or without modification, # are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, # this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 'AS IS' # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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.""" from __future__ import absolute_import, unicode_literals __author__ = 'Kurt McKee <contactme@kurtmckee.org>' __license__ = 'BSD 2-clause' __version__ = '5.2.1' # HTTP "User-Agent" header to send to servers when downloading feeds. # If you are embedding feedparser in a larger application, you should # change this to your application name and URL. USER_AGENT = "feedparser/%s +https://github.com/kurtmckee/feedparser/" % __version__ from . import api from .api import parse from .datetimes import registerDateHandler from .exceptions import * api.USER_AGENT = USER_AGENT
gpl-3.0
ewmoore/numpy
setup.py
1
7204
#!/usr/bin/env python """NumPy: array processing for numbers, strings, records, and objects. NumPy is a general-purpose array-processing package designed to efficiently manipulate large multi-dimensional arrays of arbitrary records without sacrificing too much speed for small multi-dimensional arrays. NumPy is built on the Numeric code base and adds features introduced by numarray as well as an extended C-API and the ability to create arrays of arbitrary type which also makes NumPy suitable for interfacing with general-purpose data-base applications. There are also basic facilities for discrete fourier transform, basic linear algebra and random number generation. """ DOCLINES = __doc__.split("\n") import os import shutil import sys import re import subprocess if sys.version_info[0] < 3: import __builtin__ as builtins else: import builtins CLASSIFIERS = """\ Development Status :: 5 - Production/Stable Intended Audience :: Science/Research Intended Audience :: Developers License :: OSI Approved Programming Language :: C Programming Language :: Python Programming Language :: Python :: 3 Topic :: Software Development Topic :: Scientific/Engineering Operating System :: Microsoft :: Windows Operating System :: POSIX Operating System :: Unix Operating System :: MacOS """ NAME = 'numpy' MAINTAINER = "NumPy Developers" MAINTAINER_EMAIL = "numpy-discussion@scipy.org" DESCRIPTION = DOCLINES[0] LONG_DESCRIPTION = "\n".join(DOCLINES[2:]) URL = "http://www.numpy.org" DOWNLOAD_URL = "http://sourceforge.net/projects/numpy/files/NumPy/" LICENSE = 'BSD' CLASSIFIERS = filter(None, CLASSIFIERS.split('\n')) AUTHOR = "Travis E. Oliphant et al." AUTHOR_EMAIL = "oliphant@enthought.com" PLATFORMS = ["Windows", "Linux", "Solaris", "Mac OS-X", "Unix"] MAJOR = 1 MINOR = 8 MICRO = 0 ISRELEASED = False VERSION = '%d.%d.%d' % (MAJOR, MINOR, MICRO) # Return the git revision as a string def git_version(): def _minimal_ext_cmd(cmd): # construct minimal environment env = {} for k in ['SYSTEMROOT', 'PATH']: v = os.environ.get(k) if v is not None: env[k] = v # LANGUAGE is used on win32 env['LANGUAGE'] = 'C' env['LANG'] = 'C' env['LC_ALL'] = 'C' out = subprocess.Popen(cmd, stdout = subprocess.PIPE, env=env).communicate()[0] return out try: out = _minimal_ext_cmd(['git', 'rev-parse', 'HEAD']) GIT_REVISION = out.strip().decode('ascii') except OSError: GIT_REVISION = "Unknown" return GIT_REVISION # BEFORE importing distutils, remove MANIFEST. distutils doesn't properly # update it when the contents of directories change. if os.path.exists('MANIFEST'): os.remove('MANIFEST') # This is a bit hackish: we are setting a global variable so that the main # numpy __init__ can detect if it is being loaded by the setup routine, to # avoid attempting to load components that aren't built yet. While ugly, it's # a lot more robust than what was previously being used. builtins.__NUMPY_SETUP__ = True def write_version_py(filename='numpy/version.py'): cnt = """ # THIS FILE IS GENERATED FROM NUMPY SETUP.PY short_version = '%(version)s' version = '%(version)s' full_version = '%(full_version)s' git_revision = '%(git_revision)s' release = %(isrelease)s if not release: version = full_version """ # Adding the git rev number needs to be done inside write_version_py(), # otherwise the import of numpy.version messes up the build under Python 3. FULLVERSION = VERSION if os.path.exists('.git'): GIT_REVISION = git_version() elif os.path.exists('numpy/version.py'): # must be a source distribution, use existing version file try: from numpy.version import git_revision as GIT_REVISION except ImportError: raise ImportError("Unable to import git_revision. Try removing " \ "numpy/version.py and the build directory " \ "before building.") else: GIT_REVISION = "Unknown" if not ISRELEASED: FULLVERSION += '.dev-' + GIT_REVISION[:7] a = open(filename, 'w') try: a.write(cnt % {'version': VERSION, 'full_version' : FULLVERSION, 'git_revision' : GIT_REVISION, 'isrelease': str(ISRELEASED)}) finally: a.close() def configuration(parent_package='',top_path=None): from numpy.distutils.misc_util import Configuration config = Configuration(None, parent_package, top_path) config.set_options(ignore_setup_xxx_py=True, assume_default_configuration=True, delegate_options_to_subpackages=True, quiet=True) config.add_subpackage('numpy') config.get_version('numpy/version.py') # sets config.version return config def setup_package(): # Perform 2to3 if needed local_path = os.path.dirname(os.path.abspath(sys.argv[0])) src_path = local_path if sys.version_info[0] == 3: src_path = os.path.join(local_path, 'build', 'py3k') sys.path.insert(0, os.path.join(local_path, 'tools')) import py3tool print("Converting to Python3 via 2to3...") py3tool.sync_2to3('numpy', os.path.join(src_path, 'numpy')) site_cfg = os.path.join(local_path, 'site.cfg') if os.path.isfile(site_cfg): shutil.copy(site_cfg, src_path) # Ugly hack to make pip work with Python 3, see #1857. # Explanation: pip messes with __file__ which interacts badly with the # change in directory due to the 2to3 conversion. Therefore we restore # __file__ to what it would have been otherwise. global __file__ __file__ = os.path.join(os.curdir, os.path.basename(__file__)) if '--egg-base' in sys.argv: # Change pip-egg-info entry to absolute path, so pip can find it # after changing directory. idx = sys.argv.index('--egg-base') if sys.argv[idx + 1] == 'pip-egg-info': sys.argv[idx + 1] = os.path.join(local_path, 'pip-egg-info') old_path = os.getcwd() os.chdir(src_path) sys.path.insert(0, src_path) # Rewrite the version file everytime write_version_py() # Run build from numpy.distutils.core import setup try: setup( name=NAME, maintainer=MAINTAINER, maintainer_email=MAINTAINER_EMAIL, description=DESCRIPTION, long_description=LONG_DESCRIPTION, url=URL, download_url=DOWNLOAD_URL, license=LICENSE, classifiers=CLASSIFIERS, author=AUTHOR, author_email=AUTHOR_EMAIL, platforms=PLATFORMS, configuration=configuration ) finally: del sys.path[0] os.chdir(old_path) return if __name__ == '__main__': setup_package()
bsd-3-clause
ovilab/lammps
tools/i-pi/ipi/tests/test_io.py
41
3225
"""Deals with testing the io system. Copyright (C) 2013, Joshua More and Michele Ceriotti 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/>. Note that this will only run if you have Python version 2.5 or later. Otherwise, replace all the with statements with f = filestream. """ import sys sys.path.append("../") sys.path.append("../../") import filecmp import os, sys import numpy as np from numpy.testing import assert_equal from common import local from ipi.engine.cell import Cell from ipi.utils.io import io_xyz from ipi.utils.io import io_pdb pos = np.array([i for i in range(3*3)]) def test_read_xyz(): """Tests that xyz files are read correctly.""" with open(local("test.pos_0.xyz"), "r") as f: atoms = io_xyz.read_xyz(f) assert(len(atoms) == 3) assert_equal(pos, atoms.q) def test_iter_xyz(): """Tests that xyz files with multiple frames are read correctly.""" with open(local("test.pos_0.xyz"), "r") as f: for num, atoms in enumerate(io_xyz.iter_xyz(f)): assert(len(atoms) == 3) assert_equal(pos*(num+1), atoms.q) def test_read_pdb(): """Tests that pdb files are read correctly.""" with open(local("test.pos_0.pdb"), "r") as f: atoms, cell = io_pdb.read_pdb(f) assert(len(atoms) == 3) assert_equal(pos, atoms.q) # TODO: test cell def test_iter_pdb(): """Tests that pdb files with multiple frames are read correctly.""" with open(local("test.pos_0.pdb"), "r") as f: for num, (atoms, cell) in enumerate(io_pdb.iter_pdb(f)): assert(len(atoms) == 3) assert_equal(pos*(num+1), atoms.q) def test_print_pdb(): """Tests that pdb files are printed correctly.""" with open(local("test.pos_0.pdb"), "r") as f: with open(local("test.pos_1.xyz"), "w") as out: for num, (atoms, cell) in enumerate(io_pdb.iter_pdb(f)): assert(len(atoms) == 3) assert_equal(pos*(num+1), atoms.q) io_xyz.print_xyz(atoms, Cell(h=np.identity(3, float)), filedesc=out) assert(filecmp.cmp(local("test.pos_0.xyz"), local("test.pos_1.xyz"))) os.unlink(local("test.pos_1.xyz")) def test_print_xyz(): """Tests that xyz files are printed correctly.""" with open(local("test.pos_0.pdb"), "r") as f: with open(local("test.pos_1.pdb"), "w") as out: for num, (atoms, cell) in enumerate(io_pdb.iter_pdb(f)): assert(len(atoms) == 3) assert_equal(pos*(num+1), atoms.q) io_pdb.print_pdb(atoms, Cell(h=np.identity(3, float)), filedesc=out) assert(filecmp.cmp(local("test.pos_0.pdb"), local("test.pos_1.pdb"))) os.unlink(local("test.pos_1.pdb"))
gpl-2.0
Elettronik/SickRage
lib/lockfile/linklockfile.py
45
2650
from __future__ import absolute_import import time import os from . import (LockBase, LockFailed, NotLocked, NotMyLock, LockTimeout, AlreadyLocked) class LinkLockFile(LockBase): """Lock access to a file using atomic property of link(2). >>> lock = LinkLockFile('somefile') >>> lock = LinkLockFile('somefile', threaded=False) """ def acquire(self, timeout=None): try: open(self.unique_name, "wb").close() except IOError: raise LockFailed("failed to create %s" % self.unique_name) timeout = timeout if timeout is not None else self.timeout end_time = time.time() if timeout is not None and timeout > 0: end_time += timeout while True: # Try and create a hard link to it. try: os.link(self.unique_name, self.lock_file) except OSError: # Link creation failed. Maybe we've double-locked? nlinks = os.stat(self.unique_name).st_nlink if nlinks == 2: # The original link plus the one I created == 2. We're # good to go. return else: # Otherwise the lock creation failed. if timeout is not None and time.time() > end_time: os.unlink(self.unique_name) if timeout > 0: raise LockTimeout("Timeout waiting to acquire" " lock for %s" % self.path) else: raise AlreadyLocked("%s is already locked" % self.path) time.sleep(timeout is not None and timeout/10 or 0.1) else: # Link creation succeeded. We're good to go. return def release(self): if not self.is_locked(): raise NotLocked("%s is not locked" % self.path) elif not os.path.exists(self.unique_name): raise NotMyLock("%s is locked, but not by me" % self.path) os.unlink(self.unique_name) os.unlink(self.lock_file) def is_locked(self): return os.path.exists(self.lock_file) def i_am_locking(self): return (self.is_locked() and os.path.exists(self.unique_name) and os.stat(self.unique_name).st_nlink == 2) def break_lock(self): if os.path.exists(self.lock_file): os.unlink(self.lock_file)
gpl-3.0
abhishek-ch/hue
desktop/core/ext-py/Django-1.6.10/django/utils/itercompat.py
113
1099
""" Providing iterator functions that are not in all version of Python we support. Where possible, we try to use the system-native version and only fall back to these implementations if necessary. """ import collections import itertools import sys import warnings def is_iterable(x): "A implementation independent way of checking for iterables" try: iter(x) except TypeError: return False else: return True def is_iterator(x): """An implementation independent way of checking for iterators Python 2.6 has a different implementation of collections.Iterator which accepts anything with a `next` method. 2.7+ requires and `__iter__` method as well. """ if sys.version_info >= (2, 7): return isinstance(x, collections.Iterator) return isinstance(x, collections.Iterator) and hasattr(x, '__iter__') def product(*args, **kwds): warnings.warn("django.utils.itercompat.product is deprecated; use the native version instead", DeprecationWarning, stacklevel=2) return itertools.product(*args, **kwds)
apache-2.0
MuhammadVT/davitpy
davitpy/pydarn/dmapio/rst/setup.py
7
1146
# Copyright (C) 2012 VT SuperDARN Lab # Full license can be found in LICENSE.txt # # 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 distutils.core import setup, Extension import os dmap = Extension("dmapio",sources=["src/dmapio.c","src/rtime.c","src/dmap.c","src/convert.c"],include_dirs = ["src"]) setup (name = "rst", version = "1.0", description = "lib to read dmap files", author = "AJ Ribeiro based on pydmap lib by Jef Spaleta", author_email = "ribeiro@vt.edu", ext_modules = [dmap] )
gpl-3.0
tbjoern/adventofcode
One/script.py
1
1159
file = open("input.txt", "r") input = file.next() sequence = input.split(", ") class walker: def __init__(self): self.east = 0 self.south = 0 self.facing = 0 self.tiles = {} def turnL(self): if self.facing == 0: self.facing = 3 else: self.facing -= 1 def turnR(self): if self.facing == 3: self.facing = 0 else: self.facing += 1 def walk(self,dist): for i in range(0, dist): if self.facing == 0: self.south -= 1 elif self.facing == 1: self.east += 1 elif self.facing == 2: self.south += 1 else: self.east -= 1 if self.kek(): return True self.addTile(self.east,self.south) return False def totalDist(self): return abs(self.east) + abs(self.south) def addTile(self, x, y): if x in self.tiles: self.tiles[x].append(y) else: self.tiles[x] = [y] def kek(self): if self.east in self.tiles: if self.south in self.tiles[self.east]: return True return False w = walker() for s in sequence: if s[0] == "R": w.turnR() else: w.turnL() if w.walk(int(s[1:])): break print w.totalDist()
mit
lepistone/stock-logistics-workflow
__unported__/stock_move_backdating/stock.py
4
4008
# -*- coding: utf-8 -*- ############################################################################## # # Copyright (C) 2012 BREMSKERL-REIBBELAGWERKE EMMERLING GmbH & Co. KG # Author Marco Dieckhoff # Copyright (C) 2013 Agile Business Group sagl (<http://www.agilebg.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/>. # ############################################################################## from openerp.osv import fields, orm from datetime import datetime from openerp.tools.translate import _ from openerp.tools import DEFAULT_SERVER_DATETIME_FORMAT class stock_move(orm.Model): _name = "stock.move" _inherit = _name _columns = { 'date_backdating': fields.datetime( "Actual Movement Date", readonly=False, states={'done': [('readonly', True)], 'cancel': [('readonly', True)]}, help="Date when the move action was committed. " "Will set the move date to this date instead " "of current date when processing to done." ), } def action_done(self, cr, uid, ids, context=None): # look at previous state and find date_backdating backdating_dates = {} for move in self.browse(cr, uid, ids, context=context): # if not already in done and date is given if (move.state != 'done') and (move.date_backdating): backdating_dates[move.id] = move.date_backdating # do actual processing result = super(stock_move, self).action_done(cr, uid, ids, context) # overwrite date field where applicable for move in self.browse(cr, uid, backdating_dates.keys(), context=context): self.write(cr, uid, [move.id], {'date': backdating_dates[move.id]}, context=context) return result def on_change_date_backdating(self, cr, uid, ids, date_backdating, context=None): """ Test if date is in the past @param date_backdating: date """ # do nothing if empty if (not date_backdating): return {} dt = datetime.strptime(date_backdating, DEFAULT_SERVER_DATETIME_FORMAT) NOW = datetime.now() if (dt > NOW): warning = {'title': _('Error!'), 'message': _('You can not process an actual movement date in the future.')} values = {'date_backdating': NOW.strftime(DEFAULT_SERVER_DATETIME_FORMAT)} return {'warning': warning, 'value': values} # otherwise, ok return {} def _create_account_move_line(self, cr, uid, move, src_account_id, dest_account_id, reference_amount, reference_currency_id, context=None): if context is None: context = {} res = super(stock_move, self)._create_account_move_line( cr, uid, move, src_account_id, dest_account_id, reference_amount, reference_currency_id, context=context ) for o2m_tuple in res: date = False if move.date_backdating: date = move.date_backdating[:10] elif move.date: date = move.date[:10] o2m_tuple[2]['date'] = date if 'move_date' not in context: context['move_date'] = date return res
agpl-3.0
DonBeo/scikit-learn
sklearn/utils/tests/test_class_weight.py
14
6559
import numpy as np from sklearn.utils.class_weight import compute_class_weight from sklearn.utils.class_weight import compute_sample_weight from sklearn.utils.testing import assert_array_almost_equal from sklearn.utils.testing import assert_almost_equal from sklearn.utils.testing import assert_raises from sklearn.utils.testing import assert_true from sklearn.utils.testing import assert_equal def test_compute_class_weight(): # Test (and demo) compute_class_weight. y = np.asarray([2, 2, 2, 3, 3, 4]) classes = np.unique(y) cw = compute_class_weight("auto", classes, y) assert_almost_equal(cw.sum(), classes.shape) assert_true(cw[0] < cw[1] < cw[2]) def test_compute_class_weight_not_present(): # Raise error when y does not contain all class labels classes = np.arange(4) y = np.asarray([0, 0, 0, 1, 1, 2]) assert_raises(ValueError, compute_class_weight, "auto", classes, y) def test_compute_class_weight_auto_negative(): # Test compute_class_weight when labels are negative # Test with balanced class labels. classes = np.array([-2, -1, 0]) y = np.asarray([-1, -1, 0, 0, -2, -2]) cw = compute_class_weight("auto", classes, y) assert_almost_equal(cw.sum(), classes.shape) assert_equal(len(cw), len(classes)) assert_array_almost_equal(cw, np.array([1., 1., 1.])) # Test with unbalanced class labels. y = np.asarray([-1, 0, 0, -2, -2, -2]) cw = compute_class_weight("auto", classes, y) assert_almost_equal(cw.sum(), classes.shape) assert_equal(len(cw), len(classes)) assert_array_almost_equal(cw, np.array([0.545, 1.636, 0.818]), decimal=3) def test_compute_class_weight_auto_unordered(): # Test compute_class_weight when classes are unordered classes = np.array([1, 0, 3]) y = np.asarray([1, 0, 0, 3, 3, 3]) cw = compute_class_weight("auto", classes, y) assert_almost_equal(cw.sum(), classes.shape) assert_equal(len(cw), len(classes)) assert_array_almost_equal(cw, np.array([1.636, 0.818, 0.545]), decimal=3) def test_compute_sample_weight(): # Test (and demo) compute_sample_weight. # Test with balanced classes y = np.asarray([1, 1, 1, 2, 2, 2]) sample_weight = compute_sample_weight("auto", y) assert_array_almost_equal(sample_weight, [1., 1., 1., 1., 1., 1.]) # Test with user-defined weights sample_weight = compute_sample_weight({1: 2, 2: 1}, y) assert_array_almost_equal(sample_weight, [2., 2., 2., 1., 1., 1.]) # Test with column vector of balanced classes y = np.asarray([[1], [1], [1], [2], [2], [2]]) sample_weight = compute_sample_weight("auto", y) assert_array_almost_equal(sample_weight, [1., 1., 1., 1., 1., 1.]) # Test with unbalanced classes y = np.asarray([1, 1, 1, 2, 2, 2, 3]) sample_weight = compute_sample_weight("auto", y) expected = np.asarray([.6, .6, .6, .6, .6, .6, 1.8]) assert_array_almost_equal(sample_weight, expected) # Test with `None` weights sample_weight = compute_sample_weight(None, y) assert_array_almost_equal(sample_weight, [1., 1., 1., 1., 1., 1., 1.]) # Test with multi-output of balanced classes y = np.asarray([[1, 0], [1, 0], [1, 0], [2, 1], [2, 1], [2, 1]]) sample_weight = compute_sample_weight("auto", y) assert_array_almost_equal(sample_weight, [1., 1., 1., 1., 1., 1.]) # Test with multi-output with user-defined weights y = np.asarray([[1, 0], [1, 0], [1, 0], [2, 1], [2, 1], [2, 1]]) sample_weight = compute_sample_weight([{1: 2, 2: 1}, {0: 1, 1: 2}], y) assert_array_almost_equal(sample_weight, [2., 2., 2., 2., 2., 2.]) # Test with multi-output of unbalanced classes y = np.asarray([[1, 0], [1, 0], [1, 0], [2, 1], [2, 1], [2, 1], [3, -1]]) sample_weight = compute_sample_weight("auto", y) assert_array_almost_equal(sample_weight, expected ** 2) def test_compute_sample_weight_with_subsample(): # Test compute_sample_weight with subsamples specified. # Test with balanced classes and all samples present y = np.asarray([1, 1, 1, 2, 2, 2]) sample_weight = compute_sample_weight("auto", y, range(6)) assert_array_almost_equal(sample_weight, [1., 1., 1., 1., 1., 1.]) # Test with column vector of balanced classes and all samples present y = np.asarray([[1], [1], [1], [2], [2], [2]]) sample_weight = compute_sample_weight("auto", y, range(6)) assert_array_almost_equal(sample_weight, [1., 1., 1., 1., 1., 1.]) # Test with a subsample y = np.asarray([1, 1, 1, 2, 2, 2]) sample_weight = compute_sample_weight("auto", y, range(4)) assert_array_almost_equal(sample_weight, [.5, .5, .5, 1.5, 1.5, 1.5]) # Test with a bootstrap subsample y = np.asarray([1, 1, 1, 2, 2, 2]) sample_weight = compute_sample_weight("auto", y, [0, 1, 1, 2, 2, 3]) expected = np.asarray([1/3., 1/3., 1/3., 5/3., 5/3., 5/3.]) assert_array_almost_equal(sample_weight, expected) # Test with a bootstrap subsample for multi-output y = np.asarray([[1, 0], [1, 0], [1, 0], [2, 1], [2, 1], [2, 1]]) sample_weight = compute_sample_weight("auto", y, [0, 1, 1, 2, 2, 3]) assert_array_almost_equal(sample_weight, expected ** 2) # Test with a missing class y = np.asarray([1, 1, 1, 2, 2, 2, 3]) sample_weight = compute_sample_weight("auto", y, range(6)) assert_array_almost_equal(sample_weight, [1., 1., 1., 1., 1., 1., 0.]) # Test with a missing class for multi-output y = np.asarray([[1, 0], [1, 0], [1, 0], [2, 1], [2, 1], [2, 1], [2, 2]]) sample_weight = compute_sample_weight("auto", y, range(6)) assert_array_almost_equal(sample_weight, [1., 1., 1., 1., 1., 1., 0.]) def test_compute_sample_weight_errors(): # Test compute_sample_weight raises errors expected. # Invalid preset string y = np.asarray([1, 1, 1, 2, 2, 2]) y_ = np.asarray([[1, 0], [1, 0], [1, 0], [2, 1], [2, 1], [2, 1]]) assert_raises(ValueError, compute_sample_weight, "ni", y) assert_raises(ValueError, compute_sample_weight, "ni", y, range(4)) assert_raises(ValueError, compute_sample_weight, "ni", y_) assert_raises(ValueError, compute_sample_weight, "ni", y_, range(4)) # Not "auto" for subsample assert_raises(ValueError, compute_sample_weight, {1: 2, 2: 1}, y, range(4)) # Not a list or preset for multi-output assert_raises(ValueError, compute_sample_weight, {1: 2, 2: 1}, y_) # Incorrect length list for multi-output assert_raises(ValueError, compute_sample_weight, [{1: 2, 2: 1}], y_)
bsd-3-clause
neilh10/micropython
tools/make-frozen.py
34
1275
#!/usr/bin/env python # # Create frozen modules structure for MicroPython. # # Usage: # # Have a directory with modules to be frozen (only modules, not packages # supported so far): # # frozen/foo.py # frozen/bar.py # # Run script, passing path to the directory above: # # ./make-frozen.py frozen > frozen.c # # Include frozen.c in your build, having defined MICROPY_MODULE_FROZEN in # config. # from __future__ import print_function import sys import os def module_name(f): return f[:-len(".py")] modules = [] root = sys.argv[1].rstrip("/") root_len = len(root) for dirpath, dirnames, filenames in os.walk(root): for f in filenames: fullpath = dirpath + "/" + f st = os.stat(fullpath) modules.append((fullpath[root_len + 1:], st)) print("#include <stdint.h>") print("const uint16_t mp_frozen_sizes[] = {") for f, st in modules: print("%d," % st.st_size) print("0};") print("const char mp_frozen_content[] = {") for f, st in modules: m = module_name(f) print('"%s\\0"' % m) data = open(sys.argv[1] + "/" + f, "rb").read() # Python2 vs Python3 tricks data = repr(data) if data[0] == "b": data = data[1:] data = data[1:-1] data = data.replace('"', '\\"') print('"%s"' % data) print("};")
mit
CLVsol/odoo_addons
clv_seedling/batch_history/clv_seedling_batch_history.py
1
2387
# -*- encoding: utf-8 -*- ################################################################################ # # # Copyright (C) 2013-Today Carlos Eduardo Vercelino - CLVsol # # # # This program is free software: you can redistribute it and/or modify # # it under the terms of the GNU Affero General Public License as published by # # the Free Software Foundation, either version 3 of the License, or # # (at your option) any later version. # # # # This program is distributed in the hope that it will be useful, # # but WITHOUT ANY WARRANTY; without even the implied warranty of # # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # # GNU Affero General Public License for more details. # # # # You should have received a copy of the GNU Affero General Public License # # along with this program. If not, see <http://www.gnu.org/licenses/>. # ################################################################################ from openerp import models, fields, api from openerp.osv import osv from datetime import * class clv_seedling_batch_history(osv.Model): _name = 'clv_seedling.batch_history' seedling_id = fields.Many2one('clv_seedling', 'Seedling', required=False) batch_id = fields.Many2one('clv_batch', 'Batch', required=False) incoming_date = fields.Datetime('Incoming Date', required=False, default=lambda *a: datetime.now().strftime('%Y-%m-%d %H:%M:%S')) outgoing_date = fields.Datetime('Outgoing Date', required=False) notes = fields.Text(string='Notes') _order = "incoming_date desc" class clv_seedling(osv.Model): _inherit = 'clv_seedling' batch_history_ids = fields.One2many('clv_seedling.batch_history', 'seedling_id', 'Batch History') class clv_batch(osv.Model): _inherit = 'clv_batch' seedling_batch_history_ids = fields.One2many('clv_seedling.batch_history', 'batch_id', 'Seedling Batch History')
agpl-3.0
schmunk42/compose
compose/config/interpolation.py
3
3229
from __future__ import absolute_import from __future__ import unicode_literals import logging from string import Template import six from .errors import ConfigurationError from compose.const import COMPOSEFILE_V2_0 as V2_0 log = logging.getLogger(__name__) class Interpolator(object): def __init__(self, templater, mapping): self.templater = templater self.mapping = mapping def interpolate(self, string): try: return self.templater(string).substitute(self.mapping) except ValueError: raise InvalidInterpolation(string) def interpolate_environment_variables(version, config, section, environment): if version <= V2_0: interpolator = Interpolator(Template, environment) else: interpolator = Interpolator(TemplateWithDefaults, environment) def process_item(name, config_dict): return dict( (key, interpolate_value(name, key, val, section, interpolator)) for key, val in (config_dict or {}).items() ) return dict( (name, process_item(name, config_dict or {})) for name, config_dict in config.items() ) def interpolate_value(name, config_key, value, section, interpolator): try: return recursive_interpolate(value, interpolator) except InvalidInterpolation as e: raise ConfigurationError( 'Invalid interpolation format for "{config_key}" option ' 'in {section} "{name}": "{string}"'.format( config_key=config_key, name=name, section=section, string=e.string)) def recursive_interpolate(obj, interpolator): if isinstance(obj, six.string_types): return interpolator.interpolate(obj) if isinstance(obj, dict): return dict( (key, recursive_interpolate(val, interpolator)) for (key, val) in obj.items() ) if isinstance(obj, list): return [recursive_interpolate(val, interpolator) for val in obj] return obj class TemplateWithDefaults(Template): idpattern = r'[_a-z][_a-z0-9]*(?::?-[^}]+)?' # Modified from python2.7/string.py def substitute(self, mapping): # Helper function for .sub() def convert(mo): # Check the most common path first. named = mo.group('named') or mo.group('braced') if named is not None: if ':-' in named: var, _, default = named.partition(':-') return mapping.get(var) or default if '-' in named: var, _, default = named.partition('-') return mapping.get(var, default) val = mapping[named] return '%s' % (val,) if mo.group('escaped') is not None: return self.delimiter if mo.group('invalid') is not None: self._invalid(mo) raise ValueError('Unrecognized named group in pattern', self.pattern) return self.pattern.sub(convert, self.template) class InvalidInterpolation(Exception): def __init__(self, string): self.string = string
apache-2.0
boneyao/sentry
src/sentry/migrations/0146_auto__add_field_auditlogentry_ip_address.py
36
29197
# -*- coding: utf-8 -*- import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding field 'AuditLogEntry.ip_address' db.add_column('sentry_auditlogentry', 'ip_address', self.gf('django.db.models.fields.GenericIPAddressField')(max_length=39, null=True), keep_default=False) def backwards(self, orm): # Deleting field 'AuditLogEntry.ip_address' db.delete_column('sentry_auditlogentry', 'ip_address') models = { 'sentry.accessgroup': { 'Meta': {'unique_together': "(('team', 'name'),)", 'object_name': 'AccessGroup'}, 'data': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'date_added': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'id': ('sentry.db.models.fields.BoundedBigAutoField', [], {'primary_key': 'True'}), 'managed': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'members': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['sentry.User']", 'symmetrical': 'False'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '64'}), 'projects': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['sentry.Project']", 'symmetrical': 'False'}), 'team': ('sentry.db.models.fields.FlexibleForeignKey', [], {'to': "orm['sentry.Team']"}), 'type': ('django.db.models.fields.IntegerField', [], {'default': '50'}) }, 'sentry.activity': { 'Meta': {'object_name': 'Activity'}, 'data': ('django.db.models.fields.TextField', [], {'null': 'True'}), 'datetime': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'event': ('sentry.db.models.fields.FlexibleForeignKey', [], {'to': "orm['sentry.Event']", 'null': 'True'}), 'group': ('sentry.db.models.fields.FlexibleForeignKey', [], {'to': "orm['sentry.Group']", 'null': 'True'}), 'id': ('sentry.db.models.fields.BoundedBigAutoField', [], {'primary_key': 'True'}), 'ident': ('django.db.models.fields.CharField', [], {'max_length': '64', 'null': 'True'}), 'project': ('sentry.db.models.fields.FlexibleForeignKey', [], {'to': "orm['sentry.Project']"}), 'type': ('django.db.models.fields.PositiveIntegerField', [], {}), 'user': ('sentry.db.models.fields.FlexibleForeignKey', [], {'to': "orm['sentry.User']", 'null': 'True'}) }, 'sentry.alert': { 'Meta': {'object_name': 'Alert'}, 'data': ('django.db.models.fields.TextField', [], {'null': 'True'}), 'datetime': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'group': ('sentry.db.models.fields.FlexibleForeignKey', [], {'to': "orm['sentry.Group']", 'null': 'True'}), 'id': ('sentry.db.models.fields.BoundedBigAutoField', [], {'primary_key': 'True'}), 'message': ('django.db.models.fields.TextField', [], {}), 'project': ('sentry.db.models.fields.FlexibleForeignKey', [], {'to': "orm['sentry.Project']"}), 'related_groups': ('django.db.models.fields.related.ManyToManyField', [], {'related_name': "'related_alerts'", 'symmetrical': 'False', 'through': "orm['sentry.AlertRelatedGroup']", 'to': "orm['sentry.Group']"}), 'status': ('django.db.models.fields.PositiveIntegerField', [], {'default': '0', 'db_index': 'True'}) }, 'sentry.alertrelatedgroup': { 'Meta': {'unique_together': "(('group', 'alert'),)", 'object_name': 'AlertRelatedGroup'}, 'alert': ('sentry.db.models.fields.FlexibleForeignKey', [], {'to': "orm['sentry.Alert']"}), 'data': ('django.db.models.fields.TextField', [], {'null': 'True'}), 'group': ('sentry.db.models.fields.FlexibleForeignKey', [], {'to': "orm['sentry.Group']"}), 'id': ('sentry.db.models.fields.BoundedBigAutoField', [], {'primary_key': 'True'}) }, 'sentry.auditlogentry': { 'Meta': {'object_name': 'AuditLogEntry'}, 'actor': ('sentry.db.models.fields.FlexibleForeignKey', [], {'related_name': "'audit_actors'", 'to': "orm['sentry.User']"}), 'data': ('sentry.db.models.fields.gzippeddict.GzippedDictField', [], {}), 'datetime': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'event': ('django.db.models.fields.PositiveIntegerField', [], {}), 'id': ('sentry.db.models.fields.BoundedBigAutoField', [], {'primary_key': 'True'}), 'ip_address': ('django.db.models.fields.GenericIPAddressField', [], {'max_length': '39', 'null': 'True'}), 'organization': ('sentry.db.models.fields.FlexibleForeignKey', [], {'to': "orm['sentry.Organization']"}), 'target_object': ('django.db.models.fields.PositiveIntegerField', [], {'null': 'True'}), 'target_user': ('sentry.db.models.fields.FlexibleForeignKey', [], {'related_name': "'audit_targets'", 'null': 'True', 'to': "orm['sentry.User']"}) }, 'sentry.broadcast': { 'Meta': {'object_name': 'Broadcast'}, 'badge': ('django.db.models.fields.CharField', [], {'max_length': '32', 'null': 'True', 'blank': 'True'}), 'date_added': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'id': ('sentry.db.models.fields.BoundedBigAutoField', [], {'primary_key': 'True'}), 'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True', 'db_index': 'True'}), 'link': ('django.db.models.fields.URLField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'}), 'message': ('django.db.models.fields.CharField', [], {'max_length': '256'}) }, 'sentry.event': { 'Meta': {'unique_together': "(('project', 'event_id'),)", 'object_name': 'Event', 'db_table': "'sentry_message'", 'index_together': "(('group', 'datetime'),)"}, 'checksum': ('django.db.models.fields.CharField', [], {'max_length': '32', 'db_index': 'True'}), 'data': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'datetime': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'db_index': 'True'}), 'event_id': ('django.db.models.fields.CharField', [], {'max_length': '32', 'null': 'True', 'db_column': "'message_id'"}), 'group': ('sentry.db.models.fields.FlexibleForeignKey', [], {'blank': 'True', 'related_name': "'event_set'", 'null': 'True', 'to': "orm['sentry.Group']"}), 'id': ('sentry.db.models.fields.BoundedBigAutoField', [], {'primary_key': 'True'}), 'message': ('django.db.models.fields.TextField', [], {}), 'num_comments': ('django.db.models.fields.PositiveIntegerField', [], {'default': '0', 'null': 'True'}), 'platform': ('django.db.models.fields.CharField', [], {'max_length': '64', 'null': 'True'}), 'project': ('sentry.db.models.fields.FlexibleForeignKey', [], {'to': "orm['sentry.Project']", 'null': 'True'}), 'time_spent': ('django.db.models.fields.IntegerField', [], {'null': 'True'}) }, 'sentry.eventmapping': { 'Meta': {'unique_together': "(('project', 'event_id'),)", 'object_name': 'EventMapping'}, 'date_added': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'event_id': ('django.db.models.fields.CharField', [], {'max_length': '32'}), 'group': ('sentry.db.models.fields.FlexibleForeignKey', [], {'to': "orm['sentry.Group']"}), 'id': ('sentry.db.models.fields.BoundedBigAutoField', [], {'primary_key': 'True'}), 'project': ('sentry.db.models.fields.FlexibleForeignKey', [], {'to': "orm['sentry.Project']"}) }, 'sentry.group': { 'Meta': {'unique_together': "(('project', 'checksum'),)", 'object_name': 'Group', 'db_table': "'sentry_groupedmessage'"}, 'active_at': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'db_index': 'True'}), 'checksum': ('django.db.models.fields.CharField', [], {'max_length': '32', 'db_index': 'True'}), 'culprit': ('django.db.models.fields.CharField', [], {'max_length': '200', 'null': 'True', 'db_column': "'view'", 'blank': 'True'}), 'data': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'first_seen': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'db_index': 'True'}), 'id': ('sentry.db.models.fields.BoundedBigAutoField', [], {'primary_key': 'True'}), 'is_public': ('django.db.models.fields.NullBooleanField', [], {'default': 'False', 'null': 'True', 'blank': 'True'}), 'last_seen': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'db_index': 'True'}), 'level': ('django.db.models.fields.PositiveIntegerField', [], {'default': '40', 'db_index': 'True', 'blank': 'True'}), 'logger': ('django.db.models.fields.CharField', [], {'default': "'root'", 'max_length': '64', 'db_index': 'True', 'blank': 'True'}), 'message': ('django.db.models.fields.TextField', [], {}), 'num_comments': ('django.db.models.fields.PositiveIntegerField', [], {'default': '0', 'null': 'True'}), 'platform': ('django.db.models.fields.CharField', [], {'max_length': '64', 'null': 'True'}), 'project': ('sentry.db.models.fields.FlexibleForeignKey', [], {'to': "orm['sentry.Project']", 'null': 'True'}), 'resolved_at': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'db_index': 'True'}), 'score': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'status': ('django.db.models.fields.PositiveIntegerField', [], {'default': '0', 'db_index': 'True'}), 'time_spent_count': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'time_spent_total': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'times_seen': ('django.db.models.fields.PositiveIntegerField', [], {'default': '1', 'db_index': 'True'}) }, 'sentry.groupassignee': { 'Meta': {'object_name': 'GroupAssignee', 'db_table': "'sentry_groupasignee'"}, 'date_added': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'group': ('sentry.db.models.fields.FlexibleForeignKey', [], {'related_name': "'assignee_set'", 'unique': 'True', 'to': "orm['sentry.Group']"}), 'id': ('sentry.db.models.fields.BoundedBigAutoField', [], {'primary_key': 'True'}), 'project': ('sentry.db.models.fields.FlexibleForeignKey', [], {'related_name': "'assignee_set'", 'to': "orm['sentry.Project']"}), 'user': ('sentry.db.models.fields.FlexibleForeignKey', [], {'related_name': "'sentry_assignee_set'", 'to': "orm['sentry.User']"}) }, 'sentry.groupbookmark': { 'Meta': {'unique_together': "(('project', 'user', 'group'),)", 'object_name': 'GroupBookmark'}, 'group': ('sentry.db.models.fields.FlexibleForeignKey', [], {'related_name': "'bookmark_set'", 'to': "orm['sentry.Group']"}), 'id': ('sentry.db.models.fields.BoundedBigAutoField', [], {'primary_key': 'True'}), 'project': ('sentry.db.models.fields.FlexibleForeignKey', [], {'related_name': "'bookmark_set'", 'to': "orm['sentry.Project']"}), 'user': ('sentry.db.models.fields.FlexibleForeignKey', [], {'related_name': "'sentry_bookmark_set'", 'to': "orm['sentry.User']"}) }, 'sentry.grouphash': { 'Meta': {'unique_together': "(('project', 'hash'),)", 'object_name': 'GroupHash'}, 'group': ('sentry.db.models.fields.FlexibleForeignKey', [], {'to': "orm['sentry.Group']", 'null': 'True'}), 'hash': ('django.db.models.fields.CharField', [], {'max_length': '32', 'db_index': 'True'}), 'id': ('sentry.db.models.fields.BoundedBigAutoField', [], {'primary_key': 'True'}), 'project': ('sentry.db.models.fields.FlexibleForeignKey', [], {'to': "orm['sentry.Project']", 'null': 'True'}) }, 'sentry.groupmeta': { 'Meta': {'unique_together': "(('group', 'key'),)", 'object_name': 'GroupMeta'}, 'group': ('sentry.db.models.fields.FlexibleForeignKey', [], {'to': "orm['sentry.Group']"}), 'id': ('sentry.db.models.fields.BoundedBigAutoField', [], {'primary_key': 'True'}), 'key': ('django.db.models.fields.CharField', [], {'max_length': '64'}), 'value': ('django.db.models.fields.TextField', [], {}) }, 'sentry.grouprulestatus': { 'Meta': {'unique_together': "(('rule', 'group'),)", 'object_name': 'GroupRuleStatus'}, 'date_added': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'group': ('sentry.db.models.fields.FlexibleForeignKey', [], {'to': "orm['sentry.Group']"}), 'id': ('sentry.db.models.fields.BoundedBigAutoField', [], {'primary_key': 'True'}), 'project': ('sentry.db.models.fields.FlexibleForeignKey', [], {'to': "orm['sentry.Project']"}), 'rule': ('sentry.db.models.fields.FlexibleForeignKey', [], {'to': "orm['sentry.Rule']"}), 'status': ('django.db.models.fields.PositiveSmallIntegerField', [], {'default': '0'}) }, 'sentry.groupseen': { 'Meta': {'unique_together': "(('user', 'group'),)", 'object_name': 'GroupSeen'}, 'group': ('sentry.db.models.fields.FlexibleForeignKey', [], {'to': "orm['sentry.Group']"}), 'id': ('sentry.db.models.fields.BoundedBigAutoField', [], {'primary_key': 'True'}), 'last_seen': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'project': ('sentry.db.models.fields.FlexibleForeignKey', [], {'to': "orm['sentry.Project']"}), 'user': ('sentry.db.models.fields.FlexibleForeignKey', [], {'to': "orm['sentry.User']", 'db_index': 'False'}) }, 'sentry.grouptagkey': { 'Meta': {'unique_together': "(('project', 'group', 'key'),)", 'object_name': 'GroupTagKey'}, 'group': ('sentry.db.models.fields.FlexibleForeignKey', [], {'to': "orm['sentry.Group']"}), 'id': ('sentry.db.models.fields.BoundedBigAutoField', [], {'primary_key': 'True'}), 'key': ('django.db.models.fields.CharField', [], {'max_length': '32'}), 'project': ('sentry.db.models.fields.FlexibleForeignKey', [], {'to': "orm['sentry.Project']", 'null': 'True'}), 'values_seen': ('django.db.models.fields.PositiveIntegerField', [], {'default': '0'}) }, 'sentry.grouptagvalue': { 'Meta': {'unique_together': "(('project', 'key', 'value', 'group'),)", 'object_name': 'GroupTagValue', 'db_table': "'sentry_messagefiltervalue'"}, 'first_seen': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'null': 'True', 'db_index': 'True'}), 'group': ('sentry.db.models.fields.FlexibleForeignKey', [], {'related_name': "'grouptag'", 'to': "orm['sentry.Group']"}), 'id': ('sentry.db.models.fields.BoundedBigAutoField', [], {'primary_key': 'True'}), 'key': ('django.db.models.fields.CharField', [], {'max_length': '32'}), 'last_seen': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'null': 'True', 'db_index': 'True'}), 'project': ('sentry.db.models.fields.FlexibleForeignKey', [], {'related_name': "'grouptag'", 'null': 'True', 'to': "orm['sentry.Project']"}), 'times_seen': ('django.db.models.fields.PositiveIntegerField', [], {'default': '0'}), 'value': ('django.db.models.fields.CharField', [], {'max_length': '200'}) }, 'sentry.lostpasswordhash': { 'Meta': {'object_name': 'LostPasswordHash'}, 'date_added': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'hash': ('django.db.models.fields.CharField', [], {'max_length': '32'}), 'id': ('sentry.db.models.fields.BoundedBigAutoField', [], {'primary_key': 'True'}), 'user': ('sentry.db.models.fields.FlexibleForeignKey', [], {'to': "orm['sentry.User']", 'unique': 'True'}) }, 'sentry.option': { 'Meta': {'object_name': 'Option'}, 'id': ('sentry.db.models.fields.BoundedBigAutoField', [], {'primary_key': 'True'}), 'key': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '64'}), 'last_updated': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'value': ('sentry.db.models.fields.pickle.UnicodePickledObjectField', [], {}) }, 'sentry.organization': { 'Meta': {'object_name': 'Organization'}, 'date_added': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'id': ('sentry.db.models.fields.BoundedBigAutoField', [], {'primary_key': 'True'}), 'members': ('django.db.models.fields.related.ManyToManyField', [], {'related_name': "'org_memberships'", 'symmetrical': 'False', 'through': "orm['sentry.OrganizationMember']", 'to': "orm['sentry.User']"}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '64'}), 'owner': ('sentry.db.models.fields.FlexibleForeignKey', [], {'to': "orm['sentry.User']"}), 'slug': ('django.db.models.fields.SlugField', [], {'unique': 'True', 'max_length': '50'}), 'status': ('django.db.models.fields.PositiveIntegerField', [], {'default': '0'}) }, 'sentry.organizationmember': { 'Meta': {'unique_together': "(('organization', 'user'), ('organization', 'email'))", 'object_name': 'OrganizationMember'}, 'date_added': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'null': 'True', 'blank': 'True'}), 'has_global_access': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'id': ('sentry.db.models.fields.BoundedBigAutoField', [], {'primary_key': 'True'}), 'organization': ('sentry.db.models.fields.FlexibleForeignKey', [], {'related_name': "'member_set'", 'to': "orm['sentry.Organization']"}), 'teams': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['sentry.Team']", 'symmetrical': 'False', 'blank': 'True'}), 'type': ('django.db.models.fields.PositiveIntegerField', [], {'default': '50'}), 'user': ('sentry.db.models.fields.FlexibleForeignKey', [], {'blank': 'True', 'related_name': "'sentry_orgmember_set'", 'null': 'True', 'to': "orm['sentry.User']"}) }, 'sentry.pendingteammember': { 'Meta': {'unique_together': "(('team', 'email'),)", 'object_name': 'PendingTeamMember'}, 'date_added': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'email': ('django.db.models.fields.EmailField', [], {'max_length': '75'}), 'id': ('sentry.db.models.fields.BoundedBigAutoField', [], {'primary_key': 'True'}), 'team': ('sentry.db.models.fields.FlexibleForeignKey', [], {'related_name': "'pending_member_set'", 'to': "orm['sentry.Team']"}), 'type': ('django.db.models.fields.IntegerField', [], {'default': '50'}) }, 'sentry.project': { 'Meta': {'unique_together': "(('team', 'slug'), ('organization', 'slug'))", 'object_name': 'Project'}, 'date_added': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'id': ('sentry.db.models.fields.BoundedBigAutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '200'}), 'organization': ('sentry.db.models.fields.FlexibleForeignKey', [], {'to': "orm['sentry.Organization']"}), 'platform': ('django.db.models.fields.CharField', [], {'max_length': '32', 'null': 'True'}), 'public': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'slug': ('django.db.models.fields.SlugField', [], {'max_length': '50', 'null': 'True'}), 'status': ('django.db.models.fields.PositiveIntegerField', [], {'default': '0', 'db_index': 'True'}), 'team': ('sentry.db.models.fields.FlexibleForeignKey', [], {'to': "orm['sentry.Team']"}) }, 'sentry.projectkey': { 'Meta': {'object_name': 'ProjectKey'}, 'date_added': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'null': 'True'}), 'id': ('sentry.db.models.fields.BoundedBigAutoField', [], {'primary_key': 'True'}), 'label': ('django.db.models.fields.CharField', [], {'max_length': '64', 'null': 'True', 'blank': 'True'}), 'project': ('sentry.db.models.fields.FlexibleForeignKey', [], {'related_name': "'key_set'", 'to': "orm['sentry.Project']"}), 'public_key': ('django.db.models.fields.CharField', [], {'max_length': '32', 'unique': 'True', 'null': 'True'}), 'roles': ('django.db.models.fields.BigIntegerField', [], {'default': '1'}), 'secret_key': ('django.db.models.fields.CharField', [], {'max_length': '32', 'unique': 'True', 'null': 'True'}), 'user': ('sentry.db.models.fields.FlexibleForeignKey', [], {'to': "orm['sentry.User']", 'null': 'True'}), 'user_added': ('sentry.db.models.fields.FlexibleForeignKey', [], {'related_name': "'keys_added_set'", 'null': 'True', 'to': "orm['sentry.User']"}) }, 'sentry.projectoption': { 'Meta': {'unique_together': "(('project', 'key'),)", 'object_name': 'ProjectOption', 'db_table': "'sentry_projectoptions'"}, 'id': ('sentry.db.models.fields.BoundedBigAutoField', [], {'primary_key': 'True'}), 'key': ('django.db.models.fields.CharField', [], {'max_length': '64'}), 'project': ('sentry.db.models.fields.FlexibleForeignKey', [], {'to': "orm['sentry.Project']"}), 'value': ('sentry.db.models.fields.pickle.UnicodePickledObjectField', [], {}) }, 'sentry.release': { 'Meta': {'unique_together': "(('project', 'version'),)", 'object_name': 'Release'}, 'date_added': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'id': ('sentry.db.models.fields.BoundedBigAutoField', [], {'primary_key': 'True'}), 'project': ('sentry.db.models.fields.FlexibleForeignKey', [], {'to': "orm['sentry.Project']"}), 'version': ('django.db.models.fields.CharField', [], {'max_length': '64'}) }, 'sentry.rule': { 'Meta': {'object_name': 'Rule'}, 'data': ('sentry.db.models.fields.gzippeddict.GzippedDictField', [], {}), 'date_added': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'id': ('sentry.db.models.fields.BoundedBigAutoField', [], {'primary_key': 'True'}), 'label': ('django.db.models.fields.CharField', [], {'max_length': '64'}), 'project': ('sentry.db.models.fields.FlexibleForeignKey', [], {'to': "orm['sentry.Project']"}) }, 'sentry.tagkey': { 'Meta': {'unique_together': "(('project', 'key'),)", 'object_name': 'TagKey', 'db_table': "'sentry_filterkey'"}, 'id': ('sentry.db.models.fields.BoundedBigAutoField', [], {'primary_key': 'True'}), 'key': ('django.db.models.fields.CharField', [], {'max_length': '32'}), 'label': ('django.db.models.fields.CharField', [], {'max_length': '64', 'null': 'True'}), 'project': ('sentry.db.models.fields.FlexibleForeignKey', [], {'to': "orm['sentry.Project']"}), 'values_seen': ('django.db.models.fields.PositiveIntegerField', [], {'default': '0'}) }, 'sentry.tagvalue': { 'Meta': {'unique_together': "(('project', 'key', 'value'),)", 'object_name': 'TagValue', 'db_table': "'sentry_filtervalue'"}, 'data': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'first_seen': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'null': 'True', 'db_index': 'True'}), 'id': ('sentry.db.models.fields.BoundedBigAutoField', [], {'primary_key': 'True'}), 'key': ('django.db.models.fields.CharField', [], {'max_length': '32'}), 'last_seen': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'null': 'True', 'db_index': 'True'}), 'project': ('sentry.db.models.fields.FlexibleForeignKey', [], {'to': "orm['sentry.Project']", 'null': 'True'}), 'times_seen': ('django.db.models.fields.PositiveIntegerField', [], {'default': '0'}), 'value': ('django.db.models.fields.CharField', [], {'max_length': '200'}) }, 'sentry.team': { 'Meta': {'object_name': 'Team'}, 'date_added': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'null': 'True'}), 'id': ('sentry.db.models.fields.BoundedBigAutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '64'}), 'organization': ('sentry.db.models.fields.FlexibleForeignKey', [], {'to': "orm['sentry.Organization']"}), 'owner': ('sentry.db.models.fields.FlexibleForeignKey', [], {'to': "orm['sentry.User']"}), 'slug': ('django.db.models.fields.SlugField', [], {'unique': 'True', 'max_length': '50'}), 'status': ('django.db.models.fields.PositiveIntegerField', [], {'default': '0'}) }, 'sentry.teammember': { 'Meta': {'unique_together': "(('team', 'user'),)", 'object_name': 'TeamMember'}, 'date_added': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'id': ('sentry.db.models.fields.BoundedBigAutoField', [], {'primary_key': 'True'}), 'team': ('sentry.db.models.fields.FlexibleForeignKey', [], {'to': "orm['sentry.Team']"}), 'type': ('django.db.models.fields.IntegerField', [], {'default': '50'}), 'user': ('sentry.db.models.fields.FlexibleForeignKey', [], {'to': "orm['sentry.User']"}) }, 'sentry.user': { 'Meta': {'object_name': 'User', 'db_table': "'auth_user'"}, 'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}), 'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'is_managed': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}), 'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '128'}) }, 'sentry.useroption': { 'Meta': {'unique_together': "(('user', 'project', 'key'),)", 'object_name': 'UserOption'}, 'id': ('sentry.db.models.fields.BoundedBigAutoField', [], {'primary_key': 'True'}), 'key': ('django.db.models.fields.CharField', [], {'max_length': '64'}), 'project': ('sentry.db.models.fields.FlexibleForeignKey', [], {'to': "orm['sentry.Project']", 'null': 'True'}), 'user': ('sentry.db.models.fields.FlexibleForeignKey', [], {'to': "orm['sentry.User']"}), 'value': ('sentry.db.models.fields.pickle.UnicodePickledObjectField', [], {}) } } complete_apps = ['sentry']
bsd-3-clause
dfang/odoo
addons/account/models/company.py
9
7291
# -*- coding: utf-8 -*- from odoo import fields, models, api, _ from datetime import timedelta class ResCompany(models.Model): _inherit = "res.company" #TODO check all the options/fields are in the views (settings + company form view) fiscalyear_last_day = fields.Integer(default=31, required=True) fiscalyear_last_month = fields.Selection([(1, 'January'), (2, 'February'), (3, 'March'), (4, 'April'), (5, 'May'), (6, 'June'), (7, 'July'), (8, 'August'), (9, 'September'), (10, 'October'), (11, 'November'), (12, 'December')], default=12, required=True) period_lock_date = fields.Date(string="Lock Date for Non-Advisers", help="Only users with the 'Adviser' role can edit accounts prior to and inclusive of this date. Use it for period locking inside an open fiscal year, for example.") fiscalyear_lock_date = fields.Date(string="Lock Date", help="No users, including Advisers, can edit accounts prior to and inclusive of this date. Use it for fiscal year locking for example.") transfer_account_id = fields.Many2one('account.account', domain=lambda self: [('reconcile', '=', True), ('user_type_id.id', '=', self.env.ref('account.data_account_type_current_assets').id), ('deprecated', '=', False)], string="Inter-Banks Transfer Account", help="Intermediary account used when moving money from a liquidity account to another") expects_chart_of_accounts = fields.Boolean(string='Expects a Chart of Accounts', default=True) chart_template_id = fields.Many2one('account.chart.template', help='The chart template for the company (if any)') bank_account_code_prefix = fields.Char(string='Prefix of the bank accounts', oldname="bank_account_code_char") cash_account_code_prefix = fields.Char(string='Prefix of the cash accounts') accounts_code_digits = fields.Integer(string='Number of digits in an account code') tax_calculation_rounding_method = fields.Selection([ ('round_per_line', 'Round per Line'), ('round_globally', 'Round Globally'), ], default='round_per_line', string='Tax Calculation Rounding Method', help="If you select 'Round per Line' : for each tax, the tax amount will first be computed and rounded for each PO/SO/invoice line and then these rounded amounts will be summed, leading to the total amount for that tax. If you select 'Round Globally': for each tax, the tax amount will be computed for each PO/SO/invoice line, then these amounts will be summed and eventually this total tax amount will be rounded. If you sell with tax included, you should choose 'Round per line' because you certainly want the sum of your tax-included line subtotals to be equal to the total amount with taxes.") currency_exchange_journal_id = fields.Many2one('account.journal', string="Exchange Gain or Loss Journal", domain=[('type', '=', 'general')]) income_currency_exchange_account_id = fields.Many2one('account.account', related='currency_exchange_journal_id.default_credit_account_id', string="Gain Exchange Rate Account", domain="[('internal_type', '=', 'other'), ('deprecated', '=', False), ('company_id', '=', id)]") expense_currency_exchange_account_id = fields.Many2one('account.account', related='currency_exchange_journal_id.default_debit_account_id', string="Loss Exchange Rate Account", domain="[('internal_type', '=', 'other'), ('deprecated', '=', False), ('company_id', '=', id)]") anglo_saxon_accounting = fields.Boolean(string="Use anglo-saxon accounting") property_stock_account_input_categ_id = fields.Many2one('account.account', string="Input Account for Stock Valuation", oldname="property_stock_account_input_categ") property_stock_account_output_categ_id = fields.Many2one('account.account', string="Output Account for Stock Valuation", oldname="property_stock_account_output_categ") property_stock_valuation_account_id = fields.Many2one('account.account', string="Account Template for Stock Valuation") bank_journal_ids = fields.One2many('account.journal', 'company_id', domain=[('type', '=', 'bank')], string='Bank Journals') overdue_msg = fields.Text(string='Overdue Payments Message', translate=True, default='''Dear Sir/Madam, Our records indicate that some payments on your account are still due. Please find details below. If the amount has already been paid, please disregard this notice. Otherwise, please forward us the total amount stated below. If you have any queries regarding your account, Please contact us. Thank you in advance for your cooperation. Best Regards,''') @api.multi def compute_fiscalyear_dates(self, date): """ Computes the start and end dates of the fiscalyear where the given 'date' belongs to @param date: a datetime object @returns: a dictionary with date_from and date_to """ self = self[0] last_month = self.fiscalyear_last_month last_day = self.fiscalyear_last_day if (date.month < last_month or (date.month == last_month and date.day <= last_day)): date = date.replace(month=last_month, day=last_day) else: date = date.replace(month=last_month, day=last_day, year=date.year + 1) date_to = date date_from = date + timedelta(days=1) date_from = date_from.replace(year=date_from.year - 1) return {'date_from': date_from, 'date_to': date_to} def get_new_account_code(self, current_code, old_prefix, new_prefix, digits): return new_prefix + current_code.replace(old_prefix, '', 1).lstrip('0').rjust(digits-len(new_prefix), '0') def reflect_code_prefix_change(self, old_code, new_code, digits): accounts = self.env['account.account'].search([('code', 'like', old_code), ('internal_type', '=', 'liquidity'), ('company_id', '=', self.id)], order='code asc') for account in accounts: if account.code.startswith(old_code): account.write({'code': self.get_new_account_code(account.code, old_code, new_code, digits)}) def reflect_code_digits_change(self, digits): accounts = self.env['account.account'].search([('company_id', '=', self.id)], order='code asc') for account in accounts: account.write({'code': account.code.rstrip('0').ljust(digits, '0')}) @api.multi def write(self, values): # Reflect the change on accounts for company in self: digits = values.get('accounts_code_digits') or company.accounts_code_digits if values.get('bank_account_code_prefix') or values.get('accounts_code_digits'): new_bank_code = values.get('bank_account_code_prefix') or company.bank_account_code_prefix company.reflect_code_prefix_change(company.bank_account_code_prefix, new_bank_code, digits) if values.get('cash_account_code_prefix') or values.get('accounts_code_digits'): new_cash_code = values.get('cash_account_code_prefix') or company.cash_account_code_prefix company.reflect_code_prefix_change(company.cash_account_code_prefix, new_cash_code, digits) if values.get('accounts_code_digits'): company.reflect_code_digits_change(digits) return super(ResCompany, self).write(values)
agpl-3.0
MFoster/breeze
django/contrib/gis/db/models/sql/query.py
209
5406
from django.db import connections from django.db.models.query import sql from django.contrib.gis.db.models.fields import GeometryField from django.contrib.gis.db.models.sql import aggregates as gis_aggregates from django.contrib.gis.db.models.sql.conversion import AreaField, DistanceField, GeomField from django.contrib.gis.db.models.sql.where import GeoWhereNode from django.contrib.gis.geometry.backend import Geometry from django.contrib.gis.measure import Area, Distance ALL_TERMS = set([ 'bbcontains', 'bboverlaps', 'contained', 'contains', 'contains_properly', 'coveredby', 'covers', 'crosses', 'disjoint', 'distance_gt', 'distance_gte', 'distance_lt', 'distance_lte', 'dwithin', 'equals', 'exact', 'intersects', 'overlaps', 'relate', 'same_as', 'touches', 'within', 'left', 'right', 'overlaps_left', 'overlaps_right', 'overlaps_above', 'overlaps_below', 'strictly_above', 'strictly_below' ]) ALL_TERMS.update(sql.constants.QUERY_TERMS) class GeoQuery(sql.Query): """ A single spatial SQL query. """ # Overridding the valid query terms. query_terms = ALL_TERMS aggregates_module = gis_aggregates compiler = 'GeoSQLCompiler' #### Methods overridden from the base Query class #### def __init__(self, model, where=GeoWhereNode): super(GeoQuery, self).__init__(model, where) # The following attributes are customized for the GeoQuerySet. # The GeoWhereNode and SpatialBackend classes contain backend-specific # routines and functions. self.custom_select = {} self.transformed_srid = None self.extra_select_fields = {} def clone(self, *args, **kwargs): obj = super(GeoQuery, self).clone(*args, **kwargs) # Customized selection dictionary and transformed srid flag have # to also be added to obj. obj.custom_select = self.custom_select.copy() obj.transformed_srid = self.transformed_srid obj.extra_select_fields = self.extra_select_fields.copy() return obj def convert_values(self, value, field, connection): """ Using the same routines that Oracle does we can convert our extra selection objects into Geometry and Distance objects. TODO: Make converted objects 'lazy' for less overhead. """ if connection.ops.oracle: # Running through Oracle's first. value = super(GeoQuery, self).convert_values(value, field or GeomField(), connection) if value is None: # Output from spatial function is NULL (e.g., called # function on a geometry field with NULL value). pass elif isinstance(field, DistanceField): # Using the field's distance attribute, can instantiate # `Distance` with the right context. value = Distance(**{field.distance_att : value}) elif isinstance(field, AreaField): value = Area(**{field.area_att : value}) elif isinstance(field, (GeomField, GeometryField)) and value: value = Geometry(value) elif field is not None: return super(GeoQuery, self).convert_values(value, field, connection) return value def get_aggregation(self, using): # Remove any aggregates marked for reduction from the subquery # and move them to the outer AggregateQuery. connection = connections[using] for alias, aggregate in self.aggregate_select.items(): if isinstance(aggregate, gis_aggregates.GeoAggregate): if not getattr(aggregate, 'is_extent', False) or connection.ops.oracle: self.extra_select_fields[alias] = GeomField() return super(GeoQuery, self).get_aggregation(using) def resolve_aggregate(self, value, aggregate, connection): """ Overridden from GeoQuery's normalize to handle the conversion of GeoAggregate objects. """ if isinstance(aggregate, self.aggregates_module.GeoAggregate): if aggregate.is_extent: if aggregate.is_extent == '3D': return connection.ops.convert_extent3d(value) else: return connection.ops.convert_extent(value) else: return connection.ops.convert_geom(value, aggregate.source) else: return super(GeoQuery, self).resolve_aggregate(value, aggregate, connection) # Private API utilities, subject to change. def _geo_field(self, field_name=None): """ Returns the first Geometry field encountered; or specified via the `field_name` keyword. The `field_name` may be a string specifying the geometry field on this GeoQuery's model, or a lookup string to a geometry field via a ForeignKey relation. """ if field_name is None: # Incrementing until the first geographic field is found. for fld in self.model._meta.fields: if isinstance(fld, GeometryField): return fld return False else: # Otherwise, check by the given field name -- which may be # a lookup to a _related_ geographic field. return GeoWhereNode._check_geo_field(self.model._meta, field_name)
bsd-3-clause
MattRijk/django-ecomsite
lib/python2.7/site-packages/django/core/management/commands/inspectdb.py
30
10340
from __future__ import unicode_literals import keyword import re from optparse import make_option from django.core.management.base import NoArgsCommand, CommandError from django.db import connections, DEFAULT_DB_ALIAS from django.utils.datastructures import SortedDict class Command(NoArgsCommand): help = "Introspects the database tables in the given database and outputs a Django model module." option_list = NoArgsCommand.option_list + ( make_option('--database', action='store', dest='database', default=DEFAULT_DB_ALIAS, help='Nominates a database to ' 'introspect. Defaults to using the "default" database.'), ) requires_model_validation = False db_module = 'django.db' def handle_noargs(self, **options): try: for line in self.handle_inspection(options): self.stdout.write("%s\n" % line) except NotImplementedError: raise CommandError("Database inspection isn't supported for the currently selected database backend.") def handle_inspection(self, options): connection = connections[options.get('database')] # 'table_name_filter' is a stealth option table_name_filter = options.get('table_name_filter') table2model = lambda table_name: table_name.title().replace('_', '').replace(' ', '').replace('-', '') strip_prefix = lambda s: s[1:] if s.startswith("u'") else s cursor = connection.cursor() yield "# This is an auto-generated Django model module." yield "# You'll have to do the following manually to clean this up:" yield "# * Rearrange models' order" yield "# * Make sure each model has one field with primary_key=True" yield "# * Remove `managed = False` lines if you wish to allow Django to create and delete the table" yield "# Feel free to rename the models, but don't rename db_table values or field names." yield "#" yield "# Also note: You'll have to insert the output of 'django-admin.py sqlcustom [appname]'" yield "# into your database." yield "from __future__ import unicode_literals" yield '' yield 'from %s import models' % self.db_module yield '' known_models = [] for table_name in connection.introspection.table_names(cursor): if table_name_filter is not None and callable(table_name_filter): if not table_name_filter(table_name): continue yield 'class %s(models.Model):' % table2model(table_name) known_models.append(table2model(table_name)) try: relations = connection.introspection.get_relations(cursor, table_name) except NotImplementedError: relations = {} try: indexes = connection.introspection.get_indexes(cursor, table_name) except NotImplementedError: indexes = {} used_column_names = [] # Holds column names used in the table so far for i, row in enumerate(connection.introspection.get_table_description(cursor, table_name)): comment_notes = [] # Holds Field notes, to be displayed in a Python comment. extra_params = SortedDict() # Holds Field parameters such as 'db_column'. column_name = row[0] is_relation = i in relations att_name, params, notes = self.normalize_col_name( column_name, used_column_names, is_relation) extra_params.update(params) comment_notes.extend(notes) used_column_names.append(att_name) # Add primary_key and unique, if necessary. if column_name in indexes: if indexes[column_name]['primary_key']: extra_params['primary_key'] = True elif indexes[column_name]['unique']: extra_params['unique'] = True if is_relation: rel_to = "self" if relations[i][1] == table_name else table2model(relations[i][1]) if rel_to in known_models: field_type = 'ForeignKey(%s' % rel_to else: field_type = "ForeignKey('%s'" % rel_to else: # Calling `get_field_type` to get the field type string and any # additional paramters and notes. field_type, field_params, field_notes = self.get_field_type(connection, table_name, row) extra_params.update(field_params) comment_notes.extend(field_notes) field_type += '(' # Don't output 'id = meta.AutoField(primary_key=True)', because # that's assumed if it doesn't exist. if att_name == 'id' and field_type == 'AutoField(' and extra_params == {'primary_key': True}: continue # Add 'null' and 'blank', if the 'null_ok' flag was present in the # table description. if row[6]: # If it's NULL... if field_type == 'BooleanField(': field_type = 'NullBooleanField(' else: extra_params['blank'] = True if not field_type in ('TextField(', 'CharField('): extra_params['null'] = True field_desc = '%s = models.%s' % (att_name, field_type) if extra_params: if not field_desc.endswith('('): field_desc += ', ' field_desc += ', '.join([ '%s=%s' % (k, strip_prefix(repr(v))) for k, v in extra_params.items()]) field_desc += ')' if comment_notes: field_desc += ' # ' + ' '.join(comment_notes) yield ' %s' % field_desc for meta_line in self.get_meta(table_name): yield meta_line def normalize_col_name(self, col_name, used_column_names, is_relation): """ Modify the column name to make it Python-compatible as a field name """ field_params = {} field_notes = [] new_name = col_name.lower() if new_name != col_name: field_notes.append('Field name made lowercase.') if is_relation: if new_name.endswith('_id'): new_name = new_name[:-3] else: field_params['db_column'] = col_name new_name, num_repl = re.subn(r'\W', '_', new_name) if num_repl > 0: field_notes.append('Field renamed to remove unsuitable characters.') if new_name.find('__') >= 0: while new_name.find('__') >= 0: new_name = new_name.replace('__', '_') if col_name.lower().find('__') >= 0: # Only add the comment if the double underscore was in the original name field_notes.append("Field renamed because it contained more than one '_' in a row.") if new_name.startswith('_'): new_name = 'field%s' % new_name field_notes.append("Field renamed because it started with '_'.") if new_name.endswith('_'): new_name = '%sfield' % new_name field_notes.append("Field renamed because it ended with '_'.") if keyword.iskeyword(new_name): new_name += '_field' field_notes.append('Field renamed because it was a Python reserved word.') if new_name[0].isdigit(): new_name = 'number_%s' % new_name field_notes.append("Field renamed because it wasn't a valid Python identifier.") if new_name in used_column_names: num = 0 while '%s_%d' % (new_name, num) in used_column_names: num += 1 new_name = '%s_%d' % (new_name, num) field_notes.append('Field renamed because of name conflict.') if col_name != new_name and field_notes: field_params['db_column'] = col_name return new_name, field_params, field_notes def get_field_type(self, connection, table_name, row): """ Given the database connection, the table name, and the cursor row description, this routine will return the given field type name, as well as any additional keyword parameters and notes for the field. """ field_params = SortedDict() field_notes = [] try: field_type = connection.introspection.get_field_type(row[1], row) except KeyError: field_type = 'TextField' field_notes.append('This field type is a guess.') # This is a hook for DATA_TYPES_REVERSE to return a tuple of # (field_type, field_params_dict). if type(field_type) is tuple: field_type, new_params = field_type field_params.update(new_params) # Add max_length for all CharFields. if field_type == 'CharField' and row[3]: field_params['max_length'] = int(row[3]) if field_type == 'DecimalField': if row[4] is None or row[5] is None: field_notes.append( 'max_digits and decimal_places have been guessed, as this ' 'database handles decimal fields as float') field_params['max_digits'] = row[4] if row[4] is not None else 10 field_params['decimal_places'] = row[5] if row[5] is not None else 5 else: field_params['max_digits'] = row[4] field_params['decimal_places'] = row[5] return field_type, field_params, field_notes def get_meta(self, table_name): """ Return a sequence comprising the lines of code necessary to construct the inner Meta class for the model corresponding to the given database table name. """ return [" class Meta:", " managed = False", " db_table = '%s'" % table_name, ""]
cc0-1.0
rubencabrera/odoo
addons/sale_journal/sale_journal.py
276
4290
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## from openerp.osv import fields, osv class sale_journal_invoice_type(osv.osv): _name = 'sale_journal.invoice.type' _description = 'Invoice Types' _columns = { 'name': fields.char('Invoice Type', required=True), 'active': fields.boolean('Active', help="If the active field is set to False, it will allow you to hide the invoice type without removing it."), 'note': fields.text('Note'), 'invoicing_method': fields.selection([('simple', 'Non grouped'), ('grouped', 'Grouped')], 'Invoicing method', required=True), } _defaults = { 'active': True, 'invoicing_method': 'simple' } #============================================== # sale journal inherit #============================================== class res_partner(osv.osv): _inherit = 'res.partner' _columns = { 'property_invoice_type': fields.property( type = 'many2one', relation = 'sale_journal.invoice.type', string = "Invoicing Type", group_name = "Accounting Properties", help = "This invoicing type will be used, by default, to invoice the current partner."), } def _commercial_fields(self, cr, uid, context=None): return super(res_partner, self)._commercial_fields(cr, uid, context=context) + ['property_invoice_type'] class picking(osv.osv): _inherit = "stock.picking" _columns = { 'invoice_type_id': fields.many2one('sale_journal.invoice.type', 'Invoice Type', readonly=True) } class stock_move(osv.osv): _inherit = "stock.move" def action_confirm(self, cr, uid, ids, context=None): """ Pass the invoice type to the picking from the sales order (Should also work in case of Phantom BoMs when on explosion the original move is deleted, similar to carrier_id on delivery) """ procs_to_check = [] for move in self.browse(cr, uid, ids, context=context): if move.procurement_id and move.procurement_id.sale_line_id and move.procurement_id.sale_line_id.order_id.invoice_type_id: procs_to_check += [move.procurement_id] res = super(stock_move, self).action_confirm(cr, uid, ids, context=context) pick_obj = self.pool.get("stock.picking") for proc in procs_to_check: pickings = list(set([x.picking_id.id for x in proc.move_ids if x.picking_id and not x.picking_id.invoice_type_id])) if pickings: pick_obj.write(cr, uid, pickings, {'invoice_type_id': proc.sale_line_id.order_id.invoice_type_id.id}, context=context) return res class sale(osv.osv): _inherit = "sale.order" _columns = { 'invoice_type_id': fields.many2one('sale_journal.invoice.type', 'Invoice Type', help="Generate invoice based on the selected option.") } def onchange_partner_id(self, cr, uid, ids, part, context=None): result = super(sale, self).onchange_partner_id(cr, uid, ids, part, context=context) if part: itype = self.pool.get('res.partner').browse(cr, uid, part, context=context).property_invoice_type if itype: result['value']['invoice_type_id'] = itype.id return result # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
agpl-3.0
what-studio/profiling
test/test_tracing.py
1
1802
# -*- coding: utf-8 -*- import sys import pytest from _utils import factorial, find_stats, foo from profiling.stats import RecordingStatistics from profiling.tracing import TracingProfiler def test_setprofile(): profiler = TracingProfiler() assert sys.getprofile() is None with profiler: assert sys.getprofile() == profiler._profile assert sys.getprofile() is None sys.setprofile(lambda *x: x) with pytest.raises(RuntimeError): profiler.start() sys.setprofile(None) def test_profile(): profiler = TracingProfiler() frame = foo() profiler._profile(frame, 'call', None) profiler._profile(frame, 'return', None) assert len(profiler.stats) == 1 stats1 = find_stats(profiler.stats, 'foo') stats2 = find_stats(profiler.stats, 'bar') stats3 = find_stats(profiler.stats, 'baz') assert stats1.own_hits == 0 assert stats2.own_hits == 0 assert stats3.own_hits == 1 assert stats1.deep_hits == 1 assert stats2.deep_hits == 1 assert stats3.deep_hits == 1 def test_profiler(): profiler = TracingProfiler(base_frame=sys._getframe()) assert isinstance(profiler.stats, RecordingStatistics) stats, cpu_time, wall_time = profiler.result() assert len(stats) == 0 with profiler: factorial(1000) factorial(10000) stats1 = find_stats(profiler.stats, 'factorial') stats2 = find_stats(profiler.stats, '__enter__') stats3 = find_stats(profiler.stats, '__exit__') assert stats1.deep_time != 0 assert stats1.deep_time == stats1.own_time assert stats1.own_time > stats2.own_time assert stats1.own_time > stats3.own_time assert stats1.own_hits == 2 assert stats2.own_hits == 0 # entering to __enter__() wasn't profiled. assert stats3.own_hits == 1
bsd-3-clause
Phil9l/cosmos
code/artificial_intelligence/src/naive_bayes/gaussian_naive_bayes.py
3
1370
# example using iris dataset # Part of Cosmos by OpenGenus import numpy as np import matplotlib.pyplot as plt import pandas as pd from sklearn.model_selection import train_test_split from sklearn.naive_bayes import GaussianNB from sklearn.metrics import classification_report, confusion_matrix dataset = pd.read_csv("iris1.csv", header=0) X = dataset.iloc[:, :-1].values y = dataset.iloc[:, 4].values X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.30, stratify=y) classifier = GaussianNB() classifier.fit(X_train, y_train) y_pred = classifier.predict(X_test) # labeled confusion matrix print( pd.crosstab(y_test, y_pred, rownames=["True"], colnames=["Predicted"], margins=True) ) from sklearn.model_selection import StratifiedKFold from sklearn.metrics import accuracy_score skf = StratifiedKFold(n_splits=10) skf.get_n_splits(X, y) StratifiedKFold(n_splits=10, random_state=None, shuffle=False) a = 0 for train_index, test_index in skf.split(X, y): # print("TRAIN:", train_index, "TEST:", test_index) #These are the mutually exclusive sets from the 10 folds X_train, X_test = X[train_index], X[test_index] y_train, y_test = y[train_index], y[test_index] y_pred = classifier.predict(X_test) accuracy = accuracy_score(y_test, y_pred) a += accuracy print("\nK-fold cross validation (10 folds): " + str(a / 10))
gpl-3.0
itmoss/Libjingle
swtoolkit/lib/TestFramework.py
18
11615
#!/usr/bin/python2.4 # Copyright 2009, Google Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following disclaimer # in the documentation and/or other materials provided with the # distribution. # * Neither the name of Google Inc. nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """Testing framework for the software construction toolkit. A TestFramework environment object is created via the usual invocation: import TestFramework test = TestFramework.TestFramework() TestFramework is a subclass of TestCommon, which is in turn is a subclass of TestCmd. """ import base64 import os import re import sys import unittest import TestCommon import TestSCons diff_re = TestCommon.diff_re fail_test = TestCommon.fail_test no_result = TestCommon.no_result pass_test = TestCommon.pass_test match_exact = TestCommon.match_exact match_re = TestCommon.match_re match_re_dotall = TestCommon.match_re_dotall python_executable = TestCommon.python_executable exe_suffix = TestCommon.exe_suffix obj_suffix = TestCommon.obj_suffix shobj_suffix = TestCommon.shobj_suffix lib_prefix = TestCommon.lib_prefix lib_suffix = TestCommon.lib_suffix dll_prefix = TestCommon.dll_prefix dll_suffix = TestCommon.dll_suffix file_expr = TestSCons.file_expr def RunUnitTests(testcase, **kwargs): """Runs all unit tests from a test case. Args: testcase: Test case class (derived from unittest.TestCase) kwargs: Optional variables to inject into each test case object. For example: RunUnitTests(MyToolTests, scons_globals=scons_globals, root_env=env) If a test fails, exits the program via sys.exit(3). """ # Make the test suite suite = unittest.makeSuite(testcase) # Inject variables into each test for t in suite._tests: for k, v in kwargs.items(): setattr(t, k, v) # Run test result = unittest.TextTestRunner(verbosity=2).run(suite) if not result.wasSuccessful(): # A unit test failed sys.exit(3) class TestFramework(TestCommon.TestCommon): """Class for testing this framework. Default behavior is to test hammer.bat on Windows or hammer.sh on any other type of system. A temporary directory gets created (we chdir there) and will be removed automatically when we exit. """ def __init__(self, *args, **kw): # If they haven't specified that they want to test some other # explicit program, either in the TestFramework() object creation or # by setting the $TEST_FRAMEWORK_EXE / %TEST_FRAMEWORK_EXE% environment # variable, then we test 'hammer.bat' on Windows systems and 'hammer.sh' # everywhere else. if not 'program' in kw: kw['program'] = os.environ.get('TEST_FRAMEWORK_EXE') if not kw['program']: if sys.platform == 'win32': kw['program'] = 'hammer.bat' else: kw['program'] = os.getcwd() + '/hammer.sh' # Pass in the magic workdir value '', which will cause a temporary # directory to be created and get us chdir'ed there--but save # the original cwd first in case we need to know where we were... if not 'workdir' in kw: kw['workdir'] = '' TestCommon.TestCommon.__init__(self, *args, **kw) # Use our match function, so we don't need to worry about trailing # whitespace on output we want to compare. self.match = self.match_visible def FakeWindowsCER(self, filename): """Write out a fake windows certificate.""" # Generated with: # makecert.exe -r -sv fake.pvk -n "CN=fakeco" fake.cer (password: secret) self.write(filename, base64.b64decode(""" MIIB7TCCAVagAwIBAgIQcInZW/UOFodA41ESSHTYuzANBgkqhkiG9w0BAQQFADARMQ8wDQYDVQQD EwZmYWtlY28wHhcNMDgwNTA3MjAyNjI2WhcNMzkxMjMxMjM1OTU5WjARMQ8wDQYDVQQDEwZmYWtl Y28wgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBANERhPhli6dLzhU3xFO81uVPrluufLF9lqF6 tNCN4cX+5JaDWZzjiX+fHR/M+8od6f2VXZ6fML9uIq/8cWOQL/oqfKbX7R/MWCvOzsrpI7iLJu4Z uYl+VhUWt3bxjl7bfH89NOS5cZhGuF7z/nVS0J0yconFhkFs6IBp3dKMuHMhAgMBAAGjRjBEMEIG A1UdAQQ7MDmAELq4xibLMx3dvWmlZHSr8S2hEzARMQ8wDQYDVQQDEwZmYWtlY2+CEHCJ2Vv1DhaH QONREkh02LswDQYJKoZIhvcNAQEEBQADgYEARvV1vBoIoP1DZosFVr11HLgKhffKhXxh8XfFLxd1 JMJc/j8x0iNlW3IcVWNeDxh8x3TTJYODTM9WPXi2PL/Ouw2dPToYRnS5vP31EoXGLYlvp1sxnyzo LLE9zUGKBTvHeaWVjHhDh66dWS9ss6pXcVrElSgZVlBTg6jZgvxV27A= """)) def FakeWindowsPVK(self, filename): """Write out a fake private key file.""" # Generated with: # makecert.exe -r -sv fake.pvk -n "CN=fakeco" fake.cer (password: secret) self.write(filename, base64.b64decode(""" HvG1sAAAAAACAAAAAQAAABAAAABUAgAAHXQX+j2ePmaFlOVCODMBigcCAAAAJAAA6tHDlTGLFBkD JbgKswhpzNuqXFUxW3ZYGQb5oH9wy5UCpIddroTpfpM8y7PMz1YWCJ2ijqIdAksv3qc9pV5xlRyF YalQoLXPn9wklkYMbl2zBQAXnDgCy3JWa07tjCIMelieKQNzsCkTHq3iPpuF/IeL+q8o0AtxizK/ SeKLVc3VXH9F6L3pIKFud0UwvFD2Phea8OhWkTsRdz9kQTKXgW2ScIhEqea9w04jY/7bOJJB9JzQ 75beIS3inuKD7r/Ynf2VJzI+AGY0Zkyq48Pmjx9yGBuMId0T4o8K4pSfQiWc5NLfLP6Jz7IzAUHW +r+9X/8p84IA5YNMeWYommfxjwHl6r0R4UOQaA2hseoq+Tqf6B6lfuWYCrZl7u8D/VYvyYWlImWg G3jJyRUwDKAyZ6/hTdGU7mlcRPMjAvg4CyWQCp9CLT4JziRxEaoQWbKQLDcVIGMqmytqujbuZBtl hR1v571uD7daAW8iKPhjkaBjAALa7kmzDIS8DY7YuMAmvV7stzBW8q/eLakmN9UWnlmpDHeCEmuj tjXhDIONv7j63So8W3B5umRJMD8eM4rC0/9Pu1e2BVlPc6J5Dgo1ZGCKmdtb8zzv0Ea7xlc2ZLU+ lqdiYR6DgsEH6gvjLzYK491yQMCbC9l9lOwhLHTGrtHsXKZyM4Puid3ODAkHlMZy4D9feWakVhpS DmB7w6ikflbPvsx200M9FMbXkcXkT6LMFmye4D8uCaooPYJDrBLVFi9gbAXtRj8WJ2+hRefzG5+N pEUUTCf3tuiV """)) def FakeWindowsPFX(self, filename): """Write out a fake windows certificate + private key file.""" # Generated using: # makecert.exe -r -sv fake.pvk -n "CN=fakeco" fake.cer (password: secret) # pvk2pfx.exe -pvk fake.pvk -spc fake.cer -pfx fake.pfx -po obscure self.write(filename, base64.b64decode(""" MIIGqgIBAzCCBmYGCSqGSIb3DQEHAaCCBlcEggZTMIIGTzCCA8AGCSqGSIb3DQEHAaCCA7EEggOt MIIDqTCCA6UGCyqGSIb3DQEMCgECoIICtjCCArIwHAYKKoZIhvcNAQwBAzAOBAjtSpL9hCNo9AIC B9AEggKQr3Jg5t3vBCYsoXK/i19qbrGoP0SVBBT9/PHEtHCw4bSwPFTD8xKLcaVwh4pNbg+ij8Wc QwGKLJ5lKItIs195qrJiIZ2vNM3ogF9S1ERhLET/fMkF1IaVAhq0gUQVBm2ivFZcMOfRQ9lIoJIg 2HqZCV9kvRHoxQLKEcdIt6tvTGGuWkoqH4fbbXwvYYHLKR/x/uX5TdUlu5TAim8uWt7bOOHQxh+g of3jDw4cvptPfZA1BjigMQZu0WGLCANfMnNORnLN2Qj7lQntmJsuDLYtUJlW3lLNN+hJQJTc+El6 gXzd786pguhFB9W5SU/ne/2c2cRzn5A5x5Wm3qNMyjIi0abcvTeBheImsE2UlzsttWClQJl8mNc1 oMtq4lv2bBfFGQjECQuYhy9jBKwH7kcNLzyGx1J7L9yzplmoqpEqPD7OOgKJLKLAFQ9S3cN9HMlV 7XSomWw5Pl/hyoyhsR7cIkkddWurdAkR1JHkwYUhQdpEI/KDbBx2BrlmmC87IpRPFAL010Q5GXMm aOXBIxMkUy9c+kmG2lHox2pl6oyajGHkzS3rAjNM8be071wBdHiMFDDs81tBjFgkgHFJj3YGES/s MnksaCkczoUSekM91p+vxLhtscGSzf/WI7GaJp1ZvzN9KyUYNgvkEZPTJErewzs/Bd3uhDBVjPlp sm+6ldkLwUvuAkLRWeP8qaXb9tY11gIGS8kHmGc6p9JiZCGDRv9jlL5zdyATNgYgRHhmFzwmecSz hJCs43NymvaSJ23XuvaaWJR646vwZWtcq5+nyjtnMLaO4venW77LNcw/yqGc1GXx4xVtvaJUI+mg Wqw6DPXwH5n/6OJWX6j15KJyK5a+tav2bvvB++zKpIFvswExgdswEwYJKoZIhvcNAQkVMQYEBAEA AAAwXQYJKwYBBAGCNxEBMVAeTgBNAGkAYwByAG8AcwBvAGYAdAAgAFMAdAByAG8AbgBnACAAQwBy AHkAcAB0AG8AZwByAGEAcABoAGkAYwAgAFAAcgBvAHYAaQBkAGUAcjBlBgkqhkiG9w0BCRQxWB5W AFAAdgBrAFQAbQBwADoANwBiAGMANgAxADQAZAA0AC0AYwA1AGUAZAAtADQANgBiADQALQBhADgA MgBmAC0AMwA4ADQAZQA1ADYAZgA5ADQAOABjAGEwggKHBgkqhkiG9w0BBwagggJ4MIICdAIBADCC Am0GCSqGSIb3DQEHATAcBgoqhkiG9w0BDAEGMA4ECOEFTlt71zU8AgIH0ICCAkDmOka8iLOM78ox x3bpLmpyG3SzcyGCNCRGZgf0jkJNT9ZS87IlGQ/S8TWYmXMnDJFZ6eNjV0uMU7hCstnkjqMXEI8O bJ1S6iIhEsezwY+c0hkfmHlHztInSAt6MYxqe/iLzVtWssqtHX+yUzrsHtFCRRkojqY/yvQP7DFU lQf7meuUceCF1QnU533AWQPcwwF5NVjoxCvEtaPAbIF4uG1C2luKawcwV9SllPLGllaoDgZkKSU6 PytuWg4pfCiM6JjAHeJoHWXi8CMZXxq7IboB7xfxZal3Gk1mJrqq9JcIISPVy3WymgfEkI2z1MFD B1qjYeA3ZaJ8CYe1ppHcaPuySZEoeMQL1K7AM8xa5tyQO9slvkwFMbur8ip0dWjEnD5h1Y8EnGpQ B2ec4P71Xr8I17V4t+uvdK0dqM6OegJvUQeSZWobwzFLpCvgHawbenL0KjPFMuOIXf8h19kjOw9D /PQo86KU/YADOSHSqOxQ9y+KeP46szCbI80XTcM5P20yPkE7qHot7jjusQR0h/7HqublR8Ex29dc 2LDpa1/LPdXGRNld8Q+JTjuHSas+CouuzVombf4oRLFO7Ycl3vdAw+uka3iweHy7UPKksxG7cQ7u hIK8U2W3lWubFhm7ymTU8DIWVKsC0sBusEFRKdz/4IsyJNJLGEgUbbOmIeRdTh/eD1GS8Tk/vQJn 22ThfPQsW16idB4eFnvPsi8FQ9Ba8ZgH6DqI/O5USNkR8C57oq9gGcHridSIQTN7k+nRW3owOzAf MAcGBSsOAwIaBBSplrQz2ypA7MX0qzq5MkSiRQhmtwQUZyfmXRh64tnnJN6H63+L1fRiqWMCAgfQ """)) def match_visible(self, str1, str2): """Returns true if the strings look the same. Args: str1: First string to compare. str2: Seconds string to compare. Returns: True if the strings are the same, after stripping trailing whitespace from lines. That is, if they look them same when printed to a terminal. """ # Add a newline at end of the strings, in case strings have trailing # whitespace but no newline at the end. str1 = re.sub('[ \t\r]*\n', '\n', str1 + '\n') str2 = re.sub('[ \t\r]*\n', '\n', str2 + '\n') return str1 == str2 def WriteSConscript(self, filename, function, python_paths=None): """Writes a SConscript which will call the function. Args: filename: Destination filename. function: Function to call from SConscript. This will be passed the globals() dict from the SConscript. python_paths: List of additional python paths to include in sys.path for SConscript. If the function needs access to SCons functions or variables, it should get them from the passed globals dict: def MySConscript(scons_globals): Environment = scons_globals['Environment'] ... Returns: Passthrough return from self.write(). """ if python_paths is None: python_paths = [] func_path, func_file = os.path.split(function.func_code.co_filename) python_paths += [ # Directory containing the module with the function to call func_path, # Directory containing THIS module, since the module calling it most # likely imports it, and the path to the TestCommon module, since this # file imports it. os.path.dirname(__file__), os.path.dirname(TestCommon.__file__), ] data = ('# SConscript file ' 'automatically created by TestFramework.WriteSConscript().\n' 'import sys\n') for p in python_paths: # Need to turn backslashes into forward-slashes, since we're writing a # string into a python source file. (Could alternately double-up the # backslashes.) data += 'sys.path.append("%s")\n' % p.replace('\\', '/') data += 'from %s import %s\n%s(globals())\n' % ( os.path.splitext(func_file)[0], function.__name__, function.__name__ ) return self.write(filename, data)
gpl-2.0
AstroHuntsman/POCS
pocs/focuser/birger.py
1
16549
import io import re import serial import time import glob from pocs.focuser.focuser import AbstractFocuser # Birger adaptor serial numbers should be 5 digits serial_number_pattern = re.compile('^\d{5}$') # Error codes should be 'ERR' followed by 1-2 digits error_pattern = re.compile('(?<=ERR)\d{1,2}') error_messages = ('No error', 'Unrecognised command', 'Lens is in manual focus mode', 'No lens connected', 'Lens distance stop error', 'Aperture not initialised', 'Invalid baud rate specified', 'Reserved', 'Reserved', 'A bad parameter was supplied to the command', 'XModem timeout', 'XModem error', 'XModem unlock code incorrect', 'Not used', 'Invalid port', 'Licence unlock failure', 'Invalid licence file', 'Invalid library file', 'Reserved', 'Reserved', 'Not used', 'Library not ready for lens communications', 'Library not ready for commands', 'Command not licensed', 'Invalid focus range in memory. Try relearning the range', 'Distance stops not supported by the lens') class Focuser(AbstractFocuser): """ Focuser class for control of a Canon DSLR lens via a Birger Engineering Canon EF-232 adapter """ # Class variable to cache the device node scanning results _birger_nodes = None # Class variable to store the device nodes already in use. Prevents scanning known Birgers & # acts as a check against Birgers assigned to incorrect ports. _assigned_nodes = [] def __init__(self, name='Birger Focuser', model='Canon EF-232', initial_position=None, dev_node_pattern='/dev/tty.USA49WG*.?', *args, **kwargs): super().__init__(name=name, model=model, *args, **kwargs) self.logger.debug('Initialising Birger focuser') if serial_number_pattern.match(self.port): # Have been given a serial number if self._birger_nodes is None: # No cached device nodes scanning results, need to scan. self._birger_nodes = {} # Find nodes matching pattern device_nodes = glob.glob(dev_node_pattern) # Remove nodes already assigned to other Birger objects device_nodes = [node for node in device_nodes if node not in self._assigned_nodes] for device_node in device_nodes: try: serial_number = self.connect(device_node) self._birger_nodes[serial_number] = device_node except (serial.SerialException, serial.SerialTimeoutException, AssertionError): # No birger on this node. pass finally: self._serial_port.close() # Search in cached device node scanning results for serial number try: device_node = self._birger_nodes[self.port] except KeyError: self.logger.critical("Could not find {} ({})!".format(self.name, self.port)) return self.port = device_node # Check that this node hasn't already been assigned to another Birgers if self.port in self._assigned_nodes: self.logger.critical("Device node {} already in use!".format(self.port)) return self.connect(self.port) self._assigned_nodes.append(self.port) self._initialise if initial_position: self.position = initial_position ################################################################################################## # Properties ################################################################################################## @property def is_connected(self): """ Checks status of serial port to determine if connected. """ connected = False if self._serial_port: connected = self._serial_port.isOpen() return connected @AbstractFocuser.position.getter def position(self): """ Returns current focus position in the lens focus encoder units """ response = self._send_command('pf', response_length=1) return int(response[0].rstrip()) @property def min_position(self): """ Returns position of close limit of focus travel, in encoder units """ return self._min_position @property def max_position(self): """ Returns position of far limit of focus travel, in encoder units """ return self._max_position @property def lens_info(self): """ Return basic lens info (e.g. '400mm,f28' for a 400 mm f/2.8 lens) """ return self._lens_info @property def library_version(self): """ Returns the version string of the Birger adaptor library (firmware). """ return self._library_version @property def hardware_version(self): """ Returns the hardware version of the Birger adaptor """ return self._hardware_version ################################################################################################## # Public Methods ################################################################################################## def connect(self, port): try: # Configure serial port. # Settings copied from Bob Abraham's birger.c self._serial_port = serial.Serial() self._serial_port.port = port self._serial_port.baudrate = 115200 self._serial_port.bytesize = serial.EIGHTBITS self._serial_port.parity = serial.PARITY_NONE self._serial_port.stopbits = serial.STOPBITS_ONE self._serial_port.timeout = 2.0 self._serial_port.xonxoff = False self._serial_port.rtscts = False self._serial_port.dsrdtr = False self._serial_port.write_timeout = None self._inter_byte_timeout = None # Establish connection self._serial_port.open() except serial.SerialException as err: self._serial_port = None self.logger.critical('Could not open {}!'.format(port)) raise err time.sleep(2) # Want to use a io.TextWrapper in order to have a readline() method with universal newlines # (Birger sends '\r', not '\n'). The line_buffering option causes an automatic flush() when # a write contains a newline character. self._serial_io = io.TextIOWrapper(io.BufferedRWPair(self._serial_port, self._serial_port), newline='\r', encoding='ascii', line_buffering=True) self.logger.debug('Established serial connection to {} on {}.'.format(self.name, port)) # Set 'verbose' and 'legacy' response modes. The response from this depends on # what the current mode is... but after a power cycle it should be 'rm1,0', 'OK' try: self._send_command('rm1,0', response_length=0) except AssertionError as err: self.logger.critical('Error communicating with {} on {}!'.format(self.name, port)) raise err # Return serial number return send_command('sn', response_length=1)[0].rstrip() def move_to(self, position): """ Move the focus to a specific position in lens encoder units. Does not do any checking of the requested position but will warn if the lens reports hitting a stop. Returns the actual position moved to in lens encoder units. """ response = self._send_command('fa{:d}'.format(int(position)), response_length=1) if response[0][:4] != 'DONE': self.logger.error("{} got response '{}', expected 'DONENNNNN,N'!".format(self, response[0].rstrip())) else: r = response[0][4:].rstrip() self.logger.debug("Moved to {} encoder units".format(r[:-2])) if r[-1] == '1': self.logger.warning('{} reported hitting a focus stop'.format(self)) return int(r[:-2]) def move_by(self, increment): """ Move the focus to a specific position in lens encoder units. Does not do any checking of the requested increment but will warn if the lens reports hitting a stop. Returns the actual distance moved in lens encoder units. """ response = self._send_command('mf{:d}'.format(increment), response_length=1) if response[0][:4] != 'DONE': self.logger.error("{} got response '{}', expected 'DONENNNNN,N'!".format(self, response[0].rstrip())) else: r = response[0][4:].rstrip() self.logger.debug("Moved by {} encoder units".format(r[:-2])) if r[-1] == '1': self.logger.warning('{} reported hitting a focus stop'.format(self)) return int(r[:-2]) ################################################################################################## # Private Methods ################################################################################################## def _send_command(self, command, response_length=None, ignore_response=False): """ Sends a command to the Birger adaptor and retrieves the response. Args: command (string): command string to send (without newline), e.g. 'fa1000', 'pf' response length (integer, optional, default=None): number of lines of response expected. For most commands this should be 0 or 1. If None readlines() will be called to capture all responses. As this will block until the timeout expires it should only be used if the number of lines expected is not known (e.g. 'ds' command). Returns: list: possibly empty list containing the '\r' terminated lines of the response from the adaptor. """ if not self.is_connected: self.logger.critical("Attempt to send command to {} when not connected!".format(self)) return # Clear the input buffer in case there's anything left over in there. self._serial_port.reset_input_buffer() # Send command self._serial_io.write(command + '\r') if ignore_response: return # In verbose mode adaptor will first echo the command echo = self._serial_io.readline().rstrip() assert echo == command, self.logger.warning("echo != command: {} != {}".format(echo, command)) # Adaptor should then send 'OK', even if there was an error. ok = self._serial_io.readline().rstrip() assert ok == 'OK' # Depending on which command was sent there may or may not be any further # response. response = [] if response_length == 0: # Not expecting any further response. Should check the buffer anyway in case an error # message has been sent. if self._serial_port.in_waiting: response.append(self._serial_io.readline()) elif response_length > 0: # Expecting some number of lines of response. Attempt to read that many lines. for i in range(response_length): response.append(self._serial_io.readline()) else: # Don't know what to expect. Call readlines() to get whatever is there. response.append(self._serial_io.readlines()) # Check for an error message in response if response: # Not an empty list. error_match = error_pattern.match(response[0]) if error_match: # Got an error message! Translate it. try: error_message = error_messages[int(error_match.group())] self.logger.error("{} returned error message '{}'!".format(self, error_message)) except Exception: self.logger.error("Unknown error '{}' from {}!".format(error_match.group(), self)) return response def _initialise(self): # Get serial number. Note, this is the serial number of the Birger adaptor, # *not* the attached lens (which would be more useful). Accessible as self.uid self._get_serial_number() # Get the version string of the adaptor software libray. Accessible as self.library_version self._get_library_version() # Get the hardware version of the adaptor. Accessible as self.hardware_version self._get_hardware_version() # Get basic lens info (e.g. '400mm,f28' for a 400 mm, f/2.8 lens). Accessible as self.lens_info self._get_lens_info() # Initialise the aperture motor. This also has the side effect of fully opening the iris. self._initialise_aperture() # Initalise focus. First move the focus to the close stop. self._move_zero() # Then reset the focus encoder counts to 0 self._zero_encoder() self._min_position = 0 # Calibrate the focus with the 'Learn Absolute Focus Range' command self._learn_focus_range() # Finally move the focus to the far stop (close to where we'll want it) and record position self._max_position = self._move_inf() self.logger.info('\t\t\t {} initialised'.format(self)) def _get_serial_number(self): response = self._send_command('sn', response_length=1) self._serial_number = response[0].rstrip() self.logger.debug("Got serial number {} for {} on {}".format(self.uid, self.name, self.port)) def _get_library_version(self): response = self._send_command('lv', response_length=1) self._library_version = response[0].rstrip() self.logger.debug("Got library version '{}' for {} on {}".format(self.library_version, self.name, self.port)) def _get_hardware_version(self): response = self._send_command('hv', response_length=1) self._hardware_version = response[0].rstrip() self.logger.debug("Got hardware version {} for {} on {}".format(self.hardware_version, self.name, self.port)) def _get_lens_info(self): response = self._send_command('id', response_length=1) self._lens_info = response[0].rstrip() self.logger.debug("Got lens info '{}' for {} on {}".format(self.lens_info, self.name, self.port)) def _initialise_aperture(self): self.logger.debug('Initialising aperture motor') response = self._send_command('in', response_length=1) if response[0].rstrip() != 'DONE': self.logger.error("{} got response '{}', expected 'DONE'!".format(self, response[0].rstrip())) def _move_zero(self): response = self._send_command('mz', response_length=1) if response[0][:4] != 'DONE': self.logger.error("{} got response '{}', expected 'DONENNNNN,1'!".format(self, response[0].rstrip())) else: r = response[0][4:].rstrip() self.logger.debug("Moved {} encoder units to close stop".format(r[:-2])) return int(r[:-2]) def _zero_encoder(self): self.logger.debug('Setting focus encoder zero point') self._send_command('sf0', response_length=0) def _learn_focus_range(self): self.logger.debug('Learning absolute focus range') response = self._send_command('la', response_length=1) if response[0].rstrip() != 'DONE:LA': self.logger.error("{} got response '{}', expected 'DONE:LA'!".format(self, response[0].rstrip())) def _move_inf(self): response = self._send_command('mi', response_length=1) if response[0][:4] != 'DONE': self.logger.error("{} got response '{}', expected 'DONENNNNN,1'!".format(self, response[0].rstrip())) else: r = response[0][4:].rstrip() self.logger.debug("Moved {} encoder units to far stop".format(r[:-2])) return int(r[:-2])
mit
edmorley/django
tests/model_fields/test_booleanfield.py
62
4543
from django import forms from django.core.exceptions import ValidationError from django.db import IntegrityError, models, transaction from django.test import SimpleTestCase, TestCase from .models import BooleanModel, FksToBooleans, NullBooleanModel class BooleanFieldTests(TestCase): def _test_get_prep_value(self, f): self.assertIs(f.get_prep_value(True), True) self.assertIs(f.get_prep_value('1'), True) self.assertIs(f.get_prep_value(1), True) self.assertIs(f.get_prep_value(False), False) self.assertIs(f.get_prep_value('0'), False) self.assertIs(f.get_prep_value(0), False) self.assertIsNone(f.get_prep_value(None)) def _test_to_python(self, f): self.assertIs(f.to_python(1), True) self.assertIs(f.to_python(0), False) def test_booleanfield_get_prep_value(self): self._test_get_prep_value(models.BooleanField()) def test_nullbooleanfield_get_prep_value(self): self._test_get_prep_value(models.NullBooleanField()) def test_booleanfield_to_python(self): self._test_to_python(models.BooleanField()) def test_nullbooleanfield_to_python(self): self._test_to_python(models.NullBooleanField()) def test_booleanfield_choices_blank(self): """ BooleanField with choices and defaults doesn't generate a formfield with the blank option (#9640, #10549). """ choices = [(1, 'Si'), (2, 'No')] f = models.BooleanField(choices=choices, default=1, null=False) self.assertEqual(f.formfield().choices, choices) def test_nullbooleanfield_formfield(self): f = models.NullBooleanField() self.assertIsInstance(f.formfield(), forms.NullBooleanField) def test_return_type(self): b = BooleanModel.objects.create(bfield=True) b.refresh_from_db() self.assertIs(b.bfield, True) b2 = BooleanModel.objects.create(bfield=False) b2.refresh_from_db() self.assertIs(b2.bfield, False) b3 = NullBooleanModel.objects.create(nbfield=True) b3.refresh_from_db() self.assertIs(b3.nbfield, True) b4 = NullBooleanModel.objects.create(nbfield=False) b4.refresh_from_db() self.assertIs(b4.nbfield, False) # When an extra clause exists, the boolean conversions are applied with # an offset (#13293). b5 = BooleanModel.objects.all().extra(select={'string_col': 'string'})[0] self.assertNotIsInstance(b5.pk, bool) def test_select_related(self): """ Boolean fields retrieved via select_related() should return booleans. """ bmt = BooleanModel.objects.create(bfield=True) bmf = BooleanModel.objects.create(bfield=False) nbmt = NullBooleanModel.objects.create(nbfield=True) nbmf = NullBooleanModel.objects.create(nbfield=False) m1 = FksToBooleans.objects.create(bf=bmt, nbf=nbmt) m2 = FksToBooleans.objects.create(bf=bmf, nbf=nbmf) # select_related('fk_field_name') ma = FksToBooleans.objects.select_related('bf').get(pk=m1.id) self.assertIs(ma.bf.bfield, True) self.assertIs(ma.nbf.nbfield, True) # select_related() mb = FksToBooleans.objects.select_related().get(pk=m1.id) mc = FksToBooleans.objects.select_related().get(pk=m2.id) self.assertIs(mb.bf.bfield, True) self.assertIs(mb.nbf.nbfield, True) self.assertIs(mc.bf.bfield, False) self.assertIs(mc.nbf.nbfield, False) def test_null_default(self): """ A BooleanField defaults to None, which isn't a valid value (#15124). """ boolean_field = BooleanModel._meta.get_field('bfield') self.assertFalse(boolean_field.has_default()) b = BooleanModel() self.assertIsNone(b.bfield) with transaction.atomic(): with self.assertRaises(IntegrityError): b.save() nb = NullBooleanModel() self.assertIsNone(nb.nbfield) nb.save() # no error class ValidationTest(SimpleTestCase): def test_boolean_field_doesnt_accept_empty_input(self): f = models.BooleanField() with self.assertRaises(ValidationError): f.clean(None, None) def test_nullbooleanfield_blank(self): """ NullBooleanField shouldn't throw a validation error when given a value of None. """ nullboolean = NullBooleanModel(nbfield=None) nullboolean.full_clean()
bsd-3-clause
NL66278/odoo
addons/website_gengo/__init__.py
316
1024
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2013-Today OpenERP S.A. (<http://www.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 controllers import models
agpl-3.0
Dhivyap/ansible
lib/ansible/modules/cloud/amazon/ec2_vpc_net_info.py
12
11676
#!/usr/bin/python # # This is a 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 Ansible 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 General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this library. If not, see <http://www.gnu.org/licenses/>. ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['stableinterface'], 'supported_by': 'core'} DOCUMENTATION = ''' --- module: ec2_vpc_net_info short_description: Gather information about ec2 VPCs in AWS description: - Gather information about ec2 VPCs in AWS - This module was called C(ec2_vpc_net_facts) before Ansible 2.9. The usage did not change. version_added: "2.1" author: "Rob White (@wimnat)" requirements: - boto3 - botocore options: vpc_ids: description: - A list of VPC IDs that exist in your account. version_added: "2.5" filters: description: - A dict of filters to apply. Each dict item consists of a filter key and a filter value. See U(https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_DescribeVpcs.html) for possible filters. extends_documentation_fragment: - aws - ec2 ''' EXAMPLES = ''' # Note: These examples do not set authentication details, see the AWS Guide for details. # Gather information about all VPCs - ec2_vpc_net_info: # Gather information about a particular VPC using VPC ID - ec2_vpc_net_info: vpc_ids: vpc-00112233 # Gather information about any VPC with a tag key Name and value Example - ec2_vpc_net_info: filters: "tag:Name": Example ''' RETURN = ''' vpcs: description: Returns an array of complex objects as described below. returned: success type: complex contains: id: description: The ID of the VPC (for backwards compatibility). returned: always type: str vpc_id: description: The ID of the VPC . returned: always type: str state: description: The state of the VPC. returned: always type: str tags: description: A dict of tags associated with the VPC. returned: always type: dict instance_tenancy: description: The instance tenancy setting for the VPC. returned: always type: str is_default: description: True if this is the default VPC for account. returned: always type: bool cidr_block: description: The IPv4 CIDR block assigned to the VPC. returned: always type: str classic_link_dns_supported: description: True/False depending on attribute setting for classic link DNS support. returned: always type: bool classic_link_enabled: description: True/False depending on if classic link support is enabled. returned: always type: bool enable_dns_hostnames: description: True/False depending on attribute setting for DNS hostnames support. returned: always type: bool enable_dns_support: description: True/False depending on attribute setting for DNS support. returned: always type: bool ipv6_cidr_block_association_set: description: An array of IPv6 cidr block association set information. returned: always type: complex contains: association_id: description: The association ID returned: always type: str ipv6_cidr_block: description: The IPv6 CIDR block that is associated with the VPC. returned: always type: str ipv6_cidr_block_state: description: A hash/dict that contains a single item. The state of the cidr block association. returned: always type: dict contains: state: description: The CIDR block association state. returned: always type: str ''' import traceback from ansible.module_utils._text import to_native from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.ec2 import ( boto3_conn, ec2_argument_spec, get_aws_connection_info, AWSRetry, HAS_BOTO3, boto3_tag_list_to_ansible_dict, camel_dict_to_snake_dict, ansible_dict_to_boto3_filter_list ) try: import botocore except ImportError: pass # caught by imported HAS_BOTO3 @AWSRetry.exponential_backoff() def describe_vpc_attr_with_backoff(connection, vpc_id, vpc_attribute): """ Describe VPC Attributes with AWSRetry backoff throttling support. connection : boto3 client connection object vpc_id : The VPC ID to pull attribute value from vpc_attribute : The VPC attribute to get the value from - valid options = enableDnsSupport or enableDnsHostnames """ return connection.describe_vpc_attribute(VpcId=vpc_id, Attribute=vpc_attribute) def describe_vpcs(connection, module): """ Describe VPCs. connection : boto3 client connection object module : AnsibleModule object """ # collect parameters filters = ansible_dict_to_boto3_filter_list(module.params.get('filters')) vpc_ids = module.params.get('vpc_ids') # init empty list for return vars vpc_info = list() vpc_list = list() # Get the basic VPC info try: response = connection.describe_vpcs(VpcIds=vpc_ids, Filters=filters) except botocore.exceptions.ClientError as e: module.fail_json(msg="Unable to describe VPCs {0}: {1}".format(vpc_ids, to_native(e)), exception=traceback.format_exc(), **camel_dict_to_snake_dict(e.response)) except botocore.exceptions.BotoCoreError as e: module.fail_json(msg="Unable to describe VPCs {0}: {1}".format(vpc_ids, to_native(e)), exception=traceback.format_exc()) # Loop through results and create a list of VPC IDs for vpc in response['Vpcs']: vpc_list.append(vpc['VpcId']) # We can get these results in bulk but still needs two separate calls to the API try: cl_enabled = connection.describe_vpc_classic_link(VpcIds=vpc_list) except botocore.exceptions.ClientError as e: if e.response["Error"]["Message"] == "The functionality you requested is not available in this region.": cl_enabled = {'Vpcs': [{'VpcId': vpc_id, 'ClassicLinkEnabled': False} for vpc_id in vpc_list]} else: module.fail_json(msg="Unable to describe if ClassicLink is enabled: {0}".format(to_native(e)), exception=traceback.format_exc(), **camel_dict_to_snake_dict(e.response)) except botocore.exceptions.BotoCoreError as e: module.fail_json(msg="Unable to describe if ClassicLink is enabled: {0}".format(to_native(e)), exception=traceback.format_exc()) try: cl_dns_support = connection.describe_vpc_classic_link_dns_support(VpcIds=vpc_list) except botocore.exceptions.ClientError as e: if e.response["Error"]["Message"] == "The functionality you requested is not available in this region.": cl_dns_support = {'Vpcs': [{'VpcId': vpc_id, 'ClassicLinkDnsSupported': False} for vpc_id in vpc_list]} else: module.fail_json(msg="Unable to describe if ClassicLinkDns is supported: {0}".format(to_native(e)), exception=traceback.format_exc(), **camel_dict_to_snake_dict(e.response)) except botocore.exceptions.BotoCoreError as e: module.fail_json(msg="Unable to describe if ClassicLinkDns is supported: {0}".format(to_native(e)), exception=traceback.format_exc()) # Loop through the results and add the other VPC attributes we gathered for vpc in response['Vpcs']: error_message = "Unable to describe VPC attribute {0}: {1}" # We have to make two separate calls per VPC to get these attributes. try: dns_support = describe_vpc_attr_with_backoff(connection, vpc['VpcId'], 'enableDnsSupport') except botocore.exceptions.ClientError as e: module.fail_json(msg=error_message.format('enableDnsSupport', to_native(e)), exception=traceback.format_exc(), **camel_dict_to_snake_dict(e.response)) except botocore.exceptions.BotoCoreError as e: module.fail_json(msg=error_message.format('enableDnsSupport', to_native(e)), exception=traceback.format_exc()) try: dns_hostnames = describe_vpc_attr_with_backoff(connection, vpc['VpcId'], 'enableDnsHostnames') except botocore.exceptions.ClientError as e: module.fail_json(msg=error_message.format('enableDnsHostnames', to_native(e)), exception=traceback.format_exc(), **camel_dict_to_snake_dict(e.response)) except botocore.exceptions.BotoCoreError as e: module.fail_json(msg=error_message.format('enableDnsHostnames', to_native(e)), exception=traceback.format_exc()) # loop through the ClassicLink Enabled results and add the value for the correct VPC for item in cl_enabled['Vpcs']: if vpc['VpcId'] == item['VpcId']: vpc['ClassicLinkEnabled'] = item['ClassicLinkEnabled'] # loop through the ClassicLink DNS support results and add the value for the correct VPC for item in cl_dns_support['Vpcs']: if vpc['VpcId'] == item['VpcId']: vpc['ClassicLinkDnsSupported'] = item['ClassicLinkDnsSupported'] # add the two DNS attributes vpc['EnableDnsSupport'] = dns_support['EnableDnsSupport'].get('Value') vpc['EnableDnsHostnames'] = dns_hostnames['EnableDnsHostnames'].get('Value') # for backwards compatibility vpc['id'] = vpc['VpcId'] vpc_info.append(camel_dict_to_snake_dict(vpc)) # convert tag list to ansible dict vpc_info[-1]['tags'] = boto3_tag_list_to_ansible_dict(vpc.get('Tags', [])) module.exit_json(vpcs=vpc_info) def main(): argument_spec = ec2_argument_spec() argument_spec.update(dict( vpc_ids=dict(type='list', default=[]), filters=dict(type='dict', default={}) )) module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=True) if module._name == 'ec2_vpc_net_facts': module.deprecate("The 'ec2_vpc_net_facts' module has been renamed to 'ec2_vpc_net_info'", version='2.13') if not HAS_BOTO3: module.fail_json(msg='boto3 and botocore are required for this module') region, ec2_url, aws_connect_params = get_aws_connection_info(module, boto3=True) connection = boto3_conn(module, conn_type='client', resource='ec2', region=region, endpoint=ec2_url, **aws_connect_params) describe_vpcs(connection, module) if __name__ == '__main__': main()
gpl-3.0
queria/my-tempest
tempest/api/compute/servers/test_list_server_filters.py
1
13183
# Copyright 2012 OpenStack Foundation # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from tempest.api.compute import base from tempest.api import utils from tempest.common.utils import data_utils from tempest import config from tempest import exceptions from tempest import test CONF = config.CONF class ListServerFiltersTestJSON(base.BaseV2ComputeTest): @classmethod def resource_setup(cls): cls.set_network_resources(network=True, subnet=True, dhcp=True) super(ListServerFiltersTestJSON, cls).resource_setup() cls.client = cls.servers_client # Check to see if the alternate image ref actually exists... images_client = cls.images_client resp, images = images_client.list_images() if cls.image_ref != cls.image_ref_alt and \ any([image for image in images if image['id'] == cls.image_ref_alt]): cls.multiple_images = True else: cls.image_ref_alt = cls.image_ref # Do some sanity checks here. If one of the images does # not exist, fail early since the tests won't work... try: cls.images_client.get_image(cls.image_ref) except exceptions.NotFound: raise RuntimeError("Image %s (image_ref) was not found!" % cls.image_ref) try: cls.images_client.get_image(cls.image_ref_alt) except exceptions.NotFound: raise RuntimeError("Image %s (image_ref_alt) was not found!" % cls.image_ref_alt) cls.s1_name = data_utils.rand_name(cls.__name__ + '-instance') resp, cls.s1 = cls.create_test_server(name=cls.s1_name, wait_until='ACTIVE') cls.s2_name = data_utils.rand_name(cls.__name__ + '-instance') resp, cls.s2 = cls.create_test_server(name=cls.s2_name, image_id=cls.image_ref_alt, wait_until='ACTIVE') cls.s3_name = data_utils.rand_name(cls.__name__ + '-instance') resp, cls.s3 = cls.create_test_server(name=cls.s3_name, flavor=cls.flavor_ref_alt, wait_until='ACTIVE') if (CONF.service_available.neutron and CONF.compute.allow_tenant_isolation): network = cls.isolated_creds.get_primary_network() cls.fixed_network_name = network['name'] else: cls.fixed_network_name = CONF.compute.fixed_network_name @utils.skip_unless_attr('multiple_images', 'Only one image found') @test.attr(type='gate') def test_list_servers_filter_by_image(self): # Filter the list of servers by image params = {'image': self.image_ref} resp, body = self.client.list_servers(params) servers = body['servers'] self.assertIn(self.s1['id'], map(lambda x: x['id'], servers)) self.assertNotIn(self.s2['id'], map(lambda x: x['id'], servers)) self.assertIn(self.s3['id'], map(lambda x: x['id'], servers)) @test.attr(type='gate') def test_list_servers_filter_by_flavor(self): # Filter the list of servers by flavor params = {'flavor': self.flavor_ref_alt} resp, body = self.client.list_servers(params) servers = body['servers'] self.assertNotIn(self.s1['id'], map(lambda x: x['id'], servers)) self.assertNotIn(self.s2['id'], map(lambda x: x['id'], servers)) self.assertIn(self.s3['id'], map(lambda x: x['id'], servers)) @test.attr(type='gate') def test_list_servers_filter_by_server_name(self): # Filter the list of servers by server name params = {'name': self.s1_name} resp, body = self.client.list_servers(params) servers = body['servers'] self.assertIn(self.s1_name, map(lambda x: x['name'], servers)) self.assertNotIn(self.s2_name, map(lambda x: x['name'], servers)) self.assertNotIn(self.s3_name, map(lambda x: x['name'], servers)) @test.attr(type='gate') def test_list_servers_filter_by_server_status(self): # Filter the list of servers by server status params = {'status': 'active'} resp, body = self.client.list_servers(params) servers = body['servers'] self.assertIn(self.s1['id'], map(lambda x: x['id'], servers)) self.assertIn(self.s2['id'], map(lambda x: x['id'], servers)) self.assertIn(self.s3['id'], map(lambda x: x['id'], servers)) @test.attr(type='gate') def test_list_servers_filter_by_shutoff_status(self): # Filter the list of servers by server shutoff status params = {'status': 'shutoff'} self.client.stop(self.s1['id']) self.client.wait_for_server_status(self.s1['id'], 'SHUTOFF') resp, body = self.client.list_servers(params) self.client.start(self.s1['id']) self.client.wait_for_server_status(self.s1['id'], 'ACTIVE') servers = body['servers'] self.assertIn(self.s1['id'], map(lambda x: x['id'], servers)) self.assertNotIn(self.s2['id'], map(lambda x: x['id'], servers)) self.assertNotIn(self.s3['id'], map(lambda x: x['id'], servers)) @test.attr(type='gate') def test_list_servers_filter_by_limit(self): # Verify only the expected number of servers are returned params = {'limit': 1} resp, servers = self.client.list_servers(params) # when _interface='xml', one element for servers_links in servers self.assertEqual(1, len([x for x in servers['servers'] if 'id' in x])) @test.attr(type='gate') def test_list_servers_filter_by_zero_limit(self): # Verify only the expected number of servers are returned params = {'limit': 0} resp, servers = self.client.list_servers(params) self.assertEqual(0, len(servers['servers'])) @test.attr(type='gate') def test_list_servers_filter_by_exceed_limit(self): # Verify only the expected number of servers are returned params = {'limit': 100000} resp, servers = self.client.list_servers(params) resp, all_servers = self.client.list_servers() self.assertEqual(len([x for x in all_servers['servers'] if 'id' in x]), len([x for x in servers['servers'] if 'id' in x])) @utils.skip_unless_attr('multiple_images', 'Only one image found') @test.attr(type='gate') def test_list_servers_detailed_filter_by_image(self): # Filter the detailed list of servers by image params = {'image': self.image_ref} resp, body = self.client.list_servers_with_detail(params) servers = body['servers'] self.assertIn(self.s1['id'], map(lambda x: x['id'], servers)) self.assertNotIn(self.s2['id'], map(lambda x: x['id'], servers)) self.assertIn(self.s3['id'], map(lambda x: x['id'], servers)) @test.attr(type='gate') def test_list_servers_detailed_filter_by_flavor(self): # Filter the detailed list of servers by flavor params = {'flavor': self.flavor_ref_alt} resp, body = self.client.list_servers_with_detail(params) servers = body['servers'] self.assertNotIn(self.s1['id'], map(lambda x: x['id'], servers)) self.assertNotIn(self.s2['id'], map(lambda x: x['id'], servers)) self.assertIn(self.s3['id'], map(lambda x: x['id'], servers)) @test.attr(type='gate') def test_list_servers_detailed_filter_by_server_name(self): # Filter the detailed list of servers by server name params = {'name': self.s1_name} resp, body = self.client.list_servers_with_detail(params) servers = body['servers'] self.assertIn(self.s1_name, map(lambda x: x['name'], servers)) self.assertNotIn(self.s2_name, map(lambda x: x['name'], servers)) self.assertNotIn(self.s3_name, map(lambda x: x['name'], servers)) @test.attr(type='gate') def test_list_servers_detailed_filter_by_server_status(self): # Filter the detailed list of servers by server status params = {'status': 'active'} resp, body = self.client.list_servers_with_detail(params) servers = body['servers'] test_ids = [s['id'] for s in (self.s1, self.s2, self.s3)] self.assertIn(self.s1['id'], map(lambda x: x['id'], servers)) self.assertIn(self.s2['id'], map(lambda x: x['id'], servers)) self.assertIn(self.s3['id'], map(lambda x: x['id'], servers)) self.assertEqual(['ACTIVE'] * 3, [x['status'] for x in servers if x['id'] in test_ids]) @test.attr(type='gate') def test_list_servers_filtered_by_name_wildcard(self): # List all servers that contains '-instance' in name params = {'name': '-instance'} resp, body = self.client.list_servers(params) servers = body['servers'] self.assertIn(self.s1_name, map(lambda x: x['name'], servers)) self.assertIn(self.s2_name, map(lambda x: x['name'], servers)) self.assertIn(self.s3_name, map(lambda x: x['name'], servers)) # Let's take random part of name and try to search it part_name = self.s1_name[6:-1] params = {'name': part_name} resp, body = self.client.list_servers(params) servers = body['servers'] self.assertIn(self.s1_name, map(lambda x: x['name'], servers)) self.assertNotIn(self.s2_name, map(lambda x: x['name'], servers)) self.assertNotIn(self.s3_name, map(lambda x: x['name'], servers)) @test.attr(type='gate') def test_list_servers_filtered_by_name_regex(self): # list of regex that should match s1, s2 and s3 regexes = ['^.*\-instance\-[0-9]+$', '^.*\-instance\-.*$'] for regex in regexes: params = {'name': regex} resp, body = self.client.list_servers(params) servers = body['servers'] self.assertIn(self.s1_name, map(lambda x: x['name'], servers)) self.assertIn(self.s2_name, map(lambda x: x['name'], servers)) self.assertIn(self.s3_name, map(lambda x: x['name'], servers)) # Let's take random part of name and try to search it part_name = self.s1_name[-10:] params = {'name': part_name} resp, body = self.client.list_servers(params) servers = body['servers'] self.assertIn(self.s1_name, map(lambda x: x['name'], servers)) self.assertNotIn(self.s2_name, map(lambda x: x['name'], servers)) self.assertNotIn(self.s3_name, map(lambda x: x['name'], servers)) @test.attr(type='gate') def test_list_servers_filtered_by_ip(self): # Filter servers by ip # Here should be listed 1 server resp, self.s1 = self.client.get_server(self.s1['id']) ip = self.s1['addresses'][self.fixed_network_name][0]['addr'] params = {'ip': ip} resp, body = self.client.list_servers(params) servers = body['servers'] self.assertIn(self.s1_name, map(lambda x: x['name'], servers)) self.assertNotIn(self.s2_name, map(lambda x: x['name'], servers)) self.assertNotIn(self.s3_name, map(lambda x: x['name'], servers)) @test.skip_because(bug="1182883", condition=CONF.service_available.neutron) @test.attr(type='gate') def test_list_servers_filtered_by_ip_regex(self): # Filter servers by regex ip # List all servers filtered by part of ip address. # Here should be listed all servers resp, self.s1 = self.client.get_server(self.s1['id']) ip = self.s1['addresses'][self.fixed_network_name][0]['addr'][0:-3] params = {'ip': ip} resp, body = self.client.list_servers(params) servers = body['servers'] self.assertIn(self.s1_name, map(lambda x: x['name'], servers)) self.assertIn(self.s2_name, map(lambda x: x['name'], servers)) self.assertIn(self.s3_name, map(lambda x: x['name'], servers)) @test.attr(type='gate') def test_list_servers_detailed_limit_results(self): # Verify only the expected number of detailed results are returned params = {'limit': 1} resp, servers = self.client.list_servers_with_detail(params) self.assertEqual(1, len(servers['servers'])) class ListServerFiltersTestXML(ListServerFiltersTestJSON): _interface = 'xml'
apache-2.0
SnappleCap/oh-mainline
vendor/packages/zope.interface/src/zope/interface/tests/test_verify.py
22
4553
############################################################################## # # Copyright (c) 2001, 2002 Zope Foundation and Contributors. # All Rights Reserved. # # This software is subject to the provisions of the Zope Public License, # Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution. # THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED # WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS # FOR A PARTICULAR PURPOSE. # ############################################################################## """Interface Verify tests """ import doctest import unittest from zope.interface import Interface, implements, classImplements, Attribute from zope.interface.verify import verifyClass, verifyObject from zope.interface.exceptions import DoesNotImplement, BrokenImplementation from zope.interface.exceptions import BrokenMethodImplementation class Test(unittest.TestCase): def testNotImplemented(self): class C(object): pass class I(Interface): pass self.assertRaises(DoesNotImplement, verifyClass, I, C) classImplements(C, I) verifyClass(I, C) def testMissingAttr(self): class I(Interface): def f(): pass class C(object): implements(I) self.assertRaises(BrokenImplementation, verifyClass, I, C) C.f=lambda self: None verifyClass(I, C) def testMissingAttr_with_Extended_Interface(self): class II(Interface): def f(): pass class I(II): pass class C(object): implements(I) self.assertRaises(BrokenImplementation, verifyClass, I, C) C.f=lambda self: None verifyClass(I, C) def testWrongArgs(self): class I(Interface): def f(a): pass class C(object): def f(self, b): pass implements(I) # We no longer require names to match. #self.assertRaises(BrokenMethodImplementation, verifyClass, I, C) C.f=lambda self, a: None verifyClass(I, C) C.f=lambda self, **kw: None self.assertRaises(BrokenMethodImplementation, verifyClass, I, C) C.f=lambda self, a, *args: None verifyClass(I, C) C.f=lambda self, a, *args, **kw: None verifyClass(I, C) C.f=lambda self, *args: None verifyClass(I, C) def testExtraArgs(self): class I(Interface): def f(a): pass class C(object): def f(self, a, b): pass implements(I) self.assertRaises(BrokenMethodImplementation, verifyClass, I, C) C.f=lambda self, a: None verifyClass(I, C) C.f=lambda self, a, b=None: None verifyClass(I, C) def testNoVar(self): class I(Interface): def f(a, *args): pass class C(object): def f(self, a): pass implements(I) self.assertRaises(BrokenMethodImplementation, verifyClass, I, C) C.f=lambda self, a, *foo: None verifyClass(I, C) def testNoKW(self): class I(Interface): def f(a, **args): pass class C(object): def f(self, a): pass implements(I) self.assertRaises(BrokenMethodImplementation, verifyClass, I, C) C.f=lambda self, a, **foo: None verifyClass(I, C) def testModule(self): from zope.interface.tests.ifoo import IFoo from zope.interface.tests import dummy verifyObject(IFoo, dummy) def testMethodForAttr(self): class IFoo(Interface): foo = Attribute("The foo Attribute") class Foo: implements(IFoo) def foo(self): pass verifyClass(IFoo, Foo) def testNonMethodForMethod(self): class IBar(Interface): def foo(): pass class Bar: implements(IBar) foo = 1 self.assertRaises(BrokenMethodImplementation, verifyClass, IBar, Bar) def test_suite(): loader=unittest.TestLoader() return unittest.TestSuite(( doctest.DocFileSuite( '../verify.txt', optionflags=doctest.NORMALIZE_WHITESPACE), loader.loadTestsFromTestCase(Test), )) if __name__=='__main__': unittest.TextTestRunner().run(test_suite())
agpl-3.0
Cactuslegs/audacity-of-nope
lib-src/lv2/lv2/plugins/eg01-amp.lv2/waflib/Tools/xlc.py
330
1175
#! /usr/bin/env python # encoding: utf-8 # WARNING! Do not edit! http://waf.googlecode.com/git/docs/wafbook/single.html#_obtaining_the_waf_file from waflib.Tools import ccroot,ar from waflib.Configure import conf @conf def find_xlc(conf): cc=conf.find_program(['xlc_r','xlc'],var='CC') cc=conf.cmd_to_list(cc) conf.get_xlc_version(cc) conf.env.CC_NAME='xlc' conf.env.CC=cc @conf def xlc_common_flags(conf): v=conf.env v['CC_SRC_F']=[] v['CC_TGT_F']=['-c','-o'] if not v['LINK_CC']:v['LINK_CC']=v['CC'] v['CCLNK_SRC_F']=[] v['CCLNK_TGT_F']=['-o'] v['CPPPATH_ST']='-I%s' v['DEFINES_ST']='-D%s' v['LIB_ST']='-l%s' v['LIBPATH_ST']='-L%s' v['STLIB_ST']='-l%s' v['STLIBPATH_ST']='-L%s' v['RPATH_ST']='-Wl,-rpath,%s' v['SONAME_ST']=[] v['SHLIB_MARKER']=[] v['STLIB_MARKER']=[] v['LINKFLAGS_cprogram']=['-Wl,-brtl'] v['cprogram_PATTERN']='%s' v['CFLAGS_cshlib']=['-fPIC'] v['LINKFLAGS_cshlib']=['-G','-Wl,-brtl,-bexpfull'] v['cshlib_PATTERN']='lib%s.so' v['LINKFLAGS_cstlib']=[] v['cstlib_PATTERN']='lib%s.a' def configure(conf): conf.find_xlc() conf.find_ar() conf.xlc_common_flags() conf.cc_load_tools() conf.cc_add_flags() conf.link_add_flags()
gpl-2.0
dushu1203/chromium.src
components/cronet/tools/extract_from_jars.py
76
1385
#!/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. import fnmatch import optparse import os import sys REPOSITORY_ROOT = os.path.abspath(os.path.join( os.path.dirname(__file__), '..', '..', '..')) sys.path.append(os.path.join(REPOSITORY_ROOT, 'build/android/gyp/util')) import build_utils def ExtractJars(options): # The paths of the files in the jar will be the same as they are passed in to # the command. Because of this, the command should be run in # options.classes_dir so the .class file paths in the jar are correct. jar_cwd = options.classes_dir build_utils.DeleteDirectory(jar_cwd) build_utils.MakeDirectory(jar_cwd) for jar in build_utils.ParseGypList(options.jars): jar_path = os.path.abspath(jar) jar_cmd = ['jar', 'xf', jar_path] build_utils.CheckOutput(jar_cmd, cwd=jar_cwd) def main(): parser = optparse.OptionParser() parser.add_option('--classes-dir', help='Directory to extract .class files.') parser.add_option('--jars', help='Paths to jars to extract.') parser.add_option('--stamp', help='Path to touch on success.') options, _ = parser.parse_args() ExtractJars(options) if options.stamp: build_utils.Touch(options.stamp) if __name__ == '__main__': sys.exit(main())
bsd-3-clause
linuxmidhun/0install
zeroinstall/cmd/remove_feed.py
1
1066
""" The B{0install remove-feed} command-line interface. """ # Copyright (C) 2011, Thomas Leonard # See the README file for details, or visit http://0install.net. syntax = "[INTERFACE] FEED" from zeroinstall import SafeException, _ from zeroinstall.injector import model, writer from zeroinstall.cmd import add_feed, UsageError add_options = add_feed.add_options def handle(config, options, args): """@type args: [str]""" if len(args) == 2: iface = config.iface_cache.get_interface(model.canonical_iface_uri(args[0])) try: feed_url = model.canonical_iface_uri(args[1]) except SafeException: feed_url = args[1] # File might not exist any longer feed_import = add_feed.find_feed_import(iface, feed_url) if not feed_import: raise SafeException(_('Interface %(interface)s has no feed %(feed)s') % {'interface': iface.uri, 'feed': feed_url}) iface.extra_feeds.remove(feed_import) writer.save_interface(iface) elif len(args) == 1: add_feed.handle(config, options, args, add_ok = False, remove_ok = True) else: raise UsageError()
lgpl-2.1
lrocheWB/navitia
source/tyr/tyr/command/build_data.py
12
1883
# Copyright (c) 2001-2014, Canal TP and/or its affiliates. All rights reserved. # # This file is part of Navitia, # the software to build cool stuff with public transport. # # Hope you'll enjoy and contribute to this project, # powered by Canal TP (www.canaltp.fr). # Help us simplify mobility and open public transport: # a non ending quest to the responsive locomotion way of traveling! # # LICENCE: 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/>. # # Stay tuned using # twitter @navitia # IRC #navitia on freenode # https://groups.google.com/d/forum/navitia # www.navitia.io from flask.ext.script import Command, Option from tyr.tasks import build_all_data, build_data import logging from navitiacommon import models class BuildDataCommand(Command): """A command used to build all the datasets """ def get_options(self): return [ Option(dest='instance_name', help="name of the instance to build. If non given, build all instances") ] def run(self, instance_name=None): if not instance_name: logging.info("Building all data") return build_all_data() instance = models.Instance.query.filter_by(name=instance_name).first() return build_data(instance)
agpl-3.0
michalliu/OpenWrt-Firefly-Libraries
staging_dir/target-mipsel_1004kc+dsp_uClibc-0.9.33.2/usr/lib/python3.4/mimetypes.py
83
20735
"""Guess the MIME type of a file. This module defines two useful functions: guess_type(url, strict=True) -- guess the MIME type and encoding of a URL. guess_extension(type, strict=True) -- guess the extension for a given MIME type. It also contains the following, for tuning the behavior: Data: knownfiles -- list of files to parse inited -- flag set when init() has been called suffix_map -- dictionary mapping suffixes to suffixes encodings_map -- dictionary mapping suffixes to encodings types_map -- dictionary mapping suffixes to types Functions: init([files]) -- parse a list of files, default knownfiles (on Windows, the default values are taken from the registry) read_mime_types(file) -- parse one file, return a dictionary or None """ import os import sys import posixpath import urllib.parse try: import winreg as _winreg except ImportError: _winreg = None __all__ = [ "guess_type","guess_extension","guess_all_extensions", "add_type","read_mime_types","init" ] knownfiles = [ "/etc/mime.types", "/etc/httpd/mime.types", # Mac OS X "/etc/httpd/conf/mime.types", # Apache "/etc/apache/mime.types", # Apache 1 "/etc/apache2/mime.types", # Apache 2 "/usr/local/etc/httpd/conf/mime.types", "/usr/local/lib/netscape/mime.types", "/usr/local/etc/httpd/conf/mime.types", # Apache 1.2 "/usr/local/etc/mime.types", # Apache 1.3 ] inited = False _db = None class MimeTypes: """MIME-types datastore. This datastore can handle information from mime.types-style files and supports basic determination of MIME type from a filename or URL, and can guess a reasonable extension given a MIME type. """ def __init__(self, filenames=(), strict=True): if not inited: init() self.encodings_map = encodings_map.copy() self.suffix_map = suffix_map.copy() self.types_map = ({}, {}) # dict for (non-strict, strict) self.types_map_inv = ({}, {}) for (ext, type) in types_map.items(): self.add_type(type, ext, True) for (ext, type) in common_types.items(): self.add_type(type, ext, False) for name in filenames: self.read(name, strict) def add_type(self, type, ext, strict=True): """Add a mapping between a type and an extension. When the extension is already known, the new type will replace the old one. When the type is already known the extension will be added to the list of known extensions. If strict is true, information will be added to list of standard types, else to the list of non-standard types. """ self.types_map[strict][ext] = type exts = self.types_map_inv[strict].setdefault(type, []) if ext not in exts: exts.append(ext) def guess_type(self, url, strict=True): """Guess the type of a file based on its URL. Return value is a tuple (type, encoding) where type is None if the type can't be guessed (no or unknown suffix) or a string of the form type/subtype, usable for a MIME Content-type header; and encoding is None for no encoding or the name of the program used to encode (e.g. compress or gzip). The mappings are table driven. Encoding suffixes are case sensitive; type suffixes are first tried case sensitive, then case insensitive. The suffixes .tgz, .taz and .tz (case sensitive!) are all mapped to '.tar.gz'. (This is table-driven too, using the dictionary suffix_map.) Optional `strict' argument when False adds a bunch of commonly found, but non-standard types. """ scheme, url = urllib.parse.splittype(url) if scheme == 'data': # syntax of data URLs: # dataurl := "data:" [ mediatype ] [ ";base64" ] "," data # mediatype := [ type "/" subtype ] *( ";" parameter ) # data := *urlchar # parameter := attribute "=" value # type/subtype defaults to "text/plain" comma = url.find(',') if comma < 0: # bad data URL return None, None semi = url.find(';', 0, comma) if semi >= 0: type = url[:semi] else: type = url[:comma] if '=' in type or '/' not in type: type = 'text/plain' return type, None # never compressed, so encoding is None base, ext = posixpath.splitext(url) while ext in self.suffix_map: base, ext = posixpath.splitext(base + self.suffix_map[ext]) if ext in self.encodings_map: encoding = self.encodings_map[ext] base, ext = posixpath.splitext(base) else: encoding = None types_map = self.types_map[True] if ext in types_map: return types_map[ext], encoding elif ext.lower() in types_map: return types_map[ext.lower()], encoding elif strict: return None, encoding types_map = self.types_map[False] if ext in types_map: return types_map[ext], encoding elif ext.lower() in types_map: return types_map[ext.lower()], encoding else: return None, encoding def guess_all_extensions(self, type, strict=True): """Guess the extensions for a file based on its MIME type. Return value is a list of strings giving the possible filename extensions, including the leading dot ('.'). The extension is not guaranteed to have been associated with any particular data stream, but would be mapped to the MIME type `type' by guess_type(). Optional `strict' argument when false adds a bunch of commonly found, but non-standard types. """ type = type.lower() extensions = self.types_map_inv[True].get(type, []) if not strict: for ext in self.types_map_inv[False].get(type, []): if ext not in extensions: extensions.append(ext) return extensions def guess_extension(self, type, strict=True): """Guess the extension for a file based on its MIME type. Return value is a string giving a filename extension, including the leading dot ('.'). The extension is not guaranteed to have been associated with any particular data stream, but would be mapped to the MIME type `type' by guess_type(). If no extension can be guessed for `type', None is returned. Optional `strict' argument when false adds a bunch of commonly found, but non-standard types. """ extensions = self.guess_all_extensions(type, strict) if not extensions: return None return extensions[0] def read(self, filename, strict=True): """ Read a single mime.types-format file, specified by pathname. If strict is true, information will be added to list of standard types, else to the list of non-standard types. """ with open(filename, encoding='utf-8') as fp: self.readfp(fp, strict) def readfp(self, fp, strict=True): """ Read a single mime.types-format file. If strict is true, information will be added to list of standard types, else to the list of non-standard types. """ while 1: line = fp.readline() if not line: break words = line.split() for i in range(len(words)): if words[i][0] == '#': del words[i:] break if not words: continue type, suffixes = words[0], words[1:] for suff in suffixes: self.add_type(type, '.' + suff, strict) def read_windows_registry(self, strict=True): """ Load the MIME types database from Windows registry. If strict is true, information will be added to list of standard types, else to the list of non-standard types. """ # Windows only if not _winreg: return def enum_types(mimedb): i = 0 while True: try: ctype = _winreg.EnumKey(mimedb, i) except EnvironmentError: break else: yield ctype i += 1 with _winreg.OpenKey(_winreg.HKEY_CLASSES_ROOT, '') as hkcr: for subkeyname in enum_types(hkcr): try: with _winreg.OpenKey(hkcr, subkeyname) as subkey: # Only check file extensions if not subkeyname.startswith("."): continue # raises EnvironmentError if no 'Content Type' value mimetype, datatype = _winreg.QueryValueEx( subkey, 'Content Type') if datatype != _winreg.REG_SZ: continue self.add_type(mimetype, subkeyname, strict) except EnvironmentError: continue def guess_type(url, strict=True): """Guess the type of a file based on its URL. Return value is a tuple (type, encoding) where type is None if the type can't be guessed (no or unknown suffix) or a string of the form type/subtype, usable for a MIME Content-type header; and encoding is None for no encoding or the name of the program used to encode (e.g. compress or gzip). The mappings are table driven. Encoding suffixes are case sensitive; type suffixes are first tried case sensitive, then case insensitive. The suffixes .tgz, .taz and .tz (case sensitive!) are all mapped to ".tar.gz". (This is table-driven too, using the dictionary suffix_map). Optional `strict' argument when false adds a bunch of commonly found, but non-standard types. """ if _db is None: init() return _db.guess_type(url, strict) def guess_all_extensions(type, strict=True): """Guess the extensions for a file based on its MIME type. Return value is a list of strings giving the possible filename extensions, including the leading dot ('.'). The extension is not guaranteed to have been associated with any particular data stream, but would be mapped to the MIME type `type' by guess_type(). If no extension can be guessed for `type', None is returned. Optional `strict' argument when false adds a bunch of commonly found, but non-standard types. """ if _db is None: init() return _db.guess_all_extensions(type, strict) def guess_extension(type, strict=True): """Guess the extension for a file based on its MIME type. Return value is a string giving a filename extension, including the leading dot ('.'). The extension is not guaranteed to have been associated with any particular data stream, but would be mapped to the MIME type `type' by guess_type(). If no extension can be guessed for `type', None is returned. Optional `strict' argument when false adds a bunch of commonly found, but non-standard types. """ if _db is None: init() return _db.guess_extension(type, strict) def add_type(type, ext, strict=True): """Add a mapping between a type and an extension. When the extension is already known, the new type will replace the old one. When the type is already known the extension will be added to the list of known extensions. If strict is true, information will be added to list of standard types, else to the list of non-standard types. """ if _db is None: init() return _db.add_type(type, ext, strict) def init(files=None): global suffix_map, types_map, encodings_map, common_types global inited, _db inited = True # so that MimeTypes.__init__() doesn't call us again db = MimeTypes() if files is None: if _winreg: db.read_windows_registry() files = knownfiles for file in files: if os.path.isfile(file): db.read(file) encodings_map = db.encodings_map suffix_map = db.suffix_map types_map = db.types_map[True] common_types = db.types_map[False] # Make the DB a global variable now that it is fully initialized _db = db def read_mime_types(file): try: f = open(file) except OSError: return None with f: db = MimeTypes() db.readfp(f, True) return db.types_map[True] def _default_mime_types(): global suffix_map global encodings_map global types_map global common_types suffix_map = { '.svgz': '.svg.gz', '.tgz': '.tar.gz', '.taz': '.tar.gz', '.tz': '.tar.gz', '.tbz2': '.tar.bz2', '.txz': '.tar.xz', } encodings_map = { '.gz': 'gzip', '.Z': 'compress', '.bz2': 'bzip2', '.xz': 'xz', } # Before adding new types, make sure they are either registered with IANA, # at http://www.iana.org/assignments/media-types # or extensions, i.e. using the x- prefix # If you add to these, please keep them sorted! types_map = { '.a' : 'application/octet-stream', '.ai' : 'application/postscript', '.aif' : 'audio/x-aiff', '.aifc' : 'audio/x-aiff', '.aiff' : 'audio/x-aiff', '.au' : 'audio/basic', '.avi' : 'video/x-msvideo', '.bat' : 'text/plain', '.bcpio' : 'application/x-bcpio', '.bin' : 'application/octet-stream', '.bmp' : 'image/x-ms-bmp', '.c' : 'text/plain', # Duplicates :( '.cdf' : 'application/x-cdf', '.cdf' : 'application/x-netcdf', '.cpio' : 'application/x-cpio', '.csh' : 'application/x-csh', '.css' : 'text/css', '.dll' : 'application/octet-stream', '.doc' : 'application/msword', '.dot' : 'application/msword', '.dvi' : 'application/x-dvi', '.eml' : 'message/rfc822', '.eps' : 'application/postscript', '.etx' : 'text/x-setext', '.exe' : 'application/octet-stream', '.gif' : 'image/gif', '.gtar' : 'application/x-gtar', '.h' : 'text/plain', '.hdf' : 'application/x-hdf', '.htm' : 'text/html', '.html' : 'text/html', '.ico' : 'image/vnd.microsoft.icon', '.ief' : 'image/ief', '.jpe' : 'image/jpeg', '.jpeg' : 'image/jpeg', '.jpg' : 'image/jpeg', '.js' : 'application/javascript', '.ksh' : 'text/plain', '.latex' : 'application/x-latex', '.m1v' : 'video/mpeg', '.m3u' : 'application/vnd.apple.mpegurl', '.m3u8' : 'application/vnd.apple.mpegurl', '.man' : 'application/x-troff-man', '.me' : 'application/x-troff-me', '.mht' : 'message/rfc822', '.mhtml' : 'message/rfc822', '.mif' : 'application/x-mif', '.mov' : 'video/quicktime', '.movie' : 'video/x-sgi-movie', '.mp2' : 'audio/mpeg', '.mp3' : 'audio/mpeg', '.mp4' : 'video/mp4', '.mpa' : 'video/mpeg', '.mpe' : 'video/mpeg', '.mpeg' : 'video/mpeg', '.mpg' : 'video/mpeg', '.ms' : 'application/x-troff-ms', '.nc' : 'application/x-netcdf', '.nws' : 'message/rfc822', '.o' : 'application/octet-stream', '.obj' : 'application/octet-stream', '.oda' : 'application/oda', '.p12' : 'application/x-pkcs12', '.p7c' : 'application/pkcs7-mime', '.pbm' : 'image/x-portable-bitmap', '.pdf' : 'application/pdf', '.pfx' : 'application/x-pkcs12', '.pgm' : 'image/x-portable-graymap', '.pl' : 'text/plain', '.png' : 'image/png', '.pnm' : 'image/x-portable-anymap', '.pot' : 'application/vnd.ms-powerpoint', '.ppa' : 'application/vnd.ms-powerpoint', '.ppm' : 'image/x-portable-pixmap', '.pps' : 'application/vnd.ms-powerpoint', '.ppt' : 'application/vnd.ms-powerpoint', '.ps' : 'application/postscript', '.pwz' : 'application/vnd.ms-powerpoint', '.py' : 'text/x-python', '.pyc' : 'application/x-python-code', '.pyo' : 'application/x-python-code', '.qt' : 'video/quicktime', '.ra' : 'audio/x-pn-realaudio', '.ram' : 'application/x-pn-realaudio', '.ras' : 'image/x-cmu-raster', '.rdf' : 'application/xml', '.rgb' : 'image/x-rgb', '.roff' : 'application/x-troff', '.rtx' : 'text/richtext', '.sgm' : 'text/x-sgml', '.sgml' : 'text/x-sgml', '.sh' : 'application/x-sh', '.shar' : 'application/x-shar', '.snd' : 'audio/basic', '.so' : 'application/octet-stream', '.src' : 'application/x-wais-source', '.sv4cpio': 'application/x-sv4cpio', '.sv4crc' : 'application/x-sv4crc', '.svg' : 'image/svg+xml', '.swf' : 'application/x-shockwave-flash', '.t' : 'application/x-troff', '.tar' : 'application/x-tar', '.tcl' : 'application/x-tcl', '.tex' : 'application/x-tex', '.texi' : 'application/x-texinfo', '.texinfo': 'application/x-texinfo', '.tif' : 'image/tiff', '.tiff' : 'image/tiff', '.tr' : 'application/x-troff', '.tsv' : 'text/tab-separated-values', '.txt' : 'text/plain', '.ustar' : 'application/x-ustar', '.vcf' : 'text/x-vcard', '.wav' : 'audio/x-wav', '.wiz' : 'application/msword', '.wsdl' : 'application/xml', '.xbm' : 'image/x-xbitmap', '.xlb' : 'application/vnd.ms-excel', # Duplicates :( '.xls' : 'application/excel', '.xls' : 'application/vnd.ms-excel', '.xml' : 'text/xml', '.xpdl' : 'application/xml', '.xpm' : 'image/x-xpixmap', '.xsl' : 'application/xml', '.xwd' : 'image/x-xwindowdump', '.zip' : 'application/zip', } # These are non-standard types, commonly found in the wild. They will # only match if strict=0 flag is given to the API methods. # Please sort these too common_types = { '.jpg' : 'image/jpg', '.mid' : 'audio/midi', '.midi': 'audio/midi', '.pct' : 'image/pict', '.pic' : 'image/pict', '.pict': 'image/pict', '.rtf' : 'application/rtf', '.xul' : 'text/xul' } _default_mime_types() if __name__ == '__main__': import getopt USAGE = """\ Usage: mimetypes.py [options] type Options: --help / -h -- print this message and exit --lenient / -l -- additionally search of some common, but non-standard types. --extension / -e -- guess extension instead of type More than one type argument may be given. """ def usage(code, msg=''): print(USAGE) if msg: print(msg) sys.exit(code) try: opts, args = getopt.getopt(sys.argv[1:], 'hle', ['help', 'lenient', 'extension']) except getopt.error as msg: usage(1, msg) strict = 1 extension = 0 for opt, arg in opts: if opt in ('-h', '--help'): usage(0) elif opt in ('-l', '--lenient'): strict = 0 elif opt in ('-e', '--extension'): extension = 1 for gtype in args: if extension: guess = guess_extension(gtype, strict) if not guess: print("I don't know anything about type", gtype) else: print(guess) else: guess, encoding = guess_type(gtype, strict) if not guess: print("I don't know anything about type", gtype) else: print('type:', guess, 'encoding:', encoding)
gpl-2.0
oscaro/django
django/contrib/flatpages/tests/test_forms.py
111
4042
from __future__ import unicode_literals from django.conf import settings from django.contrib.flatpages.forms import FlatpageForm from django.contrib.flatpages.models import FlatPage from django.test import TestCase, override_settings from django.utils import translation @override_settings(SITE_ID=1) class FlatpageAdminFormTests(TestCase): fixtures = ['example_site'] def setUp(self): self.form_data = { 'title': "A test page", 'content': "This is a test", 'sites': [settings.SITE_ID], } def test_flatpage_admin_form_url_validation(self): "The flatpage admin form correctly validates urls" self.assertTrue(FlatpageForm(data=dict(url='/new_flatpage/', **self.form_data)).is_valid()) self.assertTrue(FlatpageForm(data=dict(url='/some.special~chars/', **self.form_data)).is_valid()) self.assertTrue(FlatpageForm(data=dict(url='/some.very_special~chars-here/', **self.form_data)).is_valid()) self.assertFalse(FlatpageForm(data=dict(url='/a space/', **self.form_data)).is_valid()) self.assertFalse(FlatpageForm(data=dict(url='/a % char/', **self.form_data)).is_valid()) self.assertFalse(FlatpageForm(data=dict(url='/a ! char/', **self.form_data)).is_valid()) self.assertFalse(FlatpageForm(data=dict(url='/a & char/', **self.form_data)).is_valid()) self.assertFalse(FlatpageForm(data=dict(url='/a ? char/', **self.form_data)).is_valid()) def test_flatpage_requires_leading_slash(self): form = FlatpageForm(data=dict(url='no_leading_slash/', **self.form_data)) with translation.override('en'): self.assertFalse(form.is_valid()) self.assertEqual(form.errors['url'], ["URL is missing a leading slash."]) @override_settings(APPEND_SLASH=True, MIDDLEWARE_CLASSES=('django.middleware.common.CommonMiddleware',)) def test_flatpage_requires_trailing_slash_with_append_slash(self): form = FlatpageForm(data=dict(url='/no_trailing_slash', **self.form_data)) with translation.override('en'): self.assertFalse(form.is_valid()) self.assertEqual(form.errors['url'], ["URL is missing a trailing slash."]) @override_settings(APPEND_SLASH=False, MIDDLEWARE_CLASSES=('django.middleware.common.CommonMiddleware',)) def test_flatpage_doesnt_requires_trailing_slash_without_append_slash(self): form = FlatpageForm(data=dict(url='/no_trailing_slash', **self.form_data)) self.assertTrue(form.is_valid()) def test_flatpage_admin_form_url_uniqueness_validation(self): "The flatpage admin form correctly enforces url uniqueness among flatpages of the same site" data = dict(url='/myflatpage1/', **self.form_data) FlatpageForm(data=data).save() f = FlatpageForm(data=data) with translation.override('en'): self.assertFalse(f.is_valid()) self.assertEqual( f.errors, {'__all__': ['Flatpage with url /myflatpage1/ already exists for site example.com']}) def test_flatpage_admin_form_edit(self): """ Existing flatpages can be edited in the admin form without triggering the url-uniqueness validation. """ existing = FlatPage.objects.create( url="/myflatpage1/", title="Some page", content="The content") existing.sites.add(settings.SITE_ID) data = dict(url='/myflatpage1/', **self.form_data) f = FlatpageForm(data=data, instance=existing) self.assertTrue(f.is_valid(), f.errors) updated = f.save() self.assertEqual(updated.title, "A test page") def test_flatpage_nosites(self): data = dict(url='/myflatpage1/', **self.form_data) data.update({'sites': ''}) f = FlatpageForm(data=data) self.assertFalse(f.is_valid()) self.assertEqual( f.errors, {'sites': [translation.ugettext('This field is required.')]})
bsd-3-clause
lifeinoppo/littlefishlet-scode
RES/REF/python_sourcecode/ipython-master/IPython/lib/inputhookglut.py
29
6104
# coding: utf-8 """ GLUT Inputhook support functions """ from __future__ import print_function #----------------------------------------------------------------------------- # Copyright (C) 2008-2011 The IPython Development Team # # Distributed under the terms of the BSD License. The full license is in # the file COPYING, distributed as part of this software. #----------------------------------------------------------------------------- # GLUT is quite an old library and it is difficult to ensure proper # integration within IPython since original GLUT does not allow to handle # events one by one. Instead, it requires for the mainloop to be entered # and never returned (there is not even a function to exit he # mainloop). Fortunately, there are alternatives such as freeglut # (available for linux and windows) and the OSX implementation gives # access to a glutCheckLoop() function that blocks itself until a new # event is received. This means we have to setup the idle callback to # ensure we got at least one event that will unblock the function. # # Furthermore, it is not possible to install these handlers without a window # being first created. We choose to make this window invisible. This means that # display mode options are set at this level and user won't be able to change # them later without modifying the code. This should probably be made available # via IPython options system. #----------------------------------------------------------------------------- # Imports #----------------------------------------------------------------------------- import os import sys import time import signal import OpenGL.GLUT as glut import OpenGL.platform as platform from timeit import default_timer as clock #----------------------------------------------------------------------------- # Constants #----------------------------------------------------------------------------- # Frame per second : 60 # Should probably be an IPython option glut_fps = 60 # Display mode : double buffeed + rgba + depth # Should probably be an IPython option glut_display_mode = (glut.GLUT_DOUBLE | glut.GLUT_RGBA | glut.GLUT_DEPTH) glutMainLoopEvent = None if sys.platform == 'darwin': try: glutCheckLoop = platform.createBaseFunction( 'glutCheckLoop', dll=platform.GLUT, resultType=None, argTypes=[], doc='glutCheckLoop( ) -> None', argNames=(), ) except AttributeError: raise RuntimeError( '''Your glut implementation does not allow interactive sessions''' '''Consider installing freeglut.''') glutMainLoopEvent = glutCheckLoop elif glut.HAVE_FREEGLUT: glutMainLoopEvent = glut.glutMainLoopEvent else: raise RuntimeError( '''Your glut implementation does not allow interactive sessions. ''' '''Consider installing freeglut.''') #----------------------------------------------------------------------------- # Platform-dependent imports and functions #----------------------------------------------------------------------------- if os.name == 'posix': import select def stdin_ready(): infds, outfds, erfds = select.select([sys.stdin],[],[],0) if infds: return True else: return False elif sys.platform == 'win32': import msvcrt def stdin_ready(): return msvcrt.kbhit() #----------------------------------------------------------------------------- # Callback functions #----------------------------------------------------------------------------- def glut_display(): # Dummy display function pass def glut_idle(): # Dummy idle function pass def glut_close(): # Close function only hides the current window glut.glutHideWindow() glutMainLoopEvent() def glut_int_handler(signum, frame): # Catch sigint and print the defautl message signal.signal(signal.SIGINT, signal.default_int_handler) print('\nKeyboardInterrupt') # Need to reprint the prompt at this stage #----------------------------------------------------------------------------- # Code #----------------------------------------------------------------------------- def inputhook_glut(): """Run the pyglet event loop by processing pending events only. This keeps processing pending events until stdin is ready. After processing all pending events, a call to time.sleep is inserted. This is needed, otherwise, CPU usage is at 100%. This sleep time should be tuned though for best performance. """ # We need to protect against a user pressing Control-C when IPython is # idle and this is running. We trap KeyboardInterrupt and pass. signal.signal(signal.SIGINT, glut_int_handler) try: t = clock() # Make sure the default window is set after a window has been closed if glut.glutGetWindow() == 0: glut.glutSetWindow( 1 ) glutMainLoopEvent() return 0 while not stdin_ready(): glutMainLoopEvent() # We need to sleep at this point to keep the idle CPU load # low. However, if sleep to long, GUI response is poor. As # a compromise, we watch how often GUI events are being processed # and switch between a short and long sleep time. Here are some # stats useful in helping to tune this. # time CPU load # 0.001 13% # 0.005 3% # 0.01 1.5% # 0.05 0.5% used_time = clock() - t if used_time > 10.0: # print 'Sleep for 1 s' # dbg time.sleep(1.0) elif used_time > 0.1: # Few GUI events coming in, so we can sleep longer # print 'Sleep for 0.05 s' # dbg time.sleep(0.05) else: # Many GUI events coming in, so sleep only very little time.sleep(0.001) except KeyboardInterrupt: pass return 0
gpl-2.0
catapult-project/catapult-csm
telemetry/telemetry/internal/browser/browser_unittest.py
1
11913
# Copyright 2012 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import logging import os import re import shutil import tempfile import unittest from telemetry.core import exceptions from telemetry import decorators from telemetry.internal.browser import browser as browser_module from telemetry.internal.browser import browser_finder from telemetry.internal.platform import gpu_device from telemetry.internal.platform import gpu_info from telemetry.internal.platform import system_info from telemetry.internal.util import path from telemetry.testing import browser_test_case from telemetry.testing import options_for_unittests from telemetry.timeline import tracing_config from devil.android import app_ui import mock import py_utils class IntentionalException(Exception): pass class BrowserTest(browser_test_case.BrowserTestCase): def testBrowserCreation(self): self.assertEquals(1, len(self._browser.tabs)) # Different browsers boot up to different things. assert self._browser.tabs[0].url @decorators.Enabled('has tabs') def testNewCloseTab(self): existing_tab = self._browser.tabs[0] self.assertEquals(1, len(self._browser.tabs)) existing_tab_url = existing_tab.url new_tab = self._browser.tabs.New() self.assertEquals(2, len(self._browser.tabs)) self.assertEquals(existing_tab.url, existing_tab_url) self.assertEquals(new_tab.url, 'about:blank') new_tab.Close() self.assertEquals(1, len(self._browser.tabs)) self.assertEquals(existing_tab.url, existing_tab_url) def testMultipleTabCalls(self): self._browser.tabs[0].Navigate(self.UrlOfUnittestFile('blank.html')) self._browser.tabs[0].WaitForDocumentReadyStateToBeInteractiveOrBetter() def testTabCallByReference(self): tab = self._browser.tabs[0] tab.Navigate(self.UrlOfUnittestFile('blank.html')) self._browser.tabs[0].WaitForDocumentReadyStateToBeInteractiveOrBetter() @decorators.Enabled('has tabs') def testCloseReferencedTab(self): self._browser.tabs.New() tab = self._browser.tabs[0] tab.Navigate(self.UrlOfUnittestFile('blank.html')) tab.Close() self.assertEquals(1, len(self._browser.tabs)) @decorators.Enabled('has tabs') def testForegroundTab(self): # Should be only one tab at this stage, so that must be the foreground tab original_tab = self._browser.tabs[0] self.assertEqual(self._browser.foreground_tab, original_tab) new_tab = self._browser.tabs.New() # New tab shouls be foreground tab self.assertEqual(self._browser.foreground_tab, new_tab) # Make sure that activating the background tab makes it the foreground tab original_tab.Activate() self.assertEqual(self._browser.foreground_tab, original_tab) # Closing the current foreground tab should switch the foreground tab to the # other tab original_tab.Close() self.assertEqual(self._browser.foreground_tab, new_tab) # This test uses the reference browser and doesn't have access to # helper binaries like crashpad_database_util. @decorators.Enabled('linux') def testGetMinidumpPathOnCrash(self): tab = self._browser.tabs[0] with self.assertRaises(exceptions.AppCrashException): tab.Navigate('chrome://crash', timeout=5) crash_minidump_path = self._browser.GetMostRecentMinidumpPath() self.assertIsNotNone(crash_minidump_path) def testGetSystemInfo(self): if not self._browser.supports_system_info: logging.warning( 'Browser does not support getting system info, skipping test.') return info = self._browser.GetSystemInfo() self.assertTrue(isinstance(info, system_info.SystemInfo)) self.assertTrue(hasattr(info, 'model_name')) self.assertTrue(hasattr(info, 'gpu')) self.assertTrue(isinstance(info.gpu, gpu_info.GPUInfo)) self.assertTrue(hasattr(info.gpu, 'devices')) self.assertTrue(len(info.gpu.devices) > 0) for g in info.gpu.devices: self.assertTrue(isinstance(g, gpu_device.GPUDevice)) def testGetSystemInfoNotCachedObject(self): if not self._browser.supports_system_info: logging.warning( 'Browser does not support getting system info, skipping test.') return info_a = self._browser.GetSystemInfo() info_b = self._browser.GetSystemInfo() self.assertFalse(info_a is info_b) def testGetSystemTotalMemory(self): self.assertTrue(self._browser.memory_stats['SystemTotalPhysicalMemory'] > 0) def testSystemInfoModelNameOnMac(self): if self._browser.platform.GetOSName() != 'mac': self.skipTest('This test is only run on macOS') return if not self._browser.supports_system_info: logging.warning( 'Browser does not support getting system info, skipping test.') return info = self._browser.GetSystemInfo() model_name_re = r"[a-zA-Z]* [0-9.]*" self.assertNotEqual(re.match(model_name_re, info.model_name), None) # crbug.com/628836 (CrOS, where system-guest indicates ChromeOS guest) # github.com/catapult-project/catapult/issues/3130 (Windows) @decorators.Disabled('cros-chrome-guest', 'system-guest', 'chromeos', 'win') def testIsTracingRunning(self): tracing_controller = self._browser.platform.tracing_controller if not tracing_controller.IsChromeTracingSupported(): return self.assertFalse(tracing_controller.is_tracing_running) config = tracing_config.TracingConfig() config.enable_chrome_trace = True tracing_controller.StartTracing(config) self.assertTrue(tracing_controller.is_tracing_running) tracing_controller.StopTracing() self.assertFalse(tracing_controller.is_tracing_running) @decorators.Enabled('android') def testGetAppUi(self): self.assertTrue(self._browser.supports_app_ui_interactions) ui = self._browser.GetAppUi() self.assertTrue(isinstance(ui, app_ui.AppUi)) self.assertIsNotNone(ui.WaitForUiNode(resource_id='action_bar_root')) class CommandLineBrowserTest(browser_test_case.BrowserTestCase): @classmethod def CustomizeBrowserOptions(cls, options): options.AppendExtraBrowserArgs('--user-agent=telemetry') def testCommandLineOverriding(self): # This test starts the browser with --user-agent=telemetry. This tests # whether the user agent is then set. t = self._browser.tabs[0] t.Navigate(self.UrlOfUnittestFile('blank.html')) t.WaitForDocumentReadyStateToBeInteractiveOrBetter() self.assertEquals(t.EvaluateJavaScript('navigator.userAgent'), 'telemetry') class DirtyProfileBrowserTest(browser_test_case.BrowserTestCase): @classmethod def CustomizeBrowserOptions(cls, options): options.profile_type = 'small_profile' @decorators.Disabled('chromeos') # crbug.com/243912 def testDirtyProfileCreation(self): self.assertEquals(1, len(self._browser.tabs)) class BrowserLoggingTest(browser_test_case.BrowserTestCase): @classmethod def CustomizeBrowserOptions(cls, options): options.logging_verbosity = options.VERBOSE_LOGGING @decorators.Disabled('chromeos', 'android') def testLogFileExist(self): self.assertTrue( os.path.isfile(self._browser._browser_backend.log_file_path)) def _GenerateBrowserProfile(number_of_tabs): """ Generate a browser profile which browser had |number_of_tabs| number of tabs opened before it was closed. Returns: profile_dir: the directory of profile. """ profile_dir = tempfile.mkdtemp() options = options_for_unittests.GetCopy() options.browser_options.output_profile_path = profile_dir browser_to_create = browser_finder.FindBrowser(options) browser_to_create.platform.network_controller.InitializeIfNeeded() try: with browser_to_create.Create(options) as browser: browser.platform.SetHTTPServerDirectories(path.GetUnittestDataDir()) blank_file_path = os.path.join(path.GetUnittestDataDir(), 'blank.html') blank_url = browser.platform.http_server.UrlOf(blank_file_path) browser.foreground_tab.Navigate(blank_url) browser.foreground_tab.WaitForDocumentReadyStateToBeComplete() for _ in xrange(number_of_tabs - 1): tab = browser.tabs.New() tab.Navigate(blank_url) tab.WaitForDocumentReadyStateToBeComplete() return profile_dir finally: browser_to_create.platform.network_controller.Close() class BrowserCreationTest(unittest.TestCase): def setUp(self): self.mock_browser_backend = mock.MagicMock() self.mock_platform_backend = mock.MagicMock() def testCleanedUpCalledWhenExceptionRaisedInBrowserCreation(self): self.mock_platform_backend.platform.FlushDnsCache.side_effect = ( IntentionalException('Boom!')) with self.assertRaises(IntentionalException): browser_module.Browser( self.mock_browser_backend, self.mock_platform_backend, credentials_path=None) self.assertTrue(self.mock_platform_backend.WillCloseBrowser.called) def testOriginalExceptionNotSwallow(self): self.mock_platform_backend.platform.FlushDnsCache.side_effect = ( IntentionalException('Boom!')) self.mock_platform_backend.WillCloseBrowser.side_effect = ( IntentionalException('Cannot close browser!')) with self.assertRaises(IntentionalException) as context: browser_module.Browser( self.mock_browser_backend, self.mock_platform_backend, credentials_path=None) self.assertIn('Boom!', context.exception.message) class BrowserRestoreSessionTest(unittest.TestCase): @classmethod def setUpClass(cls): cls._number_of_tabs = 4 cls._profile_dir = _GenerateBrowserProfile(cls._number_of_tabs) cls._options = options_for_unittests.GetCopy() cls._options.browser_options.AppendExtraBrowserArgs( ['--restore-last-session']) cls._options.browser_options.profile_dir = cls._profile_dir cls._browser_to_create = browser_finder.FindBrowser(cls._options) cls._browser_to_create.platform.network_controller.InitializeIfNeeded() @decorators.Enabled('has tabs') @decorators.Disabled('chromeos', 'win', 'mac') # TODO(nednguyen): Enable this test on windowsn platform def testRestoreBrowserWithMultipleTabs(self): with self._browser_to_create.Create(self._options) as browser: # The number of tabs will be self._number_of_tabs + 1 as it includes the # old tabs and a new blank tab. expected_number_of_tabs = self._number_of_tabs + 1 try: py_utils.WaitFor( lambda: len(browser.tabs) == expected_number_of_tabs, 10) except: logging.error('Number of tabs is %s' % len(browser.tabs)) raise self.assertEquals(expected_number_of_tabs, len(browser.tabs)) @classmethod def tearDownClass(cls): cls._browser_to_create.platform.network_controller.Close() shutil.rmtree(cls._profile_dir) class TestBrowserOperationDoNotLeakTempFiles(unittest.TestCase): @decorators.Enabled('win', 'linux') # TODO(ashleymarie): Re-enable on mac # BUG=catapult:#3523 @decorators.Isolated def testBrowserNotLeakingTempFiles(self): options = options_for_unittests.GetCopy() browser_to_create = browser_finder.FindBrowser(options) self.assertIsNotNone(browser_to_create) before_browser_run_temp_dir_content = os.listdir(tempfile.tempdir) browser_to_create.platform.network_controller.InitializeIfNeeded() try: with browser_to_create.Create(options) as browser: tab = browser.tabs.New() tab.Navigate('about:blank') self.assertEquals(2, tab.EvaluateJavaScript('1 + 1')) after_browser_run_temp_dir_content = os.listdir(tempfile.tempdir) self.assertEqual(before_browser_run_temp_dir_content, after_browser_run_temp_dir_content) finally: browser_to_create.platform.network_controller.Close()
bsd-3-clause
helixyte/TheLMA
thelma/repositories/rdb/mappers/experimentjob.py
1
1080
""" This file is part of the TheLMA (THe Laboratory Management Application) project. See LICENSE.txt for licensing, CONTRIBUTORS.txt for contributor information. Experiment job mapper. """ from sqlalchemy.orm import relationship from everest.repositories.rdb.utils import mapper from thelma.entities.experiment import Experiment from thelma.entities.job import ExperimentJob from thelma.entities.job import JOB_TYPES __docformat__ = 'reStructuredText en' __all__ = ['create_mapper'] def create_mapper(job_mapper, job_tbl, experiment_tbl): "Mapper factory." m = mapper(ExperimentJob, job_tbl, inherits=job_mapper, properties=dict( experiments=relationship(Experiment, order_by=experiment_tbl.c.experiment_id, back_populates='job', cascade='save-update, merge, delete' ) ), polymorphic_identity=JOB_TYPES.EXPERIMENT ) return m
mit
pkimber/old_story
example/wsgi.py
2
1053
""" WSGI config for app project. This module contains the WSGI application used by Django's development server and any production WSGI deployments. It should expose a module-level variable named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover this application via the ``WSGI_APPLICATION`` setting. Usually you will have the standard Django WSGI application here, but it also might make sense to replace the whole Django WSGI application with a custom one that later delegates to the Django one. For example, you could introduce WSGI middleware here, or combine a Django application with an application of another framework. """ # This application object is used by any WSGI server configured to use this # file. This includes Django's development server, if the WSGI_APPLICATION # setting points here. from django.core.wsgi import get_wsgi_application application = get_wsgi_application() # Apply WSGI middleware here. # from helloworld.wsgi import HelloWorldApplication # application = HelloWorldApplication(application)
apache-2.0
ujuo/opencv
opencv-3.2.0/platforms/android/build-tests/test_ndk_build.py
6
5109
#!/usr/bin/env python import unittest import os, sys, subprocess, argparse, shutil, re TEMPLATE_ANDROID_MK = '''\ LOCAL_PATH := $(call my-dir) include $(CLEAR_VARS) {cut} LOCAL_MODULE := mixed_sample LOCAL_SRC_FILES := {cpp1} LOCAL_LDLIBS += -llog -ldl include $(BUILD_SHARED_LIBRARY) include $(CLEAR_VARS) {cut} LOCAL_MODULE := mixed_sample2 LOCAL_SRC_FILES := {cpp2} LOCAL_LDLIBS += -llog -ldl LOCAL_SHARED_LIBS := mixed_sample include $(BUILD_SHARED_LIBRARY) ''' TEMPLATE_APPLICATION_MK = '''\ APP_STL := gnustl_static APP_CPPFLAGS := -frtti -fexceptions APP_ABI := {abi} APP_PLATFORM := android-9 ''' TEMPLATE_JNI = '''\ #include <jni.h> #include <opencv2/core.hpp> #include <opencv2/imgproc.hpp> #include <opencv2/features2d.hpp> #include <vector> using namespace std; using namespace cv; extern "C" { JNIEXPORT void JNICALL Java_org_opencv_samples_tutorial4_Sample4Mixed_FindFeatures(JNIEnv*, jobject, jlong addrGray, jlong addrRgba); JNIEXPORT void JNICALL Java_org_opencv_samples_tutorial4_Sample4Mixed_FindFeatures(JNIEnv*, jobject, jlong addrGray, jlong addrRgba) { Mat& mGr = *(Mat*)addrGray; Mat& mRgb = *(Mat*)addrRgba; vector<KeyPoint> v; Ptr<FastFeatureDetector> detector = FastFeatureDetector::create(50); detector->detect(mGr, v); for( unsigned int i = 0; i < v.size(); i++ ) { const KeyPoint& kp = v[i]; circle(mRgb, Point(kp.pt.x, kp.pt.y), 10, Scalar(255,0,0,255)); } } } ''' #=================================================================================================== class TestNDKBuild(unittest.TestCase): def __init__(self, abi, libtype, opencv_mk_path, workdir, *args, **kwargs): unittest.TestCase.__init__(self, *args, **kwargs) self.abi = abi # official NDK ABI name or 'all' self.libtype = libtype # 'static', etc self.opencv_mk_path = opencv_mk_path self.workdir = workdir self.jnidir = os.path.join(self.workdir, "jni") self.cpp1 = "jni_part1.cpp" self.cpp2 = "jni_part2.cpp" def shortDescription(self): return "ABI: %s, LIBTYPE: %s" % (self.abi, self.libtype) def gen_android_mk(self): p = [] if self.libtype == "static": p.append("OPENCV_LIB_TYPE := STATIC") elif self.libtype == "shared_debug": p.append("OPENCV_LIB_TYPE := SHARED") p.append("OPENCV_CAMERA_MODULES:=on") p.append("OPENCV_INSTALL_MODULES:=on") elif self.libtype == "shared": p.append("OPENCV_LIB_TYPE := SHARED") p.append("include %s" % os.path.join(self.opencv_mk_path, "OpenCV.mk")) return TEMPLATE_ANDROID_MK.format(cut = "\n".join(p), cpp1 = self.cpp1, cpp2 = self.cpp2) def gen_jni_code(self): return TEMPLATE_JNI def gen_application_mk(self): return TEMPLATE_APPLICATION_MK.format(abi = self.abi) def write_jni_file(self, fname, contents): with open(os.path.join(self.jnidir, fname), "w") as f: f.write(contents) def setUp(self): if os.path.exists(self.workdir): shutil.rmtree(self.workdir) os.mkdir(self.workdir) os.mkdir(self.jnidir) self.write_jni_file("Android.mk", self.gen_android_mk()) self.write_jni_file("Application.mk", self.gen_application_mk()) self.write_jni_file(self.cpp1, self.gen_jni_code()) self.write_jni_file(self.cpp2, self.gen_jni_code()) os.chdir(self.workdir) def tearDown(self): if os.path.exists(self.workdir): shutil.rmtree(self.workdir) def runTest(self): ndk_path = os.environ["ANDROID_NDK"] retcode = subprocess.call([os.path.join(ndk_path, 'ndk-build'), "V=0"]) self.assertEqual(retcode, 0) def suite(workdir, opencv_mk_path): abis = ["armeabi", "armeabi-v7a", "x86", "mips"] ndk_path = os.environ["ANDROID_NDK"] with open(os.path.join(ndk_path, "RELEASE.TXT"), "r") as f: s = f.read() if re.search(r'r10[b-e]', s): abis.extend(["arm64-v8a", "x86", "x86_64"]) abis.append("all") suite = unittest.TestSuite() for libtype in ["static", "shared", "shared_debug"]: for abi in abis: suite.addTest(TestNDKBuild(abi, libtype, opencv_mk_path, workdir)) return suite if __name__ == '__main__': parser = argparse.ArgumentParser(description='Test OpenCV for Android SDK with NDK') parser.add_argument('--ndk_path', help="Path to Android NDK to use for build") parser.add_argument("--workdir", default="testspace", help="Working directory (and output)") parser.add_argument("opencv_mk_path", help="Path to folder with OpenCV.mk file (usually <SDK>/sdk/native/jni/") args = parser.parse_args() if args.ndk_path is not None: os.environ["ANDROID_NDK"] = os.path.abspath(args.ndk_path) print("Using NDK: %s" % os.environ["ANDROID_NDK"]) res = unittest.TextTestRunner(verbosity=3).run(suite(os.path.abspath(args.workdir), os.path.abspath(args.opencv_mk_path))) if not res.wasSuccessful(): sys.exit(res)
gpl-3.0
unsiloai/syntaxnet-ops-hack
tensorflow/contrib/keras/api/keras/applications/xception/__init__.py
57
1148
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Xception Keras application.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow.contrib.keras.python.keras.applications.xception import decode_predictions from tensorflow.contrib.keras.python.keras.applications.xception import preprocess_input from tensorflow.contrib.keras.python.keras.applications.xception import Xception del absolute_import del division del print_function
apache-2.0
SeanEstey/Bravo
app/notify/tasks.py
1
7873
'''app.notify.tasks''' import json, os, pytz from os import environ as env from datetime import datetime, date, time, timedelta from dateutil.parser import parse from bson import ObjectId as oid from flask import g, render_template from app import get_keys, celery #, smart_emit from app.lib.dt import to_local from app.lib import mailgun from app.main import schedule from app.main.parser import is_bus from app.main.etapestry import call, EtapError from . import email, events, sms, voice, pickups, triggers from logging import getLogger log = getLogger(__name__) #------------------------------------------------------------------------------- @celery.task(bind=True) def monitor_triggers(self, **kwargs): ready = g.db.triggers.find({ 'status':'pending', 'fire_dt':{ '$lt':datetime.utcnow()}}) for trigger in ready: evnt = g.db.events.find_one({'_id':trigger['evnt_id']}) g.group = evnt['agency'] log.debug('Firing event trigger for %s', evnt['name'], extra={'trigger_id':str(trigger['_id'])}) try: fire_trigger(trigger['_id']) except Exception as e: log.exception('Error firing event trigger for %s', evnt['name']) pending = g.db.triggers.find({ 'status':'pending', 'fire_dt': { '$gt':datetime.utcnow()}}).sort('fire_dt', 1) output = [] if pending.count() > 0: tgr = pending.next() delta = tgr['fire_dt'] - datetime.utcnow().replace(tzinfo=pytz.utc) to_str = str(delta)[:-7] return 'next trigger pending in %s' % to_str else: return '0 pending' #------------------------------------------------------------------------------- @celery.task(bind=True) def fire_trigger(self, _id=None, **rest): '''Sends out all dependent sms/voice/email notifics messages ''' status = '' n_errors = 0 trig = g.db.triggers.find_one({'_id':oid(_id)}) event = g.db.events.find_one({'_id':trig['evnt_id']}) g.group = event['agency'] g.db.triggers.update_one( {'_id':oid(_id)}, {'$set': {'task_id':self.request.id, 'status':'in-progress'}}) events.update_status(trig['evnt_id']) ready = g.db.notifics.find( {'trig_id':oid(_id), 'tracking.status':'pending'}) count = ready.count() log.info('Sending notifications for event %s...', event['name'], extra={'type':trig['type'], 'n_total':count}) #smart_emit('trigger_status',{ # 'trig_id': str(_id), 'status': 'in-progress'}) if env['BRV_SANDBOX'] == 'True': log.info('sandbox: simulating voice/sms, rerouting emails') for n in ready: try: if n['type'] == 'voice': status = voice.call(n, get_keys('twilio')) elif n['type'] == 'sms': status = sms.send(n, get_keys('twilio')) elif n['type'] == 'email': status = email.send(n, get_keys('mailgun')) except Exception as e: n_errors +=1 status = 'error' log.exception('Error sending notification to %s', n['to'], extra={'type':n['type']}) else: if status == 'failed': n_errors += 1 finally: pass #smart_emit('notific_status', { # 'notific_id':str(n['_id']), 'status':status}) g.db.triggers.update_one({'_id':oid(_id)}, {'$set': {'status': 'fired'}}) '''smart_emit('trigger_status', { 'trig_id': str(_id), 'status': 'fired', 'sent': count - n_errors, 'errors': n_errors})''' log.info('%s/%s notifications sent for event %s', count - n_errors, count, event['name'], extra={'type':trig['type'], 'n_total':count, 'n_errors':n_errors}) return 'success' #------------------------------------------------------------------------------- @celery.task(bind=True) def schedule_reminders(self, group=None, for_date=None, **rest): if for_date: for_date = parse(for_date).date() groups = [g.db['groups'].find_one({'name':group})] if group else g.db['groups'].find() evnt_ids = [] for group_ in groups: n_success = n_fails = 0 g.group = group_['name'] log.info('Scheduling notification events...') days_ahead = int(group_['notify']['sched_delta_days']) on_date = date.today() + timedelta(days=days_ahead) if not for_date else for_date date_str = on_date.strftime('%m-%d-%Y') blocks = [] for key in group_['cal_ids']: blocks += schedule.get_blocks( group_['cal_ids'][key], datetime.combine(on_date,time(8,0)), datetime.combine(on_date,time(9,0)), get_keys('google')['oauth']) if len(blocks) == 0: log.debug('no blocks on %s', date_str) continue else: log.debug('%s events on %s: %s', len(blocks), date_str, ", ".join(blocks)) for block in blocks: if is_bus(block) and group_['notify']['sched_business'] == False: continue try: evnt_id = pickups.create_reminder(g.group, block, on_date) except EtapError as e: n_fails +=1 log.exception('Error creating notification event %s', block) continue else: n_success +=1 evnt_ids.append(str(evnt_id)) log.info('Created notification event %s', block) log.info('Created %s/%s scheduled notification events', n_success, n_success + n_fails) return json.dumps(evnt_ids) #------------------------------------------------------------------------------- @celery.task(bind=True) def skip_pickup(self, evnt_id=None, acct_id=None, **rest): '''User has opted out of a pickup via sms/voice/email noification. Run is_valid() before calling this function. @acct_id: _id from db.accounts, not eTap account id ''' # Cancel any pending parent notifications result = g.db.notifics.update_many( {'acct_id':oid(acct_id), 'evnt_id':oid(evnt_id), 'tracking.status':'pending'}, {'$set':{'tracking.status':'cancelled'}}) acct = g.db.accounts.find_one_and_update( {'_id':oid(acct_id)}, {'$set': {'opted_out': True}}) evnt = g.db.events.find_one({'_id':oid(evnt_id)}) if not evnt or not acct: msg = 'evnt/acct not found (evnt_id=%s, acct_id=%s' %(evnt_id,acct_id) log.error(msg) raise Exception(msg) g.group = evnt['agency'] log.info('%s opted out of pickup', acct.get('name') or acct.get('email'), extra={'event_name':evnt['name'], 'account_id':acct['udf']['etap_id']}) try: call('skip_pickup', data={ 'acct_id': acct['udf']['etap_id'], 'date': acct['udf']['pickup_dt'].strftime('%d/%m/%Y'), 'next_pickup': to_local( acct['udf']['future_pickup_dt'], to_str='%d/%m/%Y')}) except Exception as e: log.exception('Error calling skip_pickup') log.exception("Error updating account %s", acct.get('name') or acct.get('email'), extra={'account_id': acct['udf']['etap_id']}) if not acct.get('email'): return 'success' try: body = render_template( 'email/%s/no_pickup.html' % g.group, to=acct['email'], account=to_local(obj=acct, to_str='%B %d %Y')) except Exception as e: log.exception('Error rendering no_pickup template') raise else: mailgun.send( acct['email'], 'Thanks for Opting Out', body, get_keys('mailgun'), v={'type':'opt_out', 'group':g.group}) return 'success'
gpl-2.0
ramon-astudillo/lxmls-toolkit
lxmls/pos_tagging/all_train_pos_tag.py
2
3145
import sys import codecs from sequences.sequence import * from sequences.sequence_list import * import readers.pos_corpus as pcc import readers.brown_pos_corpus as bpc import sequences.extended_feature as exfc import sequences.structured_perceptron as spc import sequences.confusion_matrix as bcm MAX_SENT_SIZE = 1000 MAX_NR_SENTENCES = 100000 MODEL_DIR = "/Users/graca/Projects/swm_src/feeds/models/all_data_postag/" def build_corpus_features(): corpus = pcc.PostagCorpus() train_seq = corpus.read_sequence_list_conll( "../../data/train-02-21.conll", max_sent_len=MAX_SENT_SIZE, max_nr_sent=MAX_NR_SENTENCES) corpus.add_sequence_list(train_seq) dev_seq = corpus.read_sequence_list_conll("../../data/dev-22.conll") corpus.add_sequence_list(dev_seq) categories = [ 'adventure', 'belles_lettres', 'editorial', 'fiction', 'government', 'hobbies', 'humor', 'learned', 'lore', 'mystery', 'news', 'religion', 'reviews', 'romance'] for cat in categories: brown_seq = corpus.read_sequence_list_brown(categories=cat) corpus.add_sequence_list(brown_seq) features = exfc.ExtendedFeatures(corpus) features.build_features() corpus.save_corpus(MODEL_DIR) features.save_features(MODEL_DIR+"features.txt") return corpus, features def train_pos(corpus, features): model = spc.StructuredPercetron(corpus, features) model.nr_rounds = 10 model.train_supervised(corpus.sequence_list.seq_list) model.save_model(MODEL_DIR) return model def eval_model(corpus, features, model): test_seq = corpus.read_sequence_list_conll("../../data/test-23.conll") pred_test = model.viterbi_decode_corpus_log(test_seq.seq_list) eval_test = model.evaluate_corpus(test_seq.seq_list, pred_test) print "Accuracy on wsj test %f" % eval_test def eval_brown(corpus, features, model): categories = ['science_fiction'] for cat in categories: brown_seq = corpus.read_sequence_list_brown(categories=cat) brown_pred = model.viterbi_decode_corpus_log(brown_seq.seq_list) brown_eval = model.evaluate_corpus(brown_seq.seq_list, brown_pred) print "Accuracy on Brown cat %s: %f" % (cat, brown_eval) def load_model(): corpus = pcc.PostagCorpus() corpus.load_corpus(MODEL_DIR) features = exfc.ExtendedFeatures(corpus) features.load_features(MODEL_DIR+"features.txt", corpus) model = spc.StructuredPercetron(corpus, features) model.load_model(MODEL_DIR) return corpus, features, model def main(): print "Building corpus" corpus, features = build_corpus_features() print "Training model" model = train_pos(corpus, features) print "Testing on wsj" eval_model(corpus, features, model) print "Testing on brown" eval_brown(corpus, features, model) # print "Loading models" # corpus,features,model = load_model() # print "Testing on wsj" # eval_model(corpus,features,model) # print "Testing on brown" # eval_brown(corpus,features,model)
mit
tashaxe/Red-DiscordBot
lib/youtube_dl/extractor/sportbox.py
24
2253
# coding: utf-8 from __future__ import unicode_literals import re from .common import InfoExtractor from ..utils import js_to_json class SportBoxEmbedIE(InfoExtractor): _VALID_URL = r'https?://news\.sportbox\.ru/vdl/player(?:/[^/]+/|\?.*?\bn?id=)(?P<id>\d+)' _TESTS = [{ 'url': 'http://news.sportbox.ru/vdl/player/ci/211355', 'info_dict': { 'id': '211355', 'ext': 'mp4', 'title': 'В Новороссийске прошел детский турнир «Поле славы боевой»', 'thumbnail': r're:^https?://.*\.jpg$', }, 'params': { # m3u8 download 'skip_download': True, }, }, { 'url': 'http://news.sportbox.ru/vdl/player?nid=370908&only_player=1&autostart=false&playeri=2&height=340&width=580', 'only_matching': True, }] @staticmethod def _extract_urls(webpage): return re.findall( r'<iframe[^>]+src="(https?://news\.sportbox\.ru/vdl/player[^"]+)"', webpage) def _real_extract(self, url): video_id = self._match_id(url) webpage = self._download_webpage(url, video_id) formats = [] def cleanup_js(code): # desktop_advert_config contains complex Javascripts and we don't need it return js_to_json(re.sub(r'desktop_advert_config.*', '', code)) jwplayer_data = self._parse_json(self._search_regex( r'(?s)player\.setup\(({.+?})\);', webpage, 'jwplayer settings'), video_id, transform_source=cleanup_js) hls_url = jwplayer_data.get('hls_url') if hls_url: formats.extend(self._extract_m3u8_formats( hls_url, video_id, ext='mp4', m3u8_id='hls')) rtsp_url = jwplayer_data.get('rtsp_url') if rtsp_url: formats.append({ 'url': rtsp_url, 'format_id': 'rtsp', }) self._sort_formats(formats) title = jwplayer_data['node_title'] thumbnail = jwplayer_data.get('image_url') return { 'id': video_id, 'title': title, 'thumbnail': thumbnail, 'formats': formats, }
gpl-3.0
eunchong/build
third_party/twisted_10_2/twisted/words/im/pbsupport.py
55
9661
# Copyright (c) 2001-2004 Twisted Matrix Laboratories. # See LICENSE for details. """L{twisted.words} support for Instance Messenger.""" from __future__ import nested_scopes from twisted.internet import defer from twisted.internet import error from twisted.python import log from twisted.python.failure import Failure from twisted.spread import pb from twisted.words.im.locals import ONLINE, OFFLINE, AWAY from twisted.words.im import basesupport, interfaces from zope.interface import implements class TwistedWordsPerson(basesupport.AbstractPerson): """I a facade for a person you can talk to through a twisted.words service. """ def __init__(self, name, wordsAccount): basesupport.AbstractPerson.__init__(self, name, wordsAccount) self.status = OFFLINE def isOnline(self): return ((self.status == ONLINE) or (self.status == AWAY)) def getStatus(self): return self.status def sendMessage(self, text, metadata): """Return a deferred... """ if metadata: d=self.account.client.perspective.directMessage(self.name, text, metadata) d.addErrback(self.metadataFailed, "* "+text) return d else: return self.account.client.perspective.callRemote('directMessage',self.name, text) def metadataFailed(self, result, text): print "result:",result,"text:",text return self.account.client.perspective.directMessage(self.name, text) def setStatus(self, status): self.status = status self.chat.getContactsList().setContactStatus(self) class TwistedWordsGroup(basesupport.AbstractGroup): implements(interfaces.IGroup) def __init__(self, name, wordsClient): basesupport.AbstractGroup.__init__(self, name, wordsClient) self.joined = 0 def sendGroupMessage(self, text, metadata=None): """Return a deferred. """ #for backwards compatibility with older twisted.words servers. if metadata: d=self.account.client.perspective.callRemote( 'groupMessage', self.name, text, metadata) d.addErrback(self.metadataFailed, "* "+text) return d else: return self.account.client.perspective.callRemote('groupMessage', self.name, text) def setTopic(self, text): self.account.client.perspective.callRemote( 'setGroupMetadata', {'topic': text, 'topic_author': self.client.name}, self.name) def metadataFailed(self, result, text): print "result:",result,"text:",text return self.account.client.perspective.callRemote('groupMessage', self.name, text) def joining(self): self.joined = 1 def leaving(self): self.joined = 0 def leave(self): return self.account.client.perspective.callRemote('leaveGroup', self.name) class TwistedWordsClient(pb.Referenceable, basesupport.AbstractClientMixin): """In some cases, this acts as an Account, since it a source of text messages (multiple Words instances may be on a single PB connection) """ def __init__(self, acct, serviceName, perspectiveName, chatui, _logonDeferred=None): self.accountName = "%s (%s:%s)" % (acct.accountName, serviceName, perspectiveName) self.name = perspectiveName print "HELLO I AM A PB SERVICE", serviceName, perspectiveName self.chat = chatui self.account = acct self._logonDeferred = _logonDeferred def getPerson(self, name): return self.chat.getPerson(name, self) def getGroup(self, name): return self.chat.getGroup(name, self) def getGroupConversation(self, name): return self.chat.getGroupConversation(self.getGroup(name)) def addContact(self, name): self.perspective.callRemote('addContact', name) def remote_receiveGroupMembers(self, names, group): print 'received group members:', names, group self.getGroupConversation(group).setGroupMembers(names) def remote_receiveGroupMessage(self, sender, group, message, metadata=None): print 'received a group message', sender, group, message, metadata self.getGroupConversation(group).showGroupMessage(sender, message, metadata) def remote_memberJoined(self, member, group): print 'member joined', member, group self.getGroupConversation(group).memberJoined(member) def remote_memberLeft(self, member, group): print 'member left' self.getGroupConversation(group).memberLeft(member) def remote_notifyStatusChanged(self, name, status): self.chat.getPerson(name, self).setStatus(status) def remote_receiveDirectMessage(self, name, message, metadata=None): self.chat.getConversation(self.chat.getPerson(name, self)).showMessage(message, metadata) def remote_receiveContactList(self, clist): for name, status in clist: self.chat.getPerson(name, self).setStatus(status) def remote_setGroupMetadata(self, dict_, groupName): if dict_.has_key("topic"): self.getGroupConversation(groupName).setTopic(dict_["topic"], dict_.get("topic_author", None)) def joinGroup(self, name): self.getGroup(name).joining() return self.perspective.callRemote('joinGroup', name).addCallback(self._cbGroupJoined, name) def leaveGroup(self, name): self.getGroup(name).leaving() return self.perspective.callRemote('leaveGroup', name).addCallback(self._cbGroupLeft, name) def _cbGroupJoined(self, result, name): groupConv = self.chat.getGroupConversation(self.getGroup(name)) groupConv.showGroupMessage("sys", "you joined") self.perspective.callRemote('getGroupMembers', name) def _cbGroupLeft(self, result, name): print 'left',name groupConv = self.chat.getGroupConversation(self.getGroup(name), 1) groupConv.showGroupMessage("sys", "you left") def connected(self, perspective): print 'Connected Words Client!', perspective if self._logonDeferred is not None: self._logonDeferred.callback(self) self.perspective = perspective self.chat.getContactsList() pbFrontEnds = { "twisted.words": TwistedWordsClient, "twisted.reality": None } class PBAccount(basesupport.AbstractAccount): implements(interfaces.IAccount) gatewayType = "PB" _groupFactory = TwistedWordsGroup _personFactory = TwistedWordsPerson def __init__(self, accountName, autoLogin, username, password, host, port, services=None): """ @param username: The name of your PB Identity. @type username: string """ basesupport.AbstractAccount.__init__(self, accountName, autoLogin, username, password, host, port) self.services = [] if not services: services = [('twisted.words', 'twisted.words', username)] for serviceType, serviceName, perspectiveName in services: self.services.append([pbFrontEnds[serviceType], serviceName, perspectiveName]) def logOn(self, chatui): """ @returns: this breaks with L{interfaces.IAccount} @returntype: DeferredList of L{interfaces.IClient}s """ # Overriding basesupport's implementation on account of the # fact that _startLogOn tends to return a deferredList rather # than a simple Deferred, and we need to do registerAccountClient. if (not self._isConnecting) and (not self._isOnline): self._isConnecting = 1 d = self._startLogOn(chatui) d.addErrback(self._loginFailed) def registerMany(results): for success, result in results: if success: chatui.registerAccountClient(result) self._cb_logOn(result) else: log.err(result) d.addCallback(registerMany) return d else: raise error.ConnectionError("Connection in progress") def _startLogOn(self, chatui): print 'Connecting...', d = pb.getObjectAt(self.host, self.port) d.addCallbacks(self._cbConnected, self._ebConnected, callbackArgs=(chatui,)) return d def _cbConnected(self, root, chatui): print 'Connected!' print 'Identifying...', d = pb.authIdentity(root, self.username, self.password) d.addCallbacks(self._cbIdent, self._ebConnected, callbackArgs=(chatui,)) return d def _cbIdent(self, ident, chatui): if not ident: print 'falsely identified.' return self._ebConnected(Failure(Exception("username or password incorrect"))) print 'Identified!' dl = [] for handlerClass, sname, pname in self.services: d = defer.Deferred() dl.append(d) handler = handlerClass(self, sname, pname, chatui, d) ident.callRemote('attach', sname, pname, handler).addCallback(handler.connected) return defer.DeferredList(dl) def _ebConnected(self, error): print 'Not connected.' return error
bsd-3-clause
vilorious/pyload
module/web/pyload_app.py
33
15873
#!/usr/bin/env python # -*- coding: utf-8 -*- """ 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/>. @author: RaNaN """ from datetime import datetime from operator import itemgetter, attrgetter import time import os import sys from os import listdir from os.path import isdir, isfile, join, abspath from sys import getfilesystemencoding from urllib import unquote from bottle import route, static_file, request, response, redirect, HTTPError, error from webinterface import PYLOAD, PYLOAD_DIR, PROJECT_DIR, SETUP, env from utils import render_to_response, parse_permissions, parse_userdata, \ login_required, get_permission, set_permission, permlist, toDict, set_session from filters import relpath, unquotepath from module.utils import formatSize, save_join, fs_encode, fs_decode # Helper def pre_processor(): s = request.environ.get('beaker.session') user = parse_userdata(s) perms = parse_permissions(s) status = {} captcha = False update = False plugins = False if user["is_authenticated"]: status = PYLOAD.statusServer() info = PYLOAD.getInfoByPlugin("UpdateManager") captcha = PYLOAD.isCaptchaWaiting() # check if update check is available if info: if info["pyload"] == "True": update = True if info["plugins"] == "True": plugins = True return {"user": user, 'status': status, 'captcha': captcha, 'perms': perms, 'url': request.url, 'update': update, 'plugins': plugins} def base(messages): return render_to_response('base.html', {'messages': messages}, [pre_processor]) ## Views @error(500) def error500(error): print "An error occured while processing the request." if error.traceback: print error.traceback return base(["An Error occured, please enable debug mode to get more details.", error, error.traceback.replace("\n", "<br>") if error.traceback else "No Traceback"]) # render js @route("/media/js/<path:re:.+\.js>") def js_dynamic(path): response.headers['Expires'] = time.strftime("%a, %d %b %Y %H:%M:%S GMT", time.gmtime(time.time() + 60 * 60 * 24 * 2)) response.headers['Cache-control'] = "public" response.headers['Content-Type'] = "text/javascript; charset=UTF-8" try: # static files are not rendered if "static" not in path and "mootools" not in path: t = env.get_template("js/%s" % path) return t.render() else: return static_file(path, root=join(PROJECT_DIR, "media", "js")) except: return HTTPError(404, "Not Found") @route('/media/<path:path>') def server_static(path): response.headers['Expires'] = time.strftime("%a, %d %b %Y %H:%M:%S GMT", time.gmtime(time.time() + 60 * 60 * 24 * 7)) response.headers['Cache-control'] = "public" return static_file(path, root=join(PROJECT_DIR, "media")) @route('/favicon.ico') def favicon(): return static_file("favicon.ico", root=join(PROJECT_DIR, "media", "img")) @route('/login', method="GET") def login(): if not PYLOAD and SETUP: redirect("/setup") else: return render_to_response("login.html", proc=[pre_processor]) @route('/nopermission') def nopermission(): return base([_("You dont have permission to access this page.")]) @route("/login", method="POST") def login_post(): user = request.forms.get("username") password = request.forms.get("password") info = PYLOAD.checkAuth(user, password) if not info: return render_to_response("login.html", {"errors": True}, [pre_processor]) set_session(request, info) return redirect("/") @route("/logout") def logout(): s = request.environ.get('beaker.session') s.delete() return render_to_response("logout.html", proc=[pre_processor]) @route("/") @route("/home") @login_required("LIST") def home(): try: res = [toDict(x) for x in PYLOAD.statusDownloads()] except: s = request.environ.get('beaker.session') s.delete() return redirect("/login") for link in res: if link["status"] == 12: link["information"] = "%s kB @ %s kB/s" % (link["size"] - link["bleft"], link["speed"]) return render_to_response("home.html", {"res": res}, [pre_processor]) @route("/queue") @login_required("LIST") def queue(): queue = PYLOAD.getQueue() queue.sort(key=attrgetter("order")) return render_to_response('queue.html', {'content': queue, 'target': 1}, [pre_processor]) @route("/collector") @login_required('LIST') def collector(): queue = PYLOAD.getCollector() queue.sort(key=attrgetter("order")) return render_to_response('queue.html', {'content': queue, 'target': 0}, [pre_processor]) @route("/downloads") @login_required('DOWNLOAD') def downloads(): root = PYLOAD.getConfigValue("general", "download_folder") if not isdir(root): return base([_('Download directory not found.')]) data = { 'folder': [], 'files': [] } items = listdir(fs_encode(root)) for item in sorted([fs_decode(x) for x in items]): if isdir(save_join(root, item)): folder = { 'name': item, 'path': item, 'files': [] } files = listdir(save_join(root, item)) for file in sorted([fs_decode(x) for x in files]): try: if isfile(save_join(root, item, file)): folder['files'].append(file) except: pass data['folder'].append(folder) elif isfile(join(root, item)): data['files'].append(item) return render_to_response('downloads.html', {'files': data}, [pre_processor]) @route("/downloads/get/<path:re:.+>") @login_required("DOWNLOAD") def get_download(path): path = unquote(path).decode("utf8") #@TODO some files can not be downloaded root = PYLOAD.getConfigValue("general", "download_folder") path = path.replace("..", "") try: return static_file(fs_encode(path), fs_encode(root)) except Exception, e: print e return HTTPError(404, "File not Found.") @route("/settings") @login_required('SETTINGS') def config(): conf = PYLOAD.getConfig() plugin = PYLOAD.getPluginConfig() conf_menu = [] plugin_menu = [] for entry in sorted(conf.keys()): conf_menu.append((entry, conf[entry].description)) for entry in sorted(plugin.keys()): plugin_menu.append((entry, plugin[entry].description)) accs = PYLOAD.getAccounts(False) for data in accs: if data.trafficleft == -1: data.trafficleft = _("unlimited") elif not data.trafficleft: data.trafficleft = _("not available") else: data.trafficleft = formatSize(data.trafficleft * 1024) if data.validuntil == -1: data.validuntil = _("unlimited") elif not data.validuntil : data.validuntil = _("not available") else: t = time.localtime(data.validuntil) data.validuntil = time.strftime("%d.%m.%Y", t) if "time" in data.options: try: data.options["time"] = data.options["time"][0] except: data.options["time"] = "0:00-0:00" if "limitDL" in data.options: data.options["limitdl"] = data.options["limitDL"][0] else: data.options["limitdl"] = "0" return render_to_response('settings.html', {'conf': {'plugin': plugin_menu, 'general': conf_menu, 'accs': accs}, 'types': PYLOAD.getAccountTypes()}, [pre_processor]) @route("/filechooser") @route("/pathchooser") @route("/filechooser/:file#.+#") @route("/pathchooser/:path#.+#") @login_required('STATUS') def path(file="", path=""): if file: type = "file" else: type = "folder" path = os.path.normpath(unquotepath(path)) if os.path.isfile(path): oldfile = path path = os.path.dirname(path) else: oldfile = '' abs = False if os.path.isdir(path): if os.path.isabs(path): cwd = os.path.abspath(path) abs = True else: cwd = relpath(path) else: cwd = os.getcwd() try: cwd = cwd.encode("utf8") except: pass cwd = os.path.normpath(os.path.abspath(cwd)) parentdir = os.path.dirname(cwd) if not abs: if os.path.abspath(cwd) == "/": cwd = relpath(cwd) else: cwd = relpath(cwd) + os.path.sep parentdir = relpath(parentdir) + os.path.sep if os.path.abspath(cwd) == "/": parentdir = "" try: folders = os.listdir(cwd) except: folders = [] files = [] for f in folders: try: f = f.decode(getfilesystemencoding()) data = {'name': f, 'fullpath': join(cwd, f)} data['sort'] = data['fullpath'].lower() data['modified'] = datetime.fromtimestamp(int(os.path.getmtime(join(cwd, f)))) data['ext'] = os.path.splitext(f)[1] except: continue if os.path.isdir(join(cwd, f)): data['type'] = 'dir' else: data['type'] = 'file' if os.path.isfile(join(cwd, f)): data['size'] = os.path.getsize(join(cwd, f)) power = 0 while (data['size'] / 1024) > 0.3: power += 1 data['size'] /= 1024. units = ('', 'K', 'M', 'G', 'T') data['unit'] = units[power] + 'Byte' else: data['size'] = '' files.append(data) files = sorted(files, key=itemgetter('type', 'sort')) return render_to_response('pathchooser.html', {'cwd': cwd, 'files': files, 'parentdir': parentdir, 'type': type, 'oldfile': oldfile, 'absolute': abs}, []) @route("/logs") @route("/logs", method="POST") @route("/logs/:item") @route("/logs/:item", method="POST") @login_required('LOGS') def logs(item=-1): s = request.environ.get('beaker.session') perpage = s.get('perpage', 34) reversed = s.get('reversed', False) warning = "" conf = PYLOAD.getConfigValue("log","file_log") if not conf: warning = "Warning: File log is disabled, see settings page." perpage_p = ((20, 20), (34, 34), (40, 40), (100, 100), (0, 'all')) fro = None if request.environ.get('REQUEST_METHOD', "GET") == "POST": try: fro = datetime.strptime(request.forms['from'], '%d.%m.%Y %H:%M:%S') except: pass try: perpage = int(request.forms['perpage']) s['perpage'] = perpage reversed = bool(request.forms.get('reversed', False)) s['reversed'] = reversed except: pass s.save() try: item = int(item) except: pass log = PYLOAD.getLog() if not perpage: item = 0 if item < 1 or type(item) is not int: item = 1 if len(log) - perpage + 1 < 1 else len(log) - perpage + 1 if type(fro) is datetime: # we will search for datetime item = -1 data = [] counter = 0 perpagecheck = 0 for l in log: counter += 1 if counter >= item: try: date, time, level, message = l.decode("utf8", "ignore").split(" ", 3) dtime = datetime.strptime(date + ' ' + time, '%d.%m.%Y %H:%M:%S') except: dtime = None date = '?' time = ' ' level = '?' message = l if item == -1 and dtime is not None and fro <= dtime: item = counter #found our datetime if item >= 0: data.append({'line': counter, 'date': date + " " + time, 'level': level, 'message': message}) perpagecheck += 1 if fro is None and dtime is not None: #if fro not set set it to first showed line fro = dtime if perpagecheck >= perpage > 0: break if fro is None: #still not set, empty log? fro = datetime.now() if reversed: data.reverse() return render_to_response('logs.html', {'warning': warning, 'log': data, 'from': fro.strftime('%d.%m.%Y %H:%M:%S'), 'reversed': reversed, 'perpage': perpage, 'perpage_p': sorted(perpage_p), 'iprev': 1 if item - perpage < 1 else item - perpage, 'inext': (item + perpage) if item + perpage < len(log) else item}, [pre_processor]) @route("/admin") @route("/admin", method="POST") @login_required("ADMIN") def admin(): # convert to dict user = dict([(name, toDict(y)) for name, y in PYLOAD.getAllUserData().iteritems()]) perms = permlist() for data in user.itervalues(): data["perms"] = {} get_permission(data["perms"], data["permission"]) data["perms"]["admin"] = True if data["role"] is 0 else False s = request.environ.get('beaker.session') if request.environ.get('REQUEST_METHOD', "GET") == "POST": for name in user: if request.POST.get("%s|admin" % name, False): user[name]["role"] = 0 user[name]["perms"]["admin"] = True elif name != s["name"]: user[name]["role"] = 1 user[name]["perms"]["admin"] = False # set all perms to false for perm in perms: user[name]["perms"][perm] = False for perm in request.POST.getall("%s|perms" % name): user[name]["perms"][perm] = True user[name]["permission"] = set_permission(user[name]["perms"]) PYLOAD.setUserPermission(name, user[name]["permission"], user[name]["role"]) return render_to_response("admin.html", {"users": user, "permlist": perms}, [pre_processor]) @route("/setup") def setup(): if PYLOAD or not SETUP: return base([_("Run pyLoadCore.py -s to access the setup.")]) return render_to_response('setup.html', {"user": False, "perms": False}) @route("/info") def info(): conf = PYLOAD.getConfigDict() if hasattr(os, "uname"): extra = os.uname() else: extra = tuple() data = {"python": sys.version, "os": " ".join((os.name, sys.platform) + extra), "version": PYLOAD.getServerVersion(), "folder": abspath(PYLOAD_DIR), "config": abspath(""), "download": abspath(conf["general"]["download_folder"]["value"]), "freespace": formatSize(PYLOAD.freeSpace()), "remote": conf["remote"]["port"]["value"], "webif": conf["webinterface"]["port"]["value"], "language": conf["general"]["language"]["value"]} return render_to_response("info.html", data, [pre_processor])
gpl-3.0
tuxofil/Gps2Udp
misc/server/gps2udp.py
1
5891
#!/usr/bin/env python """ Receive Geo location data from the Gps2Udp Android application via UDP/IP and forward them to the stdout line by line. There is some requirements to a valid incoming packet: - it must be of form: TIMESTAMP LATITUDE LONGITUDE ACCURACY [other fields]; - TIMESTAMP is a Unix timestamp (seconds since 1 Jan 1970); - the diff between TIMESTAMP and local time must be less than MAX_TIME_DIFF (definition of the MAX_TIME_DIFF variable see below); - TIMESTAMP must be greater than timestamp of a previous valid packet; - LATITUDE is a float between [-90.0..90.0]; - LONGITUDE is a float between [-180.0..180.0]; - ACCURACY is an integer between [0..MAX_ACCURACY] (definition of MAX_ACCURACY variable see below). If any of the requirements are not met, the packet will be silently ignored. When started with --signed command line option, an extra field must be defined in each incoming UDP packet - DIGEST. With the field common packet format must be of form: TIMESTAMP LATITUDE LONGITUDE ACCURACY DIGEST DIGEST - is a SHA1 from "TIMESTAMP LATITUDE LONGITUDE ACCURACY" + secret string known only by Gps2Udp client (Android app) and the server. The server reads the secret from GPS2UDP_SECRET environment variable. Important notes. When in --signed mode: - any packet without the digest will be ignored; - any packet with digest not matched with digest calculated on the server side, will be ignored; - if the secret is not defined (GPS2UDP_SECRET environment variable is not set or empty), no packets will be matched as valid. """ import getopt import hashlib import os import os.path import socket import sys import time DEFAULT_PORT = 5000 # Maximum time difference between a timestamp in a packet and # the local Unix timestamp (in seconds). MAX_TIME_DIFF = 60 * 5 # Maximum valid accuracy value (in meters). MAX_ACCURACY = 10000 # 10km # Here will be stored the timestamp of the last valid packet received. # The timestamp will be used later to avoid receiving data from the past. LAST_TIMESTAMP = None def usage(exitcode = 1): """ Show usage info and exit. """ argv0 = os.path.basename(sys.argv[0]) print 'Usage: {0} [options]'.format(argv0) print ' Options:' print ' --signed check every UDP packet for digital signature;' print ' --port=N UDP port number to listen. Default is 5000.' sys.exit(exitcode) def main(): """ Entry point. """ try: cmd_opts, _cmd_args = getopt.getopt( sys.argv[1:], '', ['port=', 'signed']) except getopt.GetoptError as exc: sys.stderr.write('Error: ' + str(exc) + '\n') usage() cmd_opts = dict(cmd_opts) port = int(cmd_opts.get('--port', str(DEFAULT_PORT))) signed = '--signed' in cmd_opts sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) sock.bind(('', port)) while True: data, _addr = sock.recvfrom(100) try: result = parse_packet(data, signed) except PacketParseError: continue sys.stdout.write(format_packet(result)) sys.stdout.flush() class PacketParseError(Exception): """Bad packet received.""" pass def parse_packet(data, signed = False): """ Parse and check incoming packet. The packet must be of form: TIMESTAMP LATITUDE LONGITUDE ACCURACY :param data: packet body :type data: string :param signed: if True, the packet will be checked for a valid digital signature :type signed: boolean :rtype: dict """ global LAST_TIMESTAMP result = {} tokens = [elem for elem in data.strip().split(' ') if elem] if signed: # check the signature if len(tokens) < 5: raise PacketParseError payload = ' '.join(tokens[:4]) digest = tokens[4] secret = os.environ.get('GPS2UDP_SECRET') if secret is None or len(secret) == 0: # secret is not defined => unable to check raise PacketParseError hasher = hashlib.sha1() hasher.update(payload + secret) if hasher.hexdigest() != digest: # digital signature mismatch raise PacketParseError else: # check tokens count if len(tokens) < 4: raise PacketParseError # parse the tokens try: result['timestamp'] = int(tokens[0]) result['latitude'] = float(tokens[1]) result['longitude'] = float(tokens[2]) result['accuracy'] = int(tokens[3]) except ValueError: raise PacketParseError # check timestamp time_diff = abs(result['timestamp'] - int(time.time())) if time_diff > MAX_TIME_DIFF: # the timestamp differs from NOW for more than 5 minutes raise PacketParseError if LAST_TIMESTAMP is not None: if result['timestamp'] <= LAST_TIMESTAMP: # the timestamp is not greater than the previous timestamp raise PacketParseError # check lat&long values if not (-90.0 <= result['latitude'] <= 90.0): raise PacketParseError if not (-180.0 <= result['longitude'] <= 180.0): raise PacketParseError # check accuracy value if result['accuracy'] < 0 or result['accuracy'] > MAX_ACCURACY: raise PacketParseError # All checks is passed => packet is valid. # Save the timestamp in global var: LAST_TIMESTAMP = result['timestamp'] return result def format_packet(data): """ Format received packet for the stdout. :param data: packet data :type data: dict :rtype: string """ return (str(data['timestamp']) + ' ' + format(data['latitude'], '.7f') + ' ' + format(data['longitude'], '.7f') + ' ' + str(data['accuracy']) + '\n') if __name__ == '__main__': try: main() except KeyboardInterrupt: sys.exit(1)
bsd-2-clause
evewspace/eve-wspace
evewspace/Alerts/tasks.py
5
1651
# Eve W-Space # Copyright 2014 Andrew Austin and contributors # # 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 celery import task from Alerts.models import SubscriptionGroup from Alerts import method_registry from django.contrib.auth import get_user_model User = get_user_model() @task def send_alert(from_user, sub_group, message, subject): """ Send an alert through all methods for sub_group. """ # Validate permissions if not sub_group.get_user_perms(from_user)[0]: raise AttributeError("User does not have broadcast permissions.") else: # Build list of users who are eligible to recieve alerts to_list = [] if not method_registry.registry: method_registry.autodiscover() for user in User.objects.filter(is_active=True): if user.has_perm('Alerts.can_alert'): to_list.append(user) results = {} for method in method_registry.registry: results[method] = method_registry.registry[method]().send_alert( to_list, subject, message, from_user, sub_group) return results
apache-2.0
Puppet-Finland/trac
files/spam-filter/tracspamfilter/captcha/keycaptcha.py
1
4322
# -*- coding: utf-8 -*- # # Copyright (C) 2015 Dirk Stöcker <trac@dstoecker.de> # All rights reserved. # # This software is licensed as described in the file COPYING, which # you should have received as part of this distribution. The terms # are also available at http://trac.edgewall.com/license.html. # # This software consists of voluntary contributions made by many # individuals. For the exact contribution history, see the revision # history and logs, available at http://projects.edgewall.com/trac/. import hashlib import random import urllib2 from trac.config import Option from trac.core import Component, implements from trac.util.html import tag from tracspamfilter.api import user_agent from tracspamfilter.captcha import ICaptchaMethod class KeycaptchaCaptcha(Component): """KeyCaptcha implementation""" implements(ICaptchaMethod) private_key = Option('spam-filter', 'captcha_keycaptcha_private_key', '', """Private key for KeyCaptcha usage.""", doc_domain="tracspamfilter") user_id = Option('spam-filter', 'captcha_keycaptcha_user_id', '', """User id for KeyCaptcha usage.""", doc_domain="tracspamfilter") def generate_captcha(self, req): session_id = "%d-3.4.0.001" % random.randint(1, 10000000) sign1 = hashlib.md5(session_id + req.remote_addr + self.private_key).hexdigest() sign2 = hashlib.md5(session_id + self.private_key).hexdigest() varblock = "var s_s_c_user_id = '%s';\n" % self.user_id varblock += "var s_s_c_session_id = '%s';\n" % session_id varblock += "var s_s_c_captcha_field_id = 'keycaptcha_response_field';\n" varblock += "var s_s_c_submit_button_id = 'keycaptcha_response_button';\n" varblock += "var s_s_c_web_server_sign = '%s';\n" % sign1 varblock += "var s_s_c_web_server_sign2 = '%s';\n" % sign2 varblock += "document.s_s_c_debugmode=1;\n" fragment = tag(tag.script(varblock, type='text/javascript')) fragment.append( tag.script(type='text/javascript', src='http://backs.keycaptcha.com/swfs/cap.js') ) fragment.append( tag.input(type='hidden', id='keycaptcha_response_field', name='keycaptcha_response_field') ) fragment.append( tag.input(type='submit', id='keycaptcha_response_button', name='keycaptcha_response_button') ) req.session['captcha_key_session'] = session_id return None, fragment def verify_key(self, private_key, user_id): if private_key is None or user_id is None: return False # FIXME - Not yet implemented return True def verify_captcha(self, req): session = None if 'captcha_key_session' in req.session: session = req.session['captcha_key_session'] del req.session['captcha_key_session'] response_field = req.args.get('keycaptcha_response_field') val = response_field.split('|') s = hashlib.md5('accept' + val[1] + self.private_key + val[2]).hexdigest() self.log.debug("KeyCaptcha response: %s .. %s .. %s", response_field, s, session) if s == val[0] and session == val[3]: try: request = urllib2.Request( url=val[2], headers={"User-agent": user_agent} ) response = urllib2.urlopen(request) return_values = response.read() response.close() except Exception, e: self.log.warning("Exception in KeyCaptcha handling (%s)", e) else: self.log.debug("KeyCaptcha check result: %s", return_values) if return_values == '1': return True self.log.warning("KeyCaptcha returned invalid check result: " "%s (%s)", return_values, response_field) else: self.log.warning("KeyCaptcha returned invalid data: " "%s (%s,%s)", response_field, s, session) return False def is_usable(self, req): return self.private_key and self.user_id
bsd-2-clause
tombstone/models
research/domain_adaptation/domain_separation/grl_ops.py
16
1124
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """GradientReversal op Python library.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import os.path import tensorflow as tf tf.logging.info(tf.resource_loader.get_data_files_path()) _grl_ops_module = tf.load_op_library( os.path.join(tf.resource_loader.get_data_files_path(), '_grl_ops.so')) gradient_reversal = _grl_ops_module.gradient_reversal
apache-2.0
dbmi-pitt/EvidenceType-Calculator
source/evidence_type_calculator/languages/de.py
4
10534
# -*- coding: utf-8 -*- { '!langcode!': 'de', '!langname!': 'Deutsch (DE)', '"update" is an optional expression like "field1=\'newvalue\'". You cannot update or delete the results of a JOIN': '"Update" ist ein optionaler Ausdruck wie "feld1=\'newvalue\'". JOIN Ergebnisse können nicht aktualisiert oder gelöscht werden', '%s %%(shop)': '%s %%(shop)', '%s %%(shop[0])': '%s %%(shop[0])', '%s %%{quark[0]}': '%s %%{quark[0]}', '%s %%{row} deleted': '%s %%{row} gelöscht', '%s %%{row} updated': '%s %%{row} aktualisiert', '%s %%{shop[0]}': '%s %%{shop[0]}', '%s %%{shop}': '%s %%{shop}', '%s selected': '%s ausgewählt', '%Y-%m-%d': '%Y-%m-%d', '%Y-%m-%d %H:%M:%S': '%Y-%m-%d %H:%M:%S', '(**%.0d MB**)': '(**%.0d MB**)', '**%(items)s** %%{item(items)}, **%(bytes)s** %%{byte(bytes)}': '**%(items)s** %%{item(items)}, **%(bytes)s** %%{byte(bytes)}', '**%(items)s** items, **%(bytes)s** %%{byte(bytes)}': '**%(items)s** items, **%(bytes)s** %%{byte(bytes)}', '**not available** (requires the Python [[guppy http://pypi.python.org/pypi/guppy/ popup]] library)': '**nicht verfügbar** (benötigt die Python [[guppy http://pypi.python.org/pypi/guppy/ popup]] Bibliothek)', '?': '?', '@markmin\x01**Hello World**': '**Hallo Welt**', '@markmin\x01An error occured, please [[reload %s]] the page': 'Ein Fehler ist aufgetreten, bitte [[laden %s]] Sie die Seite neu', '``**not available**``:red (requires the Python [[guppy http://pypi.python.org/pypi/guppy/ popup]] library)': '``**nicht verfügbar**``:rot (benötigt die Python [[guppy http://pypi.python.org/pypi/guppy/ popup]] Bibliothek)', 'About': 'Über', 'Access Control': 'Zugangskontrolle', 'admin': 'admin', 'Administrative Interface': 'Administrationsoberfläche', 'Ajax Recipes': 'Ajax Rezepte', 'An error occured, please [[reload %s]] the page': 'Ein Fehler ist aufgetreten, bitte [[laden %s]] Sie die Seite neu', 'appadmin is disabled because insecure channel': 'Appadmin ist deaktiviert, wegen der Benutzung eines unsicheren Kanals', 'Are you sure you want to delete this object?': 'Sind Sie sich sicher, dass Sie dieses Objekt löschen wollen?', 'Available Databases and Tables': 'Verfügbare Datenbanken und Tabellen', 'Buy this book': 'Dieses Buch kaufen', "Buy web2py's book": "web2py's Buch kaufen", 'cache': 'cache', 'Cache': 'Cache', 'Cache Cleared': 'Cache geleert', 'Cache contains items up to **%(hours)02d** %%{hour(hours)} **%(min)02d** %%{minute(min)} **%(sec)02d** %%{second(sec)} old.': 'Cache enthält items die bis zu **%(hours)02d** %%{hour(hours)} **%(min)02d** %%{minute(min)} **%(sec)02d** %%{second(sec)} alt sind.', 'Cache Keys': 'Cache Schlüssel', 'Cannot be empty': 'Darf nicht leer sein', 'Check to delete': 'Auswählen um zu löschen', 'Clear CACHE?': 'CACHE löschen?', 'Clear DISK': 'DISK löschen', 'Clear RAM': 'RAM löschen', 'Client IP': 'Client IP', 'Community': 'Community', 'Components and Plugins': 'Komponenten und Plugins', 'Config.ini': 'Config.ini', 'Controller': 'Controller', 'Copyright': 'Copyright', 'Created By': 'Erstellt von', 'Created On': 'Erstellt am', 'Current request': 'Derzeitiger Request', 'Current response': 'Derzeitige Response', 'Current session': 'Derzeitige Session', 'customize me!': 'Pass mich an!', 'data uploaded': 'Datei hochgeladen', 'Database': 'Datenbank', 'Database %s select': 'Datenbank %s ausgewählt', 'Database Administration (appadmin)': 'Datenbankadministration (appadmin)', 'db': 'db', 'DB Model': 'Muster-DB', 'Delete:': 'Lösche:', 'Demo': 'Demo', 'Deployment Recipes': 'Entwicklungsrezepte', 'Description': 'Beschreibung', 'design': 'Design', 'Design': 'Design', 'DISK': 'DISK', 'Disk Cache Keys': 'Disk Cache Keys', 'Disk Cleared': 'Disk gelöscht', 'DISK contains items up to **%(hours)02d** %%{hour(hours)} **%(min)02d** %%{minute(min)} **%(sec)02d** %%{second(sec)} old.': 'DISK enthält items die bis zu **%(hours)02d** %%{hour(hours)} **%(min)02d** %%{minute(min)} **%(sec)02d** %%{second(sec)} alt sind.', 'Documentation': 'Dokumentation', "Don't know what to do?": 'Wissen Sie nicht weiter?', 'done!': 'Fertig!', 'Download': 'Download', 'E-mail': 'E-mail', 'Edit current record': 'Diesen Eintrag editieren', 'Email and SMS': 'Email und SMS', 'Enter an integer between %(min)g and %(max)g': 'Eine Zahl zwischen %(min)g und %(max)g eingeben', 'enter an integer between %(min)g and %(max)g': 'eine Zahl zwischen %(min)g und %(max)g eingeben', 'enter date and time as %(format)s': 'ein Datum und eine Uhrzeit als %(format)s eingeben', 'Errors': 'Fehlermeldungen', 'export as csv file': 'als csv Datei exportieren', 'FAQ': 'FAQ', 'First name': 'Vorname', 'Forms and Validators': 'Forms und Validators', 'Free Applications': 'Kostenlose Anwendungen', 'Graph Model': 'Muster-Graph', 'Group %(group_id)s created': 'Gruppe %(group_id)s erstellt', 'Group ID': 'Gruppen ID', 'Group uniquely assigned to user %(id)s': 'Gruppe eindeutigem Benutzer %(id)s zugewiesen', 'Groups': 'Gruppen', 'Hello World': 'Hallo Welt', 'Hello World ## Kommentar': 'Hallo Welt ', 'Hello World## Kommentar': 'Hallo Welt', 'Helping web2py': 'Helping web2py', 'Hit Ratio: **%(ratio)s%%** (**%(hits)s** %%{hit(hits)} and **%(misses)s** %%{miss(misses)})': 'Trefferquote: **%(ratio)s%%** (**%(hits)s** %%{hit(hits)} und **%(misses)s** %%{miss(misses)})', 'Home': 'Startseite', 'How did you get here?': 'Wie sind Sie hier her gelangt?', 'import': 'Importieren', 'Import/Export': 'Importieren/Exportieren', 'Internal State': 'Innerer Zustand', 'Introduction': 'Einführung', 'Invalid email': 'Ungültige Email', 'Invalid Query': 'Ungültige Query', 'invalid request': 'Ungültiger Request', 'Is Active': 'Ist aktiv', 'Key': 'Schlüssel', 'Last name': 'Nachname', 'Layout': 'Layout', 'Layout Plugins': 'Layout Plugins', 'Layouts': 'Layouts', 'Live Chat': 'Live Chat', 'Log In': 'Log In', 'Logged in': 'Eingeloggt', 'Logged out': 'Ausgeloggt', 'Login': 'Einloggen', 'Logout': 'Ausloggen', 'Lost Password': 'Passwort vergessen', 'Lost password?': 'Passwort vergessen?', 'Manage %(action)s': '%(action)s verwalten', 'Manage Access Control': 'Zugangskontrolle verwalten', 'Manage Cache': 'Cache verwalten', 'Memberships': 'Mitgliedschaften', 'Menu Model': 'Menü-Muster', 'Modified By': 'Verändert von', 'Modified On': 'Verändert am', 'My Sites': 'Meine Seiten', 'Name': 'Name', 'New Record': 'Neuer Eintrag', 'new record inserted': 'neuer Eintrag hinzugefügt', 'next %s rows': 'nächste %s Reihen', 'No databases in this application': 'Keine Datenbank in dieser Anwendung', 'Number of entries: **%s**': 'Nummer der Einträge: **%s**', 'Object or table name': 'Objekt- oder Tabellenname', 'Online book': 'Online Buch', 'Online examples': 'Online Beispiele', 'or import from csv file': 'oder von csv Datei importieren', 'Origin': 'Ursprung', 'Other Plugins': 'Andere Plugins', 'Other Recipes': 'Andere Rezepte', 'Overview': 'Überblick', 'Password': 'Passwort', "Password fields don't match": 'Passwortfelder sind nicht gleich', 'Permission': 'Erlaubnis', 'Permissions': 'Erlaubnisse', 'please input your password again': 'Bitte geben Sie ihr Passwort erneut ein', 'Plugins': 'Plugins', 'Powered by': 'Unterstützt von', 'Preface': 'Allgemeines', 'previous %s rows': 'vorherige %s Reihen', 'Profile': 'Profil', 'pygraphviz library not found': 'pygraphviz Bibliothek wurde nicht gefunden', 'Python': 'Python', 'Query:': 'Query:', 'Quick Examples': 'Kurze Beispiele', 'RAM': 'RAM', 'RAM Cache Keys': 'RAM Cache Keys', 'Ram Cleared': 'Ram gelöscht', 'RAM contains items up to **%(hours)02d** %%{hour(hours)} **%(min)02d** %%{minute(min)} **%(sec)02d** %%{second(sec)} old.': 'RAM enthält items die bis zu **%(hours)02d** %%{hour(hours)} **%(min)02d** %%{minute(min)} **%(sec)02d** %%{second(sec)} alt sind.', 'Recipes': 'Rezepte', 'Record': 'Eintrag', 'record does not exist': 'Eintrag existiert nicht', 'Record ID': 'ID des Eintrags', 'Record id': 'id des Eintrags', 'Register': 'Register', 'Registration identifier': 'Registrierungsbezeichnung', 'Registration key': 'Registierungsschlüssel', 'Registration successful': 'Registrierung erfolgreich', 'Remember me (for 30 days)': 'Eingeloggt bleiben (30 Tage lang)', 'Reset Password key': 'Passwortschlüssel zurücksetzen', 'Role': 'Rolle', 'Roles': 'Rollen', 'Rows in Table': 'Tabellenreihen', 'Rows selected': 'Reihen ausgewählt', 'Save model as...': 'Speichere Vorlage als...', 'Semantic': 'Semantik', 'Services': 'Dienste', 'Sign Up': 'Registrieren', 'Size of cache:': 'Cachegröße:', 'state': 'Status', 'Statistics': 'Statistik', 'Stylesheet': 'Stylesheet', 'submit': 'Submit', 'Support': 'Support', 'Table': 'Tabelle', 'The "query" is a condition like "db.table1.field1==\'value\'". Something like "db.table1.field1==db.table2.field2" results in a SQL JOIN.': 'Die "query" ist eine Bedingung wie "db.tabelle1.feld1==\'wert\'". So etwas wie "db.tabelle1.feld1==db.tabelle2.feld2" resultiert in einem SQL JOIN.', 'The Core': 'Der Core', 'The output of the file is a dictionary that was rendered by the view %s': 'Die Ausgabe der Datei ist ein "dictionary", welches vom "view" %s gerendert wurde', 'The Views': 'Die Views', 'This App': 'Diese App', 'This email already has an account': 'Diese email besitzt bereits ein Konto', 'Time in Cache (h:m:s)': 'Zeit im Cache (h:m:s)', 'Timestamp': 'Zeitstempel', 'Traceback': 'Zurückverfolgen', 'Twitter': 'Twitter', 'unable to parse csv file': 'csv Datei konnte nicht geparst werden', 'Update:': 'Update:', 'Use (...)&(...) for AND, (...)|(...) for OR, and ~(...) for NOT to build more complex queries.': 'Benutze (...)&(...) für AND, (...)|(...) für OR, und ~(...) für NOT um komplexere Queries zu erstellen.', 'User': 'Benutzer', 'User %(id)s Logged-in': 'Benutzer %(id)s hat sich eingeloggt', 'User %(id)s Logged-out': 'Benutzer %(id)s hat sich ausgeloggt', 'User %(id)s Registered': 'Benutzer %(id)s hat sich registriert', 'User ID': 'Benutzer ID', 'Users': 'Benutzer', 'value already in database or empty': 'Wert ist bereits in der Datenbank oder leer', 'Verify Password': 'Passwort überprüfen', 'Videos': 'Videos', 'View': 'Ansicht', 'Welcome': 'Willkommen', 'Welcome to web2py!': 'Willkommen bei web2py!', 'Which called the function %s located in the file %s': 'Welche die Funktion %s in der Datei %s aufrief', 'Working...': 'Arbeite...', 'You are successfully running web2py': 'web2py wird erfolgreich ausgeführt', 'You can modify this application and adapt it to your needs': 'Sie können diese Anwendung verändern und Ihren Bedürfnissen anpassen', 'You visited the url %s': 'Sie haben die URL %s besucht', }
apache-2.0
anthonybishopric/pyboxfs
fs/errors.py
2
10848
""" Defines the Exception classes thrown by PyFilesystem objects. Exceptions relating to the underlying filesystem are translated in to one of the following Exceptions. Exceptions that relate to a path store that path in `self.path`. All Exception classes are derived from `FSError` which can be used as a catch-all exception. """ __all__ = ['FSError', 'CreateFailedError', 'PathError', 'OperationFailedError', 'UnsupportedError', 'RemoteConnectionError', 'StorageSpaceError', 'PermissionDeniedError', 'FSClosedError', 'OperationTimeoutError', 'RemoveRootError', 'ResourceError', 'NoSysPathError', 'NoMetaError', 'NoPathURLError', 'ResourceNotFoundError', 'ResourceInvalidError', 'DestinationExistsError', 'DirectoryNotEmptyError', 'ParentDirectoryMissingError', 'ResourceLockedError', 'NoMMapError', 'BackReferenceError', 'convert_fs_errors', 'convert_os_errors' ] import sys import errno from fs.path import * from fs.local_functools import wraps class FSError(Exception): """Base exception class for the FS module.""" default_message = "Unspecified error" def __init__(self,msg=None,details=None): if msg is None: msg = self.default_message self.msg = msg self.details = details def __str__(self): keys = {} for k,v in self.__dict__.iteritems(): if isinstance(v,unicode): v = v.encode(sys.getfilesystemencoding()) keys[k] = v return str(self.msg % keys) def __unicode__(self): return unicode(self.msg) % self.__dict__ def __reduce__(self): return (self.__class__,(),self.__dict__.copy(),) class CreateFailedError(FSError): """An exception thrown when a FS could not be created""" default_message = "Unable to create filesystem" class PathError(FSError): """Exception for errors to do with a path string. """ default_message = "Path is invalid: %(path)s" def __init__(self,path="",**kwds): self.path = path super(PathError,self).__init__(**kwds) class OperationFailedError(FSError): """Base exception class for errors associated with a specific operation.""" default_message = "Unable to %(opname)s: unspecified error [%(errno)s - %(details)s]" def __init__(self,opname="",path=None,**kwds): self.opname = opname self.path = path self.errno = getattr(kwds.get("details",None),"errno",None) super(OperationFailedError,self).__init__(**kwds) class UnsupportedError(OperationFailedError): """Exception raised for operations that are not supported by the FS.""" default_message = "Unable to %(opname)s: not supported by this filesystem" class RemoteConnectionError(OperationFailedError): """Exception raised when operations encounter remote connection trouble.""" default_message = "%(opname)s: remote connection errror" class StorageSpaceError(OperationFailedError): """Exception raised when operations encounter storage space trouble.""" default_message = "Unable to %(opname)s: insufficient storage space" class PermissionDeniedError(OperationFailedError): default_message = "Unable to %(opname)s: permission denied" class FSClosedError(OperationFailedError): default_message = "Unable to %(opname)s: the FS has been closed" class OperationTimeoutError(OperationFailedError): default_message = "Unable to %(opname)s: operation timed out" class RemoveRootError(OperationFailedError): default_message = "Can't remove root dir" class ResourceError(FSError): """Base exception class for error associated with a specific resource.""" default_message = "Unspecified resource error: %(path)s" def __init__(self,path="",**kwds): self.path = path self.opname = kwds.pop("opname",None) super(ResourceError,self).__init__(**kwds) class NoSysPathError(ResourceError): """Exception raised when there is no syspath for a given path.""" default_message = "No mapping to OS filesystem: %(path)s" class NoMetaError(FSError): """Exception raised when there is no meta value available.""" default_message = "No meta value named '%(meta_name)s' could be retrieved" def __init__(self, meta_name, msg=None): self.meta_name = meta_name super(NoMetaError, self).__init__(msg) def __reduce__(self): return (self.__class__,(self.meta_name,),self.__dict__.copy(),) class NoPathURLError(ResourceError): """Exception raised when there is no URL form for a given path.""" default_message = "No URL form: %(path)s" class ResourceNotFoundError(ResourceError): """Exception raised when a required resource is not found.""" default_message = "Resource not found: %(path)s" class ResourceInvalidError(ResourceError): """Exception raised when a resource is the wrong type.""" default_message = "Resource is invalid: %(path)s" class DestinationExistsError(ResourceError): """Exception raised when a target destination already exists.""" default_message = "Destination exists: %(path)s" class DirectoryNotEmptyError(ResourceError): """Exception raised when a directory to be removed is not empty.""" default_message = "Directory is not empty: %(path)s" class ParentDirectoryMissingError(ResourceError): """Exception raised when a parent directory is missing.""" default_message = "Parent directory is missing: %(path)s" class ResourceLockedError(ResourceError): """Exception raised when a resource can't be used because it is locked.""" default_message = "Resource is locked: %(path)s" class NoMMapError(ResourceError): """Exception raise when getmmap fails to create a mmap""" default_message = "Can't get mmap for %(path)s" class BackReferenceError(ValueError): """Exception raised when too many backrefs exist in a path (ex: '/..', '/docs/../..').""" def convert_fs_errors(func): """Function wrapper to convert FSError instances into OSError.""" @wraps(func) def wrapper(*args,**kwds): try: return func(*args,**kwds) except ResourceNotFoundError, e: raise OSError(errno.ENOENT,str(e)) except ParentDirectoryMissingError, e: if sys.platform == "win32": raise OSError(errno.ESRCH,str(e)) else: raise OSError(errno.ENOENT,str(e)) except ResourceInvalidError, e: raise OSError(errno.EINVAL,str(e)) except PermissionDeniedError, e: raise OSError(errno.EACCES,str(e)) except ResourceLockedError, e: if sys.platform == "win32": raise WindowsError(32,str(e)) else: raise OSError(errno.EACCES,str(e)) except DirectoryNotEmptyError, e: raise OSError(errno.ENOTEMPTY,str(e)) except DestinationExistsError, e: raise OSError(errno.EEXIST,str(e)) except StorageSpaceError, e: raise OSError(errno.ENOSPC,str(e)) except RemoteConnectionError, e: raise OSError(errno.ENETDOWN,str(e)) except UnsupportedError, e: raise OSError(errno.ENOSYS,str(e)) except FSError, e: raise OSError(errno.EFAULT,str(e)) return wrapper def convert_os_errors(func): """Function wrapper to convert OSError/IOError instances into FSError.""" opname = func.__name__ @wraps(func) def wrapper(self,*args,**kwds): try: return func(self,*args,**kwds) except (OSError,IOError), e: (exc_type,exc_inst,tb) = sys.exc_info() path = getattr(e,"filename",None) if path and path[0] == "/" and hasattr(self,"root_path"): path = normpath(path) if isprefix(self.root_path,path): path = path[len(self.root_path):] if not hasattr(e,"errno") or not e.errno: raise OperationFailedError(opname,details=e),None,tb if e.errno == errno.ENOENT: raise ResourceNotFoundError(path,opname=opname,details=e),None,tb if e.errno == errno.ESRCH: raise ResourceNotFoundError(path,opname=opname,details=e),None,tb if e.errno == errno.ENOTEMPTY: raise DirectoryNotEmptyError(path,opname=opname,details=e),None,tb if e.errno == errno.EEXIST: raise DestinationExistsError(path,opname=opname,details=e),None,tb if e.errno == 183: # some sort of win32 equivalent to EEXIST raise DestinationExistsError(path,opname=opname,details=e),None,tb if e.errno == errno.ENOTDIR: raise ResourceInvalidError(path,opname=opname,details=e),None,tb if e.errno == errno.EISDIR: raise ResourceInvalidError(path,opname=opname,details=e),None,tb if e.errno == errno.EINVAL: raise ResourceInvalidError(path,opname=opname,details=e),None,tb if e.errno == errno.ENOSPC: raise StorageSpaceError(opname,path=path,details=e),None,tb if e.errno == errno.EPERM: raise PermissionDeniedError(opname,path=path,details=e),None,tb if hasattr(errno,"ENONET") and e.errno == errno.ENONET: raise RemoteConnectionError(opname,path=path,details=e),None,tb if e.errno == errno.ENETDOWN: raise RemoteConnectionError(opname,path=path,details=e),None,tb if e.errno == errno.ECONNRESET: raise RemoteConnectionError(opname,path=path,details=e),None,tb if e.errno == errno.EACCES: if sys.platform == "win32": if e.args[0] and e.args[0] == 32: raise ResourceLockedError(path,opname=opname,details=e),None,tb raise PermissionDeniedError(opname,details=e),None,tb # Sometimes windows gives some random errors... if sys.platform == "win32": if e.errno in (13,): raise ResourceInvalidError(path,opname=opname,details=e),None,tb if e.errno == errno.ENAMETOOLONG: raise PathError(path,details=e),None,tb if e.errno == errno.EOPNOTSUPP: raise UnsupportedError(opname,details=e),None,tb if e.errno == errno.ENOSYS: raise UnsupportedError(opname,details=e),None,tb raise OperationFailedError(opname,details=e),None,tb return wrapper
bsd-3-clause
nmearl/pyqtgraph
pyqtgraph/widgets/ColorMapWidget.py
34
9933
from ..Qt import QtGui, QtCore from .. import parametertree as ptree import numpy as np from ..pgcollections import OrderedDict from .. import functions as fn __all__ = ['ColorMapWidget'] class ColorMapWidget(ptree.ParameterTree): """ This class provides a widget allowing the user to customize color mapping for multi-column data. Given a list of field names, the user may specify multiple criteria for assigning colors to each record in a numpy record array. Multiple criteria are evaluated and combined into a single color for each record by user-defined compositing methods. For simpler color mapping using a single gradient editor, see :class:`GradientWidget <pyqtgraph.GradientWidget>` """ sigColorMapChanged = QtCore.Signal(object) def __init__(self, parent=None): ptree.ParameterTree.__init__(self, parent=parent, showHeader=False) self.params = ColorMapParameter() self.setParameters(self.params) self.params.sigTreeStateChanged.connect(self.mapChanged) ## wrap a couple methods self.setFields = self.params.setFields self.map = self.params.map def mapChanged(self): self.sigColorMapChanged.emit(self) def widgetGroupInterface(self): return (self.sigColorMapChanged, self.saveState, self.restoreState) def saveState(self): return self.params.saveState() def restoreState(self, state): self.params.restoreState(state) class ColorMapParameter(ptree.types.GroupParameter): sigColorMapChanged = QtCore.Signal(object) def __init__(self): self.fields = {} ptree.types.GroupParameter.__init__(self, name='Color Map', addText='Add Mapping..', addList=[]) self.sigTreeStateChanged.connect(self.mapChanged) def mapChanged(self): self.sigColorMapChanged.emit(self) def addNew(self, name): mode = self.fields[name].get('mode', 'range') if mode == 'range': item = RangeColorMapItem(name, self.fields[name]) elif mode == 'enum': item = EnumColorMapItem(name, self.fields[name]) self.addChild(item) return item def fieldNames(self): return self.fields.keys() def setFields(self, fields): """ Set the list of fields to be used by the mapper. The format of *fields* is:: [ (fieldName, {options}), ... ] ============== ============================================================ Field Options: mode Either 'range' or 'enum' (default is range). For 'range', The user may specify a gradient of colors to be applied linearly across a specific range of values. For 'enum', the user specifies a single color for each unique value (see *values* option). units String indicating the units of the data for this field. values List of unique values for which the user may assign a color when mode=='enum'. Optionally may specify a dict instead {value: name}. ============== ============================================================ """ self.fields = OrderedDict(fields) #self.fields = fields #self.fields.sort() names = self.fieldNames() self.setAddList(names) def map(self, data, mode='byte'): """ Return an array of colors corresponding to *data*. ============== ================================================================= **Arguments:** data A numpy record array where the fields in data.dtype match those defined by a prior call to setFields(). mode Either 'byte' or 'float'. For 'byte', the method returns an array of dtype ubyte with values scaled 0-255. For 'float', colors are returned as 0.0-1.0 float values. ============== ================================================================= """ if isinstance(data, dict): data = np.array([tuple(data.values())], dtype=[(k, float) for k in data.keys()]) colors = np.zeros((len(data),4)) for item in self.children(): if not item['Enabled']: continue chans = item.param('Channels..') mask = np.empty((len(data), 4), dtype=bool) for i,f in enumerate(['Red', 'Green', 'Blue', 'Alpha']): mask[:,i] = chans[f] colors2 = item.map(data) op = item['Operation'] if op == 'Add': colors[mask] = colors[mask] + colors2[mask] elif op == 'Multiply': colors[mask] *= colors2[mask] elif op == 'Overlay': a = colors2[:,3:4] c3 = colors * (1-a) + colors2 * a c3[:,3:4] = colors[:,3:4] + (1-colors[:,3:4]) * a colors = c3 elif op == 'Set': colors[mask] = colors2[mask] colors = np.clip(colors, 0, 1) if mode == 'byte': colors = (colors * 255).astype(np.ubyte) return colors def saveState(self): items = OrderedDict() for item in self: itemState = item.saveState(filter='user') itemState['field'] = item.fieldName items[item.name()] = itemState state = {'fields': self.fields, 'items': items} return state def restoreState(self, state): if 'fields' in state: self.setFields(state['fields']) for itemState in state['items']: item = self.addNew(itemState['field']) item.restoreState(itemState) class RangeColorMapItem(ptree.types.SimpleParameter): mapType = 'range' def __init__(self, name, opts): self.fieldName = name units = opts.get('units', '') ptree.types.SimpleParameter.__init__(self, name=name, autoIncrementName=True, type='colormap', removable=True, renamable=True, children=[ #dict(name="Field", type='list', value=name, values=fields), dict(name='Min', type='float', value=0.0, suffix=units, siPrefix=True), dict(name='Max', type='float', value=1.0, suffix=units, siPrefix=True), dict(name='Operation', type='list', value='Overlay', values=['Overlay', 'Add', 'Multiply', 'Set']), dict(name='Channels..', type='group', expanded=False, children=[ dict(name='Red', type='bool', value=True), dict(name='Green', type='bool', value=True), dict(name='Blue', type='bool', value=True), dict(name='Alpha', type='bool', value=True), ]), dict(name='Enabled', type='bool', value=True), dict(name='NaN', type='color'), ]) def map(self, data): data = data[self.fieldName] scaled = np.clip((data-self['Min']) / (self['Max']-self['Min']), 0, 1) cmap = self.value() colors = cmap.map(scaled, mode='float') mask = np.isnan(data) | np.isinf(data) nanColor = self['NaN'] nanColor = (nanColor.red()/255., nanColor.green()/255., nanColor.blue()/255., nanColor.alpha()/255.) colors[mask] = nanColor return colors class EnumColorMapItem(ptree.types.GroupParameter): mapType = 'enum' def __init__(self, name, opts): self.fieldName = name vals = opts.get('values', []) if isinstance(vals, list): vals = OrderedDict([(v,str(v)) for v in vals]) childs = [{'name': v, 'type': 'color'} for v in vals] childs = [] for val,vname in vals.items(): ch = ptree.Parameter.create(name=vname, type='color') ch.maskValue = val childs.append(ch) ptree.types.GroupParameter.__init__(self, name=name, autoIncrementName=True, removable=True, renamable=True, children=[ dict(name='Values', type='group', children=childs), dict(name='Operation', type='list', value='Overlay', values=['Overlay', 'Add', 'Multiply', 'Set']), dict(name='Channels..', type='group', expanded=False, children=[ dict(name='Red', type='bool', value=True), dict(name='Green', type='bool', value=True), dict(name='Blue', type='bool', value=True), dict(name='Alpha', type='bool', value=True), ]), dict(name='Enabled', type='bool', value=True), dict(name='Default', type='color'), ]) def map(self, data): data = data[self.fieldName] colors = np.empty((len(data), 4)) default = np.array(fn.colorTuple(self['Default'])) / 255. colors[:] = default for v in self.param('Values'): mask = data == v.maskValue c = np.array(fn.colorTuple(v.value())) / 255. colors[mask] = c #scaled = np.clip((data-self['Min']) / (self['Max']-self['Min']), 0, 1) #cmap = self.value() #colors = cmap.map(scaled, mode='float') #mask = np.isnan(data) | np.isinf(data) #nanColor = self['NaN'] #nanColor = (nanColor.red()/255., nanColor.green()/255., nanColor.blue()/255., nanColor.alpha()/255.) #colors[mask] = nanColor return colors
mit
thiagopena/PySIGNFe
pysignfe/nfse/bhiss/v10/SubstituicaoNfse.py
1
1459
# -*- coding: utf-8 -*- from pysignfe.xml_sped import * class InfSubstituicaoNfse(XMLNFe): def __init__(self): super(InfSubstituicaoNfse, self).__init__() self.Id = TagCaracter(nome=u'InfSubstituicaoNfse', propriedade=u'Id', raiz=u'/') self.NfseSubstituidora = TagInteiro(nome=u'NfseSubstituidora', tamanho=[1,15], raiz=u'/') def get_xml(self): self.Id.valor = u'substituicao:'+str(self.NfseSubstituidora.valor) xml = XMLNFe.get_xml(self) xml += self.Id.xml xml += self.NfseSubstituidora.xml xml += u'</InfSubstituicaoNfse>' return xml def set_xml(self, arquivo): if self._le_xml(arquivo): self.NfseSubstituidora.xml = arquivo xml = property(get_xml, set_xml) class SubstituicaoNfse(XMLNFe): def __init__(self): super(SubstituicaoNfse, self).__init__() self.InfSubstituicaoNfse = InfSubstituicaoNfse() self.Signature = Signature() def get_xml(self): xml = XMLNFe.get_xml(self) xml += u'<SubstituicaoNfse>' xml += self.InfSubstituicaoNfse.xml xml += self.Signature.xml xml += u'</SubstituicaoNfse>' return xml def set_xml(self, arquivo): if self._le_xml(arquivo): self.InfSubstituicaoNfse.xml = arquivo self.Signature.xml = self._le_noh('//Rps/sig:Signature') xml = property(get_xml, set_xml)
lgpl-2.1
xyguo/scikit-learn
sklearn/decomposition/nmf.py
6
46993
""" Non-negative matrix factorization """ # Author: Vlad Niculae # Lars Buitinck # Mathieu Blondel <mathieu@mblondel.org> # Tom Dupre la Tour # Author: Chih-Jen Lin, National Taiwan University (original projected gradient # NMF implementation) # Author: Anthony Di Franco (Projected gradient, Python and NumPy port) # License: BSD 3 clause from __future__ import division, print_function from math import sqrt import warnings import numbers import numpy as np import scipy.sparse as sp from ..externals import six from ..base import BaseEstimator, TransformerMixin from ..utils import check_random_state, check_array from ..utils.extmath import randomized_svd, safe_sparse_dot, squared_norm from ..utils.extmath import fast_dot from ..utils.validation import check_is_fitted, check_non_negative from ..utils import deprecated from ..exceptions import ConvergenceWarning from .cdnmf_fast import _update_cdnmf_fast def safe_vstack(Xs): if any(sp.issparse(X) for X in Xs): return sp.vstack(Xs) else: return np.vstack(Xs) def norm(x): """Dot product-based Euclidean norm implementation See: http://fseoane.net/blog/2011/computing-the-vector-norm/ """ return sqrt(squared_norm(x)) def trace_dot(X, Y): """Trace of np.dot(X, Y.T).""" return np.dot(X.ravel(), Y.ravel()) def _sparseness(x): """Hoyer's measure of sparsity for a vector""" sqrt_n = np.sqrt(len(x)) return (sqrt_n - np.linalg.norm(x, 1) / norm(x)) / (sqrt_n - 1) def _check_init(A, shape, whom): A = check_array(A) if np.shape(A) != shape: raise ValueError('Array with wrong shape passed to %s. Expected %s, ' 'but got %s ' % (whom, shape, np.shape(A))) check_non_negative(A, whom) if np.max(A) == 0: raise ValueError('Array passed to %s is full of zeros.' % whom) def _safe_compute_error(X, W, H): """Frobenius norm between X and WH, safe for sparse array""" if not sp.issparse(X): error = norm(X - np.dot(W, H)) else: norm_X = np.dot(X.data, X.data) norm_WH = trace_dot(np.dot(np.dot(W.T, W), H), H) cross_prod = trace_dot((X * H.T), W) error = sqrt(norm_X + norm_WH - 2. * cross_prod) return error def _check_string_param(sparseness, solver): allowed_sparseness = (None, 'data', 'components') if sparseness not in allowed_sparseness: raise ValueError( 'Invalid sparseness parameter: got %r instead of one of %r' % (sparseness, allowed_sparseness)) allowed_solver = ('pg', 'cd') if solver not in allowed_solver: raise ValueError( 'Invalid solver parameter: got %r instead of one of %r' % (solver, allowed_solver)) def _initialize_nmf(X, n_components, init=None, eps=1e-6, random_state=None): """Algorithms for NMF initialization. Computes an initial guess for the non-negative rank k matrix approximation for X: X = WH Parameters ---------- X : array-like, shape (n_samples, n_features) The data matrix to be decomposed. n_components : integer The number of components desired in the approximation. init : None | 'random' | 'nndsvd' | 'nndsvda' | 'nndsvdar' Method used to initialize the procedure. Default: 'nndsvdar' if n_components < n_features, otherwise 'random'. Valid options: - 'random': non-negative random matrices, scaled with: sqrt(X.mean() / n_components) - 'nndsvd': Nonnegative Double Singular Value Decomposition (NNDSVD) initialization (better for sparseness) - 'nndsvda': NNDSVD with zeros filled with the average of X (better when sparsity is not desired) - 'nndsvdar': NNDSVD with zeros filled with small random values (generally faster, less accurate alternative to NNDSVDa for when sparsity is not desired) - 'custom': use custom matrices W and H eps : float Truncate all values less then this in output to zero. random_state : int seed, RandomState instance, or None (default) Random number generator seed control, used in 'nndsvdar' and 'random' modes. Returns ------- W : array-like, shape (n_samples, n_components) Initial guesses for solving X ~= WH H : array-like, shape (n_components, n_features) Initial guesses for solving X ~= WH References ---------- C. Boutsidis, E. Gallopoulos: SVD based initialization: A head start for nonnegative matrix factorization - Pattern Recognition, 2008 http://tinyurl.com/nndsvd """ check_non_negative(X, "NMF initialization") n_samples, n_features = X.shape if init is None: if n_components < n_features: init = 'nndsvd' else: init = 'random' # Random initialization if init == 'random': avg = np.sqrt(X.mean() / n_components) rng = check_random_state(random_state) H = avg * rng.randn(n_components, n_features) W = avg * rng.randn(n_samples, n_components) # we do not write np.abs(H, out=H) to stay compatible with # numpy 1.5 and earlier where the 'out' keyword is not # supported as a kwarg on ufuncs np.abs(H, H) np.abs(W, W) return W, H # NNDSVD initialization U, S, V = randomized_svd(X, n_components, random_state=random_state) W, H = np.zeros(U.shape), np.zeros(V.shape) # The leading singular triplet is non-negative # so it can be used as is for initialization. W[:, 0] = np.sqrt(S[0]) * np.abs(U[:, 0]) H[0, :] = np.sqrt(S[0]) * np.abs(V[0, :]) for j in range(1, n_components): x, y = U[:, j], V[j, :] # extract positive and negative parts of column vectors x_p, y_p = np.maximum(x, 0), np.maximum(y, 0) x_n, y_n = np.abs(np.minimum(x, 0)), np.abs(np.minimum(y, 0)) # and their norms x_p_nrm, y_p_nrm = norm(x_p), norm(y_p) x_n_nrm, y_n_nrm = norm(x_n), norm(y_n) m_p, m_n = x_p_nrm * y_p_nrm, x_n_nrm * y_n_nrm # choose update if m_p > m_n: u = x_p / x_p_nrm v = y_p / y_p_nrm sigma = m_p else: u = x_n / x_n_nrm v = y_n / y_n_nrm sigma = m_n lbd = np.sqrt(S[j] * sigma) W[:, j] = lbd * u H[j, :] = lbd * v W[W < eps] = 0 H[H < eps] = 0 if init == "nndsvd": pass elif init == "nndsvda": avg = X.mean() W[W == 0] = avg H[H == 0] = avg elif init == "nndsvdar": rng = check_random_state(random_state) avg = X.mean() W[W == 0] = abs(avg * rng.randn(len(W[W == 0])) / 100) H[H == 0] = abs(avg * rng.randn(len(H[H == 0])) / 100) else: raise ValueError( 'Invalid init parameter: got %r instead of one of %r' % (init, (None, 'random', 'nndsvd', 'nndsvda', 'nndsvdar'))) return W, H def _nls_subproblem(V, W, H, tol, max_iter, alpha=0., l1_ratio=0., sigma=0.01, beta=0.1): """Non-negative least square solver Solves a non-negative least squares subproblem using the projected gradient descent algorithm. Parameters ---------- V : array-like, shape (n_samples, n_features) Constant matrix. W : array-like, shape (n_samples, n_components) Constant matrix. H : array-like, shape (n_components, n_features) Initial guess for the solution. tol : float Tolerance of the stopping condition. max_iter : int Maximum number of iterations before timing out. alpha : double, default: 0. Constant that multiplies the regularization terms. Set it to zero to have no regularization. l1_ratio : double, default: 0. The regularization mixing parameter, with 0 <= l1_ratio <= 1. For l1_ratio = 0 the penalty is an L2 penalty. For l1_ratio = 1 it is an L1 penalty. For 0 < l1_ratio < 1, the penalty is a combination of L1 and L2. sigma : float Constant used in the sufficient decrease condition checked by the line search. Smaller values lead to a looser sufficient decrease condition, thus reducing the time taken by the line search, but potentially increasing the number of iterations of the projected gradient procedure. 0.01 is a commonly used value in the optimization literature. beta : float Factor by which the step size is decreased (resp. increased) until (resp. as long as) the sufficient decrease condition is satisfied. Larger values allow to find a better step size but lead to longer line search. 0.1 is a commonly used value in the optimization literature. Returns ------- H : array-like, shape (n_components, n_features) Solution to the non-negative least squares problem. grad : array-like, shape (n_components, n_features) The gradient. n_iter : int The number of iterations done by the algorithm. References ---------- C.-J. Lin. Projected gradient methods for non-negative matrix factorization. Neural Computation, 19(2007), 2756-2779. http://www.csie.ntu.edu.tw/~cjlin/nmf/ """ WtV = safe_sparse_dot(W.T, V) WtW = fast_dot(W.T, W) # values justified in the paper (alpha is renamed gamma) gamma = 1 for n_iter in range(1, max_iter + 1): grad = np.dot(WtW, H) - WtV if alpha > 0 and l1_ratio == 1.: grad += alpha elif alpha > 0: grad += alpha * (l1_ratio + (1 - l1_ratio) * H) # The following multiplication with a boolean array is more than twice # as fast as indexing into grad. if norm(grad * np.logical_or(grad < 0, H > 0)) < tol: break Hp = H for inner_iter in range(20): # Gradient step. Hn = H - gamma * grad # Projection step. Hn *= Hn > 0 d = Hn - H gradd = np.dot(grad.ravel(), d.ravel()) dQd = np.dot(np.dot(WtW, d).ravel(), d.ravel()) suff_decr = (1 - sigma) * gradd + 0.5 * dQd < 0 if inner_iter == 0: decr_gamma = not suff_decr if decr_gamma: if suff_decr: H = Hn break else: gamma *= beta elif not suff_decr or (Hp == Hn).all(): H = Hp break else: gamma /= beta Hp = Hn if n_iter == max_iter: warnings.warn("Iteration limit reached in nls subproblem.") return H, grad, n_iter def _update_projected_gradient_w(X, W, H, tolW, nls_max_iter, alpha, l1_ratio, sparseness, beta, eta): """Helper function for _fit_projected_gradient""" n_samples, n_features = X.shape n_components_ = H.shape[0] if sparseness is None: Wt, gradW, iterW = _nls_subproblem(X.T, H.T, W.T, tolW, nls_max_iter, alpha=alpha, l1_ratio=l1_ratio) elif sparseness == 'data': Wt, gradW, iterW = _nls_subproblem( safe_vstack([X.T, np.zeros((1, n_samples))]), safe_vstack([H.T, np.sqrt(beta) * np.ones((1, n_components_))]), W.T, tolW, nls_max_iter, alpha=alpha, l1_ratio=l1_ratio) elif sparseness == 'components': Wt, gradW, iterW = _nls_subproblem( safe_vstack([X.T, np.zeros((n_components_, n_samples))]), safe_vstack([H.T, np.sqrt(eta) * np.eye(n_components_)]), W.T, tolW, nls_max_iter, alpha=alpha, l1_ratio=l1_ratio) return Wt.T, gradW.T, iterW def _update_projected_gradient_h(X, W, H, tolH, nls_max_iter, alpha, l1_ratio, sparseness, beta, eta): """Helper function for _fit_projected_gradient""" n_samples, n_features = X.shape n_components_ = W.shape[1] if sparseness is None: H, gradH, iterH = _nls_subproblem(X, W, H, tolH, nls_max_iter, alpha=alpha, l1_ratio=l1_ratio) elif sparseness == 'data': H, gradH, iterH = _nls_subproblem( safe_vstack([X, np.zeros((n_components_, n_features))]), safe_vstack([W, np.sqrt(eta) * np.eye(n_components_)]), H, tolH, nls_max_iter, alpha=alpha, l1_ratio=l1_ratio) elif sparseness == 'components': H, gradH, iterH = _nls_subproblem( safe_vstack([X, np.zeros((1, n_features))]), safe_vstack([W, np.sqrt(beta) * np.ones((1, n_components_))]), H, tolH, nls_max_iter, alpha=alpha, l1_ratio=l1_ratio) return H, gradH, iterH def _fit_projected_gradient(X, W, H, tol, max_iter, nls_max_iter, alpha, l1_ratio, sparseness, beta, eta): """Compute Non-negative Matrix Factorization (NMF) with Projected Gradient References ---------- C.-J. Lin. Projected gradient methods for non-negative matrix factorization. Neural Computation, 19(2007), 2756-2779. http://www.csie.ntu.edu.tw/~cjlin/nmf/ P. Hoyer. Non-negative Matrix Factorization with Sparseness Constraints. Journal of Machine Learning Research 2004. """ gradW = (np.dot(W, np.dot(H, H.T)) - safe_sparse_dot(X, H.T, dense_output=True)) gradH = (np.dot(np.dot(W.T, W), H) - safe_sparse_dot(W.T, X, dense_output=True)) init_grad = squared_norm(gradW) + squared_norm(gradH.T) # max(0.001, tol) to force alternating minimizations of W and H tolW = max(0.001, tol) * np.sqrt(init_grad) tolH = tolW for n_iter in range(1, max_iter + 1): # stopping condition # as discussed in paper proj_grad_W = squared_norm(gradW * np.logical_or(gradW < 0, W > 0)) proj_grad_H = squared_norm(gradH * np.logical_or(gradH < 0, H > 0)) if (proj_grad_W + proj_grad_H) / init_grad < tol ** 2: break # update W W, gradW, iterW = _update_projected_gradient_w(X, W, H, tolW, nls_max_iter, alpha, l1_ratio, sparseness, beta, eta) if iterW == 1: tolW = 0.1 * tolW # update H H, gradH, iterH = _update_projected_gradient_h(X, W, H, tolH, nls_max_iter, alpha, l1_ratio, sparseness, beta, eta) if iterH == 1: tolH = 0.1 * tolH H[H == 0] = 0 # fix up negative zeros if n_iter == max_iter: W, _, _ = _update_projected_gradient_w(X, W, H, tol, nls_max_iter, alpha, l1_ratio, sparseness, beta, eta) return W, H, n_iter def _update_coordinate_descent(X, W, Ht, l1_reg, l2_reg, shuffle, random_state): """Helper function for _fit_coordinate_descent Update W to minimize the objective function, iterating once over all coordinates. By symmetry, to update H, one can call _update_coordinate_descent(X.T, Ht, W, ...) """ n_components = Ht.shape[1] HHt = fast_dot(Ht.T, Ht) XHt = safe_sparse_dot(X, Ht) # L2 regularization corresponds to increase of the diagonal of HHt if l2_reg != 0.: # adds l2_reg only on the diagonal HHt.flat[::n_components + 1] += l2_reg # L1 regularization corresponds to decrease of each element of XHt if l1_reg != 0.: XHt -= l1_reg if shuffle: permutation = random_state.permutation(n_components) else: permutation = np.arange(n_components) # The following seems to be required on 64-bit Windows w/ Python 3.5. permutation = np.asarray(permutation, dtype=np.intp) return _update_cdnmf_fast(W, HHt, XHt, permutation) def _fit_coordinate_descent(X, W, H, tol=1e-4, max_iter=200, alpha=0.001, l1_ratio=0., regularization=None, update_H=True, verbose=0, shuffle=False, random_state=None): """Compute Non-negative Matrix Factorization (NMF) with Coordinate Descent The objective function is minimized with an alternating minimization of W and H. Each minimization is done with a cyclic (up to a permutation of the features) Coordinate Descent. Parameters ---------- X : array-like, shape (n_samples, n_features) Constant matrix. W : array-like, shape (n_samples, n_components) Initial guess for the solution. H : array-like, shape (n_components, n_features) Initial guess for the solution. tol : float, default: 1e-4 Tolerance of the stopping condition. max_iter : integer, default: 200 Maximum number of iterations before timing out. alpha : double, default: 0. Constant that multiplies the regularization terms. l1_ratio : double, default: 0. The regularization mixing parameter, with 0 <= l1_ratio <= 1. For l1_ratio = 0 the penalty is an L2 penalty. For l1_ratio = 1 it is an L1 penalty. For 0 < l1_ratio < 1, the penalty is a combination of L1 and L2. regularization : 'both' | 'components' | 'transformation' | None Select whether the regularization affects the components (H), the transformation (W), both or none of them. update_H : boolean, default: True Set to True, both W and H will be estimated from initial guesses. Set to False, only W will be estimated. verbose : integer, default: 0 The verbosity level. shuffle : boolean, default: False If true, randomize the order of coordinates in the CD solver. random_state : integer seed, RandomState instance, or None (default) Random number generator seed control. Returns ------- W : array-like, shape (n_samples, n_components) Solution to the non-negative least squares problem. H : array-like, shape (n_components, n_features) Solution to the non-negative least squares problem. n_iter : int The number of iterations done by the algorithm. References ---------- Cichocki, Andrzej, and P. H. A. N. Anh-Huy. "Fast local algorithms for large scale nonnegative matrix and tensor factorizations." IEICE transactions on fundamentals of electronics, communications and computer sciences 92.3: 708-721, 2009. """ # so W and Ht are both in C order in memory Ht = check_array(H.T, order='C') X = check_array(X, accept_sparse='csr') # L1 and L2 regularization l1_H, l2_H, l1_W, l2_W = 0, 0, 0, 0 if regularization in ('both', 'components'): alpha = float(alpha) l1_H = l1_ratio * alpha l2_H = (1. - l1_ratio) * alpha if regularization in ('both', 'transformation'): alpha = float(alpha) l1_W = l1_ratio * alpha l2_W = (1. - l1_ratio) * alpha rng = check_random_state(random_state) for n_iter in range(max_iter): violation = 0. # Update W violation += _update_coordinate_descent(X, W, Ht, l1_W, l2_W, shuffle, rng) # Update H if update_H: violation += _update_coordinate_descent(X.T, Ht, W, l1_H, l2_H, shuffle, rng) if n_iter == 0: violation_init = violation if violation_init == 0: break if verbose: print("violation:", violation / violation_init) if violation / violation_init <= tol: if verbose: print("Converged at iteration", n_iter + 1) break return W, Ht.T, n_iter def non_negative_factorization(X, W=None, H=None, n_components=None, init='random', update_H=True, solver='cd', tol=1e-4, max_iter=200, alpha=0., l1_ratio=0., regularization=None, random_state=None, verbose=0, shuffle=False, nls_max_iter=2000, sparseness=None, beta=1, eta=0.1): """Compute Non-negative Matrix Factorization (NMF) Find two non-negative matrices (W, H) whose product approximates the non- negative matrix X. This factorization can be used for example for dimensionality reduction, source separation or topic extraction. The objective function is:: 0.5 * ||X - WH||_Fro^2 + alpha * l1_ratio * ||vec(W)||_1 + alpha * l1_ratio * ||vec(H)||_1 + 0.5 * alpha * (1 - l1_ratio) * ||W||_Fro^2 + 0.5 * alpha * (1 - l1_ratio) * ||H||_Fro^2 Where:: ||A||_Fro^2 = \sum_{i,j} A_{ij}^2 (Frobenius norm) ||vec(A)||_1 = \sum_{i,j} abs(A_{ij}) (Elementwise L1 norm) The objective function is minimized with an alternating minimization of W and H. If H is given and update_H=False, it solves for W only. Parameters ---------- X : array-like, shape (n_samples, n_features) Constant matrix. W : array-like, shape (n_samples, n_components) If init='custom', it is used as initial guess for the solution. H : array-like, shape (n_components, n_features) If init='custom', it is used as initial guess for the solution. If update_H=False, it is used as a constant, to solve for W only. n_components : integer Number of components, if n_components is not set all features are kept. init : None | 'random' | 'nndsvd' | 'nndsvda' | 'nndsvdar' | 'custom' Method used to initialize the procedure. Default: 'nndsvd' if n_components < n_features, otherwise random. Valid options: - 'random': non-negative random matrices, scaled with: sqrt(X.mean() / n_components) - 'nndsvd': Nonnegative Double Singular Value Decomposition (NNDSVD) initialization (better for sparseness) - 'nndsvda': NNDSVD with zeros filled with the average of X (better when sparsity is not desired) - 'nndsvdar': NNDSVD with zeros filled with small random values (generally faster, less accurate alternative to NNDSVDa for when sparsity is not desired) - 'custom': use custom matrices W and H update_H : boolean, default: True Set to True, both W and H will be estimated from initial guesses. Set to False, only W will be estimated. solver : 'pg' | 'cd' Numerical solver to use: 'pg' is a (deprecated) Projected Gradient solver. 'cd' is a Coordinate Descent solver. tol : float, default: 1e-4 Tolerance of the stopping condition. max_iter : integer, default: 200 Maximum number of iterations before timing out. alpha : double, default: 0. Constant that multiplies the regularization terms. l1_ratio : double, default: 0. The regularization mixing parameter, with 0 <= l1_ratio <= 1. For l1_ratio = 0 the penalty is an elementwise L2 penalty (aka Frobenius Norm). For l1_ratio = 1 it is an elementwise L1 penalty. For 0 < l1_ratio < 1, the penalty is a combination of L1 and L2. regularization : 'both' | 'components' | 'transformation' | None Select whether the regularization affects the components (H), the transformation (W), both or none of them. random_state : integer seed, RandomState instance, or None (default) Random number generator seed control. verbose : integer, default: 0 The verbosity level. shuffle : boolean, default: False If true, randomize the order of coordinates in the CD solver. nls_max_iter : integer, default: 2000 Number of iterations in NLS subproblem. Used only in the deprecated 'pg' solver. sparseness : 'data' | 'components' | None, default: None Where to enforce sparsity in the model. Used only in the deprecated 'pg' solver. beta : double, default: 1 Degree of sparseness, if sparseness is not None. Larger values mean more sparseness. Used only in the deprecated 'pg' solver. eta : double, default: 0.1 Degree of correctness to maintain, if sparsity is not None. Smaller values mean larger error. Used only in the deprecated 'pg' solver. Returns ------- W : array-like, shape (n_samples, n_components) Solution to the non-negative least squares problem. H : array-like, shape (n_components, n_features) Solution to the non-negative least squares problem. n_iter : int Actual number of iterations. References ---------- C.-J. Lin. Projected gradient methods for non-negative matrix factorization. Neural Computation, 19(2007), 2756-2779. http://www.csie.ntu.edu.tw/~cjlin/nmf/ Cichocki, Andrzej, and P. H. A. N. Anh-Huy. "Fast local algorithms for large scale nonnegative matrix and tensor factorizations." IEICE transactions on fundamentals of electronics, communications and computer sciences 92.3: 708-721, 2009. """ X = check_array(X, accept_sparse=('csr', 'csc')) check_non_negative(X, "NMF (input X)") _check_string_param(sparseness, solver) n_samples, n_features = X.shape if n_components is None: n_components = n_features if not isinstance(n_components, six.integer_types) or n_components <= 0: raise ValueError("Number of components must be positive;" " got (n_components=%r)" % n_components) if not isinstance(max_iter, numbers.Number) or max_iter < 0: raise ValueError("Maximum number of iteration must be positive;" " got (max_iter=%r)" % max_iter) if not isinstance(tol, numbers.Number) or tol < 0: raise ValueError("Tolerance for stopping criteria must be " "positive; got (tol=%r)" % tol) # check W and H, or initialize them if init == 'custom' and update_H: _check_init(H, (n_components, n_features), "NMF (input H)") _check_init(W, (n_samples, n_components), "NMF (input W)") elif not update_H: _check_init(H, (n_components, n_features), "NMF (input H)") W = np.zeros((n_samples, n_components)) else: W, H = _initialize_nmf(X, n_components, init=init, random_state=random_state) if solver == 'pg': warnings.warn("'pg' solver will be removed in release 0.19." " Use 'cd' solver instead.", DeprecationWarning) if update_H: # fit_transform W, H, n_iter = _fit_projected_gradient(X, W, H, tol, max_iter, nls_max_iter, alpha, l1_ratio, sparseness, beta, eta) else: # transform W, H, n_iter = _update_projected_gradient_w(X, W, H, tol, nls_max_iter, alpha, l1_ratio, sparseness, beta, eta) elif solver == 'cd': W, H, n_iter = _fit_coordinate_descent(X, W, H, tol, max_iter, alpha, l1_ratio, regularization, update_H=update_H, verbose=verbose, shuffle=shuffle, random_state=random_state) else: raise ValueError("Invalid solver parameter '%s'." % solver) if n_iter == max_iter: warnings.warn("Maximum number of iteration %d reached. Increase it to" " improve convergence." % max_iter, ConvergenceWarning) return W, H, n_iter class NMF(BaseEstimator, TransformerMixin): """Non-Negative Matrix Factorization (NMF) Find two non-negative matrices (W, H) whose product approximates the non- negative matrix X. This factorization can be used for example for dimensionality reduction, source separation or topic extraction. The objective function is:: 0.5 * ||X - WH||_Fro^2 + alpha * l1_ratio * ||vec(W)||_1 + alpha * l1_ratio * ||vec(H)||_1 + 0.5 * alpha * (1 - l1_ratio) * ||W||_Fro^2 + 0.5 * alpha * (1 - l1_ratio) * ||H||_Fro^2 Where:: ||A||_Fro^2 = \sum_{i,j} A_{ij}^2 (Frobenius norm) ||vec(A)||_1 = \sum_{i,j} abs(A_{ij}) (Elementwise L1 norm) The objective function is minimized with an alternating minimization of W and H. Read more in the :ref:`User Guide <NMF>`. Parameters ---------- n_components : int or None Number of components, if n_components is not set all features are kept. init : 'random' | 'nndsvd' | 'nndsvda' | 'nndsvdar' | 'custom' Method used to initialize the procedure. Default: 'nndsvdar' if n_components < n_features, otherwise random. Valid options: - 'random': non-negative random matrices, scaled with: sqrt(X.mean() / n_components) - 'nndsvd': Nonnegative Double Singular Value Decomposition (NNDSVD) initialization (better for sparseness) - 'nndsvda': NNDSVD with zeros filled with the average of X (better when sparsity is not desired) - 'nndsvdar': NNDSVD with zeros filled with small random values (generally faster, less accurate alternative to NNDSVDa for when sparsity is not desired) - 'custom': use custom matrices W and H solver : 'pg' | 'cd' Numerical solver to use: 'pg' is a Projected Gradient solver (deprecated). 'cd' is a Coordinate Descent solver (recommended). .. versionadded:: 0.17 Coordinate Descent solver. .. versionchanged:: 0.17 Deprecated Projected Gradient solver. tol : double, default: 1e-4 Tolerance value used in stopping conditions. max_iter : integer, default: 200 Number of iterations to compute. random_state : integer seed, RandomState instance, or None (default) Random number generator seed control. alpha : double, default: 0. Constant that multiplies the regularization terms. Set it to zero to have no regularization. .. versionadded:: 0.17 *alpha* used in the Coordinate Descent solver. l1_ratio : double, default: 0. The regularization mixing parameter, with 0 <= l1_ratio <= 1. For l1_ratio = 0 the penalty is an elementwise L2 penalty (aka Frobenius Norm). For l1_ratio = 1 it is an elementwise L1 penalty. For 0 < l1_ratio < 1, the penalty is a combination of L1 and L2. .. versionadded:: 0.17 Regularization parameter *l1_ratio* used in the Coordinate Descent solver. shuffle : boolean, default: False If true, randomize the order of coordinates in the CD solver. .. versionadded:: 0.17 *shuffle* parameter used in the Coordinate Descent solver. nls_max_iter : integer, default: 2000 Number of iterations in NLS subproblem. Used only in the deprecated 'pg' solver. .. versionchanged:: 0.17 Deprecated Projected Gradient solver. Use Coordinate Descent solver instead. sparseness : 'data' | 'components' | None, default: None Where to enforce sparsity in the model. Used only in the deprecated 'pg' solver. .. versionchanged:: 0.17 Deprecated Projected Gradient solver. Use Coordinate Descent solver instead. beta : double, default: 1 Degree of sparseness, if sparseness is not None. Larger values mean more sparseness. Used only in the deprecated 'pg' solver. .. versionchanged:: 0.17 Deprecated Projected Gradient solver. Use Coordinate Descent solver instead. eta : double, default: 0.1 Degree of correctness to maintain, if sparsity is not None. Smaller values mean larger error. Used only in the deprecated 'pg' solver. .. versionchanged:: 0.17 Deprecated Projected Gradient solver. Use Coordinate Descent solver instead. Attributes ---------- components_ : array, [n_components, n_features] Non-negative components of the data. reconstruction_err_ : number Frobenius norm of the matrix difference between the training data and the reconstructed data from the fit produced by the model. ``|| X - WH ||_2`` n_iter_ : int Actual number of iterations. Examples -------- >>> import numpy as np >>> X = np.array([[1,1], [2, 1], [3, 1.2], [4, 1], [5, 0.8], [6, 1]]) >>> from sklearn.decomposition import NMF >>> model = NMF(n_components=2, init='random', random_state=0) >>> model.fit(X) #doctest: +ELLIPSIS +NORMALIZE_WHITESPACE NMF(alpha=0.0, beta=1, eta=0.1, init='random', l1_ratio=0.0, max_iter=200, n_components=2, nls_max_iter=2000, random_state=0, shuffle=False, solver='cd', sparseness=None, tol=0.0001, verbose=0) >>> model.components_ array([[ 2.09783018, 0.30560234], [ 2.13443044, 2.13171694]]) >>> model.reconstruction_err_ #doctest: +ELLIPSIS 0.00115993... References ---------- C.-J. Lin. Projected gradient methods for non-negative matrix factorization. Neural Computation, 19(2007), 2756-2779. http://www.csie.ntu.edu.tw/~cjlin/nmf/ Cichocki, Andrzej, and P. H. A. N. Anh-Huy. "Fast local algorithms for large scale nonnegative matrix and tensor factorizations." IEICE transactions on fundamentals of electronics, communications and computer sciences 92.3: 708-721, 2009. """ def __init__(self, n_components=None, init=None, solver='cd', tol=1e-4, max_iter=200, random_state=None, alpha=0., l1_ratio=0., verbose=0, shuffle=False, nls_max_iter=2000, sparseness=None, beta=1, eta=0.1): self.n_components = n_components self.init = init self.solver = solver self.tol = tol self.max_iter = max_iter self.random_state = random_state self.alpha = alpha self.l1_ratio = l1_ratio self.verbose = verbose self.shuffle = shuffle if sparseness is not None: warnings.warn("Controlling regularization through the sparseness," " beta and eta arguments is only available" " for 'pg' solver, which will be removed" " in release 0.19. Use another solver with L1 or L2" " regularization instead.", DeprecationWarning) self.nls_max_iter = nls_max_iter self.sparseness = sparseness self.beta = beta self.eta = eta def fit_transform(self, X, y=None, W=None, H=None): """Learn a NMF model for the data X and returns the transformed data. This is more efficient than calling fit followed by transform. Parameters ---------- X: {array-like, sparse matrix}, shape (n_samples, n_features) Data matrix to be decomposed W : array-like, shape (n_samples, n_components) If init='custom', it is used as initial guess for the solution. H : array-like, shape (n_components, n_features) If init='custom', it is used as initial guess for the solution. Attributes ---------- components_ : array-like, shape (n_components, n_features) Factorization matrix, sometimes called 'dictionary'. n_iter_ : int Actual number of iterations for the transform. Returns ------- W: array, shape (n_samples, n_components) Transformed data. """ X = check_array(X, accept_sparse=('csr', 'csc')) W, H, n_iter_ = non_negative_factorization( X=X, W=W, H=H, n_components=self.n_components, init=self.init, update_H=True, solver=self.solver, tol=self.tol, max_iter=self.max_iter, alpha=self.alpha, l1_ratio=self.l1_ratio, regularization='both', random_state=self.random_state, verbose=self.verbose, shuffle=self.shuffle, nls_max_iter=self.nls_max_iter, sparseness=self.sparseness, beta=self.beta, eta=self.eta) if self.solver == 'pg': self.comp_sparseness_ = _sparseness(H.ravel()) self.data_sparseness_ = _sparseness(W.ravel()) self.reconstruction_err_ = _safe_compute_error(X, W, H) self.n_components_ = H.shape[0] self.components_ = H self.n_iter_ = n_iter_ return W def fit(self, X, y=None, **params): """Learn a NMF model for the data X. Parameters ---------- X: {array-like, sparse matrix}, shape (n_samples, n_features) Data matrix to be decomposed Attributes ---------- components_ : array-like, shape (n_components, n_features) Factorization matrix, sometimes called 'dictionary'. n_iter_ : int Actual number of iterations for the transform. Returns ------- self """ self.fit_transform(X, **params) return self def transform(self, X): """Transform the data X according to the fitted NMF model Parameters ---------- X: {array-like, sparse matrix}, shape (n_samples, n_features) Data matrix to be transformed by the model Attributes ---------- n_iter_ : int Actual number of iterations for the transform. Returns ------- W: array, shape (n_samples, n_components) Transformed data """ check_is_fitted(self, 'n_components_') W, _, n_iter_ = non_negative_factorization( X=X, W=None, H=self.components_, n_components=self.n_components_, init=self.init, update_H=False, solver=self.solver, tol=self.tol, max_iter=self.max_iter, alpha=self.alpha, l1_ratio=self.l1_ratio, regularization='both', random_state=self.random_state, verbose=self.verbose, shuffle=self.shuffle, nls_max_iter=self.nls_max_iter, sparseness=self.sparseness, beta=self.beta, eta=self.eta) self.n_iter_ = n_iter_ return W def inverse_transform(self, W): """ Parameters ---------- W: {array-like, sparse matrix}, shape (n_samples, n_components) Transformed Data matrix Returns ------- X: {array-like, sparse matrix}, shape (n_samples, n_features) Data matrix of original shape .. versionadded:: 0.18 """ check_is_fitted(self, 'n_components_') return np.dot(W, self.components_) @deprecated("It will be removed in release 0.19. Use NMF instead." "'pg' solver is still available until release 0.19.") class ProjectedGradientNMF(NMF): """Non-Negative Matrix Factorization (NMF) Find two non-negative matrices (W, H) whose product approximates the non- negative matrix X. This factorization can be used for example for dimensionality reduction, source separation or topic extraction. The objective function is:: 0.5 * ||X - WH||_Fro^2 + alpha * l1_ratio * ||vec(W)||_1 + alpha * l1_ratio * ||vec(H)||_1 + 0.5 * alpha * (1 - l1_ratio) * ||W||_Fro^2 + 0.5 * alpha * (1 - l1_ratio) * ||H||_Fro^2 Where:: ||A||_Fro^2 = \sum_{i,j} A_{ij}^2 (Frobenius norm) ||vec(A)||_1 = \sum_{i,j} abs(A_{ij}) (Elementwise L1 norm) The objective function is minimized with an alternating minimization of W and H. Read more in the :ref:`User Guide <NMF>`. Parameters ---------- n_components : int or None Number of components, if n_components is not set all features are kept. init : 'random' | 'nndsvd' | 'nndsvda' | 'nndsvdar' | 'custom' Method used to initialize the procedure. Default: 'nndsvdar' if n_components < n_features, otherwise random. Valid options: - 'random': non-negative random matrices, scaled with: sqrt(X.mean() / n_components) - 'nndsvd': Nonnegative Double Singular Value Decomposition (NNDSVD) initialization (better for sparseness) - 'nndsvda': NNDSVD with zeros filled with the average of X (better when sparsity is not desired) - 'nndsvdar': NNDSVD with zeros filled with small random values (generally faster, less accurate alternative to NNDSVDa for when sparsity is not desired) - 'custom': use custom matrices W and H solver : 'pg' | 'cd' Numerical solver to use: 'pg' is a Projected Gradient solver (deprecated). 'cd' is a Coordinate Descent solver (recommended). .. versionadded:: 0.17 Coordinate Descent solver. .. versionchanged:: 0.17 Deprecated Projected Gradient solver. tol : double, default: 1e-4 Tolerance value used in stopping conditions. max_iter : integer, default: 200 Number of iterations to compute. random_state : integer seed, RandomState instance, or None (default) Random number generator seed control. alpha : double, default: 0. Constant that multiplies the regularization terms. Set it to zero to have no regularization. .. versionadded:: 0.17 *alpha* used in the Coordinate Descent solver. l1_ratio : double, default: 0. The regularization mixing parameter, with 0 <= l1_ratio <= 1. For l1_ratio = 0 the penalty is an elementwise L2 penalty (aka Frobenius Norm). For l1_ratio = 1 it is an elementwise L1 penalty. For 0 < l1_ratio < 1, the penalty is a combination of L1 and L2. .. versionadded:: 0.17 Regularization parameter *l1_ratio* used in the Coordinate Descent solver. shuffle : boolean, default: False If true, randomize the order of coordinates in the CD solver. .. versionadded:: 0.17 *shuffle* parameter used in the Coordinate Descent solver. nls_max_iter : integer, default: 2000 Number of iterations in NLS subproblem. Used only in the deprecated 'pg' solver. .. versionchanged:: 0.17 Deprecated Projected Gradient solver. Use Coordinate Descent solver instead. sparseness : 'data' | 'components' | None, default: None Where to enforce sparsity in the model. Used only in the deprecated 'pg' solver. .. versionchanged:: 0.17 Deprecated Projected Gradient solver. Use Coordinate Descent solver instead. beta : double, default: 1 Degree of sparseness, if sparseness is not None. Larger values mean more sparseness. Used only in the deprecated 'pg' solver. .. versionchanged:: 0.17 Deprecated Projected Gradient solver. Use Coordinate Descent solver instead. eta : double, default: 0.1 Degree of correctness to maintain, if sparsity is not None. Smaller values mean larger error. Used only in the deprecated 'pg' solver. .. versionchanged:: 0.17 Deprecated Projected Gradient solver. Use Coordinate Descent solver instead. Attributes ---------- components_ : array, [n_components, n_features] Non-negative components of the data. reconstruction_err_ : number Frobenius norm of the matrix difference between the training data and the reconstructed data from the fit produced by the model. ``|| X - WH ||_2`` n_iter_ : int Actual number of iterations. Examples -------- >>> import numpy as np >>> X = np.array([[1,1], [2, 1], [3, 1.2], [4, 1], [5, 0.8], [6, 1]]) >>> from sklearn.decomposition import NMF >>> model = NMF(n_components=2, init='random', random_state=0) >>> model.fit(X) #doctest: +ELLIPSIS +NORMALIZE_WHITESPACE NMF(alpha=0.0, beta=1, eta=0.1, init='random', l1_ratio=0.0, max_iter=200, n_components=2, nls_max_iter=2000, random_state=0, shuffle=False, solver='cd', sparseness=None, tol=0.0001, verbose=0) >>> model.components_ array([[ 2.09783018, 0.30560234], [ 2.13443044, 2.13171694]]) >>> model.reconstruction_err_ #doctest: +ELLIPSIS 0.00115993... References ---------- C.-J. Lin. Projected gradient methods for non-negative matrix factorization. Neural Computation, 19(2007), 2756-2779. http://www.csie.ntu.edu.tw/~cjlin/nmf/ Cichocki, Andrzej, and P. H. A. N. Anh-Huy. "Fast local algorithms for large scale nonnegative matrix and tensor factorizations." IEICE transactions on fundamentals of electronics, communications and computer sciences 92.3: 708-721, 2009. """ def __init__(self, n_components=None, solver='pg', init=None, tol=1e-4, max_iter=200, random_state=None, alpha=0., l1_ratio=0., verbose=0, nls_max_iter=2000, sparseness=None, beta=1, eta=0.1): super(ProjectedGradientNMF, self).__init__( n_components=n_components, init=init, solver='pg', tol=tol, max_iter=max_iter, random_state=random_state, alpha=alpha, l1_ratio=l1_ratio, verbose=verbose, nls_max_iter=nls_max_iter, sparseness=sparseness, beta=beta, eta=eta)
bsd-3-clause
thopiekar/Cura
plugins/VersionUpgrade/VersionUpgrade21to22/MachineInstance.py
3
7993
# Copyright (c) 2018 Ultimaker B.V. # Cura is released under the terms of the LGPLv3 or higher. import configparser #To read config files. import io #To write config files to strings as if they were files. import os.path #To get the path to write new user profiles to. from typing import Dict, List, Optional, Set, Tuple import urllib #To serialise the user container file name properly. import urllib.parse import UM.VersionUpgrade #To indicate that a file is of incorrect format. import UM.VersionUpgradeManager #To schedule more files to be upgraded. from UM.Resources import Resources #To get the config storage path. ## Creates a new machine instance instance by parsing a serialised machine # instance in version 1 of the file format. # # \param serialised The serialised form of a machine instance in version 1. # \param filename The supposed file name of this machine instance, without # extension. # \return A machine instance instance, or None if the file format is # incorrect. def importFrom(serialised: str, filename: str) -> Optional["MachineInstance"]: try: return MachineInstance(serialised, filename) except (configparser.Error, UM.VersionUpgrade.FormatException, UM.VersionUpgrade.InvalidVersionException): return None ## A representation of a machine instance used as intermediary form for # conversion from one format to the other. class MachineInstance: ## Reads version 1 of the file format, storing it in memory. # # \param serialised A string with the contents of a machine instance file, # without extension. # \param filename The supposed file name of this machine instance. def __init__(self, serialised: str, filename: str) -> None: self._filename = filename config = configparser.ConfigParser(interpolation = None) config.read_string(serialised) # Read the input string as config file. # Checking file correctness. if not config.has_section("general"): raise UM.VersionUpgrade.FormatException("No \"general\" section.") if not config.has_option("general", "version"): raise UM.VersionUpgrade.FormatException("No \"version\" in \"general\" section.") if not config.has_option("general", "name"): raise UM.VersionUpgrade.FormatException("No \"name\" in \"general\" section.") if not config.has_option("general", "type"): raise UM.VersionUpgrade.FormatException("No \"type\" in \"general\" section.") if int(config.get("general", "version")) != 1: # Explicitly hard-code version 1, since if this number changes the programmer MUST change this entire function. raise UM.VersionUpgrade.InvalidVersionException("The version of this machine instance is wrong. It must be 1.") self._type_name = config.get("general", "type") self._variant_name = config.get("general", "variant", fallback = "empty_variant") self._name = config.get("general", "name", fallback = "") self._key = config.get("general", "key", fallback = "") self._active_profile_name = config.get("general", "active_profile", fallback = "empty_quality") self._active_material_name = config.get("general", "material", fallback = "empty_material") self._machine_setting_overrides = {} # type: Dict[str, str] for key, value in config["machine_settings"].items(): self._machine_setting_overrides[key] = value ## Serialises this machine instance as file format version 2. # # This is where the actual translation happens in this case. # # \return A tuple containing the new filename and a serialised form of # this machine instance, serialised in version 2 of the file format. def export(self) -> Tuple[List[str], List[str]]: config = configparser.ConfigParser(interpolation = None) # Build a config file in the form of version 2. config.add_section("general") config.set("general", "name", self._name) config.set("general", "id", self._name) config.set("general", "version", "2") # Hard-code version 2, since if this number changes the programmer MUST change this entire function. import VersionUpgrade21to22 # Import here to prevent circular dependencies. has_machine_qualities = self._type_name in VersionUpgrade21to22.VersionUpgrade21to22.VersionUpgrade21to22.machinesWithMachineQuality() type_name = VersionUpgrade21to22.VersionUpgrade21to22.VersionUpgrade21to22.translatePrinter(self._type_name) active_material = VersionUpgrade21to22.VersionUpgrade21to22.VersionUpgrade21to22.translateMaterial(self._active_material_name) variant = VersionUpgrade21to22.VersionUpgrade21to22.VersionUpgrade21to22.translateVariant(self._variant_name, type_name) variant_materials = VersionUpgrade21to22.VersionUpgrade21to22.VersionUpgrade21to22.translateVariantForMaterials(self._variant_name, type_name) #Convert to quality profile if we have one of the built-in profiles, otherwise convert to a quality-changes profile. if self._active_profile_name in VersionUpgrade21to22.VersionUpgrade21to22.VersionUpgrade21to22.builtInProfiles(): active_quality = VersionUpgrade21to22.VersionUpgrade21to22.VersionUpgrade21to22.translateProfile(self._active_profile_name) active_quality_changes = "empty_quality_changes" else: active_quality = VersionUpgrade21to22.VersionUpgrade21to22.VersionUpgrade21to22.getQualityFallback(type_name, variant, active_material) active_quality_changes = self._active_profile_name if has_machine_qualities: #This machine now has machine-quality profiles. active_material += "_" + variant_materials #Create a new user profile and schedule it to be upgraded. user_profile = configparser.ConfigParser(interpolation = None) user_profile["general"] = { "version": "2", "name": "Current settings", "definition": type_name } user_profile["metadata"] = { "type": "user", "machine": self._name } user_profile["values"] = {} version_upgrade_manager = UM.VersionUpgradeManager.VersionUpgradeManager.getInstance() user_version_to_paths_dict = version_upgrade_manager.getStoragePaths("user") paths_set = set() # type: Set[str] for paths in user_version_to_paths_dict.values(): paths_set |= paths user_storage = os.path.join(Resources.getDataStoragePath(), next(iter(paths_set))) user_profile_file = os.path.join(user_storage, urllib.parse.quote_plus(self._name) + "_current_settings.inst.cfg") if not os.path.exists(user_storage): os.makedirs(user_storage) with open(user_profile_file, "w", encoding = "utf-8") as file_handle: user_profile.write(file_handle) version_upgrade_manager.upgradeExtraFile(user_storage, urllib.parse.quote_plus(self._name), "user") containers = [ self._name + "_current_settings", #The current profile doesn't know the definition ID when it was upgraded, only the instance ID, so it will be invalid. Sorry, your current settings are lost now. active_quality_changes, active_quality, active_material, variant, type_name ] config.set("general", "containers", ",".join(containers)) config.add_section("metadata") config.set("metadata", "type", "machine") VersionUpgrade21to22.VersionUpgrade21to22.VersionUpgrade21to22.translateSettings(self._machine_setting_overrides) config.add_section("values") for key, value in self._machine_setting_overrides.items(): config.set("values", key, str(value)) output = io.StringIO() config.write(output) return [self._filename], [output.getvalue()]
lgpl-3.0
bobisme/odoo
addons/delivery/partner.py
383
1404
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## from openerp.osv import fields, osv class res_partner(osv.osv): _inherit = 'res.partner' _columns = { 'property_delivery_carrier': fields.property( type='many2one', relation='delivery.carrier', string="Delivery Method", help="This delivery method will be used when invoicing from picking."), } # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
agpl-3.0
ckane/crits
crits/config/database_example.py
17
1635
# This is an example file. You should copy this to "database.py" and # make your changes there. # Modifying this example file will not change the settings that CRITs uses. # MongoDB connection information MONGO_HOST = 'localhost' # server to connect to MONGO_PORT = 27017 # port MongoD is running on MONGO_DATABASE = 'crits' # database name to connect to # The following optional settings should only be changed if you specifically # enabled and configured them during your MongoDB installation # See http://docs.mongodb.org/v2.4/administration/security/ regarding implementation MONGO_SSL = False # whether MongoD has SSL enabled MONGO_USER = '' # mongo user with "readWrite" role in the database MONGO_PASSWORD = '' # password for the mongo user # Set this to a sufficiently long random string. We recommend running # the following code from a python shell to generate the string and pasting # the output here. # # from django.utils.crypto import get_random_string as grs # print grs(50, 'abcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*(-_=+)') SECRET_KEY = '' # DB to use for files FILE_DB = GRIDFS # Set to S3 (NO QUOTES) to use S3. You'll also want to set # the stuff below and create your buckets. # Separator to use in bucket names (if needed) #S3_SEPARATOR = '.' # Unique ID to append to bucket names (if needed) #S3_ID="" # S3 credentials (if needed) #AWS_ACCESS_KEY_ID = "" #AWS_SECRET_ACCESS_KEY = "" # If your S3 location is somewhere other than s3.amazonaws.com, then you # can specify a different hostname here. (if needed) #S3_HOSTNAME = ""
mit
shsingh/ansible
lib/ansible/module_utils/network/eos/config/lldp_interfaces/lldp_interfaces.py
19
7085
# -*- coding: utf-8 -*- # Copyright 2019 Red Hat # GNU General Public License v3.0+ # (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) """ The eos_lldp_interfaces class It is in this file where the current configuration (as dict) is compared to the provided configuration (as dict) and the command set necessary to bring the current configuration to it's desired end-state is created """ from __future__ import (absolute_import, division, print_function) __metaclass__ = type from ansible.module_utils.network.common.cfg.base import ConfigBase from ansible.module_utils.network.common.utils import to_list, dict_diff, param_list_to_dict from ansible.module_utils.network.eos.facts.facts import Facts from ansible.module_utils.network.eos.utils.utils import normalize_interface class Lldp_interfaces(ConfigBase): """ The eos_lldp_interfaces class """ gather_subset = [ '!all', '!min', ] gather_network_resources = [ 'lldp_interfaces', ] def get_lldp_interfaces_facts(self): """ Get the 'facts' (the current configuration) :rtype: A dictionary :returns: The current configuration as a dictionary """ facts, _warnings = Facts(self._module).get_facts(self.gather_subset, self.gather_network_resources) lldp_interfaces_facts = facts['ansible_network_resources'].get('lldp_interfaces') if not lldp_interfaces_facts: return [] return lldp_interfaces_facts def execute_module(self): """ Execute the module :rtype: A dictionary :returns: The result from module execution """ result = {'changed': False} warnings = list() commands = list() existing_lldp_interfaces_facts = self.get_lldp_interfaces_facts() commands.extend(self.set_config(existing_lldp_interfaces_facts)) if commands: if not self._module.check_mode: self._connection.edit_config(commands) result['changed'] = True result['commands'] = commands changed_lldp_interfaces_facts = self.get_lldp_interfaces_facts() result['before'] = existing_lldp_interfaces_facts if result['changed']: result['after'] = changed_lldp_interfaces_facts result['warnings'] = warnings return result def set_config(self, existing_lldp_interfaces_facts): """ Collect the configuration from the args passed to the module, collect the current configuration (as a dict from facts) :rtype: A list :returns: the commands necessary to migrate the current configuration to the desired configuration """ want = self._module.params['config'] have = existing_lldp_interfaces_facts resp = self.set_state(want, have) return to_list(resp) def set_state(self, want, have): """ Select the appropriate function based on the state provided :param want: the desired configuration as a dictionary :param have: the current configuration as a dictionary :rtype: A list :returns: the commands necessary to migrate the current configuration to the desired configuration """ state = self._module.params['state'] want = param_list_to_dict(want, remove_key=False) have = param_list_to_dict(have, remove_key=False) if state == 'overridden': commands = self._state_overridden(want, have) elif state == 'deleted': commands = self._state_deleted(want, have) elif state == 'merged': commands = self._state_merged(want, have) elif state == 'replaced': commands = self._state_replaced(want, have) return commands @staticmethod def _state_replaced(want, have): """ The command generator when state is replaced :rtype: A list :returns: the commands necessary to migrate the current configuration to the desired configuration """ commands = [] for key, desired in want.items(): interface_name = normalize_interface(key) if interface_name in have: extant = have[interface_name] else: extant = dict(name=interface_name) add_config = dict_diff(extant, desired) del_config = dict_diff(desired, extant) commands.extend(generate_commands(interface_name, add_config, del_config)) return commands @staticmethod def _state_overridden(want, have): """ The command generator when state is overridden :rtype: A list :returns: the commands necessary to migrate the current configuration to the desired configuration """ commands = [] for key, extant in have.items(): if key in want: desired = want[key] else: desired = dict(name=key) add_config = dict_diff(extant, desired) del_config = dict_diff(desired, extant) commands.extend(generate_commands(key, add_config, del_config)) return commands @staticmethod def _state_merged(want, have): """ The command generator when state is merged :rtype: A list :returns: the commands necessary to merge the provided into the current configuration """ commands = [] for key, desired in want.items(): interface_name = normalize_interface(key) if interface_name in have: extant = have[interface_name] else: extant = dict(name=interface_name) add_config = dict_diff(extant, desired) commands.extend(generate_commands(interface_name, add_config, {})) return commands @staticmethod def _state_deleted(want, have): """ The command generator when state is deleted :rtype: A list :returns: the commands necessary to remove the current configuration of the provided objects """ commands = [] for key in want.keys(): interface_name = normalize_interface(key) desired = dict(name=interface_name) if interface_name in have: extant = have[interface_name] else: continue del_config = dict_diff(desired, extant) commands.extend(generate_commands(interface_name, {}, del_config)) return commands def generate_commands(name, to_set, to_remove): commands = [] for key, value in to_set.items(): if value is None: continue prefix = "" if value else "no " commands.append("{0}lldp {1}".format(prefix, key)) for key in to_remove: commands.append("lldp {0}".format(key)) if commands: commands.insert(0, "interface {0}".format(name)) return commands
gpl-3.0
panyam/libgraph
libgraph/graphs.py
1
2606
class Edge(object): def __init__(self, source, target, data = None): self._source, self._target, self.data = source, target, data def __repr__(self): return "Edge<%s <-> %s>" % (repr(self.source), repr(self.target)) @property def source(self): return self._source @property def target(self): return self._target class Graph(object): def __init__(self, multi = False, directed = False, key_func = None, neighbors_func = None): self.nodes = {} self._is_directed = directed self._is_multi = multi self.neighbors_func = neighbors_func self.key_func = key_func or (lambda x: x) @property def is_directed(self): return self._is_directed @property def is_multi(self): return self._is_multi def get_edge(self, source, target): return self.nodes.get(self.key_func(source), {}).get(self.key_func(target), None) def add_nodes(self, *nodes): return [self.add_node(node) for node in nodes] def add_node(self, node): """ Adds or update a node (any hashable) in the graph. """ if node not in self.nodes: self.nodes[self.key_func(node)] = {} return self.nodes[self.key_func(node)] def neighbors(self, node): """Return the neighbors of a node.""" if self.neighbors_func: return self.neighbors_func(node) else: return self.nodes.get(self.key_func(node), {}) def iter_neighbors(self, node, reverse = False): """ Return an iterator of neighbors (along with any edge data) for a particular node. Override this method for custom node storage and inspection strategies. """ neighbors = self.neighbors(node) if type(neighbors) is dict: if reverse: return reversed(self.neighbors(node).items()) else: return self.neighbors(node).iteritems() else: if reverse: return reversed(neighbors) else: return neighbors def add_raw_edge(self, edge): self.add_nodes(edge.source,edge.target) source,target = edge.source,edge.target source_key = self.key_func(source) target_key = self.key_func(target) self.nodes[source_key][target_key] = edge if not self.is_directed and source_key != target_key: self.nodes[target_key][source_key] = edge return edge def add_edge(self, source, target): return self.add_raw_edge(Edge(source, target)) def add_edges(self, *edges): return [self.add_edge(*e) for e in edges]
apache-2.0
dydek/django
tests/gis_tests/geoapp/test_serializers.py
245
3731
from __future__ import unicode_literals import json from django.contrib.gis.geos import LinearRing, Point, Polygon from django.core import serializers from django.test import TestCase, mock, skipUnlessDBFeature from django.utils import six from .models import City, MultiFields, PennsylvaniaCity @skipUnlessDBFeature("gis_enabled") class GeoJSONSerializerTests(TestCase): fixtures = ['initial'] def test_builtin_serializers(self): """ 'geojson' should be listed in available serializers. """ all_formats = set(serializers.get_serializer_formats()) public_formats = set(serializers.get_public_serializer_formats()) self.assertIn('geojson', all_formats), self.assertIn('geojson', public_formats) def test_serialization_base(self): geojson = serializers.serialize('geojson', City.objects.all().order_by('name')) try: geodata = json.loads(geojson) except Exception: self.fail("Serialized output is not valid JSON") self.assertEqual(len(geodata['features']), len(City.objects.all())) self.assertEqual(geodata['features'][0]['geometry']['type'], 'Point') self.assertEqual(geodata['features'][0]['properties']['name'], 'Chicago') def test_geometry_field_option(self): """ When a model has several geometry fields, the 'geometry_field' option can be used to specify the field to use as the 'geometry' key. """ MultiFields.objects.create( city=City.objects.first(), name='Name', point=Point(5, 23), poly=Polygon(LinearRing((0, 0), (0, 5), (5, 5), (5, 0), (0, 0)))) geojson = serializers.serialize('geojson', MultiFields.objects.all()) geodata = json.loads(geojson) self.assertEqual(geodata['features'][0]['geometry']['type'], 'Point') geojson = serializers.serialize('geojson', MultiFields.objects.all(), geometry_field='poly') geodata = json.loads(geojson) self.assertEqual(geodata['features'][0]['geometry']['type'], 'Polygon') def test_fields_option(self): """ The fields option allows to define a subset of fields to be present in the 'properties' of the generated output. """ PennsylvaniaCity.objects.create(name='Mansfield', county='Tioga', point='POINT(-77.071445 41.823881)') geojson = serializers.serialize('geojson', PennsylvaniaCity.objects.all(), fields=('county', 'point')) geodata = json.loads(geojson) self.assertIn('county', geodata['features'][0]['properties']) self.assertNotIn('founded', geodata['features'][0]['properties']) def test_srid_option(self): geojson = serializers.serialize('geojson', City.objects.all().order_by('name'), srid=2847) geodata = json.loads(geojson) self.assertEqual( [int(c) for c in geodata['features'][0]['geometry']['coordinates']], [1564802, 5613214]) @mock.patch('django.contrib.gis.serializers.geojson.HAS_GDAL', False) def test_without_gdal(self): # Without coordinate transformation, the serialization should succeed: serializers.serialize('geojson', City.objects.all()) with six.assertRaisesRegex(self, serializers.base.SerializationError, '.*GDAL is not installed'): # Coordinate transformations need GDAL serializers.serialize('geojson', City.objects.all(), srid=2847) def test_deserialization_exception(self): """ GeoJSON cannot be deserialized. """ with self.assertRaises(serializers.base.SerializerDoesNotExist): serializers.deserialize('geojson', '{}')
bsd-3-clause
shanemcd/ansible
lib/ansible/utils/module_docs_fragments/infinibox.py
210
1564
# # (c) 2016, Gregory Shulov <gregory.shulov@gmail.com> # # 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/>. class ModuleDocFragment(object): # Standard Infinibox documentation fragment DOCUMENTATION = ''' options: system: description: - Infinibox Hostname or IPv4 Address. required: true user: description: - Infinibox User username with sufficient priveledges ( see notes ). required: false password: description: - Infinibox User password. required: false notes: - This module requires infinisdk python library - You must set INFINIBOX_USER and INFINIBOX_PASSWORD environment variables if user and password arguments are not passed to the module directly - Ansible uses the infinisdk configuration file C(~/.infinidat/infinisdk.ini) if no credentials are provided. See U(http://infinisdk.readthedocs.io/en/latest/getting_started.html) requirements: - "python >= 2.7" - infinisdk '''
gpl-3.0
Hardslog/android_kernel_asus_ze551kl
Documentation/networking/cxacru-cf.py
14668
1626
#!/usr/bin/env python # Copyright 2009 Simon Arlott # # This program is free software; you can redistribute it and/or modify it # under the terms of the GNU General Public License as published by the Free # Software Foundation; either version 2 of the License, or (at your option) # any later version. # # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or # FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for # more details. # # You should have received a copy of the GNU General Public License along with # this program; if not, write to the Free Software Foundation, Inc., 59 # Temple Place - Suite 330, Boston, MA 02111-1307, USA. # # Usage: cxacru-cf.py < cxacru-cf.bin # Output: values string suitable for the sysfs adsl_config attribute # # Warning: cxacru-cf.bin with MD5 hash cdbac2689969d5ed5d4850f117702110 # contains mis-aligned values which will stop the modem from being able # to make a connection. If the first and last two bytes are removed then # the values become valid, but the modulation will be forced to ANSI # T1.413 only which may not be appropriate. # # The original binary format is a packed list of le32 values. import sys import struct i = 0 while True: buf = sys.stdin.read(4) if len(buf) == 0: break elif len(buf) != 4: sys.stdout.write("\n") sys.stderr.write("Error: read {0} not 4 bytes\n".format(len(buf))) sys.exit(1) if i > 0: sys.stdout.write(" ") sys.stdout.write("{0:x}={1}".format(i, struct.unpack("<I", buf)[0])) i += 1 sys.stdout.write("\n")
gpl-2.0
gameduell/duell
bin/win/python2.7.9/Lib/distutils/command/bdist_msi.py
164
35191
# -*- coding: iso-8859-1 -*- # Copyright (C) 2005, 2006 Martin von Löwis # Licensed to PSF under a Contributor Agreement. # The bdist_wininst command proper # based on bdist_wininst """ Implements the bdist_msi command. """ import sys, os from sysconfig import get_python_version from distutils.core import Command from distutils.dir_util import remove_tree from distutils.version import StrictVersion from distutils.errors import DistutilsOptionError from distutils import log from distutils.util import get_platform import msilib from msilib import schema, sequence, text from msilib import Directory, Feature, Dialog, add_data class PyDialog(Dialog): """Dialog class with a fixed layout: controls at the top, then a ruler, then a list of buttons: back, next, cancel. Optionally a bitmap at the left.""" def __init__(self, *args, **kw): """Dialog(database, name, x, y, w, h, attributes, title, first, default, cancel, bitmap=true)""" Dialog.__init__(self, *args) ruler = self.h - 36 #if kw.get("bitmap", True): # self.bitmap("Bitmap", 0, 0, bmwidth, ruler, "PythonWin") self.line("BottomLine", 0, ruler, self.w, 0) def title(self, title): "Set the title text of the dialog at the top." # name, x, y, w, h, flags=Visible|Enabled|Transparent|NoPrefix, # text, in VerdanaBold10 self.text("Title", 15, 10, 320, 60, 0x30003, r"{\VerdanaBold10}%s" % title) def back(self, title, next, name = "Back", active = 1): """Add a back button with a given title, the tab-next button, its name in the Control table, possibly initially disabled. Return the button, so that events can be associated""" if active: flags = 3 # Visible|Enabled else: flags = 1 # Visible return self.pushbutton(name, 180, self.h-27 , 56, 17, flags, title, next) def cancel(self, title, next, name = "Cancel", active = 1): """Add a cancel button with a given title, the tab-next button, its name in the Control table, possibly initially disabled. Return the button, so that events can be associated""" if active: flags = 3 # Visible|Enabled else: flags = 1 # Visible return self.pushbutton(name, 304, self.h-27, 56, 17, flags, title, next) def next(self, title, next, name = "Next", active = 1): """Add a Next button with a given title, the tab-next button, its name in the Control table, possibly initially disabled. Return the button, so that events can be associated""" if active: flags = 3 # Visible|Enabled else: flags = 1 # Visible return self.pushbutton(name, 236, self.h-27, 56, 17, flags, title, next) def xbutton(self, name, title, next, xpos): """Add a button with a given title, the tab-next button, its name in the Control table, giving its x position; the y-position is aligned with the other buttons. Return the button, so that events can be associated""" return self.pushbutton(name, int(self.w*xpos - 28), self.h-27, 56, 17, 3, title, next) class bdist_msi (Command): description = "create a Microsoft Installer (.msi) binary distribution" user_options = [('bdist-dir=', None, "temporary directory for creating the distribution"), ('plat-name=', 'p', "platform name to embed in generated filenames " "(default: %s)" % get_platform()), ('keep-temp', 'k', "keep the pseudo-installation tree around after " + "creating the distribution archive"), ('target-version=', None, "require a specific python version" + " on the target system"), ('no-target-compile', 'c', "do not compile .py to .pyc on the target system"), ('no-target-optimize', 'o', "do not compile .py to .pyo (optimized)" "on the target system"), ('dist-dir=', 'd', "directory to put final built distributions in"), ('skip-build', None, "skip rebuilding everything (for testing/debugging)"), ('install-script=', None, "basename of installation script to be run after" "installation or before deinstallation"), ('pre-install-script=', None, "Fully qualified filename of a script to be run before " "any files are installed. This script need not be in the " "distribution"), ] boolean_options = ['keep-temp', 'no-target-compile', 'no-target-optimize', 'skip-build'] all_versions = ['2.0', '2.1', '2.2', '2.3', '2.4', '2.5', '2.6', '2.7', '2.8', '2.9', '3.0', '3.1', '3.2', '3.3', '3.4', '3.5', '3.6', '3.7', '3.8', '3.9'] other_version = 'X' def initialize_options (self): self.bdist_dir = None self.plat_name = None self.keep_temp = 0 self.no_target_compile = 0 self.no_target_optimize = 0 self.target_version = None self.dist_dir = None self.skip_build = None self.install_script = None self.pre_install_script = None self.versions = None def finalize_options (self): self.set_undefined_options('bdist', ('skip_build', 'skip_build')) if self.bdist_dir is None: bdist_base = self.get_finalized_command('bdist').bdist_base self.bdist_dir = os.path.join(bdist_base, 'msi') short_version = get_python_version() if (not self.target_version) and self.distribution.has_ext_modules(): self.target_version = short_version if self.target_version: self.versions = [self.target_version] if not self.skip_build and self.distribution.has_ext_modules()\ and self.target_version != short_version: raise DistutilsOptionError, \ "target version can only be %s, or the '--skip-build'" \ " option must be specified" % (short_version,) else: self.versions = list(self.all_versions) self.set_undefined_options('bdist', ('dist_dir', 'dist_dir'), ('plat_name', 'plat_name'), ) if self.pre_install_script: raise DistutilsOptionError, "the pre-install-script feature is not yet implemented" if self.install_script: for script in self.distribution.scripts: if self.install_script == os.path.basename(script): break else: raise DistutilsOptionError, \ "install_script '%s' not found in scripts" % \ self.install_script self.install_script_key = None # finalize_options() def run (self): if not self.skip_build: self.run_command('build') install = self.reinitialize_command('install', reinit_subcommands=1) install.prefix = self.bdist_dir install.skip_build = self.skip_build install.warn_dir = 0 install_lib = self.reinitialize_command('install_lib') # we do not want to include pyc or pyo files install_lib.compile = 0 install_lib.optimize = 0 if self.distribution.has_ext_modules(): # If we are building an installer for a Python version other # than the one we are currently running, then we need to ensure # our build_lib reflects the other Python version rather than ours. # Note that for target_version!=sys.version, we must have skipped the # build step, so there is no issue with enforcing the build of this # version. target_version = self.target_version if not target_version: assert self.skip_build, "Should have already checked this" target_version = sys.version[0:3] plat_specifier = ".%s-%s" % (self.plat_name, target_version) build = self.get_finalized_command('build') build.build_lib = os.path.join(build.build_base, 'lib' + plat_specifier) log.info("installing to %s", self.bdist_dir) install.ensure_finalized() # avoid warning of 'install_lib' about installing # into a directory not in sys.path sys.path.insert(0, os.path.join(self.bdist_dir, 'PURELIB')) install.run() del sys.path[0] self.mkpath(self.dist_dir) fullname = self.distribution.get_fullname() installer_name = self.get_installer_filename(fullname) installer_name = os.path.abspath(installer_name) if os.path.exists(installer_name): os.unlink(installer_name) metadata = self.distribution.metadata author = metadata.author if not author: author = metadata.maintainer if not author: author = "UNKNOWN" version = metadata.get_version() # ProductVersion must be strictly numeric # XXX need to deal with prerelease versions sversion = "%d.%d.%d" % StrictVersion(version).version # Prefix ProductName with Python x.y, so that # it sorts together with the other Python packages # in Add-Remove-Programs (APR) fullname = self.distribution.get_fullname() if self.target_version: product_name = "Python %s %s" % (self.target_version, fullname) else: product_name = "Python %s" % (fullname) self.db = msilib.init_database(installer_name, schema, product_name, msilib.gen_uuid(), sversion, author) msilib.add_tables(self.db, sequence) props = [('DistVersion', version)] email = metadata.author_email or metadata.maintainer_email if email: props.append(("ARPCONTACT", email)) if metadata.url: props.append(("ARPURLINFOABOUT", metadata.url)) if props: add_data(self.db, 'Property', props) self.add_find_python() self.add_files() self.add_scripts() self.add_ui() self.db.Commit() if hasattr(self.distribution, 'dist_files'): tup = 'bdist_msi', self.target_version or 'any', fullname self.distribution.dist_files.append(tup) if not self.keep_temp: remove_tree(self.bdist_dir, dry_run=self.dry_run) def add_files(self): db = self.db cab = msilib.CAB("distfiles") rootdir = os.path.abspath(self.bdist_dir) root = Directory(db, cab, None, rootdir, "TARGETDIR", "SourceDir") f = Feature(db, "Python", "Python", "Everything", 0, 1, directory="TARGETDIR") items = [(f, root, '')] for version in self.versions + [self.other_version]: target = "TARGETDIR" + version name = default = "Python" + version desc = "Everything" if version is self.other_version: title = "Python from another location" level = 2 else: title = "Python %s from registry" % version level = 1 f = Feature(db, name, title, desc, 1, level, directory=target) dir = Directory(db, cab, root, rootdir, target, default) items.append((f, dir, version)) db.Commit() seen = {} for feature, dir, version in items: todo = [dir] while todo: dir = todo.pop() for file in os.listdir(dir.absolute): afile = os.path.join(dir.absolute, file) if os.path.isdir(afile): short = "%s|%s" % (dir.make_short(file), file) default = file + version newdir = Directory(db, cab, dir, file, default, short) todo.append(newdir) else: if not dir.component: dir.start_component(dir.logical, feature, 0) if afile not in seen: key = seen[afile] = dir.add_file(file) if file==self.install_script: if self.install_script_key: raise DistutilsOptionError( "Multiple files with name %s" % file) self.install_script_key = '[#%s]' % key else: key = seen[afile] add_data(self.db, "DuplicateFile", [(key + version, dir.component, key, None, dir.logical)]) db.Commit() cab.commit(db) def add_find_python(self): """Adds code to the installer to compute the location of Python. Properties PYTHON.MACHINE.X.Y and PYTHON.USER.X.Y will be set from the registry for each version of Python. Properties TARGETDIRX.Y will be set from PYTHON.USER.X.Y if defined, else from PYTHON.MACHINE.X.Y. Properties PYTHONX.Y will be set to TARGETDIRX.Y\\python.exe""" start = 402 for ver in self.versions: install_path = r"SOFTWARE\Python\PythonCore\%s\InstallPath" % ver machine_reg = "python.machine." + ver user_reg = "python.user." + ver machine_prop = "PYTHON.MACHINE." + ver user_prop = "PYTHON.USER." + ver machine_action = "PythonFromMachine" + ver user_action = "PythonFromUser" + ver exe_action = "PythonExe" + ver target_dir_prop = "TARGETDIR" + ver exe_prop = "PYTHON" + ver if msilib.Win64: # type: msidbLocatorTypeRawValue + msidbLocatorType64bit Type = 2+16 else: Type = 2 add_data(self.db, "RegLocator", [(machine_reg, 2, install_path, None, Type), (user_reg, 1, install_path, None, Type)]) add_data(self.db, "AppSearch", [(machine_prop, machine_reg), (user_prop, user_reg)]) add_data(self.db, "CustomAction", [(machine_action, 51+256, target_dir_prop, "[" + machine_prop + "]"), (user_action, 51+256, target_dir_prop, "[" + user_prop + "]"), (exe_action, 51+256, exe_prop, "[" + target_dir_prop + "]\\python.exe"), ]) add_data(self.db, "InstallExecuteSequence", [(machine_action, machine_prop, start), (user_action, user_prop, start + 1), (exe_action, None, start + 2), ]) add_data(self.db, "InstallUISequence", [(machine_action, machine_prop, start), (user_action, user_prop, start + 1), (exe_action, None, start + 2), ]) add_data(self.db, "Condition", [("Python" + ver, 0, "NOT TARGETDIR" + ver)]) start += 4 assert start < 500 def add_scripts(self): if self.install_script: start = 6800 for ver in self.versions + [self.other_version]: install_action = "install_script." + ver exe_prop = "PYTHON" + ver add_data(self.db, "CustomAction", [(install_action, 50, exe_prop, self.install_script_key)]) add_data(self.db, "InstallExecuteSequence", [(install_action, "&Python%s=3" % ver, start)]) start += 1 # XXX pre-install scripts are currently refused in finalize_options() # but if this feature is completed, it will also need to add # entries for each version as the above code does if self.pre_install_script: scriptfn = os.path.join(self.bdist_dir, "preinstall.bat") f = open(scriptfn, "w") # The batch file will be executed with [PYTHON], so that %1 # is the path to the Python interpreter; %0 will be the path # of the batch file. # rem =""" # %1 %0 # exit # """ # <actual script> f.write('rem ="""\n%1 %0\nexit\n"""\n') f.write(open(self.pre_install_script).read()) f.close() add_data(self.db, "Binary", [("PreInstall", msilib.Binary(scriptfn)) ]) add_data(self.db, "CustomAction", [("PreInstall", 2, "PreInstall", None) ]) add_data(self.db, "InstallExecuteSequence", [("PreInstall", "NOT Installed", 450)]) def add_ui(self): db = self.db x = y = 50 w = 370 h = 300 title = "[ProductName] Setup" # see "Dialog Style Bits" modal = 3 # visible | modal modeless = 1 # visible # UI customization properties add_data(db, "Property", # See "DefaultUIFont Property" [("DefaultUIFont", "DlgFont8"), # See "ErrorDialog Style Bit" ("ErrorDialog", "ErrorDlg"), ("Progress1", "Install"), # modified in maintenance type dlg ("Progress2", "installs"), ("MaintenanceForm_Action", "Repair"), # possible values: ALL, JUSTME ("WhichUsers", "ALL") ]) # Fonts, see "TextStyle Table" add_data(db, "TextStyle", [("DlgFont8", "Tahoma", 9, None, 0), ("DlgFontBold8", "Tahoma", 8, None, 1), #bold ("VerdanaBold10", "Verdana", 10, None, 1), ("VerdanaRed9", "Verdana", 9, 255, 0), ]) # UI Sequences, see "InstallUISequence Table", "Using a Sequence Table" # Numbers indicate sequence; see sequence.py for how these action integrate add_data(db, "InstallUISequence", [("PrepareDlg", "Not Privileged or Windows9x or Installed", 140), ("WhichUsersDlg", "Privileged and not Windows9x and not Installed", 141), # In the user interface, assume all-users installation if privileged. ("SelectFeaturesDlg", "Not Installed", 1230), # XXX no support for resume installations yet #("ResumeDlg", "Installed AND (RESUME OR Preselected)", 1240), ("MaintenanceTypeDlg", "Installed AND NOT RESUME AND NOT Preselected", 1250), ("ProgressDlg", None, 1280)]) add_data(db, 'ActionText', text.ActionText) add_data(db, 'UIText', text.UIText) ##################################################################### # Standard dialogs: FatalError, UserExit, ExitDialog fatal=PyDialog(db, "FatalError", x, y, w, h, modal, title, "Finish", "Finish", "Finish") fatal.title("[ProductName] Installer ended prematurely") fatal.back("< Back", "Finish", active = 0) fatal.cancel("Cancel", "Back", active = 0) fatal.text("Description1", 15, 70, 320, 80, 0x30003, "[ProductName] setup ended prematurely because of an error. Your system has not been modified. To install this program at a later time, please run the installation again.") fatal.text("Description2", 15, 155, 320, 20, 0x30003, "Click the Finish button to exit the Installer.") c=fatal.next("Finish", "Cancel", name="Finish") c.event("EndDialog", "Exit") user_exit=PyDialog(db, "UserExit", x, y, w, h, modal, title, "Finish", "Finish", "Finish") user_exit.title("[ProductName] Installer was interrupted") user_exit.back("< Back", "Finish", active = 0) user_exit.cancel("Cancel", "Back", active = 0) user_exit.text("Description1", 15, 70, 320, 80, 0x30003, "[ProductName] setup was interrupted. Your system has not been modified. " "To install this program at a later time, please run the installation again.") user_exit.text("Description2", 15, 155, 320, 20, 0x30003, "Click the Finish button to exit the Installer.") c = user_exit.next("Finish", "Cancel", name="Finish") c.event("EndDialog", "Exit") exit_dialog = PyDialog(db, "ExitDialog", x, y, w, h, modal, title, "Finish", "Finish", "Finish") exit_dialog.title("Completing the [ProductName] Installer") exit_dialog.back("< Back", "Finish", active = 0) exit_dialog.cancel("Cancel", "Back", active = 0) exit_dialog.text("Description", 15, 235, 320, 20, 0x30003, "Click the Finish button to exit the Installer.") c = exit_dialog.next("Finish", "Cancel", name="Finish") c.event("EndDialog", "Return") ##################################################################### # Required dialog: FilesInUse, ErrorDlg inuse = PyDialog(db, "FilesInUse", x, y, w, h, 19, # KeepModeless|Modal|Visible title, "Retry", "Retry", "Retry", bitmap=False) inuse.text("Title", 15, 6, 200, 15, 0x30003, r"{\DlgFontBold8}Files in Use") inuse.text("Description", 20, 23, 280, 20, 0x30003, "Some files that need to be updated are currently in use.") inuse.text("Text", 20, 55, 330, 50, 3, "The following applications are using files that need to be updated by this setup. Close these applications and then click Retry to continue the installation or Cancel to exit it.") inuse.control("List", "ListBox", 20, 107, 330, 130, 7, "FileInUseProcess", None, None, None) c=inuse.back("Exit", "Ignore", name="Exit") c.event("EndDialog", "Exit") c=inuse.next("Ignore", "Retry", name="Ignore") c.event("EndDialog", "Ignore") c=inuse.cancel("Retry", "Exit", name="Retry") c.event("EndDialog","Retry") # See "Error Dialog". See "ICE20" for the required names of the controls. error = Dialog(db, "ErrorDlg", 50, 10, 330, 101, 65543, # Error|Minimize|Modal|Visible title, "ErrorText", None, None) error.text("ErrorText", 50,9,280,48,3, "") #error.control("ErrorIcon", "Icon", 15, 9, 24, 24, 5242881, None, "py.ico", None, None) error.pushbutton("N",120,72,81,21,3,"No",None).event("EndDialog","ErrorNo") error.pushbutton("Y",240,72,81,21,3,"Yes",None).event("EndDialog","ErrorYes") error.pushbutton("A",0,72,81,21,3,"Abort",None).event("EndDialog","ErrorAbort") error.pushbutton("C",42,72,81,21,3,"Cancel",None).event("EndDialog","ErrorCancel") error.pushbutton("I",81,72,81,21,3,"Ignore",None).event("EndDialog","ErrorIgnore") error.pushbutton("O",159,72,81,21,3,"Ok",None).event("EndDialog","ErrorOk") error.pushbutton("R",198,72,81,21,3,"Retry",None).event("EndDialog","ErrorRetry") ##################################################################### # Global "Query Cancel" dialog cancel = Dialog(db, "CancelDlg", 50, 10, 260, 85, 3, title, "No", "No", "No") cancel.text("Text", 48, 15, 194, 30, 3, "Are you sure you want to cancel [ProductName] installation?") #cancel.control("Icon", "Icon", 15, 15, 24, 24, 5242881, None, # "py.ico", None, None) c=cancel.pushbutton("Yes", 72, 57, 56, 17, 3, "Yes", "No") c.event("EndDialog", "Exit") c=cancel.pushbutton("No", 132, 57, 56, 17, 3, "No", "Yes") c.event("EndDialog", "Return") ##################################################################### # Global "Wait for costing" dialog costing = Dialog(db, "WaitForCostingDlg", 50, 10, 260, 85, modal, title, "Return", "Return", "Return") costing.text("Text", 48, 15, 194, 30, 3, "Please wait while the installer finishes determining your disk space requirements.") c = costing.pushbutton("Return", 102, 57, 56, 17, 3, "Return", None) c.event("EndDialog", "Exit") ##################################################################### # Preparation dialog: no user input except cancellation prep = PyDialog(db, "PrepareDlg", x, y, w, h, modeless, title, "Cancel", "Cancel", "Cancel") prep.text("Description", 15, 70, 320, 40, 0x30003, "Please wait while the Installer prepares to guide you through the installation.") prep.title("Welcome to the [ProductName] Installer") c=prep.text("ActionText", 15, 110, 320, 20, 0x30003, "Pondering...") c.mapping("ActionText", "Text") c=prep.text("ActionData", 15, 135, 320, 30, 0x30003, None) c.mapping("ActionData", "Text") prep.back("Back", None, active=0) prep.next("Next", None, active=0) c=prep.cancel("Cancel", None) c.event("SpawnDialog", "CancelDlg") ##################################################################### # Feature (Python directory) selection seldlg = PyDialog(db, "SelectFeaturesDlg", x, y, w, h, modal, title, "Next", "Next", "Cancel") seldlg.title("Select Python Installations") seldlg.text("Hint", 15, 30, 300, 20, 3, "Select the Python locations where %s should be installed." % self.distribution.get_fullname()) seldlg.back("< Back", None, active=0) c = seldlg.next("Next >", "Cancel") order = 1 c.event("[TARGETDIR]", "[SourceDir]", ordering=order) for version in self.versions + [self.other_version]: order += 1 c.event("[TARGETDIR]", "[TARGETDIR%s]" % version, "FEATURE_SELECTED AND &Python%s=3" % version, ordering=order) c.event("SpawnWaitDialog", "WaitForCostingDlg", ordering=order + 1) c.event("EndDialog", "Return", ordering=order + 2) c = seldlg.cancel("Cancel", "Features") c.event("SpawnDialog", "CancelDlg") c = seldlg.control("Features", "SelectionTree", 15, 60, 300, 120, 3, "FEATURE", None, "PathEdit", None) c.event("[FEATURE_SELECTED]", "1") ver = self.other_version install_other_cond = "FEATURE_SELECTED AND &Python%s=3" % ver dont_install_other_cond = "FEATURE_SELECTED AND &Python%s<>3" % ver c = seldlg.text("Other", 15, 200, 300, 15, 3, "Provide an alternate Python location") c.condition("Enable", install_other_cond) c.condition("Show", install_other_cond) c.condition("Disable", dont_install_other_cond) c.condition("Hide", dont_install_other_cond) c = seldlg.control("PathEdit", "PathEdit", 15, 215, 300, 16, 1, "TARGETDIR" + ver, None, "Next", None) c.condition("Enable", install_other_cond) c.condition("Show", install_other_cond) c.condition("Disable", dont_install_other_cond) c.condition("Hide", dont_install_other_cond) ##################################################################### # Disk cost cost = PyDialog(db, "DiskCostDlg", x, y, w, h, modal, title, "OK", "OK", "OK", bitmap=False) cost.text("Title", 15, 6, 200, 15, 0x30003, "{\DlgFontBold8}Disk Space Requirements") cost.text("Description", 20, 20, 280, 20, 0x30003, "The disk space required for the installation of the selected features.") cost.text("Text", 20, 53, 330, 60, 3, "The highlighted volumes (if any) do not have enough disk space " "available for the currently selected features. You can either " "remove some files from the highlighted volumes, or choose to " "install less features onto local drive(s), or select different " "destination drive(s).") cost.control("VolumeList", "VolumeCostList", 20, 100, 330, 150, 393223, None, "{120}{70}{70}{70}{70}", None, None) cost.xbutton("OK", "Ok", None, 0.5).event("EndDialog", "Return") ##################################################################### # WhichUsers Dialog. Only available on NT, and for privileged users. # This must be run before FindRelatedProducts, because that will # take into account whether the previous installation was per-user # or per-machine. We currently don't support going back to this # dialog after "Next" was selected; to support this, we would need to # find how to reset the ALLUSERS property, and how to re-run # FindRelatedProducts. # On Windows9x, the ALLUSERS property is ignored on the command line # and in the Property table, but installer fails according to the documentation # if a dialog attempts to set ALLUSERS. whichusers = PyDialog(db, "WhichUsersDlg", x, y, w, h, modal, title, "AdminInstall", "Next", "Cancel") whichusers.title("Select whether to install [ProductName] for all users of this computer.") # A radio group with two options: allusers, justme g = whichusers.radiogroup("AdminInstall", 15, 60, 260, 50, 3, "WhichUsers", "", "Next") g.add("ALL", 0, 5, 150, 20, "Install for all users") g.add("JUSTME", 0, 25, 150, 20, "Install just for me") whichusers.back("Back", None, active=0) c = whichusers.next("Next >", "Cancel") c.event("[ALLUSERS]", "1", 'WhichUsers="ALL"', 1) c.event("EndDialog", "Return", ordering = 2) c = whichusers.cancel("Cancel", "AdminInstall") c.event("SpawnDialog", "CancelDlg") ##################################################################### # Installation Progress dialog (modeless) progress = PyDialog(db, "ProgressDlg", x, y, w, h, modeless, title, "Cancel", "Cancel", "Cancel", bitmap=False) progress.text("Title", 20, 15, 200, 15, 0x30003, "{\DlgFontBold8}[Progress1] [ProductName]") progress.text("Text", 35, 65, 300, 30, 3, "Please wait while the Installer [Progress2] [ProductName]. " "This may take several minutes.") progress.text("StatusLabel", 35, 100, 35, 20, 3, "Status:") c=progress.text("ActionText", 70, 100, w-70, 20, 3, "Pondering...") c.mapping("ActionText", "Text") #c=progress.text("ActionData", 35, 140, 300, 20, 3, None) #c.mapping("ActionData", "Text") c=progress.control("ProgressBar", "ProgressBar", 35, 120, 300, 10, 65537, None, "Progress done", None, None) c.mapping("SetProgress", "Progress") progress.back("< Back", "Next", active=False) progress.next("Next >", "Cancel", active=False) progress.cancel("Cancel", "Back").event("SpawnDialog", "CancelDlg") ################################################################### # Maintenance type: repair/uninstall maint = PyDialog(db, "MaintenanceTypeDlg", x, y, w, h, modal, title, "Next", "Next", "Cancel") maint.title("Welcome to the [ProductName] Setup Wizard") maint.text("BodyText", 15, 63, 330, 42, 3, "Select whether you want to repair or remove [ProductName].") g=maint.radiogroup("RepairRadioGroup", 15, 108, 330, 60, 3, "MaintenanceForm_Action", "", "Next") #g.add("Change", 0, 0, 200, 17, "&Change [ProductName]") g.add("Repair", 0, 18, 200, 17, "&Repair [ProductName]") g.add("Remove", 0, 36, 200, 17, "Re&move [ProductName]") maint.back("< Back", None, active=False) c=maint.next("Finish", "Cancel") # Change installation: Change progress dialog to "Change", then ask # for feature selection #c.event("[Progress1]", "Change", 'MaintenanceForm_Action="Change"', 1) #c.event("[Progress2]", "changes", 'MaintenanceForm_Action="Change"', 2) # Reinstall: Change progress dialog to "Repair", then invoke reinstall # Also set list of reinstalled features to "ALL" c.event("[REINSTALL]", "ALL", 'MaintenanceForm_Action="Repair"', 5) c.event("[Progress1]", "Repairing", 'MaintenanceForm_Action="Repair"', 6) c.event("[Progress2]", "repairs", 'MaintenanceForm_Action="Repair"', 7) c.event("Reinstall", "ALL", 'MaintenanceForm_Action="Repair"', 8) # Uninstall: Change progress to "Remove", then invoke uninstall # Also set list of removed features to "ALL" c.event("[REMOVE]", "ALL", 'MaintenanceForm_Action="Remove"', 11) c.event("[Progress1]", "Removing", 'MaintenanceForm_Action="Remove"', 12) c.event("[Progress2]", "removes", 'MaintenanceForm_Action="Remove"', 13) c.event("Remove", "ALL", 'MaintenanceForm_Action="Remove"', 14) # Close dialog when maintenance action scheduled c.event("EndDialog", "Return", 'MaintenanceForm_Action<>"Change"', 20) #c.event("NewDialog", "SelectFeaturesDlg", 'MaintenanceForm_Action="Change"', 21) maint.cancel("Cancel", "RepairRadioGroup").event("SpawnDialog", "CancelDlg") def get_installer_filename(self, fullname): # Factored out to allow overriding in subclasses if self.target_version: base_name = "%s.%s-py%s.msi" % (fullname, self.plat_name, self.target_version) else: base_name = "%s.%s.msi" % (fullname, self.plat_name) installer_name = os.path.join(self.dist_dir, base_name) return installer_name
bsd-2-clause
googleapis/googleapis-gen
google/cloud/billing/v1/billing-v1-py/google/cloud/billing_v1/types/__init__.py
1
1795
# -*- coding: utf-8 -*- # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # from .cloud_billing import ( BillingAccount, CreateBillingAccountRequest, GetBillingAccountRequest, GetProjectBillingInfoRequest, ListBillingAccountsRequest, ListBillingAccountsResponse, ListProjectBillingInfoRequest, ListProjectBillingInfoResponse, ProjectBillingInfo, UpdateBillingAccountRequest, UpdateProjectBillingInfoRequest, ) from .cloud_catalog import ( AggregationInfo, Category, ListServicesRequest, ListServicesResponse, ListSkusRequest, ListSkusResponse, PricingExpression, PricingInfo, Service, Sku, ) __all__ = ( 'BillingAccount', 'CreateBillingAccountRequest', 'GetBillingAccountRequest', 'GetProjectBillingInfoRequest', 'ListBillingAccountsRequest', 'ListBillingAccountsResponse', 'ListProjectBillingInfoRequest', 'ListProjectBillingInfoResponse', 'ProjectBillingInfo', 'UpdateBillingAccountRequest', 'UpdateProjectBillingInfoRequest', 'AggregationInfo', 'Category', 'ListServicesRequest', 'ListServicesResponse', 'ListSkusRequest', 'ListSkusResponse', 'PricingExpression', 'PricingInfo', 'Service', 'Sku', )
apache-2.0
ononeor12/python-social-auth
social/backends/behance.py
70
1581
""" Behance OAuth2 backend, docs at: http://psa.matiasaguirre.net/docs/backends/behance.html """ from social.backends.oauth import BaseOAuth2 class BehanceOAuth2(BaseOAuth2): """Behance OAuth authentication backend""" name = 'behance' AUTHORIZATION_URL = 'https://www.behance.net/v2/oauth/authenticate' ACCESS_TOKEN_URL = 'https://www.behance.net/v2/oauth/token' ACCESS_TOKEN_METHOD = 'POST' SCOPE_SEPARATOR = '|' EXTRA_DATA = [('username', 'username')] REDIRECT_STATE = False def get_user_id(self, details, response): return response['user']['id'] def get_user_details(self, response): """Return user details from Behance account""" user = response['user'] fullname, first_name, last_name = self.get_user_names( user['display_name'], user['first_name'], user['last_name'] ) return {'username': user['username'], 'fullname': fullname, 'first_name': first_name, 'last_name': last_name, 'email': ''} def extra_data(self, user, uid, response, details=None, *args, **kwargs): # Pull up the embedded user attributes so they can be found as extra # data. See the example token response for possible attributes: # http://www.behance.net/dev/authentication#step-by-step data = response.copy() data.update(response['user']) return super(BehanceOAuth2, self).extra_data(user, uid, data, details, *args, **kwargs)
bsd-3-clause
hlzz/dotfiles
graphics/VTK-7.0.0/Rendering/Volume/Testing/Python/volRCClipPlanes.py
2
3843
#!/usr/bin/env python import vtk from vtk.test import Testing from vtk.util.misc import vtkGetDataRoot VTK_DATA_ROOT = vtkGetDataRoot() # Simple volume rendering example. reader = vtk.vtkSLCReader() reader.SetFileName("" + str(VTK_DATA_ROOT) + "/Data/sphere.slc") reader.Update() # Create transfer functions for opacity and color opacityTransferFunction = vtk.vtkPiecewiseFunction() opacityTransferFunction.AddPoint(20,0.0) opacityTransferFunction.AddPoint(255,1.0) colorTransferFunction = vtk.vtkColorTransferFunction() # Improve coverage colorTransferFunction.SetColorSpaceToRGB() colorTransferFunction.AddRGBPoint(100,1,1,1) colorTransferFunction.AddRGBPoint(0,0,0,0) colorTransferFunction.AddRGBPoint(200,1,0,1) colorTransferFunction.AddRGBPoint(100,0,0,0) colorTransferFunction.RemovePoint(100) colorTransferFunction.RemovePoint(0) colorTransferFunction.RemovePoint(200) colorTransferFunction.AddHSVPoint(100,1,1,1) colorTransferFunction.AddHSVPoint(0,0,0,0) colorTransferFunction.AddHSVPoint(200,1,0,1) colorTransferFunction.AddHSVPoint(100,0,0,0) colorTransferFunction.RemovePoint(0) colorTransferFunction.RemovePoint(200) colorTransferFunction.RemovePoint(100) colorTransferFunction.AddRGBSegment(0,1,1,1,100,0,0,0) colorTransferFunction.AddRGBSegment(50,1,1,1,150,0,0,0) colorTransferFunction.AddRGBSegment(60,1,1,1,90,0,0,0) colorTransferFunction.AddHSVSegment(90,1,1,1,105,0,0,0) colorTransferFunction.AddHSVSegment(40,1,1,1,155,0,0,0) colorTransferFunction.AddHSVSegment(30,1,1,1,95,0,0,0) colorTransferFunction.RemoveAllPoints() colorTransferFunction.AddHSVPoint(0.0,0.01,1.0,1.0) colorTransferFunction.AddHSVPoint(127.5,0.50,1.0,1.0) colorTransferFunction.AddHSVPoint(255.0,0.99,1.0,1.0) colorTransferFunction.SetColorSpaceToHSV() # Create properties, mappers, volume actors, and ray cast function volumeProperty = vtk.vtkVolumeProperty() volumeProperty.SetColor(colorTransferFunction) volumeProperty.SetScalarOpacity(opacityTransferFunction) volumeProperty.SetInterpolationTypeToLinear() compositeFunction = vtk.vtkVolumeRayCastCompositeFunction() volumeMapper = vtk.vtkVolumeRayCastMapper() volumeMapper.SetInputConnection(reader.GetOutputPort()) volumeMapper.SetVolumeRayCastFunction(compositeFunction) volume = vtk.vtkVolume() volume.SetMapper(volumeMapper) volume.SetProperty(volumeProperty) # Create geometric sphere sphereSource = vtk.vtkSphereSource() sphereSource.SetCenter(25,25,25) sphereSource.SetRadius(30) sphereSource.SetThetaResolution(15) sphereSource.SetPhiResolution(15) sphereMapper = vtk.vtkPolyDataMapper() sphereMapper.SetInputConnection(sphereSource.GetOutputPort()) sphereActor = vtk.vtkActor() sphereActor.SetMapper(sphereMapper) # Set up the planes plane1 = vtk.vtkPlane() plane1.SetOrigin(25,25,20) plane1.SetNormal(0,0,1) plane2 = vtk.vtkPlane() plane2.SetOrigin(25,25,30) plane2.SetNormal(0,0,-1) plane3 = vtk.vtkPlane() plane3.SetOrigin(20,25,25) plane3.SetNormal(1,0,0) plane4 = vtk.vtkPlane() plane4.SetOrigin(30,25,25) plane4.SetNormal(-1,0,0) sphereMapper.AddClippingPlane(plane1) sphereMapper.AddClippingPlane(plane2) volumeMapper.AddClippingPlane(plane3) volumeMapper.AddClippingPlane(plane4) # Okay now the graphics stuff ren1 = vtk.vtkRenderer() renWin = vtk.vtkRenderWindow() renWin.AddRenderer(ren1) renWin.SetSize(256,256) iren = vtk.vtkRenderWindowInteractor() iren.SetRenderWindow(renWin) ren1.GetCullers().InitTraversal() culler = ren1.GetCullers().GetNextItem() culler.SetSortingStyleToBackToFront() ren1.AddViewProp(sphereActor) ren1.AddViewProp(volume) ren1.SetBackground(0.1,0.2,0.4) renWin.Render() ren1.GetActiveCamera().Azimuth(45) ren1.GetActiveCamera().Elevation(15) ren1.GetActiveCamera().Roll(45) ren1.GetActiveCamera().Zoom(2.0) iren.Initialize() # --- end of script --
bsd-3-clause
minhphung171093/GreenERP_V7
openerp/addons/mail/tests/test_mail_features.py
22
49719
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Business Applications # Copyright (c) 2012-TODAY 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/>. # ############################################################################## from openerp.addons.mail.tests.test_mail_base import TestMailBase from openerp.tools.mail import html_sanitize class test_mail(TestMailBase): def test_000_alias_setup(self): """ Test basic mail.alias setup works, before trying to use them for routing """ cr, uid = self.cr, self.uid self.user_valentin_id = self.res_users.create(cr, uid, {'name': 'Valentin Cognito', 'email': 'valentin.cognito@gmail.com', 'login': 'valentin.cognito'}) self.user_valentin = self.res_users.browse(cr, uid, self.user_valentin_id) self.assertEquals(self.user_valentin.alias_name, self.user_valentin.login, "Login should be used as alias") self.user_pagan_id = self.res_users.create(cr, uid, {'name': 'Pagan Le Marchant', 'email': 'plmarchant@gmail.com', 'login': 'plmarchant@gmail.com'}) self.user_pagan = self.res_users.browse(cr, uid, self.user_pagan_id) self.assertEquals(self.user_pagan.alias_name, 'plmarchant', "If login is an email, the alias should keep only the local part") self.user_barty_id = self.res_users.create(cr, uid, {'name': 'Bartholomew Ironside', 'email': 'barty@gmail.com', 'login': 'b4r+_#_R3wl$$'}) self.user_barty = self.res_users.browse(cr, uid, self.user_barty_id) self.assertEquals(self.user_barty.alias_name, 'b4r+_-_r3wl-', 'Disallowed chars should be replaced by hyphens') def test_00_followers_function_field(self): """ Tests designed for the many2many function field 'follower_ids'. We will test to perform writes using the many2many commands 0, 3, 4, 5 and 6. """ cr, uid, user_admin, partner_bert_id, group_pigs = self.cr, self.uid, self.user_admin, self.partner_bert_id, self.group_pigs # Data: create 'disturbing' values in mail.followers: same res_id, other res_model; same res_model, other res_id group_dummy_id = self.mail_group.create(cr, uid, {'name': 'Dummy group'}, {'mail_create_nolog': True}) self.mail_followers.create(cr, uid, {'res_model': 'mail.thread', 'res_id': self.group_pigs_id, 'partner_id': partner_bert_id}) self.mail_followers.create(cr, uid, {'res_model': 'mail.group', 'res_id': group_dummy_id, 'partner_id': partner_bert_id}) # Pigs just created: should be only Admin as follower follower_ids = set([follower.id for follower in group_pigs.message_follower_ids]) self.assertEqual(follower_ids, set([user_admin.partner_id.id]), 'Admin should be the only Pigs fan') # Subscribe Bert through a '4' command group_pigs.write({'message_follower_ids': [(4, partner_bert_id)]}) group_pigs.refresh() follower_ids = set([follower.id for follower in group_pigs.message_follower_ids]) self.assertEqual(follower_ids, set([partner_bert_id, user_admin.partner_id.id]), 'Bert and Admin should be the only Pigs fans') # Unsubscribe Bert through a '3' command group_pigs.write({'message_follower_ids': [(3, partner_bert_id)]}) group_pigs.refresh() follower_ids = set([follower.id for follower in group_pigs.message_follower_ids]) self.assertEqual(follower_ids, set([user_admin.partner_id.id]), 'Admin should be the only Pigs fan') # Set followers through a '6' command group_pigs.write({'message_follower_ids': [(6, 0, [partner_bert_id])]}) group_pigs.refresh() follower_ids = set([follower.id for follower in group_pigs.message_follower_ids]) self.assertEqual(follower_ids, set([partner_bert_id]), 'Bert should be the only Pigs fan') # Add a follower created on the fly through a '0' command group_pigs.write({'message_follower_ids': [(0, 0, {'name': 'Patrick Fiori'})]}) partner_patrick_id = self.res_partner.search(cr, uid, [('name', '=', 'Patrick Fiori')])[0] group_pigs.refresh() follower_ids = set([follower.id for follower in group_pigs.message_follower_ids]) self.assertEqual(follower_ids, set([partner_bert_id, partner_patrick_id]), 'Bert and Patrick should be the only Pigs fans') # Finally, unlink through a '5' command group_pigs.write({'message_follower_ids': [(5, 0)]}) group_pigs.refresh() follower_ids = set([follower.id for follower in group_pigs.message_follower_ids]) self.assertFalse(follower_ids, 'Pigs group should not have fans anymore') # Test dummy data has not been altered fol_obj_ids = self.mail_followers.search(cr, uid, [('res_model', '=', 'mail.thread'), ('res_id', '=', self.group_pigs_id)]) follower_ids = set([follower.partner_id.id for follower in self.mail_followers.browse(cr, uid, fol_obj_ids)]) self.assertEqual(follower_ids, set([partner_bert_id]), 'Bert should be the follower of dummy mail.thread data') fol_obj_ids = self.mail_followers.search(cr, uid, [('res_model', '=', 'mail.group'), ('res_id', '=', group_dummy_id)]) follower_ids = set([follower.partner_id.id for follower in self.mail_followers.browse(cr, uid, fol_obj_ids)]) self.assertEqual(follower_ids, set([partner_bert_id, user_admin.partner_id.id]), 'Bert and Admin should be the followers of dummy mail.group data') def test_05_message_followers_and_subtypes(self): """ Tests designed for the subscriber API as well as message subtypes """ cr, uid, user_admin, user_raoul, group_pigs = self.cr, self.uid, self.user_admin, self.user_raoul, self.group_pigs # Data: message subtypes self.mail_message_subtype.create(cr, uid, {'name': 'mt_mg_def', 'default': True, 'res_model': 'mail.group'}) self.mail_message_subtype.create(cr, uid, {'name': 'mt_other_def', 'default': True, 'res_model': 'crm.lead'}) self.mail_message_subtype.create(cr, uid, {'name': 'mt_all_def', 'default': True, 'res_model': False}) mt_mg_nodef = self.mail_message_subtype.create(cr, uid, {'name': 'mt_mg_nodef', 'default': False, 'res_model': 'mail.group'}) mt_all_nodef = self.mail_message_subtype.create(cr, uid, {'name': 'mt_all_nodef', 'default': False, 'res_model': False}) default_group_subtypes = self.mail_message_subtype.search(cr, uid, [('default', '=', True), '|', ('res_model', '=', 'mail.group'), ('res_model', '=', False)]) # ---------------------------------------- # CASE1: test subscriptions with subtypes # ---------------------------------------- # Do: subscribe Raoul, should have default subtypes group_pigs.message_subscribe_users([user_raoul.id]) group_pigs.refresh() # Test: 2 followers (Admin and Raoul) follower_ids = [follower.id for follower in group_pigs.message_follower_ids] self.assertEqual(set(follower_ids), set([user_raoul.partner_id.id, user_admin.partner_id.id]), 'message_subscribe: Admin and Raoul should be the only 2 Pigs fans') # Raoul follows default subtypes fol_ids = self.mail_followers.search(cr, uid, [ ('res_model', '=', 'mail.group'), ('res_id', '=', self.group_pigs_id), ('partner_id', '=', user_raoul.partner_id.id) ]) fol_obj = self.mail_followers.browse(cr, uid, fol_ids)[0] fol_subtype_ids = set([subtype.id for subtype in fol_obj.subtype_ids]) self.assertEqual(set(fol_subtype_ids), set(default_group_subtypes), 'message_subscribe: Raoul subscription subtypes are incorrect, should be all default ones') # Do: subscribe Raoul with specified new subtypes group_pigs.message_subscribe_users([user_raoul.id], subtype_ids=[mt_mg_nodef]) # Test: 2 followers (Admin and Raoul) follower_ids = [follower.id for follower in group_pigs.message_follower_ids] self.assertEqual(set(follower_ids), set([user_raoul.partner_id.id, user_admin.partner_id.id]), 'message_subscribe: Admin and Raoul should be the only 2 Pigs fans') # Test: 2 lines in mail.followers (no duplicate for Raoul) fol_ids = self.mail_followers.search(cr, uid, [ ('res_model', '=', 'mail.group'), ('res_id', '=', self.group_pigs_id), ]) self.assertEqual(len(fol_ids), 2, 'message_subscribe: subscribing an already-existing follower should not create new entries in mail.followers') # Test: Raoul follows only specified subtypes fol_ids = self.mail_followers.search(cr, uid, [ ('res_model', '=', 'mail.group'), ('res_id', '=', self.group_pigs_id), ('partner_id', '=', user_raoul.partner_id.id) ]) fol_obj = self.mail_followers.browse(cr, uid, fol_ids)[0] fol_subtype_ids = set([subtype.id for subtype in fol_obj.subtype_ids]) self.assertEqual(set(fol_subtype_ids), set([mt_mg_nodef]), 'message_subscribe: Raoul subscription subtypes are incorrect, should be only specified') # Do: Subscribe Raoul without specified subtypes: should not erase existing subscription subtypes group_pigs.message_subscribe_users([user_raoul.id, user_raoul.id]) group_pigs.message_subscribe_users([user_raoul.id]) group_pigs.refresh() # Test: 2 followers (Admin and Raoul) follower_ids = [follower.id for follower in group_pigs.message_follower_ids] self.assertEqual(set(follower_ids), set([user_raoul.partner_id.id, user_admin.partner_id.id]), 'message_subscribe: Admin and Raoul should be the only 2 Pigs fans') # Test: Raoul follows default subtypes fol_ids = self.mail_followers.search(cr, uid, [ ('res_model', '=', 'mail.group'), ('res_id', '=', self.group_pigs_id), ('partner_id', '=', user_raoul.partner_id.id) ]) fol_obj = self.mail_followers.browse(cr, uid, fol_ids)[0] fol_subtype_ids = set([subtype.id for subtype in fol_obj.subtype_ids]) self.assertEqual(set(fol_subtype_ids), set([mt_mg_nodef]), 'message_subscribe: Raoul subscription subtypes are incorrect, should be only specified') # Do: Unsubscribe Raoul twice through message_unsubscribe_users group_pigs.message_unsubscribe_users([user_raoul.id, user_raoul.id]) group_pigs.refresh() # Test: 1 follower (Admin) follower_ids = [follower.id for follower in group_pigs.message_follower_ids] self.assertEqual(follower_ids, [user_admin.partner_id.id], 'Admin must be the only Pigs fan') # Test: 1 lines in mail.followers (no duplicate for Raoul) fol_ids = self.mail_followers.search(cr, uid, [ ('res_model', '=', 'mail.group'), ('res_id', '=', self.group_pigs_id) ]) self.assertEqual(len(fol_ids), 1, 'message_subscribe: group should have only 1 entry in mail.follower for 1 follower') # Do: subscribe Admin with subtype_ids group_pigs.message_subscribe_users([uid], [mt_mg_nodef, mt_all_nodef]) fol_ids = self.mail_followers.search(cr, uid, [('res_model', '=', 'mail.group'), ('res_id', '=', self.group_pigs_id), ('partner_id', '=', user_admin.partner_id.id)]) fol_obj = self.mail_followers.browse(cr, uid, fol_ids)[0] fol_subtype_ids = set([subtype.id for subtype in fol_obj.subtype_ids]) self.assertEqual(set(fol_subtype_ids), set([mt_mg_nodef, mt_all_nodef]), 'subscription subtypes are incorrect') # ---------------------------------------- # CASE2: test mail_thread fields # ---------------------------------------- subtype_data = group_pigs._get_subscription_data(None, None)[group_pigs.id]['message_subtype_data'] self.assertEqual(set(subtype_data.keys()), set(['Discussions', 'mt_mg_def', 'mt_all_def', 'mt_mg_nodef', 'mt_all_nodef']), 'mail.group available subtypes incorrect') self.assertFalse(subtype_data['Discussions']['followed'], 'Admin should not follow Discussions in pigs') self.assertTrue(subtype_data['mt_mg_nodef']['followed'], 'Admin should follow mt_mg_nodef in pigs') self.assertTrue(subtype_data['mt_all_nodef']['followed'], 'Admin should follow mt_all_nodef in pigs') def test_10_message_quote_context(self): """ Tests designed for message_post. """ cr, uid, user_admin, group_pigs = self.cr, self.uid, self.user_admin, self.group_pigs msg1_id = self.mail_message.create(cr, uid, {'body': 'Thread header about Zap Brannigan', 'subject': 'My subject'}) msg2_id = self.mail_message.create(cr, uid, {'body': 'First answer, should not be displayed', 'subject': 'Re: My subject', 'parent_id': msg1_id}) msg3_id = self.mail_message.create(cr, uid, {'body': 'Second answer', 'subject': 'Re: My subject', 'parent_id': msg1_id}) msg4_id = self.mail_message.create(cr, uid, {'body': 'Third answer', 'subject': 'Re: My subject', 'parent_id': msg1_id}) msg_new_id = self.mail_message.create(cr, uid, {'body': 'My answer I am propagating', 'subject': 'Re: My subject', 'parent_id': msg1_id}) result = self.mail_message.message_quote_context(cr, uid, msg_new_id, limit=3) self.assertIn('Thread header about Zap Brannigan', result, 'Thread header content should be in quote.') self.assertIn('Second answer', result, 'Answer should be in quote.') self.assertIn('Third answer', result, 'Answer should be in quote.') self.assertIn('expandable', result, 'Expandable should be present.') self.assertNotIn('First answer, should not be displayed', result, 'Old answer should not be in quote.') self.assertNotIn('My answer I am propagating', result, 'Thread header content should be in quote.') def test_20_message_post(self): """ Tests designed for message_post. """ cr, uid, user_raoul, group_pigs = self.cr, self.uid, self.user_raoul, self.group_pigs # -------------------------------------------------- # Data creation # -------------------------------------------------- # 0 - Update existing users-partners self.res_users.write(cr, uid, [uid], {'email': 'a@a', 'notification_email_send': 'comment'}) self.res_users.write(cr, uid, [self.user_raoul_id], {'email': 'r@r'}) # 1 - Bert Tartopoils, with email, should receive emails for comments and emails p_b_id = self.res_partner.create(cr, uid, {'name': 'Bert Tartopoils', 'email': 'b@b'}) # 2 - Carine Poilvache, with email, should receive emails for emails p_c_id = self.res_partner.create(cr, uid, {'name': 'Carine Poilvache', 'email': 'c@c', 'notification_email_send': 'email'}) # 3 - Dédé Grosbedon, without email, to test email verification; should receive emails for every message p_d_id = self.res_partner.create(cr, uid, {'name': 'Dédé Grosbedon', 'email': 'd@d', 'notification_email_send': 'all'}) # 4 - Attachments attach1_id = self.ir_attachment.create(cr, user_raoul.id, { 'name': 'Attach1', 'datas_fname': 'Attach1', 'datas': 'bWlncmF0aW9uIHRlc3Q=', 'res_model': 'mail.compose.message', 'res_id': 0}) attach2_id = self.ir_attachment.create(cr, user_raoul.id, { 'name': 'Attach2', 'datas_fname': 'Attach2', 'datas': 'bWlncmF0aW9uIHRlc3Q=', 'res_model': 'mail.compose.message', 'res_id': 0}) attach3_id = self.ir_attachment.create(cr, user_raoul.id, { 'name': 'Attach3', 'datas_fname': 'Attach3', 'datas': 'bWlncmF0aW9uIHRlc3Q=', 'res_model': 'mail.compose.message', 'res_id': 0}) # 5 - Mail data _subject = 'Pigs' _mail_subject = 'Re: %s' % (group_pigs.name) _body1 = '<p>Pigs rules</p>' _body2 = '<html>Pigs rocks</html>' _attachments = [ ('List1', 'My first attachment'), ('List2', 'My second attachment') ] # -------------------------------------------------- # CASE1: post comment + partners + attachments # -------------------------------------------------- # Data: set alias_domain to see emails with alias self.registry('ir.config_parameter').set_param(self.cr, self.uid, 'mail.catchall.domain', 'schlouby.fr') # Data: change Pigs name to test reply_to self.mail_group.write(cr, uid, [self.group_pigs_id], {'name': '"Pigs" !ù $%-'}) # Do: subscribe Raoul new_follower_ids = [self.partner_raoul_id] group_pigs.message_subscribe(new_follower_ids) # Test: group followers = Raoul + uid group_fids = [follower.id for follower in group_pigs.message_follower_ids] test_fids = new_follower_ids + [self.partner_admin_id] self.assertEqual(set(test_fids), set(group_fids), 'message_subscribe: incorrect followers after subscribe') # Do: Raoul message_post on Pigs self._init_mock_build_email() msg1_id = self.mail_group.message_post(cr, user_raoul.id, self.group_pigs_id, body=_body1, subject=_subject, partner_ids=[p_b_id, p_c_id], attachment_ids=[attach1_id, attach2_id], attachments=_attachments, type='comment', subtype='mt_comment') msg = self.mail_message.browse(cr, uid, msg1_id) msg_message_id = msg.message_id msg_pids = [partner.id for partner in msg.notified_partner_ids] msg_aids = [attach.id for attach in msg.attachment_ids] sent_emails = self._build_email_kwargs_list # Test: mail_message: subject and body not modified self.assertEqual(_subject, msg.subject, 'message_post: mail.message subject incorrect') self.assertEqual(_body1, msg.body, 'message_post: mail.message body incorrect') # Test: mail_message: notified_partner_ids = group followers + partner_ids - author test_pids = set([self.partner_admin_id, p_b_id, p_c_id]) self.assertEqual(test_pids, set(msg_pids), 'message_post: mail.message notified partners incorrect') # Test: mail_message: attachments (4, attachment_ids + attachments) test_aids = set([attach1_id, attach2_id]) msg_attach_names = set([attach.name for attach in msg.attachment_ids]) test_attach_names = set(['Attach1', 'Attach2', 'List1', 'List2']) self.assertEqual(len(msg_aids), 4, 'message_post: mail.message wrong number of attachments') self.assertEqual(msg_attach_names, test_attach_names, 'message_post: mail.message attachments incorrectly added') self.assertTrue(test_aids.issubset(set(msg_aids)), 'message_post: mail.message attachments duplicated') for attach in msg.attachment_ids: self.assertEqual(attach.res_model, 'mail.group', 'message_post: mail.message attachments were not linked to the document') self.assertEqual(attach.res_id, group_pigs.id, 'message_post: mail.message attachments were not linked to the document') if 'List' in attach.name: self.assertIn((attach.name, attach.datas.decode('base64')), _attachments, 'message_post: mail.message attachment name / data incorrect') dl_attach = self.mail_message.download_attachment(cr, user_raoul.id, id_message=msg.id, attachment_id=attach.id) self.assertIn((dl_attach['filename'], dl_attach['base64'].decode('base64')), _attachments, 'message_post: mail.message download_attachment is incorrect') # Test: followers: same as before (author was already subscribed) group_pigs.refresh() group_fids = [follower.id for follower in group_pigs.message_follower_ids] test_fids = new_follower_ids + [self.partner_admin_id] self.assertEqual(set(test_fids), set(group_fids), 'message_post: wrong followers after posting') # Test: mail_mail: notifications have been deleted self.assertFalse(self.mail_mail.search(cr, uid, [('mail_message_id', '=', msg1_id)]), 'message_post: mail.mail notifications should have been auto-deleted!') # Test: notifications emails: to a and b, c is email only, r is author # test_emailto = ['Administrator <a@a>', 'Bert Tartopoils <b@b>'] test_emailto = [u'"Followers of \\"Pigs\\" !\xf9 $%-" <a@a>', u'"Followers of \\"Pigs\\" !\xf9 $%-" <b@b>'] self.assertEqual(len(sent_emails), 2, 'message_post: notification emails wrong number of send emails') self.assertEqual(set([m['email_to'][0] for m in sent_emails]), set(test_emailto), 'message_post: notification emails wrong recipients (email_to)') for sent_email in sent_emails: self.assertEqual(sent_email['email_from'], 'Raoul Grosbedon <raoul@schlouby.fr>', 'message_post: notification email wrong email_from: should use alias of sender') self.assertEqual(len(sent_email['email_to']), 1, 'message_post: notification email sent to more than one email address instead of a precise partner') self.assertIn(sent_email['email_to'][0], test_emailto, 'message_post: notification email email_to incorrect') self.assertEqual(sent_email['reply_to'], u'"Followers of \\"Pigs\\" !\xf9 $%-" <group+pigs@schlouby.fr>', 'message_post: notification email reply_to incorrect') self.assertEqual(_subject, sent_email['subject'], 'message_post: notification email subject incorrect') self.assertIn(_body1, sent_email['body'], 'message_post: notification email body incorrect') self.assertIn(user_raoul.signature, sent_email['body'], 'message_post: notification email body should contain the sender signature') self.assertIn('Pigs rules', sent_email['body_alternative'], 'message_post: notification email body alternative should contain the body') self.assertNotIn('<p>', sent_email['body_alternative'], 'message_post: notification email body alternative still contains html') self.assertIn(user_raoul.signature, sent_email['body_alternative'], 'message_post: notification email body alternative should contain the sender signature') self.assertFalse(sent_email['references'], 'message_post: references should be False when sending a message that is not a reply') # Test: notification linked to this message = group followers = notified_partner_ids notif_ids = self.mail_notification.search(cr, uid, [('message_id', '=', msg1_id)]) notif_pids = set([notif.partner_id.id for notif in self.mail_notification.browse(cr, uid, notif_ids)]) self.assertEqual(notif_pids, test_pids, 'message_post: mail.message created mail.notification incorrect') # Data: Pigs name back to normal self.mail_group.write(cr, uid, [self.group_pigs_id], {'name': 'Pigs'}) # -------------------------------------------------- # CASE2: reply + parent_id + parent notification # -------------------------------------------------- # Data: remove alias_domain to see emails with alias param_ids = self.registry('ir.config_parameter').search(cr, uid, [('key', '=', 'mail.catchall.domain')]) self.registry('ir.config_parameter').unlink(cr, uid, param_ids) # Do: Raoul message_post on Pigs self._init_mock_build_email() msg2_id = self.mail_group.message_post(cr, user_raoul.id, self.group_pigs_id, body=_body2, type='email', subtype='mt_comment', partner_ids=[p_d_id], parent_id=msg1_id, attachment_ids=[attach3_id], context={'mail_post_autofollow': True}) msg = self.mail_message.browse(cr, uid, msg2_id) msg_pids = [partner.id for partner in msg.notified_partner_ids] msg_aids = [attach.id for attach in msg.attachment_ids] sent_emails = self._build_email_kwargs_list # Test: mail_message: subject is False, body, parent_id is msg_id self.assertEqual(msg.subject, False, 'message_post: mail.message subject incorrect') self.assertEqual(msg.body, html_sanitize(_body2), 'message_post: mail.message body incorrect') self.assertEqual(msg.parent_id.id, msg1_id, 'message_post: mail.message parent_id incorrect') # Test: mail_message: notified_partner_ids = group followers test_pids = [self.partner_admin_id, p_d_id] self.assertEqual(set(test_pids), set(msg_pids), 'message_post: mail.message partners incorrect') # Test: mail_message: notifications linked to this message = group followers = notified_partner_ids notif_ids = self.mail_notification.search(cr, uid, [('message_id', '=', msg2_id)]) notif_pids = [notif.partner_id.id for notif in self.mail_notification.browse(cr, uid, notif_ids)] self.assertEqual(set(test_pids), set(notif_pids), 'message_post: mail.message notification partners incorrect') # Test: mail_mail: notifications deleted self.assertFalse(self.mail_mail.search(cr, uid, [('mail_message_id', '=', msg2_id)]), 'mail.mail notifications should have been auto-deleted!') # Test: emails send by server (to a, b, c, d) # test_emailto = [u'Administrator <a@a>', u'Bert Tartopoils <b@b>', u'Carine Poilvache <c@c>', u'D\xe9d\xe9 Grosbedon <d@d>'] test_emailto = [u'Followers of Pigs <a@a>', u'Followers of Pigs <b@b>', u'Followers of Pigs <c@c>', u'Followers of Pigs <d@d>'] # self.assertEqual(len(sent_emails), 3, 'sent_email number of sent emails incorrect') for sent_email in sent_emails: self.assertEqual(sent_email['email_from'], 'Raoul Grosbedon <r@r>', 'message_post: notification email wrong email_from: should use email of sender when no alias domain set') self.assertEqual(len(sent_email['email_to']), 1, 'message_post: notification email sent to more than one email address instead of a precise partner') self.assertIn(sent_email['email_to'][0], test_emailto, 'message_post: notification email email_to incorrect') self.assertEqual(sent_email['reply_to'], 'Followers of Pigs <r@r>', 'message_post: notification email reply_to incorrect: should name Followers of Pigs, and have raoul email') self.assertEqual(_mail_subject, sent_email['subject'], 'message_post: notification email subject incorrect') self.assertIn(html_sanitize(_body2), sent_email['body'], 'message_post: notification email does not contain the body') self.assertIn(user_raoul.signature, sent_email['body'], 'message_post: notification email body should contain the sender signature') self.assertIn('Pigs rocks', sent_email['body_alternative'], 'message_post: notification email body alternative should contain the body') self.assertNotIn('<p>', sent_email['body_alternative'], 'message_post: notification email body alternative still contains html') self.assertIn(user_raoul.signature, sent_email['body_alternative'], 'message_post: notification email body alternative should contain the sender signature') self.assertIn(msg_message_id, sent_email['references'], 'message_post: notification email references lacks parent message message_id') # Test: attachments + download for attach in msg.attachment_ids: self.assertEqual(attach.res_model, 'mail.group', 'message_post: mail.message attachment res_model incorrect') self.assertEqual(attach.res_id, self.group_pigs_id, 'message_post: mail.message attachment res_id incorrect') # Test: Dédé has been notified -> should also have been notified of the parent message msg = self.mail_message.browse(cr, uid, msg1_id) msg_pids = set([partner.id for partner in msg.notified_partner_ids]) test_pids = set([self.partner_admin_id, p_b_id, p_c_id, p_d_id]) self.assertEqual(test_pids, msg_pids, 'message_post: mail.message parent notification not created') # Do: reply to last message msg3_id = self.mail_group.message_post(cr, user_raoul.id, self.group_pigs_id, body='Test', parent_id=msg2_id) msg = self.mail_message.browse(cr, uid, msg3_id) # Test: check that its parent will be the first message self.assertEqual(msg.parent_id.id, msg1_id, 'message_post did not flatten the thread structure') def test_25_message_compose_wizard(self): """ Tests designed for the mail.compose.message wizard. """ cr, uid, user_raoul, group_pigs = self.cr, self.uid, self.user_raoul, self.group_pigs mail_compose = self.registry('mail.compose.message') # -------------------------------------------------- # Data creation # -------------------------------------------------- # 0 - Update existing users-partners self.res_users.write(cr, uid, [uid], {'email': 'a@a'}) self.res_users.write(cr, uid, [self.user_raoul_id], {'email': 'r@r'}) # 1 - Bert Tartopoils, with email, should receive emails for comments and emails p_b_id = self.res_partner.create(cr, uid, {'name': 'Bert Tartopoils', 'email': 'b@b'}) # 2 - Carine Poilvache, with email, should receive emails for emails p_c_id = self.res_partner.create(cr, uid, {'name': 'Carine Poilvache', 'email': 'c@c', 'notification_email_send': 'email'}) # 3 - Dédé Grosbedon, without email, to test email verification; should receive emails for every message p_d_id = self.res_partner.create(cr, uid, {'name': 'Dédé Grosbedon', 'email': 'd@d', 'notification_email_send': 'all'}) # 4 - Create a Bird mail.group, that will be used to test mass mailing group_bird_id = self.mail_group.create(cr, uid, { 'name': 'Bird', 'description': 'Bird resistance', }, context={'mail_create_nolog': True}) group_bird = self.mail_group.browse(cr, uid, group_bird_id) # 5 - Mail data _subject = 'Pigs' _body = 'Pigs <b>rule</b>' _reply_subject = 'Re: %s' % _subject _attachments = [ {'name': 'First', 'datas_fname': 'first.txt', 'datas': 'My first attachment'.encode('base64')}, {'name': 'Second', 'datas_fname': 'second.txt', 'datas': 'My second attachment'.encode('base64')} ] _attachments_test = [('first.txt', 'My first attachment'), ('second.txt', 'My second attachment')] # 6 - Subscribe Bert to Pigs group_pigs.message_subscribe([p_b_id]) # -------------------------------------------------- # CASE1: wizard + partners + context keys # -------------------------------------------------- # Do: Raoul wizard-composes on Pigs with auto-follow for partners, not for author compose_id = mail_compose.create(cr, user_raoul.id, { 'subject': _subject, 'body': _body, 'partner_ids': [(4, p_c_id), (4, p_d_id)], }, context={ 'default_composition_mode': 'comment', 'default_model': 'mail.group', 'default_res_id': self.group_pigs_id, }) compose = mail_compose.browse(cr, uid, compose_id) # Test: mail.compose.message: composition_mode, model, res_id self.assertEqual(compose.composition_mode, 'comment', 'compose wizard: mail.compose.message incorrect composition_mode') self.assertEqual(compose.model, 'mail.group', 'compose wizard: mail.compose.message incorrect model') self.assertEqual(compose.res_id, self.group_pigs_id, 'compose wizard: mail.compose.message incorrect res_id') # Do: Post the comment mail_compose.send_mail(cr, user_raoul.id, [compose_id], {'mail_post_autofollow': True, 'mail_create_nosubscribe': True}) group_pigs.refresh() message = group_pigs.message_ids[0] # Test: mail.group: followers (c and d added by auto follow key; raoul not added by nosubscribe key) pigs_pids = [p.id for p in group_pigs.message_follower_ids] test_pids = [self.partner_admin_id, p_b_id, p_c_id, p_d_id] self.assertEqual(set(pigs_pids), set(test_pids), 'compose wizard: mail_post_autofollow and mail_create_nosubscribe context keys not correctly taken into account') # Test: mail.message: subject, body inside p self.assertEqual(message.subject, _subject, 'compose wizard: mail.message incorrect subject') self.assertEqual(message.body, '<p>%s</p>' % _body, 'compose wizard: mail.message incorrect body') # Test: mail.message: notified_partner_ids = admin + bert (followers) + c + d (recipients) msg_pids = [partner.id for partner in message.notified_partner_ids] test_pids = [self.partner_admin_id, p_b_id, p_c_id, p_d_id] self.assertEqual(set(msg_pids), set(test_pids), 'compose wizard: mail.message notified_partner_ids incorrect') # -------------------------------------------------- # CASE2: reply + attachments # -------------------------------------------------- # Do: Reply with attachments compose_id = mail_compose.create(cr, user_raoul.id, { 'attachment_ids': [(0, 0, _attachments[0]), (0, 0, _attachments[1])] }, context={ 'default_composition_mode': 'reply', 'default_model': 'mail.thread', 'default_res_id': self.group_pigs_id, 'default_parent_id': message.id }) compose = mail_compose.browse(cr, uid, compose_id) # Test: mail.compose.message: model, res_id, parent_id self.assertEqual(compose.model, 'mail.group', 'compose wizard: mail.compose.message incorrect model') self.assertEqual(compose.res_id, self.group_pigs_id, 'compose wizard: mail.compose.message incorrect res_id') self.assertEqual(compose.parent_id.id, message.id, 'compose wizard: mail.compose.message incorrect parent_id') # Test: mail.compose.message: subject as Re:.., body, parent_id self.assertEqual(compose.subject, _reply_subject, 'compose wizard: mail.compose.message incorrect subject') self.assertFalse(compose.body, 'compose wizard: mail.compose.message body should not contain parent message body') self.assertEqual(compose.parent_id and compose.parent_id.id, message.id, 'compose wizard: mail.compose.message parent_id incorrect') # Test: mail.compose.message: attachments for attach in compose.attachment_ids: self.assertIn((attach.datas_fname, attach.datas.decode('base64')), _attachments_test, 'compose wizard: mail.message attachment name / data incorrect') # -------------------------------------------------- # CASE3: mass_mail on Pigs and Bird # -------------------------------------------------- # Do: Compose in mass_mail_mode on pigs and bird compose_id = mail_compose.create(cr, user_raoul.id, { 'subject': _subject, 'body': '${object.description}', 'partner_ids': [(4, p_c_id), (4, p_d_id)], }, context={ 'default_composition_mode': 'mass_mail', 'default_model': 'mail.group', 'default_res_id': False, 'active_ids': [self.group_pigs_id, group_bird_id], }) compose = mail_compose.browse(cr, uid, compose_id) # D: Post the comment, get created message for each group mail_compose.send_mail(cr, user_raoul.id, [compose_id], context={ 'default_res_id': -1, 'active_ids': [self.group_pigs_id, group_bird_id] }) group_pigs.refresh() group_bird.refresh() message1 = group_pigs.message_ids[0] message2 = group_bird.message_ids[0] # Test: Pigs and Bird did receive their message test_msg_ids = self.mail_message.search(cr, uid, [], limit=2) self.assertIn(message1.id, test_msg_ids, 'compose wizard: Pigs did not receive its mass mailing message') self.assertIn(message2.id, test_msg_ids, 'compose wizard: Bird did not receive its mass mailing message') # Test: mail.message: subject, body, subtype, notified partners (nobody + specific recipients) self.assertEqual(message1.subject, _subject, 'compose wizard: message_post: mail.message in mass mail subject incorrect') self.assertEqual(message1.body, '<p>%s</p>' % group_pigs.description, 'compose wizard: message_post: mail.message in mass mail body incorrect') self.assertEqual(set([p.id for p in message1.notified_partner_ids]), set([p_c_id, p_d_id]), 'compose wizard: message_post: mail.message in mass mail incorrect notified partners') self.assertEqual(message2.subject, _subject, 'compose wizard: message_post: mail.message in mass mail subject incorrect') self.assertEqual(message2.body, '<p>%s</p>' % group_bird.description, 'compose wizard: message_post: mail.message in mass mail body incorrect') self.assertEqual(set([p.id for p in message2.notified_partner_ids]), set([p_c_id, p_d_id]), 'compose wizard: message_post: mail.message in mass mail incorrect notified partners') # Test: mail.group followers: author not added as follower in mass mail mode pigs_pids = [p.id for p in group_pigs.message_follower_ids] test_pids = [self.partner_admin_id, p_b_id, p_c_id, p_d_id] self.assertEqual(set(pigs_pids), set(test_pids), 'compose wizard: mail_post_autofollow and mail_create_nosubscribe context keys not correctly taken into account') bird_pids = [p.id for p in group_bird.message_follower_ids] test_pids = [self.partner_admin_id] self.assertEqual(set(bird_pids), set(test_pids), 'compose wizard: mail_post_autofollow and mail_create_nosubscribe context keys not correctly taken into account') def test_30_needaction(self): """ Tests for mail.message needaction. """ cr, uid, user_admin, user_raoul, group_pigs = self.cr, self.uid, self.user_admin, self.user_raoul, self.group_pigs group_pigs_demo = self.mail_group.browse(cr, self.user_raoul_id, self.group_pigs_id) na_admin_base = self.mail_message._needaction_count(cr, uid, domain=[]) na_demo_base = self.mail_message._needaction_count(cr, user_raoul.id, domain=[]) # Test: number of unread notification = needaction on mail.message notif_ids = self.mail_notification.search(cr, uid, [ ('partner_id', '=', user_admin.partner_id.id), ('read', '=', False) ]) na_count = self.mail_message._needaction_count(cr, uid, domain=[]) self.assertEqual(len(notif_ids), na_count, 'unread notifications count does not match needaction count') # Do: post 2 message on group_pigs as admin, 3 messages as demo user for dummy in range(2): group_pigs.message_post(body='My Body', subtype='mt_comment') for dummy in range(3): group_pigs_demo.message_post(body='My Demo Body', subtype='mt_comment') # Test: admin has 3 new notifications (from demo), and 3 new needaction notif_ids = self.mail_notification.search(cr, uid, [ ('partner_id', '=', user_admin.partner_id.id), ('read', '=', False) ]) self.assertEqual(len(notif_ids), na_admin_base + 3, 'Admin should have 3 new unread notifications') na_admin = self.mail_message._needaction_count(cr, uid, domain=[]) na_admin_group = self.mail_message._needaction_count(cr, uid, domain=[('model', '=', 'mail.group'), ('res_id', '=', self.group_pigs_id)]) self.assertEqual(na_admin, na_admin_base + 3, 'Admin should have 3 new needaction') self.assertEqual(na_admin_group, 3, 'Admin should have 3 needaction related to Pigs') # Test: demo has 0 new notifications (not a follower, not receiving its own messages), and 0 new needaction notif_ids = self.mail_notification.search(cr, uid, [ ('partner_id', '=', user_raoul.partner_id.id), ('read', '=', False) ]) self.assertEqual(len(notif_ids), na_demo_base + 0, 'Demo should have 0 new unread notifications') na_demo = self.mail_message._needaction_count(cr, user_raoul.id, domain=[]) na_demo_group = self.mail_message._needaction_count(cr, user_raoul.id, domain=[('model', '=', 'mail.group'), ('res_id', '=', self.group_pigs_id)]) self.assertEqual(na_demo, na_demo_base + 0, 'Demo should have 0 new needaction') self.assertEqual(na_demo_group, 0, 'Demo should have 0 needaction related to Pigs') def test_40_track_field(self): """ Testing auto tracking of fields. """ def _strip_string_spaces(body): return body.replace(' ', '').replace('\n', '') # Data: subscribe Raoul to Pigs, because he will change the public attribute and may loose access to the record cr, uid = self.cr, self.uid self.mail_group.message_subscribe_users(cr, uid, [self.group_pigs_id], [self.user_raoul_id]) # Data: res.users.group, to test group_public_id automatic logging group_system_ref = self.registry('ir.model.data').get_object_reference(cr, uid, 'base', 'group_system') group_system_id = group_system_ref and group_system_ref[1] or False # Data: custom subtypes mt_private_id = self.mail_message_subtype.create(cr, uid, {'name': 'private', 'description': 'Private public'}) self.ir_model_data.create(cr, uid, {'name': 'mt_private', 'model': 'mail.message.subtype', 'module': 'mail', 'res_id': mt_private_id}) mt_name_supername_id = self.mail_message_subtype.create(cr, uid, {'name': 'name_supername', 'description': 'Supername name'}) self.ir_model_data.create(cr, uid, {'name': 'mt_name_supername', 'model': 'mail.message.subtype', 'module': 'mail', 'res_id': mt_name_supername_id}) mt_group_public_id = self.mail_message_subtype.create(cr, uid, {'name': 'group_public', 'description': 'Group changed'}) self.ir_model_data.create(cr, uid, {'name': 'mt_group_public', 'model': 'mail.message.subtype', 'module': 'mail', 'res_id': mt_group_public_id}) # Data: alter mail_group model for testing purposes (test on classic, selection and many2one fields) self.mail_group._track = { 'public': { 'mail.mt_private': lambda self, cr, uid, obj, ctx=None: obj['public'] == 'private', }, 'name': { 'mail.mt_name_supername': lambda self, cr, uid, obj, ctx=None: obj['name'] == 'supername', }, 'group_public_id': { 'mail.mt_group_public': lambda self, cr, uid, obj, ctx=None: True, }, } public_col = self.mail_group._columns.get('public') name_col = self.mail_group._columns.get('name') group_public_col = self.mail_group._columns.get('group_public_id') public_col.track_visibility = 'onchange' name_col.track_visibility = 'always' group_public_col.track_visibility = 'onchange' # Test: change name -> always tracked, not related to a subtype self.mail_group.write(cr, self.user_raoul_id, [self.group_pigs_id], {'public': 'public'}) self.group_pigs.refresh() self.assertEqual(len(self.group_pigs.message_ids), 1, 'tracked: a message should have been produced') # Test: first produced message: no subtype, name change tracked last_msg = self.group_pigs.message_ids[-1] self.assertFalse(last_msg.subtype_id, 'tracked: message should not have been linked to a subtype') self.assertIn(u'SelectedGroupOnly\u2192Public', _strip_string_spaces(last_msg.body), 'tracked: message body incorrect') self.assertIn('Pigs', _strip_string_spaces(last_msg.body), 'tracked: message body does not hold always tracked field') # Test: change name as supername, public as private -> 2 subtypes self.mail_group.write(cr, self.user_raoul_id, [self.group_pigs_id], {'name': 'supername', 'public': 'private'}) self.group_pigs.refresh() self.assertEqual(len(self.group_pigs.message_ids), 3, 'tracked: two messages should have been produced') # Test: first produced message: mt_name_supername last_msg = self.group_pigs.message_ids[-2] self.assertEqual(last_msg.subtype_id.id, mt_private_id, 'tracked: message should be linked to mt_private subtype') self.assertIn('Private public', last_msg.body, 'tracked: message body does not hold the subtype description') self.assertIn(u'Pigs\u2192supername', _strip_string_spaces(last_msg.body), 'tracked: message body incorrect') # Test: second produced message: mt_name_supername last_msg = self.group_pigs.message_ids[-3] self.assertEqual(last_msg.subtype_id.id, mt_name_supername_id, 'tracked: message should be linked to mt_name_supername subtype') self.assertIn('Supername name', last_msg.body, 'tracked: message body does not hold the subtype description') self.assertIn(u'Public\u2192Private', _strip_string_spaces(last_msg.body), 'tracked: message body incorrect') self.assertIn(u'Pigs\u2192supername', _strip_string_spaces(last_msg.body), 'tracked feature: message body does not hold always tracked field') # Test: change public as public, group_public_id -> 1 subtype, name always tracked self.mail_group.write(cr, self.user_raoul_id, [self.group_pigs_id], {'public': 'public', 'group_public_id': group_system_id}) self.group_pigs.refresh() self.assertEqual(len(self.group_pigs.message_ids), 4, 'tracked: one message should have been produced') # Test: first produced message: mt_group_public_id, with name always tracked, public tracked on change last_msg = self.group_pigs.message_ids[-4] self.assertEqual(last_msg.subtype_id.id, mt_group_public_id, 'tracked: message should not be linked to any subtype') self.assertIn('Group changed', last_msg.body, 'tracked: message body does not hold the subtype description') self.assertIn(u'Private\u2192Public', _strip_string_spaces(last_msg.body), 'tracked: message body does not hold changed tracked field') self.assertIn(u'HumanResources/Employee\u2192Administration/Settings', _strip_string_spaces(last_msg.body), 'tracked: message body does not hold always tracked field') # Test: change not tracked field, no tracking message self.mail_group.write(cr, self.user_raoul_id, [self.group_pigs_id], {'description': 'Dummy'}) self.group_pigs.refresh() self.assertEqual(len(self.group_pigs.message_ids), 4, 'tracked: No message should have been produced') # Data: removed changes public_col.track_visibility = None name_col.track_visibility = None group_public_col.track_visibility = None self.mail_group._track = {}
agpl-3.0
pavlovml/tensorflow
tensorflow/python/training/queue_runner_test.py
5
6835
"""Tests for QueueRunner.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import time import tensorflow.python.platform import tensorflow as tf class QueueRunnerTest(tf.test.TestCase): def testBasic(self): with self.test_session() as sess: # CountUpTo will raise OUT_OF_RANGE when it reaches the count. zero64 = tf.constant(0, dtype=tf.int64) var = tf.Variable(zero64) count_up_to = var.count_up_to(3) queue = tf.FIFOQueue(10, tf.float32) tf.initialize_all_variables().run() qr = tf.train.QueueRunner(queue, [count_up_to]) threads = qr.create_threads(sess) for t in threads: t.start() for t in threads: t.join() self.assertEqual(0, len(qr.exceptions_raised)) # The variable should be 3. self.assertEqual(3, var.eval()) def testTwoOps(self): with self.test_session() as sess: # CountUpTo will raise OUT_OF_RANGE when it reaches the count. zero64 = tf.constant(0, dtype=tf.int64) var0 = tf.Variable(zero64) count_up_to_3 = var0.count_up_to(3) var1 = tf.Variable(zero64) count_up_to_30 = var1.count_up_to(30) queue = tf.FIFOQueue(10, tf.float32) qr = tf.train.QueueRunner(queue, [count_up_to_3, count_up_to_30]) threads = qr.create_threads(sess) tf.initialize_all_variables().run() for t in threads: t.start() for t in threads: t.join() self.assertEqual(0, len(qr.exceptions_raised)) self.assertEqual(3, var0.eval()) self.assertEqual(30, var1.eval()) def testExceptionsCaptured(self): with self.test_session() as sess: queue = tf.FIFOQueue(10, tf.float32) qr = tf.train.QueueRunner(queue, ["i fail", "so fail"]) threads = qr.create_threads(sess) tf.initialize_all_variables().run() for t in threads: t.start() for t in threads: t.join() exceptions = qr.exceptions_raised self.assertEqual(2, len(exceptions)) self.assertTrue("Operation not in the graph" in str(exceptions[0])) self.assertTrue("Operation not in the graph" in str(exceptions[1])) def testRealDequeueEnqueue(self): with self.test_session() as sess: q0 = tf.FIFOQueue(3, tf.float32) enqueue0 = q0.enqueue((10.0,)) close0 = q0.close() q1 = tf.FIFOQueue(30, tf.float32) enqueue1 = q1.enqueue((q0.dequeue(),)) dequeue1 = q1.dequeue() qr = tf.train.QueueRunner(q1, [enqueue1]) threads = qr.create_threads(sess) for t in threads: t.start() # Enqueue 2 values, then close queue0. enqueue0.run() enqueue0.run() close0.run() # Wait for the queue runner to terminate. for t in threads: t.join() # It should have terminated cleanly. self.assertEqual(0, len(qr.exceptions_raised)) # The 2 values should be in queue1. self.assertEqual(10.0, dequeue1.eval()) self.assertEqual(10.0, dequeue1.eval()) # And queue1 should now be closed. with self.assertRaisesRegexp(tf.errors.OutOfRangeError, "is closed"): dequeue1.eval() def testRespectCoordShouldStop(self): with self.test_session() as sess: # CountUpTo will raise OUT_OF_RANGE when it reaches the count. zero64 = tf.constant(0, dtype=tf.int64) var = tf.Variable(zero64) count_up_to = var.count_up_to(3) queue = tf.FIFOQueue(10, tf.float32) tf.initialize_all_variables().run() qr = tf.train.QueueRunner(queue, [count_up_to]) # As the coordinator to stop. The queue runner should # finish immediately. coord = tf.train.Coordinator() coord.request_stop() threads = qr.create_threads(sess, coord) for t in threads: t.start() coord.join(threads) self.assertEqual(0, len(qr.exceptions_raised)) # The variable should be 0. self.assertEqual(0, var.eval()) def testRequestStopOnException(self): with self.test_session() as sess: queue = tf.FIFOQueue(10, tf.float32) qr = tf.train.QueueRunner(queue, ["not an op"]) coord = tf.train.Coordinator() threads = qr.create_threads(sess, coord) for t in threads: t.start() # The exception should be re-raised when joining. with self.assertRaisesRegexp(ValueError, "Operation not in the graph"): coord.join(threads) def testGracePeriod(self): with self.test_session() as sess: # The enqueue will quickly block. queue = tf.FIFOQueue(2, tf.float32) enqueue = queue.enqueue((10.0,)) dequeue = queue.dequeue() qr = tf.train.QueueRunner(queue, [enqueue]) coord = tf.train.Coordinator() threads = qr.create_threads(sess, coord, start=True) # Dequeue one element and then request stop. dequeue.op.run() time.sleep(0.02) coord.request_stop() # We should be able to join because the RequestStop() will cause # the queue to be closed and the enqueue to terminate. coord.join(threads, stop_grace_period_secs=0.05) def testNoMultiThreads(self): with self.test_session() as sess: # CountUpTo will raise OUT_OF_RANGE when it reaches the count. zero64 = tf.constant(0, dtype=tf.int64) var = tf.Variable(zero64) count_up_to = var.count_up_to(3) queue = tf.FIFOQueue(10, tf.float32) tf.initialize_all_variables().run() coord = tf.train.Coordinator() qr = tf.train.QueueRunner(queue, [count_up_to]) threads = [] threads.extend(qr.create_threads(sess, coord=coord)) with self.assertRaisesRegexp( RuntimeError, "Threads are already running"): threads.extend(qr.create_threads(sess, coord=coord)) coord.request_stop() coord.join(threads, stop_grace_period_secs=0.5) def testThreads(self): with self.test_session() as sess: # CountUpTo will raise OUT_OF_RANGE when it reaches the count. zero64 = tf.constant(0, dtype=tf.int64) var = tf.Variable(zero64) count_up_to = var.count_up_to(3) queue = tf.FIFOQueue(10, tf.float32) tf.initialize_all_variables().run() qr = tf.train.QueueRunner(queue, [count_up_to, "bad op"]) threads = qr.create_threads(sess, start=True) for t in threads: t.join() exceptions = qr.exceptions_raised self.assertEqual(1, len(exceptions)) self.assertTrue("Operation not in the graph" in str(exceptions[0])) threads = qr.create_threads(sess, start=True) for t in threads: t.join() exceptions = qr.exceptions_raised self.assertEqual(1, len(exceptions)) self.assertTrue("Operation not in the graph" in str(exceptions[0])) if __name__ == "__main__": tf.test.main()
apache-2.0
bplancher/odoo
addons/event/models/event_mail.py
6
5812
# -*- coding: utf-8 -*- from datetime import datetime from dateutil.relativedelta import relativedelta from openerp import api, fields, models, tools _INTERVALS = { 'hours': lambda interval: relativedelta(hours=interval), 'days': lambda interval: relativedelta(days=interval), 'weeks': lambda interval: relativedelta(days=7*interval), 'months': lambda interval: relativedelta(months=interval), 'now': lambda interval: relativedelta(hours=0), } class EventMailScheduler(models.Model): """ Event automated mailing. This model replaces all existing fields and configuration allowing to send emails on events since Odoo 9. A cron exists that periodically checks for mailing to run. """ _name = 'event.mail' event_id = fields.Many2one('event.event', string='Event', required=True, ondelete='cascade') sequence = fields.Integer('Display order') interval_nbr = fields.Integer('Interval', default=1) interval_unit = fields.Selection([ ('now', 'Immediately'), ('hours', 'Hour(s)'), ('days', 'Day(s)'), ('weeks', 'Week(s)'), ('months', 'Month(s)')], string='Unit', default='hours', required=True) interval_type = fields.Selection([ ('after_sub', 'After each subscription'), ('before_event', 'Before the event'), ('after_event', 'After the event')], string='When to Run ', default="before_event", required=True) template_id = fields.Many2one( 'mail.template', string='Email to Send', domain=[('model', '=', 'event.registration')], required=True, ondelete='restrict', help='This field contains the template of the mail that will be automatically sent') scheduled_date = fields.Datetime('Scheduled Sent Mail', compute='_compute_scheduled_date', store=True) mail_registration_ids = fields.One2many('event.mail.registration', 'scheduler_id') mail_sent = fields.Boolean('Mail Sent on Event') done = fields.Boolean('Sent', compute='_compute_done', store=True) @api.one @api.depends('mail_sent', 'interval_type', 'event_id.registration_ids', 'mail_registration_ids') def _compute_done(self): if self.interval_type in ['before_event', 'after_event']: self.done = self.mail_sent else: self.done = len(self.mail_registration_ids) == len(self.event_id.registration_ids) and all(line.mail_sent for line in self.mail_registration_ids) @api.one @api.depends('event_id.state', 'event_id.date_begin', 'interval_type', 'interval_unit', 'interval_nbr') def _compute_scheduled_date(self): if self.event_id.state not in ['confirm', 'done']: self.scheduled_date = False else: if self.interval_type == 'after_sub': date, sign = self.event_id.create_date, 1 elif self.interval_type == 'before_event': date, sign = self.event_id.date_begin, -1 else: date, sign = self.event_id.date_end, 1 self.scheduled_date = datetime.strptime(date, tools.DEFAULT_SERVER_DATETIME_FORMAT) + _INTERVALS[self.interval_unit](sign * self.interval_nbr) @api.one def execute(self): if self.interval_type == 'after_sub': # update registration lines lines = [] reg_ids = [mail_reg.registration_id for mail_reg in self.mail_registration_ids] for registration in filter(lambda item: item not in reg_ids, self.event_id.registration_ids): lines.append((0, 0, {'registration_id': registration.id})) if lines: self.write({'mail_registration_ids': lines}) # execute scheduler on registrations self.mail_registration_ids.filtered(lambda reg: reg.scheduled_date and reg.scheduled_date <= datetime.strftime(fields.datetime.now(), tools.DEFAULT_SERVER_DATETIME_FORMAT)).execute() else: if not self.mail_sent: self.event_id.mail_attendees(self.template_id.id) self.write({'mail_sent': True}) return True @api.model def run(self, autocommit=False): schedulers = self.search([('done', '=', False), ('scheduled_date', '<=', datetime.strftime(fields.datetime.now(), tools.DEFAULT_SERVER_DATETIME_FORMAT))]) for scheduler in schedulers: scheduler.execute() if autocommit: self.env.cr.commit() return True class EventMailRegistration(models.Model): _name = 'event.mail.registration' _description = 'Registration Mail Scheduler' _rec_name = 'scheduler_id' _order = 'scheduled_date DESC' scheduler_id = fields.Many2one('event.mail', 'Mail Scheduler', required=True, ondelete='cascade') registration_id = fields.Many2one('event.registration', 'Attendee', required=True, ondelete='cascade') scheduled_date = fields.Datetime('Scheduled Time', compute='_compute_scheduled_date', store=True) mail_sent = fields.Boolean('Mail Sent') @api.one def execute(self): if self.registration_id.state in ['open', 'done'] and not self.mail_sent: self.scheduler_id.template_id.send_mail(self.registration_id.id) self.write({'mail_sent': True}) @api.one @api.depends('registration_id', 'scheduler_id.interval_unit', 'scheduler_id.interval_type') def _compute_scheduled_date(self): if self.registration_id: date_open = self.registration_id.date_open date_open_datetime = date_open and datetime.strptime(date_open, tools.DEFAULT_SERVER_DATETIME_FORMAT) or fields.datetime.now() self.scheduled_date = date_open_datetime + _INTERVALS[self.scheduler_id.interval_unit](self.scheduler_id.interval_nbr) else: self.scheduled_date = False
agpl-3.0
openstack/nova
nova/tests/functional/db/test_compute_node.py
3
11359
# Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from oslo_serialization import jsonutils from oslo_utils.fixture import uuidsentinel import nova.conf from nova import context from nova.db import api as db from nova import objects from nova.objects import compute_node from nova.objects import fields as obj_fields from nova import test CONF = nova.conf.CONF _HOSTNAME = 'fake-host' _NODENAME = 'fake-node' _VIRT_DRIVER_AVAIL_RESOURCES = { 'vcpus': 4, 'memory_mb': 512, 'local_gb': 6, 'vcpus_used': 0, 'memory_mb_used': 0, 'local_gb_used': 0, 'hypervisor_type': 'fake', 'hypervisor_version': 0, 'hypervisor_hostname': _NODENAME, 'cpu_info': '', 'numa_topology': None, } fake_compute_obj = objects.ComputeNode( host=_HOSTNAME, vcpus=_VIRT_DRIVER_AVAIL_RESOURCES['vcpus'], memory_mb=_VIRT_DRIVER_AVAIL_RESOURCES['memory_mb'], local_gb=_VIRT_DRIVER_AVAIL_RESOURCES['local_gb'], vcpus_used=_VIRT_DRIVER_AVAIL_RESOURCES['vcpus_used'], memory_mb_used=_VIRT_DRIVER_AVAIL_RESOURCES['memory_mb_used'], local_gb_used=_VIRT_DRIVER_AVAIL_RESOURCES['local_gb_used'], hypervisor_type='fake', hypervisor_version=0, hypervisor_hostname=_HOSTNAME, free_ram_mb=(_VIRT_DRIVER_AVAIL_RESOURCES['memory_mb'] - _VIRT_DRIVER_AVAIL_RESOURCES['memory_mb_used']), free_disk_gb=(_VIRT_DRIVER_AVAIL_RESOURCES['local_gb'] - _VIRT_DRIVER_AVAIL_RESOURCES['local_gb_used']), current_workload=0, running_vms=0, cpu_info='{}', disk_available_least=0, host_ip='1.1.1.1', supported_hv_specs=[ objects.HVSpec.from_list([ obj_fields.Architecture.I686, obj_fields.HVType.KVM, obj_fields.VMMode.HVM]) ], metrics=None, pci_device_pools=None, extra_resources=None, stats={}, numa_topology=None, cpu_allocation_ratio=16.0, ram_allocation_ratio=1.5, disk_allocation_ratio=1.0, ) class ComputeNodeTestCase(test.TestCase): def setUp(self): super(ComputeNodeTestCase, self).setUp() self.context = context.RequestContext('fake-user', 'fake-project') def _create_zero_and_none_cn(self): cn1 = fake_compute_obj.obj_clone() cn1._context = self.context cn1.create() db.compute_node_update(self.context, cn1.id, {'cpu_allocation_ratio': 0.0, 'disk_allocation_ratio': 0.0, 'ram_allocation_ratio': 0.0}) cn1_db = db.compute_node_get(self.context, cn1.id) for x in ['cpu', 'disk', 'ram']: self.assertEqual(0.0, cn1_db['%s_allocation_ratio' % x]) cn2 = fake_compute_obj.obj_clone() cn2._context = self.context cn2.host += '-alt' cn2.create() # We can't set a cn_obj.xxx_allocation_ratio to None, # so we set ratio to None in db directly db.compute_node_update(self.context, cn2.id, {'cpu_allocation_ratio': None, 'disk_allocation_ratio': None, 'ram_allocation_ratio': None}) cn2_db = db.compute_node_get(self.context, cn2.id) for x in ['cpu', 'disk', 'ram']: self.assertIsNone(cn2_db['%s_allocation_ratio' % x]) def test_get_all_by_uuids(self): cn1 = fake_compute_obj.obj_clone() cn1._context = self.context cn1.create() cn2 = fake_compute_obj.obj_clone() cn2._context = self.context # Two compute nodes can't have the same tuple (host, node, deleted) cn2.host = _HOSTNAME + '2' cn2.create() # A deleted compute node cn3 = fake_compute_obj.obj_clone() cn3._context = self.context cn3.host = _HOSTNAME + '3' cn3.create() cn3.destroy() cns = objects.ComputeNodeList.get_all_by_uuids(self.context, []) self.assertEqual(0, len(cns)) # Ensure that asking for one compute node when there are multiple only # returns the one we want. cns = objects.ComputeNodeList.get_all_by_uuids(self.context, [cn1.uuid]) self.assertEqual(1, len(cns)) cns = objects.ComputeNodeList.get_all_by_uuids(self.context, [cn1.uuid, cn2.uuid]) self.assertEqual(2, len(cns)) # Ensure that asking for a non-existing UUID along with # existing UUIDs doesn't limit the return of the existing # compute nodes... cns = objects.ComputeNodeList.get_all_by_uuids(self.context, [cn1.uuid, cn2.uuid, uuidsentinel.noexists]) self.assertEqual(2, len(cns)) # Ensure we don't get the deleted one, even if we ask for it cns = objects.ComputeNodeList.get_all_by_uuids(self.context, [cn1.uuid, cn2.uuid, cn3.uuid]) self.assertEqual(2, len(cns)) def test_get_by_hypervisor_type(self): cn1 = fake_compute_obj.obj_clone() cn1._context = self.context cn1.hypervisor_type = 'ironic' cn1.create() cn2 = fake_compute_obj.obj_clone() cn2._context = self.context cn2.hypervisor_type = 'libvirt' cn2.host += '-alt' cn2.create() cns = objects.ComputeNodeList.get_by_hypervisor_type(self.context, 'ironic') self.assertEqual(1, len(cns)) self.assertEqual(cn1.uuid, cns[0].uuid) def test_numa_topology_online_migration_when_load(self): """Ensure legacy NUMA topology objects are reserialized to o.vo's.""" cn = fake_compute_obj.obj_clone() cn._context = self.context cn.create() legacy_topology = jsonutils.dumps({ "cells": [ { "id": 0, "cpus": "0-3", "mem": {"total": 512, "used": 256}, "cpu_usage": 2, }, { "id": 1, "cpus": "4,5,6,7", "mem": {"total": 512, "used": 0}, "cpu_usage": 0, } ] }) db.compute_node_update( self.context, cn.id, {'numa_topology': legacy_topology}) cn_db = db.compute_node_get(self.context, cn.id) self.assertEqual(legacy_topology, cn_db['numa_topology']) self.assertNotIn('nova_object.name', cn_db['numa_topology']) # trigger online migration objects.ComputeNodeList.get_all(self.context) cn_db = db.compute_node_get(self.context, cn.id) self.assertNotEqual(legacy_topology, cn_db['numa_topology']) self.assertIn('nova_object.name', cn_db['numa_topology']) def test_ratio_online_migration_when_load(self): # set cpu and disk, and leave ram unset(None) self.flags(cpu_allocation_ratio=1.0) self.flags(disk_allocation_ratio=2.0) self._create_zero_and_none_cn() # trigger online migration objects.ComputeNodeList.get_all(self.context) cns = db.compute_node_get_all(self.context) for cn in cns: # the cpu/disk ratio is refreshed to CONF.xxx_allocation_ratio self.assertEqual(CONF.cpu_allocation_ratio, cn['cpu_allocation_ratio']) self.assertEqual(CONF.disk_allocation_ratio, cn['disk_allocation_ratio']) # the ram ratio is refreshed to CONF.initial_xxx_allocation_ratio self.assertEqual(CONF.initial_ram_allocation_ratio, cn['ram_allocation_ratio']) def test_migrate_empty_ratio(self): # we have 5 records to process, the last of which is deleted for i in range(5): cn = fake_compute_obj.obj_clone() cn._context = self.context cn.host += '-alt-%s' % i cn.create() db.compute_node_update(self.context, cn.id, {'cpu_allocation_ratio': 0.0}) if i == 4: cn.destroy() # first only process 2 res = compute_node.migrate_empty_ratio(self.context, 2) self.assertEqual(res, (2, 2)) # then process others - there should only be 2 found since one # of the remaining compute nodes is deleted and gets filtered out res = compute_node.migrate_empty_ratio(self.context, 999) self.assertEqual(res, (2, 2)) def test_migrate_none_or_zero_ratio_with_none_ratio_conf(self): cn1 = fake_compute_obj.obj_clone() cn1._context = self.context cn1.create() db.compute_node_update(self.context, cn1.id, {'cpu_allocation_ratio': 0.0, 'disk_allocation_ratio': 0.0, 'ram_allocation_ratio': 0.0}) self.flags(initial_cpu_allocation_ratio=32.0) self.flags(initial_ram_allocation_ratio=8.0) self.flags(initial_disk_allocation_ratio=2.0) res = compute_node.migrate_empty_ratio(self.context, 1) self.assertEqual(res, (1, 1)) # the ratio is refreshed to CONF.initial_xxx_allocation_ratio # beacause CONF.xxx_allocation_ratio is None cns = db.compute_node_get_all(self.context) # the ratio is refreshed to CONF.xxx_allocation_ratio for cn in cns: for x in ['cpu', 'disk', 'ram']: conf_key = 'initial_%s_allocation_ratio' % x key = '%s_allocation_ratio' % x self.assertEqual(getattr(CONF, conf_key), cn[key]) def test_migrate_none_or_zero_ratio_with_not_empty_ratio(self): cn1 = fake_compute_obj.obj_clone() cn1._context = self.context cn1.create() db.compute_node_update(self.context, cn1.id, {'cpu_allocation_ratio': 32.0, 'ram_allocation_ratio': 4.0, 'disk_allocation_ratio': 3.0}) res = compute_node.migrate_empty_ratio(self.context, 1) # the non-empty ratio will not be refreshed self.assertEqual(res, (0, 0)) cns = db.compute_node_get_all(self.context) for cn in cns: self.assertEqual(32.0, cn['cpu_allocation_ratio']) self.assertEqual(4.0, cn['ram_allocation_ratio']) self.assertEqual(3.0, cn['disk_allocation_ratio'])
apache-2.0
Serag8/Bachelor
google_appengine/google/appengine/ext/key_range/__init__.py
13
28453
#!/usr/bin/env python # # Copyright 2007 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. # """Key range representation and splitting.""" import os try: import json as simplejson except ImportError: try: import simplejson except ImportError: simplejson = None from google.appengine.api import datastore from google.appengine.api import namespace_manager from google.appengine.datastore import datastore_pb from google.appengine.ext import db try: from google.appengine.ext import ndb except ImportError: ndb = None # It is acceptable to set key_range.ndb to the ndb module, # imported through some other way (e.g. from the app dir). class Error(Exception): """Base class for exceptions in this module.""" class KeyRangeError(Error): """Error while trying to generate a KeyRange.""" class SimplejsonUnavailableError(Error): """Error using json functionality with unavailable json and simplejson.""" def _IsNdbQuery(query): return ndb is not None and isinstance(query, ndb.Query) class KeyRange(object): """Represents a range of keys in the datastore. A KeyRange object represents a key range (key_start, include_start, key_end, include_end) and a scan direction (KeyRange.DESC or KeyRange.ASC). """ DESC = "DESC" ASC = "ASC" def __init__(self, key_start=None, key_end=None, direction=None, include_start=True, include_end=True, namespace=None, _app=None): """Initialize a KeyRange object. Args: key_start: The starting key for this range (db.Key or ndb.Key). key_end: The ending key for this range (db.Key or ndb.Key). direction: The direction of the query for this range. include_start: Whether the start key should be included in the range. include_end: Whether the end key should be included in the range. namespace: The namespace for this range. If None then the current namespace is used. NOTE: If NDB keys are passed in, they are converted to db.Key instances before being stored. """ if direction is None: direction = KeyRange.ASC assert direction in (KeyRange.ASC, KeyRange.DESC) self.direction = direction if ndb is not None: if isinstance(key_start, ndb.Key): key_start = key_start.to_old_key() if isinstance(key_end, ndb.Key): key_end = key_end.to_old_key() self.key_start = key_start self.key_end = key_end self.include_start = include_start self.include_end = include_end if namespace is not None: self.namespace = namespace else: self.namespace = namespace_manager.get_namespace() self._app = _app def __str__(self): if self.include_start: left_side = "[" else: left_side = "(" if self.include_end: right_side = "]" else: right_side = ")" return "%s%s%r to %r%s" % (self.direction, left_side, self.key_start, self.key_end, right_side) def __repr__(self): return ("key_range.KeyRange(key_start=%r,key_end=%r,direction=%r," "include_start=%r,include_end=%r, namespace=%r)") % ( self.key_start, self.key_end, self.direction, self.include_start, self.include_end, self.namespace) def advance(self, key): """Updates the start of the range immediately past the specified key. Args: key: A db.Key or ndb.Key. """ self.include_start = False if ndb is not None: if isinstance(key, ndb.Key): key = key.to_old_key() self.key_start = key def filter_query(self, query, filters=None): """Add query filter to restrict to this key range. Args: query: A db.Query or ndb.Query instance. filters: optional list of filters to apply to the query. Each filter is a tuple: (<property_name_as_str>, <query_operation_as_str>, <value>). User filters are applied first. Returns: The input query restricted to this key range. """ if ndb is not None: if _IsNdbQuery(query): return self.filter_ndb_query(query, filters=filters) assert not _IsNdbQuery(query) if filters: for f in filters: query.filter("%s %s" % (f[0], f[1]), f[2]) if self.include_start: start_comparator = ">=" else: start_comparator = ">" if self.include_end: end_comparator = "<=" else: end_comparator = "<" if self.key_start: query.filter("__key__ %s" % start_comparator, self.key_start) if self.key_end: query.filter("__key__ %s" % end_comparator, self.key_end) return query def filter_ndb_query(self, query, filters=None): """Add query filter to restrict to this key range. Args: query: An ndb.Query instance. filters: optional list of filters to apply to the query. Each filter is a tuple: (<property_name_as_str>, <query_operation_as_str>, <value>). User filters are applied first. Returns: The input query restricted to this key range. """ assert _IsNdbQuery(query) if filters: for f in filters: query = query.filter(ndb.FilterNode(*f)) if self.include_start: start_comparator = ">=" else: start_comparator = ">" if self.include_end: end_comparator = "<=" else: end_comparator = "<" if self.key_start: query = query.filter(ndb.FilterNode("__key__", start_comparator, self.key_start)) if self.key_end: query = query.filter(ndb.FilterNode("__key__", end_comparator, self.key_end)) return query def filter_datastore_query(self, query, filters=None): """Add query filter to restrict to this key range. Args: query: A datastore.Query instance. filters: optional list of filters to apply to the query. Each filter is a tuple: (<property_name_as_str>, <query_operation_as_str>, <value>). User filters are applied first. Returns: The input query restricted to this key range. """ assert isinstance(query, datastore.Query) if filters: for f in filters: query.update({"%s %s" % (f[0], f[1]): f[2]}) if self.include_start: start_comparator = ">=" else: start_comparator = ">" if self.include_end: end_comparator = "<=" else: end_comparator = "<" if self.key_start: query.update({"__key__ %s" % start_comparator: self.key_start}) if self.key_end: query.update({"__key__ %s" % end_comparator: self.key_end}) return query def __get_direction(self, asc, desc): """Check that self.direction is in (KeyRange.ASC, KeyRange.DESC). Args: asc: Argument to return if self.direction is KeyRange.ASC desc: Argument to return if self.direction is KeyRange.DESC Returns: asc or desc appropriately Raises: KeyRangeError: if self.direction is not in (KeyRange.ASC, KeyRange.DESC). """ if self.direction == KeyRange.ASC: return asc elif self.direction == KeyRange.DESC: return desc else: raise KeyRangeError("KeyRange direction unexpected: %s", self.direction) def make_directed_query(self, kind_class, keys_only=False): """Construct a query for this key range, including the scan direction. Args: kind_class: A kind implementation class (a subclass of either db.Model or ndb.Model). keys_only: bool, default False, use keys_only on Query? Returns: A db.Query or ndb.Query instance (corresponding to kind_class). Raises: KeyRangeError: if self.direction is not in (KeyRange.ASC, KeyRange.DESC). """ if ndb is not None: if issubclass(kind_class, ndb.Model): return self.make_directed_ndb_query(kind_class, keys_only=keys_only) assert self._app is None, '_app is not supported for db.Query' direction = self.__get_direction("", "-") query = db.Query(kind_class, namespace=self.namespace, keys_only=keys_only) query.order("%s__key__" % direction) query = self.filter_query(query) return query def make_directed_ndb_query(self, kind_class, keys_only=False): """Construct an NDB query for this key range, including the scan direction. Args: kind_class: An ndb.Model subclass. keys_only: bool, default False, use keys_only on Query? Returns: An ndb.Query instance. Raises: KeyRangeError: if self.direction is not in (KeyRange.ASC, KeyRange.DESC). """ assert issubclass(kind_class, ndb.Model) if keys_only: default_options = ndb.QueryOptions(keys_only=True) else: default_options = None query = kind_class.query(app=self._app, namespace=self.namespace, default_options=default_options) query = self.filter_ndb_query(query) if self.__get_direction(True, False): query = query.order(kind_class._key) else: query = query.order(-kind_class._key) return query def make_directed_datastore_query(self, kind, keys_only=False): """Construct a query for this key range, including the scan direction. Args: kind: A string. keys_only: bool, default False, use keys_only on Query? Returns: A datastore.Query instance. Raises: KeyRangeError: if self.direction is not in (KeyRange.ASC, KeyRange.DESC). """ direction = self.__get_direction(datastore.Query.ASCENDING, datastore.Query.DESCENDING) query = datastore.Query(kind, _app=self._app, keys_only=keys_only) query.Order(("__key__", direction)) query = self.filter_datastore_query(query) return query def make_ascending_query(self, kind_class, keys_only=False, filters=None): """Construct a query for this key range without setting the scan direction. Args: kind_class: A kind implementation class (a subclass of either db.Model or ndb.Model). keys_only: bool, default False, query only for keys. filters: optional list of filters to apply to the query. Each filter is a tuple: (<property_name_as_str>, <query_operation_as_str>, <value>). User filters are applied first. Returns: A db.Query or ndb.Query instance (corresponding to kind_class). """ if ndb is not None: if issubclass(kind_class, ndb.Model): return self.make_ascending_ndb_query( kind_class, keys_only=keys_only, filters=filters) assert self._app is None, '_app is not supported for db.Query' query = db.Query(kind_class, namespace=self.namespace, keys_only=keys_only) query.order("__key__") query = self.filter_query(query, filters=filters) return query def make_ascending_ndb_query(self, kind_class, keys_only=False, filters=None): """Construct an NDB query for this key range, without the scan direction. Args: kind_class: An ndb.Model subclass. keys_only: bool, default False, query only for keys. Returns: An ndb.Query instance. """ assert issubclass(kind_class, ndb.Model) if keys_only: default_options = ndb.QueryOptions(keys_only=True) else: default_options = None query = kind_class.query(app=self._app, namespace=self.namespace, default_options=default_options) query = self.filter_ndb_query(query, filters=filters) query = query.order(kind_class._key) return query def make_ascending_datastore_query(self, kind, keys_only=False, filters=None): """Construct a query for this key range without setting the scan direction. Args: kind: A string. keys_only: bool, default False, use keys_only on Query? filters: optional list of filters to apply to the query. Each filter is a tuple: (<property_name_as_str>, <query_operation_as_str>, <value>). User filters are applied first. Returns: A datastore.Query instance. """ query = datastore.Query(kind, namespace=self.namespace, _app=self._app, keys_only=keys_only) query.Order(("__key__", datastore.Query.ASCENDING)) query = self.filter_datastore_query(query, filters=filters) return query def split_range(self, batch_size=0): """Split this key range into a list of at most two ranges. This method attempts to split the key range approximately in half. Numeric ranges are split in the middle into two equal ranges and string ranges are split lexicographically in the middle. If the key range is smaller than batch_size it is left unsplit. Note that splitting is done without knowledge of the distribution of actual entities in the key range, so there is no guarantee (nor any particular reason to believe) that the entities of the range are evenly split. Args: batch_size: The maximum size of a key range that should not be split. Returns: A list of one or two key ranges covering the same space as this range. """ key_start = self.key_start key_end = self.key_end include_start = self.include_start include_end = self.include_end key_pairs = [] if not key_start: key_pairs.append((key_start, include_start, key_end, include_end, KeyRange.ASC)) elif not key_end: key_pairs.append((key_start, include_start, key_end, include_end, KeyRange.DESC)) else: key_split = KeyRange.split_keys(key_start, key_end, batch_size) first_include_end = True if key_split == key_start: first_include_end = first_include_end and include_start key_pairs.append((key_start, include_start, key_split, first_include_end, KeyRange.DESC)) second_include_end = include_end if key_split == key_end: second_include_end = False key_pairs.append((key_split, False, key_end, second_include_end, KeyRange.ASC)) ranges = [KeyRange(key_start=start, include_start=include_start, key_end=end, include_end=include_end, direction=direction, namespace=self.namespace, _app=self._app) for (start, include_start, end, include_end, direction) in key_pairs] return ranges def __hash__(self): raise TypeError('KeyRange is unhashable') def __cmp__(self, other): """Compare two key ranges. Key ranges with a value of None for key_start or key_end, are always considered to have include_start=False or include_end=False, respectively, when comparing. Since None indicates an unbounded side of the range, the include specifier is meaningless. The ordering generated is total but somewhat arbitrary. Args: other: An object to compare to this one. Returns: -1: if this key range is less than other. 0: if this key range is equal to other. 1: if this key range is greater than other. """ if not isinstance(other, KeyRange): return 1 self_list = [self.key_start, self.key_end, self.direction, self.include_start, self.include_end, self._app, self.namespace] if not self.key_start: self_list[3] = False if not self.key_end: self_list[4] = False other_list = [other.key_start, other.key_end, other.direction, other.include_start, other.include_end, other._app, other.namespace] if not other.key_start: other_list[3] = False if not other.key_end: other_list[4] = False return cmp(self_list, other_list) @staticmethod def bisect_string_range(start, end): """Returns a string that is approximately in the middle of the range. (start, end) is treated as a string range, and it is assumed start <= end in the usual lexicographic string ordering. The output key mid is guaranteed to satisfy start <= mid <= end. The method proceeds by comparing initial characters of start and end. When the characters are equal, they are appended to the mid string. In the first place that the characters differ, the difference characters are averaged and this average is appended to the mid string. If averaging resulted in rounding down, and additional character is added to the mid string to make up for the rounding down. This extra step is necessary for correctness in the case that the average of the two characters is equal to the character in the start string. This method makes the assumption that most keys are ascii and it attempts to perform splitting within the ascii range when that results in a valid split. Args: start: A string. end: A string such that start <= end. Returns: A string mid such that start <= mid <= end. """ if start == end: return start start += "\0" end += "\0" midpoint = [] expected_max = 127 for i in xrange(min(len(start), len(end))): if start[i] == end[i]: midpoint.append(start[i]) else: ord_sum = ord(start[i]) + ord(end[i]) midpoint.append(unichr(ord_sum / 2)) if ord_sum % 2: if len(start) > i + 1: ord_start = ord(start[i+1]) else: ord_start = 0 if ord_start < expected_max: ord_split = (expected_max + ord_start) / 2 else: ord_split = (0xFFFF + ord_start) / 2 midpoint.append(unichr(ord_split)) break return "".join(midpoint) @staticmethod def split_keys(key_start, key_end, batch_size): """Return a key that is between key_start and key_end inclusive. This method compares components of the ancestor paths of key_start and key_end. The first place in the path that differs is approximately split in half. If the kind components differ, a new non-existent kind halfway between the two is used to split the space. If the id_or_name components differ, then a new id_or_name that is halfway between the two is selected. If the lower id_or_name is numeric and the upper id_or_name is a string, then the minumum string key u'\0' is used as the split id_or_name. The key that is returned is the shared portion of the ancestor path followed by the generated split component. Args: key_start: A db.Key or ndb.Key instance for the lower end of a range. key_end: A db.Key or ndb.Key instance for the upper end of a range. batch_size: The maximum size of a range that should not be split. Returns: A db.Key instance, k, such that key_start <= k <= key_end. NOTE: Even though ndb.Key instances are accepted as arguments, the return value is always a db.Key instance. """ if ndb is not None: if isinstance(key_start, ndb.Key): key_start = key_start.to_old_key() if isinstance(key_end, ndb.Key): key_end = key_end.to_old_key() assert key_start.app() == key_end.app() assert key_start.namespace() == key_end.namespace() path1 = key_start.to_path() path2 = key_end.to_path() len1 = len(path1) len2 = len(path2) assert len1 % 2 == 0 assert len2 % 2 == 0 out_path = [] min_path_len = min(len1, len2) / 2 for i in xrange(min_path_len): kind1 = path1[2*i] kind2 = path2[2*i] if kind1 != kind2: split_kind = KeyRange.bisect_string_range(kind1, kind2) out_path.append(split_kind) out_path.append(unichr(0)) break last = (len1 == len2 == 2*(i + 1)) id_or_name1 = path1[2*i + 1] id_or_name2 = path2[2*i + 1] id_or_name_split = KeyRange._split_id_or_name( id_or_name1, id_or_name2, batch_size, last) if id_or_name1 == id_or_name_split: out_path.append(kind1) out_path.append(id_or_name1) else: out_path.append(kind1) out_path.append(id_or_name_split) break return db.Key.from_path( *out_path, **{"_app": key_start.app(), "namespace": key_start.namespace()}) @staticmethod def _split_id_or_name(id_or_name1, id_or_name2, batch_size, maintain_batches): """Return an id_or_name that is between id_or_name1 an id_or_name2. Attempts to split the range [id_or_name1, id_or_name2] in half, unless maintain_batches is true and the size of the range [id_or_name1, id_or_name2] is less than or equal to batch_size. Args: id_or_name1: A number or string or the id_or_name component of a key id_or_name2: A number or string or the id_or_name component of a key batch_size: The range size that will not be split if maintain_batches is true. maintain_batches: A boolean for whether to keep small ranges intact. Returns: An id_or_name such that id_or_name1 <= id_or_name <= id_or_name2. """ if (isinstance(id_or_name1, (int, long)) and isinstance(id_or_name2, (int, long))): if not maintain_batches or id_or_name2 - id_or_name1 > batch_size: return (id_or_name1 + id_or_name2) / 2 else: return id_or_name1 elif (isinstance(id_or_name1, basestring) and isinstance(id_or_name2, basestring)): return KeyRange.bisect_string_range(id_or_name1, id_or_name2) else: if (not isinstance(id_or_name1, (int, long)) or not isinstance(id_or_name2, basestring)): raise KeyRangeError("Wrong key order: %r, %r" % (id_or_name1, id_or_name2)) zero_ch = unichr(0) if id_or_name2 == zero_ch: return (id_or_name1 + 2**63 - 1) / 2 return zero_ch @staticmethod def guess_end_key(kind, key_start, probe_count=30, split_rate=5): """Guess the end of a key range with a binary search of probe queries. When the 'key_start' parameter has a key hierarchy, this function will only determine the key range for keys in a similar hierarchy. That means if the keys are in the form: kind=Foo, name=bar/kind=Stuff, name=meep only this range will be probed: kind=Foo, name=*/kind=Stuff, name=* That means other entities of kind 'Stuff' that are children of another parent entity kind will be skipped: kind=Other, name=cookie/kind=Stuff, name=meep Args: key_start: The starting key of the search range. In most cases this should be id = 0 or name = '\0'. May be db.Key or ndb.Key. kind: String name of the entity kind. probe_count: Optional, how many probe queries to run. split_rate: Exponential rate to use for splitting the range on the way down from the full key space. For smaller ranges this should be higher so more of the keyspace is skipped on initial descent. Returns: db.Key that is guaranteed to be as high or higher than the highest key existing for this Kind. Doing a query between 'key_start' and this returned Key (inclusive) will contain all entities of this Kind. NOTE: Even though an ndb.Key instance is accepted as argument, the return value is always a db.Key instance. """ if ndb is not None: if isinstance(key_start, ndb.Key): key_start = key_start.to_old_key() app = key_start.app() namespace = key_start.namespace() full_path = key_start.to_path() for index, piece in enumerate(full_path): if index % 2 == 0: continue elif isinstance(piece, basestring): full_path[index] = u"\xffff" else: full_path[index] = 2**63 - 1 key_end = db.Key.from_path(*full_path, **{"_app": app, "namespace": namespace}) split_key = key_end for i in xrange(probe_count): for j in xrange(split_rate): split_key = KeyRange.split_keys(key_start, split_key, 1) results = datastore.Query( kind, {"__key__ >": split_key}, namespace=namespace, _app=app, keys_only=True).Get(1) if results: if results[0].name() and not key_start.name(): return KeyRange.guess_end_key( kind, results[0], probe_count - 1, split_rate) else: split_rate = 1 key_start = results[0] split_key = key_end else: key_end = split_key return key_end @classmethod def compute_split_points(cls, kind, count): """Computes a set of KeyRanges that are split points for a kind. Args: kind: String with the entity kind to split. count: Number of non-overlapping KeyRanges to generate. Returns: A list of KeyRange objects that are non-overlapping. At most "count" + 1 KeyRange objects will be returned. At least one will be returned. """ query = datastore.Query(kind=kind, keys_only=True) query.Order("__scatter__") random_keys = query.Get(count) if not random_keys: return [cls()] random_keys.sort() key_ranges = [] key_ranges.append(cls( key_start=None, key_end=random_keys[0], direction=cls.ASC, include_start=False, include_end=False)) for i in xrange(0, len(random_keys) - 1): key_ranges.append(cls( key_start=random_keys[i], key_end=random_keys[i + 1], direction=cls.ASC, include_start=True, include_end=False)) key_ranges.append(cls( key_start=random_keys[-1], key_end=None, direction=cls.ASC, include_start=True, include_end=False)) return key_ranges def to_json(self): """Serialize KeyRange to json. Returns: string with KeyRange json representation. """ if simplejson is None: raise SimplejsonUnavailableError( "JSON functionality requires json or simplejson to be available") def key_to_str(key): if key: return str(key) else: return None obj_dict = { "direction": self.direction, "key_start": key_to_str(self.key_start), "key_end": key_to_str(self.key_end), "include_start": self.include_start, "include_end": self.include_end, "namespace": self.namespace, } if self._app: obj_dict["_app"] = self._app return simplejson.dumps(obj_dict, sort_keys=True) @staticmethod def from_json(json_str): """Deserialize KeyRange from its json representation. Args: json_str: string with json representation created by key_range_to_json. Returns: deserialized KeyRange instance. """ if simplejson is None: raise SimplejsonUnavailableError( "JSON functionality requires json or simplejson to be available") def key_from_str(key_str): if key_str: return db.Key(key_str) else: return None json = simplejson.loads(json_str) return KeyRange(key_from_str(json["key_start"]), key_from_str(json["key_end"]), json["direction"], json["include_start"], json["include_end"], json.get("namespace"), _app=json.get("_app"))
mit
wuxue/altanalyze
mpmath/calculus/quadrature.py
17
38274
import math from ..libmp.backend import xrange class QuadratureRule(object): """ Quadrature rules are implemented using this class, in order to simplify the code and provide a common infrastructure for tasks such as error estimation and node caching. You can implement a custom quadrature rule by subclassing :class:`QuadratureRule` and implementing the appropriate methods. The subclass can then be used by :func:`~mpmath.quad` by passing it as the *method* argument. :class:`QuadratureRule` instances are supposed to be singletons. :class:`QuadratureRule` therefore implements instance caching in :func:`~mpmath.__new__`. """ def __init__(self, ctx): self.ctx = ctx self.standard_cache = {} self.transformed_cache = {} self.interval_count = {} def clear(self): """ Delete cached node data. """ self.standard_cache = {} self.transformed_cache = {} self.interval_count = {} def calc_nodes(self, degree, prec, verbose=False): r""" Compute nodes for the standard interval `[-1, 1]`. Subclasses should probably implement only this method, and use :func:`~mpmath.get_nodes` method to retrieve the nodes. """ raise NotImplementedError def get_nodes(self, a, b, degree, prec, verbose=False): """ Return nodes for given interval, degree and precision. The nodes are retrieved from a cache if already computed; otherwise they are computed by calling :func:`~mpmath.calc_nodes` and are then cached. Subclasses should probably not implement this method, but just implement :func:`~mpmath.calc_nodes` for the actual node computation. """ key = (a, b, degree, prec) if key in self.transformed_cache: return self.transformed_cache[key] orig = self.ctx.prec try: self.ctx.prec = prec+20 # Get nodes on standard interval if (degree, prec) in self.standard_cache: nodes = self.standard_cache[degree, prec] else: nodes = self.calc_nodes(degree, prec, verbose) self.standard_cache[degree, prec] = nodes # Transform to general interval nodes = self.transform_nodes(nodes, a, b, verbose) if key in self.interval_count: self.transformed_cache[key] = nodes else: self.interval_count[key] = True finally: self.ctx.prec = orig return nodes def transform_nodes(self, nodes, a, b, verbose=False): r""" Rescale standardized nodes (for `[-1, 1]`) to a general interval `[a, b]`. For a finite interval, a simple linear change of variables is used. Otherwise, the following transformations are used: .. math :: [a, \infty] : t = \frac{1}{x} + (a-1) [-\infty, b] : t = (b+1) - \frac{1}{x} [-\infty, \infty] : t = \frac{x}{\sqrt{1-x^2}} """ ctx = self.ctx a = ctx.convert(a) b = ctx.convert(b) one = ctx.one if (a, b) == (-one, one): return nodes half = ctx.mpf(0.5) new_nodes = [] if ctx.isinf(a) or ctx.isinf(b): if (a, b) == (ctx.ninf, ctx.inf): p05 = -half for x, w in nodes: x2 = x*x px1 = one-x2 spx1 = px1**p05 x = x*spx1 w *= spx1/px1 new_nodes.append((x, w)) elif a == ctx.ninf: b1 = b+1 for x, w in nodes: u = 2/(x+one) x = b1-u w *= half*u**2 new_nodes.append((x, w)) elif b == ctx.inf: a1 = a-1 for x, w in nodes: u = 2/(x+one) x = a1+u w *= half*u**2 new_nodes.append((x, w)) elif a == ctx.inf or b == ctx.ninf: return [(x,-w) for (x,w) in self.transform_nodes(nodes, b, a, verbose)] else: raise NotImplementedError else: # Simple linear change of variables C = (b-a)/2 D = (b+a)/2 for x, w in nodes: new_nodes.append((D+C*x, C*w)) return new_nodes def guess_degree(self, prec): """ Given a desired precision `p` in bits, estimate the degree `m` of the quadrature required to accomplish full accuracy for typical integrals. By default, :func:`~mpmath.quad` will perform up to `m` iterations. The value of `m` should be a slight overestimate, so that "slightly bad" integrals can be dealt with automatically using a few extra iterations. On the other hand, it should not be too big, so :func:`~mpmath.quad` can quit within a reasonable amount of time when it is given an "unsolvable" integral. The default formula used by :func:`~mpmath.guess_degree` is tuned for both :class:`TanhSinh` and :class:`GaussLegendre`. The output is roughly as follows: +---------+---------+ | `p` | `m` | +=========+=========+ | 50 | 6 | +---------+---------+ | 100 | 7 | +---------+---------+ | 500 | 10 | +---------+---------+ | 3000 | 12 | +---------+---------+ This formula is based purely on a limited amount of experimentation and will sometimes be wrong. """ # Expected degree # XXX: use mag g = int(4 + max(0, self.ctx.log(prec/30.0, 2))) # Reasonable "worst case" g += 2 return g def estimate_error(self, results, prec, epsilon): r""" Given results from integrations `[I_1, I_2, \ldots, I_k]` done with a quadrature of rule of degree `1, 2, \ldots, k`, estimate the error of `I_k`. For `k = 2`, we estimate `|I_{\infty}-I_2|` as `|I_2-I_1|`. For `k > 2`, we extrapolate `|I_{\infty}-I_k| \approx |I_{k+1}-I_k|` from `|I_k-I_{k-1}|` and `|I_k-I_{k-2}|` under the assumption that each degree increment roughly doubles the accuracy of the quadrature rule (this is true for both :class:`TanhSinh` and :class:`GaussLegendre`). The extrapolation formula is given by Borwein, Bailey & Girgensohn. Although not very conservative, this method seems to be very robust in practice. """ if len(results) == 2: return abs(results[0]-results[1]) try: if results[-1] == results[-2] == results[-3]: return self.ctx.zero D1 = self.ctx.log(abs(results[-1]-results[-2]), 10) D2 = self.ctx.log(abs(results[-1]-results[-3]), 10) except ValueError: return epsilon D3 = -prec D4 = min(0, max(D1**2/D2, 2*D1, D3)) return self.ctx.mpf(10) ** int(D4) def summation(self, f, points, prec, epsilon, max_degree, verbose=False): """ Main integration function. Computes the 1D integral over the interval specified by *points*. For each subinterval, performs quadrature of degree from 1 up to *max_degree* until :func:`~mpmath.estimate_error` signals convergence. :func:`~mpmath.summation` transforms each subintegration to the standard interval and then calls :func:`~mpmath.sum_next`. """ ctx = self.ctx I = err = ctx.zero for i in xrange(len(points)-1): a, b = points[i], points[i+1] if a == b: continue # XXX: we could use a single variable transformation, # but this is not good in practice. We get better accuracy # by having 0 as an endpoint. if (a, b) == (ctx.ninf, ctx.inf): _f = f f = lambda x: _f(-x) + _f(x) a, b = (ctx.zero, ctx.inf) results = [] for degree in xrange(1, max_degree+1): nodes = self.get_nodes(a, b, degree, prec, verbose) if verbose: print("Integrating from %s to %s (degree %s of %s)" % \ (ctx.nstr(a), ctx.nstr(b), degree, max_degree)) results.append(self.sum_next(f, nodes, degree, prec, results, verbose)) if degree > 1: err = self.estimate_error(results, prec, epsilon) if err <= epsilon: break if verbose: print("Estimated error:", ctx.nstr(err)) I += results[-1] if err > epsilon: if verbose: print("Failed to reach full accuracy. Estimated error:", ctx.nstr(err)) return I, err def sum_next(self, f, nodes, degree, prec, previous, verbose=False): r""" Evaluates the step sum `\sum w_k f(x_k)` where the *nodes* list contains the `(w_k, x_k)` pairs. :func:`~mpmath.summation` will supply the list *results* of values computed by :func:`~mpmath.sum_next` at previous degrees, in case the quadrature rule is able to reuse them. """ return self.ctx.fdot((w, f(x)) for (x,w) in nodes) class TanhSinh(QuadratureRule): r""" This class implements "tanh-sinh" or "doubly exponential" quadrature. This quadrature rule is based on the Euler-Maclaurin integral formula. By performing a change of variables involving nested exponentials / hyperbolic functions (hence the name), the derivatives at the endpoints vanish rapidly. Since the error term in the Euler-Maclaurin formula depends on the derivatives at the endpoints, a simple step sum becomes extremely accurate. In practice, this means that doubling the number of evaluation points roughly doubles the number of accurate digits. Comparison to Gauss-Legendre: * Initial computation of nodes is usually faster * Handles endpoint singularities better * Handles infinite integration intervals better * Is slower for smooth integrands once nodes have been computed The implementation of the tanh-sinh algorithm is based on the description given in Borwein, Bailey & Girgensohn, "Experimentation in Mathematics - Computational Paths to Discovery", A K Peters, 2003, pages 312-313. In the present implementation, a few improvements have been made: * A more efficient scheme is used to compute nodes (exploiting recurrence for the exponential function) * The nodes are computed successively instead of all at once Various documents describing the algorithm are available online, e.g.: * http://crd.lbl.gov/~dhbailey/dhbpapers/dhb-tanh-sinh.pdf * http://users.cs.dal.ca/~jborwein/tanh-sinh.pdf """ def sum_next(self, f, nodes, degree, prec, previous, verbose=False): """ Step sum for tanh-sinh quadrature of degree `m`. We exploit the fact that half of the abscissas at degree `m` are precisely the abscissas from degree `m-1`. Thus reusing the result from the previous level allows a 2x speedup. """ h = self.ctx.mpf(2)**(-degree) # Abscissas overlap, so reusing saves half of the time if previous: S = previous[-1]/(h*2) else: S = self.ctx.zero S += self.ctx.fdot((w,f(x)) for (x,w) in nodes) return h*S def calc_nodes(self, degree, prec, verbose=False): r""" The abscissas and weights for tanh-sinh quadrature of degree `m` are given by .. math:: x_k = \tanh(\pi/2 \sinh(t_k)) w_k = \pi/2 \cosh(t_k) / \cosh(\pi/2 \sinh(t_k))^2 where `t_k = t_0 + hk` for a step length `h \sim 2^{-m}`. The list of nodes is actually infinite, but the weights die off so rapidly that only a few are needed. """ ctx = self.ctx nodes = [] extra = 20 ctx.prec += extra tol = ctx.ldexp(1, -prec-10) pi4 = ctx.pi/4 # For simplicity, we work in steps h = 1/2^n, with the first point # offset so that we can reuse the sum from the previous degree # We define degree 1 to include the "degree 0" steps, including # the point x = 0. (It doesn't work well otherwise; not sure why.) t0 = ctx.ldexp(1, -degree) if degree == 1: #nodes.append((mpf(0), pi4)) #nodes.append((-mpf(0), pi4)) nodes.append((ctx.zero, ctx.pi/2)) h = t0 else: h = t0*2 # Since h is fixed, we can compute the next exponential # by simply multiplying by exp(h) expt0 = ctx.exp(t0) a = pi4 * expt0 b = pi4 / expt0 udelta = ctx.exp(h) urdelta = 1/udelta for k in xrange(0, 20*2**degree+1): # Reference implementation: # t = t0 + k*h # x = tanh(pi/2 * sinh(t)) # w = pi/2 * cosh(t) / cosh(pi/2 * sinh(t))**2 # Fast implementation. Note that c = exp(pi/2 * sinh(t)) c = ctx.exp(a-b) d = 1/c co = (c+d)/2 si = (c-d)/2 x = si / co w = (a+b) / co**2 diff = abs(x-1) if diff <= tol: break nodes.append((x, w)) nodes.append((-x, w)) a *= udelta b *= urdelta if verbose and k % 300 == 150: # Note: the number displayed is rather arbitrary. Should # figure out how to print something that looks more like a # percentage print("Calculating nodes:", ctx.nstr(-ctx.log(diff, 10) / prec)) ctx.prec -= extra return nodes class GaussLegendre(QuadratureRule): """ This class implements Gauss-Legendre quadrature, which is exceptionally efficient for polynomials and polynomial-like (i.e. very smooth) integrands. The abscissas and weights are given by roots and values of Legendre polynomials, which are the orthogonal polynomials on `[-1, 1]` with respect to the unit weight (see :func:`~mpmath.legendre`). In this implementation, we take the "degree" `m` of the quadrature to denote a Gauss-Legendre rule of degree `3 \cdot 2^m` (following Borwein, Bailey & Girgensohn). This way we get quadratic, rather than linear, convergence as the degree is incremented. Comparison to tanh-sinh quadrature: * Is faster for smooth integrands once nodes have been computed * Initial computation of nodes is usually slower * Handles endpoint singularities worse * Handles infinite integration intervals worse """ def calc_nodes(self, degree, prec, verbose=False): """ Calculates the abscissas and weights for Gauss-Legendre quadrature of degree of given degree (actually `3 \cdot 2^m`). """ ctx = self.ctx # It is important that the epsilon is set lower than the # "real" epsilon epsilon = ctx.ldexp(1, -prec-8) # Fairly high precision might be required for accurate # evaluation of the roots orig = ctx.prec ctx.prec = int(prec*1.5) if degree == 1: x = ctx.mpf(3)/5 w = ctx.mpf(5)/9 nodes = [(-x,w),(ctx.zero,ctx.mpf(8)/9),(x,w)] ctx.prec = orig return nodes nodes = [] n = 3*2**(degree-1) upto = n//2 + 1 for j in xrange(1, upto): # Asymptotic formula for the roots r = ctx.mpf(math.cos(math.pi*(j-0.25)/(n+0.5))) # Newton iteration while 1: t1, t2 = 1, 0 # Evaluates the Legendre polynomial using its defining # recurrence relation for j1 in xrange(1,n+1): t3, t2, t1 = t2, t1, ((2*j1-1)*r*t1 - (j1-1)*t2)/j1 t4 = n*(r*t1- t2)/(r**2-1) t5 = r a = t1/t4 r = r - a if abs(a) < epsilon: break x = r w = 2/((1-r**2)*t4**2) if verbose and j % 30 == 15: print("Computing nodes (%i of %i)" % (j, upto)) nodes.append((x, w)) nodes.append((-x, w)) ctx.prec = orig return nodes class QuadratureMethods: def __init__(ctx, *args, **kwargs): ctx._gauss_legendre = GaussLegendre(ctx) ctx._tanh_sinh = TanhSinh(ctx) def quad(ctx, f, *points, **kwargs): r""" Computes a single, double or triple integral over a given 1D interval, 2D rectangle, or 3D cuboid. A basic example:: >>> from mpmath import * >>> mp.dps = 15; mp.pretty = True >>> quad(sin, [0, pi]) 2.0 A basic 2D integral:: >>> f = lambda x, y: cos(x+y/2) >>> quad(f, [-pi/2, pi/2], [0, pi]) 4.0 **Interval format** The integration range for each dimension may be specified using a list or tuple. Arguments are interpreted as follows: ``quad(f, [x1, x2])`` -- calculates `\int_{x_1}^{x_2} f(x) \, dx` ``quad(f, [x1, x2], [y1, y2])`` -- calculates `\int_{x_1}^{x_2} \int_{y_1}^{y_2} f(x,y) \, dy \, dx` ``quad(f, [x1, x2], [y1, y2], [z1, z2])`` -- calculates `\int_{x_1}^{x_2} \int_{y_1}^{y_2} \int_{z_1}^{z_2} f(x,y,z) \, dz \, dy \, dx` Endpoints may be finite or infinite. An interval descriptor may also contain more than two points. In this case, the integration is split into subintervals, between each pair of consecutive points. This is useful for dealing with mid-interval discontinuities, or integrating over large intervals where the function is irregular or oscillates. **Options** :func:`~mpmath.quad` recognizes the following keyword arguments: *method* Chooses integration algorithm (described below). *error* If set to true, :func:`~mpmath.quad` returns `(v, e)` where `v` is the integral and `e` is the estimated error. *maxdegree* Maximum degree of the quadrature rule to try before quitting. *verbose* Print details about progress. **Algorithms** Mpmath presently implements two integration algorithms: tanh-sinh quadrature and Gauss-Legendre quadrature. These can be selected using *method='tanh-sinh'* or *method='gauss-legendre'* or by passing the classes *method=TanhSinh*, *method=GaussLegendre*. The functions :func:`~mpmath.quadts` and :func:`~mpmath.quadgl` are also available as shortcuts. Both algorithms have the property that doubling the number of evaluation points roughly doubles the accuracy, so both are ideal for high precision quadrature (hundreds or thousands of digits). At high precision, computing the nodes and weights for the integration can be expensive (more expensive than computing the function values). To make repeated integrations fast, nodes are automatically cached. The advantages of the tanh-sinh algorithm are that it tends to handle endpoint singularities well, and that the nodes are cheap to compute on the first run. For these reasons, it is used by :func:`~mpmath.quad` as the default algorithm. Gauss-Legendre quadrature often requires fewer function evaluations, and is therefore often faster for repeated use, but the algorithm does not handle endpoint singularities as well and the nodes are more expensive to compute. Gauss-Legendre quadrature can be a better choice if the integrand is smooth and repeated integrations are required (e.g. for multiple integrals). See the documentation for :class:`TanhSinh` and :class:`GaussLegendre` for additional details. **Examples of 1D integrals** Intervals may be infinite or half-infinite. The following two examples evaluate the limits of the inverse tangent function (`\int 1/(1+x^2) = \tan^{-1} x`), and the Gaussian integral `\int_{\infty}^{\infty} \exp(-x^2)\,dx = \sqrt{\pi}`:: >>> mp.dps = 15 >>> quad(lambda x: 2/(x**2+1), [0, inf]) 3.14159265358979 >>> quad(lambda x: exp(-x**2), [-inf, inf])**2 3.14159265358979 Integrals can typically be resolved to high precision. The following computes 50 digits of `\pi` by integrating the area of the half-circle defined by `x^2 + y^2 \le 1`, `-1 \le x \le 1`, `y \ge 0`:: >>> mp.dps = 50 >>> 2*quad(lambda x: sqrt(1-x**2), [-1, 1]) 3.1415926535897932384626433832795028841971693993751 One can just as well compute 1000 digits (output truncated):: >>> mp.dps = 1000 >>> 2*quad(lambda x: sqrt(1-x**2), [-1, 1]) #doctest:+ELLIPSIS 3.141592653589793238462643383279502884...216420198 Complex integrals are supported. The following computes a residue at `z = 0` by integrating counterclockwise along the diamond-shaped path from `1` to `+i` to `-1` to `-i` to `1`:: >>> mp.dps = 15 >>> chop(quad(lambda z: 1/z, [1,j,-1,-j,1])) (0.0 + 6.28318530717959j) **Examples of 2D and 3D integrals** Here are several nice examples of analytically solvable 2D integrals (taken from MathWorld [1]) that can be evaluated to high precision fairly rapidly by :func:`~mpmath.quad`:: >>> mp.dps = 30 >>> f = lambda x, y: (x-1)/((1-x*y)*log(x*y)) >>> quad(f, [0, 1], [0, 1]) 0.577215664901532860606512090082 >>> +euler 0.577215664901532860606512090082 >>> f = lambda x, y: 1/sqrt(1+x**2+y**2) >>> quad(f, [-1, 1], [-1, 1]) 3.17343648530607134219175646705 >>> 4*log(2+sqrt(3))-2*pi/3 3.17343648530607134219175646705 >>> f = lambda x, y: 1/(1-x**2 * y**2) >>> quad(f, [0, 1], [0, 1]) 1.23370055013616982735431137498 >>> pi**2 / 8 1.23370055013616982735431137498 >>> quad(lambda x, y: 1/(1-x*y), [0, 1], [0, 1]) 1.64493406684822643647241516665 >>> pi**2 / 6 1.64493406684822643647241516665 Multiple integrals may be done over infinite ranges:: >>> mp.dps = 15 >>> print(quad(lambda x,y: exp(-x-y), [0, inf], [1, inf])) 0.367879441171442 >>> print(1/e) 0.367879441171442 For nonrectangular areas, one can call :func:`~mpmath.quad` recursively. For example, we can replicate the earlier example of calculating `\pi` by integrating over the unit-circle, and actually use double quadrature to actually measure the area circle:: >>> f = lambda x: quad(lambda y: 1, [-sqrt(1-x**2), sqrt(1-x**2)]) >>> quad(f, [-1, 1]) 3.14159265358979 Here is a simple triple integral:: >>> mp.dps = 15 >>> f = lambda x,y,z: x*y/(1+z) >>> quad(f, [0,1], [0,1], [1,2], method='gauss-legendre') 0.101366277027041 >>> (log(3)-log(2))/4 0.101366277027041 **Singularities** Both tanh-sinh and Gauss-Legendre quadrature are designed to integrate smooth (infinitely differentiable) functions. Neither algorithm copes well with mid-interval singularities (such as mid-interval discontinuities in `f(x)` or `f'(x)`). The best solution is to split the integral into parts:: >>> mp.dps = 15 >>> quad(lambda x: abs(sin(x)), [0, 2*pi]) # Bad 3.99900894176779 >>> quad(lambda x: abs(sin(x)), [0, pi, 2*pi]) # Good 4.0 The tanh-sinh rule often works well for integrands having a singularity at one or both endpoints:: >>> mp.dps = 15 >>> quad(log, [0, 1], method='tanh-sinh') # Good -1.0 >>> quad(log, [0, 1], method='gauss-legendre') # Bad -0.999932197413801 However, the result may still be inaccurate for some functions:: >>> quad(lambda x: 1/sqrt(x), [0, 1], method='tanh-sinh') 1.99999999946942 This problem is not due to the quadrature rule per se, but to numerical amplification of errors in the nodes. The problem can be circumvented by temporarily increasing the precision:: >>> mp.dps = 30 >>> a = quad(lambda x: 1/sqrt(x), [0, 1], method='tanh-sinh') >>> mp.dps = 15 >>> +a 2.0 **Highly variable functions** For functions that are smooth (in the sense of being infinitely differentiable) but contain sharp mid-interval peaks or many "bumps", :func:`~mpmath.quad` may fail to provide full accuracy. For example, with default settings, :func:`~mpmath.quad` is able to integrate `\sin(x)` accurately over an interval of length 100 but not over length 1000:: >>> quad(sin, [0, 100]); 1-cos(100) # Good 0.137681127712316 0.137681127712316 >>> quad(sin, [0, 1000]); 1-cos(1000) # Bad -37.8587612408485 0.437620923709297 One solution is to break the integration into 10 intervals of length 100:: >>> quad(sin, linspace(0, 1000, 10)) # Good 0.437620923709297 Another is to increase the degree of the quadrature:: >>> quad(sin, [0, 1000], maxdegree=10) # Also good 0.437620923709297 Whether splitting the interval or increasing the degree is more efficient differs from case to case. Another example is the function `1/(1+x^2)`, which has a sharp peak centered around `x = 0`:: >>> f = lambda x: 1/(1+x**2) >>> quad(f, [-100, 100]) # Bad 3.64804647105268 >>> quad(f, [-100, 100], maxdegree=10) # Good 3.12159332021646 >>> quad(f, [-100, 0, 100]) # Also good 3.12159332021646 **References** 1. http://mathworld.wolfram.com/DoubleIntegral.html """ rule = kwargs.get('method', 'tanh-sinh') if type(rule) is str: if rule == 'tanh-sinh': rule = ctx._tanh_sinh elif rule == 'gauss-legendre': rule = ctx._gauss_legendre else: raise ValueError("unknown quadrature rule: %s" % rule) else: rule = rule(ctx) verbose = kwargs.get('verbose') dim = len(points) orig = prec = ctx.prec epsilon = ctx.eps/8 m = kwargs.get('maxdegree') or rule.guess_degree(prec) points = [ctx._as_points(p) for p in points] try: ctx.prec += 20 if dim == 1: v, err = rule.summation(f, points[0], prec, epsilon, m, verbose) elif dim == 2: v, err = rule.summation(lambda x: \ rule.summation(lambda y: f(x,y), \ points[1], prec, epsilon, m)[0], points[0], prec, epsilon, m, verbose) elif dim == 3: v, err = rule.summation(lambda x: \ rule.summation(lambda y: \ rule.summation(lambda z: f(x,y,z), \ points[2], prec, epsilon, m)[0], points[1], prec, epsilon, m)[0], points[0], prec, epsilon, m, verbose) else: raise NotImplementedError("quadrature must have dim 1, 2 or 3") finally: ctx.prec = orig if kwargs.get("error"): return +v, err return +v def quadts(ctx, *args, **kwargs): """ Performs tanh-sinh quadrature. The call quadts(func, *points, ...) is simply a shortcut for: quad(func, *points, ..., method=TanhSinh) For example, a single integral and a double integral: quadts(lambda x: exp(cos(x)), [0, 1]) quadts(lambda x, y: exp(cos(x+y)), [0, 1], [0, 1]) See the documentation for quad for information about how points arguments and keyword arguments are parsed. See documentation for TanhSinh for algorithmic information about tanh-sinh quadrature. """ kwargs['method'] = 'tanh-sinh' return ctx.quad(*args, **kwargs) def quadgl(ctx, *args, **kwargs): """ Performs Gauss-Legendre quadrature. The call quadgl(func, *points, ...) is simply a shortcut for: quad(func, *points, ..., method=GaussLegendre) For example, a single integral and a double integral: quadgl(lambda x: exp(cos(x)), [0, 1]) quadgl(lambda x, y: exp(cos(x+y)), [0, 1], [0, 1]) See the documentation for quad for information about how points arguments and keyword arguments are parsed. See documentation for TanhSinh for algorithmic information about tanh-sinh quadrature. """ kwargs['method'] = 'gauss-legendre' return ctx.quad(*args, **kwargs) def quadosc(ctx, f, interval, omega=None, period=None, zeros=None): r""" Calculates .. math :: I = \int_a^b f(x) dx where at least one of `a` and `b` is infinite and where `f(x) = g(x) \cos(\omega x + \phi)` for some slowly decreasing function `g(x)`. With proper input, :func:`~mpmath.quadosc` can also handle oscillatory integrals where the oscillation rate is different from a pure sine or cosine wave. In the standard case when `|a| < \infty, b = \infty`, :func:`~mpmath.quadosc` works by evaluating the infinite series .. math :: I = \int_a^{x_1} f(x) dx + \sum_{k=1}^{\infty} \int_{x_k}^{x_{k+1}} f(x) dx where `x_k` are consecutive zeros (alternatively some other periodic reference point) of `f(x)`. Accordingly, :func:`~mpmath.quadosc` requires information about the zeros of `f(x)`. For a periodic function, you can specify the zeros by either providing the angular frequency `\omega` (*omega*) or the *period* `2 \pi/\omega`. In general, you can specify the `n`-th zero by providing the *zeros* arguments. Below is an example of each:: >>> from mpmath import * >>> mp.dps = 15; mp.pretty = True >>> f = lambda x: sin(3*x)/(x**2+1) >>> quadosc(f, [0,inf], omega=3) 0.37833007080198 >>> quadosc(f, [0,inf], period=2*pi/3) 0.37833007080198 >>> quadosc(f, [0,inf], zeros=lambda n: pi*n/3) 0.37833007080198 >>> (ei(3)*exp(-3)-exp(3)*ei(-3))/2 # Computed by Mathematica 0.37833007080198 Note that *zeros* was specified to multiply `n` by the *half-period*, not the full period. In theory, it does not matter whether each partial integral is done over a half period or a full period. However, if done over half-periods, the infinite series passed to :func:`~mpmath.nsum` becomes an *alternating series* and this typically makes the extrapolation much more efficient. Here is an example of an integration over the entire real line, and a half-infinite integration starting at `-\infty`:: >>> quadosc(lambda x: cos(x)/(1+x**2), [-inf, inf], omega=1) 1.15572734979092 >>> pi/e 1.15572734979092 >>> quadosc(lambda x: cos(x)/x**2, [-inf, -1], period=2*pi) -0.0844109505595739 >>> cos(1)+si(1)-pi/2 -0.0844109505595738 Of course, the integrand may contain a complex exponential just as well as a real sine or cosine:: >>> quadosc(lambda x: exp(3*j*x)/(1+x**2), [-inf,inf], omega=3) (0.156410688228254 + 0.0j) >>> pi/e**3 0.156410688228254 >>> quadosc(lambda x: exp(3*j*x)/(2+x+x**2), [-inf,inf], omega=3) (0.00317486988463794 - 0.0447701735209082j) >>> 2*pi/sqrt(7)/exp(3*(j+sqrt(7))/2) (0.00317486988463794 - 0.0447701735209082j) **Non-periodic functions** If `f(x) = g(x) h(x)` for some function `h(x)` that is not strictly periodic, *omega* or *period* might not work, and it might be necessary to use *zeros*. A notable exception can be made for Bessel functions which, though not periodic, are "asymptotically periodic" in a sufficiently strong sense that the sum extrapolation will work out:: >>> quadosc(j0, [0, inf], period=2*pi) 1.0 >>> quadosc(j1, [0, inf], period=2*pi) 1.0 More properly, one should provide the exact Bessel function zeros:: >>> j0zero = lambda n: findroot(j0, pi*(n-0.25)) >>> quadosc(j0, [0, inf], zeros=j0zero) 1.0 For an example where *zeros* becomes necessary, consider the complete Fresnel integrals .. math :: \int_0^{\infty} \cos x^2\,dx = \int_0^{\infty} \sin x^2\,dx = \sqrt{\frac{\pi}{8}}. Although the integrands do not decrease in magnitude as `x \to \infty`, the integrals are convergent since the oscillation rate increases (causing consecutive periods to asymptotically cancel out). These integrals are virtually impossible to calculate to any kind of accuracy using standard quadrature rules. However, if one provides the correct asymptotic distribution of zeros (`x_n \sim \sqrt{n}`), :func:`~mpmath.quadosc` works:: >>> mp.dps = 30 >>> f = lambda x: cos(x**2) >>> quadosc(f, [0,inf], zeros=lambda n:sqrt(pi*n)) 0.626657068657750125603941321203 >>> f = lambda x: sin(x**2) >>> quadosc(f, [0,inf], zeros=lambda n:sqrt(pi*n)) 0.626657068657750125603941321203 >>> sqrt(pi/8) 0.626657068657750125603941321203 (Interestingly, these integrals can still be evaluated if one places some other constant than `\pi` in the square root sign.) In general, if `f(x) \sim g(x) \cos(h(x))`, the zeros follow the inverse-function distribution `h^{-1}(x)`:: >>> mp.dps = 15 >>> f = lambda x: sin(exp(x)) >>> quadosc(f, [1,inf], zeros=lambda n: log(n)) -0.25024394235267 >>> pi/2-si(e) -0.250243942352671 **Non-alternating functions** If the integrand oscillates around a positive value, without alternating signs, the extrapolation might fail. A simple trick that sometimes works is to multiply or divide the frequency by 2:: >>> f = lambda x: 1/x**2+sin(x)/x**4 >>> quadosc(f, [1,inf], omega=1) # Bad 1.28642190869861 >>> quadosc(f, [1,inf], omega=0.5) # Perfect 1.28652953559617 >>> 1+(cos(1)+ci(1)+sin(1))/6 1.28652953559617 **Fast decay** :func:`~mpmath.quadosc` is primarily useful for slowly decaying integrands. If the integrand decreases exponentially or faster, :func:`~mpmath.quad` will likely handle it without trouble (and generally be much faster than :func:`~mpmath.quadosc`):: >>> quadosc(lambda x: cos(x)/exp(x), [0, inf], omega=1) 0.5 >>> quad(lambda x: cos(x)/exp(x), [0, inf]) 0.5 """ a, b = ctx._as_points(interval) a = ctx.convert(a) b = ctx.convert(b) if [omega, period, zeros].count(None) != 2: raise ValueError( \ "must specify exactly one of omega, period, zeros") if a == ctx.ninf and b == ctx.inf: s1 = ctx.quadosc(f, [a, 0], omega=omega, zeros=zeros, period=period) s2 = ctx.quadosc(f, [0, b], omega=omega, zeros=zeros, period=period) return s1 + s2 if a == ctx.ninf: if zeros: return ctx.quadosc(lambda x:f(-x), [-b,-a], lambda n: zeros(-n)) else: return ctx.quadosc(lambda x:f(-x), [-b,-a], omega=omega, period=period) if b != ctx.inf: raise ValueError("quadosc requires an infinite integration interval") if not zeros: if omega: period = 2*ctx.pi/omega zeros = lambda n: n*period/2 #for n in range(1,10): # p = zeros(n) # if p > a: # break #if n >= 9: # raise ValueError("zeros do not appear to be correctly indexed") n = 1 s = ctx.quadgl(f, [a, zeros(n)]) def term(k): return ctx.quadgl(f, [zeros(k), zeros(k+1)]) s += ctx.nsum(term, [n, ctx.inf]) return s if __name__ == '__main__': import doctest doctest.testmod()
apache-2.0
morissette/devopsdays-hackathon-2016
venv/lib/python2.7/site-packages/botocore/vendored/requests/packages/chardet/gb2312freq.py
3132
36011
######################## 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 ######################### # GB2312 most frequently used character table # # Char to FreqOrder table , from hz6763 # 512 --> 0.79 -- 0.79 # 1024 --> 0.92 -- 0.13 # 2048 --> 0.98 -- 0.06 # 6768 --> 1.00 -- 0.02 # # Ideal Distribution Ratio = 0.79135/(1-0.79135) = 3.79 # Random Distribution Ration = 512 / (3755 - 512) = 0.157 # # Typical Distribution Ratio about 25% of Ideal one, still much higher that RDR GB2312_TYPICAL_DISTRIBUTION_RATIO = 0.9 GB2312_TABLE_SIZE = 3760 GB2312CharToFreqOrder = ( 1671, 749,1443,2364,3924,3807,2330,3921,1704,3463,2691,1511,1515, 572,3191,2205, 2361, 224,2558, 479,1711, 963,3162, 440,4060,1905,2966,2947,3580,2647,3961,3842, 2204, 869,4207, 970,2678,5626,2944,2956,1479,4048, 514,3595, 588,1346,2820,3409, 249,4088,1746,1873,2047,1774, 581,1813, 358,1174,3590,1014,1561,4844,2245, 670, 1636,3112, 889,1286, 953, 556,2327,3060,1290,3141, 613, 185,3477,1367, 850,3820, 1715,2428,2642,2303,2732,3041,2562,2648,3566,3946,1349, 388,3098,2091,1360,3585, 152,1687,1539, 738,1559, 59,1232,2925,2267,1388,1249,1741,1679,2960, 151,1566, 1125,1352,4271, 924,4296, 385,3166,4459, 310,1245,2850, 70,3285,2729,3534,3575, 2398,3298,3466,1960,2265, 217,3647, 864,1909,2084,4401,2773,1010,3269,5152, 853, 3051,3121,1244,4251,1895, 364,1499,1540,2313,1180,3655,2268, 562, 715,2417,3061, 544, 336,3768,2380,1752,4075, 950, 280,2425,4382, 183,2759,3272, 333,4297,2155, 1688,2356,1444,1039,4540, 736,1177,3349,2443,2368,2144,2225, 565, 196,1482,3406, 927,1335,4147, 692, 878,1311,1653,3911,3622,1378,4200,1840,2969,3149,2126,1816, 2534,1546,2393,2760, 737,2494, 13, 447, 245,2747, 38,2765,2129,2589,1079, 606, 360, 471,3755,2890, 404, 848, 699,1785,1236, 370,2221,1023,3746,2074,2026,2023, 2388,1581,2119, 812,1141,3091,2536,1519, 804,2053, 406,1596,1090, 784, 548,4414, 1806,2264,2936,1100, 343,4114,5096, 622,3358, 743,3668,1510,1626,5020,3567,2513, 3195,4115,5627,2489,2991, 24,2065,2697,1087,2719, 48,1634, 315, 68, 985,2052, 198,2239,1347,1107,1439, 597,2366,2172, 871,3307, 919,2487,2790,1867, 236,2570, 1413,3794, 906,3365,3381,1701,1982,1818,1524,2924,1205, 616,2586,2072,2004, 575, 253,3099, 32,1365,1182, 197,1714,2454,1201, 554,3388,3224,2748, 756,2587, 250, 2567,1507,1517,3529,1922,2761,2337,3416,1961,1677,2452,2238,3153, 615, 911,1506, 1474,2495,1265,1906,2749,3756,3280,2161, 898,2714,1759,3450,2243,2444, 563, 26, 3286,2266,3769,3344,2707,3677, 611,1402, 531,1028,2871,4548,1375, 261,2948, 835, 1190,4134, 353, 840,2684,1900,3082,1435,2109,1207,1674, 329,1872,2781,4055,2686, 2104, 608,3318,2423,2957,2768,1108,3739,3512,3271,3985,2203,1771,3520,1418,2054, 1681,1153, 225,1627,2929, 162,2050,2511,3687,1954, 124,1859,2431,1684,3032,2894, 585,4805,3969,2869,2704,2088,2032,2095,3656,2635,4362,2209, 256, 518,2042,2105, 3777,3657, 643,2298,1148,1779, 190, 989,3544, 414, 11,2135,2063,2979,1471, 403, 3678, 126, 770,1563, 671,2499,3216,2877, 600,1179, 307,2805,4937,1268,1297,2694, 252,4032,1448,1494,1331,1394, 127,2256, 222,1647,1035,1481,3056,1915,1048, 873, 3651, 210, 33,1608,2516, 200,1520, 415, 102, 0,3389,1287, 817, 91,3299,2940, 836,1814, 549,2197,1396,1669,2987,3582,2297,2848,4528,1070, 687, 20,1819, 121, 1552,1364,1461,1968,2617,3540,2824,2083, 177, 948,4938,2291, 110,4549,2066, 648, 3359,1755,2110,2114,4642,4845,1693,3937,3308,1257,1869,2123, 208,1804,3159,2992, 2531,2549,3361,2418,1350,2347,2800,2568,1291,2036,2680, 72, 842,1990, 212,1233, 1154,1586, 75,2027,3410,4900,1823,1337,2710,2676, 728,2810,1522,3026,4995, 157, 755,1050,4022, 710, 785,1936,2194,2085,1406,2777,2400, 150,1250,4049,1206, 807, 1910, 534, 529,3309,1721,1660, 274, 39,2827, 661,2670,1578, 925,3248,3815,1094, 4278,4901,4252, 41,1150,3747,2572,2227,4501,3658,4902,3813,3357,3617,2884,2258, 887, 538,4187,3199,1294,2439,3042,2329,2343,2497,1255, 107, 543,1527, 521,3478, 3568, 194,5062, 15, 961,3870,1241,1192,2664, 66,5215,3260,2111,1295,1127,2152, 3805,4135, 901,1164,1976, 398,1278, 530,1460, 748, 904,1054,1966,1426, 53,2909, 509, 523,2279,1534, 536,1019, 239,1685, 460,2353, 673,1065,2401,3600,4298,2272, 1272,2363, 284,1753,3679,4064,1695, 81, 815,2677,2757,2731,1386, 859, 500,4221, 2190,2566, 757,1006,2519,2068,1166,1455, 337,2654,3203,1863,1682,1914,3025,1252, 1409,1366, 847, 714,2834,2038,3209, 964,2970,1901, 885,2553,1078,1756,3049, 301, 1572,3326, 688,2130,1996,2429,1805,1648,2930,3421,2750,3652,3088, 262,1158,1254, 389,1641,1812, 526,1719, 923,2073,1073,1902, 468, 489,4625,1140, 857,2375,3070, 3319,2863, 380, 116,1328,2693,1161,2244, 273,1212,1884,2769,3011,1775,1142, 461, 3066,1200,2147,2212, 790, 702,2695,4222,1601,1058, 434,2338,5153,3640, 67,2360, 4099,2502, 618,3472,1329, 416,1132, 830,2782,1807,2653,3211,3510,1662, 192,2124, 296,3979,1739,1611,3684, 23, 118, 324, 446,1239,1225, 293,2520,3814,3795,2535, 3116, 17,1074, 467,2692,2201, 387,2922, 45,1326,3055,1645,3659,2817, 958, 243, 1903,2320,1339,2825,1784,3289, 356, 576, 865,2315,2381,3377,3916,1088,3122,1713, 1655, 935, 628,4689,1034,1327, 441, 800, 720, 894,1979,2183,1528,5289,2702,1071, 4046,3572,2399,1571,3281, 79, 761,1103, 327, 134, 758,1899,1371,1615, 879, 442, 215,2605,2579, 173,2048,2485,1057,2975,3317,1097,2253,3801,4263,1403,1650,2946, 814,4968,3487,1548,2644,1567,1285, 2, 295,2636, 97, 946,3576, 832, 141,4257, 3273, 760,3821,3521,3156,2607, 949,1024,1733,1516,1803,1920,2125,2283,2665,3180, 1501,2064,3560,2171,1592, 803,3518,1416, 732,3897,4258,1363,1362,2458, 119,1427, 602,1525,2608,1605,1639,3175, 694,3064, 10, 465, 76,2000,4846,4208, 444,3781, 1619,3353,2206,1273,3796, 740,2483, 320,1723,2377,3660,2619,1359,1137,1762,1724, 2345,2842,1850,1862, 912, 821,1866, 612,2625,1735,2573,3369,1093, 844, 89, 937, 930,1424,3564,2413,2972,1004,3046,3019,2011, 711,3171,1452,4178, 428, 801,1943, 432, 445,2811, 206,4136,1472, 730, 349, 73, 397,2802,2547, 998,1637,1167, 789, 396,3217, 154,1218, 716,1120,1780,2819,4826,1931,3334,3762,2139,1215,2627, 552, 3664,3628,3232,1405,2383,3111,1356,2652,3577,3320,3101,1703, 640,1045,1370,1246, 4996, 371,1575,2436,1621,2210, 984,4033,1734,2638, 16,4529, 663,2755,3255,1451, 3917,2257,1253,1955,2234,1263,2951, 214,1229, 617, 485, 359,1831,1969, 473,2310, 750,2058, 165, 80,2864,2419, 361,4344,2416,2479,1134, 796,3726,1266,2943, 860, 2715, 938, 390,2734,1313,1384, 248, 202, 877,1064,2854, 522,3907, 279,1602, 297, 2357, 395,3740, 137,2075, 944,4089,2584,1267,3802, 62,1533,2285, 178, 176, 780, 2440, 201,3707, 590, 478,1560,4354,2117,1075, 30, 74,4643,4004,1635,1441,2745, 776,2596, 238,1077,1692,1912,2844, 605, 499,1742,3947, 241,3053, 980,1749, 936, 2640,4511,2582, 515,1543,2162,5322,2892,2993, 890,2148,1924, 665,1827,3581,1032, 968,3163, 339,1044,1896, 270, 583,1791,1720,4367,1194,3488,3669, 43,2523,1657, 163,2167, 290,1209,1622,3378, 550, 634,2508,2510, 695,2634,2384,2512,1476,1414, 220,1469,2341,2138,2852,3183,2900,4939,2865,3502,1211,3680, 854,3227,1299,2976, 3172, 186,2998,1459, 443,1067,3251,1495, 321,1932,3054, 909, 753,1410,1828, 436, 2441,1119,1587,3164,2186,1258, 227, 231,1425,1890,3200,3942, 247, 959, 725,5254, 2741, 577,2158,2079, 929, 120, 174, 838,2813, 591,1115, 417,2024, 40,3240,1536, 1037, 291,4151,2354, 632,1298,2406,2500,3535,1825,1846,3451, 205,1171, 345,4238, 18,1163, 811, 685,2208,1217, 425,1312,1508,1175,4308,2552,1033, 587,1381,3059, 2984,3482, 340,1316,4023,3972, 792,3176, 519, 777,4690, 918, 933,4130,2981,3741, 90,3360,2911,2200,5184,4550, 609,3079,2030, 272,3379,2736, 363,3881,1130,1447, 286, 779, 357,1169,3350,3137,1630,1220,2687,2391, 747,1277,3688,2618,2682,2601, 1156,3196,5290,4034,3102,1689,3596,3128, 874, 219,2783, 798, 508,1843,2461, 269, 1658,1776,1392,1913,2983,3287,2866,2159,2372, 829,4076, 46,4253,2873,1889,1894, 915,1834,1631,2181,2318, 298, 664,2818,3555,2735, 954,3228,3117, 527,3511,2173, 681,2712,3033,2247,2346,3467,1652, 155,2164,3382, 113,1994, 450, 899, 494, 994, 1237,2958,1875,2336,1926,3727, 545,1577,1550, 633,3473, 204,1305,3072,2410,1956, 2471, 707,2134, 841,2195,2196,2663,3843,1026,4940, 990,3252,4997, 368,1092, 437, 3212,3258,1933,1829, 675,2977,2893, 412, 943,3723,4644,3294,3283,2230,2373,5154, 2389,2241,2661,2323,1404,2524, 593, 787, 677,3008,1275,2059, 438,2709,2609,2240, 2269,2246,1446, 36,1568,1373,3892,1574,2301,1456,3962, 693,2276,5216,2035,1143, 2720,1919,1797,1811,2763,4137,2597,1830,1699,1488,1198,2090, 424,1694, 312,3634, 3390,4179,3335,2252,1214, 561,1059,3243,2295,2561, 975,5155,2321,2751,3772, 472, 1537,3282,3398,1047,2077,2348,2878,1323,3340,3076, 690,2906, 51, 369, 170,3541, 1060,2187,2688,3670,2541,1083,1683, 928,3918, 459, 109,4427, 599,3744,4286, 143, 2101,2730,2490, 82,1588,3036,2121, 281,1860, 477,4035,1238,2812,3020,2716,3312, 1530,2188,2055,1317, 843, 636,1808,1173,3495, 649, 181,1002, 147,3641,1159,2414, 3750,2289,2795, 813,3123,2610,1136,4368, 5,3391,4541,2174, 420, 429,1728, 754, 1228,2115,2219, 347,2223,2733, 735,1518,3003,2355,3134,1764,3948,3329,1888,2424, 1001,1234,1972,3321,3363,1672,1021,1450,1584, 226, 765, 655,2526,3404,3244,2302, 3665, 731, 594,2184, 319,1576, 621, 658,2656,4299,2099,3864,1279,2071,2598,2739, 795,3086,3699,3908,1707,2352,2402,1382,3136,2475,1465,4847,3496,3865,1085,3004, 2591,1084, 213,2287,1963,3565,2250, 822, 793,4574,3187,1772,1789,3050, 595,1484, 1959,2770,1080,2650, 456, 422,2996, 940,3322,4328,4345,3092,2742, 965,2784, 739, 4124, 952,1358,2498,2949,2565, 332,2698,2378, 660,2260,2473,4194,3856,2919, 535, 1260,2651,1208,1428,1300,1949,1303,2942, 433,2455,2450,1251,1946, 614,1269, 641, 1306,1810,2737,3078,2912, 564,2365,1419,1415,1497,4460,2367,2185,1379,3005,1307, 3218,2175,1897,3063, 682,1157,4040,4005,1712,1160,1941,1399, 394, 402,2952,1573, 1151,2986,2404, 862, 299,2033,1489,3006, 346, 171,2886,3401,1726,2932, 168,2533, 47,2507,1030,3735,1145,3370,1395,1318,1579,3609,4560,2857,4116,1457,2529,1965, 504,1036,2690,2988,2405, 745,5871, 849,2397,2056,3081, 863,2359,3857,2096, 99, 1397,1769,2300,4428,1643,3455,1978,1757,3718,1440, 35,4879,3742,1296,4228,2280, 160,5063,1599,2013, 166, 520,3479,1646,3345,3012, 490,1937,1545,1264,2182,2505, 1096,1188,1369,1436,2421,1667,2792,2460,1270,2122, 727,3167,2143, 806,1706,1012, 1800,3037, 960,2218,1882, 805, 139,2456,1139,1521, 851,1052,3093,3089, 342,2039, 744,5097,1468,1502,1585,2087, 223, 939, 326,2140,2577, 892,2481,1623,4077, 982, 3708, 135,2131, 87,2503,3114,2326,1106, 876,1616, 547,2997,2831,2093,3441,4530, 4314, 9,3256,4229,4148, 659,1462,1986,1710,2046,2913,2231,4090,4880,5255,3392, 3274,1368,3689,4645,1477, 705,3384,3635,1068,1529,2941,1458,3782,1509, 100,1656, 2548, 718,2339, 408,1590,2780,3548,1838,4117,3719,1345,3530, 717,3442,2778,3220, 2898,1892,4590,3614,3371,2043,1998,1224,3483, 891, 635, 584,2559,3355, 733,1766, 1729,1172,3789,1891,2307, 781,2982,2271,1957,1580,5773,2633,2005,4195,3097,1535, 3213,1189,1934,5693,3262, 586,3118,1324,1598, 517,1564,2217,1868,1893,4445,3728, 2703,3139,1526,1787,1992,3882,2875,1549,1199,1056,2224,1904,2711,5098,4287, 338, 1993,3129,3489,2689,1809,2815,1997, 957,1855,3898,2550,3275,3057,1105,1319, 627, 1505,1911,1883,3526, 698,3629,3456,1833,1431, 746, 77,1261,2017,2296,1977,1885, 125,1334,1600, 525,1798,1109,2222,1470,1945, 559,2236,1186,3443,2476,1929,1411, 2411,3135,1777,3372,2621,1841,1613,3229, 668,1430,1839,2643,2916, 195,1989,2671, 2358,1387, 629,3205,2293,5256,4439, 123,1310, 888,1879,4300,3021,3605,1003,1162, 3192,2910,2010, 140,2395,2859, 55,1082,2012,2901, 662, 419,2081,1438, 680,2774, 4654,3912,1620,1731,1625,5035,4065,2328, 512,1344, 802,5443,2163,2311,2537, 524, 3399, 98,1155,2103,1918,2606,3925,2816,1393,2465,1504,3773,2177,3963,1478,4346, 180,1113,4655,3461,2028,1698, 833,2696,1235,1322,1594,4408,3623,3013,3225,2040, 3022, 541,2881, 607,3632,2029,1665,1219, 639,1385,1686,1099,2803,3231,1938,3188, 2858, 427, 676,2772,1168,2025, 454,3253,2486,3556, 230,1950, 580, 791,1991,1280, 1086,1974,2034, 630, 257,3338,2788,4903,1017, 86,4790, 966,2789,1995,1696,1131, 259,3095,4188,1308, 179,1463,5257, 289,4107,1248, 42,3413,1725,2288, 896,1947, 774,4474,4254, 604,3430,4264, 392,2514,2588, 452, 237,1408,3018, 988,4531,1970, 3034,3310, 540,2370,1562,1288,2990, 502,4765,1147, 4,1853,2708, 207, 294,2814, 4078,2902,2509, 684, 34,3105,3532,2551, 644, 709,2801,2344, 573,1727,3573,3557, 2021,1081,3100,4315,2100,3681, 199,2263,1837,2385, 146,3484,1195,2776,3949, 997, 1939,3973,1008,1091,1202,1962,1847,1149,4209,5444,1076, 493, 117,5400,2521, 972, 1490,2934,1796,4542,2374,1512,2933,2657, 413,2888,1135,2762,2314,2156,1355,2369, 766,2007,2527,2170,3124,2491,2593,2632,4757,2437, 234,3125,3591,1898,1750,1376, 1942,3468,3138, 570,2127,2145,3276,4131, 962, 132,1445,4196, 19, 941,3624,3480, 3366,1973,1374,4461,3431,2629, 283,2415,2275, 808,2887,3620,2112,2563,1353,3610, 955,1089,3103,1053, 96, 88,4097, 823,3808,1583, 399, 292,4091,3313, 421,1128, 642,4006, 903,2539,1877,2082, 596, 29,4066,1790, 722,2157, 130, 995,1569, 769, 1485, 464, 513,2213, 288,1923,1101,2453,4316, 133, 486,2445, 50, 625, 487,2207, 57, 423, 481,2962, 159,3729,1558, 491, 303, 482, 501, 240,2837, 112,3648,2392, 1783, 362, 8,3433,3422, 610,2793,3277,1390,1284,1654, 21,3823, 734, 367, 623, 193, 287, 374,1009,1483, 816, 476, 313,2255,2340,1262,2150,2899,1146,2581, 782, 2116,1659,2018,1880, 255,3586,3314,1110,2867,2137,2564, 986,2767,5185,2006, 650, 158, 926, 762, 881,3157,2717,2362,3587, 306,3690,3245,1542,3077,2427,1691,2478, 2118,2985,3490,2438, 539,2305, 983, 129,1754, 355,4201,2386, 827,2923, 104,1773, 2838,2771, 411,2905,3919, 376, 767, 122,1114, 828,2422,1817,3506, 266,3460,1007, 1609,4998, 945,2612,4429,2274, 726,1247,1964,2914,2199,2070,4002,4108, 657,3323, 1422, 579, 455,2764,4737,1222,2895,1670, 824,1223,1487,2525, 558, 861,3080, 598, 2659,2515,1967, 752,2583,2376,2214,4180, 977, 704,2464,4999,2622,4109,1210,2961, 819,1541, 142,2284, 44, 418, 457,1126,3730,4347,4626,1644,1876,3671,1864, 302, 1063,5694, 624, 723,1984,3745,1314,1676,2488,1610,1449,3558,3569,2166,2098, 409, 1011,2325,3704,2306, 818,1732,1383,1824,1844,3757, 999,2705,3497,1216,1423,2683, 2426,2954,2501,2726,2229,1475,2554,5064,1971,1794,1666,2014,1343, 783, 724, 191, 2434,1354,2220,5065,1763,2752,2472,4152, 131, 175,2885,3434, 92,1466,4920,2616, 3871,3872,3866, 128,1551,1632, 669,1854,3682,4691,4125,1230, 188,2973,3290,1302, 1213, 560,3266, 917, 763,3909,3249,1760, 868,1958, 764,1782,2097, 145,2277,3774, 4462, 64,1491,3062, 971,2132,3606,2442, 221,1226,1617, 218, 323,1185,3207,3147, 571, 619,1473,1005,1744,2281, 449,1887,2396,3685, 275, 375,3816,1743,3844,3731, 845,1983,2350,4210,1377, 773, 967,3499,3052,3743,2725,4007,1697,1022,3943,1464, 3264,2855,2722,1952,1029,2839,2467, 84,4383,2215, 820,1391,2015,2448,3672, 377, 1948,2168, 797,2545,3536,2578,2645, 94,2874,1678, 405,1259,3071, 771, 546,1315, 470,1243,3083, 895,2468, 981, 969,2037, 846,4181, 653,1276,2928, 14,2594, 557, 3007,2474, 156, 902,1338,1740,2574, 537,2518, 973,2282,2216,2433,1928, 138,2903, 1293,2631,1612, 646,3457, 839,2935, 111, 496,2191,2847, 589,3186, 149,3994,2060, 4031,2641,4067,3145,1870, 37,3597,2136,1025,2051,3009,3383,3549,1121,1016,3261, 1301, 251,2446,2599,2153, 872,3246, 637, 334,3705, 831, 884, 921,3065,3140,4092, 2198,1944, 246,2964, 108,2045,1152,1921,2308,1031, 203,3173,4170,1907,3890, 810, 1401,2003,1690, 506, 647,1242,2828,1761,1649,3208,2249,1589,3709,2931,5156,1708, 498, 666,2613, 834,3817,1231, 184,2851,1124, 883,3197,2261,3710,1765,1553,2658, 1178,2639,2351, 93,1193, 942,2538,2141,4402, 235,1821, 870,1591,2192,1709,1871, 3341,1618,4126,2595,2334, 603, 651, 69, 701, 268,2662,3411,2555,1380,1606, 503, 448, 254,2371,2646, 574,1187,2309,1770, 322,2235,1292,1801, 305, 566,1133, 229, 2067,2057, 706, 167, 483,2002,2672,3295,1820,3561,3067, 316, 378,2746,3452,1112, 136,1981, 507,1651,2917,1117, 285,4591, 182,2580,3522,1304, 335,3303,1835,2504, 1795,1792,2248, 674,1018,2106,2449,1857,2292,2845, 976,3047,1781,2600,2727,1389, 1281, 52,3152, 153, 265,3950, 672,3485,3951,4463, 430,1183, 365, 278,2169, 27, 1407,1336,2304, 209,1340,1730,2202,1852,2403,2883, 979,1737,1062, 631,2829,2542, 3876,2592, 825,2086,2226,3048,3625, 352,1417,3724, 542, 991, 431,1351,3938,1861, 2294, 826,1361,2927,3142,3503,1738, 463,2462,2723, 582,1916,1595,2808, 400,3845, 3891,2868,3621,2254, 58,2492,1123, 910,2160,2614,1372,1603,1196,1072,3385,1700, 3267,1980, 696, 480,2430, 920, 799,1570,2920,1951,2041,4047,2540,1321,4223,2469, 3562,2228,1271,2602, 401,2833,3351,2575,5157, 907,2312,1256, 410, 263,3507,1582, 996, 678,1849,2316,1480, 908,3545,2237, 703,2322, 667,1826,2849,1531,2604,2999, 2407,3146,2151,2630,1786,3711, 469,3542, 497,3899,2409, 858, 837,4446,3393,1274, 786, 620,1845,2001,3311, 484, 308,3367,1204,1815,3691,2332,1532,2557,1842,2020, 2724,1927,2333,4440, 567, 22,1673,2728,4475,1987,1858,1144,1597, 101,1832,3601, 12, 974,3783,4391, 951,1412, 1,3720, 453,4608,4041, 528,1041,1027,3230,2628, 1129, 875,1051,3291,1203,2262,1069,2860,2799,2149,2615,3278, 144,1758,3040, 31, 475,1680, 366,2685,3184, 311,1642,4008,2466,5036,1593,1493,2809, 216,1420,1668, 233, 304,2128,3284, 232,1429,1768,1040,2008,3407,2740,2967,2543, 242,2133, 778, 1565,2022,2620, 505,2189,2756,1098,2273, 372,1614, 708, 553,2846,2094,2278, 169, 3626,2835,4161, 228,2674,3165, 809,1454,1309, 466,1705,1095, 900,3423, 880,2667, 3751,5258,2317,3109,2571,4317,2766,1503,1342, 866,4447,1118, 63,2076, 314,1881, 1348,1061, 172, 978,3515,1747, 532, 511,3970, 6, 601, 905,2699,3300,1751, 276, 1467,3725,2668, 65,4239,2544,2779,2556,1604, 578,2451,1802, 992,2331,2624,1320, 3446, 713,1513,1013, 103,2786,2447,1661, 886,1702, 916, 654,3574,2031,1556, 751, 2178,2821,2179,1498,1538,2176, 271, 914,2251,2080,1325, 638,1953,2937,3877,2432, 2754, 95,3265,1716, 260,1227,4083, 775, 106,1357,3254, 426,1607, 555,2480, 772, 1985, 244,2546, 474, 495,1046,2611,1851,2061, 71,2089,1675,2590, 742,3758,2843, 3222,1433, 267,2180,2576,2826,2233,2092,3913,2435, 956,1745,3075, 856,2113,1116, 451, 3,1988,2896,1398, 993,2463,1878,2049,1341,2718,2721,2870,2108, 712,2904, 4363,2753,2324, 277,2872,2349,2649, 384, 987, 435, 691,3000, 922, 164,3939, 652, 1500,1184,4153,2482,3373,2165,4848,2335,3775,3508,3154,2806,2830,1554,2102,1664, 2530,1434,2408, 893,1547,2623,3447,2832,2242,2532,3169,2856,3223,2078, 49,3770, 3469, 462, 318, 656,2259,3250,3069, 679,1629,2758, 344,1138,1104,3120,1836,1283, 3115,2154,1437,4448, 934, 759,1999, 794,2862,1038, 533,2560,1722,2342, 855,2626, 1197,1663,4476,3127, 85,4240,2528, 25,1111,1181,3673, 407,3470,4561,2679,2713, 768,1925,2841,3986,1544,1165, 932, 373,1240,2146,1930,2673, 721,4766, 354,4333, 391,2963, 187, 61,3364,1442,1102, 330,1940,1767, 341,3809,4118, 393,2496,2062, 2211, 105, 331, 300, 439, 913,1332, 626, 379,3304,1557, 328, 689,3952, 309,1555, 931, 317,2517,3027, 325, 569, 686,2107,3084, 60,1042,1333,2794, 264,3177,4014, 1628, 258,3712, 7,4464,1176,1043,1778, 683, 114,1975, 78,1492, 383,1886, 510, 386, 645,5291,2891,2069,3305,4138,3867,2939,2603,2493,1935,1066,1848,3588,1015, 1282,1289,4609, 697,1453,3044,2666,3611,1856,2412, 54, 719,1330, 568,3778,2459, 1748, 788, 492, 551,1191,1000, 488,3394,3763, 282,1799, 348,2016,1523,3155,2390, 1049, 382,2019,1788,1170, 729,2968,3523, 897,3926,2785,2938,3292, 350,2319,3238, 1718,1717,2655,3453,3143,4465, 161,2889,2980,2009,1421, 56,1908,1640,2387,2232, 1917,1874,2477,4921, 148, 83,3438, 592,4245,2882,1822,1055, 741, 115,1496,1624, 381,1638,4592,1020, 516,3214, 458, 947,4575,1432, 211,1514,2926,1865,2142, 189, 852,1221,1400,1486, 882,2299,4036, 351, 28,1122, 700,6479,6480,6481,6482,6483, # last 512 #Everything below is of no interest for detection purpose 5508,6484,3900,3414,3974,4441,4024,3537,4037,5628,5099,3633,6485,3148,6486,3636, 5509,3257,5510,5973,5445,5872,4941,4403,3174,4627,5873,6276,2286,4230,5446,5874, 5122,6102,6103,4162,5447,5123,5323,4849,6277,3980,3851,5066,4246,5774,5067,6278, 3001,2807,5695,3346,5775,5974,5158,5448,6487,5975,5976,5776,3598,6279,5696,4806, 4211,4154,6280,6488,6489,6490,6281,4212,5037,3374,4171,6491,4562,4807,4722,4827, 5977,6104,4532,4079,5159,5324,5160,4404,3858,5359,5875,3975,4288,4610,3486,4512, 5325,3893,5360,6282,6283,5560,2522,4231,5978,5186,5449,2569,3878,6284,5401,3578, 4415,6285,4656,5124,5979,2506,4247,4449,3219,3417,4334,4969,4329,6492,4576,4828, 4172,4416,4829,5402,6286,3927,3852,5361,4369,4830,4477,4867,5876,4173,6493,6105, 4657,6287,6106,5877,5450,6494,4155,4868,5451,3700,5629,4384,6288,6289,5878,3189, 4881,6107,6290,6495,4513,6496,4692,4515,4723,5100,3356,6497,6291,3810,4080,5561, 3570,4430,5980,6498,4355,5697,6499,4724,6108,6109,3764,4050,5038,5879,4093,3226, 6292,5068,5217,4693,3342,5630,3504,4831,4377,4466,4309,5698,4431,5777,6293,5778, 4272,3706,6110,5326,3752,4676,5327,4273,5403,4767,5631,6500,5699,5880,3475,5039, 6294,5562,5125,4348,4301,4482,4068,5126,4593,5700,3380,3462,5981,5563,3824,5404, 4970,5511,3825,4738,6295,6501,5452,4516,6111,5881,5564,6502,6296,5982,6503,4213, 4163,3454,6504,6112,4009,4450,6113,4658,6297,6114,3035,6505,6115,3995,4904,4739, 4563,4942,4110,5040,3661,3928,5362,3674,6506,5292,3612,4791,5565,4149,5983,5328, 5259,5021,4725,4577,4564,4517,4364,6298,5405,4578,5260,4594,4156,4157,5453,3592, 3491,6507,5127,5512,4709,4922,5984,5701,4726,4289,6508,4015,6116,5128,4628,3424, 4241,5779,6299,4905,6509,6510,5454,5702,5780,6300,4365,4923,3971,6511,5161,3270, 3158,5985,4100, 867,5129,5703,6117,5363,3695,3301,5513,4467,6118,6512,5455,4232, 4242,4629,6513,3959,4478,6514,5514,5329,5986,4850,5162,5566,3846,4694,6119,5456, 4869,5781,3779,6301,5704,5987,5515,4710,6302,5882,6120,4392,5364,5705,6515,6121, 6516,6517,3736,5988,5457,5989,4695,2457,5883,4551,5782,6303,6304,6305,5130,4971, 6122,5163,6123,4870,3263,5365,3150,4871,6518,6306,5783,5069,5706,3513,3498,4409, 5330,5632,5366,5458,5459,3991,5990,4502,3324,5991,5784,3696,4518,5633,4119,6519, 4630,5634,4417,5707,4832,5992,3418,6124,5993,5567,4768,5218,6520,4595,3458,5367, 6125,5635,6126,4202,6521,4740,4924,6307,3981,4069,4385,6308,3883,2675,4051,3834, 4302,4483,5568,5994,4972,4101,5368,6309,5164,5884,3922,6127,6522,6523,5261,5460, 5187,4164,5219,3538,5516,4111,3524,5995,6310,6311,5369,3181,3386,2484,5188,3464, 5569,3627,5708,6524,5406,5165,4677,4492,6312,4872,4851,5885,4468,5996,6313,5709, 5710,6128,2470,5886,6314,5293,4882,5785,3325,5461,5101,6129,5711,5786,6525,4906, 6526,6527,4418,5887,5712,4808,2907,3701,5713,5888,6528,3765,5636,5331,6529,6530, 3593,5889,3637,4943,3692,5714,5787,4925,6315,6130,5462,4405,6131,6132,6316,5262, 6531,6532,5715,3859,5716,5070,4696,5102,3929,5788,3987,4792,5997,6533,6534,3920, 4809,5000,5998,6535,2974,5370,6317,5189,5263,5717,3826,6536,3953,5001,4883,3190, 5463,5890,4973,5999,4741,6133,6134,3607,5570,6000,4711,3362,3630,4552,5041,6318, 6001,2950,2953,5637,4646,5371,4944,6002,2044,4120,3429,6319,6537,5103,4833,6538, 6539,4884,4647,3884,6003,6004,4758,3835,5220,5789,4565,5407,6540,6135,5294,4697, 4852,6320,6321,3206,4907,6541,6322,4945,6542,6136,6543,6323,6005,4631,3519,6544, 5891,6545,5464,3784,5221,6546,5571,4659,6547,6324,6137,5190,6548,3853,6549,4016, 4834,3954,6138,5332,3827,4017,3210,3546,4469,5408,5718,3505,4648,5790,5131,5638, 5791,5465,4727,4318,6325,6326,5792,4553,4010,4698,3439,4974,3638,4335,3085,6006, 5104,5042,5166,5892,5572,6327,4356,4519,5222,5573,5333,5793,5043,6550,5639,5071, 4503,6328,6139,6551,6140,3914,3901,5372,6007,5640,4728,4793,3976,3836,4885,6552, 4127,6553,4451,4102,5002,6554,3686,5105,6555,5191,5072,5295,4611,5794,5296,6556, 5893,5264,5894,4975,5466,5265,4699,4976,4370,4056,3492,5044,4886,6557,5795,4432, 4769,4357,5467,3940,4660,4290,6141,4484,4770,4661,3992,6329,4025,4662,5022,4632, 4835,4070,5297,4663,4596,5574,5132,5409,5895,6142,4504,5192,4664,5796,5896,3885, 5575,5797,5023,4810,5798,3732,5223,4712,5298,4084,5334,5468,6143,4052,4053,4336, 4977,4794,6558,5335,4908,5576,5224,4233,5024,4128,5469,5225,4873,6008,5045,4729, 4742,4633,3675,4597,6559,5897,5133,5577,5003,5641,5719,6330,6560,3017,2382,3854, 4406,4811,6331,4393,3964,4946,6561,2420,3722,6562,4926,4378,3247,1736,4442,6332, 5134,6333,5226,3996,2918,5470,4319,4003,4598,4743,4744,4485,3785,3902,5167,5004, 5373,4394,5898,6144,4874,1793,3997,6334,4085,4214,5106,5642,4909,5799,6009,4419, 4189,3330,5899,4165,4420,5299,5720,5227,3347,6145,4081,6335,2876,3930,6146,3293, 3786,3910,3998,5900,5300,5578,2840,6563,5901,5579,6147,3531,5374,6564,6565,5580, 4759,5375,6566,6148,3559,5643,6336,6010,5517,6337,6338,5721,5902,3873,6011,6339, 6567,5518,3868,3649,5722,6568,4771,4947,6569,6149,4812,6570,2853,5471,6340,6341, 5644,4795,6342,6012,5723,6343,5724,6013,4349,6344,3160,6150,5193,4599,4514,4493, 5168,4320,6345,4927,3666,4745,5169,5903,5005,4928,6346,5725,6014,4730,4203,5046, 4948,3395,5170,6015,4150,6016,5726,5519,6347,5047,3550,6151,6348,4197,4310,5904, 6571,5581,2965,6152,4978,3960,4291,5135,6572,5301,5727,4129,4026,5905,4853,5728, 5472,6153,6349,4533,2700,4505,5336,4678,3583,5073,2994,4486,3043,4554,5520,6350, 6017,5800,4487,6351,3931,4103,5376,6352,4011,4321,4311,4190,5136,6018,3988,3233, 4350,5906,5645,4198,6573,5107,3432,4191,3435,5582,6574,4139,5410,6353,5411,3944, 5583,5074,3198,6575,6354,4358,6576,5302,4600,5584,5194,5412,6577,6578,5585,5413, 5303,4248,5414,3879,4433,6579,4479,5025,4854,5415,6355,4760,4772,3683,2978,4700, 3797,4452,3965,3932,3721,4910,5801,6580,5195,3551,5907,3221,3471,3029,6019,3999, 5908,5909,5266,5267,3444,3023,3828,3170,4796,5646,4979,4259,6356,5647,5337,3694, 6357,5648,5338,4520,4322,5802,3031,3759,4071,6020,5586,4836,4386,5048,6581,3571, 4679,4174,4949,6154,4813,3787,3402,3822,3958,3215,3552,5268,4387,3933,4950,4359, 6021,5910,5075,3579,6358,4234,4566,5521,6359,3613,5049,6022,5911,3375,3702,3178, 4911,5339,4521,6582,6583,4395,3087,3811,5377,6023,6360,6155,4027,5171,5649,4421, 4249,2804,6584,2270,6585,4000,4235,3045,6156,5137,5729,4140,4312,3886,6361,4330, 6157,4215,6158,3500,3676,4929,4331,3713,4930,5912,4265,3776,3368,5587,4470,4855, 3038,4980,3631,6159,6160,4132,4680,6161,6362,3923,4379,5588,4255,6586,4121,6587, 6363,4649,6364,3288,4773,4774,6162,6024,6365,3543,6588,4274,3107,3737,5050,5803, 4797,4522,5589,5051,5730,3714,4887,5378,4001,4523,6163,5026,5522,4701,4175,2791, 3760,6589,5473,4224,4133,3847,4814,4815,4775,3259,5416,6590,2738,6164,6025,5304, 3733,5076,5650,4816,5590,6591,6165,6592,3934,5269,6593,3396,5340,6594,5804,3445, 3602,4042,4488,5731,5732,3525,5591,4601,5196,6166,6026,5172,3642,4612,3202,4506, 4798,6366,3818,5108,4303,5138,5139,4776,3332,4304,2915,3415,4434,5077,5109,4856, 2879,5305,4817,6595,5913,3104,3144,3903,4634,5341,3133,5110,5651,5805,6167,4057, 5592,2945,4371,5593,6596,3474,4182,6367,6597,6168,4507,4279,6598,2822,6599,4777, 4713,5594,3829,6169,3887,5417,6170,3653,5474,6368,4216,2971,5228,3790,4579,6369, 5733,6600,6601,4951,4746,4555,6602,5418,5475,6027,3400,4665,5806,6171,4799,6028, 5052,6172,3343,4800,4747,5006,6370,4556,4217,5476,4396,5229,5379,5477,3839,5914, 5652,5807,4714,3068,4635,5808,6173,5342,4192,5078,5419,5523,5734,6174,4557,6175, 4602,6371,6176,6603,5809,6372,5735,4260,3869,5111,5230,6029,5112,6177,3126,4681, 5524,5915,2706,3563,4748,3130,6178,4018,5525,6604,6605,5478,4012,4837,6606,4534, 4193,5810,4857,3615,5479,6030,4082,3697,3539,4086,5270,3662,4508,4931,5916,4912, 5811,5027,3888,6607,4397,3527,3302,3798,2775,2921,2637,3966,4122,4388,4028,4054, 1633,4858,5079,3024,5007,3982,3412,5736,6608,3426,3236,5595,3030,6179,3427,3336, 3279,3110,6373,3874,3039,5080,5917,5140,4489,3119,6374,5812,3405,4494,6031,4666, 4141,6180,4166,6032,5813,4981,6609,5081,4422,4982,4112,3915,5653,3296,3983,6375, 4266,4410,5654,6610,6181,3436,5082,6611,5380,6033,3819,5596,4535,5231,5306,5113, 6612,4952,5918,4275,3113,6613,6376,6182,6183,5814,3073,4731,4838,5008,3831,6614, 4888,3090,3848,4280,5526,5232,3014,5655,5009,5737,5420,5527,6615,5815,5343,5173, 5381,4818,6616,3151,4953,6617,5738,2796,3204,4360,2989,4281,5739,5174,5421,5197, 3132,5141,3849,5142,5528,5083,3799,3904,4839,5480,2880,4495,3448,6377,6184,5271, 5919,3771,3193,6034,6035,5920,5010,6036,5597,6037,6378,6038,3106,5422,6618,5423, 5424,4142,6619,4889,5084,4890,4313,5740,6620,3437,5175,5307,5816,4199,5198,5529, 5817,5199,5656,4913,5028,5344,3850,6185,2955,5272,5011,5818,4567,4580,5029,5921, 3616,5233,6621,6622,6186,4176,6039,6379,6380,3352,5200,5273,2908,5598,5234,3837, 5308,6623,6624,5819,4496,4323,5309,5201,6625,6626,4983,3194,3838,4167,5530,5922, 5274,6381,6382,3860,3861,5599,3333,4292,4509,6383,3553,5481,5820,5531,4778,6187, 3955,3956,4324,4389,4218,3945,4325,3397,2681,5923,4779,5085,4019,5482,4891,5382, 5383,6040,4682,3425,5275,4094,6627,5310,3015,5483,5657,4398,5924,3168,4819,6628, 5925,6629,5532,4932,4613,6041,6630,4636,6384,4780,4204,5658,4423,5821,3989,4683, 5822,6385,4954,6631,5345,6188,5425,5012,5384,3894,6386,4490,4104,6632,5741,5053, 6633,5823,5926,5659,5660,5927,6634,5235,5742,5824,4840,4933,4820,6387,4859,5928, 4955,6388,4143,3584,5825,5346,5013,6635,5661,6389,5014,5484,5743,4337,5176,5662, 6390,2836,6391,3268,6392,6636,6042,5236,6637,4158,6638,5744,5663,4471,5347,3663, 4123,5143,4293,3895,6639,6640,5311,5929,5826,3800,6189,6393,6190,5664,5348,3554, 3594,4749,4603,6641,5385,4801,6043,5827,4183,6642,5312,5426,4761,6394,5665,6191, 4715,2669,6643,6644,5533,3185,5427,5086,5930,5931,5386,6192,6044,6645,4781,4013, 5745,4282,4435,5534,4390,4267,6045,5746,4984,6046,2743,6193,3501,4087,5485,5932, 5428,4184,4095,5747,4061,5054,3058,3862,5933,5600,6646,5144,3618,6395,3131,5055, 5313,6396,4650,4956,3855,6194,3896,5202,4985,4029,4225,6195,6647,5828,5486,5829, 3589,3002,6648,6397,4782,5276,6649,6196,6650,4105,3803,4043,5237,5830,6398,4096, 3643,6399,3528,6651,4453,3315,4637,6652,3984,6197,5535,3182,3339,6653,3096,2660, 6400,6654,3449,5934,4250,4236,6047,6401,5831,6655,5487,3753,4062,5832,6198,6199, 6656,3766,6657,3403,4667,6048,6658,4338,2897,5833,3880,2797,3780,4326,6659,5748, 5015,6660,5387,4351,5601,4411,6661,3654,4424,5935,4339,4072,5277,4568,5536,6402, 6662,5238,6663,5349,5203,6200,5204,6201,5145,4536,5016,5056,4762,5834,4399,4957, 6202,6403,5666,5749,6664,4340,6665,5936,5177,5667,6666,6667,3459,4668,6404,6668, 6669,4543,6203,6670,4276,6405,4480,5537,6671,4614,5205,5668,6672,3348,2193,4763, 6406,6204,5937,5602,4177,5669,3419,6673,4020,6205,4443,4569,5388,3715,3639,6407, 6049,4058,6206,6674,5938,4544,6050,4185,4294,4841,4651,4615,5488,6207,6408,6051, 5178,3241,3509,5835,6208,4958,5836,4341,5489,5278,6209,2823,5538,5350,5206,5429, 6675,4638,4875,4073,3516,4684,4914,4860,5939,5603,5389,6052,5057,3237,5490,3791, 6676,6409,6677,4821,4915,4106,5351,5058,4243,5539,4244,5604,4842,4916,5239,3028, 3716,5837,5114,5605,5390,5940,5430,6210,4332,6678,5540,4732,3667,3840,6053,4305, 3408,5670,5541,6410,2744,5240,5750,6679,3234,5606,6680,5607,5671,3608,4283,4159, 4400,5352,4783,6681,6411,6682,4491,4802,6211,6412,5941,6413,6414,5542,5751,6683, 4669,3734,5942,6684,6415,5943,5059,3328,4670,4144,4268,6685,6686,6687,6688,4372, 3603,6689,5944,5491,4373,3440,6416,5543,4784,4822,5608,3792,4616,5838,5672,3514, 5391,6417,4892,6690,4639,6691,6054,5673,5839,6055,6692,6056,5392,6212,4038,5544, 5674,4497,6057,6693,5840,4284,5675,4021,4545,5609,6418,4454,6419,6213,4113,4472, 5314,3738,5087,5279,4074,5610,4959,4063,3179,4750,6058,6420,6214,3476,4498,4716, 5431,4960,4685,6215,5241,6694,6421,6216,6695,5841,5945,6422,3748,5946,5179,3905, 5752,5545,5947,4374,6217,4455,6423,4412,6218,4803,5353,6696,3832,5280,6219,4327, 4702,6220,6221,6059,4652,5432,6424,3749,4751,6425,5753,4986,5393,4917,5948,5030, 5754,4861,4733,6426,4703,6697,6222,4671,5949,4546,4961,5180,6223,5031,3316,5281, 6698,4862,4295,4934,5207,3644,6427,5842,5950,6428,6429,4570,5843,5282,6430,6224, 5088,3239,6060,6699,5844,5755,6061,6431,2701,5546,6432,5115,5676,4039,3993,3327, 4752,4425,5315,6433,3941,6434,5677,4617,4604,3074,4581,6225,5433,6435,6226,6062, 4823,5756,5116,6227,3717,5678,4717,5845,6436,5679,5846,6063,5847,6064,3977,3354, 6437,3863,5117,6228,5547,5394,4499,4524,6229,4605,6230,4306,4500,6700,5951,6065, 3693,5952,5089,4366,4918,6701,6231,5548,6232,6702,6438,4704,5434,6703,6704,5953, 4168,6705,5680,3420,6706,5242,4407,6066,3812,5757,5090,5954,4672,4525,3481,5681, 4618,5395,5354,5316,5955,6439,4962,6707,4526,6440,3465,4673,6067,6441,5682,6708, 5435,5492,5758,5683,4619,4571,4674,4804,4893,4686,5493,4753,6233,6068,4269,6442, 6234,5032,4705,5146,5243,5208,5848,6235,6443,4963,5033,4640,4226,6236,5849,3387, 6444,6445,4436,4437,5850,4843,5494,4785,4894,6709,4361,6710,5091,5956,3331,6237, 4987,5549,6069,6711,4342,3517,4473,5317,6070,6712,6071,4706,6446,5017,5355,6713, 6714,4988,5436,6447,4734,5759,6715,4735,4547,4456,4754,6448,5851,6449,6450,3547, 5852,5318,6451,6452,5092,4205,6716,6238,4620,4219,5611,6239,6072,4481,5760,5957, 5958,4059,6240,6453,4227,4537,6241,5761,4030,4186,5244,5209,3761,4457,4876,3337, 5495,5181,6242,5959,5319,5612,5684,5853,3493,5854,6073,4169,5613,5147,4895,6074, 5210,6717,5182,6718,3830,6243,2798,3841,6075,6244,5855,5614,3604,4606,5496,5685, 5118,5356,6719,6454,5960,5357,5961,6720,4145,3935,4621,5119,5962,4261,6721,6455, 4786,5963,4375,4582,6245,6246,6247,6076,5437,4877,5856,3376,4380,6248,4160,6722, 5148,6456,5211,6457,6723,4718,6458,6724,6249,5358,4044,3297,6459,6250,5857,5615, 5497,5245,6460,5498,6725,6251,6252,5550,3793,5499,2959,5396,6461,6462,4572,5093, 5500,5964,3806,4146,6463,4426,5762,5858,6077,6253,4755,3967,4220,5965,6254,4989, 5501,6464,4352,6726,6078,4764,2290,5246,3906,5438,5283,3767,4964,2861,5763,5094, 6255,6256,4622,5616,5859,5860,4707,6727,4285,4708,4824,5617,6257,5551,4787,5212, 4965,4935,4687,6465,6728,6466,5686,6079,3494,4413,2995,5247,5966,5618,6729,5967, 5764,5765,5687,5502,6730,6731,6080,5397,6467,4990,6258,6732,4538,5060,5619,6733, 4719,5688,5439,5018,5149,5284,5503,6734,6081,4607,6259,5120,3645,5861,4583,6260, 4584,4675,5620,4098,5440,6261,4863,2379,3306,4585,5552,5689,4586,5285,6735,4864, 6736,5286,6082,6737,4623,3010,4788,4381,4558,5621,4587,4896,3698,3161,5248,4353, 4045,6262,3754,5183,4588,6738,6263,6739,6740,5622,3936,6741,6468,6742,6264,5095, 6469,4991,5968,6743,4992,6744,6083,4897,6745,4256,5766,4307,3108,3968,4444,5287, 3889,4343,6084,4510,6085,4559,6086,4898,5969,6746,5623,5061,4919,5249,5250,5504, 5441,6265,5320,4878,3242,5862,5251,3428,6087,6747,4237,5624,5442,6266,5553,4539, 6748,2585,3533,5398,4262,6088,5150,4736,4438,6089,6267,5505,4966,6749,6268,6750, 6269,5288,5554,3650,6090,6091,4624,6092,5690,6751,5863,4270,5691,4277,5555,5864, 6752,5692,4720,4865,6470,5151,4688,4825,6753,3094,6754,6471,3235,4653,6755,5213, 5399,6756,3201,4589,5865,4967,6472,5866,6473,5019,3016,6757,5321,4756,3957,4573, 6093,4993,5767,4721,6474,6758,5625,6759,4458,6475,6270,6760,5556,4994,5214,5252, 6271,3875,5768,6094,5034,5506,4376,5769,6761,2120,6476,5253,5770,6762,5771,5970, 3990,5971,5557,5558,5772,6477,6095,2787,4641,5972,5121,6096,6097,6272,6763,3703, 5867,5507,6273,4206,6274,4789,6098,6764,3619,3646,3833,3804,2394,3788,4936,3978, 4866,4899,6099,6100,5559,6478,6765,3599,5868,6101,5869,5870,6275,6766,4527,6767) # flake8: noqa
gpl-3.0
hanshuoziyan/llvm-pred
scripts/freqavg.py
4
2663
#!/usr/bin/python3 # 通过Value-To-Edge 和 Edge 来比较差异. 使用算数平均. # using equation: # $\frac {pred - real} {min(pred, real)}$ import argparse import re def perror(*args, **keys): from sys import stderr print(file=stderr, *args, **keys) exit(-1) def calc_average(v2e_map, e_map): print("### following predication exceeds too much ###") part_n = 0 total_n = 0 total = 0.0 part = 0.0 for k in v2e_map.keys() & e_map.keys(): predict = int(v2e_map[k]) real = int(e_map[k]) diff = abs(predict - real)/min(real, predict) if diff > 2: print("predicted: %7d real: %7d rate: %.2f\t%s" % (predict, real, diff, k)) else: part += diff part_n += 1 total += diff total_n += 1 print() print("### general report ###") # 平均公式选用算数平均. print("total diverse rate:", round(total/total_n*100,2), "%") print("diverse rate without exceeded predication:", round(part/part_n*100, 2), "%") #去除差别过大的再求平均 def read_profiling(filename): handle = open(filename, 'r') anchor_ready = cmd_ready = False # found begin position in text data = {} pattern = re.compile(r'(\d+)/[0-9.e+]+\s+(.+)') is_v2e = True for line in handle: if anchor_ready: m = pattern.search(line) if m == None: continue # freq == m.group(1) # name == m.group(2) data[m.group(2)] = m.group(1) if cmd_ready: is_v2e = line.strip('\r\n') == "" cmd_ready = False if line.startswith('Sorted executed basic blocks'): anchor_ready = True if line.startswith('LLVM profiling output for execution'): cmd_ready = True handle.close() if not anchor_ready: return None return data, is_v2e def main(): parser = argparse.ArgumentParser(description = 'caculate average compare between value-to-edge and edge profiling') parser.add_argument('value_to_edge', type=str) parser.add_argument('edge', type=str) args = parser.parse_args() v2e_map, yes_v2e = read_profiling(args.value_to_edge) e_map, no_v2e = read_profiling(args.edge) if e_map == None or v2e_map == None: perror('file format unmatch, please use ``llvm-prof -list-all`` to generate output') if yes_v2e == no_v2e: perror('arg order unmatch, first arg should be value_to_edge, second should be edge') if yes_v2e == False: # swap order v2e_map, e_map = e_map, v2e_map calc_average(v2e_map, e_map) main()
gpl-3.0
KyleAMoore/KanjiNani
Android/.buildozer/android/platform/build/build/other_builds/kivy-python3crystax-sdl2/armeabi-v7a/kivy/examples/canvas/canvas_stress.py
21
2146
''' Canvas stress ============= This example tests the performance of our Graphics engine by drawing large numbers of small squares. You should see a black canvas with buttons and a label at the bottom. Pressing the buttons adds small colored squares to the canvas. ''' from kivy.uix.button import Button from kivy.uix.widget import Widget from kivy.uix.label import Label from kivy.uix.boxlayout import BoxLayout from kivy.app import App from kivy.graphics import Color, Rectangle from random import random as r from functools import partial class StressCanvasApp(App): def add_rects(self, label, wid, count, *largs): label.text = str(int(label.text) + count) with wid.canvas: for x in range(count): Color(r(), 1, 1, mode='hsv') Rectangle(pos=(r() * wid.width + wid.x, r() * wid.height + wid.y), size=(20, 20)) def double_rects(self, label, wid, *largs): count = int(label.text) self.add_rects(label, wid, count, *largs) def reset_rects(self, label, wid, *largs): label.text = '0' wid.canvas.clear() def build(self): wid = Widget() label = Label(text='0') btn_add100 = Button(text='+ 100 rects', on_press=partial(self.add_rects, label, wid, 100)) btn_add500 = Button(text='+ 500 rects', on_press=partial(self.add_rects, label, wid, 500)) btn_double = Button(text='x 2', on_press=partial(self.double_rects, label, wid)) btn_reset = Button(text='Reset', on_press=partial(self.reset_rects, label, wid)) layout = BoxLayout(size_hint=(1, None), height=50) layout.add_widget(btn_add100) layout.add_widget(btn_add500) layout.add_widget(btn_double) layout.add_widget(btn_reset) layout.add_widget(label) root = BoxLayout(orientation='vertical') root.add_widget(wid) root.add_widget(layout) return root if __name__ == '__main__': StressCanvasApp().run()
gpl-3.0
cmelange/ansible
lib/ansible/executor/module_common.py
22
38218
# (c) 2013-2014, Michael DeHaan <michael.dehaan@gmail.com> # (c) 2015 Toshio Kuratomi <tkuratomi@ansible.com> # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Ansible is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Ansible. If not, see <http://www.gnu.org/licenses/>. # Make coding more python3-ish from __future__ import (absolute_import, division, print_function) __metaclass__ = type import ast import base64 import datetime import imp import json import os import shlex import zipfile import random import re from io import BytesIO from ansible.release import __version__, __author__ from ansible import constants as C from ansible.errors import AnsibleError from ansible.module_utils._text import to_bytes, to_text from ansible.plugins import module_utils_loader from ansible.plugins.shell.powershell import async_watchdog, async_wrapper, become_wrapper, leaf_exec # Must import strategy and use write_locks from there # If we import write_locks directly then we end up binding a # variable to the object and then it never gets updated. from ansible.executor import action_write_locks try: from __main__ import display except ImportError: from ansible.utils.display import Display display = Display() REPLACER = b"#<<INCLUDE_ANSIBLE_MODULE_COMMON>>" REPLACER_VERSION = b"\"<<ANSIBLE_VERSION>>\"" REPLACER_COMPLEX = b"\"<<INCLUDE_ANSIBLE_MODULE_COMPLEX_ARGS>>\"" REPLACER_WINDOWS = b"# POWERSHELL_COMMON" REPLACER_JSONARGS = b"<<INCLUDE_ANSIBLE_MODULE_JSON_ARGS>>" REPLACER_SELINUX = b"<<SELINUX_SPECIAL_FILESYSTEMS>>" # We could end up writing out parameters with unicode characters so we need to # specify an encoding for the python source file ENCODING_STRING = u'# -*- coding: utf-8 -*-' # module_common is relative to module_utils, so fix the path _MODULE_UTILS_PATH = os.path.join(os.path.dirname(__file__), '..', 'module_utils') # ****************************************************************************** ANSIBALLZ_TEMPLATE = u'''%(shebang)s %(coding)s ANSIBALLZ_WRAPPER = True # For test-module script to tell this is a ANSIBALLZ_WRAPPER # This code is part of Ansible, but is an independent component. # The code in this particular templatable string, and this templatable string # only, is BSD licensed. Modules which end up using this snippet, which is # dynamically combined together by Ansible still belong to the author of the # module, and they may assign their own license to the complete work. # # Copyright (c), James Cammarata, 2016 # Copyright (c), Toshio Kuratomi, 2016 # # Redistribution and use in source and binary forms, with or without modification, # are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. # IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, # PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE # USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import os import os.path import sys import __main__ # For some distros and python versions we pick up this script in the temporary # directory. This leads to problems when the ansible module masks a python # library that another import needs. We have not figured out what about the # specific distros and python versions causes this to behave differently. # # Tested distros: # Fedora23 with python3.4 Works # Ubuntu15.10 with python2.7 Works # Ubuntu15.10 with python3.4 Fails without this # Ubuntu16.04.1 with python3.5 Fails without this # To test on another platform: # * use the copy module (since this shadows the stdlib copy module) # * Turn off pipelining # * Make sure that the destination file does not exist # * ansible ubuntu16-test -m copy -a 'src=/etc/motd dest=/var/tmp/m' # This will traceback in shutil. Looking at the complete traceback will show # that shutil is importing copy which finds the ansible module instead of the # stdlib module scriptdir = None try: scriptdir = os.path.dirname(os.path.abspath(__main__.__file__)) except (AttributeError, OSError): # Some platforms don't set __file__ when reading from stdin # OSX raises OSError if using abspath() in a directory we don't have # permission to read. pass if scriptdir is not None: sys.path = [p for p in sys.path if p != scriptdir] import base64 import shutil import zipfile import tempfile import subprocess if sys.version_info < (3,): bytes = str PY3 = False else: unicode = str PY3 = True try: # Python-2.6+ from io import BytesIO as IOStream except ImportError: # Python < 2.6 from StringIO import StringIO as IOStream ZIPDATA = """%(zipdata)s""" def invoke_module(module, modlib_path, json_params): pythonpath = os.environ.get('PYTHONPATH') if pythonpath: os.environ['PYTHONPATH'] = ':'.join((modlib_path, pythonpath)) else: os.environ['PYTHONPATH'] = modlib_path p = subprocess.Popen([%(interpreter)s, module], env=os.environ, shell=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE) (stdout, stderr) = p.communicate(json_params) if not isinstance(stderr, (bytes, unicode)): stderr = stderr.read() if not isinstance(stdout, (bytes, unicode)): stdout = stdout.read() if PY3: sys.stderr.buffer.write(stderr) sys.stdout.buffer.write(stdout) else: sys.stderr.write(stderr) sys.stdout.write(stdout) return p.returncode def debug(command, zipped_mod, json_params): # The code here normally doesn't run. It's only used for debugging on the # remote machine. # # The subcommands in this function make it easier to debug ansiballz # modules. Here's the basic steps: # # Run ansible with the environment variable: ANSIBLE_KEEP_REMOTE_FILES=1 and -vvv # to save the module file remotely:: # $ ANSIBLE_KEEP_REMOTE_FILES=1 ansible host1 -m ping -a 'data=october' -vvv # # Part of the verbose output will tell you where on the remote machine the # module was written to:: # [...] # <host1> SSH: EXEC ssh -C -q -o ControlMaster=auto -o ControlPersist=60s -o KbdInteractiveAuthentication=no -o # PreferredAuthentications=gssapi-with-mic,gssapi-keyex,hostbased,publickey -o PasswordAuthentication=no -o ConnectTimeout=10 -o # ControlPath=/home/badger/.ansible/cp/ansible-ssh-%%h-%%p-%%r -tt rhel7 '/bin/sh -c '"'"'LANG=en_US.UTF-8 LC_ALL=en_US.UTF-8 # LC_MESSAGES=en_US.UTF-8 /usr/bin/python /home/badger/.ansible/tmp/ansible-tmp-1461173013.93-9076457629738/ping'"'"'' # [...] # # Login to the remote machine and run the module file via from the previous # step with the explode subcommand to extract the module payload into # source files:: # $ ssh host1 # $ /usr/bin/python /home/badger/.ansible/tmp/ansible-tmp-1461173013.93-9076457629738/ping explode # Module expanded into: # /home/badger/.ansible/tmp/ansible-tmp-1461173408.08-279692652635227/ansible # # You can now edit the source files to instrument the code or experiment with # different parameter values. When you're ready to run the code you've modified # (instead of the code from the actual zipped module), use the execute subcommand like this:: # $ /usr/bin/python /home/badger/.ansible/tmp/ansible-tmp-1461173013.93-9076457629738/ping execute # Okay to use __file__ here because we're running from a kept file basedir = os.path.join(os.path.abspath(os.path.dirname(__file__)), 'debug_dir') args_path = os.path.join(basedir, 'args') script_path = os.path.join(basedir, 'ansible_module_%(ansible_module)s.py') if command == 'explode': # transform the ZIPDATA into an exploded directory of code and then # print the path to the code. This is an easy way for people to look # at the code on the remote machine for debugging it in that # environment z = zipfile.ZipFile(zipped_mod) for filename in z.namelist(): if filename.startswith('/'): raise Exception('Something wrong with this module zip file: should not contain absolute paths') dest_filename = os.path.join(basedir, filename) if dest_filename.endswith(os.path.sep) and not os.path.exists(dest_filename): os.makedirs(dest_filename) else: directory = os.path.dirname(dest_filename) if not os.path.exists(directory): os.makedirs(directory) f = open(dest_filename, 'wb') f.write(z.read(filename)) f.close() # write the args file f = open(args_path, 'wb') f.write(json_params) f.close() print('Module expanded into:') print('%%s' %% basedir) exitcode = 0 elif command == 'execute': # Execute the exploded code instead of executing the module from the # embedded ZIPDATA. This allows people to easily run their modified # code on the remote machine to see how changes will affect it. # This differs slightly from default Ansible execution of Python modules # as it passes the arguments to the module via a file instead of stdin. # Set pythonpath to the debug dir pythonpath = os.environ.get('PYTHONPATH') if pythonpath: os.environ['PYTHONPATH'] = ':'.join((basedir, pythonpath)) else: os.environ['PYTHONPATH'] = basedir p = subprocess.Popen([%(interpreter)s, script_path, args_path], env=os.environ, shell=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE) (stdout, stderr) = p.communicate() if not isinstance(stderr, (bytes, unicode)): stderr = stderr.read() if not isinstance(stdout, (bytes, unicode)): stdout = stdout.read() if PY3: sys.stderr.buffer.write(stderr) sys.stdout.buffer.write(stdout) else: sys.stderr.write(stderr) sys.stdout.write(stdout) return p.returncode elif command == 'excommunicate': # This attempts to run the module in-process (by importing a main # function and then calling it). It is not the way ansible generally # invokes the module so it won't work in every case. It is here to # aid certain debuggers which work better when the code doesn't change # from one process to another but there may be problems that occur # when using this that are only artifacts of how we're invoking here, # not actual bugs (as they don't affect the real way that we invoke # ansible modules) # stub the args and python path sys.argv = ['%(ansible_module)s', args_path] sys.path.insert(0, basedir) from ansible_module_%(ansible_module)s import main main() print('WARNING: Module returned to wrapper instead of exiting') sys.exit(1) else: print('WARNING: Unknown debug command. Doing nothing.') exitcode = 0 return exitcode if __name__ == '__main__': # # See comments in the debug() method for information on debugging # ANSIBALLZ_PARAMS = %(params)s if PY3: ANSIBALLZ_PARAMS = ANSIBALLZ_PARAMS.encode('utf-8') try: # There's a race condition with the controller removing the # remote_tmpdir and this module executing under async. So we cannot # store this in remote_tmpdir (use system tempdir instead) temp_path = tempfile.mkdtemp(prefix='ansible_') zipped_mod = os.path.join(temp_path, 'ansible_modlib.zip') modlib = open(zipped_mod, 'wb') modlib.write(base64.b64decode(ZIPDATA)) modlib.close() if len(sys.argv) == 2: exitcode = debug(sys.argv[1], zipped_mod, ANSIBALLZ_PARAMS) else: z = zipfile.ZipFile(zipped_mod, mode='r') module = os.path.join(temp_path, 'ansible_module_%(ansible_module)s.py') f = open(module, 'wb') f.write(z.read('ansible_module_%(ansible_module)s.py')) f.close() # When installed via setuptools (including python setup.py install), # ansible may be installed with an easy-install.pth file. That file # may load the system-wide install of ansible rather than the one in # the module. sitecustomize is the only way to override that setting. z = zipfile.ZipFile(zipped_mod, mode='a') # py3: zipped_mod will be text, py2: it's bytes. Need bytes at the end sitecustomize = u'import sys\\nsys.path.insert(0,"%%s")\\n' %% zipped_mod sitecustomize = sitecustomize.encode('utf-8') # Use a ZipInfo to work around zipfile limitation on hosts with # clocks set to a pre-1980 year (for instance, Raspberry Pi) zinfo = zipfile.ZipInfo() zinfo.filename = 'sitecustomize.py' zinfo.date_time = ( %(year)i, %(month)i, %(day)i, %(hour)i, %(minute)i, %(second)i) z.writestr(zinfo, sitecustomize) z.close() exitcode = invoke_module(module, zipped_mod, ANSIBALLZ_PARAMS) finally: try: shutil.rmtree(temp_path) except OSError: # tempdir creation probably failed pass sys.exit(exitcode) ''' def _strip_comments(source): # Strip comments and blank lines from the wrapper buf = [] for line in source.splitlines(): l = line.strip() if not l or l.startswith(u'#'): continue buf.append(line) return u'\n'.join(buf) if C.DEFAULT_KEEP_REMOTE_FILES: # Keep comments when KEEP_REMOTE_FILES is set. That way users will see # the comments with some nice usage instructions ACTIVE_ANSIBALLZ_TEMPLATE = ANSIBALLZ_TEMPLATE else: # ANSIBALLZ_TEMPLATE stripped of comments for smaller over the wire size ACTIVE_ANSIBALLZ_TEMPLATE = _strip_comments(ANSIBALLZ_TEMPLATE) class ModuleDepFinder(ast.NodeVisitor): # Caveats: # This code currently does not handle: # * relative imports from py2.6+ from . import urls IMPORT_PREFIX_SIZE = len('ansible.module_utils.') def __init__(self, *args, **kwargs): """ Walk the ast tree for the python module. Save submodule[.submoduleN][.identifier] into self.submodules self.submodules will end up with tuples like: - ('basic',) - ('urls', 'fetch_url') - ('database', 'postgres') - ('database', 'postgres', 'quote') It's up to calling code to determine whether the final element of the dotted strings are module names or something else (function, class, or variable names) """ super(ModuleDepFinder, self).__init__(*args, **kwargs) self.submodules = set() def visit_Import(self, node): # import ansible.module_utils.MODLIB[.MODLIBn] [as asname] for alias in (a for a in node.names if a.name.startswith('ansible.module_utils.')): py_mod = alias.name[self.IMPORT_PREFIX_SIZE:] py_mod = tuple(py_mod.split('.')) self.submodules.add(py_mod) self.generic_visit(node) def visit_ImportFrom(self, node): if node.module.startswith('ansible.module_utils'): where_from = node.module[self.IMPORT_PREFIX_SIZE:] if where_from: # from ansible.module_utils.MODULE1[.MODULEn] import IDENTIFIER [as asname] # from ansible.module_utils.MODULE1[.MODULEn] import MODULEn+1 [as asname] # from ansible.module_utils.MODULE1[.MODULEn] import MODULEn+1 [,IDENTIFIER] [as asname] py_mod = tuple(where_from.split('.')) for alias in node.names: self.submodules.add(py_mod + (alias.name,)) else: # from ansible.module_utils import MODLIB [,MODLIB2] [as asname] for alias in node.names: self.submodules.add((alias.name,)) self.generic_visit(node) def _slurp(path): if not os.path.exists(path): raise AnsibleError("imported module support code does not exist at %s" % os.path.abspath(path)) fd = open(path, 'rb') data = fd.read() fd.close() return data def _get_shebang(interpreter, task_vars, args=tuple()): """ Note not stellar API: Returns None instead of always returning a shebang line. Doing it this way allows the caller to decide to use the shebang it read from the file rather than trust that we reformatted what they already have correctly. """ interpreter_config = u'ansible_%s_interpreter' % os.path.basename(interpreter).strip() if interpreter_config not in task_vars: return (None, interpreter) interpreter = task_vars[interpreter_config].strip() shebang = u'#!' + interpreter if args: shebang = shebang + u' ' + u' '.join(args) return (shebang, interpreter) def recursive_finder(name, data, py_module_names, py_module_cache, zf): """ Using ModuleDepFinder, make sure we have all of the module_utils files that the module its module_utils files needs. """ # Parse the module and find the imports of ansible.module_utils tree = ast.parse(data) finder = ModuleDepFinder() finder.visit(tree) # # Determine what imports that we've found are modules (vs class, function. # variable names) for packages # normalized_modules = set() # Loop through the imports that we've found to normalize them # Exclude paths that match with paths we've already processed # (Have to exclude them a second time once the paths are processed) module_utils_paths = [p for p in module_utils_loader._get_paths(subdirs=False) if os.path.isdir(p)] module_utils_paths.append(_MODULE_UTILS_PATH) for py_module_name in finder.submodules.difference(py_module_names): module_info = None if py_module_name[0] == 'six': # Special case the python six library because it messes up the # import process in an incompatible way module_info = imp.find_module('six', module_utils_paths) py_module_name = ('six',) idx = 0 else: # Check whether either the last or the second to last identifier is # a module name for idx in (1, 2): if len(py_module_name) < idx: break try: module_info = imp.find_module(py_module_name[-idx], [os.path.join(p, *py_module_name[:-idx]) for p in module_utils_paths]) break except ImportError: continue # Could not find the module. Construct a helpful error message. if module_info is None: msg = ['Could not find imported module support code for %s. Looked for' % name] if idx == 2: msg.append('either %s.py or %s.py' % (py_module_name[-1], py_module_name[-2])) else: msg.append(py_module_name[-1]) raise AnsibleError(' '.join(msg)) # Found a byte compiled file rather than source. We cannot send byte # compiled over the wire as the python version might be different. # imp.find_module seems to prefer to return source packages so we just # error out if imp.find_module returns byte compiled files (This is # fragile as it depends on undocumented imp.find_module behaviour) if module_info[2][2] not in (imp.PY_SOURCE, imp.PKG_DIRECTORY): msg = ['Could not find python source for imported module support code for %s. Looked for' % name] if idx == 2: msg.append('either %s.py or %s.py' % (py_module_name[-1], py_module_name[-2])) else: msg.append(py_module_name[-1]) raise AnsibleError(' '.join(msg)) if idx == 2: # We've determined that the last portion was an identifier and # thus, not part of the module name py_module_name = py_module_name[:-1] # If not already processed then we've got work to do if py_module_name not in py_module_names: # If not in the cache, then read the file into the cache # We already have a file handle for the module open so it makes # sense to read it now if py_module_name not in py_module_cache: if module_info[2][2] == imp.PKG_DIRECTORY: # Read the __init__.py instead of the module file as this is # a python package py_module_cache[py_module_name + ('__init__',)] = _slurp(os.path.join(os.path.join(module_info[1], '__init__.py'))) normalized_modules.add(py_module_name + ('__init__',)) else: py_module_cache[py_module_name] = module_info[0].read() module_info[0].close() normalized_modules.add(py_module_name) # Make sure that all the packages that this module is a part of # are also added for i in range(1, len(py_module_name)): py_pkg_name = py_module_name[:-i] + ('__init__',) if py_pkg_name not in py_module_names: pkg_dir_info = imp.find_module(py_pkg_name[-1], [os.path.join(p, *py_pkg_name[:-1]) for p in module_utils_paths]) normalized_modules.add(py_pkg_name) py_module_cache[py_pkg_name] = _slurp(pkg_dir_info[1]) # # iterate through all of the ansible.module_utils* imports that we haven't # already checked for new imports # # set of modules that we haven't added to the zipfile unprocessed_py_module_names = normalized_modules.difference(py_module_names) for py_module_name in unprocessed_py_module_names: py_module_path = os.path.join(*py_module_name) py_module_file_name = '%s.py' % py_module_path zf.writestr(os.path.join("ansible/module_utils", py_module_file_name), py_module_cache[py_module_name]) # Add the names of the files we're scheduling to examine in the loop to # py_module_names so that we don't re-examine them in the next pass # through recursive_finder() py_module_names.update(unprocessed_py_module_names) for py_module_file in unprocessed_py_module_names: recursive_finder(py_module_file, py_module_cache[py_module_file], py_module_names, py_module_cache, zf) # Save memory; the file won't have to be read again for this ansible module. del py_module_cache[py_module_file] def _is_binary(b_module_data): textchars = bytearray(set([7, 8, 9, 10, 12, 13, 27]) | set(range(0x20, 0x100)) - set([0x7f])) start = b_module_data[:1024] return bool(start.translate(None, textchars)) def _find_module_utils(module_name, b_module_data, module_path, module_args, task_vars, module_compression): """ Given the source of the module, convert it to a Jinja2 template to insert module code and return whether it's a new or old style module. """ module_substyle = module_style = 'old' # module_style is something important to calling code (ActionBase). It # determines how arguments are formatted (json vs k=v) and whether # a separate arguments file needs to be sent over the wire. # module_substyle is extra information that's useful internally. It tells # us what we have to look to substitute in the module files and whether # we're using module replacer or ansiballz to format the module itself. if _is_binary(b_module_data): module_substyle = module_style = 'binary' elif REPLACER in b_module_data: # Do REPLACER before from ansible.module_utils because we need make sure # we substitute "from ansible.module_utils basic" for REPLACER module_style = 'new' module_substyle = 'python' b_module_data = b_module_data.replace(REPLACER, b'from ansible.module_utils.basic import *') elif b'from ansible.module_utils.' in b_module_data: module_style = 'new' module_substyle = 'python' elif REPLACER_WINDOWS in b_module_data or b'#Requires -Module' in b_module_data: module_style = 'new' module_substyle = 'powershell' elif REPLACER_JSONARGS in b_module_data: module_style = 'new' module_substyle = 'jsonargs' elif b'WANT_JSON' in b_module_data: module_substyle = module_style = 'non_native_want_json' shebang = None # Neither old-style, non_native_want_json nor binary modules should be modified # except for the shebang line (Done by modify_module) if module_style in ('old', 'non_native_want_json', 'binary'): return b_module_data, module_style, shebang output = BytesIO() py_module_names = set() if module_substyle == 'python': params = dict(ANSIBLE_MODULE_ARGS=module_args,) python_repred_params = repr(json.dumps(params)) try: compression_method = getattr(zipfile, module_compression) except AttributeError: display.warning(u'Bad module compression string specified: %s. Using ZIP_STORED (no compression)' % module_compression) compression_method = zipfile.ZIP_STORED lookup_path = os.path.join(C.DEFAULT_LOCAL_TMP, 'ansiballz_cache') cached_module_filename = os.path.join(lookup_path, "%s-%s" % (module_name, module_compression)) zipdata = None # Optimization -- don't lock if the module has already been cached if os.path.exists(cached_module_filename): display.debug('ANSIBALLZ: using cached module: %s' % cached_module_filename) zipdata = open(cached_module_filename, 'rb').read() else: if module_name in action_write_locks.action_write_locks: display.debug('ANSIBALLZ: Using lock for %s' % module_name) lock = action_write_locks.action_write_locks[module_name] else: # If the action plugin directly invokes the module (instead of # going through a strategy) then we don't have a cross-process # Lock specifically for this module. Use the "unexpected # module" lock instead display.debug('ANSIBALLZ: Using generic lock for %s' % module_name) lock = action_write_locks.action_write_locks[None] display.debug('ANSIBALLZ: Acquiring lock') with lock: display.debug('ANSIBALLZ: Lock acquired: %s' % id(lock)) # Check that no other process has created this while we were # waiting for the lock if not os.path.exists(cached_module_filename): display.debug('ANSIBALLZ: Creating module') # Create the module zip data zipoutput = BytesIO() zf = zipfile.ZipFile(zipoutput, mode='w', compression=compression_method) # Note: If we need to import from release.py first, # remember to catch all exceptions: https://github.com/ansible/ansible/issues/16523 zf.writestr('ansible/__init__.py', b'from pkgutil import extend_path\n__path__=extend_path(__path__,__name__)\n__version__="' + to_bytes(__version__) + b'"\n__author__="' + to_bytes(__author__) + b'"\n') zf.writestr('ansible/module_utils/__init__.py', b'from pkgutil import extend_path\n__path__=extend_path(__path__,__name__)\n') zf.writestr('ansible_module_%s.py' % module_name, b_module_data) py_module_cache = { ('__init__',): b'' } recursive_finder(module_name, b_module_data, py_module_names, py_module_cache, zf) zf.close() zipdata = base64.b64encode(zipoutput.getvalue()) # Write the assembled module to a temp file (write to temp # so that no one looking for the file reads a partially # written file) if not os.path.exists(lookup_path): # Note -- if we have a global function to setup, that would # be a better place to run this os.makedirs(lookup_path) display.debug('ANSIBALLZ: Writing module') with open(cached_module_filename + '-part', 'wb') as f: f.write(zipdata) # Rename the file into its final position in the cache so # future users of this module can read it off the # filesystem instead of constructing from scratch. display.debug('ANSIBALLZ: Renaming module') os.rename(cached_module_filename + '-part', cached_module_filename) display.debug('ANSIBALLZ: Done creating module') if zipdata is None: display.debug('ANSIBALLZ: Reading module after lock') # Another process wrote the file while we were waiting for # the write lock. Go ahead and read the data from disk # instead of re-creating it. try: zipdata = open(cached_module_filename, 'rb').read() except IOError: raise AnsibleError('A different worker process failed to create module file.' ' Look at traceback for that process for debugging information.') zipdata = to_text(zipdata, errors='surrogate_or_strict') shebang, interpreter = _get_shebang(u'/usr/bin/python', task_vars) if shebang is None: shebang = u'#!/usr/bin/python' # Enclose the parts of the interpreter in quotes because we're # substituting it into the template as a Python string interpreter_parts = interpreter.split(u' ') interpreter = u"'{0}'".format(u"', '".join(interpreter_parts)) now=datetime.datetime.utcnow() output.write(to_bytes(ACTIVE_ANSIBALLZ_TEMPLATE % dict( zipdata=zipdata, ansible_module=module_name, params=python_repred_params, shebang=shebang, interpreter=interpreter, coding=ENCODING_STRING, year=now.year, month=now.month, day=now.day, hour=now.hour, minute=now.minute, second=now.second, ))) b_module_data = output.getvalue() elif module_substyle == 'powershell': # Powershell/winrm don't actually make use of shebang so we can # safely set this here. If we let the fallback code handle this # it can fail in the presence of the UTF8 BOM commonly added by # Windows text editors shebang = u'#!powershell' # powershell wrapper build is currently handled in build_windows_module_payload, called in action # _configure_module after this function returns. elif module_substyle == 'jsonargs': module_args_json = to_bytes(json.dumps(module_args)) # these strings could be included in a third-party module but # officially they were included in the 'basic' snippet for new-style # python modules (which has been replaced with something else in # ansiballz) If we remove them from jsonargs-style module replacer # then we can remove them everywhere. python_repred_args = to_bytes(repr(module_args_json)) b_module_data = b_module_data.replace(REPLACER_VERSION, to_bytes(repr(__version__))) b_module_data = b_module_data.replace(REPLACER_COMPLEX, python_repred_args) b_module_data = b_module_data.replace(REPLACER_SELINUX, to_bytes(','.join(C.DEFAULT_SELINUX_SPECIAL_FS))) # The main event -- substitute the JSON args string into the module b_module_data = b_module_data.replace(REPLACER_JSONARGS, module_args_json) facility = b'syslog.' + to_bytes(task_vars.get('ansible_syslog_facility', C.DEFAULT_SYSLOG_FACILITY), errors='surrogate_or_strict') b_module_data = b_module_data.replace(b'syslog.LOG_USER', facility) return (b_module_data, module_style, shebang) def modify_module(module_name, module_path, module_args, task_vars=dict(), module_compression='ZIP_STORED'): """ Used to insert chunks of code into modules before transfer rather than doing regular python imports. This allows for more efficient transfer in a non-bootstrapping scenario by not moving extra files over the wire and also takes care of embedding arguments in the transferred modules. This version is done in such a way that local imports can still be used in the module code, so IDEs don't have to be aware of what is going on. Example: from ansible.module_utils.basic import * ... will result in the insertion of basic.py into the module from the module_utils/ directory in the source tree. For powershell, this code effectively no-ops, as the exec wrapper requires access to a number of properties not available here. """ with open(module_path, 'rb') as f: # read in the module source b_module_data = f.read() (b_module_data, module_style, shebang) = _find_module_utils(module_name, b_module_data, module_path, module_args, task_vars, module_compression) if module_style == 'binary': return (b_module_data, module_style, to_text(shebang, nonstring='passthru')) elif shebang is None: lines = b_module_data.split(b"\n", 1) if lines[0].startswith(b"#!"): shebang = lines[0].strip() args = shlex.split(str(shebang[2:])) interpreter = args[0] interpreter = to_bytes(interpreter) new_shebang = to_bytes(_get_shebang(interpreter, task_vars, args[1:])[0], errors='surrogate_or_strict', nonstring='passthru') if new_shebang: lines[0] = shebang = new_shebang if os.path.basename(interpreter).startswith(b'python'): lines.insert(1, to_bytes(ENCODING_STRING)) else: # No shebang, assume a binary module? pass b_module_data = b"\n".join(lines) else: shebang = to_bytes(shebang, errors='surrogate_or_strict') return (b_module_data, module_style, to_text(shebang, nonstring='passthru')) def build_windows_module_payload(module_name, module_path, b_module_data, module_args, task_vars, task, play_context): exec_manifest = dict( module_entry=base64.b64encode(b_module_data), powershell_modules=dict(), module_args=module_args, actions=['exec'] ) exec_manifest['exec'] = base64.b64encode(to_bytes(leaf_exec)) if task.async > 0: exec_manifest["actions"].insert(0, 'async_watchdog') exec_manifest["async_watchdog"] = base64.b64encode(to_bytes(async_watchdog)) exec_manifest["actions"].insert(0, 'async_wrapper') exec_manifest["async_wrapper"] = base64.b64encode(to_bytes(async_wrapper)) exec_manifest["async_jid"] = str(random.randint(0, 999999999999)) exec_manifest["async_timeout_sec"] = task.async if play_context.become and play_context.become_method=='runas': exec_manifest["actions"].insert(0, 'become') exec_manifest["become_user"] = play_context.become_user exec_manifest["become_password"] = play_context.become_pass exec_manifest["become"] = base64.b64encode(to_bytes(become_wrapper)) lines = b_module_data.split(b'\n') module_names = set() requires_module_list = re.compile(r'(?i)^#requires \-module(?:s?) (.+)') for line in lines: # legacy, equivalent to #Requires -Modules powershell if REPLACER_WINDOWS in line: module_names.add(b'powershell') # TODO: add #Requires checks for Ansible.ModuleUtils.X for m in module_names: exec_manifest["powershell_modules"][m] = base64.b64encode( to_bytes(_slurp(os.path.join(_MODULE_UTILS_PATH, m + ".ps1")))) # FUTURE: smuggle this back as a dict instead of serializing here; the connection plugin may need to modify it b_module_data = json.dumps(exec_manifest) return b_module_data
gpl-3.0
danielneis/osf.io
framework/mongo/handlers.py
22
2745
# -*- coding: utf-8 -*- import logging import pymongo from flask import g from werkzeug.local import LocalProxy from website import settings logger = logging.getLogger(__name__) def get_mongo_client(): """Create MongoDB client and authenticate database. """ client = pymongo.MongoClient(settings.DB_HOST, settings.DB_PORT) db = client[settings.DB_NAME] if settings.DB_USER and settings.DB_PASS: db.authenticate(settings.DB_USER, settings.DB_PASS) return client def connection_before_request(): """Attach MongoDB client to `g`. """ g._mongo_client = get_mongo_client() def connection_teardown_request(error=None): """Close MongoDB client if attached to `g`. """ try: g._mongo_client.close() except AttributeError: if not settings.DEBUG_MODE: logger.error('MongoDB client not attached to request.') handlers = { 'before_request': connection_before_request, 'teardown_request': connection_teardown_request, } # Set up getters for `LocalProxy` objects _mongo_client = get_mongo_client() def _get_current_client(): """Getter for `client` proxy. Return default client if no client attached to `g` or no request context. """ try: return g._mongo_client except (AttributeError, RuntimeError): return _mongo_client def _get_current_database(): """Getter for `database` proxy. """ return _get_current_client()[settings.DB_NAME] # Set up `LocalProxy` objects client = LocalProxy(_get_current_client) database = LocalProxy(_get_current_database) def set_up_storage(schemas, storage_class, prefix='', addons=None, **kwargs): '''Setup the storage backend for each schema in ``schemas``. note:: ``**kwargs`` are passed to the constructor of ``storage_class`` Example usage with modular-odm and pymongo: :: >>> from pymongo import MongoClient >>> from modularodm.storage import MongoStorage >>> from models import User, Node, Tag >>> client = MongoClient(port=20771) >>> db = client['mydb'] >>> models = [User, Node, Tag] >>> set_up_storage(models, MongoStorage) ''' _schemas = [] _schemas.extend(schemas) for addon in (addons or []): _schemas.extend(addon.models) for schema in _schemas: collection = '{0}{1}'.format(prefix, schema._name) schema.set_storage( storage_class( db=database, collection=collection, **kwargs ) ) # Allow models to define extra indices for index in getattr(schema, '__indices__', []): database[collection].ensure_index(**index)
apache-2.0
Just-D/chromium-1
tools/telemetry/third_party/gsutilz/third_party/boto/boto/sqs/messageattributes.py
159
2487
# Copyright (c) 2006,2007 Mitch Garnaat http://garnaat.org/ # Copyright (c) 2014 Amazon.com, Inc. All rights reserved. # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, dis- # tribute, sublicense, and/or sell copies of the Software, and to permit # persons to whom the Software is furnished to do so, subject to the fol- # lowing conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS # OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABIL- # ITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT # SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, # WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS # IN THE SOFTWARE. """ Represents an SQS MessageAttribute Name/Value set """ class MessageAttributes(dict): def __init__(self, parent): self.parent = parent self.current_key = None self.current_value = None def startElement(self, name, attrs, connection): if name == 'Value': self.current_value = MessageAttributeValue(self) return self.current_value def endElement(self, name, value, connection): if name == 'MessageAttribute': self[self.current_key] = self.current_value elif name == 'Name': self.current_key = value elif name == 'Value': pass else: setattr(self, name, value) class MessageAttributeValue(dict): def __init__(self, parent): self.parent = parent def startElement(self, name, attrs, connection): pass def endElement(self, name, value, connection): if name == 'DataType': self['data_type'] = value elif name == 'StringValue': self['string_value'] = value elif name == 'BinaryValue': self['binary_value'] = value elif name == 'StringListValue': self['string_list_value'] = value elif name == 'BinaryListValue': self['binary_list_value'] = value
bsd-3-clause
angelapper/edx-platform
common/djangoapps/util/tests/test_milestones_helpers.py
3
5370
""" Tests for the milestones helpers library, which is the integration point for the edx_milestones API """ import ddt from django.conf import settings from milestones.exceptions import InvalidCourseKeyException, InvalidUserException from mock import patch from milestones import api as milestones_api from milestones.models import MilestoneRelationshipType from xmodule.modulestore.tests.django_utils import ModuleStoreTestCase from xmodule.modulestore.tests.factories import CourseFactory from util import milestones_helpers @patch.dict(settings.FEATURES, {'MILESTONES_APP': False}) @ddt.ddt class MilestonesHelpersTestCase(ModuleStoreTestCase): """ Main test suite for Milestones API client library """ CREATE_USER = False def setUp(self): """ Test case scaffolding """ super(MilestonesHelpersTestCase, self).setUp() self.course = CourseFactory.create( metadata={ 'entrance_exam_enabled': True, } ) self.user = {'id': '123'} self.milestone = milestones_api.add_milestone({ 'name': 'Test Milestone', 'namespace': 'doesnt.matter', 'description': 'Testing Milestones Helpers Library', }) MilestoneRelationshipType.objects.get_or_create(name='requires') MilestoneRelationshipType.objects.get_or_create(name='fulfills') @ddt.data( (False, False, False), (True, False, False), (False, True, False), (True, True, True), ) def test_pre_requisite_courses_enabled(self, feature_flags): """ Tests is_prerequisite_courses_enabled function with a set of possible values for ENABLE_PREREQUISITE_COURSES and MILESTONES_APP feature flags. """ with patch.dict("django.conf.settings.FEATURES", { 'ENABLE_PREREQUISITE_COURSES': feature_flags[0], 'MILESTONES_APP': feature_flags[1] }): self.assertEqual(feature_flags[2], milestones_helpers.is_prerequisite_courses_enabled()) def test_add_milestone_returns_none_when_app_disabled(self): response = milestones_helpers.add_milestone(milestone_data=self.milestone) self.assertIsNone(response) def test_get_milestones_returns_none_when_app_disabled(self): response = milestones_helpers.get_milestones(namespace="whatever") self.assertEqual(len(response), 0) def test_get_milestone_relationship_types_returns_none_when_app_disabled(self): response = milestones_helpers.get_milestone_relationship_types() self.assertEqual(len(response), 0) def test_add_course_milestone_returns_none_when_app_disabled(self): response = milestones_helpers.add_course_milestone(unicode(self.course.id), 'requires', self.milestone) self.assertIsNone(response) def test_get_course_milestones_returns_none_when_app_disabled(self): response = milestones_helpers.get_course_milestones(unicode(self.course.id)) self.assertEqual(len(response), 0) def test_add_course_content_milestone_returns_none_when_app_disabled(self): response = milestones_helpers.add_course_content_milestone( unicode(self.course.id), 'i4x://any/content/id', 'requires', self.milestone ) self.assertIsNone(response) def test_get_course_content_milestones_returns_none_when_app_disabled(self): response = milestones_helpers.get_course_content_milestones( unicode(self.course.id), 'i4x://doesnt/matter/for/this/test', 'requires' ) self.assertEqual(len(response), 0) def test_remove_content_references_returns_none_when_app_disabled(self): response = milestones_helpers.remove_content_references("i4x://any/content/id/will/do") self.assertIsNone(response) def test_get_namespace_choices_returns_values_when_app_disabled(self): response = milestones_helpers.get_namespace_choices() self.assertIn('ENTRANCE_EXAM', response) def test_get_course_milestones_fulfillment_paths_returns_none_when_app_disabled(self): response = milestones_helpers.get_course_milestones_fulfillment_paths(unicode(self.course.id), self.user) self.assertIsNone(response) def test_add_user_milestone_returns_none_when_app_disabled(self): response = milestones_helpers.add_user_milestone(self.user, self.milestone) self.assertIsNone(response) def test_get_service_returns_none_when_app_disabled(self): """MilestonesService is None when app disabled""" response = milestones_helpers.get_service() self.assertIsNone(response) @patch.dict(settings.FEATURES, {'MILESTONES_APP': True}) def test_any_unfulfilled_milestones(self): """ Tests any_unfulfilled_milestones for invalid arguments with the app enabled. """ # Should not raise any exceptions milestones_helpers.any_unfulfilled_milestones(self.course.id, self.user['id']) with self.assertRaises(InvalidCourseKeyException): milestones_helpers.any_unfulfilled_milestones(None, self.user['id']) with self.assertRaises(InvalidUserException): milestones_helpers.any_unfulfilled_milestones(self.course.id, None)
agpl-3.0
nalaswad/nalaswad-closure
closure/bin/build/jscompiler_test.py
27
3602
#!/usr/bin/env python # # Copyright 2013 The Closure Library 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 test for depstree.""" __author__ = 'nnaze@google.com (Nathan Naze)' import unittest import jscompiler class JsCompilerTestCase(unittest.TestCase): """Unit tests for jscompiler module.""" def testGetJsCompilerArgs(self): original_check = jscompiler._JavaSupports32BitMode jscompiler._JavaSupports32BitMode = lambda: False args = jscompiler._GetJsCompilerArgs( 'path/to/jscompiler.jar', (1, 6), ['path/to/src1.js', 'path/to/src2.js'], ['--test_jvm_flag'], ['--test_compiler_flag'] ) self.assertEqual( ['java', '-client', '--test_jvm_flag', '-jar', 'path/to/jscompiler.jar', '--js', 'path/to/src1.js', '--js', 'path/to/src2.js', '--test_compiler_flag'], args) def CheckJava15RaisesError(): jscompiler._GetJsCompilerArgs( 'path/to/jscompiler.jar', (1, 5), ['path/to/src1.js', 'path/to/src2.js'], ['--test_jvm_flag'], ['--test_compiler_flag']) self.assertRaises(jscompiler.JsCompilerError, CheckJava15RaisesError) jscompiler._JavaSupports32BitMode = original_check def testGetJsCompilerArgs32BitJava(self): original_check = jscompiler._JavaSupports32BitMode # Should include the -d32 flag only if 32-bit Java is supported by the # system. jscompiler._JavaSupports32BitMode = lambda: True args = jscompiler._GetJsCompilerArgs( 'path/to/jscompiler.jar', (1, 6), ['path/to/src1.js', 'path/to/src2.js'], ['--test_jvm_flag'], ['--test_compiler_flag']) self.assertEqual( ['java', '-d32', '-client', '--test_jvm_flag', '-jar', 'path/to/jscompiler.jar', '--js', 'path/to/src1.js', '--js', 'path/to/src2.js', '--test_compiler_flag'], args) # Should exclude the -d32 flag if 32-bit Java is not supported by the # system. jscompiler._JavaSupports32BitMode = lambda: False args = jscompiler._GetJsCompilerArgs( 'path/to/jscompiler.jar', (1, 6), ['path/to/src1.js', 'path/to/src2.js'], ['--test_jvm_flag'], ['--test_compiler_flag']) self.assertEqual( ['java', '-client', '--test_jvm_flag', '-jar', 'path/to/jscompiler.jar', '--js', 'path/to/src1.js', '--js', 'path/to/src2.js', '--test_compiler_flag'], args) jscompiler._JavaSupports32BitMode = original_check def testGetJavaVersion(self): def assertVersion(expected, version_string): self.assertEquals(expected, version_string) assertVersion((1, 7), _TEST_JAVA_VERSION_STRING) assertVersion((1, 4), 'java version "1.4.0_03-ea"') _TEST_JAVA_VERSION_STRING = """\ openjdk version "1.7.0-google-v5" OpenJDK Runtime Environment (build 1.7.0-google-v5-64327-39803485) OpenJDK Server VM (build 22.0-b10, mixed mode) """ if __name__ == '__main__': unittest.main()
apache-2.0
akarol/cfme_tests
cfme/tests/cloud_infra_common/test_html5_vm_console.py
1
8156
# -*- coding: utf-8 -*- """Test for HTML5 Remote Consoles of VMware/RHEV/RHOSP Providers.""" import pytest import imghdr import time import re from cfme.cloud.provider.openstack import OpenStackProvider from cfme.common.provider import CloudInfraProvider from cfme.infrastructure.provider.virtualcenter import VMwareProvider from cfme.common.vm import VM from cfme.utils import ssh from cfme.utils.blockers import BZ from cfme.utils.log import logger from cfme.utils.conf import credentials from cfme.utils.providers import ProviderFilter from wait_for import wait_for from markers.env_markers.provider import providers pytestmark = [ pytest.mark.usefixtures('setup_provider'), pytest.mark.provider(gen_func=providers, filters=[ProviderFilter(classes=[CloudInfraProvider], required_flags=['html5_console'])], scope='module'), ] @pytest.fixture(scope="function") def vm_obj(request, provider, setup_provider, console_template, vm_name): """ Create a VM on the provider with the given template, and return the vm_obj. Also, it will remove VM from provider using nested function _delete_vm after the test is completed. """ vm_obj = VM.factory(vm_name, provider, template_name=console_template.name) @request.addfinalizer def _delete_vm(): try: vm_obj.delete_from_provider() except Exception: logger.warning("Failed to delete vm `{}`.".format(vm_obj.name)) vm_obj.create_on_provider(timeout=2400, find_in_cfme=True, allow_skip="default") if provider.one_of(OpenStackProvider): # Assign FloatingIP to Openstack Instance from pool # so that we can SSH to it public_net = provider.data['public_network'] provider.mgmt.assign_floating_ip(vm_obj.name, public_net) return vm_obj @pytest.mark.rhv1 def test_html5_vm_console(appliance, provider, configure_websocket, vm_obj, configure_console_vnc, take_screenshot): """ Test the HTML5 console support for a particular provider. The supported providers are: VMware Openstack RHV For a given provider, and a given VM, the console will be opened, and then: - The console's status will be checked. - A command that creates a file will be sent through the console. - Using ssh we will check that the command worked (i.e. that the file was created. """ console_vm_username = credentials[provider.data.templates.get('console_template') ['creds']].get('username') console_vm_password = credentials[provider.data.templates.get('console_template') ['creds']].get('password') vm_obj.open_console(console='VM Console') assert vm_obj.vm_console, 'VMConsole object should be created' vm_console = vm_obj.vm_console try: # If the banner/connection-status element exists we can get # the connection status text and if the console is healthy, it should connect. assert vm_console.wait_for_connect(180), "VM Console did not reach 'connected' state" # Get the login screen image, and make sure it is a jpeg file: screen = vm_console.get_screen() assert imghdr.what('', screen) == 'jpeg' assert vm_console.wait_for_text(text_to_find="login:", timeout=200), ("VM Console" " didn't prompt for Login") # Enter Username: vm_console.send_keys(console_vm_username) assert vm_console.wait_for_text(text_to_find="Password", timeout=200), ("VM Console" " didn't prompt for Password") # Enter Password: vm_console.send_keys("{}\n".format(console_vm_password)) time.sleep(5) # wait for login to complete # This regex can find if there is a word 'login','password','incorrect' present in # text, irrespective of its case regex_for_login_password = re.compile(r'\blogin\b | \bpassword\b| \bincorrect\b', flags=re.I | re.X) def _validate_login(): """ Try to read what is on present on the last line in console. If it is word 'login', enter username, if 'password' enter password, in order to make the login successful """ if vm_console.find_text_on_screen(text_to_find='login', current_line=True): vm_console.send_keys(console_vm_username) if vm_console.find_text_on_screen(text_to_find='Password', current_line=True): vm_console.send_keys("{}\n".format(console_vm_password)) # if the login attempt failed for some reason (happens with RHOS-cirros), # last line of the console will contain one of the following words: # [login, password, incorrect] # if so, regex_for_login_password will find it and result will not be [] # .split('\n')[-1] splits the console text on '\n' & picks last item of resulting list result = regex_for_login_password.findall(vm_console.get_screen_text().split('\n')[-1]) return result == [] # if _validate_login() returns True, it means we did not find any of words # [login, password, incorrect] on last line of console text, which implies login success wait_for(func=_validate_login, timeout=300, delay=5) logger.info("Wait to get the '$' prompt") if provider.one_of(VMwareProvider): vm_console.wait_for_text(text_to_find=provider.data.templates.get('console_template') ['prompt_text'], timeout=200) else: time.sleep(15) # create file on system vm_console.send_keys("touch blather") if not (BZ.bugzilla.get_bug(1491387).is_opened): # Test pressing ctrl-alt-delete...we should be able to get a new login prompt: vm_console.send_ctrl_alt_delete() assert vm_console.wait_for_text(text_to_find="login:", timeout=200, to_disappear=True), ("Text 'login:' never disappeared, indicating failure" " of CTRL+ALT+DEL button functionality, please check if OS reboots on " "CTRL+ALT+DEL key combination and CTRL+ALT+DEL button on HTML5 Console is working.") assert vm_console.wait_for_text(text_to_find="login:", timeout=200), ("VM Console" " didn't prompt for Login") if not provider.one_of(OpenStackProvider): assert vm_console.send_fullscreen(), ("VM Console Toggle Full Screen button does" " not work") with ssh.SSHClient(hostname=vm_obj.ip_address, username=console_vm_username, password=console_vm_password) as ssh_client: # if file was created in previous steps it will be removed here # we will get instance of SSHResult # Sometimes Openstack drops characters from word 'blather' hence try to remove # file using partial file name. Known issue, being worked on. command_result = ssh_client.run_command("rm blather", ensure_user=True) assert command_result except Exception as e: # Take a screenshot if an exception occurs vm_console.switch_to_console() take_screenshot("ConsoleScreenshot") vm_console.switch_to_appliance() raise e finally: vm_console.close_console_window() # Logout is required because when running the Test back 2 back against RHV and VMware # Providers, following issue would arise: # If test for RHV is just finished, code would proceed to adding VMware Provider and once it # is added, then it will navigate to Infrastructure -> Virtual Machines Page, it will see # "Page Does not Exists" Error, because the browser will try to go to the # VM details page of RHV VM which is already deleted # at the End of test for RHV Provider Console and test would fail. # Logging out would get rid of this issue. appliance.server.logout()
gpl-2.0
mitar/django
django/contrib/admin/templatetags/log.py
99
2119
from django import template from django.contrib.admin.models import LogEntry register = template.Library() class AdminLogNode(template.Node): def __init__(self, limit, varname, user): self.limit, self.varname, self.user = limit, varname, user def __repr__(self): return "<GetAdminLog Node>" def render(self, context): if self.user is None: context[self.varname] = LogEntry.objects.all().select_related('content_type', 'user')[:self.limit] else: user_id = self.user if not user_id.isdigit(): user_id = context[self.user].id context[self.varname] = LogEntry.objects.filter(user__id__exact=user_id).select_related('content_type', 'user')[:self.limit] return '' @register.tag def get_admin_log(parser, token): """ Populates a template variable with the admin log for the given criteria. Usage:: {% get_admin_log [limit] as [varname] for_user [context_var_containing_user_obj] %} Examples:: {% get_admin_log 10 as admin_log for_user 23 %} {% get_admin_log 10 as admin_log for_user user %} {% get_admin_log 10 as admin_log %} Note that ``context_var_containing_user_obj`` can be a hard-coded integer (user ID) or the name of a template context variable containing the user object whose ID you want. """ tokens = token.contents.split() if len(tokens) < 4: raise template.TemplateSyntaxError( "'get_admin_log' statements require two arguments") if not tokens[1].isdigit(): raise template.TemplateSyntaxError( "First argument to 'get_admin_log' must be an integer") if tokens[2] != 'as': raise template.TemplateSyntaxError( "Second argument to 'get_admin_log' must be 'as'") if len(tokens) > 4: if tokens[4] != 'for_user': raise template.TemplateSyntaxError( "Fourth argument to 'get_admin_log' must be 'for_user'") return AdminLogNode(limit=tokens[1], varname=tokens[3], user=(len(tokens) > 5 and tokens[5] or None))
bsd-3-clause
guymers/containers_by_bazel
scripts/debian/extract_dependencies.py
2
1179
import re import sys with open(sys.argv[1], "r") as f: i = 0 for line in f: line = line.strip() if not line: continue if i == 1: match = re.search(r'name = "(.+)",$', line) name = match.group(1) if match else None if not name: raise Exception("Failed to find name in line: {0}".format(line)) i = 2 elif i == 2: # skip 'download_file_path' i = 3 elif i == 3: match = re.search(r'urls = \["(.+)"\],$', line) url = match.group(1) if match else None if not url: raise Exception("Failed to find url in line: {0}".format(line)) i = 4 elif i == 4: match = re.search(r'sha256 = "(.+)",$', line) sha256 = match.group(1) if match else None if not sha256: raise Exception("Failed to find sha256 in line: {0}".format(line)) i = 5 elif i == 5: if line != ")": raise Exception("Expected ')' actual: {0}".format(line)) print('{0} {1} {2}'.format(name, url, sha256)) i = 0 elif line == "http_file(": i = 1
apache-2.0
adsabs/citation_helper_service
citation_helper_service/citation_helper.py
1
1894
''' Created on Nov 1, 2014 @author: ehenneken ''' from __future__ import absolute_import # general module imports import sys import os import operator from itertools import groupby from flask import current_app from .utils import get_data from .utils import get_meta_data __all__ = ['get_suggestions'] def get_suggestions(**args): # initializations papers = [] bibcodes = [] if 'bibcodes' in args: bibcodes = args['bibcodes'] if len(bibcodes) == 0: return [] # Any overrides for default values? Nsuggestions = current_app.config.get('CITATION_HELPER_NUMBER_SUGGESTIONS') # get rid of potential trailing spaces bibcodes = [a.strip() for a in bibcodes][ :current_app.config.get('CITATION_HELPER_MAX_INPUT')] # start processing # get the citations for all publications (keeping multiplicity is # essential) papers = get_data(bibcodes=bibcodes) if "Error" in papers: return papers # removes papers from the original list to get candidates papers = [a for a in papers if a not in bibcodes] # establish frequencies of papers in results paperFreq = [(k, len(list(g))) for k, g in groupby(sorted(papers))] # and sort them, most frequent first paperFreq = sorted(paperFreq, key=operator.itemgetter(1), reverse=True) # remove all papers with frequencies smaller than threshold paperFreq = [a for a in paperFreq if a[1] > current_app.config.get( 'CITATION_HELPER_THRESHOLD_FREQUENCY')] # get metadata for suggestions meta_dict = get_meta_data(results=paperFreq[:Nsuggestions]) if "Error"in meta_dict: return meta_dict # return results in required format return [{'bibcode': x, 'score': y, 'title': meta_dict[x]['title'], 'author':meta_dict[x]['author']} for (x, y) in paperFreq[:Nsuggestions] if x in meta_dict.keys()]
mit
2014c2g3/0623exam
static/Brython3.1.0-20150301-090019/Lib/gc.py
743
3548
"""This module provides access to the garbage collector for reference cycles. enable() -- Enable automatic garbage collection. disable() -- Disable automatic garbage collection. isenabled() -- Returns true if automatic collection is enabled. collect() -- Do a full collection right now. get_count() -- Return the current collection counts. set_debug() -- Set debugging flags. get_debug() -- Get debugging flags. set_threshold() -- Set the collection thresholds. get_threshold() -- Return the current the collection thresholds. get_objects() -- Return a list of all objects tracked by the collector. is_tracked() -- Returns true if a given object is tracked. get_referrers() -- Return the list of objects that refer to an object. get_referents() -- Return the list of objects that an object refers to. """ DEBUG_COLLECTABLE = 2 DEBUG_LEAK = 38 DEBUG_SAVEALL = 32 DEBUG_STATS = 1 DEBUG_UNCOLLECTABLE = 4 class __loader__: pass callbacks = [] def collect(*args,**kw): """collect([generation]) -> n With no arguments, run a full collection. The optional argument may be an integer specifying which generation to collect. A ValueError is raised if the generation number is invalid. The number of unreachable objects is returned. """ pass def disable(*args,**kw): """disable() -> None Disable automatic garbage collection. """ pass def enable(*args,**kw): """enable() -> None Enable automatic garbage collection. """ pass garbage = [] def get_count(*args,**kw): """get_count() -> (count0, count1, count2) Return the current collection counts """ pass def get_debug(*args,**kw): """get_debug() -> flags Get the garbage collection debugging flags. """ pass def get_objects(*args,**kw): """get_objects() -> [...] Return a list of objects tracked by the collector (excluding the list returned). """ pass def get_referents(*args,**kw): """get_referents(*objs) -> list Return the list of objects that are directly referred to by objs.""" pass def get_referrers(*args,**kw): """get_referrers(*objs) -> list Return the list of objects that directly refer to any of objs.""" pass def get_threshold(*args,**kw): """get_threshold() -> (threshold0, threshold1, threshold2) Return the current collection thresholds """ pass def is_tracked(*args,**kw): """is_tracked(obj) -> bool Returns true if the object is tracked by the garbage collector. Simple atomic objects will return false. """ pass def isenabled(*args,**kw): """isenabled() -> status Returns true if automatic garbage collection is enabled. """ pass def set_debug(*args,**kw): """set_debug(flags) -> None Set the garbage collection debugging flags. Debugging information is written to sys.stderr. flags is an integer and can have the following bits turned on: DEBUG_STATS - Print statistics during collection. DEBUG_COLLECTABLE - Print collectable objects found. DEBUG_UNCOLLECTABLE - Print unreachable but uncollectable objects found. DEBUG_SAVEALL - Save objects to gc.garbage rather than freeing them. DEBUG_LEAK - Debug leaking programs (everything but STATS). """ pass def set_threshold(*args,**kw): """set_threshold(threshold0, [threshold1, threshold2]) -> None Sets the collection thresholds. Setting threshold0 to zero disables collection. """ pass
gpl-3.0
spaceof7/QGIS
python/plugins/processing/algs/grass7/ext/i_pansharpen.py
5
2139
# -*- coding: utf-8 -*- """ *************************************************************************** i_pansharpen.py --------------- Date : March 2016 Copyright : (C) 2016 by Médéric Ribreux Email : medspx at medspx dot fr *************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * *************************************************************************** """ __author__ = 'Médéric Ribreux' __date__ = 'March 2016' __copyright__ = '(C) 2016, Médéric Ribreux' # This will get replaced with a git SHA1 when you do a git archive __revision__ = '$Format:%H$' from processing.core.parameters import getParameterFromString def processCommand(alg, parameters): # Temporary remove outputs: outputs = [alg.getOutputFromName('{}output'.format(f)) for f in ['red', 'green', 'blue']] for out in outputs: alg.removeOutputFromName(out.name) # create a false output base = getParameterFromString('ParameterString|output|Name for output basename raster map(s)|None|False|False') base.value = alg.getTempFilename() alg.addParameter(base) alg.processCommand() # Re-add outputs for output in outputs: alg.addOutput(output) def processOutputs(alg): base = alg.getParameterValue('output') for channel in ['red', 'green', 'blue']: command = 'r.out.gdal -c -t -f --overwrite createopt="TFW=YES,COMPRESS=LZW" input={} output=\"{}\"'.format( '{}_{}'.format(base, channel), alg.getOutputValue('{}output'.format(channel)) ) alg.commands.append(command) alg.outputCommands.append(command)
gpl-2.0
TheTimmy/spack
var/spack/repos/builtin/packages/miniamr/package.py
2
2528
############################################################################## # Copyright (c) 2013-2017, Lawrence Livermore National Security, LLC. # Produced at the Lawrence Livermore National Laboratory. # # This file is part of Spack. # Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved. # LLNL-CODE-647188 # # For details, see https://github.com/llnl/spack # Please also see the LICENSE file for our notice and the LGPL. # # This program 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) version 2.1, February 1999. # # 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 terms and # conditions of 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 program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA ############################################################################## from spack import * class Miniamr(MakefilePackage): """Proxy Application. 3D stencil calculation with Adaptive Mesh Refinement (AMR) """ homepage = "https://mantevo.org" url = "http://mantevo.org/downloads/releaseTarballs/miniapps/MiniAMR/miniAMR_1.0_all.tgz" tags = ['proxy-app'] version('1.0', '812e5aaaab99689a4e9381a3bbd718a6') variant('mpi', default=True, description='Build with MPI support') depends_on('mpi', when="+mpi") @property def build_targets(self): targets = [] if '+mpi' in self.spec: targets.append('CC={0}'.format(self.spec['mpi'].mpicc)) targets.append('LDLIBS=-lm') targets.append('--file=Makefile.mpi') targets.append('--directory=miniAMR_ref') else: targets.append('--file=Makefile.serial') targets.append('--directory=miniAMR_serial') return targets def install(self, spec, prefix): # Manual installation mkdir(prefix.bin) mkdir(prefix.doc) if '+mpi' in spec: install('miniAMR_ref/miniAMR.x', prefix.bin) else: install('miniAMR_serial/miniAMR.x', prefix.bin) # Install Support Documents install('miniAMR_ref/README', prefix.doc)
lgpl-2.1
linuxdaemon/CloudBot
plugins/minecraft_status.py
7
1373
import json import requests from cloudbot import hook @hook.command(autohelp=False) def mcstatus(reply): """- gets the status of various Mojang (Minecraft) servers""" try: request = requests.get("http://status.mojang.com/check") request.raise_for_status() except (requests.exceptions.HTTPError, requests.exceptions.ConnectionError) as e: reply("Unable to get Minecraft server status: {}".format(e)) raise # lets just reformat this data to get in a nice format data = json.loads(request.text.replace("}", "").replace("{", "").replace("]", "}").replace("[", "{")) out = [] # use a loop so we don't have to update it if they add more servers green = [] yellow = [] red = [] for server, status in list(data.items()): if status == "green": green.append(server) elif status == "yellow": yellow.append(server) else: red.append(server) if green: green.sort() out.append("\x02Online\x02: " + ", ".join(green)) if yellow: yellow.sort() out.append("\x02Issues\x02: " + ", ".join(yellow)) if red: red.sort() out.append("\x02Offline\x02: " + ", ".join(red)) out = " ".join(out) return "\x0f" + out.replace(".mojang.com", ".mj") \ .replace(".minecraft.net", ".mc")
gpl-3.0
MaDKaTZe/phantomjs
src/breakpad/src/tools/gyp/pylib/gyp/MSVSNew.py
138
11514
#!/usr/bin/python2.4 # Copyright (c) 2009 Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """New implementation of Visual Studio project generation for SCons.""" import common import os import random # hashlib is supplied as of Python 2.5 as the replacement interface for md5 # and other secure hashes. In 2.6, md5 is deprecated. Import hashlib if # available, avoiding a deprecation warning under 2.6. Import md5 otherwise, # preserving 2.4 compatibility. try: import hashlib _new_md5 = hashlib.md5 except ImportError: import md5 _new_md5 = md5.new # Initialize random number generator random.seed() # GUIDs for project types ENTRY_TYPE_GUIDS = { 'project': '{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}', 'folder': '{2150E333-8FDC-42A3-9474-1A3956D46DE8}', } #------------------------------------------------------------------------------ # Helper functions def MakeGuid(name, seed='msvs_new'): """Returns a GUID for the specified target name. Args: name: Target name. seed: Seed for MD5 hash. Returns: A GUID-line string calculated from the name and seed. This generates something which looks like a GUID, but depends only on the name and seed. This means the same name/seed will always generate the same GUID, so that projects and solutions which refer to each other can explicitly determine the GUID to refer to explicitly. It also means that the GUID will not change when the project for a target is rebuilt. """ # Calculate a MD5 signature for the seed and name. d = _new_md5(str(seed) + str(name)).hexdigest().upper() # Convert most of the signature to GUID form (discard the rest) guid = ('{' + d[:8] + '-' + d[8:12] + '-' + d[12:16] + '-' + d[16:20] + '-' + d[20:32] + '}') return guid #------------------------------------------------------------------------------ class MSVSFolder: """Folder in a Visual Studio project or solution.""" def __init__(self, path, name = None, entries = None, guid = None, items = None): """Initializes the folder. Args: path: Full path to the folder. name: Name of the folder. entries: List of folder entries to nest inside this folder. May contain Folder or Project objects. May be None, if the folder is empty. guid: GUID to use for folder, if not None. items: List of solution items to include in the folder project. May be None, if the folder does not directly contain items. """ if name: self.name = name else: # Use last layer. self.name = os.path.basename(path) self.path = path self.guid = guid # Copy passed lists (or set to empty lists) self.entries = list(entries or []) self.items = list(items or []) self.entry_type_guid = ENTRY_TYPE_GUIDS['folder'] def get_guid(self): if self.guid is None: # Use consistent guids for folders (so things don't regenerate). self.guid = MakeGuid(self.path, seed='msvs_folder') return self.guid #------------------------------------------------------------------------------ class MSVSProject: """Visual Studio project.""" def __init__(self, path, name = None, dependencies = None, guid = None, config_platform_overrides = None): """Initializes the project. Args: path: Relative path to project file. name: Name of project. If None, the name will be the same as the base name of the project file. dependencies: List of other Project objects this project is dependent upon, if not None. guid: GUID to use for project, if not None. config_platform_overrides: optional dict of configuration platforms to used in place of the default for this target. """ self.path = path self.guid = guid if name: self.name = name else: # Use project filename self.name = os.path.splitext(os.path.basename(path))[0] # Copy passed lists (or set to empty lists) self.dependencies = list(dependencies or []) self.entry_type_guid = ENTRY_TYPE_GUIDS['project'] if config_platform_overrides: self.config_platform_overrides = config_platform_overrides else: self.config_platform_overrides = {} def get_guid(self): if self.guid is None: # Set GUID from path # TODO(rspangler): This is fragile. # 1. We can't just use the project filename sans path, since there could # be multiple projects with the same base name (for example, # foo/unittest.vcproj and bar/unittest.vcproj). # 2. The path needs to be relative to $SOURCE_ROOT, so that the project # GUID is the same whether it's included from base/base.sln or # foo/bar/baz/baz.sln. # 3. The GUID needs to be the same each time this builder is invoked, so # that we don't need to rebuild the solution when the project changes. # 4. We should be able to handle pre-built project files by reading the # GUID from the files. self.guid = MakeGuid(self.name) return self.guid #------------------------------------------------------------------------------ class MSVSSolution: """Visual Studio solution.""" def __init__(self, path, version, entries=None, variants=None, websiteProperties=True): """Initializes the solution. Args: path: Path to solution file. version: Format version to emit. entries: List of entries in solution. May contain Folder or Project objects. May be None, if the folder is empty. variants: List of build variant strings. If none, a default list will be used. websiteProperties: Flag to decide if the website properties section is generated. """ self.path = path self.websiteProperties = websiteProperties self.version = version # Copy passed lists (or set to empty lists) self.entries = list(entries or []) if variants: # Copy passed list self.variants = variants[:] else: # Use default self.variants = ['Debug|Win32', 'Release|Win32'] # TODO(rspangler): Need to be able to handle a mapping of solution config # to project config. Should we be able to handle variants being a dict, # or add a separate variant_map variable? If it's a dict, we can't # guarantee the order of variants since dict keys aren't ordered. # TODO(rspangler): Automatically write to disk for now; should delay until # node-evaluation time. self.Write() def Write(self, writer=common.WriteOnDiff): """Writes the solution file to disk. Raises: IndexError: An entry appears multiple times. """ # Walk the entry tree and collect all the folders and projects. all_entries = [] entries_to_check = self.entries[:] while entries_to_check: # Pop from the beginning of the list to preserve the user's order. e = entries_to_check.pop(0) # A project or folder can only appear once in the solution's folder tree. # This also protects from cycles. if e in all_entries: #raise IndexError('Entry "%s" appears more than once in solution' % # e.name) continue all_entries.append(e) # If this is a folder, check its entries too. if isinstance(e, MSVSFolder): entries_to_check += e.entries # Sort by name then guid (so things are in order on vs2008). def NameThenGuid(a, b): if a.name < b.name: return -1 if a.name > b.name: return 1 if a.get_guid() < b.get_guid(): return -1 if a.get_guid() > b.get_guid(): return 1 return 0 all_entries = sorted(all_entries, NameThenGuid) # Open file and print header f = writer(self.path) f.write('Microsoft Visual Studio Solution File, ' 'Format Version %s\r\n' % self.version.SolutionVersion()) f.write('# %s\r\n' % self.version.Description()) # Project entries for e in all_entries: f.write('Project("%s") = "%s", "%s", "%s"\r\n' % ( e.entry_type_guid, # Entry type GUID e.name, # Folder name e.path.replace('/', '\\'), # Folder name (again) e.get_guid(), # Entry GUID )) # TODO(rspangler): Need a way to configure this stuff if self.websiteProperties: f.write('\tProjectSection(WebsiteProperties) = preProject\r\n' '\t\tDebug.AspNetCompiler.Debug = "True"\r\n' '\t\tRelease.AspNetCompiler.Debug = "False"\r\n' '\tEndProjectSection\r\n') if isinstance(e, MSVSFolder): if e.items: f.write('\tProjectSection(SolutionItems) = preProject\r\n') for i in e.items: f.write('\t\t%s = %s\r\n' % (i, i)) f.write('\tEndProjectSection\r\n') if isinstance(e, MSVSProject): if e.dependencies: f.write('\tProjectSection(ProjectDependencies) = postProject\r\n') for d in e.dependencies: f.write('\t\t%s = %s\r\n' % (d.get_guid(), d.get_guid())) f.write('\tEndProjectSection\r\n') f.write('EndProject\r\n') # Global section f.write('Global\r\n') # Configurations (variants) f.write('\tGlobalSection(SolutionConfigurationPlatforms) = preSolution\r\n') for v in self.variants: f.write('\t\t%s = %s\r\n' % (v, v)) f.write('\tEndGlobalSection\r\n') # Sort config guids for easier diffing of solution changes. config_guids = [] config_guids_overrides = {} for e in all_entries: if isinstance(e, MSVSProject): config_guids.append(e.get_guid()) config_guids_overrides[e.get_guid()] = e.config_platform_overrides config_guids.sort() f.write('\tGlobalSection(ProjectConfigurationPlatforms) = postSolution\r\n') for g in config_guids: for v in self.variants: nv = config_guids_overrides[g].get(v, v) # Pick which project configuration to build for this solution # configuration. f.write('\t\t%s.%s.ActiveCfg = %s\r\n' % ( g, # Project GUID v, # Solution build configuration nv, # Project build config for that solution config )) # Enable project in this solution configuration. f.write('\t\t%s.%s.Build.0 = %s\r\n' % ( g, # Project GUID v, # Solution build configuration nv, # Project build config for that solution config )) f.write('\tEndGlobalSection\r\n') # TODO(rspangler): Should be able to configure this stuff too (though I've # never seen this be any different) f.write('\tGlobalSection(SolutionProperties) = preSolution\r\n') f.write('\t\tHideSolutionNode = FALSE\r\n') f.write('\tEndGlobalSection\r\n') # Folder mappings # TODO(rspangler): Should omit this section if there are no folders f.write('\tGlobalSection(NestedProjects) = preSolution\r\n') for e in all_entries: if not isinstance(e, MSVSFolder): continue # Does not apply to projects, only folders for subentry in e.entries: f.write('\t\t%s = %s\r\n' % (subentry.get_guid(), e.get_guid())) f.write('\tEndGlobalSection\r\n') f.write('EndGlobal\r\n') f.close()
bsd-3-clause
ran0101/namebench
nb_third_party/jinja2/exceptions.py
398
4530
# -*- coding: utf-8 -*- """ jinja2.exceptions ~~~~~~~~~~~~~~~~~ Jinja exceptions. :copyright: (c) 2010 by the Jinja Team. :license: BSD, see LICENSE for more details. """ class TemplateError(Exception): """Baseclass for all template errors.""" def __init__(self, message=None): if message is not None: message = unicode(message).encode('utf-8') Exception.__init__(self, message) @property def message(self): if self.args: message = self.args[0] if message is not None: return message.decode('utf-8', 'replace') class TemplateNotFound(IOError, LookupError, TemplateError): """Raised if a template does not exist.""" # looks weird, but removes the warning descriptor that just # bogusly warns us about message being deprecated message = None def __init__(self, name, message=None): IOError.__init__(self) if message is None: message = name self.message = message self.name = name self.templates = [name] def __str__(self): return self.message.encode('utf-8') # unicode goes after __str__ because we configured 2to3 to rename # __unicode__ to __str__. because the 2to3 tree is not designed to # remove nodes from it, we leave the above __str__ around and let # it override at runtime. def __unicode__(self): return self.message class TemplatesNotFound(TemplateNotFound): """Like :class:`TemplateNotFound` but raised if multiple templates are selected. This is a subclass of :class:`TemplateNotFound` exception, so just catching the base exception will catch both. .. versionadded:: 2.2 """ def __init__(self, names=(), message=None): if message is None: message = u'non of the templates given were found: ' + \ u', '.join(map(unicode, names)) TemplateNotFound.__init__(self, names and names[-1] or None, message) self.templates = list(names) class TemplateSyntaxError(TemplateError): """Raised to tell the user that there is a problem with the template.""" def __init__(self, message, lineno, name=None, filename=None): TemplateError.__init__(self, message) self.lineno = lineno self.name = name self.filename = filename self.source = None # this is set to True if the debug.translate_syntax_error # function translated the syntax error into a new traceback self.translated = False def __str__(self): return unicode(self).encode('utf-8') # unicode goes after __str__ because we configured 2to3 to rename # __unicode__ to __str__. because the 2to3 tree is not designed to # remove nodes from it, we leave the above __str__ around and let # it override at runtime. def __unicode__(self): # for translated errors we only return the message if self.translated: return self.message # otherwise attach some stuff location = 'line %d' % self.lineno name = self.filename or self.name if name: location = 'File "%s", %s' % (name, location) lines = [self.message, ' ' + location] # if the source is set, add the line to the output if self.source is not None: try: line = self.source.splitlines()[self.lineno - 1] except IndexError: line = None if line: lines.append(' ' + line.strip()) return u'\n'.join(lines) class TemplateAssertionError(TemplateSyntaxError): """Like a template syntax error, but covers cases where something in the template caused an error at compile time that wasn't necessarily caused by a syntax error. However it's a direct subclass of :exc:`TemplateSyntaxError` and has the same attributes. """ class TemplateRuntimeError(TemplateError): """A generic runtime error in the template engine. Under some situations Jinja may raise this exception. """ class UndefinedError(TemplateRuntimeError): """Raised if a template tries to operate on :class:`Undefined`.""" class SecurityError(TemplateRuntimeError): """Raised if a template tries to do something insecure if the sandbox is enabled. """ class FilterArgumentError(TemplateRuntimeError): """This error is raised if a filter was called with inappropriate arguments """
apache-2.0
yamt/neutron
quantum/api/rpc/agentnotifiers/dhcp_rpc_agent_api.py
2
5741
# Copyright (c) 2013 OpenStack Foundation. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or # implied. # See the License for the specific language governing permissions and # limitations under the License. from quantum.common import constants from quantum.common import topics from quantum.common import utils from quantum import manager from quantum.openstack.common import log as logging from quantum.openstack.common.rpc import proxy LOG = logging.getLogger(__name__) class DhcpAgentNotifyAPI(proxy.RpcProxy): """API for plugin to notify DHCP agent.""" BASE_RPC_API_VERSION = '1.0' # It seems dhcp agent does not support bulk operation VALID_RESOURCES = ['network', 'subnet', 'port'] VALID_METHOD_NAMES = ['network.create.end', 'network.update.end', 'network.delete.end', 'subnet.create.end', 'subnet.update.end', 'subnet.delete.end', 'port.create.end', 'port.update.end', 'port.delete.end'] def __init__(self, topic=topics.DHCP_AGENT): super(DhcpAgentNotifyAPI, self).__init__( topic=topic, default_version=self.BASE_RPC_API_VERSION) def _get_dhcp_agents(self, context, network_id): plugin = manager.QuantumManager.get_plugin() dhcp_agents = plugin.get_dhcp_agents_hosting_networks( context, [network_id], active=True) return [(dhcp_agent.host, dhcp_agent.topic) for dhcp_agent in dhcp_agents] def _notification_host(self, context, method, payload, host): """Notify the agent on host.""" self.cast( context, self.make_msg(method, payload=payload), topic='%s.%s' % (topics.DHCP_AGENT, host)) def _notification(self, context, method, payload, network_id): """Notify all the agents that are hosting the network.""" plugin = manager.QuantumManager.get_plugin() if (method != 'network_delete_end' and utils.is_extension_supported( plugin, constants.AGENT_SCHEDULER_EXT_ALIAS)): if method == 'port_create_end': # we don't schedule when we create network # because we want to give admin a chance to # schedule network manually by API adminContext = (context if context.is_admin else context.elevated()) network = plugin.get_network(adminContext, network_id) chosen_agent = plugin.schedule_network(adminContext, network) if chosen_agent: self._notification_host( context, 'network_create_end', {'network': {'id': network_id}}, chosen_agent['host']) for (host, topic) in self._get_dhcp_agents(context, network_id): self.cast( context, self.make_msg(method, payload=payload), topic='%s.%s' % (topic, host)) else: # besides the non-agentscheduler plugin, # There is no way to query who is hosting the network # when the network is deleted, so we need to fanout self._notification_fanout(context, method, payload) def _notification_fanout(self, context, method, payload): """Fanout the payload to all dhcp agents.""" self.fanout_cast( context, self.make_msg(method, payload=payload), topic=topics.DHCP_AGENT) def network_removed_from_agent(self, context, network_id, host): self._notification_host(context, 'network_delete_end', {'network_id': network_id}, host) def network_added_to_agent(self, context, network_id, host): self._notification_host(context, 'network_create_end', {'network': {'id': network_id}}, host) def agent_updated(self, context, admin_state_up, host): self._notification_host(context, 'agent_updated', {'admin_state_up': admin_state_up}, host) def notify(self, context, data, methodname): # data is {'key' : 'value'} with only one key if methodname not in self.VALID_METHOD_NAMES: return obj_type = data.keys()[0] if obj_type not in self.VALID_RESOURCES: return obj_value = data[obj_type] network_id = None if obj_type == 'network' and 'id' in obj_value: network_id = obj_value['id'] elif obj_type in ['port', 'subnet'] and 'network_id' in obj_value: network_id = obj_value['network_id'] if not network_id: return methodname = methodname.replace(".", "_") if methodname.endswith("_delete_end"): if 'id' in obj_value: self._notification(context, methodname, {obj_type + '_id': obj_value['id']}, network_id) else: self._notification(context, methodname, data, network_id)
apache-2.0
yzl0083/orange
Orange/OrangeWidgets/Classify/OWCN2.py
6
13020
""" <name>CN2</name> <description>Rule-based (CN2) learner/classifier.</description> <icon>icons/CN2.svg</icon> <contact>Ales Erjavec (ales.erjavec(@at@)fri.uni-lj.si)</contact> <priority>300</priority> """ from OWWidget import * import OWGUI, orange, orngCN2, sys from orngWrap import PreprocessedLearner NAME = "CN2" DESCRIPTION = "Rule-based (CN2) learner/classifier" AUTHOR = "Ales Erjavec" PRIORITY = 300 ICON = "icons/CN2.svg" # Sphinx documentation label reference HELP_REF = "CN2 Rules" INPUTS = ( dict(name="Data", type=ExampleTable, handler="dataset", doc="Training data set", id="train-data"), dict(name="Preprocess", type=PreprocessedLearner, handler="setPreprocessor", doc="Data preprocessor", id="preprocessor") ) OUTPUTS = ( dict(name="Learner", type=orange.Learner, doc="A CN2 Rules learner instance", id="learner"), dict(name="Classifier", type=orange.Classifier, doc="A rule classifier induced from given training data.", id="classifier"), dict(name="Unordered CN2 Classifier", type=orngCN2.CN2UnorderedClassifier, doc="Same as 'Classifier'", id="unordered-cn2-classifier") ) class CN2ProgressBar(orange.ProgressCallback): def __init__(self, widget, start=0.0, end=0.0): self.start = start self.end = end self.widget = widget orange.ProgressCallback.__init__(self) def __call__(self,value,a): self.widget.progressBarSet(100*(self.start+(self.end-self.start)*value)) class OWCN2(OWWidget): settingsList=["name", "QualityButton", "CoveringButton", "m", "MaxRuleLength", "useMaxRuleLength", "MinCoverage", "BeamWidth", "Alpha", "Weight", "stepAlpha"] callbackDeposit=[] def __init__(self, parent=None, signalManager=None): OWWidget.__init__(self, parent, signalManager,"CN2", wantMainArea=False, resizingEnabled=False) self.inputs = [("Data", ExampleTable, self.dataset), ("Preprocess", PreprocessedLearner, self.setPreprocessor)] self.outputs = [("Learner", orange.Learner),("Classifier",orange.Classifier),("Unordered CN2 Classifier", orngCN2.CN2UnorderedClassifier)] self.QualityButton = 0 self.CoveringButton = 0 self.Alpha = 0.05 self.stepAlpha = 0.2 self.BeamWidth = 5 self.MinCoverage = 0 self.MaxRuleLength = 0 self.useMaxRuleLength = False self.Weight = 0.9 self.m = 2 self.name = "CN2 rules" self.loadSettings() self.data=None self.preprocessor = None ##GUI labelWidth = 150 self.learnerName = OWGUI.lineEdit(self.controlArea, self, "name", box="Learner/classifier name", tooltip="Name to be used by other widgets to identify the learner/classifier") #self.learnerName.setText(self.name) OWGUI.separator(self.controlArea) self.ruleQualityBG = OWGUI.widgetBox(self.controlArea, "Rule quality estimation") self.ruleQualityBG.buttons = [] OWGUI.separator(self.controlArea) self.ruleValidationGroup = OWGUI.widgetBox(self.controlArea, "Pre-prunning (LRS)") OWGUI.separator(self.controlArea) OWGUI.spin(self.controlArea, self, "BeamWidth", 1, 100, box="Beam width", tooltip="The width of the search beam\n(number of rules to be specialized)") OWGUI.separator(self.controlArea) self.coveringAlgBG = OWGUI.widgetBox(self.controlArea, "Covering algorithm") self.coveringAlgBG.buttons = [] b1 = QRadioButton("Laplace", self.ruleQualityBG) self.ruleQualityBG.layout().addWidget(b1) g = OWGUI.widgetBox(self.ruleQualityBG, orientation="horizontal") b2 = QRadioButton("m-estimate", g) g.layout().addWidget(b2) self.mSpin = OWGUI.doubleSpin(g,self,"m",0,100) b3 = QRadioButton("EVC", self.ruleQualityBG) self.ruleQualityBG.layout().addWidget(b3) b4 = QRadioButton("WRACC", self.ruleQualityBG) self.ruleQualityBG.layout().addWidget(b4) self.ruleQualityBG.buttons = [b1, b2, b3, b4] for i, button in enumerate([b1, b2, b3, b4]): self.connect(button, SIGNAL("clicked()"), lambda v=i: self.qualityButtonPressed(v)) form = QFormLayout( labelAlignment=Qt.AlignLeft, formAlignment=Qt.AlignLeft, fieldGrowthPolicy=QFormLayout.AllNonFixedFieldsGrow ) self.ruleValidationGroup.layout().addLayout(form) alpha_spin = OWGUI.doubleSpin( self.ruleValidationGroup, self, "Alpha", 0, 1, 0.001, tooltip="Required significance of the difference between the " + "class distribution on all examples and covered examples") step_alpha_spin = OWGUI.doubleSpin( self.ruleValidationGroup, self, "stepAlpha", 0, 1, 0.001, tooltip="Required significance of each specialization of a rule.") min_coverage_spin = OWGUI.spin( self.ruleValidationGroup, self, "MinCoverage", 0, 100, tooltip="Minimum number of examples a rule must cover " + "(use 0 for not setting the limit)") min_coverage_spin.setSpecialValueText("Unlimited") # Check box needs to be in alayout for the form layout to center it # in the vertical direction. max_rule_box = OWGUI.widgetBox(self.ruleValidationGroup, "") max_rule_cb = OWGUI.checkBox( max_rule_box, self, "useMaxRuleLength", "Maximal rule length") max_rule_spin = OWGUI.spin( self.ruleValidationGroup, self, "MaxRuleLength", 1, 100, tooltip="Maximal number of conditions in the left " + "part of the rule") max_rule_cb.disables += [max_rule_spin] max_rule_cb.makeConsistent() form.addRow("Alpha (vs. default rule)", alpha_spin) form.addRow("Stopping Alpha (vs. parent rule)", step_alpha_spin) form.addRow("Minimum coverage", min_coverage_spin) form.addRow(max_rule_box, max_rule_spin) B1 = QRadioButton("Exclusive covering", self.coveringAlgBG) self.coveringAlgBG.layout().addWidget(B1) g = OWGUI.widgetBox(self.coveringAlgBG, orientation="horizontal") B2 = QRadioButton("Weighted covering", g) g.layout().addWidget(B2) self.coveringAlgBG.buttons = [B1, B2] self.weightSpin=OWGUI.doubleSpin(g,self,"Weight",0,0.95,0.05) for i, button in enumerate([B1, B2]): self.connect(button, SIGNAL("clicked()"), lambda v=i: self.coveringAlgButtonPressed(v)) OWGUI.separator(self.controlArea) self.btnApply = OWGUI.button(self.controlArea, self, "&Apply", callback=self.applySettings, default=True) self.Alpha=float(self.Alpha) self.stepAlpha=float(self.stepAlpha) self.Weight=float(self.Weight) #self.ruleQualityBG.buttons[self.QualityButton].setChecked(1) self.qualityButtonPressed(self.QualityButton) self.coveringAlgButtonPressed(self.CoveringButton) self.resize(100,100) self.setLearner() def sendReport(self): self.reportSettings("Learning parameters", [("Rule quality estimation", ["Laplace", "m-estimate with m=%.2f" % self.m, "WRACC"][self.QualityButton]), ("Pruning alpha (vs. default rule)", "%.3f" % self.Alpha), ("Stopping alpha (vs. parent rule)", "%.3f" % self.stepAlpha), ("Minimum coverage", "%.3f" % self.MinCoverage), ("Maximal rule length", self.MaxRuleLength if self.useMaxRuleLength else "unlimited"), ("Beam width", self.BeamWidth), ("Covering", ["Exclusive", "Weighted with a weight of %.2f" % self.Weight][self.CoveringButton])]) self.reportData(self.data) def setLearner(self): if hasattr(self, "btnApply"): self.btnApply.setFocus() #progress bar self.progressBarInit() #learner / specific handling in case of EVC learning (completely different type of class) if self.useMaxRuleLength: maxRuleLength = self.MaxRuleLength else: maxRuleLength = -1 if self.QualityButton == 2: self.learner=orngCN2.CN2EVCUnorderedLearner(width=self.BeamWidth, rule_sig=self.Alpha, att_sig=self.stepAlpha, min_coverage = self.MinCoverage, max_rule_complexity = maxRuleLength) if self.preprocessor: self.learner = self.preprocessor.wrapLearner(self.learner) self.learner.name = self.name # self.learner.progressCallback=CN2ProgressBar(self) self.send("Learner",self.learner) else: self.learner=orngCN2.CN2UnorderedLearner() self.learner.name = self.name # self.learner.progressCallback=CN2ProgressBar(self) # self.send("Learner",self.learner) ruleFinder=orange.RuleBeamFinder() if self.QualityButton==0: ruleFinder.evaluator=orange.RuleEvaluator_Laplace() elif self.QualityButton==1: ruleFinder.evaluator=orngCN2.mEstimate(self.m) elif self.QualityButton==3: ruleFinder.evaluator=orngCN2.WRACCEvaluator() ruleFinder.ruleStoppingValidator=orange.RuleValidator_LRS(alpha=self.stepAlpha, min_coverage=self.MinCoverage, max_rule_complexity=maxRuleLength) ruleFinder.validator=orange.RuleValidator_LRS(alpha=self.Alpha, min_coverage=self.MinCoverage, max_rule_complexity=maxRuleLength) ruleFinder.ruleFilter=orange.RuleBeamFilter_Width(width=self.BeamWidth) self.learner.ruleFinder=ruleFinder if self.CoveringButton==0: self.learner.coverAndRemove=orange.RuleCovererAndRemover_Default() elif self.CoveringButton==1: self.learner.coverAndRemove=orngCN2.CovererAndRemover_multWeights(mult=self.Weight) if self.preprocessor: self.learner = self.preprocessor.wrapLearner(self.learner) self.learner.name = self.name self.send("Learner", self.learner) self.classifier=None self.error() if self.data: oldDomain = orange.Domain(self.data.domain) learnData = orange.ExampleTable(oldDomain, self.data) self.learner.progressCallback=CN2ProgressBar(self) self.classifier=self.learner(learnData) self.learner.progressCallback=None self.classifier.name=self.name for r in self.classifier.rules: r.examples = orange.ExampleTable(oldDomain, r.examples) self.classifier.examples = orange.ExampleTable(oldDomain, self.classifier.examples) self.classifier.setattr("data",self.classifier.examples) self.error("") ## except orange.KernelException, (errValue): ## self.classifier=None ## self.error(errValue) ## except Exception: ## self.classifier=None ## if not self.data.domain.classVar: ## self.error("Classless domain.") ## elif self.data.domain.classVar.varType == orange.VarTypes.Continuous: ## self.error("CN2 can learn only from discrete class.") ## else: ## self.error("Unknown error") self.send("Classifier", self.classifier) self.send("Unordered CN2 Classifier", self.classifier) self.progressBarFinished() def dataset(self, data): #self.data=data self.data = self.isDataWithClass(data, orange.VarTypes.Discrete, checkMissing=True) and data or None self.setLearner() def setPreprocessor(self, pp): self.preprocessor = pp self.setLearner() def qualityButtonPressed(self, id=0): self.QualityButton = id for i in range(len(self.ruleQualityBG.buttons)): self.ruleQualityBG.buttons[i].setChecked(id == i) self.mSpin.control.setEnabled(id == 1) self.coveringAlgBG.setEnabled(not id == 2) def coveringAlgButtonPressed(self,id=0): self.CoveringButton = id for i in range(len(self.coveringAlgBG.buttons)): self.coveringAlgBG.buttons[i].setChecked(id == i) self.weightSpin.control.setEnabled(id == 1) def applySettings(self): self.setLearner() if __name__=="__main__": app=QApplication(sys.argv) w=OWCN2() #w.dataset(orange.ExampleTable("titanic.tab")) w.dataset(orange.ExampleTable("titanic.tab")) w.show() app.exec_() w.saveSettings()
gpl-3.0
fenimore/freeebot
freeebot.py
1
5664
#!/usr/bin/env python """Twitter Bot for posting craigslist postings of Free Stuff Currently set up for New York. Example usage: python tweetstuffs.py Attributes: - NO_IMAGE -- link for when there is no image found - FILE -- path to tmp file - PATH -- current directory - C_KEY, C_SECRET, A_TOKEN, A_TOKEN_SECRET -- twitter api tokens @author: Fenimore Love @license: MIT @date: 2015-2016 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. """ import re, sys, os, time, urllib.error, urllib.request from datetime import datetime from time import gmtime, strftime, sleep import tweepy #from freestuffs import stuff_scraper from freestuffs.stuff_scraper import StuffScraper from secrets import * # ====== Individual bot configuration ========================== bot_username = 'freeebot' logfile = bot_username # ============================================================== PATH = os.getcwd() if not os.path.exists(PATH + '/tmp/'): os.makedirs(PATH + '/tmp/') if not os.path.exists(PATH + '/log/'): os.makedirs(PATH + '/log/') NO_IMAGE = 'http://upload.wikimedia.org/wikipedia/commons/a/ac/No_image_available.svg' FILE = PATH + '/tmp/tmp-filename.jpg' def create_tweet(stuff): """Create string for tweet with stuff. TODO: replace New York with NY TODO: add a hashtag """ post = {"title": stuff['title'], "loc" : stuff['location'], "url" : stuff['url']} _text = post["loc"].strip(', New York') + "\n" + post["title"] +" " + post["url"] + ' #FreeStuffNY' _text = check_length(_text, post) return _text def tweet(new_stuffs_set): """Tweet new free stuff.""" auth = tweepy.OAuthHandler(C_KEY, C_SECRET) auth.set_access_token(A_TOKEN, A_TOKEN_SECRET) api = tweepy.API(auth) # Unpack set of sorted tuples back into dicts stuffs = map(dict, new_stuffs_set) if len(list(new_stuffs_set)) is not 0: # if there exists new items for stuff in stuffs: tweet = create_tweet(stuff) if str(stuff['image']) == NO_IMAGE: isImage = False else: isImage = True try: urllib.request.urlretrieve(stuff['image'], FILE) except: log('image: '+ stuff['image'] + 'can\'t be found') isImage = False try: if isImage: log("\n\n Posting with Media \n " + tweet + "\n ----\n") api.update_with_media(FILE, status=tweet) else: log("\n\n Posting without media\n " + tweet + "\n ----\n") api.update_status(tweet) except tweepy.TweepError as e: log('Failure ' + stuff['title']) log(e.reason) else: print("\n ----\n") def check_length(tweet, post): """Check if tweet is proper length.""" size = len(tweet) - len(post["url"]) if size < 145: # tweet is good return tweet else: log("Tweet too long") tweet = post["loc"] + "\n" + post["title"] + " " + post["url"] size = len(tweet) - post["url"] if size > 144: # tweet is still not good tweet = post["title"] + " " + post["url"] return tweet return tweet def log(message): """Log message to logfile. And print it out.""" # TODO: fix date = strftime("-%d-%b-%Y", gmtime()) path = os.path.realpath(os.path.join(os.getcwd(), 'log')) with open(os.path.join(path, logfile + date + '.log'),'a+') as f: t = strftime("%d %b %Y %H:%M:%S", gmtime()) print("\n" + t + " " + message) # print it tooo... f.write("\n" + t + " " + message) if __name__ == "__main__": """Tweet newly posted Free stuff objects. Using sets of the tupled-sorted-dict-stuffs to compare old scrapes and new. No need calling for precise, as twitter doesn't need the coordinates. If the set has 15 items, doesn't post, in order to stop flooding twitter on start up. """ #process_log = open(os.path.join('log', logfile_username),'a+') _location = 'newyork' # TODO: Change to brooklyn? stale_set = set() # the B set is what has already been log("\n\nInitiating\n\n") while True: stuffs = [] # a list of dicts for stuff in StuffScraper(_location, 15).stuffs: # convert stuff stuff_dict = {'title':stuff.thing, # object into dict 'location':stuff.location, 'url':stuff.url, 'image':stuff.image} stuffs.append(stuff_dict) fresh_set = set() # A set, Fresh out the oven for stuff in stuffs: tup = tuple(sorted(stuff.items())) fresh_set.add(tup) """Evaluate if there have been new posts""" ready_set = fresh_set - stale_set # Get the difference stale_set = fresh_set if len(list(ready_set)) is not 15: tweet(ready_set) log("\n New Stuffs : " + str(len(list(ready_set)))+ "\n Todays Stuffs : "+ str(len(list(stale_set)))+ "\n\n Sleep Now (-_-)Zzz... \n") sleep(1000) # 3600 Seconds = Hour
mit
disqus/django-mailviews
mailviews/tests/utils.py
5
2314
# flake8: noqa """ Backport of `django.test.utils.override_settings` from Django 1.3 and above. """ from functools import wraps from django.conf import settings, UserSettingsHolder class override_settings(object): """ Acts as either a decorator, or a context manager. If it's a decorator it takes a function and returns a wrapped function. If it's a contextmanager it's used with the ``with`` statement. In either event entering/exiting are called before and after, respectively, the function/block is executed. """ def __init__(self, **kwargs): self.options = kwargs self.wrapped = settings._wrapped def __enter__(self): self.enable() def __exit__(self, exc_type, exc_value, traceback): self.disable() def __call__(self, test_func): from django.test import TransactionTestCase if isinstance(test_func, type) and issubclass(test_func, TransactionTestCase): original_pre_setup = test_func._pre_setup original_post_teardown = test_func._post_teardown def _pre_setup(innerself): self.enable() original_pre_setup(innerself) def _post_teardown(innerself): original_post_teardown(innerself) self.disable() test_func._pre_setup = _pre_setup test_func._post_teardown = _post_teardown return test_func else: @wraps(test_func) def inner(*args, **kwargs): with self: return test_func(*args, **kwargs) return inner def enable(self): override = UserSettingsHolder(settings._wrapped) for key, new_value in self.options.items(): setattr(override, key, new_value) settings._wrapped = override # for key, new_value in self.options.items(): # setting_changed.send(sender=settings._wrapped.__class__, # setting=key, value=new_value) def disable(self): settings._wrapped = self.wrapped for key in self.options: new_value = getattr(settings, key, None) # setting_changed.send(sender=settings._wrapped.__class__, # setting=key, value=new_value)
apache-2.0
alhowaidi/cvmfsNDN
python/parser.py
6
4026
import math class Counter: def __init__(self, name, number, description): self.name = name self.description = description try: self.values = [int(number)] except ValueError: self.values = [0] def sum(self): counter = 0.0 for n in self.values: counter += n return counter def avg(self): return self.sum() / len(self.values) def variance(self): counter = 0.0 average = self.avg() for n in self.values: diff = n - average counter += diff * diff return counter / len(self.values) def std(self): return math.sqrt(self.variance()) class Parser: def __init__(self, filename=None): self.counters = {} self.warm_cache = False self.repository = "" if filename is not None: self.parse(filename) @staticmethod def parse_boolean(string): return string == "yes" or string == "true" \ or string == "TRUE" or string == "True" def __parseline(self, line): if line[0] == "#": parameter = line[1:-1].replace(" ", "").split("=") if parameter[0] == "warm_cache": self.warm_cache = Parser.parse_boolean(parameter[1]) elif parameter[0] == "repo": self.repository = parameter[1].split(".")[0] else: params = line.strip().split("|") if len(params) == 3: counter = Counter(params[0], params[1], params[2]) if counter.name in self.counters: self.counters[counter.name].values += counter.values else: self.counters[counter.name] = counter def parse(self, filename): datafile = open(filename, "r") for line in datafile: self.__parseline(line) datafile.close() def to_csv(self, filename): csv = open(filename, "w") csv.write(";" + self.repository) for counter in self.counters: csv.write(counter.name + ";" + str(counter.avg())) csv.close() @staticmethod def to_csv_comparison(parser1, parser2, filename): csv = open(filename, "w") csv.write(";origin_avg;origin_std;external_avg;external_std\n") for key in parser1.counters: csv.write(parser1.counters[key].name + ";" + str(parser1.counters[key].avg()).replace(".", ",") + ";" + str(parser1.counters[key].std()).replace(".", ",") + ";" + str(parser2.counters[key].avg()).replace(".", ",") + ";" + str(parser2.counters[key].std()).replace(".", ",") + "\n") csv.close() @staticmethod def to_csv_multiple_comparison(parser_list1, parser_list2, filename): counter_names = parser_list1.values()[0].counters.keys() repository_names = sorted(parser_list1) csv = open(filename, "w") for repository_name in repository_names: pos = repository_name.rfind("/") + 1 csv.write(";" + repository_name[pos:] + ";;;") csv.write("\n") for i in range(0, len(parser_list1)): csv.write(";origin_avg;origin_std;external_avg;external_std") csv.write("\n") for counter_name in counter_names: csv.write(counter_name + ";") for repository_name in repository_names: parser1 = parser_list1[repository_name] parser2 = parser_list2[repository_name] csv.write(str(parser1.counters[counter_name].avg()).replace(".", ",") + ";" + str(parser1.counters[counter_name].std()).replace(".", ",") + ";" + str(parser2.counters[counter_name].avg()).replace(".", ",") + ";" + str(parser2.counters[counter_name].std()).replace(".", ",") + ";") csv.write("\n") csv.close()
bsd-3-clause
michelts/lettuce
tests/integration/lib/Django-1.2.5/django/core/cache/backends/locmem.py
46
4062
"Thread-safe in-memory cache backend." import time try: import cPickle as pickle except ImportError: import pickle from django.core.cache.backends.base import BaseCache from django.utils.synch import RWLock class CacheClass(BaseCache): def __init__(self, _, params): BaseCache.__init__(self, params) self._cache = {} self._expire_info = {} max_entries = params.get('max_entries', 300) try: self._max_entries = int(max_entries) except (ValueError, TypeError): self._max_entries = 300 cull_frequency = params.get('cull_frequency', 3) try: self._cull_frequency = int(cull_frequency) except (ValueError, TypeError): self._cull_frequency = 3 self._lock = RWLock() def add(self, key, value, timeout=None): self.validate_key(key) self._lock.writer_enters() try: exp = self._expire_info.get(key) if exp is None or exp <= time.time(): try: self._set(key, pickle.dumps(value), timeout) return True except pickle.PickleError: pass return False finally: self._lock.writer_leaves() def get(self, key, default=None): self.validate_key(key) self._lock.reader_enters() try: exp = self._expire_info.get(key) if exp is None: return default elif exp > time.time(): try: return pickle.loads(self._cache[key]) except pickle.PickleError: return default finally: self._lock.reader_leaves() self._lock.writer_enters() try: try: del self._cache[key] del self._expire_info[key] except KeyError: pass return default finally: self._lock.writer_leaves() def _set(self, key, value, timeout=None): if len(self._cache) >= self._max_entries: self._cull() if timeout is None: timeout = self.default_timeout self._cache[key] = value self._expire_info[key] = time.time() + timeout def set(self, key, value, timeout=None): self.validate_key(key) self._lock.writer_enters() # Python 2.4 doesn't allow combined try-except-finally blocks. try: try: self._set(key, pickle.dumps(value), timeout) except pickle.PickleError: pass finally: self._lock.writer_leaves() def has_key(self, key): self.validate_key(key) self._lock.reader_enters() try: exp = self._expire_info.get(key) if exp is None: return False elif exp > time.time(): return True finally: self._lock.reader_leaves() self._lock.writer_enters() try: try: del self._cache[key] del self._expire_info[key] except KeyError: pass return False finally: self._lock.writer_leaves() def _cull(self): if self._cull_frequency == 0: self.clear() else: doomed = [k for (i, k) in enumerate(self._cache) if i % self._cull_frequency == 0] for k in doomed: self._delete(k) def _delete(self, key): try: del self._cache[key] except KeyError: pass try: del self._expire_info[key] except KeyError: pass def delete(self, key): self.validate_key(key) self._lock.writer_enters() try: self._delete(key) finally: self._lock.writer_leaves() def clear(self): self._cache.clear() self._expire_info.clear()
gpl-3.0
mrpiracyPT/repository.mrpiracy
plugin.video.mrpiracy/resources/lib/js2py/legecy_translators/translator.py
96
5676
from flow import translate_flow from constants import remove_constants, recover_constants from objects import remove_objects, remove_arrays, translate_object, translate_array, set_func_translator from functions import remove_functions, reset_inline_count from jsparser import inject_before_lval, indent, dbg TOP_GLOBAL = '''from js2py.pyjs import *\nvar = Scope( JS_BUILTINS )\nset_global_object(var)\n''' def translate_js(js, top=TOP_GLOBAL): """js has to be a javascript source code. returns equivalent python code.""" # Remove constant literals no_const, constants = remove_constants(js) #print 'const count', len(constants) # Remove object literals no_obj, objects, obj_count = remove_objects(no_const) #print 'obj count', len(objects) # Remove arrays no_arr, arrays, arr_count = remove_arrays(no_obj) #print 'arr count', len(arrays) # Here remove and replace functions reset_inline_count() no_func, hoisted, inline = remove_functions(no_arr) #translate flow and expressions py_seed, to_register = translate_flow(no_func) # register variables and hoisted functions #top += '# register variables\n' top += 'var.registers(%s)\n' % str(to_register + hoisted.keys()) #Recover functions # hoisted functions recovery defs = '' #defs += '# define hoisted functions\n' #print len(hoisted) , 'HH'*40 for nested_name, nested_info in hoisted.iteritems(): nested_block, nested_args = nested_info new_code = translate_func('PyJsLvalTempHoisted', nested_block, nested_args) new_code += 'PyJsLvalTempHoisted.func_name = %s\n' %repr(nested_name) defs += new_code +'\nvar.put(%s, PyJsLvalTempHoisted)\n' % repr(nested_name) #defs += '# Everting ready!\n' # inline functions recovery for nested_name, nested_info in inline.iteritems(): nested_block, nested_args = nested_info new_code = translate_func(nested_name, nested_block, nested_args) py_seed = inject_before_lval(py_seed, nested_name.split('@')[0], new_code) # add hoisted definitiond - they have literals that have to be recovered py_seed = defs + py_seed #Recover arrays for arr_lval, arr_code in arrays.iteritems(): translation, obj_count, arr_count = translate_array(arr_code, arr_lval, obj_count, arr_count) py_seed = inject_before_lval(py_seed, arr_lval, translation) #Recover objects for obj_lval, obj_code in objects.iteritems(): translation, obj_count, arr_count = translate_object(obj_code, obj_lval, obj_count, arr_count) py_seed = inject_before_lval(py_seed, obj_lval, translation) #Recover constants py_code = recover_constants(py_seed, constants) return top + py_code def translate_func(name, block, args): """Translates functions and all nested functions to Python code. name - name of that function (global functions will be available under var while inline will be available directly under this name ) block - code of the function (*with* brackets {} ) args - arguments that this function takes""" inline = name.startswith('PyJsLvalInline') real_name = '' if inline: name, real_name = name.split('@') arglist = ', '.join(args) +', ' if args else '' code = '@Js\ndef %s(%sthis, arguments, var=var):\n' % (name, arglist) # register local variables scope = "'this':this, 'arguments':arguments" #it will be a simple dictionary for arg in args: scope += ', %s:%s' %(repr(arg), arg) if real_name: scope += ', %s:%s' % (repr(real_name), name) code += indent('var = Scope({%s}, var)\n' % scope) block, nested_hoisted, nested_inline = remove_functions(block) py_code, to_register = translate_flow(block) #register variables declared with var and names of hoisted functions. to_register += nested_hoisted.keys() if to_register: code += indent('var.registers(%s)\n'% str(to_register)) for nested_name, info in nested_hoisted.iteritems(): nested_block, nested_args = info new_code = translate_func('PyJsLvalTempHoisted', nested_block, nested_args) # Now put definition of hoisted function on the top code += indent(new_code) code += indent('PyJsLvalTempHoisted.func_name = %s\n' %repr(nested_name)) code += indent('var.put(%s, PyJsLvalTempHoisted)\n' % repr(nested_name)) for nested_name, info in nested_inline.iteritems(): nested_block, nested_args = info new_code = translate_func(nested_name, nested_block, nested_args) # Inject definitions of inline functions just before usage # nested inline names have this format : LVAL_NAME@REAL_NAME py_code = inject_before_lval(py_code, nested_name.split('@')[0], new_code) if py_code.strip(): code += indent(py_code) return code set_func_translator(translate_func) #print inject_before_lval(' chuj\n moj\n lval\nelse\n', 'lval', 'siema\njestem piter\n') import time #print time.time() #print translate_js('if (1) console.log("Hello, World!"); else if (5) console.log("Hello world?");') #print time.time() t = """ var x = [1,2,3,4,5,6]; for (var e in x) {console.log(e); delete x[3];} console.log(5 in [1,2,3,4,5]); """ SANDBOX =''' import traceback try: %s except: print traceback.format_exc() print raw_input('Press Enter to quit') ''' if __name__=='__main__': # test with jq if works then it really works :) #with open('jq.js', 'r') as f: #jq = f.read() #res = translate_js(jq) res = translate_js(t) dbg(SANDBOX% indent(res)) print 'Done'
gpl-2.0