dataset
stringclasses
1 value
id
stringlengths
32
32
domain
stringclasses
1 value
text
stringlengths
438
869k
timestamp
timestamp[s]date
2026-03-31 15:30:28
2026-03-31 15:37:32
codeparrot_clean
663b385249ce5c4aa020cb6941bb0b1b
code
# Copyright 2014 IBM Corp. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. """ Tests for volume replication API code. """ import json import mock from oslo_config import cfg import webob from cinder import context from cinder import test from cinder.tests.unit.api import fakes from cinder.tests.unit import utils as tests_utils CONF = cfg.CONF def app(): # no auth, just let environ['cinder.context'] pass through api = fakes.router.APIRouter() mapper = fakes.urlmap.URLMap() mapper['/v2'] = api return mapper class VolumeReplicationAPITestCase(test.TestCase): """Test Cases for replication API.""" def setUp(self): super(VolumeReplicationAPITestCase, self).setUp() self.ctxt = context.RequestContext('admin', 'fake', True) self.volume_params = { 'host': CONF.host, 'size': 1} def _get_resp(self, operation, volume_id, xml=False): """Helper for a replication action req for the specified volume_id.""" req = webob.Request.blank('/v2/fake/volumes/%s/action' % volume_id) req.method = 'POST' if xml: body = '<os-%s-replica/>' % operation req.headers['Content-Type'] = 'application/xml' req.headers['Accept'] = 'application/xml' req.body = body else: body = {'os-%s-replica' % operation: ''} req.headers['Content-Type'] = 'application/json' req.body = json.dumps(body) req.environ['cinder.context'] = context.RequestContext('admin', 'fake', True) res = req.get_response(app()) return req, res def test_promote_bad_id(self): (req, res) = self._get_resp('promote', 'fake') msg = ("request: %s\nresult: %s" % (req, res)) self.assertEqual(404, res.status_int, msg) def test_promote_bad_id_xml(self): (req, res) = self._get_resp('promote', 'fake', xml=True) msg = ("request: %s\nresult: %s" % (req, res)) self.assertEqual(404, res.status_int, msg) def test_promote_volume_not_replicated(self): volume = tests_utils.create_volume( self.ctxt, **self.volume_params) (req, res) = self._get_resp('promote', volume['id']) msg = ("request: %s\nresult: %s" % (req, res)) self.assertEqual(400, res.status_int, msg) def test_promote_volume_not_replicated_xml(self): volume = tests_utils.create_volume( self.ctxt, **self.volume_params) (req, res) = self._get_resp('promote', volume['id'], xml=True) msg = ("request: %s\nresult: %s" % (req, res)) self.assertEqual(400, res.status_int, msg) @mock.patch('cinder.volume.rpcapi.VolumeAPI.promote_replica') def test_promote_replication_volume_status(self, _rpcapi_promote): for status in ['error', 'in-use']: volume = tests_utils.create_volume(self.ctxt, status = status, replication_status = 'active', **self.volume_params) (req, res) = self._get_resp('promote', volume['id']) msg = ("request: %s\nresult: %s" % (req, res)) self.assertEqual(400, res.status_int, msg) for status in ['available']: volume = tests_utils.create_volume(self.ctxt, status = status, replication_status = 'active', **self.volume_params) (req, res) = self._get_resp('promote', volume['id']) msg = ("request: %s\nresult: %s" % (req, res)) self.assertEqual(202, res.status_int, msg) @mock.patch('cinder.volume.rpcapi.VolumeAPI.promote_replica') def test_promote_replication_volume_status_xml(self, _rpcapi_promote): for status in ['error', 'in-use']: volume = tests_utils.create_volume(self.ctxt, status = status, replication_status = 'active', **self.volume_params) (req, res) = self._get_resp('promote', volume['id'], xml=True) msg = ("request: %s\nresult: %s" % (req, res)) self.assertEqual(400, res.status_int, msg) for status in ['available']: volume = tests_utils.create_volume(self.ctxt, status = status, replication_status = 'active', **self.volume_params) (req, res) = self._get_resp('promote', volume['id'], xml=True) msg = ("request: %s\nresult: %s" % (req, res)) self.assertEqual(202, res.status_int, msg) @mock.patch('cinder.volume.rpcapi.VolumeAPI.promote_replica') def test_promote_replication_replication_status(self, _rpcapi_promote): for status in ['error', 'copying', 'inactive']: volume = tests_utils.create_volume(self.ctxt, status = 'available', replication_status = status, **self.volume_params) (req, res) = self._get_resp('promote', volume['id']) msg = ("request: %s\nresult: %s" % (req, res)) self.assertEqual(400, res.status_int, msg) for status in ['active', 'active-stopped']: volume = tests_utils.create_volume(self.ctxt, status = 'available', replication_status = status, **self.volume_params) (req, res) = self._get_resp('promote', volume['id']) msg = ("request: %s\nresult: %s" % (req, res)) self.assertEqual(202, res.status_int, msg) @mock.patch('cinder.volume.rpcapi.VolumeAPI.promote_replica') def test_promote_replication_replication_status_xml(self, _rpcapi_promote): for status in ['error', 'copying', 'inactive']: volume = tests_utils.create_volume(self.ctxt, status = 'available', replication_status = status, **self.volume_params) (req, res) = self._get_resp('promote', volume['id'], xml=True) msg = ("request: %s\nresult: %s" % (req, res)) self.assertEqual(400, res.status_int, msg) for status in ['active', 'active-stopped']: volume = tests_utils.create_volume(self.ctxt, status = 'available', replication_status = status, **self.volume_params) (req, res) = self._get_resp('promote', volume['id'], xml=True) msg = ("request: %s\nresult: %s" % (req, res)) self.assertEqual(202, res.status_int, msg) def test_reenable_bad_id(self): (req, res) = self._get_resp('reenable', 'fake') msg = ("request: %s\nresult: %s" % (req, res)) self.assertEqual(404, res.status_int, msg) def test_reenable_bad_id_xml(self): (req, res) = self._get_resp('reenable', 'fake', xml=True) msg = ("request: %s\nresult: %s" % (req, res)) self.assertEqual(404, res.status_int, msg) def test_reenable_volume_not_replicated(self): volume = tests_utils.create_volume( self.ctxt, **self.volume_params) (req, res) = self._get_resp('reenable', volume['id']) msg = ("request: %s\nresult: %s" % (req, res)) self.assertEqual(400, res.status_int, msg) def test_reenable_volume_not_replicated_xml(self): volume = tests_utils.create_volume( self.ctxt, **self.volume_params) (req, res) = self._get_resp('reenable', volume['id'], xml=True) msg = ("request: %s\nresult: %s" % (req, res)) self.assertEqual(400, res.status_int, msg) @mock.patch('cinder.volume.rpcapi.VolumeAPI.reenable_replication') def test_reenable_replication_replication_status(self, _rpcapi_promote): for status in ['active', 'copying']: volume = tests_utils.create_volume(self.ctxt, status = 'available', replication_status = status, **self.volume_params) (req, res) = self._get_resp('reenable', volume['id']) msg = ("request: %s\nresult: %s" % (req, res)) self.assertEqual(400, res.status_int, msg) for status in ['inactive', 'active-stopped', 'error']: volume = tests_utils.create_volume(self.ctxt, status = 'available', replication_status = status, **self.volume_params) (req, res) = self._get_resp('reenable', volume['id']) msg = ("request: %s\nresult: %s" % (req, res)) self.assertEqual(202, res.status_int, msg) @mock.patch('cinder.volume.rpcapi.VolumeAPI.reenable_replication') def test_reenable_replication_replication_status_xml(self, _rpcapi_promote): for status in ['active', 'copying']: volume = tests_utils.create_volume(self.ctxt, status = 'available', replication_status = status, **self.volume_params) (req, res) = self._get_resp('reenable', volume['id'], xml=True) msg = ("request: %s\nresult: %s" % (req, res)) self.assertEqual(400, res.status_int, msg) for status in ['inactive', 'active-stopped', 'error']: volume = tests_utils.create_volume(self.ctxt, status = 'available', replication_status = status, **self.volume_params) (req, res) = self._get_resp('reenable', volume['id'], xml=True) msg = ("request: %s\nresult: %s" % (req, res)) self.assertEqual(202, res.status_int, msg)
2026-03-31T15:30:28
codeparrot_clean
5b9828d3e0b31b8e4fc57df8ba9c219a
code
# changes by dscherer@cmu.edu # - IOBinding.open() replaces the current window with the opened file, # if the current window is both unmodified and unnamed # - IOBinding.loadfile() interprets Windows, UNIX, and Macintosh # end-of-line conventions, instead of relying on the standard library, # which will only understand the local convention. import os import types import sys import codecs import tempfile import tkFileDialog import tkMessageBox import re from Tkinter import * from SimpleDialog import SimpleDialog from idlelib.configHandler import idleConf try: from codecs import BOM_UTF8 except ImportError: # only available since Python 2.3 BOM_UTF8 = '\xef\xbb\xbf' # Try setting the locale, so that we can find out # what encoding to use try: import locale locale.setlocale(locale.LC_CTYPE, "") except (ImportError, locale.Error): pass # Encoding for file names filesystemencoding = sys.getfilesystemencoding() encoding = "ascii" if sys.platform == 'win32': # On Windows, we could use "mbcs". However, to give the user # a portable encoding name, we need to find the code page try: encoding = locale.getdefaultlocale()[1] codecs.lookup(encoding) except LookupError: pass else: try: # Different things can fail here: the locale module may not be # loaded, it may not offer nl_langinfo, or CODESET, or the # resulting codeset may be unknown to Python. We ignore all # these problems, falling back to ASCII encoding = locale.nl_langinfo(locale.CODESET) if encoding is None or encoding is '': # situation occurs on Mac OS X encoding = 'ascii' codecs.lookup(encoding) except (NameError, AttributeError, LookupError): # Try getdefaultlocale well: it parses environment variables, # which may give a clue. Unfortunately, getdefaultlocale has # bugs that can cause ValueError. try: encoding = locale.getdefaultlocale()[1] if encoding is None or encoding is '': # situation occurs on Mac OS X encoding = 'ascii' codecs.lookup(encoding) except (ValueError, LookupError): pass encoding = encoding.lower() coding_re = re.compile("coding[:=]\s*([-\w_.]+)") class EncodingMessage(SimpleDialog): "Inform user that an encoding declaration is needed." def __init__(self, master, enc): self.should_edit = False self.root = top = Toplevel(master) top.bind("<Return>", self.return_event) top.bind("<Escape>", self.do_ok) top.protocol("WM_DELETE_WINDOW", self.wm_delete_window) top.wm_title("I/O Warning") top.wm_iconname("I/O Warning") self.top = top l1 = Label(top, text="Non-ASCII found, yet no encoding declared. Add a line like") l1.pack(side=TOP, anchor=W) l2 = Entry(top, font="courier") l2.insert(0, "# -*- coding: %s -*-" % enc) # For some reason, the text is not selectable anymore if the # widget is disabled. # l2['state'] = DISABLED l2.pack(side=TOP, anchor = W, fill=X) l3 = Label(top, text="to your file\n" "Choose OK to save this file as %s\n" "Edit your general options to silence this warning" % enc) l3.pack(side=TOP, anchor = W) buttons = Frame(top) buttons.pack(side=TOP, fill=X) # Both return and cancel mean the same thing: do nothing self.default = self.cancel = 0 b1 = Button(buttons, text="Ok", default="active", command=self.do_ok) b1.pack(side=LEFT, fill=BOTH, expand=1) b2 = Button(buttons, text="Edit my file", command=self.do_edit) b2.pack(side=LEFT, fill=BOTH, expand=1) self._set_transient(master) def do_ok(self): self.done(0) def do_edit(self): self.done(1) def coding_spec(str): """Return the encoding declaration according to PEP 263. Raise LookupError if the encoding is declared but unknown. """ # Only consider the first two lines str = str.split("\n")[:2] str = "\n".join(str) match = coding_re.search(str) if not match: return None name = match.group(1) # Check whether the encoding is known import codecs try: codecs.lookup(name) except LookupError: # The standard encoding error does not indicate the encoding raise LookupError, "Unknown encoding "+name return name class IOBinding: def __init__(self, editwin): self.editwin = editwin self.text = editwin.text self.__id_open = self.text.bind("<<open-window-from-file>>", self.open) self.__id_save = self.text.bind("<<save-window>>", self.save) self.__id_saveas = self.text.bind("<<save-window-as-file>>", self.save_as) self.__id_savecopy = self.text.bind("<<save-copy-of-window-as-file>>", self.save_a_copy) self.fileencoding = None self.__id_print = self.text.bind("<<print-window>>", self.print_window) def close(self): # Undo command bindings self.text.unbind("<<open-window-from-file>>", self.__id_open) self.text.unbind("<<save-window>>", self.__id_save) self.text.unbind("<<save-window-as-file>>",self.__id_saveas) self.text.unbind("<<save-copy-of-window-as-file>>", self.__id_savecopy) self.text.unbind("<<print-window>>", self.__id_print) # Break cycles self.editwin = None self.text = None self.filename_change_hook = None def get_saved(self): return self.editwin.get_saved() def set_saved(self, flag): self.editwin.set_saved(flag) def reset_undo(self): self.editwin.reset_undo() filename_change_hook = None def set_filename_change_hook(self, hook): self.filename_change_hook = hook filename = None dirname = None def set_filename(self, filename): if filename and os.path.isdir(filename): self.filename = None self.dirname = filename else: self.filename = filename self.dirname = None self.set_saved(1) if self.filename_change_hook: self.filename_change_hook() def open(self, event=None, editFile=None): if self.editwin.flist: if not editFile: filename = self.askopenfile() else: filename=editFile if filename: # If the current window has no filename and hasn't been # modified, we replace its contents (no loss). Otherwise # we open a new window. But we won't replace the # shell window (which has an interp(reter) attribute), which # gets set to "not modified" at every new prompt. try: interp = self.editwin.interp except AttributeError: interp = None if not self.filename and self.get_saved() and not interp: self.editwin.flist.open(filename, self.loadfile) else: self.editwin.flist.open(filename) else: self.text.focus_set() return "break" # # Code for use outside IDLE: if self.get_saved(): reply = self.maybesave() if reply == "cancel": self.text.focus_set() return "break" if not editFile: filename = self.askopenfile() else: filename=editFile if filename: self.loadfile(filename) else: self.text.focus_set() return "break" eol = r"(\r\n)|\n|\r" # \r\n (Windows), \n (UNIX), or \r (Mac) eol_re = re.compile(eol) eol_convention = os.linesep # Default def loadfile(self, filename): try: # open the file in binary mode so that we can handle # end-of-line convention ourselves. f = open(filename,'rb') chars = f.read() f.close() except IOError, msg: tkMessageBox.showerror("I/O Error", str(msg), master=self.text) return False chars = self.decode(chars) # We now convert all end-of-lines to '\n's firsteol = self.eol_re.search(chars) if firsteol: self.eol_convention = firsteol.group(0) if isinstance(self.eol_convention, unicode): # Make sure it is an ASCII string self.eol_convention = self.eol_convention.encode("ascii") chars = self.eol_re.sub(r"\n", chars) self.text.delete("1.0", "end") self.set_filename(None) self.text.insert("1.0", chars) self.reset_undo() self.set_filename(filename) self.text.mark_set("insert", "1.0") self.text.see("insert") self.updaterecentfileslist(filename) return True def decode(self, chars): """Create a Unicode string If that fails, let Tcl try its best """ # Check presence of a UTF-8 signature first if chars.startswith(BOM_UTF8): try: chars = chars[3:].decode("utf-8") except UnicodeError: # has UTF-8 signature, but fails to decode... return chars else: # Indicates that this file originally had a BOM self.fileencoding = BOM_UTF8 return chars # Next look for coding specification try: enc = coding_spec(chars) except LookupError, name: tkMessageBox.showerror( title="Error loading the file", message="The encoding '%s' is not known to this Python "\ "installation. The file may not display correctly" % name, master = self.text) enc = None if enc: try: return unicode(chars, enc) except UnicodeError: pass # If it is ASCII, we need not to record anything try: return unicode(chars, 'ascii') except UnicodeError: pass # Finally, try the locale's encoding. This is deprecated; # the user should declare a non-ASCII encoding try: chars = unicode(chars, encoding) self.fileencoding = encoding except UnicodeError: pass return chars def maybesave(self): if self.get_saved(): return "yes" message = "Do you want to save %s before closing?" % ( self.filename or "this untitled document") confirm = tkMessageBox.askyesnocancel( title="Save On Close", message=message, default=tkMessageBox.YES, master=self.text) if confirm: reply = "yes" self.save(None) if not self.get_saved(): reply = "cancel" elif confirm is None: reply = "cancel" else: reply = "no" self.text.focus_set() return reply def save(self, event): if not self.filename: self.save_as(event) else: if self.writefile(self.filename): self.set_saved(True) try: self.editwin.store_file_breaks() except AttributeError: # may be a PyShell pass self.text.focus_set() return "break" def save_as(self, event): filename = self.asksavefile() if filename: if self.writefile(filename): self.set_filename(filename) self.set_saved(1) try: self.editwin.store_file_breaks() except AttributeError: pass self.text.focus_set() self.updaterecentfileslist(filename) return "break" def save_a_copy(self, event): filename = self.asksavefile() if filename: self.writefile(filename) self.text.focus_set() self.updaterecentfileslist(filename) return "break" def writefile(self, filename): self.fixlastline() chars = self.encode(self.text.get("1.0", "end-1c")) if self.eol_convention != "\n": chars = chars.replace("\n", self.eol_convention) try: f = open(filename, "wb") f.write(chars) f.flush() f.close() return True except IOError, msg: tkMessageBox.showerror("I/O Error", str(msg), master=self.text) return False def encode(self, chars): if isinstance(chars, types.StringType): # This is either plain ASCII, or Tk was returning mixed-encoding # text to us. Don't try to guess further. return chars # See whether there is anything non-ASCII in it. # If not, no need to figure out the encoding. try: return chars.encode('ascii') except UnicodeError: pass # If there is an encoding declared, try this first. try: enc = coding_spec(chars) failed = None except LookupError, msg: failed = msg enc = None if enc: try: return chars.encode(enc) except UnicodeError: failed = "Invalid encoding '%s'" % enc if failed: tkMessageBox.showerror( "I/O Error", "%s. Saving as UTF-8" % failed, master = self.text) # If there was a UTF-8 signature, use that. This should not fail if self.fileencoding == BOM_UTF8 or failed: return BOM_UTF8 + chars.encode("utf-8") # Try the original file encoding next, if any if self.fileencoding: try: return chars.encode(self.fileencoding) except UnicodeError: tkMessageBox.showerror( "I/O Error", "Cannot save this as '%s' anymore. Saving as UTF-8" \ % self.fileencoding, master = self.text) return BOM_UTF8 + chars.encode("utf-8") # Nothing was declared, and we had not determined an encoding # on loading. Recommend an encoding line. config_encoding = idleConf.GetOption("main","EditorWindow", "encoding") if config_encoding == 'utf-8': # User has requested that we save files as UTF-8 return BOM_UTF8 + chars.encode("utf-8") ask_user = True try: chars = chars.encode(encoding) enc = encoding if config_encoding == 'locale': ask_user = False except UnicodeError: chars = BOM_UTF8 + chars.encode("utf-8") enc = "utf-8" if not ask_user: return chars dialog = EncodingMessage(self.editwin.top, enc) dialog.go() if dialog.num == 1: # User asked us to edit the file encline = "# -*- coding: %s -*-\n" % enc firstline = self.text.get("1.0", "2.0") if firstline.startswith("#!"): # Insert encoding after #! line self.text.insert("2.0", encline) else: self.text.insert("1.0", encline) return self.encode(self.text.get("1.0", "end-1c")) return chars def fixlastline(self): c = self.text.get("end-2c") if c != '\n': self.text.insert("end-1c", "\n") def print_window(self, event): confirm = tkMessageBox.askokcancel( title="Print", message="Print to Default Printer", default=tkMessageBox.OK, master=self.text) if not confirm: self.text.focus_set() return "break" tempfilename = None saved = self.get_saved() if saved: filename = self.filename # shell undo is reset after every prompt, looks saved, probably isn't if not saved or filename is None: (tfd, tempfilename) = tempfile.mkstemp(prefix='IDLE_tmp_') filename = tempfilename os.close(tfd) if not self.writefile(tempfilename): os.unlink(tempfilename) return "break" platform = os.name printPlatform = True if platform == 'posix': #posix platform command = idleConf.GetOption('main','General', 'print-command-posix') command = command + " 2>&1" elif platform == 'nt': #win32 platform command = idleConf.GetOption('main','General','print-command-win') else: #no printing for this platform printPlatform = False if printPlatform: #we can try to print for this platform command = command % filename pipe = os.popen(command, "r") # things can get ugly on NT if there is no printer available. output = pipe.read().strip() status = pipe.close() if status: output = "Printing failed (exit status 0x%x)\n" % \ status + output if output: output = "Printing command: %s\n" % repr(command) + output tkMessageBox.showerror("Print status", output, master=self.text) else: #no printing for this platform message = "Printing is not enabled for this platform: %s" % platform tkMessageBox.showinfo("Print status", message, master=self.text) if tempfilename: os.unlink(tempfilename) return "break" opendialog = None savedialog = None filetypes = [ ("Python files", "*.py *.pyw", "TEXT"), ("Text files", "*.txt", "TEXT"), ("All files", "*"), ] def askopenfile(self): dir, base = self.defaultfilename("open") if not self.opendialog: self.opendialog = tkFileDialog.Open(master=self.text, filetypes=self.filetypes) filename = self.opendialog.show(initialdir=dir, initialfile=base) if isinstance(filename, unicode): filename = filename.encode(filesystemencoding) return filename def defaultfilename(self, mode="open"): if self.filename: return os.path.split(self.filename) elif self.dirname: return self.dirname, "" else: try: pwd = os.getcwd() except os.error: pwd = "" return pwd, "" def asksavefile(self): dir, base = self.defaultfilename("save") if not self.savedialog: self.savedialog = tkFileDialog.SaveAs(master=self.text, filetypes=self.filetypes) filename = self.savedialog.show(initialdir=dir, initialfile=base) if isinstance(filename, unicode): filename = filename.encode(filesystemencoding) return filename def updaterecentfileslist(self,filename): "Update recent file list on all editor windows" self.editwin.update_recent_files_list(filename) def test(): root = Tk() class MyEditWin: def __init__(self, text): self.text = text self.flist = None self.text.bind("<Control-o>", self.open) self.text.bind("<Control-s>", self.save) self.text.bind("<Alt-s>", self.save_as) self.text.bind("<Alt-z>", self.save_a_copy) def get_saved(self): return 0 def set_saved(self, flag): pass def reset_undo(self): pass def open(self, event): self.text.event_generate("<<open-window-from-file>>") def save(self, event): self.text.event_generate("<<save-window>>") def save_as(self, event): self.text.event_generate("<<save-window-as-file>>") def save_a_copy(self, event): self.text.event_generate("<<save-copy-of-window-as-file>>") text = Text(root) text.pack() text.focus_set() editwin = MyEditWin(text) io = IOBinding(editwin) root.mainloop() if __name__ == "__main__": test()
2026-03-31T15:30:28
codeparrot_clean
9ecfe16eaaee98dca194fa794741bdf6
code
""" Encoding Aliases Support This module is used by the encodings package search function to map encodings names to module names. Note that the search function normalizes the encoding names before doing the lookup, so the mapping will have to map normalized encoding names to module names. Contents: The following aliases dictionary contains mappings of all IANA character set names for which the Python core library provides codecs. In addition to these, a few Python specific codec aliases have also been added. """ aliases = { # Please keep this list sorted alphabetically by value ! # ascii codec '646' : 'ascii', 'ansi_x3.4_1968' : 'ascii', 'ansi_x3_4_1968' : 'ascii', # some email headers use this non-standard name 'ansi_x3.4_1986' : 'ascii', 'cp367' : 'ascii', 'csascii' : 'ascii', 'ibm367' : 'ascii', 'iso646_us' : 'ascii', 'iso_646.irv_1991' : 'ascii', 'iso_ir_6' : 'ascii', 'us' : 'ascii', 'us_ascii' : 'ascii', # base64_codec codec 'base64' : 'base64_codec', 'base_64' : 'base64_codec', # big5 codec 'big5_tw' : 'big5', 'csbig5' : 'big5', # big5hkscs codec 'big5_hkscs' : 'big5hkscs', 'hkscs' : 'big5hkscs', # bz2_codec codec 'bz2' : 'bz2_codec', # cp037 codec '037' : 'cp037', 'csibm037' : 'cp037', 'ebcdic_cp_ca' : 'cp037', 'ebcdic_cp_nl' : 'cp037', 'ebcdic_cp_us' : 'cp037', 'ebcdic_cp_wt' : 'cp037', 'ibm037' : 'cp037', 'ibm039' : 'cp037', # cp1026 codec '1026' : 'cp1026', 'csibm1026' : 'cp1026', 'ibm1026' : 'cp1026', # cp1140 codec '1140' : 'cp1140', 'ibm1140' : 'cp1140', # cp1250 codec '1250' : 'cp1250', 'windows_1250' : 'cp1250', # cp1251 codec '1251' : 'cp1251', 'windows_1251' : 'cp1251', # cp1252 codec '1252' : 'cp1252', 'windows_1252' : 'cp1252', # cp1253 codec '1253' : 'cp1253', 'windows_1253' : 'cp1253', # cp1254 codec '1254' : 'cp1254', 'windows_1254' : 'cp1254', # cp1255 codec '1255' : 'cp1255', 'windows_1255' : 'cp1255', # cp1256 codec '1256' : 'cp1256', 'windows_1256' : 'cp1256', # cp1257 codec '1257' : 'cp1257', 'windows_1257' : 'cp1257', # cp1258 codec '1258' : 'cp1258', 'windows_1258' : 'cp1258', # cp424 codec '424' : 'cp424', 'csibm424' : 'cp424', 'ebcdic_cp_he' : 'cp424', 'ibm424' : 'cp424', # cp437 codec '437' : 'cp437', 'cspc8codepage437' : 'cp437', 'ibm437' : 'cp437', # cp500 codec '500' : 'cp500', 'csibm500' : 'cp500', 'ebcdic_cp_be' : 'cp500', 'ebcdic_cp_ch' : 'cp500', 'ibm500' : 'cp500', # cp775 codec '775' : 'cp775', 'cspc775baltic' : 'cp775', 'ibm775' : 'cp775', # cp850 codec '850' : 'cp850', 'cspc850multilingual' : 'cp850', 'ibm850' : 'cp850', # cp852 codec '852' : 'cp852', 'cspcp852' : 'cp852', 'ibm852' : 'cp852', # cp855 codec '855' : 'cp855', 'csibm855' : 'cp855', 'ibm855' : 'cp855', # cp857 codec '857' : 'cp857', 'csibm857' : 'cp857', 'ibm857' : 'cp857', # cp858 codec '858' : 'cp858', 'csibm858' : 'cp858', 'ibm858' : 'cp858', # cp860 codec '860' : 'cp860', 'csibm860' : 'cp860', 'ibm860' : 'cp860', # cp861 codec '861' : 'cp861', 'cp_is' : 'cp861', 'csibm861' : 'cp861', 'ibm861' : 'cp861', # cp862 codec '862' : 'cp862', 'cspc862latinhebrew' : 'cp862', 'ibm862' : 'cp862', # cp863 codec '863' : 'cp863', 'csibm863' : 'cp863', 'ibm863' : 'cp863', # cp864 codec '864' : 'cp864', 'csibm864' : 'cp864', 'ibm864' : 'cp864', # cp865 codec '865' : 'cp865', 'csibm865' : 'cp865', 'ibm865' : 'cp865', # cp866 codec '866' : 'cp866', 'csibm866' : 'cp866', 'ibm866' : 'cp866', # cp869 codec '869' : 'cp869', 'cp_gr' : 'cp869', 'csibm869' : 'cp869', 'ibm869' : 'cp869', # cp932 codec '932' : 'cp932', 'ms932' : 'cp932', 'mskanji' : 'cp932', 'ms_kanji' : 'cp932', # cp949 codec '949' : 'cp949', 'ms949' : 'cp949', 'uhc' : 'cp949', # cp950 codec '950' : 'cp950', 'ms950' : 'cp950', # euc_jis_2004 codec 'jisx0213' : 'euc_jis_2004', 'eucjis2004' : 'euc_jis_2004', 'euc_jis2004' : 'euc_jis_2004', # euc_jisx0213 codec 'eucjisx0213' : 'euc_jisx0213', # euc_jp codec 'eucjp' : 'euc_jp', 'ujis' : 'euc_jp', 'u_jis' : 'euc_jp', # euc_kr codec 'euckr' : 'euc_kr', 'korean' : 'euc_kr', 'ksc5601' : 'euc_kr', 'ks_c_5601' : 'euc_kr', 'ks_c_5601_1987' : 'euc_kr', 'ksx1001' : 'euc_kr', 'ks_x_1001' : 'euc_kr', # gb18030 codec 'gb18030_2000' : 'gb18030', # gb2312 codec 'chinese' : 'gb2312', 'csiso58gb231280' : 'gb2312', 'euc_cn' : 'gb2312', 'euccn' : 'gb2312', 'eucgb2312_cn' : 'gb2312', 'gb2312_1980' : 'gb2312', 'gb2312_80' : 'gb2312', 'iso_ir_58' : 'gb2312', # gbk codec '936' : 'gbk', 'cp936' : 'gbk', 'ms936' : 'gbk', # hex_codec codec 'hex' : 'hex_codec', # hp_roman8 codec 'roman8' : 'hp_roman8', 'r8' : 'hp_roman8', 'csHPRoman8' : 'hp_roman8', # hz codec 'hzgb' : 'hz', 'hz_gb' : 'hz', 'hz_gb_2312' : 'hz', # iso2022_jp codec 'csiso2022jp' : 'iso2022_jp', 'iso2022jp' : 'iso2022_jp', 'iso_2022_jp' : 'iso2022_jp', # iso2022_jp_1 codec 'iso2022jp_1' : 'iso2022_jp_1', 'iso_2022_jp_1' : 'iso2022_jp_1', # iso2022_jp_2 codec 'iso2022jp_2' : 'iso2022_jp_2', 'iso_2022_jp_2' : 'iso2022_jp_2', # iso2022_jp_2004 codec 'iso_2022_jp_2004' : 'iso2022_jp_2004', 'iso2022jp_2004' : 'iso2022_jp_2004', # iso2022_jp_3 codec 'iso2022jp_3' : 'iso2022_jp_3', 'iso_2022_jp_3' : 'iso2022_jp_3', # iso2022_jp_ext codec 'iso2022jp_ext' : 'iso2022_jp_ext', 'iso_2022_jp_ext' : 'iso2022_jp_ext', # iso2022_kr codec 'csiso2022kr' : 'iso2022_kr', 'iso2022kr' : 'iso2022_kr', 'iso_2022_kr' : 'iso2022_kr', # iso8859_10 codec 'csisolatin6' : 'iso8859_10', 'iso_8859_10' : 'iso8859_10', 'iso_8859_10_1992' : 'iso8859_10', 'iso_ir_157' : 'iso8859_10', 'l6' : 'iso8859_10', 'latin6' : 'iso8859_10', # iso8859_11 codec 'thai' : 'iso8859_11', 'iso_8859_11' : 'iso8859_11', 'iso_8859_11_2001' : 'iso8859_11', # iso8859_13 codec 'iso_8859_13' : 'iso8859_13', 'l7' : 'iso8859_13', 'latin7' : 'iso8859_13', # iso8859_14 codec 'iso_8859_14' : 'iso8859_14', 'iso_8859_14_1998' : 'iso8859_14', 'iso_celtic' : 'iso8859_14', 'iso_ir_199' : 'iso8859_14', 'l8' : 'iso8859_14', 'latin8' : 'iso8859_14', # iso8859_15 codec 'iso_8859_15' : 'iso8859_15', 'l9' : 'iso8859_15', 'latin9' : 'iso8859_15', # iso8859_16 codec 'iso_8859_16' : 'iso8859_16', 'iso_8859_16_2001' : 'iso8859_16', 'iso_ir_226' : 'iso8859_16', 'l10' : 'iso8859_16', 'latin10' : 'iso8859_16', # iso8859_2 codec 'csisolatin2' : 'iso8859_2', 'iso_8859_2' : 'iso8859_2', 'iso_8859_2_1987' : 'iso8859_2', 'iso_ir_101' : 'iso8859_2', 'l2' : 'iso8859_2', 'latin2' : 'iso8859_2', # iso8859_3 codec 'csisolatin3' : 'iso8859_3', 'iso_8859_3' : 'iso8859_3', 'iso_8859_3_1988' : 'iso8859_3', 'iso_ir_109' : 'iso8859_3', 'l3' : 'iso8859_3', 'latin3' : 'iso8859_3', # iso8859_4 codec 'csisolatin4' : 'iso8859_4', 'iso_8859_4' : 'iso8859_4', 'iso_8859_4_1988' : 'iso8859_4', 'iso_ir_110' : 'iso8859_4', 'l4' : 'iso8859_4', 'latin4' : 'iso8859_4', # iso8859_5 codec 'csisolatincyrillic' : 'iso8859_5', 'cyrillic' : 'iso8859_5', 'iso_8859_5' : 'iso8859_5', 'iso_8859_5_1988' : 'iso8859_5', 'iso_ir_144' : 'iso8859_5', # iso8859_6 codec 'arabic' : 'iso8859_6', 'asmo_708' : 'iso8859_6', 'csisolatinarabic' : 'iso8859_6', 'ecma_114' : 'iso8859_6', 'iso_8859_6' : 'iso8859_6', 'iso_8859_6_1987' : 'iso8859_6', 'iso_ir_127' : 'iso8859_6', # iso8859_7 codec 'csisolatingreek' : 'iso8859_7', 'ecma_118' : 'iso8859_7', 'elot_928' : 'iso8859_7', 'greek' : 'iso8859_7', 'greek8' : 'iso8859_7', 'iso_8859_7' : 'iso8859_7', 'iso_8859_7_1987' : 'iso8859_7', 'iso_ir_126' : 'iso8859_7', # iso8859_8 codec 'csisolatinhebrew' : 'iso8859_8', 'hebrew' : 'iso8859_8', 'iso_8859_8' : 'iso8859_8', 'iso_8859_8_1988' : 'iso8859_8', 'iso_ir_138' : 'iso8859_8', # iso8859_9 codec 'csisolatin5' : 'iso8859_9', 'iso_8859_9' : 'iso8859_9', 'iso_8859_9_1989' : 'iso8859_9', 'iso_ir_148' : 'iso8859_9', 'l5' : 'iso8859_9', 'latin5' : 'iso8859_9', # johab codec 'cp1361' : 'johab', 'ms1361' : 'johab', # koi8_r codec 'cskoi8r' : 'koi8_r', # latin_1 codec # # Note that the latin_1 codec is implemented internally in C and a # lot faster than the charmap codec iso8859_1 which uses the same # encoding. This is why we discourage the use of the iso8859_1 # codec and alias it to latin_1 instead. # '8859' : 'latin_1', 'cp819' : 'latin_1', 'csisolatin1' : 'latin_1', 'ibm819' : 'latin_1', 'iso8859' : 'latin_1', 'iso8859_1' : 'latin_1', 'iso_8859_1' : 'latin_1', 'iso_8859_1_1987' : 'latin_1', 'iso_ir_100' : 'latin_1', 'l1' : 'latin_1', 'latin' : 'latin_1', 'latin1' : 'latin_1', # mac_cyrillic codec 'maccyrillic' : 'mac_cyrillic', # mac_greek codec 'macgreek' : 'mac_greek', # mac_iceland codec 'maciceland' : 'mac_iceland', # mac_latin2 codec 'maccentraleurope' : 'mac_latin2', 'maclatin2' : 'mac_latin2', # mac_roman codec 'macroman' : 'mac_roman', # mac_turkish codec 'macturkish' : 'mac_turkish', # mbcs codec 'dbcs' : 'mbcs', # ptcp154 codec 'csptcp154' : 'ptcp154', 'pt154' : 'ptcp154', 'cp154' : 'ptcp154', 'cyrillic_asian' : 'ptcp154', # quopri_codec codec 'quopri' : 'quopri_codec', 'quoted_printable' : 'quopri_codec', 'quotedprintable' : 'quopri_codec', # rot_13 codec 'rot13' : 'rot_13', # shift_jis codec 'csshiftjis' : 'shift_jis', 'shiftjis' : 'shift_jis', 'sjis' : 'shift_jis', 's_jis' : 'shift_jis', # shift_jis_2004 codec 'shiftjis2004' : 'shift_jis_2004', 'sjis_2004' : 'shift_jis_2004', 's_jis_2004' : 'shift_jis_2004', # shift_jisx0213 codec 'shiftjisx0213' : 'shift_jisx0213', 'sjisx0213' : 'shift_jisx0213', 's_jisx0213' : 'shift_jisx0213', # tactis codec 'tis260' : 'tactis', # tis_620 codec 'tis620' : 'tis_620', 'tis_620_0' : 'tis_620', 'tis_620_2529_0' : 'tis_620', 'tis_620_2529_1' : 'tis_620', 'iso_ir_166' : 'tis_620', # utf_16 codec 'u16' : 'utf_16', 'utf16' : 'utf_16', # utf_16_be codec 'unicodebigunmarked' : 'utf_16_be', 'utf_16be' : 'utf_16_be', # utf_16_le codec 'unicodelittleunmarked' : 'utf_16_le', 'utf_16le' : 'utf_16_le', # utf_32 codec 'u32' : 'utf_32', 'utf32' : 'utf_32', # utf_32_be codec 'utf_32be' : 'utf_32_be', # utf_32_le codec 'utf_32le' : 'utf_32_le', # utf_7 codec 'u7' : 'utf_7', 'utf7' : 'utf_7', 'unicode_1_1_utf_7' : 'utf_7', # utf_8 codec 'u8' : 'utf_8', 'utf' : 'utf_8', 'utf8' : 'utf_8', 'utf8_ucs2' : 'utf_8', 'utf8_ucs4' : 'utf_8', # uu_codec codec 'uu' : 'uu_codec', # zlib_codec codec 'zip' : 'zlib_codec', 'zlib' : 'zlib_codec', }
2026-03-31T15:30:28
codeparrot_clean
bc0940ea7268a5d156ee64bd9b95de28
code
# Authors: Alexandre Gramfort <alexandre.gramfort@telecom-paristech.fr> # Denis Engemann <denis.engemann@gmail.com> # Eric Larson <larson.eric.d@gmail.com> # # License: BSD (3-clause) import numpy as np from .peak_finder import peak_finder from .. import pick_types, pick_channels from ..utils import logger, verbose from ..filter import band_pass_filter from ..epochs import Epochs @verbose def find_eog_events(raw, event_id=998, l_freq=1, h_freq=10, filter_length='10s', ch_name=None, tstart=0, verbose=None): """Locate EOG artifacts Parameters ---------- raw : instance of Raw The raw data. event_id : int The index to assign to found events. l_freq : float Low cut-off frequency in Hz. h_freq : float High cut-off frequency in Hz. filter_length : str | int | None Number of taps to use for filtering. ch_name: str | None If not None, use specified channel(s) for EOG tstart : float Start detection after tstart seconds. verbose : bool, str, int, or None If not None, override default verbose level (see mne.verbose). Returns ------- eog_events : array Events. """ # Getting EOG Channel eog_inds = _get_eog_channel_index(ch_name, raw) logger.info('EOG channel index for this subject is: %s' % eog_inds) eog, _ = raw[eog_inds, :] eog_events = _find_eog_events(eog, event_id=event_id, l_freq=l_freq, h_freq=h_freq, sampling_rate=raw.info['sfreq'], first_samp=raw.first_samp, filter_length=filter_length, tstart=tstart) return eog_events def _find_eog_events(eog, event_id, l_freq, h_freq, sampling_rate, first_samp, filter_length='10s', tstart=0.): """Helper function""" logger.info('Filtering the data to remove DC offset to help ' 'distinguish blinks from saccades') # filtering to remove dc offset so that we know which is blink and saccades fmax = np.minimum(45, sampling_rate / 2.0 - 0.75) # protect Nyquist filteog = np.array([band_pass_filter(x, sampling_rate, 2, fmax, filter_length=filter_length) for x in eog]) temp = np.sqrt(np.sum(filteog ** 2, axis=1)) indexmax = np.argmax(temp) # easier to detect peaks with filtering. filteog = band_pass_filter(eog[indexmax], sampling_rate, l_freq, h_freq, filter_length=filter_length) # detecting eog blinks and generating event file logger.info('Now detecting blinks and generating corresponding events') temp = filteog - np.mean(filteog) n_samples_start = int(sampling_rate * tstart) if np.abs(np.max(temp)) > np.abs(np.min(temp)): eog_events, _ = peak_finder(filteog[n_samples_start:], extrema=1) else: eog_events, _ = peak_finder(filteog[n_samples_start:], extrema=-1) eog_events += n_samples_start n_events = len(eog_events) logger.info("Number of EOG events detected : %d" % n_events) eog_events = np.array([eog_events + first_samp, np.zeros(n_events, int), event_id * np.ones(n_events, int)]).T return eog_events def _get_eog_channel_index(ch_name, inst): if isinstance(ch_name, str): # Check if multiple EOG Channels if ',' in ch_name: ch_name = ch_name.split(',') else: ch_name = [ch_name] eog_inds = pick_channels(inst.ch_names, include=ch_name) if len(eog_inds) == 0: raise ValueError('%s not in channel list' % ch_name) else: logger.info('Using channel %s as EOG channel%s' % ( " and ".join(ch_name), '' if len(eog_inds) < 2 else 's')) elif ch_name is None: eog_inds = pick_types(inst.info, meg=False, eeg=False, stim=False, eog=True, ecg=False, emg=False, ref_meg=False, exclude='bads') if len(eog_inds) == 0: logger.info('No EOG channels found') logger.info('Trying with EEG 061 and EEG 062') eog_inds = pick_channels(inst.ch_names, include=['EEG 061', 'EEG 062']) if len(eog_inds) != 2: raise RuntimeError('EEG 61 or EEG 62 channel not found !!') else: raise ValueError('Could not find EOG channel.') return eog_inds @verbose def create_eog_epochs(raw, ch_name=None, event_id=998, picks=None, tmin=-0.5, tmax=0.5, l_freq=1, h_freq=10, reject=None, flat=None, baseline=None, preload=True, verbose=None): """Conveniently generate epochs around EOG artifact events Parameters ---------- raw : instance of Raw The raw data ch_name : str The name of the channel to use for EOG peak detection. The argument is mandatory if the dataset contains no EOG channels. event_id : int The index to assign to found events picks : array-like of int | None (default) Indices of channels to include (if None, all channels are used). tmin : float Start time before event. tmax : float End time after event. l_freq : float Low pass frequency. h_freq : float High pass frequency. reject : dict | None Rejection parameters based on peak-to-peak amplitude. Valid keys are 'grad' | 'mag' | 'eeg' | 'eog' | 'ecg'. If reject is None then no rejection is done. Example:: reject = dict(grad=4000e-13, # T / m (gradiometers) mag=4e-12, # T (magnetometers) eeg=40e-6, # uV (EEG channels) eog=250e-6 # uV (EOG channels) ) flat : dict | None Rejection parameters based on flatness of signal. Valid keys are 'grad' | 'mag' | 'eeg' | 'eog' | 'ecg', and values are floats that set the minimum acceptable peak-to-peak amplitude. If flat is None then no rejection is done. baseline : tuple or list of length 2, or None The time interval to apply rescaling / baseline correction. If None do not apply it. If baseline is (a, b) the interval is between "a (s)" and "b (s)". If a is None the beginning of the data is used and if b is None then b is set to the end of the interval. If baseline is equal ot (None, None) all the time interval is used. If None, no correction is applied. preload : bool Preload epochs or not. verbose : bool, str, int, or None If not None, override default verbose level (see mne.verbose). Returns ------- eog_epochs : instance of Epochs Data epoched around EOG events. """ events = find_eog_events(raw, ch_name=ch_name, event_id=event_id, l_freq=l_freq, h_freq=h_freq) # create epochs around EOG events eog_epochs = Epochs(raw, events=events, event_id=event_id, tmin=tmin, tmax=tmax, proj=False, reject=reject, flat=flat, picks=picks, baseline=baseline, preload=preload) return eog_epochs
2026-03-31T15:30:28
codeparrot_clean
33732242af947c34bba32949a0663411
code
""" South Africa-specific Form helpers """ from django.core.validators import EMPTY_VALUES from django.forms import ValidationError from django.forms.fields import CharField, RegexField from django.utils.checksums import luhn from django.utils.translation import gettext as _ import re from datetime import date id_re = re.compile(r'^(?P<yy>\d\d)(?P<mm>\d\d)(?P<dd>\d\d)(?P<mid>\d{4})(?P<end>\d{3})') class ZAIDField(CharField): """A form field for South African ID numbers -- the checksum is validated using the Luhn checksum, and uses a simlistic (read: not entirely accurate) check for the birthdate """ default_error_messages = { 'invalid': _(u'Enter a valid South African ID number'), } def clean(self, value): super(ZAIDField, self).clean(value) if value in EMPTY_VALUES: return u'' # strip spaces and dashes value = value.strip().replace(' ', '').replace('-', '') match = re.match(id_re, value) if not match: raise ValidationError(self.error_messages['invalid']) g = match.groupdict() try: # The year 2000 is conveniently a leapyear. # This algorithm will break in xx00 years which aren't leap years # There is no way to guess the century of a ZA ID number d = date(int(g['yy']) + 2000, int(g['mm']), int(g['dd'])) except ValueError: raise ValidationError(self.error_messages['invalid']) if not luhn(value): raise ValidationError(self.error_messages['invalid']) return value class ZAPostCodeField(RegexField): default_error_messages = { 'invalid': _(u'Enter a valid South African postal code'), } def __init__(self, max_length=None, min_length=None, *args, **kwargs): super(ZAPostCodeField, self).__init__(r'^\d{4}$', max_length, min_length, *args, **kwargs)
2026-03-31T15:30:28
codeparrot_clean
8bdc2a8bd0a233f6a5f549dc8da7b52f
code
"""Word completion for GNU readline. The completer completes keywords, built-ins and globals in a selectable namespace (which defaults to __main__); when completing NAME.NAME..., it evaluates (!) the expression up to the last dot and completes its attributes. It's very cool to do "import sys" type "sys.", hit the completion key (twice), and see the list of names defined by the sys module! Tip: to use the tab key as the completion key, call readline.parse_and_bind("tab: complete") Notes: - Exceptions raised by the completer function are *ignored* (and generally cause the completion to fail). This is a feature -- since readline sets the tty device in raw (or cbreak) mode, printing a traceback wouldn't work well without some complicated hoopla to save, reset and restore the tty state. - The evaluation of the NAME.NAME... form may cause arbitrary application defined code to be executed if an object with a __getattr__ hook is found. Since it is the responsibility of the application (or the user) to enable this feature, I consider this an acceptable risk. More complicated expressions (e.g. function calls or indexing operations) are *not* evaluated. - When the original stdin is not a tty device, GNU readline is never used, and this module (and the readline module) are silently inactive. """ import atexit import builtins import __main__ __all__ = ["Completer"] class Completer: def __init__(self, namespace = None): """Create a new completer for the command line. Completer([namespace]) -> completer instance. If unspecified, the default namespace where completions are performed is __main__ (technically, __main__.__dict__). Namespaces should be given as dictionaries. Completer instances should be used as the completion mechanism of readline via the set_completer() call: readline.set_completer(Completer(my_namespace).complete) """ if namespace and not isinstance(namespace, dict): raise TypeError('namespace must be a dictionary') # Don't bind to namespace quite yet, but flag whether the user wants a # specific namespace or to use __main__.__dict__. This will allow us # to bind to __main__.__dict__ at completion time, not now. if namespace is None: self.use_main_ns = 1 else: self.use_main_ns = 0 self.namespace = namespace def complete(self, text, state): """Return the next possible completion for 'text'. This is called successively with state == 0, 1, 2, ... until it returns None. The completion should begin with 'text'. """ if self.use_main_ns: self.namespace = __main__.__dict__ if state == 0: if "." in text: self.matches = self.attr_matches(text) else: self.matches = self.global_matches(text) try: return self.matches[state] except IndexError: return None def _callable_postfix(self, val, word): if callable(val): word = word + "(" return word def global_matches(self, text): """Compute matches when text is a simple name. Return a list of all keywords, built-in functions and names currently defined in self.namespace that match. """ import keyword matches = [] n = len(text) for word in keyword.kwlist: if word[:n] == text: matches.append(word) for nspace in [builtins.__dict__, self.namespace]: for word, val in nspace.items(): if word[:n] == text and word != "__builtins__": matches.append(self._callable_postfix(val, word)) return matches def attr_matches(self, text): """Compute matches when text contains a dot. Assuming the text is of the form NAME.NAME....[NAME], and is evaluable in self.namespace, it will be evaluated and its attributes (as revealed by dir()) are used as possible completions. (For class instances, class members are also considered.) WARNING: this can still invoke arbitrary C code, if an object with a __getattr__ hook is evaluated. """ import re m = re.match(r"(\w+(\.\w+)*)\.(\w*)", text) if not m: return [] expr, attr = m.group(1, 3) try: thisobject = eval(expr, self.namespace) except Exception: return [] # get the content of the object, except __builtins__ words = dir(thisobject) if "__builtins__" in words: words.remove("__builtins__") if hasattr(thisobject, '__class__'): words.append('__class__') words.extend(get_class_members(thisobject.__class__)) matches = [] n = len(attr) for word in words: if word[:n] == attr and hasattr(thisobject, word): val = getattr(thisobject, word) word = self._callable_postfix(val, "%s.%s" % (expr, word)) matches.append(word) return matches def get_class_members(klass): ret = dir(klass) if hasattr(klass,'__bases__'): for base in klass.__bases__: ret = ret + get_class_members(base) return ret try: import readline except ImportError: pass else: readline.set_completer(Completer().complete) # Release references early at shutdown (the readline module's # contents are quasi-immortal, and the completer function holds a # reference to globals). atexit.register(lambda: readline.set_completer(None))
2026-03-31T15:30:28
codeparrot_clean
7708d438bd8c9645b0e3c5a0fb13ea95
code
# # This source file is part of the EdgeDB open source project. # # Copyright 2020-present MagicStack Inc. and the EdgeDB authors. # # 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. # """EdgeQL multiplicity inference. A top-down multiplicity inferer that traverses the full AST populating multiplicity fields and performing multiplicity checks. """ from __future__ import annotations from typing import * import functools from edb import errors from edb.edgeql import qltypes from edb.schema import pointers as s_pointers from edb.ir import ast as irast from edb.ir import typeutils as irtyputils from . import cardinality from . import context as inference_context ZERO = qltypes.Multiplicity.ZERO ONE = qltypes.Multiplicity.ONE MANY = qltypes.Multiplicity.MANY def _max_multiplicity( args: Iterable[qltypes.Multiplicity] ) -> qltypes.Multiplicity: # Coincidentally, the lexical order of multiplicity is opposite of # order of multiplicity values. arg_list = list(args) if not arg_list: return ZERO else: return min(arg_list) def _common_multiplicity( args: Iterable[irast.Base], *, scope_tree: irast.ScopeTreeNode, ctx: inference_context.InfCtx, ) -> qltypes.Multiplicity: return _max_multiplicity( infer_multiplicity(a, scope_tree=scope_tree, ctx=ctx) for a in args) @functools.singledispatch def _infer_multiplicity( ir: irast.Expr, *, scope_tree: irast.ScopeTreeNode, ctx: inference_context.InfCtx, ) -> qltypes.Multiplicity: # return MANY raise ValueError(f'infer_multiplicity: cannot handle {ir!r}') @_infer_multiplicity.register def __infer_none( ir: None, *, scope_tree: irast.ScopeTreeNode, ctx: inference_context.InfCtx, ) -> qltypes.Multiplicity: # Here for debugging purposes. raise ValueError('invalid infer_multiplicity(None, schema) call') @_infer_multiplicity.register def __infer_statement( ir: irast.Statement, *, scope_tree: irast.ScopeTreeNode, ctx: inference_context.InfCtx, ) -> qltypes.Multiplicity: return infer_multiplicity( ir.expr, scope_tree=scope_tree, ctx=ctx) @_infer_multiplicity.register def __infer_empty_set( ir: irast.EmptySet, *, scope_tree: irast.ScopeTreeNode, ctx: inference_context.InfCtx, ) -> qltypes.Multiplicity: return ZERO @_infer_multiplicity.register def __infer_type_introspection( ir: irast.TypeIntrospection, *, scope_tree: irast.ScopeTreeNode, ctx: inference_context.InfCtx, ) -> qltypes.Multiplicity: # TODO: The result is always ONE, but we still want to actually # introspect the expression. Unfortunately, currently the # expression is not available at this stage. # # E.g. consider: # WITH X := Foo {bar := {Bar, Bar}} # SELECT INTROSPECT TYPEOF X.bar; return ONE def _infer_shape( ir: irast.Set, *, is_mutation: bool=False, scope_tree: irast.ScopeTreeNode, ctx: inference_context.InfCtx, ) -> None: for shape_set, _ in ir.shape: new_scope = cardinality._get_set_scope(shape_set, scope_tree, ctx=ctx) if shape_set.expr and shape_set.rptr: expr_mult = infer_multiplicity( shape_set.expr, scope_tree=new_scope, ctx=ctx) ptrref = shape_set.rptr.ptrref if expr_mult is MANY and irtyputils.is_object(ptrref.out_target): raise errors.QueryError( f'possibly not a strict set returned by an ' f'expression for a computable ' f'{ptrref.shortname.name}.', hint=( f'Use DISTINCT for the entire computable expression ' f'to resolve this.' ), context=shape_set.context ) _infer_shape( shape_set, is_mutation=is_mutation, scope_tree=scope_tree, ctx=ctx) def _infer_set( ir: irast.Set, *, is_mutation: bool=False, scope_tree: irast.ScopeTreeNode, ctx: inference_context.InfCtx, ) -> qltypes.Multiplicity: result = _infer_set_inner( ir, is_mutation=is_mutation, scope_tree=scope_tree, ctx=ctx) ctx.inferred_multiplicity[ir, scope_tree] = result # The shape doesn't affect multiplicity, but requires validation. _infer_shape(ir, is_mutation=is_mutation, scope_tree=scope_tree, ctx=ctx) return result def _infer_set_inner( ir: irast.Set, *, is_mutation: bool=False, scope_tree: irast.ScopeTreeNode, ctx: inference_context.InfCtx, ) -> qltypes.Multiplicity: rptr = ir.rptr new_scope = cardinality._get_set_scope(ir, scope_tree, ctx=ctx) if rptr is not None: # Validate the source infer_multiplicity(rptr.source, scope_tree=new_scope, ctx=ctx) if ir.expr: expr_mult = infer_multiplicity(ir.expr, scope_tree=new_scope, ctx=ctx) if rptr is not None: rptrref = rptr.ptrref if isinstance(rptr.ptrref, irast.TupleIndirectionPointerRef): # All bets are off for tuple elements. return MANY elif not irtyputils.is_object(ir.typeref): # This is not an expression and is some kind of scalar, so # multiplicity cannot be guaranteed to be ONE (most scalar # expressions don't have an implicit requirement to be sets) # unless we also have an exclusive constraint. if rptr is not None: schema = ctx.env.schema # We should only have some kind of path terminating in a # property here. assert isinstance(rptrref, irast.PointerRef) ptr = schema.get_by_id(rptrref.id, type=s_pointers.Pointer) if ptr.is_exclusive(schema): # Got an exclusive constraint return ONE return MANY else: # This is some kind of a link at the end of a path. # Therefore the target is a proper set. return ONE elif ir.expr is not None: return expr_mult else: # Evidently this is not a pointer, expression, or a scalar. # This is an object type and therefore a proper set. return ONE @_infer_multiplicity.register def __infer_func_call( ir: irast.FunctionCall, *, scope_tree: irast.ScopeTreeNode, ctx: inference_context.InfCtx, ) -> qltypes.Multiplicity: # If the function returns a set (for any reason), all bets are off # and the maximum multiplicity cannot be inferred. card = cardinality.infer_cardinality( ir, scope_tree=scope_tree, ctx=ctx) # We still want to validate the multiplicity of the arguments, though. for arg in ir.args: infer_multiplicity(arg.expr, scope_tree=scope_tree, ctx=ctx) if card is not None and card.is_single(): return ONE elif str(ir.func_shortname) == 'std::enumerate': # Technically the output of enumerate is always of # multiplicity ONE because it's a set of tuples with first # elements being guaranteed to be distinct. return ONE else: return MANY @_infer_multiplicity.register def __infer_oper_call( ir: irast.OperatorCall, *, scope_tree: irast.ScopeTreeNode, ctx: inference_context.InfCtx, ) -> qltypes.Multiplicity: mult = [] cards = [] for arg in ir.args: cards.append( cardinality.infer_cardinality( arg.expr, scope_tree=scope_tree, ctx=ctx)) mult.append( infer_multiplicity( arg.expr, scope_tree=scope_tree, ctx=ctx)) op_name = str(ir.func_shortname) if op_name == 'std::UNION': # UNION will produce multiplicity MANY unless most or all of # the elements multiplicity is ZERO (from an empty set). result = ZERO for m in mult: if m is ONE and result is ZERO: result = m elif m is ONE and result is not ZERO: return MANY elif m is MANY: return MANY return result elif op_name == 'std::DISTINCT': if mult[0] is ZERO: return ZERO else: return ONE elif op_name == 'std::IF': # If the cardinality of the condition is more than ONE, then # the multiplicity cannot be inferred. if cards[1].is_single(): # Now it's just a matter of the multiplicity of the # possible results. return _max_multiplicity((mult[0], mult[2])) else: return MANY else: # The rest of the operators (other than UNION, DISTINCT, or # IF..ELSE). We can ignore the SET OF args because the results # are actually proportional to the element-wise args in our # operators. result = _max_multiplicity(mult) if result is MANY: return result # Even when arguments are of multiplicity ONE, we cannot # exclude the possibility of the result being of multiplicity # MANY. We need to check that at most one argument has # cardinality more than ONE. if len([card for card in cards if card.is_multi()]) > 1: return MANY else: return result @_infer_multiplicity.register def __infer_const( ir: irast.BaseConstant, *, scope_tree: irast.ScopeTreeNode, ctx: inference_context.InfCtx, ) -> qltypes.Multiplicity: return ONE @_infer_multiplicity.register def __infer_param( ir: irast.Parameter, *, scope_tree: irast.ScopeTreeNode, ctx: inference_context.InfCtx, ) -> qltypes.Multiplicity: return ONE @_infer_multiplicity.register def __infer_const_set( ir: irast.ConstantSet, *, scope_tree: irast.ScopeTreeNode, ctx: inference_context.InfCtx, ) -> qltypes.Multiplicity: if len(ir.elements) == len({el.value for el in ir.elements}): return ONE else: return MANY @_infer_multiplicity.register def __infer_typecheckop( ir: irast.TypeCheckOp, *, scope_tree: irast.ScopeTreeNode, ctx: inference_context.InfCtx, ) -> qltypes.Multiplicity: # Unless this is a singleton, the multiplicity cannot be assumed to be ONE. card = cardinality.infer_cardinality( ir, scope_tree=scope_tree, ctx=ctx) if card is not None and card.is_single(): return ONE else: return MANY @_infer_multiplicity.register def __infer_typecast( ir: irast.TypeCast, *, scope_tree: irast.ScopeTreeNode, ctx: inference_context.InfCtx, ) -> qltypes.Multiplicity: return infer_multiplicity( ir.expr, scope_tree=scope_tree, ctx=ctx, ) def _infer_stmt_multiplicity( ir: irast.FilteredStmt, *, scope_tree: irast.ScopeTreeNode, ctx: inference_context.InfCtx, ) -> qltypes.Multiplicity: result = infer_multiplicity( ir.subject if isinstance(ir, irast.MutatingStmt) else ir.result, scope_tree=scope_tree, ctx=ctx, ) # WITH block bindings need to be validated, they don't have to # have multiplicity ONE, but their sub-expressions must be valid. # # Inferring how the FILTER clause affects multiplicity is in # general impossible, but we still want to ensure that the FILTER # expression has valid multiplicity. for part in ir.bindings + [ir.where]: if part: infer_multiplicity(part, scope_tree=scope_tree, ctx=ctx) return result def _infer_for_multiplicity( ir: irast.SelectStmt, *, scope_tree: irast.ScopeTreeNode, ctx: inference_context.InfCtx, ) -> qltypes.Multiplicity: assert ir.iterator_stmt is not None itexpr = ir.iterator_stmt.expr if isinstance(ir.result.expr, irast.SelectStmt): union = ir.result.expr if (isinstance(union.where, irast.Set) and isinstance(union.where.expr, irast.OperatorCall) and str(union.where.expr.func_shortname) == 'std::='): op = union.where.expr left, right = (a.expr for a in op.args) # The iterator set may be wrapped in an `enumerate`, this # requires different handling. has_enumerate = ( isinstance(itexpr, irast.SelectStmt) and isinstance(itfn := itexpr.result.expr, irast.FunctionCall) and str(itfn.func_shortname) == 'std::enumerate' ) # First make sure that the cardinality of the FILTER # expression is is no more than 1. Then make sure both # operands are paths. if union.where_card.is_single(): it = None if left.rptr is not None: it = right elif right.rptr is not None: it = left if it is not None: if has_enumerate: assert isinstance(itfn, irast.FunctionCall) enumerate_mult = infer_multiplicity( itfn.args[0].expr, scope_tree=scope_tree, ctx=ctx, ) if ( enumerate_mult is ONE and it.rptr is not None and isinstance( it.rptr, irast.TupleIndirectionPointer ) # Tuple comes from the iterator set and it.rptr.source.expr is itexpr # the indirection is accessing element 1 and str(it.rptr.ptrref.name) == '__tuple__::1' ): return ONE elif (it.is_binding and it.expr is itexpr): return ONE elif isinstance(ir.result.expr, irast.InsertStmt): # A union of inserts always has multiplicity ONE return ONE return MANY @_infer_multiplicity.register def __infer_select_stmt( ir: irast.SelectStmt, *, scope_tree: irast.ScopeTreeNode, ctx: inference_context.InfCtx, ) -> qltypes.Multiplicity: result = _infer_stmt_multiplicity(ir, scope_tree=scope_tree, ctx=ctx) itmult = None if ir.iterator_stmt: # If this is a FOR, then there's a common pattern which can be # detected and the multiplicity of it is ONE. Otherwise it # cannot be reliably inferred. # # The pattern is: FOR x IN {<set of multiplicity ONE>} UNION # (SELECT ... FILTER .prop = x) As long as the FILTER has just # a single .prop = x expression, this is going to be a bunch # of disjoint unions and the final multiplicity will be ONE. itmult = infer_multiplicity( ir.iterator_stmt, scope_tree=scope_tree, ctx=ctx, ) # OFFSET, LIMIT and ORDER BY have already been validated to be # singletons, but their sub-expressions (if any) still need to be # validated. for part in [ir.limit, ir.offset] + [sort.expr for sort in ir.orderby]: if part: new_scope = cardinality._get_set_scope(part, scope_tree, ctx=ctx) infer_multiplicity(part, scope_tree=new_scope, ctx=ctx) if itmult is not None: if itmult is ONE: return _infer_for_multiplicity( ir, scope_tree=scope_tree, ctx=ctx) return MANY else: return result @_infer_multiplicity.register def __infer_insert_stmt( ir: irast.InsertStmt, *, scope_tree: irast.ScopeTreeNode, ctx: inference_context.InfCtx, ) -> qltypes.Multiplicity: # INSERT will always return a proper set, but we still want to # process the sub-expressions. infer_multiplicity( ir.subject, is_mutation=True, scope_tree=scope_tree, ctx=ctx ) new_scope = cardinality._get_set_scope(ir.result, scope_tree, ctx=ctx) infer_multiplicity( ir.result, is_mutation=True, scope_tree=new_scope, ctx=ctx ) if ir.on_conflict: for part in [ir.on_conflict.select_ir, ir.on_conflict.else_ir]: if part: infer_multiplicity(part, scope_tree=scope_tree, ctx=ctx) return ONE @_infer_multiplicity.register def __infer_update_stmt( ir: irast.UpdateStmt, *, scope_tree: irast.ScopeTreeNode, ctx: inference_context.InfCtx, ) -> qltypes.Multiplicity: # Presumably UPDATE will always return a proper set, even if it's # fed something with higher multiplicity, but we still want to # process the expression being updated. infer_multiplicity( ir.result, is_mutation=True, scope_tree=scope_tree, ctx=ctx, ) result = _infer_stmt_multiplicity(ir, scope_tree=scope_tree, ctx=ctx) if result is ZERO: return ZERO else: return ONE @_infer_multiplicity.register def __infer_delete_stmt( ir: irast.DeleteStmt, *, scope_tree: irast.ScopeTreeNode, ctx: inference_context.InfCtx, ) -> qltypes.Multiplicity: # Presumably DELETE will always return a proper set, even if it's # fed something with higher multiplicity, but we still want to # process the expression being deleted. infer_multiplicity( ir.result, is_mutation=True, scope_tree=scope_tree, ctx=ctx, ) result = _infer_stmt_multiplicity(ir, scope_tree=scope_tree, ctx=ctx) if result is ZERO: return ZERO else: return ONE @_infer_multiplicity.register def __infer_group_stmt( ir: irast.GroupStmt, *, scope_tree: irast.ScopeTreeNode, ctx: inference_context.InfCtx, ) -> qltypes.Multiplicity: raise NotImplementedError @_infer_multiplicity.register def __infer_slice( ir: irast.SliceIndirection, *, scope_tree: irast.ScopeTreeNode, ctx: inference_context.InfCtx, ) -> qltypes.Multiplicity: # Slice indirection multiplicity is guaranteed to be ONE as long # as the cardinality of this expression is at most one, otherwise # the results of index indirection can contain values with # multiplicity > 1. card = cardinality.infer_cardinality( ir, scope_tree=scope_tree, ctx=ctx) if card is not None and card.is_single(): return ONE else: return MANY @_infer_multiplicity.register def __infer_index( ir: irast.IndexIndirection, *, scope_tree: irast.ScopeTreeNode, ctx: inference_context.InfCtx, ) -> qltypes.Multiplicity: # Index indirection multiplicity is guaranteed to be ONE as long # as the cardinality of this expression is at most one, otherwise # the results of index indirection can contain values with # multiplicity > 1. card = cardinality.infer_cardinality( ir, scope_tree=scope_tree, ctx=ctx) if card is not None and card.is_single(): return ONE else: return MANY @_infer_multiplicity.register def __infer_array( ir: irast.Array, *, scope_tree: irast.ScopeTreeNode, ctx: inference_context.InfCtx, ) -> qltypes.Multiplicity: return _common_multiplicity(ir.elements, scope_tree=scope_tree, ctx=ctx) @_infer_multiplicity.register def __infer_tuple( ir: irast.Tuple, *, scope_tree: irast.ScopeTreeNode, ctx: inference_context.InfCtx, ) -> qltypes.Multiplicity: return _common_multiplicity( [el.val for el in ir.elements], scope_tree=scope_tree, ctx=ctx ) def infer_multiplicity( ir: irast.Base, *, is_mutation: bool=False, scope_tree: irast.ScopeTreeNode, ctx: inference_context.InfCtx, ) -> qltypes.Multiplicity: result = ctx.inferred_multiplicity.get((ir, scope_tree)) if result is not None: return result # We can use cardinality as a helper in determining multiplicity, # since singletons have multiplicity one. card = cardinality.infer_cardinality( ir, is_mutation=is_mutation, scope_tree=scope_tree, ctx=ctx) if isinstance(ir, irast.Set): result = _infer_set( ir, is_mutation=is_mutation, scope_tree=scope_tree, ctx=ctx, ) else: result = _infer_multiplicity(ir, scope_tree=scope_tree, ctx=ctx) if card is not None and card.is_single(): # We've validated multiplicity, so now we can just override it # safely. result = ONE if result not in {ZERO, ONE, MANY}: raise errors.QueryError( 'could not determine the multiplicity of ' 'set produced by expression', context=ir.context) ctx.inferred_multiplicity[ir, scope_tree] = result return result
2026-03-31T15:30:28
codeparrot_clean
bf45fe2213dac45291186a5dc2b5ba48
code
# 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. # ============================================================================== """Export a TensorFlow model. See: go/tf-exporter """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import os import re import six from google.protobuf.any_pb2 import Any from tensorflow.contrib.session_bundle import constants from tensorflow.contrib.session_bundle import gc from tensorflow.contrib.session_bundle import manifest_pb2 from tensorflow.core.framework import graph_pb2 from tensorflow.python.framework import dtypes from tensorflow.python.framework import ops from tensorflow.python.platform import gfile from tensorflow.python.platform import tf_logging as logging from tensorflow.python.training import saver as tf_saver from tensorflow.python.training import training_util from tensorflow.python.util import compat from tensorflow.python.util.deprecation import deprecated @deprecated("2017-06-30", "Please use SavedModel instead.") def gfile_copy_callback(files_to_copy, export_dir_path): """Callback to copy files using `gfile.Copy` to an export directory. This method is used as the default `assets_callback` in `Exporter.init` to copy assets from the `assets_collection`. It can also be invoked directly to copy additional supplementary files into the export directory (in which case it is not a callback). Args: files_to_copy: A dictionary that maps original file paths to desired basename in the export directory. export_dir_path: Directory to copy the files to. """ logging.info("Write assets into: %s using gfile_copy.", export_dir_path) gfile.MakeDirs(export_dir_path) for source_filepath, basename in files_to_copy.items(): new_path = os.path.join( compat.as_bytes(export_dir_path), compat.as_bytes(basename)) logging.info("Copying asset %s to path %s.", source_filepath, new_path) if gfile.Exists(new_path): # Guard against being restarted while copying assets, and the file # existing and being in an unknown state. # TODO(b/28676216): Do some file checks before deleting. logging.info("Removing file %s.", new_path) gfile.Remove(new_path) gfile.Copy(source_filepath, new_path) @deprecated("2017-06-30", "Please use SavedModel instead.") def regression_signature(input_tensor, output_tensor): """Creates a regression signature. Args: input_tensor: Tensor specifying the input to a graph. output_tensor: Tensor specifying the output of a graph. Returns: A Signature message. """ signature = manifest_pb2.Signature() signature.regression_signature.input.tensor_name = input_tensor.name signature.regression_signature.output.tensor_name = output_tensor.name return signature @deprecated("2017-06-30", "Please use SavedModel instead.") def classification_signature(input_tensor, classes_tensor=None, scores_tensor=None): """Creates a classification signature. Args: input_tensor: Tensor specifying the input to a graph. classes_tensor: Tensor specifying the output classes of a graph. scores_tensor: Tensor specifying the scores of the output classes. Returns: A Signature message. """ signature = manifest_pb2.Signature() signature.classification_signature.input.tensor_name = input_tensor.name if classes_tensor is not None: signature.classification_signature.classes.tensor_name = classes_tensor.name if scores_tensor is not None: signature.classification_signature.scores.tensor_name = scores_tensor.name return signature @deprecated("2017-06-30", "Please use SavedModel instead.") def generic_signature(name_tensor_map): """Creates a generic signature of name to Tensor name. Args: name_tensor_map: Map from logical name to Tensor. Returns: A Signature message. """ signature = manifest_pb2.Signature() for name, tensor in six.iteritems(name_tensor_map): signature.generic_signature.map[name].tensor_name = tensor.name return signature class Exporter(object): """Exporter helps package a TensorFlow model for serving. Args: saver: Saver object. """ def __init__(self, saver): # Makes a copy of the saver-def and disables garbage-collection, since the # exporter enforces garbage-collection independently. Specifically, since # the exporter performs atomic copies of the saver output, it is required # that garbage-collection via the underlying saver be disabled. saver_def = saver.as_saver_def() saver_def.ClearField("max_to_keep") self._saver = tf_saver.Saver(saver_def=saver_def) self._has_init = False self._assets_to_copy = {} @deprecated("2017-06-30", "Please use SavedModel instead.") def init(self, graph_def=None, init_op=None, clear_devices=False, default_graph_signature=None, named_graph_signatures=None, assets_collection=None, assets_callback=gfile_copy_callback): """Initialization. Args: graph_def: A GraphDef message of the graph to be used in inference. GraphDef of default graph is used when None. init_op: Op to be used in initialization. clear_devices: If device info of the graph should be cleared upon export. default_graph_signature: Default signature of the graph. named_graph_signatures: Map of named input/output signatures of the graph. assets_collection: A collection of constant asset filepath tensors. If set the assets will be exported into the asset directory. assets_callback: callback with two argument called during export with the list of files to copy and the asset path. Raises: RuntimeError: if init is called more than once. TypeError: if init_op is not an Operation or None. ValueError: if asset file path tensors are not non-empty constant string scalar tensors. """ # Avoid Dangerous default value [] if named_graph_signatures is None: named_graph_signatures = {} assets = [] if assets_collection: for asset_tensor in assets_collection: asset_filepath = self._file_path_value(asset_tensor) if not asset_filepath: raise ValueError("invalid asset filepath tensor %s" % asset_tensor) basename = os.path.basename(asset_filepath) assets.append((basename, asset_tensor)) self._assets_to_copy[asset_filepath] = basename if self._has_init: raise RuntimeError("init should be called only once") self._has_init = True if graph_def or clear_devices: copy = graph_pb2.GraphDef() if graph_def: copy.CopyFrom(graph_def) else: copy.CopyFrom(ops.get_default_graph().as_graph_def()) if clear_devices: for node in copy.node: node.device = "" graph_any_buf = Any() graph_any_buf.Pack(copy) ops.add_to_collection(constants.GRAPH_KEY, graph_any_buf) if init_op: if not isinstance(init_op, ops.Operation): raise TypeError("init_op needs to be an Operation: %s" % init_op) ops.add_to_collection(constants.INIT_OP_KEY, init_op) signatures_proto = manifest_pb2.Signatures() if default_graph_signature: signatures_proto.default_signature.CopyFrom(default_graph_signature) for signature_name, signature in six.iteritems(named_graph_signatures): signatures_proto.named_signatures[signature_name].CopyFrom(signature) signatures_any_buf = Any() signatures_any_buf.Pack(signatures_proto) ops.add_to_collection(constants.SIGNATURES_KEY, signatures_any_buf) for filename, tensor in assets: asset = manifest_pb2.AssetFile() asset.filename = filename asset.tensor_binding.tensor_name = tensor.name asset_any_buf = Any() asset_any_buf.Pack(asset) ops.add_to_collection(constants.ASSETS_KEY, asset_any_buf) self._assets_callback = assets_callback @deprecated("2017-06-30", "Please use SavedModel instead.") def export(self, export_dir_base, global_step_tensor, sess=None, exports_to_keep=None): """Exports the model. Args: export_dir_base: A string path to the base export dir. global_step_tensor: An Tensor or tensor name providing the global step counter to append to the export directory path and set in the manifest version. sess: A Session to use to save the parameters. exports_to_keep: a gc.Path filter function used to determine the set of exports to keep. If set to None, all versions will be kept. Returns: The string path to the exported directory. Raises: RuntimeError: if init is not called. RuntimeError: if the export would overwrite an existing directory. """ if not self._has_init: raise RuntimeError("init must be called first") # Export dir must not end with / or it will break exports to keep. Strip /. if export_dir_base.endswith("/"): export_dir_base = export_dir_base[:-1] global_step = training_util.global_step(sess, global_step_tensor) export_dir = os.path.join( compat.as_bytes(export_dir_base), compat.as_bytes(constants.VERSION_FORMAT_SPECIFIER % global_step)) # Prevent overwriting on existing exports which could lead to bad/corrupt # storage and loading of models. This is an important check that must be # done before any output files or directories are created. if gfile.Exists(export_dir): raise RuntimeError("Overwriting exports can cause corruption and are " "not allowed. Duplicate export dir: %s" % export_dir) # Output to a temporary directory which is atomically renamed to the final # directory when complete. tmp_export_dir = compat.as_text(export_dir) + "-tmp" gfile.MakeDirs(tmp_export_dir) self._saver.save(sess, os.path.join( compat.as_text(tmp_export_dir), compat.as_text(constants.EXPORT_BASE_NAME)), meta_graph_suffix=constants.EXPORT_SUFFIX_NAME) # Run the asset callback. if self._assets_callback and self._assets_to_copy: assets_dir = os.path.join( compat.as_bytes(tmp_export_dir), compat.as_bytes(constants.ASSETS_DIRECTORY)) gfile.MakeDirs(assets_dir) self._assets_callback(self._assets_to_copy, assets_dir) # TODO(b/27794910): Delete *checkpoint* file before rename. gfile.Rename(tmp_export_dir, export_dir) if exports_to_keep: # create a simple parser that pulls the export_version from the directory. def parser(path): match = re.match("^" + export_dir_base + "/(\\d{8})$", path.path) if not match: return None return path._replace(export_version=int(match.group(1))) paths_to_delete = gc.negation(exports_to_keep) for p in paths_to_delete(gc.get_paths(export_dir_base, parser=parser)): gfile.DeleteRecursively(p.path) return export_dir def _file_path_value(self, path_tensor): """Returns the filepath value stored in constant `path_tensor`.""" if not isinstance(path_tensor, ops.Tensor): raise TypeError("tensor is not a Tensor") if path_tensor.op.type != "Const": raise TypeError("Only constants tensor are supported") if path_tensor.dtype != dtypes.string: raise TypeError("File paths should be string") str_value = path_tensor.op.get_attr("value").string_val if len(str_value) != 1: raise TypeError("Only scalar tensors are supported") return str_value[0]
2026-03-31T15:30:28
codeparrot_clean
188dcb349ade2535e88af2e1b175077d
code
############################################################################## # # Copyright (c) 2008-2011 Alistek Ltd (http://www.alistek.com) All Rights Reserved. # General contacts <info@alistek.com> # # WARNING: This program as such is intended to be used by professional # programmers who take the whole responsability of assessing all potential # consequences resulting from its eventual inadequacies and bugs # End users who are looking for a ready-to-use solution with commercial # garantees and support are strongly adviced to contract a Free Software # Service Company # # 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 module is GPLv3 or newer and incompatible # with OpenERP SA "AGPL + Private Use License"! # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. # ############################################################################## from code128 import get_code from code39 import create_c39 from EANBarCode import EanBarCode try: from cStringIO import StringIO except ImportError: from StringIO import StringIO def make_barcode(code, code_type='ean13', rotate=None, height=50, xw=1): if code: if code_type.lower()=='ean13': bar=EanBarCode() im = bar.getImage(code,height) elif code_type.lower()=='code128': im = get_code(code, xw, height) elif code_type.lower()=='code39': im = create_c39(height, xw, code) else: return StringIO(), 'image/png' tf = StringIO() try: if rotate!=None: im=im.rotate(int(rotate)) except Exception, e: pass im.save(tf, 'png') size_x = str(im.size[0]/96.0)+'in' size_y = str(im.size[1]/96.0)+'in' return tf, 'image/png', size_x, size_y
2026-03-31T15:30:28
codeparrot_clean
0406d39a69d1c095d61bfbe97becebda
code
# # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. # from thrift.protocol import TBinaryProtocol from thrift.transport import TTransport def serialize(thrift_object, protocol_factory=TBinaryProtocol.TBinaryProtocolFactory()): transport = TTransport.TMemoryBuffer() protocol = protocol_factory.getProtocol(transport) thrift_object.write(protocol) return transport.getvalue() def deserialize(base, buf, protocol_factory=TBinaryProtocol.TBinaryProtocolFactory()): transport = TTransport.TMemoryBuffer(buf) protocol = protocol_factory.getProtocol(transport) base.read(protocol) return base
2026-03-31T15:30:28
codeparrot_clean
ad2815ac8405c3a6d57e64ad948d5125
code
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2011 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/>. # ############################################################################## from openerp import SUPERUSER_ID from openerp.osv import osv from openerp.tools.translate import _ class mail_mail(osv.Model): """ Update of mail_mail class, to add the signin URL to notifications. """ _inherit = 'mail.mail' def _get_partner_access_link(self, cr, uid, mail, partner=None, context=None): """ Generate URLs for links in mails: - partner is not an user: signup_url - partner is an user: fallback on classic URL """ if context is None: context = {} partner_obj = self.pool.get('res.partner') if partner and not partner.user_ids: contex_signup = dict(context, signup_valid=True) signup_url = partner_obj._get_signup_url_for_action(cr, SUPERUSER_ID, [partner.id], action='mail.action_mail_redirect', model=mail.model, res_id=mail.res_id, context=contex_signup)[partner.id] return ", <span class='oe_mail_footer_access'><small>%(access_msg)s <a style='color:inherit' href='%(portal_link)s'>%(portal_msg)s</a></small></span>" % { 'access_msg': _('access directly to'), 'portal_link': signup_url, 'portal_msg': '%s %s' % (context.get('model_name', ''), mail.record_name) if mail.record_name else _('your messages '), } else: return super(mail_mail, self)._get_partner_access_link(cr, uid, mail, partner=partner, context=context)
2026-03-31T15:30:28
codeparrot_clean
19d333103c37a365d95b0768c445010f
code
# -*- coding: UTF-8 -*- # Copyright 2014-2015 Rumma & Ko Ltd # # License: GNU Affero General Public License v3 (see file COPYING for details) """ Choicelists for `lino_xl.lib.humanlinks`. """ from __future__ import unicode_literals from __future__ import print_function from django.utils.translation import gettext_lazy as _ from django.utils.translation import pgettext_lazy as pgettext from django.utils.text import format_lazy from lino_xl.lib.contacts.roles import ContactsStaff from lino.api import dd class LinkType(dd.Choice): symmetric = False def __init__(self, value, name, mptext, fptext, mctext, fctext, **kw): self.mptext = mptext # male parent self.fptext = fptext self.mctext = mctext self.fctext = fctext # text = string_concat( # mptext, ' (', fptext, ') / ', mctext, ' (', fctext, ')') # text = string_concat(mctext, ' (', fctext, ')') text = format_lazy(u"{}({})",mptext, fptext) # text = "%s (%s) / %s (%s)" % (mptext, fptext, mctext, fctext) super(LinkType, self).__init__(value, text, name, **kw) def as_parent(self, human): if human is None: return self.text return human.mf(self.mptext, self.fptext) def as_child(self, human): if human is None: return self.text return human.mf(self.mctext, self.fctext) class LinkTypes(dd.ChoiceList): """The global list of human link types. This is used as choicelist for the :attr:`type <lino_xl.lib.humanlinks.models.Link.type>` field of a human link. The default list contains the following data: .. django2rst:: rt.show(humanlinks.LinkTypes) .. attribute:: adoptive_parent A person who adopts a child of other parents as his or her own child. .. attribute:: stepparent Someone that your mother or father marries after the marriage to or relationship with your other parent has ended .. attribute:: foster_parent A man (woman) who looks after or brings up a child or children as a father (mother), in place of the natural or adoptive father (mother). [`thefreedictionary <http://www.thefreedictionary.com/foster+father>`_] """ required_roles = dd.login_required(ContactsStaff) verbose_name = _("Parency type") verbose_name_plural = _("Parency types") item_class = LinkType add = LinkTypes.add_item add('01', 'parent', _("Father"), _("Mother"), _("Son"), _("Daughter")) add('02', 'adoptive_parent', _("Adoptive father"), _("Adoptive mother"), _("Adopted son"), _("Adopted daughter")) add('03', 'grandparent', _("Grandfather"), _("Grandmother"), _("Grandson"), _("Granddaughter")) add('05', 'spouse', _("Husband"), _("Wife"), _("Husband"), _("Wife"), symmetric=True) add('06', 'friend', pgettext("male", "Friend"), pgettext("female", "Friend"), pgettext("male", "Friend"), pgettext("female", "Friend"), symmetric=True) add('07', 'partner', pgettext("male", "Partner"), pgettext("female", "Partner"), pgettext("male", "Partner"), pgettext("female", "Partner"), symmetric=True) add('08', 'stepparent', _("Stepfather"), _("Stepmother"), _("Stepson"), _("Stepdaughter")) add('09', 'foster_parent', _("Foster father"), _("Foster mother"), _("Foster son"), _("Foster daughter")) add('10', 'sibling', pgettext("male", "Brother"), pgettext("female", "Sister"), pgettext("male", "Brother"), pgettext("female", "Sister"), symmetric=True) add('11', 'cousin', pgettext("male", "Cousin"), pgettext("female", "Cousin"), pgettext("male", "Cousin"), pgettext("female", "Cousin"), symmetric=True) add('12', 'uncle', _("Uncle"), _("Aunt"), _("Nephew"), _("Niece")) add('80', 'relative', pgettext("male", "Relative"), pgettext("female", "Relative"), pgettext("male", "Relative"), pgettext("female", "Relative"), symmetric=True) add('90', 'other', pgettext("male", "Other"), pgettext("female", "Other"), pgettext("male", "Other"), pgettext("female", "Other"), symmetric=True)
2026-03-31T15:30:28
codeparrot_clean
811e0c9ea8bd5678b65f7a203f87198e
code
""" These classes are light wrappers around Django's database API that provide convenience functionality and permalink functions for the databrowse app. """ from django.db import models from django.utils import formats from django.utils.text import capfirst from django.utils.encoding import smart_unicode, smart_str, iri_to_uri from django.utils.safestring import mark_safe from django.db.models.query import QuerySet EMPTY_VALUE = '(None)' DISPLAY_SIZE = 100 class EasyModel(object): def __init__(self, site, model): self.site = site self.model = model self.model_list = site.registry.keys() self.verbose_name = model._meta.verbose_name self.verbose_name_plural = model._meta.verbose_name_plural def __repr__(self): return '<EasyModel for %s>' % smart_str(self.model._meta.object_name) def model_databrowse(self): "Returns the ModelDatabrowse class for this model." return self.site.registry[self.model] def url(self): return mark_safe('%s%s/%s/' % (self.site.root_url, self.model._meta.app_label, self.model._meta.module_name)) def objects(self, **kwargs): return self.get_query_set().filter(**kwargs) def get_query_set(self): easy_qs = self.model._default_manager.get_query_set()._clone(klass=EasyQuerySet) easy_qs._easymodel = self return easy_qs def object_by_pk(self, pk): return EasyInstance(self, self.model._default_manager.get(pk=pk)) def sample_objects(self): for obj in self.model._default_manager.all()[:3]: yield EasyInstance(self, obj) def field(self, name): try: f = self.model._meta.get_field(name) except models.FieldDoesNotExist: return None return EasyField(self, f) def fields(self): return [EasyField(self, f) for f in (self.model._meta.fields + self.model._meta.many_to_many)] class EasyField(object): def __init__(self, easy_model, field): self.model, self.field = easy_model, field def __repr__(self): return smart_str(u'<EasyField for %s.%s>' % (self.model.model._meta.object_name, self.field.name)) def choices(self): for value, label in self.field.choices: yield EasyChoice(self.model, self, value, label) def url(self): if self.field.choices: return mark_safe('%s%s/%s/%s/' % (self.model.site.root_url, self.model.model._meta.app_label, self.model.model._meta.module_name, self.field.name)) elif self.field.rel: return mark_safe('%s%s/%s/' % (self.model.site.root_url, self.model.model._meta.app_label, self.model.model._meta.module_name)) class EasyChoice(object): def __init__(self, easy_model, field, value, label): self.model, self.field = easy_model, field self.value, self.label = value, label def __repr__(self): return smart_str(u'<EasyChoice for %s.%s>' % (self.model.model._meta.object_name, self.field.name)) def url(self): return mark_safe('%s%s/%s/%s/%s/' % (self.model.site.root_url, self.model.model._meta.app_label, self.model.model._meta.module_name, self.field.field.name, iri_to_uri(self.value))) class EasyInstance(object): def __init__(self, easy_model, instance): self.model, self.instance = easy_model, instance def __repr__(self): return smart_str(u'<EasyInstance for %s (%s)>' % (self.model.model._meta.object_name, self.instance._get_pk_val())) def __unicode__(self): val = smart_unicode(self.instance) if len(val) > DISPLAY_SIZE: return val[:DISPLAY_SIZE] + u'...' return val def __str__(self): return self.__unicode__().encode('utf-8') def pk(self): return self.instance._get_pk_val() def url(self): return mark_safe('%s%s/%s/objects/%s/' % (self.model.site.root_url, self.model.model._meta.app_label, self.model.model._meta.module_name, iri_to_uri(self.pk()))) def fields(self): """ Generator that yields EasyInstanceFields for each field in this EasyInstance's model. """ for f in self.model.model._meta.fields + self.model.model._meta.many_to_many: yield EasyInstanceField(self.model, self, f) def related_objects(self): """ Generator that yields dictionaries of all models that have this EasyInstance's model as a ForeignKey or ManyToManyField, along with lists of related objects. """ for rel_object in self.model.model._meta.get_all_related_objects() + self.model.model._meta.get_all_related_many_to_many_objects(): if rel_object.model not in self.model.model_list: continue # Skip models that aren't in the model_list em = EasyModel(self.model.site, rel_object.model) yield { 'model': em, 'related_field': rel_object.field.verbose_name, 'object_list': [EasyInstance(em, i) for i in getattr(self.instance, rel_object.get_accessor_name()).all()], } class EasyInstanceField(object): def __init__(self, easy_model, instance, field): self.model, self.field, self.instance = easy_model, field, instance self.raw_value = getattr(instance.instance, field.name) def __repr__(self): return smart_str(u'<EasyInstanceField for %s.%s>' % (self.model.model._meta.object_name, self.field.name)) def values(self): """ Returns a list of values for this field for this instance. It's a list so we can accomodate many-to-many fields. """ # This import is deliberately inside the function because it causes # some settings to be imported, and we don't want to do that at the # module level. if self.field.rel: if isinstance(self.field.rel, models.ManyToOneRel): objs = getattr(self.instance.instance, self.field.name) elif isinstance(self.field.rel, models.ManyToManyRel): # ManyToManyRel return list(getattr(self.instance.instance, self.field.name).all()) elif self.field.choices: objs = dict(self.field.choices).get(self.raw_value, EMPTY_VALUE) elif isinstance(self.field, models.DateField) or isinstance(self.field, models.TimeField): if self.raw_value: if isinstance(self.field, models.DateTimeField): objs = capfirst(formats.date_format(self.raw_value, 'DATETIME_FORMAT')) elif isinstance(self.field, models.TimeField): objs = capfirst(formats.time_format(self.raw_value, 'TIME_FORMAT')) else: objs = capfirst(formats.date_format(self.raw_value, 'DATE_FORMAT')) else: objs = EMPTY_VALUE elif isinstance(self.field, models.BooleanField) or isinstance(self.field, models.NullBooleanField): objs = {True: 'Yes', False: 'No', None: 'Unknown'}[self.raw_value] else: objs = self.raw_value return [objs] def urls(self): "Returns a list of (value, URL) tuples." # First, check the urls() method for each plugin. plugin_urls = [] for plugin_name, plugin in self.model.model_databrowse().plugins.items(): urls = plugin.urls(plugin_name, self) if urls is not None: #plugin_urls.append(urls) values = self.values() return zip(self.values(), urls) if self.field.rel: m = EasyModel(self.model.site, self.field.rel.to) if self.field.rel.to in self.model.model_list: lst = [] for value in self.values(): if value is None: continue url = mark_safe('%s%s/%s/objects/%s/' % (self.model.site.root_url, m.model._meta.app_label, m.model._meta.module_name, iri_to_uri(value._get_pk_val()))) lst.append((smart_unicode(value), url)) else: lst = [(value, None) for value in self.values()] elif self.field.choices: lst = [] for value in self.values(): url = mark_safe('%s%s/%s/fields/%s/%s/' % (self.model.site.root_url, self.model.model._meta.app_label, self.model.model._meta.module_name, self.field.name, iri_to_uri(self.raw_value))) lst.append((value, url)) elif isinstance(self.field, models.URLField): val = self.values()[0] lst = [(val, iri_to_uri(val))] else: lst = [(self.values()[0], None)] return lst class EasyQuerySet(QuerySet): """ When creating (or cloning to) an `EasyQuerySet`, make sure to set the `_easymodel` variable to the related `EasyModel`. """ def iterator(self, *args, **kwargs): for obj in super(EasyQuerySet, self).iterator(*args, **kwargs): yield EasyInstance(self._easymodel, obj) def _clone(self, *args, **kwargs): c = super(EasyQuerySet, self)._clone(*args, **kwargs) c._easymodel = self._easymodel return c
2026-03-31T15:30:28
codeparrot_clean
7b661ef3cd25c5098fd7078b08c22f3c
code
# -*- coding: utf-8 - # # This file is part of gunicorn released under the MIT license. # See the NOTICE for more information. """The debug module contains utilities and functions for better debugging Gunicorn.""" import sys import linecache import re import inspect __all__ = ['spew', 'unspew'] _token_spliter = re.compile('\W+') class Spew(object): """ """ def __init__(self, trace_names=None, show_values=True): self.trace_names = trace_names self.show_values = show_values def __call__(self, frame, event, arg): if event == 'line': lineno = frame.f_lineno if '__file__' in frame.f_globals: filename = frame.f_globals['__file__'] if (filename.endswith('.pyc') or filename.endswith('.pyo')): filename = filename[:-1] name = frame.f_globals['__name__'] line = linecache.getline(filename, lineno) else: name = '[unknown]' try: src = inspect.getsourcelines(frame) line = src[lineno] except IOError: line = 'Unknown code named [%s]. VM instruction #%d' % ( frame.f_code.co_name, frame.f_lasti) if self.trace_names is None or name in self.trace_names: print('%s:%s: %s' % (name, lineno, line.rstrip())) if not self.show_values: return self details = [] tokens = _token_spliter.split(line) for tok in tokens: if tok in frame.f_globals: details.append('%s=%r' % (tok, frame.f_globals[tok])) if tok in frame.f_locals: details.append('%s=%r' % (tok, frame.f_locals[tok])) if details: print("\t%s" % ' '.join(details)) return self def spew(trace_names=None, show_values=False): """Install a trace hook which writes incredibly detailed logs about what code is being executed to stdout. """ sys.settrace(Spew(trace_names, show_values)) def unspew(): """Remove the trace hook installed by spew. """ sys.settrace(None)
2026-03-31T15:30:28
codeparrot_clean
817fe1516fbb50b99ca28e095a396f2c
code
try: import distutils.msvc9compiler except ImportError: pass unpatched = dict() def patch_for_specialized_compiler(): """ Patch functions in distutils.msvc9compiler to use the standalone compiler build for Python (Windows only). Fall back to original behavior when the standalone compiler is not available. """ if 'distutils' not in globals(): # The module isn't available to be patched return if unpatched: # Already patched return unpatched.update(vars(distutils.msvc9compiler)) distutils.msvc9compiler.find_vcvarsall = find_vcvarsall distutils.msvc9compiler.query_vcvarsall = query_vcvarsall def find_vcvarsall(version): Reg = distutils.msvc9compiler.Reg VC_BASE = r'Software\%sMicrosoft\DevDiv\VCForPython\%0.1f' key = VC_BASE % ('', version) try: # Per-user installs register the compiler path here productdir = Reg.get_value(key, "installdir") except KeyError: try: # All-user installs on a 64-bit system register here key = VC_BASE % ('Wow6432Node\\', version) productdir = Reg.get_value(key, "installdir") except KeyError: productdir = None if productdir: import os vcvarsall = os.path.join(productdir, "vcvarsall.bat") if os.path.isfile(vcvarsall): return vcvarsall return unpatched['find_vcvarsall'](version) def query_vcvarsall(version, *args, **kwargs): try: return unpatched['query_vcvarsall'](version, *args, **kwargs) except distutils.errors.DistutilsPlatformError as exc: if exc and "vcvarsall.bat" in exc.args[0]: message = 'Microsoft Visual C++ %0.1f is required (%s).' % (version, exc.args[0]) if int(version) == 9: # This redirection link is maintained by Microsoft. # Contact vspython@microsoft.com if it needs updating. raise distutils.errors.DistutilsPlatformError( message + ' Get it from http://aka.ms/vcpython27' ) raise distutils.errors.DistutilsPlatformError(message) raise
2026-03-31T15:30:28
codeparrot_clean
206442d159680b90ca871837e1cc5cb5
code
# -*- coding: utf-8 -*- import re import os import sys import xbmc import urllib import xbmcvfs import xbmcaddon import xbmcgui,xbmcplugin from bs4 import BeautifulSoup import requests import simplejson __addon__ = xbmcaddon.Addon() __author__ = __addon__.getAddonInfo('author') __scriptid__ = __addon__.getAddonInfo('id') __scriptname__ = __addon__.getAddonInfo('name') __version__ = __addon__.getAddonInfo('version') __language__ = __addon__.getLocalizedString __cwd__ = xbmc.translatePath( __addon__.getAddonInfo('path') ).decode("utf-8") __profile__ = xbmc.translatePath( __addon__.getAddonInfo('profile') ).decode("utf-8") __resource__ = xbmc.translatePath( os.path.join( __cwd__, 'resources', 'lib' ) ).decode("utf-8") __temp__ = xbmc.translatePath( os.path.join( __profile__, 'temp') ).decode("utf-8") sys.path.append (__resource__) SUBHD_API = 'http://subhd.com/search/%s' SUBHD_BASE = 'http://subhd.com' UserAgent = 'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; Trident/6.0)' def log(module, msg): xbmc.log((u"%s::%s - %s" % (__scriptname__,module,msg,)).encode('utf-8'),level=xbmc.LOGDEBUG ) def normalizeString(str): return str def session_get(url, id='', referer=''): if id: HEADERS={'Accept': 'application/json, text/javascript, */*; q=0.01', 'Accept-Encoding': 'gzip, deflate', 'Accept-Language': 'zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2', 'Host': 'subhd.com', 'Origin': 'http://subhd.com', 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:58.0) Gecko/20100101 Firefox/58.0'} s = requests.Session() s.headers.update(HEADERS) r = s.get(referer) s.headers.update({'Referer': referer}) r = s.post(url, data={'sub_id': id}) return r.content else: HEADERS={'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8', 'Accept-Encoding': 'gzip, deflate, sdch', 'Accept-Language': 'zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2', 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:58.0) Gecko/20100101 Firefox/58.0'} s = requests.Session() s.headers.update(HEADERS) r = s.get(url) return r.content def Search( item ): subtitles_list = [] log(sys._getframe().f_code.co_name, "Search for [%s] by name" % (os.path.basename( item['file_original_path'] ),)) if item['mansearch']: search_string = item['mansearchstr'] elif len(item['tvshow']) > 0: search_string = "%s S%.2dE%.2d" % (item['tvshow'], int(item['season']), int(item['episode'])) else: search_string = item['title'] url = SUBHD_API % (urllib.quote(search_string)) data = session_get(url) try: soup = BeautifulSoup(data, "html.parser") except: return results = soup.find_all("div", class_="box") # if can't find subtitle for the specified episode, try the whole season instead if (len(results) == 0) and (len(item['tvshow']) > 0): search_string = "%s S%.2d" % (item['tvshow'], int(item['season'])) url = SUBHD_API % (urllib.quote(search_string)) data = session_get(url) try: soup = BeautifulSoup(data, "html.parser") except: return results = [x for x in soup.find_all("div", class_="box") if x.find('div', class_='tvlist')] for it in results: link = SUBHD_BASE + it.find("div", class_="d_title").a.get('href').encode('utf-8') version = it.find("div", class_="d_title").a.get('title').encode('utf-8') if version.find('本字幕按 ') == 0: version = version.split()[1] try: group = it.find("div", class_="d_zu").text.encode('utf-8') if group.isspace(): group = '' except: group = '' if group and (version.find(group) == -1): version += ' ' + group try: r2 = it.find_all("span", class_="label") langs = [x.text.encode('utf-8') for x in r2][:-1] except: langs = '未知' name = '%s (%s)' % (version, ",".join(langs)) if ('英文' in langs) and not(('简体' in langs) or ('繁体' in langs)): subtitles_list.append({"language_name":"English", "filename":name, "link":link, "language_flag":'en', "rating":"0", "lang":langs}) else: subtitles_list.append({"language_name":"Chinese", "filename":name, "link":link, "language_flag":'zh', "rating":"0", "lang":langs}) if subtitles_list: for it in subtitles_list: listitem = xbmcgui.ListItem(label=it["language_name"], label2=it["filename"], iconImage=it["rating"], thumbnailImage=it["language_flag"] ) listitem.setProperty( "sync", "false" ) listitem.setProperty( "hearing_imp", "false" ) url = "plugin://%s/?action=download&link=%s&lang=%s" % (__scriptid__, it["link"], it["lang"] ) xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=url,listitem=listitem,isFolder=False) def rmtree(path): if isinstance(path, unicode): path = path.encode('utf-8') dirs, files = xbmcvfs.listdir(path) for dir in dirs: rmtree(os.path.join(path, dir)) for file in files: xbmcvfs.delete(os.path.join(path, file)) xbmcvfs.rmdir(path) def Download(url,lang): try: rmtree(__temp__) except: pass try: os.makedirs(__temp__) except: pass referer = url subtitle_list = [] exts = [".srt", ".sub", ".txt", ".smi", ".ssa", ".ass" ] try: data = session_get(url) soup = BeautifulSoup(data, "html.parser") id = soup.find("button", class_="btn btn-danger btn-sm").get("sid").encode('utf-8') url = "http://subhd.com/ajax/down_ajax" data = session_get(url, id=id, referer=referer) json_response = simplejson.loads(data) if json_response['success']: url = json_response['url'].replace(r'\/','/').decode("unicode-escape").encode('utf-8') if url[:4] <> 'http': url = 'http://subhd.com%s' % (url) log(sys._getframe().f_code.co_name, "Downloading %s" % (url.decode('utf-8'))) data = session_get(url) else: msg = json_response['msg'].decode("unicode-escape") xbmc.executebuiltin((u'XBMC.Notification("subhd","%s")' % (msg)).encode('utf-8'), True) data = '' except: log(sys._getframe().f_code.co_name, "%s (%d) [%s]" % ( sys.exc_info()[2].tb_frame.f_code.co_name, sys.exc_info()[2].tb_lineno, sys.exc_info()[1] )) return [] if len(data) < 1024: return [] zip = os.path.join(__temp__, "subtitles%s" % os.path.splitext(url)[1]) with open(zip, "wb") as subFile: subFile.write(data) subFile.close() xbmc.sleep(500) if data[:4] == 'Rar!' or data[:2] == 'PK': xbmc.executebuiltin(('XBMC.Extract("%s","%s")' % (zip,__temp__,)).encode('utf-8'), True) path = __temp__ dirs, files = xbmcvfs.listdir(path) if ('__MACOSX') in dirs: dirs.remove('__MACOSX') if len(dirs) > 0: path = os.path.join(__temp__, dirs[0].decode('utf-8')) dirs, files = xbmcvfs.listdir(path) list = [] for subfile in files: if (os.path.splitext( subfile )[1] in exts): list.append(subfile.decode('utf-8')) if len(list) == 1: subtitle_list.append(os.path.join(path, list[0])) elif len(list) > 1: sel = xbmcgui.Dialog().select('请选择压缩包中的字幕', list) if sel == -1: sel = 0 subtitle_list.append(os.path.join(path, list[sel])) return subtitle_list def get_params(): param=[] paramstring=sys.argv[2] if len(paramstring)>=2: params=paramstring cleanedparams=params.replace('?','') if (params[len(params)-1]=='/'): params=params[0:len(params)-2] pairsofparams=cleanedparams.split('&') param={} for i in range(len(pairsofparams)): splitparams={} splitparams=pairsofparams[i].split('=') if (len(splitparams))==2: param[splitparams[0]]=splitparams[1] return param params = get_params() if params['action'] == 'search' or params['action'] == 'manualsearch': item = {} item['temp'] = False item['rar'] = False item['mansearch'] = False item['year'] = xbmc.getInfoLabel("VideoPlayer.Year") # Year item['season'] = str(xbmc.getInfoLabel("VideoPlayer.Season")) # Season item['episode'] = str(xbmc.getInfoLabel("VideoPlayer.Episode")) # Episode item['tvshow'] = normalizeString(xbmc.getInfoLabel("VideoPlayer.TVshowtitle")) # Show item['title'] = normalizeString(xbmc.getInfoLabel("VideoPlayer.OriginalTitle")) # try to get original title item['file_original_path'] = urllib.unquote(xbmc.Player().getPlayingFile().decode('utf-8')) # Full path of a playing file item['3let_language'] = [] if 'searchstring' in params: item['mansearch'] = True item['mansearchstr'] = params['searchstring'] for lang in urllib.unquote(params['languages']).decode('utf-8').split(","): item['3let_language'].append(xbmc.convertLanguage(lang,xbmc.ISO_639_2)) if item['title'] == "": item['title'] = xbmc.getInfoLabel("VideoPlayer.Title") # no original title, get just Title if item['title'] == os.path.basename(xbmc.Player().getPlayingFile()): # get movie title and year if is filename title, year = xbmc.getCleanMovieTitle(item['title']) item['title'] = normalizeString(title.replace('[','').replace(']','')) item['year'] = year if item['episode'].lower().find("s") > -1: # Check if season is "Special" item['season'] = "0" # item['episode'] = item['episode'][-1:] if ( item['file_original_path'].find("http") > -1 ): item['temp'] = True elif ( item['file_original_path'].find("rar://") > -1 ): item['rar'] = True item['file_original_path'] = os.path.dirname(item['file_original_path'][6:]) elif ( item['file_original_path'].find("stack://") > -1 ): stackPath = item['file_original_path'].split(" , ") item['file_original_path'] = stackPath[0][8:] Search(item) elif params['action'] == 'download': subs = Download(params["link"], params["lang"]) for sub in subs: listitem = xbmcgui.ListItem(label=sub) xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=sub,listitem=listitem,isFolder=False) xbmcplugin.endOfDirectory(int(sys.argv[1]))
2026-03-31T15:30:28
codeparrot_clean
24d35f16f87cd6a4fdd75b4757f930b8
code
""" Tests for logout for enterprise flow """ import ddt import mock from django.test.utils import override_settings from django.urls import reverse from openedx.core.djangolib.testing.utils import CacheIsolationTestCase, skip_unless_lms from openedx.features.enterprise_support.api import enterprise_enabled from openedx.features.enterprise_support.tests import ( FAKE_ENTERPRISE_CUSTOMER, FEATURES_WITH_ENTERPRISE_ENABLED, factories ) from openedx.features.enterprise_support.tests.mixins.enterprise import EnterpriseServiceMockMixin from student.tests.factories import UserFactory from util.testing import UrlResetMixin @ddt.ddt @override_settings(FEATURES=FEATURES_WITH_ENTERPRISE_ENABLED) @skip_unless_lms class EnterpriseLogoutTests(EnterpriseServiceMockMixin, CacheIsolationTestCase, UrlResetMixin): """ Tests for the enterprise logout functionality. """ def setUp(self): super(EnterpriseLogoutTests, self).setUp() self.user = UserFactory() self.enterprise_customer = FAKE_ENTERPRISE_CUSTOMER self.enterprise_learner = factories.EnterpriseCustomerUserFactory(user_id=self.user.id) self.client.login(username=self.user.username, password='test') patcher = mock.patch('openedx.features.enterprise_support.api.enterprise_customer_from_api') self.mock_enterprise_customer_from_api = patcher.start() self.mock_enterprise_customer_from_api.return_value = self.enterprise_customer self.addCleanup(patcher.stop) @ddt.data( ('https%3A%2F%2Ftest.edx.org%2Fcourses', False), ('/courses/course-v1:ARTS+D1+2018_T/course/', False), ('invalid-url', False), ('/enterprise/c5dad9a7-741c-4841-868f-850aca3ff848/course/Microsoft+DAT206x/enroll/', True), ('%2Fenterprise%2Fc5dad9a7-741c-4841-868f-850aca3ff848%2Fcourse%2FMicrosoft%2BDAT206x%2Fenroll%2F', True), ('/enterprise/handle_consent_enrollment/efd91463-dc40-4882-aeb9-38202131e7b2/course', True), ('%2Fenterprise%2Fhandle_consent_enrollment%2Fefd91463-dc40-4882-aeb9-38202131e7b2%2Fcourse', True), ) @ddt.unpack def test_logout_enterprise_target(self, redirect_url, enterprise_target): url = '{logout_path}?redirect_url={redirect_url}'.format( logout_path=reverse('logout'), redirect_url=redirect_url ) self.assertTrue(enterprise_enabled()) response = self.client.get(url, HTTP_HOST='testserver') expected = { 'enterprise_target': enterprise_target, } self.assertDictContainsSubset(expected, response.context_data) if enterprise_target: self.assertContains(response, 'We are signing you in.')
2026-03-31T15:30:28
codeparrot_clean
528be7d19d0349971fa84cf7bd6296ea
code
######################################################################## # File : FC_Scaling_test # Author : Andrei Tsaregorodtsev ######################################################################## """ Test suite for a generic File Catalog scalability tests """ __RCSID__ = "$Id$" from DIRAC.Core.Base import Script from DIRAC import S_OK import sys, pprint, os, numpy Script.setUsageMessage( """ Test suite for a generic File Catalog scalability tests """ ) testType = 'noTest' def setTestType( value ): global testType testType = value return S_OK() testDir = '' def setTestDirectory( value ): global testDir testDir = value return S_OK() nClients = 1 def setNumberOfClients( value ): global nClients nClients = int( value ) return S_OK() nQueries = 100 def setNumberOfQueries( value ): global nQueries nQueries = int( value ) return S_OK() lfnListFile = 'lfns_100.txt' def setLFNListFile( value ): global lfnListFile lfnListFile = value return S_OK() outputFile = "output.txt" def setOutputFile( value ): global outputFile outputFile = value return S_OK() catalog = 'AugerTestFileCatalog' def setCatalog( value ): global catalog catalog = value return S_OK() fullTest = False def setFullTest( value ): global fullTest fullTest = True return S_OK() shortRange = False def setShortRange( value ): global shortRange shortRange = True return S_OK() verbosity = 0 def setVerbosity( value ): global verbosity verbosity += 1 return S_OK() Script.registerSwitch( "t:", "type=", "test type", setTestType ) Script.registerSwitch( "D:", "directory=", "test directory", setTestDirectory ) Script.registerSwitch( "N:", "clients=", "number of parallel clients", setNumberOfClients ) Script.registerSwitch( "Q:", "queries=", "number of queries in one test", setNumberOfQueries ) Script.registerSwitch( "C:", "catalog=", "catalog to use", setCatalog ) Script.registerSwitch( "L:", "lfnList=", "file with a list of LFNs", setLFNListFile ) Script.registerSwitch( "F", "fullTest", "run the full test", setFullTest ) Script.registerSwitch( "O:", "output=", "file with output result", setOutputFile ) Script.registerSwitch( "v", "verbose", "file with output result", setVerbosity ) Script.registerSwitch( "S", "shortRange", "run short parameter range", setShortRange ) Script.parseCommandLine( ignoreErrors = True ) from DIRAC.Resources.Catalog.FileCatalog import FileCatalog from DIRAC.Core.Utilities.ProcessPool import ProcessPool from DIRAC import S_OK import time fc = FileCatalog( catalogs=[catalog] ) resultTest = [] def listDirectory( n_queries ): global testDir start = time.time() sCount = 0 fCount = 0 resultList = [] startTotal = time.time() for i in xrange( n_queries ) : start = time.time() result = fc.listDirectory( testDir ) resultList.append( time.time() - start ) if result['OK']: sCount += 1 else: fCount += 1 total = time.time() - startTotal average, error = doStats( resultList ) if verbosity >= 1: print "getReplicas: Total time", total, 'Success', sCount, 'Failure', \ fCount, 'Average', average, 'Stdvar', error result = S_OK( (resultList, sCount, fCount) ) return result def getBulkReplicas( n_queries ): global lfnListFile, verbosity lFile = open(lfnListFile) lfnList = [ l.strip().replace('//','/') for l in lFile.read().strip().split() ] lFile.close() start = time.time() sCount = 0 fCount = 0 resultList = [] startTotal = time.time() for i in xrange( n_queries ) : start = time.time() result = fc.getReplicas( lfnList ) resultList.append( time.time() - start ) if verbosity >= 2: print "getReplicas: received lfns", len(result['Value']['Successful']) for lfn in result['Value']['Successful']: print result['Value']['Successful'][lfn] if verbosity >= 3: for lfn,res in result['Value']['Successful'].items(): print lfn print res break if result['OK']: sCount += 1 else: fCount += 1 total = time.time() - startTotal average, error = doStats( resultList ) if verbosity >= 1: print "getReplicas: Total time", total, 'Success', sCount, 'Failure', \ fCount, 'Average', average, 'Stdvar', error result = S_OK( (resultList, sCount, fCount) ) return result def getDirectoryReplicas( n_queries ): global testDir, verbosity sCount = 0 fCount = 0 resultList = [] startTotal = time.time() for i in xrange( n_queries ) : start = time.time() result = fc.getDirectoryReplicas( testDir ) resultList.append( time.time() - start ) if verbosity >= 2: print "Returned values", len(result['Value']['Successful'][testDir]) for lfn,res in result['Value']['Successful'][testDir].items(): print lfn print res break if result['OK']: sCount += 1 else: fCount += 1 total = time.time() - startTotal average, error = doStats( resultList ) if verbosity >= 1: print "getDirectoryReplicas: Total time", total, 'Success', sCount, 'Failure', \ fCount, '\nAverage', average, 'Stdvar', error result = S_OK( (resultList, sCount, fCount) ) return result def finalize(task,result): global resultTest, verbosity if verbosity >= 2: if result['OK']: print "Test time ", result['Value'], task.getTaskID() else: print "Error:", result['Message'] resultTest.append( result['Value'] ) def doException( expt ): print "Exception", expt def runTest( ): global nClients, nQueries, testType, resultTest, testDir, lfnListFile resultTest = [] pp = ProcessPool( nClients ) testFunction = eval( testType ) for c in xrange( nClients ): pp.createAndQueueTask( testFunction, [nQueries], callback=finalize, exceptionCallback=doException ) pp.processAllResults(3600) pp.finalize(0) timeResult = [] for testTime,success,failure in resultTest: #print testTime,success,failure timeResult += testTime averageTime, errorTime = doStats( timeResult ) rateResult = [ nClients/t for t in timeResult ] averageRate, errorRate = doStats( rateResult ) if testDir: print "\nTest results for clients %d, %s" % ( nClients, testDir ) else: print "\nTest results for clients %d, %s" % ( nClients, lfnListFile ) print "Query time: %.2f +/- %.2f" % (averageTime, errorTime) print "Query rate: %.2f +/- %.2f" % (averageRate, errorRate) return( (averageTime, errorTime), (averageRate, errorRate) ) def doStats( testArray ): array = list( testArray ) # Delete min and max value first del array[ array.index(max(array)) ] del array[ array.index(min(array)) ] numArray = numpy.array( array ) average = numpy.mean( numArray ) stddev = numpy.std( numArray ) return (average, stddev) numberOfFilesList = [ 10, 100, 500, 1000, 2000, 5000, 10000, 15000, 20000 ] numberOfFilesList_short = [ 100, 1000, 5000, 10000, 20000 ] numberOfClientsList = [1,2,3,5,7,10,12,15,20,30,50,75] numberOfClientsList_short = [1,5,10,20] directoriesList = [ (35455, "/auger/prod/QGSjetII_gr20_simADSTv2r5p1/en18.000/th0.65/2008/11/12"), (24024, "/auger/prod/QGSjetII_gr20/2008/09/04/en17.500/th0.65"), #(15205, "/auger/generated/2012-09-03"), (18391,"/auger/prod/QGSjetII_gr20_simADSTv2r5p1/en17.500/th0.65/2008/11/11"), (9907, "/auger/prod/QGSjetII_gr20/2008/09/03/en17.500/th0.65"), (5157, "/auger/prod/QGSjetII_gr20/2008/09/04/en20.000/th0.65"), (2538, "/auger/prod/QGSjetII_gr21/2009/01/12/en18.500/th0.65"), (1500, "/auger/prod/epos_gr03_sim/en17.500/th26.000"), (502, "/auger/prod/REPLICATED20081014/epos_gr08/en21.250/th26.000") ] directoriesList_short = [ (35455, "/auger/prod/QGSjetII_gr20_simADSTv2r5p1/en18.000/th0.65/2008/11/12"), (18391,"/auger/prod/QGSjetII_gr20_simADSTv2r5p1/en17.500/th0.65/2008/11/11"), (5157, "/auger/prod/QGSjetII_gr20/2008/09/04/en20.000/th0.65"), (1000, "/auger/prod/PhotonLib_gr22/2009/02/27/en17.500/th26.000") ] directoriesList.reverse() directoriesList_short.reverse() def executeTest( nc, nf, queryDict, rateDict, queryDict_r, rateDict_r ): global nClients nClients = nc t1,t2 = runTest() query,querys = t1 rate, rates = t2 fileLabel = "%d files" % nf queryDict.setdefault( fileLabel, {} ) queryDict[fileLabel][nc] = (query,querys) rateDict.setdefault( fileLabel, {} ) rateDict[fileLabel][nc] = (rate,rates) clientLabel = "%d clients" % nc queryDict_r.setdefault( clientLabel, {} ) queryDict_r[clientLabel][nf] = (query,querys) rateDict_r.setdefault( clientLabel, {} ) rateDict_r[clientLabel][nf] = (rate,rates) def runFullTest(): global outputFile, nClients, testDir, lfnListFile, shortRange queryDict = {} rateDict = {} queryDict_r = {} rateDict_r = {} ncList = numberOfClientsList if shortRange: ncList = numberOfClientsList_short nfList = numberOfFilesList if shortRange: nfList = numberOfFilesList_short ndList = directoriesList if shortRange: ndList = directoriesList_short for nc in ncList: if testType in ['getBulkReplicas']: for nf in nfList: lfnListFile = "lfns_%d.txt" % nf executeTest( nc, nf, queryDict, rateDict, queryDict_r, rateDict_r ) elif testType in ['getDirectoryReplicas', "listDirectory"]: for nf, directory in ndList: testDir = directory executeTest( nc, nf, queryDict, rateDict, queryDict_r, rateDict_r ) # Writing out result outFile = open( outputFile, "w" ) outFile.write( "Test type %s \n" % testType ) outFile.write( "Number of queries per unit test %d \n" % nQueries ) outFile.write( "Results: \n\n\n" ) outFile.write( 'data_f = ' + str( queryDict ) + '\n\n\n' ) outFile.write( 'data_f_r = ' + str( rateDict ) + '\n\n\n' ) outFile.write( 'data_c = ' + str( queryDict_r ) + '\n\n\n' ) outFile.write( 'data_c_r = ' + str( rateDict_r ) + '\n\n\n' ) outFile.close() pprint.pprint( queryDict ) pprint.pprint( rateDict ) pprint.pprint( queryDict_r ) pprint.pprint( rateDict_r ) ######################################################################### if os.path.exists( outputFile ): print "Output file %s already exists, exiting ..." sys.exit(-1) if fullTest: runFullTest() else: runTest()
2026-03-31T15:30:28
codeparrot_clean
10c24a0f85d3cda4e3b174ff0ca288f3
code
# -*- coding: utf-8 -*- # $Id: da.py 7678 2013-07-03 09:57:36Z milde $ # Author: E D # Copyright: This module has been placed in the public domain. # New language mappings are welcome. Before doing a new translation, please # read <http://docutils.sf.net/docs/howto/i18n.html>. Two files must be # translated for each language: one in docutils/languages, the other in # docutils/parsers/rst/languages. """ Danish-language mappings for language-dependent features of Docutils. """ __docformat__ = 'reStructuredText' labels = { # fixed: language-dependent 'author': 'Forfatter', 'authors': 'Forfattere', 'organization': 'Organisation', 'address': 'Adresse', 'contact': 'Kontakt', 'version': 'Version', 'revision': 'Revision', 'status': 'Status', 'date': 'Dato', 'copyright': 'Copyright', 'dedication': 'Dedikation', 'abstract': 'Resumé', 'attention': 'Giv agt!', 'caution': 'Pas på!', 'danger': '!FARE!', 'error': 'Fejl', 'hint': 'Vink', 'important': 'Vigtigt', 'note': 'Bemærk', 'tip': 'Tips', 'warning': 'Advarsel', 'contents': 'Indhold'} """Mapping of node class name to label text.""" bibliographic_fields = { # language-dependent: fixed 'forfatter': 'author', 'forfattere': 'authors', 'organisation': 'organization', 'adresse': 'address', 'kontakt': 'contact', 'version': 'version', 'revision': 'revision', 'status': 'status', 'dato': 'date', 'copyright': 'copyright', 'dedikation': 'dedication', 'resume': 'abstract', 'resumé': 'abstract'} """Danish (lowcased) to canonical name mapping for bibliographic fields.""" author_separators = [';', ','] """List of separator strings for the 'Authors' bibliographic field. Tried in order."""
2026-03-31T15:30:28
codeparrot_clean
a725b09b911327a0b18cb2510650cbe8
code
# Copyright (c) 2014 Hewlett-Packard Development Company, L.P. # # 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 openstack documentation fragment DOCUMENTATION = ''' options: cloud: description: - Named cloud to operate against. Provides default values for I(auth) and I(auth_type). This parameter is not needed if I(auth) is provided or if OpenStack OS_* environment variables are present. required: false auth: description: - Dictionary containing auth information as needed by the cloud's auth plugin strategy. For the default I(password) plugin, this would contain I(auth_url), I(username), I(password), I(project_name) and any information about domains if the cloud supports them. For other plugins, this param will need to contain whatever parameters that auth plugin requires. This parameter is not needed if a named cloud is provided or OpenStack OS_* environment variables are present. required: false auth_type: description: - Name of the auth plugin to use. If the cloud uses something other than password authentication, the name of the plugin should be indicated here and the contents of the I(auth) parameter should be updated accordingly. required: false default: password region_name: description: - Name of the region. required: false wait: description: - Should ansible wait until the requested resource is complete. required: false default: "yes" choices: ["yes", "no"] timeout: description: - How long should ansible wait for the requested resource. required: false default: 180 api_timeout: description: - How long should the socket layer wait before timing out for API calls. If this is omitted, nothing will be passed to the requests library. required: false default: None validate_certs: description: - Whether or not SSL API requests should be verified. Before 2.3 this defaulted to True. required: false default: null aliases: ['verify'] cacert: description: - A path to a CA Cert bundle that can be used as part of verifying SSL API requests. required: false default: None cert: description: - A path to a client certificate to use as part of the SSL transaction. required: false default: None key: description: - A path to a client key to use as part of the SSL transaction. required: false default: None endpoint_type: description: - Endpoint URL type to fetch from the service catalog. choices: [public, internal, admin] required: false default: public requirements: - python >= 2.7 - shade notes: - The standard OpenStack environment variables, such as C(OS_USERNAME) may be used instead of providing explicit values. - Auth information is driven by os-client-config, which means that values can come from a yaml config file in /etc/ansible/openstack.yaml, /etc/openstack/clouds.yaml or ~/.config/openstack/clouds.yaml, then from standard environment variables, then finally by explicit parameters in plays. More information can be found at U(http://docs.openstack.org/developer/os-client-config) '''
2026-03-31T15:30:28
codeparrot_clean
3a90bfb6fa37ed834ec1ea6e8c8ad4f0
code
#!/usr/bin/env python import numpy from scipy import optimize def find_interval(f, x, *args): x1 = x x2 = x if x == 0.: dx = 1./50. else: dx = x/50. maxiter = 40 twosqrt = numpy.sqrt(2) a = x fa = f(a, *args) b = x fb = f(b, *args) for i in range(maxiter): dx = dx*twosqrt a = x - dx fa = f(a, *args) b = x + dx fb = f(b, *args) if (fa*fb < 0.): return (a, b) raise "Couldn't find a suitable range." # This function evaluates a new point, sets the y range, # and tests for convergence def get_y(x, f, eps, ymax, ymin, *args): y = f(x, *args) ymax = max(ymax, y) ymin = min(ymin, y) converged = (abs(y) < eps*(ymax-ymin)) return (y, ymax, ymin, converged) def fzero(the_func, root_bracket, *args, **parms): # the_func is the function we wish to find the zeros of # root_bracket is an initial guess of the zero location. # Can be a float or a sequence of two floats specifying a range # *args contains any other parameters needed for f # **parms can be eps (allowable error) or maxiter (max number of iterations.) answer=optimize.zeros.brenth(the_func,263,315,args=(e_target)) return answer def testfunc(x): return numpy.sin(x) if __name__=="__main__": f = testfunc x = 1. print fzero(f, x) print fzero(f, x, eps=1e-300, maxiter = 80.)
2026-03-31T15:30:28
codeparrot_clean
89af0b311bd93d59d9cd240df5b31742
code
# -*- coding: utf-8 -*- ''' Exodus Add-on Copyright (C) 2016 Exodus 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/>. ''' import re,urllib,urlparse,json,time from resources.lib.modules import cleantitle from resources.lib.modules import client from resources.lib.modules import directstream from resources.lib.modules import cache class source: def __init__(self): self.priority = 1 self.language = ['en'] self.domains = ['xmovies8.tv', 'xmovies8.ru'] self.base_link = 'https://xmovies8.ru' self.moviesearch_link = '/movies/search?s=%s' def movie(self, imdb, title, localtitle, year): try: url = self.searchMovie(title, year) if url == None: t = cache.get(self.getImdbTitle, 900, imdb) if t != title: url = self.searchMovie(t, year) return url except: return def getImdbTitle(self, imdb): try: t = 'http://www.omdbapi.com/?i=%s' % imdb t = client.request(t) t = json.loads(t) t = cleantitle.normalize(t['Title']) return t except: return def searchMovie(self, title, year): try: title = cleantitle.normalize(title) url = urlparse.urljoin(self.base_link, self.moviesearch_link % (cleantitle.geturl(title.replace('\'', '-')))) r = client.request(url) t = cleantitle.get(title) r = client.parseDOM(r, 'h2', attrs={'class': 'tit'}) r = [(client.parseDOM(i, 'a', ret='href'), client.parseDOM(i, 'a', ret='title')) for i in r] r = [(i[0][0], i[1][0]) for i in r if len(i[0]) > 0 and len(i[1]) > 0] r = [(i[0], re.findall('(.+?) \((\d{4})', i[1])) for i in r] r = [(i[0], i[1][0][0], i[1][0][1]) for i in r if len(i[1]) > 0] r = [i[0] for i in r if t in cleantitle.get(i[1]) and year == i[2]][0] url = re.findall('(?://.+?|)(/.+)', r)[0] url = client.replaceHTMLCodes(url) return url.encode('utf-8') except: return def sources(self, url, hostDict, hostprDict): try: sources = [] if url == None: return sources url = urlparse.urljoin(self.base_link, url) url = path = re.sub('/watching.html$', '', url.strip('/')) url = referer = url + '/watching.html' p = client.request(url) p = re.findall('load_player\(.+?(\d+)', p) p = urllib.urlencode({'id': p[0]}) headers = { 'Accept-Formating': 'application/json, text/javascript', 'Server': 'cloudflare-nginx', 'Referer': referer} r = urlparse.urljoin(self.base_link, '/ajax/movie/load_player_v3') r = client.request(r, post=p, headers=headers, XHR=True) url = json.loads(r)['value'] url = client.request(url, headers=headers, XHR=True, output='geturl') if 'openload.io' in url or 'openload.co' in url or 'oload.tv' in url: sources.append({'source': 'openload.co', 'quality': 'HD', 'language': 'en', 'url': url, 'direct': False,'debridonly': False}) raise Exception() r = client.request(url, headers=headers, XHR=True) try: src = json.loads(r)['playlist'][0]['sources'] links = [i['file'] for i in src if 'file' in i] for i in links: try: sources.append( {'source': 'gvideo', 'quality': directstream.googletag(i)[0]['quality'], 'language': 'en', 'url': i, 'direct': True, 'debridonly': False}) except: pass except: pass return sources except: return sources def resolve(self, url): try: for i in range(3): u = directstream.googlepass(url) if not u == None: break return u except: return
2026-03-31T15:30:28
codeparrot_clean
4567b384733e65a3b8fd33a7f9c8bea7
code
from __future__ import (absolute_import, division, print_function) __metaclass__ = type from ansible.plugins.action import ActionBase import linchpin.MockUtils.MockUtils as mock_utils class ActionModule(ActionBase): def run(self, tmp=None, task_vars=None): """ Simple action plugin that returns the mocked output when linchpin_mock is True """ super(ActionModule, self).run(tmp, task_vars) # contains all the module arguments module_args = self._task.args.copy() # task vars.keys() contains all the variable required # when passed a extra_var as key value pair task_vars # would return mocked output of the named module. # print(task_vars['vars'].keys()) # print(task_vars['vars'].get('linchpin_mock', False)) linchpin_mock = task_vars['vars'].get('linchpin_mock', False) if linchpin_mock: return mock_utils.get_mock_data(module_args, "gcp_compute_network") module_return = self._execute_module(module_args=module_args, task_vars=task_vars, tmp=tmp) return module_return
2026-03-31T15:30:28
codeparrot_clean
037dac2e8cdf88c5d23e6e77ec9da05a
code
#!/usr/bin/python # -*- coding: utf-8 -*- # # Copyright (c) 2016 Red Hat, Inc. # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community'} DOCUMENTATION = ''' --- module: ovirt_host_pm short_description: Module to manage power management of hosts in oVirt/RHV version_added: "2.3" author: "Ondra Machacek (@machacekondra)" description: - "Module to manage power management of hosts in oVirt/RHV." options: name: description: - "Name of the host to manage." required: true aliases: ['host'] state: description: - "Should the host be present/absent." choices: ['present', 'absent'] default: present address: description: - "Address of the power management interface." username: description: - "Username to be used to connect to power management interface." password: description: - "Password of the user specified in C(username) parameter." type: description: - "Type of the power management. oVirt/RHV predefined values are I(drac5), I(ipmilan), I(rsa), I(bladecenter), I(alom), I(apc), I(apc_snmp), I(eps), I(wti), I(rsb), I(cisco_ucs), I(drac7), I(hpblade), I(ilo), I(ilo2), I(ilo3), I(ilo4), I(ilo_ssh), but user can have defined custom type." port: description: - "Power management interface port." options: description: - "Dictionary of additional fence agent options (including Power Management slot)." - "Additional information about options can be found at U(https://github.com/ClusterLabs/fence-agents/blob/master/doc/FenceAgentAPI.md)." encrypt_options: description: - "If I(true) options will be encrypted when send to agent." aliases: ['encrypt'] order: description: - "Integer value specifying, by default it's added at the end." version_added: "2.5" extends_documentation_fragment: ovirt ''' EXAMPLES = ''' # Examples don't contain auth parameter for simplicity, # look at ovirt_auth module to see how to reuse authentication: # Add fence agent to host 'myhost' - ovirt_host_pm: name: myhost address: 1.2.3.4 options: myoption1: x myoption2: y username: admin password: admin port: 3333 type: ipmilan # Add fence agent to host 'myhost' using 'slot' option - ovirt_host_pm: name: myhost address: 1.2.3.4 options: myoption1: x myoption2: y slot: myslot username: admin password: admin port: 3333 type: ipmilan # Remove ipmilan fence agent with address 1.2.3.4 on host 'myhost' - ovirt_host_pm: state: absent name: myhost address: 1.2.3.4 type: ipmilan ''' RETURN = ''' id: description: ID of the agent which is managed returned: On success if agent is found. type: str sample: 7de90f31-222c-436c-a1ca-7e655bd5b60c agent: description: "Dictionary of all the agent attributes. Agent attributes can be found on your oVirt/RHV instance at following url: http://ovirt.github.io/ovirt-engine-api-model/master/#types/agent." returned: On success if agent is found. type: dict ''' import traceback try: import ovirtsdk4.types as otypes except ImportError: pass from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.ovirt import ( BaseModule, check_sdk, create_connection, equal, ovirt_full_argument_spec, search_by_name, ) class HostModule(BaseModule): def build_entity(self): return otypes.Host( power_management=otypes.PowerManagement( enabled=True, ), ) def update_check(self, entity): return equal(True, entity.power_management.enabled) class HostPmModule(BaseModule): def pre_create(self, entity): # Save the entity, so we know if Agent already existed self.entity = entity def build_entity(self): last = next((s for s in sorted([a.order for a in self._service.list()])), 0) order = self.param('order') if self.param('order') is not None else self.entity.order if self.entity else last + 1 return otypes.Agent( address=self._module.params['address'], encrypt_options=self._module.params['encrypt_options'], options=[ otypes.Option( name=name, value=value, ) for name, value in self._module.params['options'].items() ] if self._module.params['options'] else None, password=self._module.params['password'], port=self._module.params['port'], type=self._module.params['type'], username=self._module.params['username'], order=order, ) def update_check(self, entity): def check_options(): if self.param('options'): current = [] if entity.options: current = [(opt.name, str(opt.value)) for opt in entity.options] passed = [(k, str(v)) for k, v in self.param('options').items()] return sorted(current) == sorted(passed) return True return ( check_options() and equal(self._module.params.get('address'), entity.address) and equal(self._module.params.get('encrypt_options'), entity.encrypt_options) and equal(self._module.params.get('username'), entity.username) and equal(self._module.params.get('port'), entity.port) and equal(self._module.params.get('type'), entity.type) and equal(self._module.params.get('order'), entity.order) ) def main(): argument_spec = ovirt_full_argument_spec( state=dict( choices=['present', 'absent'], default='present', ), name=dict(default=None, required=True, aliases=['host']), address=dict(default=None), username=dict(default=None), password=dict(default=None, no_log=True), type=dict(default=None), port=dict(default=None, type='int'), order=dict(default=None, type='int'), options=dict(default=None, type='dict'), encrypt_options=dict(default=None, type='bool', aliases=['encrypt']), ) module = AnsibleModule( argument_spec=argument_spec, supports_check_mode=True, ) check_sdk(module) try: auth = module.params.pop('auth') connection = create_connection(auth) hosts_service = connection.system_service().hosts_service() host = search_by_name(hosts_service, module.params['name']) fence_agents_service = hosts_service.host_service(host.id).fence_agents_service() host_pm_module = HostPmModule( connection=connection, module=module, service=fence_agents_service, ) host_module = HostModule( connection=connection, module=module, service=hosts_service, ) state = module.params['state'] if state == 'present': agent = host_pm_module.search_entity( search_params={ 'address': module.params['address'], 'type': module.params['type'], } ) ret = host_pm_module.create(entity=agent) # Enable Power Management, if it's not enabled: host_module.create(entity=host) elif state == 'absent': agent = host_pm_module.search_entity( search_params={ 'address': module.params['address'], 'type': module.params['type'], } ) ret = host_pm_module.remove(entity=agent) module.exit_json(**ret) except Exception as e: module.fail_json(msg=str(e), exception=traceback.format_exc()) finally: connection.close(logout=auth.get('token') is None) if __name__ == "__main__": main()
2026-03-31T15:30:28
codeparrot_clean
720bf7051f19c2bd217c6d5add37f956
code
#!/usr/bin/env python3 # -*- coding: utf-8 -*- __author__ = 'mookaka' import os, sys, time, subprocess from watchdog.observers import Observer from watchdog.events import FileSystemEventHandler command = ['echo', 'ok'] process = None def log(s): print('[Monitor] %s' % s) class MyFileSystemEventHandler(FileSystemEventHandler): def __init__(self,fn): super(MyFileSystemEventHandler, self).__init__() self.restart = fn def on_any_event(self, event): if event.src_path.endswith('.py'): log('Python source file changed: %s' % event.src_path) self.restart def kill_process(): global process if process: log('Kill process [%s]...' % process.pid) process.kill() process.wait() log('Process ended with code %s.' % process.returncode) process = None def start_process(): global process, command log('Start process %s...' & ' '.join(command)) process = subprocess.Popen(command, stdin=sys.stdin, stdout=sys.stdout, stderr=sys.stderr) def restart_process(): kill_process() start_process() def start_watch(path, callback): observer = Observer() observer.schedule(MyFileSystemEventHandler(restart_process), path, recursive=True) observer.start() log('Watching directory %s...' % path) start_process() try: while True: time.sleep(0.5) except KeyboardInterrupt: observer.stop() observer.join() if __name__ == '__main__': argv = sys.argv[1:] if not argv: print('Usage: ./pymonitor your-script.py') exit(0) if argv[0] != 'python3': argv.insert(0, 'python3') command = argv path = os.path.abspath('.') start_watch(path, None)
2026-03-31T15:30:28
codeparrot_clean
a2209addb91c7147173d7c545b0e8c73
code
# 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. # ============================================================================== """Benchmarks for low-level eager execution primitives. Packaged as a test to ensure that this code is exercised by continuous integration tests. To get numbers: bazel build -c opt :benchmarks_test && ./bazel-bin/tensorflow/python/eager/benchmarks_test --iters=0 """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import argparse import contextlib import sys import time import numpy as np from six.moves import xrange # pylint: disable=redefined-builtin from tensorflow.python import pywrap_tensorflow from tensorflow.python.eager import backprop # pylint: disable=unused-import from tensorflow.python.eager import context from tensorflow.python.eager import function from tensorflow.python.eager import tensor from tensorflow.python.eager import test from tensorflow.python.framework import test_util from tensorflow.python.ops import gen_math_ops from tensorflow.python.ops import math_ops from tensorflow.python.ops import random_ops FLAGS = None @contextlib.contextmanager def timer(label, iters=30000): start = time.time() yield xrange(iters) end = time.time() t = (end - start) * 1e6 / iters print("%-40s took %.2fus (%d iterations)" % (label, t, iters)) def benchmark_create_tensor(n): """Benchmark overheads of creating a Tensor object.""" def label(s): return "{:20s}".format(s) with timer(label("np.array([[3]])"), iters=n) as iters: for _ in iters: np.array([[3]]) with timer(label("Tensor([[3]])"), iters=n) as iters: for _ in iters: tensor.Tensor([[3]]) def benchmark_matmul(shape, n, use_gpu=False): """Benchmark for matrix multiplication using tf.matmul.""" transpose_b = (shape[0] != shape[1]) m = random_ops.random_uniform(shape) if use_gpu: m = m.as_gpu_tensor() # Warm up the GPU - the very first kernel invocation # seems to require a bunch of setup. math_ops.matmul(m, m, transpose_b=transpose_b) def label(s): return "MatMul {}: {:30s}".format(shape, s) if not use_gpu: a = m.as_cpu_tensor().numpy() b = a.T if transpose_b else a with timer(label("np.dot"), iters=n) as iters: for _ in iters: np.dot(a, b) with timer(label("tf.matmul"), iters=n) as iters: for _ in iters: math_ops.matmul(m, m, transpose_b=transpose_b) with timer(label("gen_math_ops.mat_mul"), iters=n) as iters: for _ in iters: gen_math_ops._mat_mul(m, m, transpose_b=transpose_b) # pylint: disable=protected-access input_handles = [m._handle, m._handle] ctx_handle = context.context()._handle # pylint: enable=protected-access attrs = ("transpose_a", False, "transpose_b", transpose_b, "T", m.dtype.as_datatype_enum) with timer(label("TFE_Py_Execute"), iters=n) as iters: for _ in iters: pywrap_tensorflow.TFE_DeleteTensorHandle( pywrap_tensorflow.TFE_Py_Execute(ctx_handle, None, "MatMul", input_handles, attrs, 1)[0]) f = function.defun(math_ops.matmul) with timer(label("defun(tf.matmul)"), iters=n) as iters: for _ in iters: f(m, m, transpose_b=transpose_b) class BenchmarksTest(test_util.TensorFlowTestCase): def testBenchmarks(self): # This isn't actually a test, but benchmarks packaged as a test # so that continuous integration runs catch any breakages. print(context.context()) benchmark_create_tensor(FLAGS.iters or 30000) benchmark_matmul([2, 2], FLAGS.iters or 30000) benchmark_matmul([100, 28 * 28], FLAGS.iters or 1000) if context.context().num_gpus() > 0: print("---- RUNNING ON GPU NOW ----") benchmark_matmul([2, 2], FLAGS.iters or 30000, use_gpu=True) benchmark_matmul([100, 28 * 28], FLAGS.iters or 1000, use_gpu=True) if __name__ == "__main__": parser = argparse.ArgumentParser() # Default iterations to 1 to keep continuos integration test times low. parser.add_argument( "--iters", type=int, default=1, help="Number of iterators for each test. None or 0 for auto-selection") FLAGS, unparsed = parser.parse_known_args() sys.argv = [sys.argv[0]] + unparsed test.main()
2026-03-31T15:30:28
codeparrot_clean
856ca5ae54aa09562135396bb62d485c
code
#!/usr/bin/python # -*- coding: utf-8 -*- # (c) 2012, Michael DeHaan <michael.dehaan@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/>. DOCUMENTATION = ''' --- module: service author: - "Ansible Core Team" - "Michael DeHaan" version_added: "0.1" short_description: Manage services. description: - Controls services on remote hosts. Supported init systems include BSD init, OpenRC, SysV, Solaris SMF, systemd, upstart. options: name: required: true description: - Name of the service. state: required: false choices: [ started, stopped, restarted, reloaded ] description: - C(started)/C(stopped) are idempotent actions that will not run commands unless necessary. C(restarted) will always bounce the service. C(reloaded) will always reload. B(At least one of state and enabled are required.) sleep: required: false version_added: "1.3" description: - If the service is being C(restarted) then sleep this many seconds between the stop and start command. This helps to workaround badly behaving init scripts that exit immediately after signaling a process to stop. pattern: required: false version_added: "0.7" description: - If the service does not respond to the status command, name a substring to look for as would be found in the output of the I(ps) command as a stand-in for a status result. If the string is found, the service will be assumed to be running. enabled: required: false choices: [ "yes", "no" ] description: - Whether the service should start on boot. B(At least one of state and enabled are required.) runlevel: required: false default: 'default' description: - "For OpenRC init scripts (ex: Gentoo) only. The runlevel that this service belongs to." arguments: description: - Additional arguments provided on the command line aliases: [ 'args' ] must_exist: required: false default: true version_added: "2.0" description: - Avoid a module failure if the named service does not exist. Useful for opportunistically starting/stopping/restarting a list of potential services. ''' EXAMPLES = ''' # Example action to start service httpd, if not running - service: name=httpd state=started # Example action to stop service httpd, if running - service: name=httpd state=stopped # Example action to restart service httpd, in all cases - service: name=httpd state=restarted # Example action to reload service httpd, in all cases - service: name=httpd state=reloaded # Example action to enable service httpd, and not touch the running state - service: name=httpd enabled=yes # Example action to start service foo, based on running process /usr/bin/foo - service: name=foo pattern=/usr/bin/foo state=started # Example action to restart network service for interface eth0 - service: name=network state=restarted args=eth0 # Example action to restart nova-compute if it exists - service: name=nova-compute state=restarted must_exist=no ''' import platform import os import re import tempfile import shlex import select import time import string import glob # The distutils module is not shipped with SUNWPython on Solaris. # It's in the SUNWPython-devel package which also contains development files # that don't belong on production boxes. Since our Solaris code doesn't # depend on LooseVersion, do not import it on Solaris. if platform.system() != 'SunOS': from distutils.version import LooseVersion class Service(object): """ This is the generic Service manipulation class that is subclassed based on platform. A subclass should override the following action methods:- - get_service_tools - service_enable - get_service_status - service_control All subclasses MUST define platform and distribution (which may be None). """ platform = 'Generic' distribution = None def __new__(cls, *args, **kwargs): return load_platform_subclass(Service, args, kwargs) def __init__(self, module): self.module = module self.name = module.params['name'] self.state = module.params['state'] self.sleep = module.params['sleep'] self.pattern = module.params['pattern'] self.enable = module.params['enabled'] self.runlevel = module.params['runlevel'] self.changed = False self.running = None self.crashed = None self.action = None self.svc_cmd = None self.svc_initscript = None self.svc_initctl = None self.enable_cmd = None self.arguments = module.params.get('arguments', '') self.rcconf_file = None self.rcconf_key = None self.rcconf_value = None self.svc_change = False # select whether we dump additional debug info through syslog self.syslogging = False # =========================================== # Platform specific methods (must be replaced by subclass). def get_service_tools(self): self.module.fail_json(msg="get_service_tools not implemented on target platform") def service_enable(self): self.module.fail_json(msg="service_enable not implemented on target platform") def get_service_status(self): self.module.fail_json(msg="get_service_status not implemented on target platform") def service_control(self): self.module.fail_json(msg="service_control not implemented on target platform") # =========================================== # Generic methods that should be used on all platforms. def execute_command(self, cmd, daemonize=False): if self.syslogging: syslog.openlog('ansible-%s' % os.path.basename(__file__)) syslog.syslog(syslog.LOG_NOTICE, 'Command %s, daemonize %r' % (cmd, daemonize)) # Most things don't need to be daemonized if not daemonize: return self.module.run_command(cmd) # This is complex because daemonization is hard for people. # What we do is daemonize a part of this module, the daemon runs the # command, picks up the return code and output, and returns it to the # main process. pipe = os.pipe() pid = os.fork() if pid == 0: os.close(pipe[0]) # Set stdin/stdout/stderr to /dev/null fd = os.open(os.devnull, os.O_RDWR) if fd != 0: os.dup2(fd, 0) if fd != 1: os.dup2(fd, 1) if fd != 2: os.dup2(fd, 2) if fd not in (0, 1, 2): os.close(fd) # Make us a daemon. Yes, that's all it takes. pid = os.fork() if pid > 0: os._exit(0) os.setsid() os.chdir("/") pid = os.fork() if pid > 0: os._exit(0) # Start the command if isinstance(cmd, basestring): cmd = shlex.split(cmd) p = subprocess.Popen(cmd, shell=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE, preexec_fn=lambda: os.close(pipe[1])) stdout = "" stderr = "" fds = [p.stdout, p.stderr] # Wait for all output, or until the main process is dead and its output is done. while fds: rfd, wfd, efd = select.select(fds, [], fds, 1) if not (rfd + wfd + efd) and p.poll() is not None: break if p.stdout in rfd: dat = os.read(p.stdout.fileno(), 4096) if not dat: fds.remove(p.stdout) stdout += dat if p.stderr in rfd: dat = os.read(p.stderr.fileno(), 4096) if not dat: fds.remove(p.stderr) stderr += dat p.wait() # Return a JSON blob to parent os.write(pipe[1], json.dumps([p.returncode, stdout, stderr])) os.close(pipe[1]) os._exit(0) elif pid == -1: self.module.fail_json(msg="unable to fork") else: os.close(pipe[1]) os.waitpid(pid, 0) # Wait for data from daemon process and process it. data = "" while True: rfd, wfd, efd = select.select([pipe[0]], [], [pipe[0]]) if pipe[0] in rfd: dat = os.read(pipe[0], 4096) if not dat: break data += dat return json.loads(data) def check_ps(self): # Set ps flags if platform.system() == 'SunOS': psflags = '-ef' else: psflags = 'auxww' # Find ps binary psbin = self.module.get_bin_path('ps', True) (rc, psout, pserr) = self.execute_command('%s %s' % (psbin, psflags)) # If rc is 0, set running as appropriate if rc == 0: self.running = False lines = psout.split("\n") for line in lines: if self.pattern in line and not "pattern=" in line: # so as to not confuse ./hacking/test-module self.running = True break def check_service_changed(self): if self.state and self.running is None: self.module.fail_json(msg="failed determining service state, possible typo of service name?") # Find out if state has changed if not self.running and self.state in ["started", "running", "reloaded"]: self.svc_change = True elif self.running and self.state in ["stopped","reloaded"]: self.svc_change = True elif self.state == "restarted": self.svc_change = True if self.module.check_mode and self.svc_change: self.module.exit_json(changed=True, msg='service state changed') def modify_service_state(self): # Only do something if state will change if self.svc_change: # Control service if self.state in ['started', 'running']: self.action = "start" elif not self.running and self.state == 'reloaded': self.action = "start" elif self.state == 'stopped': self.action = "stop" elif self.state == 'reloaded': self.action = "reload" elif self.state == 'restarted': self.action = "restart" if self.module.check_mode: self.module.exit_json(changed=True, msg='changing service state') return self.service_control() else: # If nothing needs to change just say all is well rc = 0 err = '' out = '' return rc, out, err def service_enable_rcconf(self): if self.rcconf_file is None or self.rcconf_key is None or self.rcconf_value is None: self.module.fail_json(msg="service_enable_rcconf() requires rcconf_file, rcconf_key and rcconf_value") self.changed = None entry = '%s="%s"\n' % (self.rcconf_key, self.rcconf_value) RCFILE = open(self.rcconf_file, "r") new_rc_conf = [] # Build a list containing the possibly modified file. for rcline in RCFILE: # Parse line removing whitespaces, quotes, etc. rcarray = shlex.split(rcline, comments=True) if len(rcarray) >= 1 and '=' in rcarray[0]: (key, value) = rcarray[0].split("=", 1) if key == self.rcconf_key: if value.upper() == self.rcconf_value: # Since the proper entry already exists we can stop iterating. self.changed = False break else: # We found the key but the value is wrong, replace with new entry. rcline = entry self.changed = True # Add line to the list. new_rc_conf.append(rcline) # We are done with reading the current rc.conf, close it. RCFILE.close() # If we did not see any trace of our entry we need to add it. if self.changed is None: new_rc_conf.append(entry) self.changed = True if self.changed is True: if self.module.check_mode: self.module.exit_json(changed=True, msg="changing service enablement") # Create a temporary file next to the current rc.conf (so we stay on the same filesystem). # This way the replacement operation is atomic. rcconf_dir = os.path.dirname(self.rcconf_file) rcconf_base = os.path.basename(self.rcconf_file) (TMP_RCCONF, tmp_rcconf_file) = tempfile.mkstemp(dir=rcconf_dir, prefix="%s-" % rcconf_base) # Write out the contents of the list into our temporary file. for rcline in new_rc_conf: os.write(TMP_RCCONF, rcline) # Close temporary file. os.close(TMP_RCCONF) # Replace previous rc.conf. self.module.atomic_move(tmp_rcconf_file, self.rcconf_file) # =========================================== # Subclass: Linux class LinuxService(Service): """ This is the Linux Service manipulation class - it is currently supporting a mixture of binaries and init scripts for controlling services started at boot, as well as for controlling the current state. """ platform = 'Linux' distribution = None def get_service_tools(self): paths = [ '/sbin', '/usr/sbin', '/bin', '/usr/bin' ] binaries = [ 'service', 'chkconfig', 'update-rc.d', 'rc-service', 'rc-update', 'initctl', 'systemctl', 'start', 'stop', 'restart', 'insserv' ] initpaths = [ '/etc/init.d' ] location = dict() for binary in binaries: location[binary] = self.module.get_bin_path(binary) for initdir in initpaths: initscript = "%s/%s" % (initdir,self.name) if os.path.isfile(initscript): self.svc_initscript = initscript def check_systemd(): # verify systemd is installed (by finding systemctl) if not location.get('systemctl', False): return False # Check if init is the systemd command, using comm as cmdline could be symlink try: f = open('/proc/1/comm', 'r') except IOError, err: # If comm doesn't exist, old kernel, no systemd return False for line in f: if 'systemd' in line: return True return False # Locate a tool to enable/disable a service if location.get('systemctl',False) and check_systemd(): # service is managed by systemd self.__systemd_unit = self.name self.svc_cmd = location['systemctl'] self.enable_cmd = location['systemctl'] elif location.get('initctl', False) and os.path.exists("/etc/init/%s.conf" % self.name): # service is managed by upstart self.enable_cmd = location['initctl'] # set the upstart version based on the output of 'initctl version' self.upstart_version = LooseVersion('0.0.0') try: version_re = re.compile(r'\(upstart (.*)\)') rc,stdout,stderr = self.module.run_command('initctl version') if rc == 0: res = version_re.search(stdout) if res: self.upstart_version = LooseVersion(res.groups()[0]) except: pass # we'll use the default of 0.0.0 if location.get('start', False): # upstart -- rather than being managed by one command, start/stop/restart are actual commands self.svc_cmd = '' elif location.get('rc-service', False): # service is managed by OpenRC self.svc_cmd = location['rc-service'] self.enable_cmd = location['rc-update'] return # already have service start/stop tool too! elif self.svc_initscript: # service is managed by with SysV init scripts if location.get('update-rc.d', False): # and uses update-rc.d self.enable_cmd = location['update-rc.d'] elif location.get('insserv', None): # and uses insserv self.enable_cmd = location['insserv'] elif location.get('chkconfig', False): # and uses chkconfig self.enable_cmd = location['chkconfig'] if self.enable_cmd is None: if self.module.params['must_exist']: self.module.fail_json(msg="no service or tool found for: %s" % self.name) else: # exiting without change on non-existent service self.module.exit_json(changed=False, exists=False) # If no service control tool selected yet, try to see if 'service' is available if self.svc_cmd is None and location.get('service', False): self.svc_cmd = location['service'] # couldn't find anything yet if self.svc_cmd is None and not self.svc_initscript: if self.module.params['must_exist']: self.module.fail_json(msg='cannot find \'service\' binary or init script for service, possible typo in service name?, aborting') else: # exiting without change on non-existent service self.module.exit_json(changed=False, exists=False) if location.get('initctl', False): self.svc_initctl = location['initctl'] def get_systemd_service_enabled(self): (rc, out, err) = self.execute_command("%s is-enabled %s" % (self.enable_cmd, self.__systemd_unit,)) if rc == 0: return True return False def get_systemd_status_dict(self): (rc, out, err) = self.execute_command("%s show %s" % (self.enable_cmd, self.__systemd_unit,)) if rc != 0: self.module.fail_json(msg='failure %d running systemctl show for %r: %s' % (rc, self.__systemd_unit, err)) key = None value_buffer = [] status_dict = {} for line in out.splitlines(): if not key: key, value = line.split('=', 1) # systemd fields that are shell commands can be multi-line # We take a value that begins with a "{" as the start of # a shell command and a line that ends with "}" as the end of # the command if value.lstrip().startswith('{'): if value.rstrip().endswith('}'): status_dict[key] = value key = None else: value_buffer.append(value) else: status_dict[key] = value key = None else: if line.rstrip().endswith('}'): status_dict[key] = '\n'.join(value_buffer) key = None else: value_buffer.append(value) return status_dict def get_systemd_service_status(self): d = self.get_systemd_status_dict() if d.get('ActiveState') == 'active': # run-once services (for which a single successful exit indicates # that they are running as designed) should not be restarted here. # Thus, we are not checking d['SubState']. self.running = True self.crashed = False elif d.get('ActiveState') == 'failed': self.running = False self.crashed = True elif d.get('ActiveState') is None: self.module.fail_json(msg='No ActiveState value in systemctl show output for %r' % (self.__systemd_unit,)) else: self.running = False self.crashed = False return self.running def get_service_status(self): if self.svc_cmd and self.svc_cmd.endswith('systemctl'): return self.get_systemd_service_status() self.action = "status" rc, status_stdout, status_stderr = self.service_control() # if we have decided the service is managed by upstart, we check for some additional output... if self.svc_initctl and self.running is None: # check the job status by upstart response initctl_rc, initctl_status_stdout, initctl_status_stderr = self.execute_command("%s status %s" % (self.svc_initctl, self.name)) if "stop/waiting" in initctl_status_stdout: self.running = False elif "start/running" in initctl_status_stdout: self.running = True if self.svc_cmd and self.svc_cmd.endswith("rc-service") and self.running is None: openrc_rc, openrc_status_stdout, openrc_status_stderr = self.execute_command("%s %s status" % (self.svc_cmd, self.name)) self.running = "started" in openrc_status_stdout self.crashed = "crashed" in openrc_status_stderr # if the job status is still not known check it by status output keywords # Only check keywords if there's only one line of output (some init # scripts will output verbosely in case of error and those can emit # keywords that are picked up as false positives if self.running is None and status_stdout.count('\n') <= 1: # first transform the status output that could irritate keyword matching cleanout = status_stdout.lower().replace(self.name.lower(), '') if "stop" in cleanout: self.running = False elif "run" in cleanout and "not" in cleanout: self.running = False elif "run" in cleanout and "not" not in cleanout: self.running = True elif "start" in cleanout and "not" not in cleanout: self.running = True elif 'could not access pid file' in cleanout: self.running = False elif 'is dead and pid file exists' in cleanout: self.running = False elif 'dead but subsys locked' in cleanout: self.running = False elif 'dead but pid file exists' in cleanout: self.running = False # if the job status is still not known check it by response code # For reference, see: # http://refspecs.linuxbase.org/LSB_4.1.0/LSB-Core-generic/LSB-Core-generic/iniscrptact.html if self.running is None: if rc in [1, 2, 3, 4, 69]: self.running = False elif rc == 0: self.running = True # if the job status is still not known check it by special conditions if self.running is None: if self.name == 'iptables' and "ACCEPT" in status_stdout: # iptables status command output is lame # TODO: lookup if we can use a return code for this instead? self.running = True return self.running def service_enable(self): if self.enable_cmd is None: self.module.fail_json(msg='cannot detect command to enable service %s, typo or init system potentially unknown' % self.name) self.changed = True action = None # # Upstart's initctl # if self.enable_cmd.endswith("initctl"): def write_to_override_file(file_name, file_contents, ): override_file = open(file_name, 'w') override_file.write(file_contents) override_file.close() initpath = '/etc/init' if self.upstart_version >= LooseVersion('0.6.7'): manreg = re.compile('^manual\s*$', re.M | re.I) config_line = 'manual\n' else: manreg = re.compile('^start on manual\s*$', re.M | re.I) config_line = 'start on manual\n' conf_file_name = "%s/%s.conf" % (initpath, self.name) override_file_name = "%s/%s.override" % (initpath, self.name) # Check to see if files contain the manual line in .conf and fail if True if manreg.search(open(conf_file_name).read()): self.module.fail_json(msg="manual stanza not supported in a .conf file") self.changed = False if os.path.exists(override_file_name): override_file_contents = open(override_file_name).read() # Remove manual stanza if present and service enabled if self.enable and manreg.search(override_file_contents): self.changed = True override_state = manreg.sub('', override_file_contents) # Add manual stanza if not present and service disabled elif not (self.enable) and not (manreg.search(override_file_contents)): self.changed = True override_state = '\n'.join((override_file_contents, config_line)) # service already in desired state else: pass # Add file with manual stanza if service disabled elif not (self.enable): self.changed = True override_state = config_line else: # service already in desired state pass if self.module.check_mode: self.module.exit_json(changed=self.changed) # The initctl method of enabling and disabling services is much # different than for the other service methods. So actually # committing the change is done in this conditional and then we # skip the boilerplate at the bottom of the method if self.changed: try: write_to_override_file(override_file_name, override_state) except: self.module.fail_json(msg='Could not modify override file') return # # SysV's chkconfig # if self.enable_cmd.endswith("chkconfig"): if self.enable: action = 'on' else: action = 'off' (rc, out, err) = self.execute_command("%s --list %s" % (self.enable_cmd, self.name)) if 'chkconfig --add %s' % self.name in err: self.execute_command("%s --add %s" % (self.enable_cmd, self.name)) (rc, out, err) = self.execute_command("%s --list %s" % (self.enable_cmd, self.name)) if not self.name in out: self.module.fail_json(msg="service %s does not support chkconfig" % self.name) state = out.split()[-1] # Check if we're already in the correct state if "3:%s" % action in out and "5:%s" % action in out: self.changed = False return # # Systemd's systemctl # if self.enable_cmd.endswith("systemctl"): if self.enable: action = 'enable' else: action = 'disable' # Check if we're already in the correct state service_enabled = self.get_systemd_service_enabled() # self.changed should already be true if self.enable == service_enabled: self.changed = False return # # OpenRC's rc-update # if self.enable_cmd.endswith("rc-update"): if self.enable: action = 'add' else: action = 'delete' (rc, out, err) = self.execute_command("%s show" % self.enable_cmd) for line in out.splitlines(): service_name, runlevels = line.split('|') service_name = service_name.strip() if service_name != self.name: continue runlevels = re.split(r'\s+', runlevels) # service already enabled for the runlevel if self.enable and self.runlevel in runlevels: self.changed = False # service already disabled for the runlevel elif not self.enable and self.runlevel not in runlevels: self.changed = False break else: # service already disabled altogether if not self.enable: self.changed = False if not self.changed: return # # update-rc.d style # if self.enable_cmd.endswith("update-rc.d"): enabled = False slinks = glob.glob('/etc/rc?.d/S??' + self.name) if slinks: enabled = True if self.enable != enabled: self.changed = True if self.enable: action = 'enable' klinks = glob.glob('/etc/rc?.d/K??' + self.name) if not klinks: (rc, out, err) = self.execute_command("%s %s defaults" % (self.enable_cmd, self.name)) if rc != 0: if err: self.module.fail_json(msg=err) else: self.module.fail_json(msg=out) % (self.enable_cmd, self.name, action) else: action = 'disable' if self.module.check_mode: rc = 0 return (rc, out, err) = self.execute_command("%s %s %s" % (self.enable_cmd, self.name, action)) if rc != 0: if err: self.module.fail_json(msg=err) else: self.module.fail_json(msg=out) % (self.enable_cmd, self.name, action) else: self.changed = False return # # insserv (Debian 7) # if self.enable_cmd.endswith("insserv"): if self.enable: (rc, out, err) = self.execute_command("%s -n %s" % (self.enable_cmd, self.name)) else: (rc, out, err) = self.execute_command("%s -nr %s" % (self.enable_cmd, self.name)) self.changed = False for line in err.splitlines(): if self.enable and line.find('enable service') != -1: self.changed = True break if not self.enable and line.find('remove service') != -1: self.changed = True break if self.module.check_mode: self.module.exit_json(changed=self.changed) if not self.changed: return if self.enable: (rc, out, err) = self.execute_command("%s %s" % (self.enable_cmd, self.name)) if (rc != 0) or (err != ''): self.module.fail_json(msg=("Failed to install service. rc: %s, out: %s, err: %s" % (rc, out, err))) return (rc, out, err) else: (rc, out, err) = self.execute_command("%s -r %s" % (self.enable_cmd, self.name)) if (rc != 0) or (err != ''): self.module.fail_json(msg=("Failed to remove service. rc: %s, out: %s, err: %s" % (rc, out, err))) return (rc, out, err) # # If we've gotten to the end, the service needs to be updated # self.changed = True # we change argument order depending on real binary used: # rc-update and systemctl need the argument order reversed if self.enable_cmd.endswith("rc-update"): args = (self.enable_cmd, action, self.name + " " + self.runlevel) elif self.enable_cmd.endswith("systemctl"): args = (self.enable_cmd, action, self.__systemd_unit) else: args = (self.enable_cmd, self.name, action) if self.module.check_mode: self.module.exit_json(changed=self.changed) (rc, out, err) = self.execute_command("%s %s %s" % args) if rc != 0: if err: self.module.fail_json(msg="Error when trying to %s %s: rc=%s %s" % (action, self.name, rc, err)) else: self.module.fail_json(msg="Failure for %s %s: rc=%s %s" % (action, self.name, rc, out)) return (rc, out, err) def service_control(self): # Decide what command to run svc_cmd = '' arguments = self.arguments if self.svc_cmd: if not self.svc_cmd.endswith("systemctl"): # SysV and OpenRC take the form <cmd> <name> <action> svc_cmd = "%s %s" % (self.svc_cmd, self.name) else: # systemd commands take the form <cmd> <action> <name> svc_cmd = self.svc_cmd arguments = "%s %s" % (self.__systemd_unit, arguments) elif self.svc_cmd is None and self.svc_initscript: # upstart svc_cmd = "%s" % self.svc_initscript # In OpenRC, if a service crashed, we need to reset its status to # stopped with the zap command, before we can start it back. if self.svc_cmd and self.svc_cmd.endswith('rc-service') and self.action == 'start' and self.crashed: self.execute_command("%s zap" % svc_cmd, daemonize=True) if self.action is not "restart": if svc_cmd != '': # upstart or systemd or OpenRC rc_state, stdout, stderr = self.execute_command("%s %s %s" % (svc_cmd, self.action, arguments), daemonize=True) else: # SysV rc_state, stdout, stderr = self.execute_command("%s %s %s" % (self.action, self.name, arguments), daemonize=True) elif self.svc_cmd and self.svc_cmd.endswith('rc-service'): # All services in OpenRC support restart. rc_state, stdout, stderr = self.execute_command("%s %s %s" % (svc_cmd, self.action, arguments), daemonize=True) else: # In other systems, not all services support restart. Do it the hard way. if svc_cmd != '': # upstart or systemd rc1, stdout1, stderr1 = self.execute_command("%s %s %s" % (svc_cmd, 'stop', arguments), daemonize=True) else: # SysV rc1, stdout1, stderr1 = self.execute_command("%s %s %s" % ('stop', self.name, arguments), daemonize=True) if self.sleep: time.sleep(self.sleep) if svc_cmd != '': # upstart or systemd rc2, stdout2, stderr2 = self.execute_command("%s %s %s" % (svc_cmd, 'start', arguments), daemonize=True) else: # SysV rc2, stdout2, stderr2 = self.execute_command("%s %s %s" % ('start', self.name, arguments), daemonize=True) # merge return information if rc1 != 0 and rc2 == 0: rc_state = rc2 stdout = stdout2 stderr = stderr2 else: rc_state = rc1 + rc2 stdout = stdout1 + stdout2 stderr = stderr1 + stderr2 return(rc_state, stdout, stderr) # =========================================== # Subclass: FreeBSD class FreeBsdService(Service): """ This is the FreeBSD Service manipulation class - it uses the /etc/rc.conf file for controlling services started at boot and the 'service' binary to check status and perform direct service manipulation. """ platform = 'FreeBSD' distribution = None def get_service_tools(self): self.svc_cmd = self.module.get_bin_path('service', True) if not self.svc_cmd: self.module.fail_json(msg='unable to find service binary') def get_service_status(self): rc, stdout, stderr = self.execute_command("%s %s %s %s" % (self.svc_cmd, self.name, 'onestatus', self.arguments)) if self.name == "pf": self.running = "Enabled" in stdout else: if rc == 1: self.running = False elif rc == 0: self.running = True def service_enable(self): if self.enable: self.rcconf_value = "YES" else: self.rcconf_value = "NO" rcfiles = [ '/etc/rc.conf','/etc/rc.conf.local', '/usr/local/etc/rc.conf' ] for rcfile in rcfiles: if os.path.isfile(rcfile): self.rcconf_file = rcfile rc, stdout, stderr = self.execute_command("%s %s %s %s" % (self.svc_cmd, self.name, 'rcvar', self.arguments)) cmd = "%s %s %s %s" % (self.svc_cmd, self.name, 'rcvar', self.arguments) rcvars = shlex.split(stdout, comments=True) if not rcvars: self.module.fail_json(msg="unable to determine rcvar", stdout=stdout, stderr=stderr) # In rare cases, i.e. sendmail, rcvar can return several key=value pairs # Usually there is just one, however. In other rare cases, i.e. uwsgi, # rcvar can return extra uncommented data that is not at all related to # the rcvar. We will just take the first key=value pair we come across # and hope for the best. for rcvar in rcvars: if '=' in rcvar: self.rcconf_key = rcvar.split('=')[0] break if self.rcconf_key is None: self.module.fail_json(msg="unable to determine rcvar", stdout=stdout, stderr=stderr) try: return self.service_enable_rcconf() except: self.module.fail_json(msg='unable to set rcvar') def service_control(self): if self.action is "start": self.action = "onestart" if self.action is "stop": self.action = "onestop" if self.action is "reload": self.action = "onereload" return self.execute_command("%s %s %s %s" % (self.svc_cmd, self.name, self.action, self.arguments)) # =========================================== # Subclass: OpenBSD class OpenBsdService(Service): """ This is the OpenBSD Service manipulation class - it uses rcctl(8) or /etc/rc.d scripts for service control. Enabling a service is only supported if rcctl is present. """ platform = 'OpenBSD' distribution = None def get_service_tools(self): self.enable_cmd = self.module.get_bin_path('rcctl') if self.enable_cmd: self.svc_cmd = self.enable_cmd else: rcdir = '/etc/rc.d' rc_script = "%s/%s" % (rcdir, self.name) if os.path.isfile(rc_script): self.svc_cmd = rc_script if not self.svc_cmd: self.module.fail_json(msg='unable to find svc_cmd') def get_service_status(self): if self.enable_cmd: rc, stdout, stderr = self.execute_command("%s %s %s" % (self.svc_cmd, 'check', self.name)) else: rc, stdout, stderr = self.execute_command("%s %s" % (self.svc_cmd, 'check')) if stderr: self.module.fail_json(msg=stderr) if rc == 1: self.running = False elif rc == 0: self.running = True def service_control(self): if self.enable_cmd: return self.execute_command("%s -f %s %s" % (self.svc_cmd, self.action, self.name)) else: return self.execute_command("%s -f %s" % (self.svc_cmd, self.action)) def service_enable(self): if not self.enable_cmd: return super(OpenBsdService, self).service_enable() rc, stdout, stderr = self.execute_command("%s %s %s %s" % (self.enable_cmd, 'getdef', self.name, 'flags')) if stderr: self.module.fail_json(msg=stderr) getdef_string = stdout.rstrip() # Depending on the service the string returned from 'getdef' may be # either a set of flags or the boolean YES/NO if getdef_string == "YES" or getdef_string == "NO": default_flags = '' else: default_flags = getdef_string rc, stdout, stderr = self.execute_command("%s %s %s %s" % (self.enable_cmd, 'get', self.name, 'flags')) if stderr: self.module.fail_json(msg=stderr) get_string = stdout.rstrip() # Depending on the service the string returned from 'get' may be # either a set of flags or the boolean YES/NO if get_string == "YES" or get_string == "NO": current_flags = '' else: current_flags = get_string # If there are arguments from the user we use these as flags unless # they are already set. if self.arguments and self.arguments != current_flags: changed_flags = self.arguments # If the user has not supplied any arguments and the current flags # differ from the default we reset them. elif not self.arguments and current_flags != default_flags: changed_flags = ' ' # Otherwise there is no need to modify flags. else: changed_flags = '' rc, stdout, stderr = self.execute_command("%s %s %s %s" % (self.enable_cmd, 'get', self.name, 'status')) if self.enable: if rc == 0 and not changed_flags: return if rc != 0: status_action = "set %s status on" % (self.name) else: status_action = '' if changed_flags: flags_action = "set %s flags %s" % (self.name, changed_flags) else: flags_action = '' else: if rc == 1: return status_action = "set %s status off" % self.name flags_action = '' # Verify state assumption if not status_action and not flags_action: self.module.fail_json(msg="neither status_action or status_flags is set, this should never happen") if self.module.check_mode: self.module.exit_json(changed=True, msg="changing service enablement") status_modified = 0 if status_action: rc, stdout, stderr = self.execute_command("%s %s" % (self.enable_cmd, status_action)) if rc != 0: if stderr: self.module.fail_json(msg=stderr) else: self.module.fail_json(msg="rcctl failed to modify service status") status_modified = 1 if flags_action: rc, stdout, stderr = self.execute_command("%s %s" % (self.enable_cmd, flags_action)) if rc != 0: if stderr: if status_modified: error_message = "rcctl modified service status but failed to set flags: " + stderr else: error_message = stderr else: if status_modified: error_message = "rcctl modified service status but failed to set flags" else: error_message = "rcctl failed to modify service flags" self.module.fail_json(msg=error_message) self.changed = True # =========================================== # Subclass: NetBSD class NetBsdService(Service): """ This is the NetBSD Service manipulation class - it uses the /etc/rc.conf file for controlling services started at boot, check status and perform direct service manipulation. Init scripts in /etc/rcd are used for controlling services (start/stop) as well as for controlling the current state. """ platform = 'NetBSD' distribution = None def get_service_tools(self): initpaths = [ '/etc/rc.d' ] # better: $rc_directories - how to get in here? Run: sh -c '. /etc/rc.conf ; echo $rc_directories' for initdir in initpaths: initscript = "%s/%s" % (initdir,self.name) if os.path.isfile(initscript): self.svc_initscript = initscript if not self.svc_initscript: self.module.fail_json(msg='unable to find rc.d script') def service_enable(self): if self.enable: self.rcconf_value = "YES" else: self.rcconf_value = "NO" rcfiles = [ '/etc/rc.conf' ] # Overkill? for rcfile in rcfiles: if os.path.isfile(rcfile): self.rcconf_file = rcfile self.rcconf_key = "%s" % string.replace(self.name,"-","_") return self.service_enable_rcconf() def get_service_status(self): self.svc_cmd = "%s" % self.svc_initscript rc, stdout, stderr = self.execute_command("%s %s" % (self.svc_cmd, 'onestatus')) if rc == 1: self.running = False elif rc == 0: self.running = True def service_control(self): if self.action is "start": self.action = "onestart" if self.action is "stop": self.action = "onestop" self.svc_cmd = "%s" % self.svc_initscript return self.execute_command("%s %s" % (self.svc_cmd, self.action), daemonize=True) # =========================================== # Subclass: SunOS class SunOSService(Service): """ This is the SunOS Service manipulation class - it uses the svcadm command for controlling services, and svcs command for checking status. It also tries to be smart about taking the service out of maintenance state if necessary. """ platform = 'SunOS' distribution = None def get_service_tools(self): self.svcs_cmd = self.module.get_bin_path('svcs', True) if not self.svcs_cmd: self.module.fail_json(msg='unable to find svcs binary') self.svcadm_cmd = self.module.get_bin_path('svcadm', True) if not self.svcadm_cmd: self.module.fail_json(msg='unable to find svcadm binary') def get_service_status(self): status = self.get_sunos_svcs_status() # Only 'online' is considered properly running. Everything else is off # or has some sort of problem. if status == 'online': self.running = True else: self.running = False def get_sunos_svcs_status(self): rc, stdout, stderr = self.execute_command("%s %s" % (self.svcs_cmd, self.name)) if rc == 1: if stderr: self.module.fail_json(msg=stderr) else: self.module.fail_json(msg=stdout) lines = stdout.rstrip("\n").split("\n") status = lines[-1].split(" ")[0] # status is one of: online, offline, degraded, disabled, maintenance, uninitialized # see man svcs(1) return status def service_enable(self): # Get current service enablement status rc, stdout, stderr = self.execute_command("%s -l %s" % (self.svcs_cmd, self.name)) if rc != 0: if stderr: self.module.fail_json(msg=stderr) else: self.module.fail_json(msg=stdout) enabled = False temporary = False # look for enabled line, which could be one of: # enabled true (temporary) # enabled false (temporary) # enabled true # enabled false for line in stdout.split("\n"): if line.startswith("enabled"): if "true" in line: enabled = True if "temporary" in line: temporary = True startup_enabled = (enabled and not temporary) or (not enabled and temporary) if self.enable and startup_enabled: return elif (not self.enable) and (not startup_enabled): return # Mark service as started or stopped (this will have the side effect of # actually stopping or starting the service) if self.enable: subcmd = "enable -rs" else: subcmd = "disable -s" rc, stdout, stderr = self.execute_command("%s %s %s" % (self.svcadm_cmd, subcmd, self.name)) if rc != 0: if stderr: self.module.fail_json(msg=stderr) else: self.module.fail_json(msg=stdout) self.changed = True def service_control(self): status = self.get_sunos_svcs_status() # if starting or reloading, clear maintenace states if self.action in ['start', 'reload', 'restart'] and status in ['maintenance', 'degraded']: rc, stdout, stderr = self.execute_command("%s clear %s" % (self.svcadm_cmd, self.name)) if rc != 0: return rc, stdout, stderr status = self.get_sunos_svcs_status() if status in ['maintenance', 'degraded']: self.module.fail_json(msg="Failed to bring service out of %s status." % status) if self.action == 'start': subcmd = "enable -rst" elif self.action == 'stop': subcmd = "disable -st" elif self.action == 'reload': subcmd = "refresh" elif self.action == 'restart' and status == 'online': subcmd = "restart" elif self.action == 'restart' and status != 'online': subcmd = "enable -rst" return self.execute_command("%s %s %s" % (self.svcadm_cmd, subcmd, self.name)) # =========================================== # Subclass: AIX class AIX(Service): """ This is the AIX Service (SRC) manipulation class - it uses lssrc, startsrc, stopsrc and refresh for service control. Enabling a service is currently not supported. Would require to add an entry in the /etc/inittab file (mkitab, chitab and rmitab commands) """ platform = 'AIX' distribution = None def get_service_tools(self): self.lssrc_cmd = self.module.get_bin_path('lssrc', True) if not self.lssrc_cmd: self.module.fail_json(msg='unable to find lssrc binary') self.startsrc_cmd = self.module.get_bin_path('startsrc', True) if not self.startsrc_cmd: self.module.fail_json(msg='unable to find startsrc binary') self.stopsrc_cmd = self.module.get_bin_path('stopsrc', True) if not self.stopsrc_cmd: self.module.fail_json(msg='unable to find stopsrc binary') self.refresh_cmd = self.module.get_bin_path('refresh', True) if not self.refresh_cmd: self.module.fail_json(msg='unable to find refresh binary') def get_service_status(self): status = self.get_aix_src_status() # Only 'active' is considered properly running. Everything else is off # or has some sort of problem. if status == 'active': self.running = True else: self.running = False def get_aix_src_status(self): rc, stdout, stderr = self.execute_command("%s -s %s" % (self.lssrc_cmd, self.name)) if rc == 1: if stderr: self.module.fail_json(msg=stderr) else: self.module.fail_json(msg=stdout) lines = stdout.rstrip("\n").split("\n") status = lines[-1].split(" ")[-1] # status is one of: active, inoperative return status def service_control(self): if self.action == 'start': srccmd = self.startsrc_cmd elif self.action == 'stop': srccmd = self.stopsrc_cmd elif self.action == 'reload': srccmd = self.refresh_cmd elif self.action == 'restart': self.execute_command("%s -s %s" % (self.stopsrc_cmd, self.name)) srccmd = self.startsrc_cmd if self.arguments and self.action == 'start': return self.execute_command("%s -a \"%s\" -s %s" % (srccmd, self.arguments, self.name)) else: return self.execute_command("%s -s %s" % (srccmd, self.name)) # =========================================== # Main control flow def main(): module = AnsibleModule( argument_spec = dict( name = dict(required=True), state = dict(choices=['running', 'started', 'stopped', 'restarted', 'reloaded']), sleep = dict(required=False, type='int', default=None), pattern = dict(required=False, default=None), enabled = dict(type='bool'), runlevel = dict(required=False, default='default'), arguments = dict(aliases=['args'], default=''), must_exist = dict(type='bool', default=True), ), supports_check_mode=True ) if module.params['state'] is None and module.params['enabled'] is None: module.fail_json(msg="Neither 'state' nor 'enabled' set") service = Service(module) if service.syslogging: syslog.openlog('ansible-%s' % os.path.basename(__file__)) syslog.syslog(syslog.LOG_NOTICE, 'Service instantiated - platform %s' % service.platform) if service.distribution: syslog.syslog(syslog.LOG_NOTICE, 'Service instantiated - distribution %s' % service.distribution) rc = 0 out = '' err = '' result = {} result['name'] = service.name # Find service management tools service.get_service_tools() # Enable/disable service startup at boot if requested if service.module.params['enabled'] is not None: # FIXME: ideally this should detect if we need to toggle the enablement state, though # it's unlikely the changed handler would need to fire in this case so it's a minor thing. service.service_enable() result['enabled'] = service.enable if module.params['state'] is None: # Not changing the running state, so bail out now. result['changed'] = service.changed module.exit_json(**result) result['state'] = service.state # Collect service status if service.pattern: service.check_ps() else: service.get_service_status() # Calculate if request will change service state service.check_service_changed() # Modify service state if necessary (rc, out, err) = service.modify_service_state() if rc != 0: if err and "Job is already running" in err: # upstart got confused, one such possibility is MySQL on Ubuntu 12.04 # where status may report it has no start/stop links and we could # not get accurate status pass else: if err: module.fail_json(msg=err) else: module.fail_json(msg=out) result['changed'] = service.changed | service.svc_change if service.module.params['enabled'] is not None: result['enabled'] = service.module.params['enabled'] if not service.module.params['state']: status = service.get_service_status() if status is None: result['state'] = 'absent' elif status is False: result['state'] = 'started' else: result['state'] = 'stopped' else: # as we may have just bounced the service the service command may not # report accurate state at this moment so just show what we ran if service.module.params['state'] in ['started','restarted','running','reloaded']: result['state'] = 'started' else: result['state'] = 'stopped' module.exit_json(**result) from ansible.module_utils.basic import * main()
2026-03-31T15:30:28
codeparrot_clean
c5307356767a47220a0e5e1cd1fecc00
code
#!/usr/bin/env python # # Copyright 2011, Google Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following disclaimer # in the documentation and/or other materials provided with the # distribution. # * Neither the name of Google Inc. nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """Tests for util module.""" import os import random import sys import unittest import set_sys_path # Update sys.path to locate mod_pywebsocket module. from mod_pywebsocket import util _TEST_DATA_DIR = os.path.join(os.path.split(__file__)[0], 'testdata') class UtilTest(unittest.TestCase): """A unittest for util module.""" def test_get_stack_trace(self): self.assertEqual('None\n', util.get_stack_trace()) try: a = 1 / 0 # Intentionally raise exception. except Exception: trace = util.get_stack_trace() self.failUnless(trace.startswith('Traceback')) self.failUnless(trace.find('ZeroDivisionError') != -1) def test_prepend_message_to_exception(self): exc = Exception('World') self.assertEqual('World', str(exc)) util.prepend_message_to_exception('Hello ', exc) self.assertEqual('Hello World', str(exc)) def test_get_script_interp(self): cygwin_path = 'c:\\cygwin\\bin' cygwin_perl = os.path.join(cygwin_path, 'perl') self.assertEqual(None, util.get_script_interp( os.path.join(_TEST_DATA_DIR, 'README'))) self.assertEqual(None, util.get_script_interp( os.path.join(_TEST_DATA_DIR, 'README'), cygwin_path)) self.assertEqual('/usr/bin/perl -wT', util.get_script_interp( os.path.join(_TEST_DATA_DIR, 'hello.pl'))) self.assertEqual(cygwin_perl + ' -wT', util.get_script_interp( os.path.join(_TEST_DATA_DIR, 'hello.pl'), cygwin_path)) def test_hexify(self): self.assertEqual('61 7a 41 5a 30 39 20 09 0d 0a 00 ff', util.hexify('azAZ09 \t\r\n\x00\xff')) class RepeatedXorMaskerTest(unittest.TestCase): """A unittest for RepeatedXorMasker class.""" def test_mask(self): # Sample input e6,97,a5 is U+65e5 in UTF-8 masker = util.RepeatedXorMasker('\xff\xff\xff\xff') result = masker.mask('\xe6\x97\xa5') self.assertEqual('\x19\x68\x5a', result) masker = util.RepeatedXorMasker('\x00\x00\x00\x00') result = masker.mask('\xe6\x97\xa5') self.assertEqual('\xe6\x97\xa5', result) masker = util.RepeatedXorMasker('\xe6\x97\xa5\x20') result = masker.mask('\xe6\x97\xa5') self.assertEqual('\x00\x00\x00', result) def test_mask_twice(self): masker = util.RepeatedXorMasker('\x00\x7f\xff\x20') # mask[0], mask[1], ... will be used. result = masker.mask('\x00\x00\x00\x00\x00') self.assertEqual('\x00\x7f\xff\x20\x00', result) # mask[2], mask[0], ... will be used for the next call. result = masker.mask('\x00\x00\x00\x00\x00') self.assertEqual('\x7f\xff\x20\x00\x7f', result) def test_mask_large_data(self): masker = util.RepeatedXorMasker('mASk') original = ''.join([chr(i % 256) for i in xrange(1000)]) result = masker.mask(original) expected = ''.join( [chr((i % 256) ^ ord('mASk'[i % 4])) for i in xrange(1000)]) self.assertEqual(expected, result) masker = util.RepeatedXorMasker('MaSk') first_part = 'The WebSocket Protocol enables two-way communication.' result = masker.mask(first_part) self.assertEqual( '\x19\t6K\x1a\x0418"\x028\x0e9A\x03\x19"\x15<\x08"\rs\x0e#' '\x001\x07(\x12s\x1f:\x0e~\x1c,\x18s\x08"\x0c>\x1e#\x080\n9' '\x08<\x05c', result) second_part = 'It has two parts: a handshake and the data transfer.' result = masker.mask(second_part) self.assertEqual( "('K%\x00 K9\x16<K=\x00!\x1f>[s\nm\t2\x05)\x12;\n&\x04s\n#" "\x05s\x1f%\x04s\x0f,\x152K9\x132\x05>\x076\x19c", result) def get_random_section(source, min_num_chunks): chunks = [] bytes_chunked = 0 while bytes_chunked < len(source): chunk_size = random.randint( 1, min(len(source) / min_num_chunks, len(source) - bytes_chunked)) chunk = source[bytes_chunked:bytes_chunked + chunk_size] chunks.append(chunk) bytes_chunked += chunk_size return chunks class InflaterDeflaterTest(unittest.TestCase): """A unittest for _Inflater and _Deflater class.""" def test_inflate_deflate_default(self): input = b'hello' + '-' * 30000 + b'hello' inflater15 = util._Inflater(15) deflater15 = util._Deflater(15) inflater8 = util._Inflater(8) deflater8 = util._Deflater(8) compressed15 = deflater15.compress_and_finish(input) compressed8 = deflater8.compress_and_finish(input) inflater15.append(compressed15) inflater8.append(compressed8) self.assertNotEqual(compressed15, compressed8) self.assertEqual(input, inflater15.decompress(-1)) self.assertEqual(input, inflater8.decompress(-1)) def test_random_section(self): random.seed(a=0) source = ''.join( [chr(random.randint(0, 255)) for i in xrange(100 * 1024)]) chunked_input = get_random_section(source, 10) print "Input chunk sizes: %r" % [len(c) for c in chunked_input] deflater = util._Deflater(15) compressed = [] for chunk in chunked_input: compressed.append(deflater.compress(chunk)) compressed.append(deflater.compress_and_finish('')) chunked_expectation = get_random_section(source, 10) print ("Expectation chunk sizes: %r" % [len(c) for c in chunked_expectation]) inflater = util._Inflater(15) inflater.append(''.join(compressed)) for chunk in chunked_expectation: decompressed = inflater.decompress(len(chunk)) self.assertEqual(chunk, decompressed) self.assertEqual('', inflater.decompress(-1)) if __name__ == '__main__': unittest.main() # vi:sts=4 sw=4 et
2026-03-31T15:30:28
codeparrot_clean
5aa5b76bbe4c613a9b5cca315e1d94ea
code
# *************************************************************************** # * Copyright (c) 2009, 2010 Yorik van Havre <yorik@uncreated.net> * # * Copyright (c) 2009, 2010 Ken Cline <cline@frii.com> * # * Copyright (c) 2020 Carlo Pavan <carlopav@gmail.com> * # * Copyright (c) 2020 Eliud Cabrera Castillo <e.cabrera-castillo@tum.de> * # * * # * This program is free software; you can redistribute it and/or modify * # * it under the terms of the GNU Lesser General Public License (LGPL) * # * as published by the Free Software Foundation; either version 2 of * # * the License, or (at your option) any later version. * # * for detail see the LICENCE text file. * # * * # * 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 Library General Public License for more details. * # * * # * You should have received a copy of the GNU Library 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 * # * * # *************************************************************************** """Provides functions to produce a mirrored object. It just creates a `Part::Mirroring` object, and sets the appropriate `Source` and `Normal` properties. """ ## @package mirror # \ingroup draftfunctions # \brief Provides functions to produce a mirrored object. ## \addtogroup draftfuctions # @{ import FreeCAD as App import draftutils.utils as utils import draftutils.gui_utils as gui_utils from draftutils.messages import _err from draftutils.translate import translate if App.GuiUp: import FreeCADGui as Gui def mirror(objlist, p1, p2): """Create a mirror object from the provided list and line. It creates a `Part::Mirroring` object from the given `objlist` using a plane that is defined by the two given points `p1` and `p2`, and either - the Draft working plane normal, or - the negative normal provided by the camera direction if the working plane normal does not exist and the graphical interface is available. If neither of these two is available, it uses as normal the +Z vector. Parameters ---------- objlist: single object or a list of objects A single object or a list of objects. p1: Base::Vector3 Point 1 of the mirror plane. It is also used as the `Placement.Base` of the resulting object. p2: Base::Vector3 Point 1 of the mirror plane. Returns ------- None If the operation fails. list List of `Part::Mirroring` objects, or a single one depending on the input `objlist`. To Do ----- Implement a mirror tool specific to the workbench that does not just use `Part::Mirroring`. It should create a derived object, that is, it should work similar to `Draft.offset`. """ utils.print_header('mirror', "Create mirror") if not objlist: _err(translate("draft","No object given")) return if p1 == p2: _err(translate("draft","The two points are coincident")) return if not isinstance(objlist, list): objlist = [objlist] if hasattr(App, "DraftWorkingPlane"): norm = App.DraftWorkingPlane.getNormal() elif App.GuiUp: norm = Gui.ActiveDocument.ActiveView.getViewDirection().negative() else: norm = App.Vector(0, 0, 1) pnorm = p2.sub(p1).cross(norm).normalize() result = [] for obj in objlist: mir = App.ActiveDocument.addObject("Part::Mirroring", "mirror") mir.Label = obj.Label + " (" + translate("draft","mirrored") + ") " mir.Source = obj mir.Base = p1 mir.Normal = pnorm gui_utils.format_object(mir, obj) result.append(mir) if len(result) == 1: result = result[0] gui_utils.select(result) return result ## @}
2026-03-31T15:30:28
codeparrot_clean
959a7be56268103138c66bc84c30ce30
code
#!/usr/bin/env python # # Copyright 2008, 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. """Verifies that Google Test warns the user when not initialized properly.""" import gtest_test_utils COMMAND = gtest_test_utils.GetTestExecutablePath('googletest-uninitialized-test_') def Assert(condition): if not condition: raise AssertionError def AssertEq(expected, actual): if expected != actual: print('Expected: %s' % (expected,)) print(' Actual: %s' % (actual,)) raise AssertionError def TestExitCodeAndOutput(command): """Runs the given command and verifies its exit code and output.""" # Verifies that 'command' exits with code 1. p = gtest_test_utils.Subprocess(command) if p.exited and p.exit_code == 0: Assert('IMPORTANT NOTICE' in p.output); Assert('InitGoogleTest' in p.output) class GTestUninitializedTest(gtest_test_utils.TestCase): def testExitCodeAndOutput(self): TestExitCodeAndOutput(COMMAND) if __name__ == '__main__': gtest_test_utils.Main()
2026-03-31T15:30:28
codeparrot_clean
d6101ab847b8ee9c9e621ec99b61f9b1
code
# (c) 2014, James Tanner <tanner.jc@gmail.com> # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Ansible is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Ansible. If not, see <http://www.gnu.org/licenses/>. # # ansible-vault is a script that encrypts/decrypts YAML files. See # http://docs.ansible.com/playbooks_vault.html for more details. from __future__ import (absolute_import, division, print_function) __metaclass__ = type import datetime import os import traceback import textwrap from ansible.compat.six import iteritems from ansible.errors import AnsibleError, AnsibleOptionsError from ansible.plugins import module_loader from ansible.cli import CLI from ansible.utils import module_docs try: from __main__ import display except ImportError: from ansible.utils.display import Display display = Display() class DocCLI(CLI): """ Vault command line class """ BLACKLIST_EXTS = ('.pyc', '.swp', '.bak', '~', '.rpm', '.md', '.txt') IGNORE_FILES = [ "COPYING", "CONTRIBUTING", "LICENSE", "README", "VERSION", "GUIDELINES", "test-docs.sh"] def __init__(self, args): super(DocCLI, self).__init__(args) self.module_list = [] def parse(self): self.parser = CLI.base_parser( usage='usage: %prog [options] [module...]', epilog='Show Ansible module documentation', module_opts=True, ) self.parser.add_option("-l", "--list", action="store_true", default=False, dest='list_dir', help='List available modules') self.parser.add_option("-s", "--snippet", action="store_true", default=False, dest='show_snippet', help='Show playbook snippet for specified module(s)') self.options, self.args = self.parser.parse_args(self.args[1:]) display.verbosity = self.options.verbosity def run(self): super(DocCLI, self).run() if self.options.module_path is not None: for i in self.options.module_path.split(os.pathsep): module_loader.add_directory(i) # list modules if self.options.list_dir: paths = module_loader._get_paths() for path in paths: self.find_modules(path) self.pager(self.get_module_list_text()) return 0 if len(self.args) == 0: raise AnsibleOptionsError("Incorrect options passed") # process command line module list text = '' for module in self.args: try: # if the module lives in a non-python file (eg, win_X.ps1), require the corresponding python file for docs filename = module_loader.find_plugin(module, mod_type='.py') if filename is None: display.warning("module %s not found in %s\n" % (module, DocCLI.print_paths(module_loader))) continue if any(filename.endswith(x) for x in self.BLACKLIST_EXTS): continue try: doc, plainexamples, returndocs = module_docs.get_docstring(filename, verbose=(self.options.verbosity > 0)) except: display.vvv(traceback.print_exc()) display.error("module %s has a documentation error formatting or is missing documentation\nTo see exact traceback use -vvv" % module) continue if doc is not None: all_keys = [] for (k,v) in iteritems(doc['options']): all_keys.append(k) all_keys = sorted(all_keys) doc['option_keys'] = all_keys doc['filename'] = filename doc['docuri'] = doc['module'].replace('_', '-') doc['now_date'] = datetime.date.today().strftime('%Y-%m-%d') doc['plainexamples'] = plainexamples doc['returndocs'] = returndocs if self.options.show_snippet: text += self.get_snippet_text(doc) else: text += self.get_man_text(doc) else: # this typically means we couldn't even parse the docstring, not just that the YAML is busted, # probably a quoting issue. raise AnsibleError("Parsing produced an empty object.") except Exception as e: display.vvv(traceback.print_exc()) raise AnsibleError("module %s missing documentation (or could not parse documentation): %s\n" % (module, str(e))) self.pager(text) return 0 def find_modules(self, path): if os.path.isdir(path): for module in os.listdir(path): if module.startswith('.'): continue elif os.path.isdir(module): self.find_modules(module) elif any(module.endswith(x) for x in self.BLACKLIST_EXTS): continue elif module.startswith('__'): continue elif module in self.IGNORE_FILES: continue elif module.startswith('_'): fullpath = '/'.join([path,module]) if os.path.islink(fullpath): # avoids aliases continue module = os.path.splitext(module)[0] # removes the extension self.module_list.append(module) def get_module_list_text(self): columns = display.columns displace = max(len(x) for x in self.module_list) linelimit = columns - displace - 5 text = [] deprecated = [] for module in sorted(set(self.module_list)): if module in module_docs.BLACKLIST_MODULES: continue # if the module lives in a non-python file (eg, win_X.ps1), require the corresponding python file for docs filename = module_loader.find_plugin(module, mod_type='.py') if filename is None: continue if filename.endswith(".ps1"): continue if os.path.isdir(filename): continue try: doc, plainexamples, returndocs = module_docs.get_docstring(filename) desc = self.tty_ify(doc.get('short_description', '?')).strip() if len(desc) > linelimit: desc = desc[:linelimit] + '...' if module.startswith('_'): # Handle deprecated deprecated.append("%-*s %-*.*s" % (displace, module[1:], linelimit, len(desc), desc)) else: text.append("%-*s %-*.*s" % (displace, module, linelimit, len(desc), desc)) except: raise AnsibleError("module %s has a documentation error formatting or is missing documentation\n" % module) if len(deprecated) > 0: text.append("\nDEPRECATED:") text.extend(deprecated) return "\n".join(text) @staticmethod def print_paths(finder): ''' Returns a string suitable for printing of the search path ''' # Uses a list to get the order right ret = [] for i in finder._get_paths(): if i not in ret: ret.append(i) return os.pathsep.join(ret) def get_snippet_text(self, doc): text = [] desc = CLI.tty_ify(doc['short_description']) text.append("- name: %s" % (desc)) text.append(" action: %s" % (doc['module'])) pad = 31 subdent = ''.join([" " for a in xrange(pad)]) limit = display.columns - pad for o in sorted(doc['options'].keys()): opt = doc['options'][o] desc = CLI.tty_ify(" ".join(opt['description'])) if opt.get('required', False): s = o + "=" else: s = o text.append(" %-20s # %s" % (s, textwrap.fill(desc, limit, subsequent_indent=subdent))) text.append('') return "\n".join(text) def get_man_text(self, doc): opt_indent=" " text = [] text.append("> %s\n" % doc['module'].upper()) pad = display.columns * 0.20 limit = max(display.columns - int(pad), 70) if isinstance(doc['description'], list): desc = " ".join(doc['description']) else: desc = doc['description'] text.append("%s\n" % textwrap.fill(CLI.tty_ify(desc), limit, initial_indent=" ", subsequent_indent=" ")) if 'deprecated' in doc and doc['deprecated'] is not None and len(doc['deprecated']) > 0: text.append("DEPRECATED: \n%s\n" % doc['deprecated']) if 'option_keys' in doc and len(doc['option_keys']) > 0: text.append("Options (= is mandatory):\n") for o in sorted(doc['option_keys']): opt = doc['options'][o] if opt.get('required', False): opt_leadin = "=" else: opt_leadin = "-" text.append("%s %s" % (opt_leadin, o)) if isinstance(opt['description'], list): desc = " ".join(opt['description']) else: desc = opt['description'] if 'choices' in opt: choices = ", ".join(str(i) for i in opt['choices']) desc = desc + " (Choices: " + choices + ")" if 'default' in opt: default = str(opt['default']) desc = desc + " [Default: " + default + "]" text.append("%s\n" % textwrap.fill(CLI.tty_ify(desc), limit, initial_indent=opt_indent, subsequent_indent=opt_indent)) if 'notes' in doc and doc['notes'] and len(doc['notes']) > 0: notes = " ".join(doc['notes']) text.append("Notes:%s\n" % textwrap.fill(CLI.tty_ify(notes), limit-6, initial_indent=" ", subsequent_indent=opt_indent)) if 'requirements' in doc and doc['requirements'] is not None and len(doc['requirements']) > 0: req = ", ".join(doc['requirements']) text.append("Requirements:%s\n" % textwrap.fill(CLI.tty_ify(req), limit-16, initial_indent=" ", subsequent_indent=opt_indent)) if 'examples' in doc and len(doc['examples']) > 0: text.append("Example%s:\n" % ('' if len(doc['examples']) < 2 else 's')) for ex in doc['examples']: text.append("%s\n" % (ex['code'])) if 'plainexamples' in doc and doc['plainexamples'] is not None: text.append("EXAMPLES:") text.append(doc['plainexamples']) if 'returndocs' in doc and doc['returndocs'] is not None: text.append("RETURN VALUES:") text.append(doc['returndocs']) text.append('') maintainers = set() if 'author' in doc: if isinstance(doc['author'], basestring): maintainers.add(doc['author']) else: maintainers.update(doc['author']) if 'maintainers' in doc: if isinstance(doc['maintainers'], basestring): maintainers.add(doc['author']) else: maintainers.update(doc['author']) text.append('MAINTAINERS: ' + ', '.join(maintainers)) text.append('') return "\n".join(text)
2026-03-31T15:30:28
codeparrot_clean
85886ea02134da74a9ffe297e3b276f5
code
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: t -*- # vi: set ft=python sts=4 ts=4 sw=4 noet : # This file is part of Fail2Ban. # # Fail2Ban 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. # # Fail2Ban 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 Fail2Ban; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # Author: Cyril Jaquier # __author__ = "Cyril Jaquier" __copyright__ = "Copyright (c) 2004 Cyril Jaquier" __license__ = "GPL" from .configreader import ConfigReader from .jailreader import JailReader from ..helpers import getLogger # Gets the instance of the logger. logSys = getLogger(__name__) class JailsReader(ConfigReader): def __init__(self, force_enable=False, **kwargs): """ Parameters ---------- force_enable : bool, optional Passed to JailReader to force enable the jails. It is for internal use """ ConfigReader.__init__(self, **kwargs) self.__jails = list() self.__force_enable = force_enable @property def jails(self): return self.__jails def read(self): self.__jails = list() return ConfigReader.read(self, "jail") def getOptions(self, section=None): """Reads configuration for jail(s) and adds enabled jails to __jails """ opts = [] self.__opts = ConfigReader.getOptions(self, "Definition", opts) if section is None: sections = self.sections() else: sections = [ section ] # Get the options of all jails. parse_status = True for sec in sections: if sec == 'INCLUDES': continue # use the cfg_share for filter/action caching and the same config for all # jails (use_config=...), therefore don't read it here: jail = JailReader(sec, force_enable=self.__force_enable, share_config=self.share_config, use_config=self._cfg) ret = jail.getOptions() if ret: if jail.isEnabled(): # We only add enabled jails self.__jails.append(jail) else: logSys.error("Errors in jail %r. Skipping..." % sec) parse_status = False return parse_status def convert(self, allow_no_files=False): """Convert read before __opts and jails to the commands stream Parameters ---------- allow_missing : bool Either to allow log files to be missing entirely. Primarily is used for testing """ stream = list() for opt in self.__opts: if opt == "": stream.append([]) # Convert jails for jail in self.__jails: stream.extend(jail.convert(allow_no_files=allow_no_files)) # Start jails for jail in self.__jails: stream.append(["start", jail.getName()]) return stream
2026-03-31T15:30:28
codeparrot_clean
476270956eb8efd2d48cb494cf76b8e7
code
#!/usr/bin/env python3 import sys, os from cookiejar import PersistentCookieJar from leftpane import LeftPane from notifier import Notifier from resources import Resources from systray import Systray from wrapper import Wrapper from os.path import expanduser from PyQt4 import QtCore, QtGui, QtWebKit from PyQt4.Qt import QApplication, QKeySequence from PyQt4.QtCore import QUrl, QSettings from PyQt4.QtWebKit import QWebSettings # Auto-detection of Unity and Dbusmenu in gi repository try: from gi.repository import Unity, Dbusmenu except ImportError: Unity = None Dbusmenu = None from launcher import DummyLauncher class zcswebapp(QtGui.QMainWindow): plugins = True debug = False forceClose = False messages = 0 def __init__(self, parent = None, settings_path = ""): super(zcswebapp, self).__init__(parent) self.setWindowTitle('zcswebapp') self.settings_path = settings_path self.notifier = Notifier(Resources.APP_NAME, Resources.get_path('zcswebapp.png')) self.settings = QSettings(self.settings_path + '/zcswebapp.cfg', QSettings.IniFormat) self.identifier = self.settings.value("Domain") if Unity is not None: self.launcher = Unity.LauncherEntry.get_for_desktop_id("zcswebapp.desktop") else: self.launcher = DummyLauncher(self) self.webSettings() self.leftPane = LeftPane(self) webView = Wrapper(self) webView.page().networkAccessManager().setCookieJar(self.cookiesjar) self.stackedWidget = QtGui.QStackedWidget() self.stackedWidget.addWidget(webView) centralWidget = QtGui.QWidget(self) layout = QtGui.QHBoxLayout() layout.setContentsMargins(0, 0, 0, 0) layout.setSpacing(0) layout.addWidget(self.leftPane) layout.addWidget(self.stackedWidget) centralWidget.setLayout(layout) self.setCentralWidget(centralWidget) self.addMenu() self.tray = Systray(self) self.systray(zcswebapp.minimized) self.installEventFilter(self) if self.identifier is None: webView.load(QtCore.QUrl(Resources.SIGNIN_URL)) else: webView.load(QtCore.QUrl(self.domain())) webView.show() def webSettings(self): self.cookiesjar = PersistentCookieJar(self) self.zoom = self.readZoom() # Required by Youtube videos (HTML5 video support only on Qt5) QWebSettings.globalSettings().setAttribute(QWebSettings.PluginsEnabled, self.plugins) # We don't want Java QWebSettings.globalSettings().setAttribute(QWebSettings.JavaEnabled, False) # We don't need History QWebSettings.globalSettings().setAttribute(QWebSettings.PrivateBrowsingEnabled, True) # Required for copy and paste clipboard integration QWebSettings.globalSettings().setAttribute(QWebSettings.JavascriptCanAccessClipboard, True) # Enabling Inspeclet only when --debug=True (requires more CPU usage) QWebSettings.globalSettings().setAttribute(QWebSettings.DeveloperExtrasEnabled, self.debug) def toggleFullScreen(self): if self.isFullScreen(): self.showMaximized() else: self.showFullScreen() def restore(self): geometry = self.settings.value("geometry") if geometry is not None: self.restoreGeometry(geometry) windowState = self.settings.value("windowState") if windowState is not None: self.restoreState(windowState) else: self.showMaximized() def systray(self, show=None): if show is None: show = self.settings.value("Systray") == "True" if show: self.tray.show() self.menus["file"]["close"].setEnabled(True) self.settings.setValue("Systray", "True") else: self.tray.setVisible(False) self.menus["file"]["close"].setEnabled(False) self.settings.setValue("Systray", "False") def readZoom(self): default = 1 if self.settings.value("Zoom") is not None: default = float(self.settings.value("Zoom")) return default def setZoom(self, factor=1): if factor > 0: for i in range(0, self.stackedWidget.count()): widget = self.stackedWidget.widget(i) widget.setZoomFactor(factor) self.settings.setValue("Zoom", factor) def zoomIn(self): self.setZoom(self.current().zoomFactor() + 0.1) def zoomOut(self): self.setZoom(self.current().zoomFactor() - 0.1) def zoomReset(self): self.setZoom() def addMenu(self): self.menus = { "file": { "preferences": self.createAction("Preferences", self.current().preferences), "systray": self.createAction("Close to Tray", self.systray, None, True), "addTeam": self.createAction("Sign in to Another Team", self.current().addTeam), "signout": self.createAction("Signout", self.current().logout), "close": self.createAction("Close", self.close, QKeySequence.Close), "exit": self.createAction("Quit", self.exit, QKeySequence.Quit) }, "edit": { "undo": self.current().pageAction(QtWebKit.QWebPage.Undo), "redo": self.current().pageAction(QtWebKit.QWebPage.Redo), "cut": self.current().pageAction(QtWebKit.QWebPage.Cut), "copy": self.current().pageAction(QtWebKit.QWebPage.Copy), "paste": self.current().pageAction(QtWebKit.QWebPage.Paste), "back": self.current().pageAction(QtWebKit.QWebPage.Back), "forward": self.current().pageAction(QtWebKit.QWebPage.Forward), "reload": self.current().pageAction(QtWebKit.QWebPage.Reload) }, "view": { "zoomin": self.createAction("Zoom In", self.zoomIn, QKeySequence.ZoomIn), "zoomout": self.createAction("Zoom Out", self.zoomOut, QKeySequence.ZoomOut), "reset": self.createAction("Reset", self.zoomReset, QtCore.Qt.CTRL + QtCore.Qt.Key_0), "fullscreen": self.createAction("Toggle Full Screen", self.toggleFullScreen, QtCore.Qt.Key_F11) }, "help": { "help": self.createAction("Help and Feedback", self.current().help, QKeySequence.HelpContents), "center": self.createAction("Slack Help Center", self.current().helpCenter), "about": self.createAction("About", self.current().about) } } menu = self.menuBar() fileMenu = menu.addMenu("&File") fileMenu.addAction(self.menus["file"]["preferences"]) fileMenu.addAction(self.menus["file"]["systray"]) fileMenu.addSeparator() fileMenu.addAction(self.menus["file"]["addTeam"]) fileMenu.addAction(self.menus["file"]["signout"]) fileMenu.addSeparator() fileMenu.addAction(self.menus["file"]["close"]) fileMenu.addAction(self.menus["file"]["exit"]) editMenu = menu.addMenu("&Edit") editMenu.addAction(self.menus["edit"]["undo"]) editMenu.addAction(self.menus["edit"]["redo"]) editMenu.addSeparator() editMenu.addAction(self.menus["edit"]["cut"]) editMenu.addAction(self.menus["edit"]["copy"]) editMenu.addAction(self.menus["edit"]["paste"]) editMenu.addSeparator() editMenu.addAction(self.menus["edit"]["back"]) editMenu.addAction(self.menus["edit"]["forward"]) editMenu.addAction(self.menus["edit"]["reload"]) viewMenu = menu.addMenu("&View") viewMenu.addAction(self.menus["view"]["zoomin"]) viewMenu.addAction(self.menus["view"]["zoomout"]) viewMenu.addAction(self.menus["view"]["reset"]) viewMenu.addSeparator() viewMenu.addAction(self.menus["view"]["fullscreen"]) helpMenu = menu.addMenu("&Help") helpMenu.addAction(self.menus["help"]["help"]) helpMenu.addAction(self.menus["help"]["center"]) helpMenu.addSeparator() helpMenu.addAction(self.menus["help"]["about"]) self.enableMenus(False) showSystray = self.settings.value("Systray") == "True" self.menus["file"]["systray"].setChecked(showSystray) self.menus["file"]["close"].setEnabled(showSystray) def enableMenus(self, enabled): self.menus["file"]["preferences"].setEnabled(enabled == True) self.menus["file"]["addTeam"].setEnabled(enabled == True) self.menus["file"]["signout"].setEnabled(enabled == True) self.menus["help"]["help"].setEnabled(enabled == True) def createAction(self, text, slot, shortcut=None, checkable=False): action = QtGui.QAction(text, self) if shortcut is not None: action.setShortcut(shortcut) action.triggered.connect(slot) if checkable: action.setCheckable(True) return action def domain(self): if self.identifier.endswith(".slack.com"): return self.identifier else: return "https://"+self.identifier+".slack.com" def current(self): return self.stackedWidget.currentWidget() def teams(self, teams): if teams is not None and len(teams) > 1: self.leftPane.show() for t in teams: try: self.leftPane.addTeam(t['id'], t['team_name'], t['team_url'], t['team_icon']['image_88'], t == teams[0]) except: self.leftPane.addTeam(t['id'], t['team_name'], t['team_url'], '', t == teams[0]) def switchTo(self, url): qUrl = QtCore.QUrl(url) index = -1 for i in range(0, self.stackedWidget.count()): if self.stackedWidget.widget(i).url().toString().startswith(url): index = i break if index != -1: self.stackedWidget.setCurrentIndex(index) else: webView = Wrapper(self) webView.page().networkAccessManager().setCookieJar(self.cookiesjar) webView.load(qUrl) webView.show() self.stackedWidget.addWidget(webView) self.stackedWidget.setCurrentWidget(webView) self.quicklist(self.current().listChannels()) self.enableMenus(self.current().isConnected()) # Save the last used team as default self.settings.setValue("Domain", 'https://'+qUrl.host()) def eventFilter(self, obj, event): if event.type() == QtCore.QEvent.ActivationChange and self.isActiveWindow(): self.focusInEvent(event) if event.type() == QtCore.QEvent.KeyPress: # Ctrl + <n> if QtGui.QApplication.keyboardModifiers() == QtCore.Qt.ControlModifier: if event.key() == QtCore.Qt.Key_1: self.leftPane.click(0) elif event.key() == QtCore.Qt.Key_2: self.leftPane.click(1) elif event.key() == QtCore.Qt.Key_3: self.leftPane.click(2) elif event.key() == QtCore.Qt.Key_4: self.leftPane.click(3) elif event.key() == QtCore.Qt.Key_5: self.leftPane.click(4) elif event.key() == QtCore.Qt.Key_6: self.leftPane.click(5) elif event.key() == QtCore.Qt.Key_7: self.leftPane.click(6) elif event.key() == QtCore.Qt.Key_8: self.leftPane.click(7) elif event.key() == QtCore.Qt.Key_9: self.leftPane.click(8) # Ctrl + Shift + <key> if (QtGui.QApplication.keyboardModifiers() & QtCore.Qt.ShiftModifier) and (QtGui.QApplication.keyboardModifiers() & QtCore.Qt.ShiftModifier): if event.key() == QtCore.Qt.Key_V: self.current().createSnippet() return QtGui.QMainWindow.eventFilter(self, obj, event); def focusInEvent(self, event): self.launcher.set_property("urgent", False) self.tray.stopAlert() def titleChanged(self): self.setWindowTitle(self.current().title()) def closeEvent(self, event): if not self.forceClose and self.settings.value("Systray") == "True": self.hide() event.ignore() else: self.cookiesjar.save() self.settings.setValue("geometry", self.saveGeometry()) self.settings.setValue("windowState", self.saveState()) def show(self): self.setWindowState(self.windowState() & ~QtCore.Qt.WindowMinimized | QtCore.Qt.WindowActive) self.activateWindow() self.setVisible(True) def exit(self): self.forceClose = True self.close() def quicklist(self, channels): if Dbusmenu is not None: ql = Dbusmenu.Menuitem.new() self.launcher.set_property("quicklist", ql) if channels is not None: for c in channels: if c['is_member']: item = Dbusmenu.Menuitem.new () item.property_set (Dbusmenu.MENUITEM_PROP_LABEL, "#"+c['name']) item.property_set ("id", c['name']) item.property_set_bool (Dbusmenu.MENUITEM_PROP_VISIBLE, True) item.connect(Dbusmenu.MENUITEM_SIGNAL_ITEM_ACTIVATED, self.current().openChannel) ql.child_append(item) self.launcher.set_property("quicklist", ql) def notify(self, title, message): self.notifier.notify(title, message) self.alert() def alert(self): if not self.isActiveWindow(): self.launcher.set_property("urgent", True) self.tray.alert() def count(self): total = 0 for i in range(0, self.stackedWidget.count()): widget = self.stackedWidget.widget(i) if widget.messages == 0: self.leftPane.stopAlert(widget.team()) else: self.leftPane.alert(widget.team()) total+=widget.messages if total > self.messages: self.alert() if 0 == total: self.launcher.set_property("count_visible", False) self.tray.setCounter(0) else: self.tray.setCounter(total) self.launcher.set_property("count", total) self.launcher.set_property("count_visible", True) self.messages = total
2026-03-31T15:30:28
codeparrot_clean
c7a440bed788e19494e554dc7acdea64
code
from __future__ import unicode_literals from django.template.defaultfilters import escapejs_filter from django.test import SimpleTestCase from ..utils import setup class EscapejsTests(SimpleTestCase): @setup({'escapejs01': '{{ a|escapejs }}'}) def test_escapejs01(self): output = self.engine.render_to_string('escapejs01', {'a': 'testing\r\njavascript \'string" <b>escaping</b>'}) self.assertEqual(output, 'testing\\u000D\\u000Ajavascript ' '\\u0027string\\u0022 \\u003Cb\\u003E' 'escaping\\u003C/b\\u003E') @setup({'escapejs02': '{% autoescape off %}{{ a|escapejs }}{% endautoescape %}'}) def test_escapejs02(self): output = self.engine.render_to_string('escapejs02', {'a': 'testing\r\njavascript \'string" <b>escaping</b>'}) self.assertEqual(output, 'testing\\u000D\\u000Ajavascript ' '\\u0027string\\u0022 \\u003Cb\\u003E' 'escaping\\u003C/b\\u003E') class FunctionTests(SimpleTestCase): def test_quotes(self): self.assertEqual( escapejs_filter('"double quotes" and \'single quotes\''), '\\u0022double quotes\\u0022 and \\u0027single quotes\\u0027', ) def test_backslashes(self): self.assertEqual(escapejs_filter(r'\ : backslashes, too'), '\\u005C : backslashes, too') def test_whitespace(self): self.assertEqual( escapejs_filter('and lots of whitespace: \r\n\t\v\f\b'), 'and lots of whitespace: \\u000D\\u000A\\u0009\\u000B\\u000C\\u0008', ) def test_script(self): self.assertEqual( escapejs_filter(r'<script>and this</script>'), '\\u003Cscript\\u003Eand this\\u003C/script\\u003E', ) def test_paragraph_separator(self): self.assertEqual( escapejs_filter('paragraph separator:\u2029and line separator:\u2028'), 'paragraph separator:\\u2029and line separator:\\u2028', )
2026-03-31T15:30:28
codeparrot_clean
9d28f4e94b896aca65443ba326d99e23
code
# Copyright (c) Twisted Matrix Laboratories. # See LICENSE for details. """ Serial Port Protocol """ # system imports import os, errno # dependent on pyserial ( http://pyserial.sf.net/ ) # only tested w/ 1.18 (5 Dec 2002) import serial from serial import PARITY_NONE, PARITY_EVEN, PARITY_ODD from serial import STOPBITS_ONE, STOPBITS_TWO from serial import FIVEBITS, SIXBITS, SEVENBITS, EIGHTBITS from serialport import BaseSerialPort # twisted imports from twisted.internet import abstract, fdesc, main class SerialPort(BaseSerialPort, abstract.FileDescriptor): """ A select()able serial device, acting as a transport. """ connected = 1 def __init__(self, protocol, deviceNameOrPortNumber, reactor, baudrate = 9600, bytesize = EIGHTBITS, parity = PARITY_NONE, stopbits = STOPBITS_ONE, timeout = 0, xonxoff = 0, rtscts = 0): abstract.FileDescriptor.__init__(self, reactor) self._serial = self._serialFactory( deviceNameOrPortNumber, baudrate=baudrate, bytesize=bytesize, parity=parity, stopbits=stopbits, timeout=timeout, xonxoff=xonxoff, rtscts=rtscts) self.reactor = reactor self.flushInput() self.flushOutput() self.protocol = protocol self.protocol.makeConnection(self) self.startReading() def fileno(self): return self._serial.fd def writeSomeData(self, data): """ Write some data to the serial device. """ return fdesc.writeToFD(self.fileno(), data) def doRead(self): """ Some data's readable from serial device. """ return fdesc.readFromFD(self.fileno(), self.protocol.dataReceived) def connectionLost(self, reason): """ Called when the serial port disconnects. Will call C{connectionLost} on the protocol that is handling the serial data. """ abstract.FileDescriptor.connectionLost(self, reason) self._serial.close() self.protocol.connectionLost(reason)
2026-03-31T15:30:28
codeparrot_clean
7ae0b6b0ad3c1be6e6aee6ea97c3fb95
code
# Copyright (C) 2010 Google Inc. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following disclaimer # in the documentation and/or other materials provided with the # distribution. # * Neither the name of Google Inc. nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import logging from webkitpy.tool.steps.abstractstep import AbstractStep from webkitpy.tool.steps.options import Options _log = logging.getLogger(__name__) class Build(AbstractStep): @classmethod def options(cls): return AbstractStep.options() + [ Options.build, Options.quiet, Options.build_style, ] def build(self, build_style): environment = self._tool.copy_current_environment() environment.disable_gcc_smartquotes() env = environment.to_dictionary() build_webkit_command = self._tool.deprecated_port().build_webkit_command(build_style=build_style) self._tool.executive.run_and_throw_if_fail(build_webkit_command, self._options.quiet, cwd=self._tool.scm().checkout_root, env=env) def run(self, state): if not self._options.build: return _log.info("Building WebKit") if self._options.build_style == "both": self.build("debug") self.build("release") else: self.build(self._options.build_style)
2026-03-31T15:30:28
codeparrot_clean
66c5909c3762c265614b6b9208c4eda5
code
#!/usr/bin/env python # # * Copyright 2012-2014 by Aerospike. # * # * Permission is hereby granted, free of charge, to any person obtaining a copy # * of this software and associated documentation files (the "Software"), to # * deal in the Software without restriction, including without limitation the # * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or # * sell copies of the Software, and to permit persons to whom the Software is # * furnished to do so, subject to the following conditions: # * # * The above copyright notice and this permission notice shall be included in # * all copies or substantial portions of the Software. # * # * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING # * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS # * IN THE SOFTWARE. # from __future__ import print_function import aerospike import sys import time from aerospike import predicates as p class TweetService(object): def __init__(self, client): self.client = client def createTweet(self): print("\n********** Create Tweet **********\n") # /*********************/// # /*****Data Model*****/// # Namespace: test # Set: tweets # Key: <username:<counter>> # Bins: # tweet - string # ts - int (Stores epoch timestamp of the tweet) # username - string # Sample Key: dash:1 # Sample Record: # { tweet: 'Put. A. Bird. On. It.', # ts: 1408574221, # username: 'dash' # } # /*********************/// userRecord = None userKey = None tweetKey = None # Get username username = str() username = raw_input("Enter username: ") if len(username) > 0: # Check if username exists meta = None policy = None userKey = ("test", "users", username) (key, metadata,userRecord) = self.client.get(userKey,policy) record = {} if userRecord: # Set Tweet Count if 'tweetcount' in userRecord: nextTweetCount = int(userRecord['tweetcount']) + 1 else: nextTweetCount = 1 # Get tweet record['tweet'] = raw_input("Enter tweet for " + username + ":") # Write record #wPolicy.recordExistsAction = RecordExistsAction.UPDATE # Create timestamp to store along with the tweet so we can # query, index and report on it ts= self.getTimeStamp() tweetKey = ("test", "tweets", username + ":" + str(nextTweetCount)) record["ts"] = ts record["username"]= username self.client.put(tweetKey,record, meta, policy) print("\nINFO: Tweet record created!\n",record,tweetKey) # Update tweet count and last tweet'd timestamp in the user # record self.updateUser(self.client, userKey, policy, ts, nextTweetCount) else: print("ERROR: User record not found!\n") def scanAllTweetsForAllUsers(self): try: # Python Scan tweetScan = self.client.scan("test", "tweets") tweetScan.select('tweet') # callback for each record read def tweetCallback((key, meta, record)): print(record) # invoke the operations, and for each record invoke the callback tweetScan.foreach(tweetCallback) except Exception as e : print("error: {0}".format(e), file=sys.stderr) def updateUser(self, client, userKey, policy, ts, tweetCount): userTweet = {} userTweet["tweetcount"] = tweetCount userTweet["lasttweeted"] = ts meta = None self.client.put(userKey,userTweet, meta, policy) print("\nINFO: The tweet count now is: " , tweetCount) def updateUserUsingOperate(self, client, userKey, policy, ts): record = self.client.operate(policy, userKey, Operation.add(Bin("tweetcount", 1)), Operation.put(Bin("lasttweeted", ts)), Operation.get()) print("\nINFO: The tweet count now is: " + record.getValue("tweetcount")) def queryTweetsByUsername(self): print("\n********** Query Tweets By Username **********\n") # Get username username = str() username = raw_input("Enter username: ") if len(username) > 0: try: self.client.index_string_create(None, "test", "tweets", "username", "username_index") time.sleep(5) print("\nINFO: String Secondary Index Created ") tweetQuery = self.client.query("test", "tweets") #tweetQuery.select('username') # callback for each record read def tweetQueryCallback((key, meta, record)): print(record["tweet"]) # invoke the operations, and for each record invoke the callback tweetQuery.where(p.equals('username',username)) tweetQuery.foreach(tweetQueryCallback) except Exception as e : print("error: {0}".format(e), file=sys.stderr) def queryUsersByTweetCount(self): print("\n********** Query Users By Tweet Count Range **********\n") # Get username try: self.client.index_integer_create(None, "test", "users", "tweetcount", "tweetcount_index") time.sleep(5) print("\nINFO: Integer Secondary Index Created ") min = int(raw_input("Enter Min Tweet Count: ")) max = int(raw_input("Enter Max Tweet Count: ")) print("\nList of users with " , min , "-" , max , " tweets:\n") tweetQuery = self.client.query("test", "users") #tweetQuery.select('username') # callback for each record read def tweetQueryCountCallback((key, meta, record)): print(record["username"] , " has " , record["tweetcount"] , " tweets\n") # invoke the operations, and for each record invoke the callback tweetQuery.where(p.between('tweetcount',min,max)) tweetQuery.foreach(tweetQueryCountCallback) except Exception as e : print("error: {0}".format(e), file=sys.stderr) def getTimeStamp(self): """ generated source for method getTimeStamp """ return int(round(time.time() * 1000)) def createTweets(self): randomTweets = ["For just $1 you get a half price download of half of the song and listen to it just once.", "People tell me my body looks like a melted candle", "Come on movie! Make it start!", "Byaaaayy", "Please, please, win! Meow, meow, meow!", "Put. A. Bird. On. It.", "A weekend wasted is a weekend well spent", "Would you like to super spike your meal?", "We have a mean no-no-bring-bag up here on aisle two.", "SEEK: See, Every, EVERY, Kind... of spot", "We can order that for you. It will take a year to get there.", "If you are pregnant, have a soda.", "Hear that snap? Hear that clap?", "Follow me and I may follow you", "Which is the best cafe in Portland? Discuss...", "Portland Coffee is for closers!", "Lets get this party started!", "How about them portland blazers!", "You got school'd, yo", "I love animals", "I love my dog", "What's up Portland", "Which is the best cafe in Portland? Discuss...", "I dont always tweet, but when I do it is on Tweetaspike"] totalUsers = 10000 maxTweets = 20 username = str() ts = 0 wr_policy = { AS_POLICY_W_EXISTS: AS_POLICY_EXISTS_IGNORE } print("\nCreate up to " , maxTweets , " tweets each for " , totalUsers , " users. Press any key to continue...\n") raw_input("..") j = 0 while j < totalUsers: username = "user" + str(random.randint(1,totalUsers)) userKey = ("test", "users", username) meta = None policy = None ts = None k = 0 (key, metadata,userRecord) = self.client.get(userKey,policy) if userRecord: totalTweets = random.randint(1,maxTweets) while k <= totalTweets: record = {} ts = self.getTimeStamp() tweetKey = ("test", "tweets", username + ":" + str(k)) record["tweet"] = random.choice(randomTweets) record["ts"] = ts record["username"]= username self.client.put(tweetKey,record, meta, wr_policy) k += 1 # Create timestamp to store along with the tweet so we can # query, index and report on it print("\nWrote " , totalTweets , " tweets for " , username , "!") if totalTweets > 0: # Update tweet count and last tweet'd timestamp in the user # record self.updateUser(self.client, userKey, wr_policy, ts, totalTweets) j += 1 # Check if user record exists # create up to maxTweets random tweets for this user # Create timestamp to store along with the tweet so we can # query, index and report on it # Update tweet count and last tweet'd timestamp in the user # record print("\n\nDone creating up to " , maxTweets , " tweets each for " , totalUsers , " users!\n")
2026-03-31T15:30:28
codeparrot_clean
a708c0783d8d4780a471b876dccf8a08
code
# This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. import json import urllib from base64 import urlsafe_b64decode from django.conf import settings from django.utils.translation import get_language import commonware.log import tower from lib import l10n_utils log = commonware.log.getLogger('facebookapps.utils') def unwrap_signed_request(request): """ Decodes and returns Facebook's `signed_request` data. See https://developers.facebook.com/docs/howtos/login/signed-request/ """ try: encoded_signed_request = request.REQUEST['signed_request'] except KeyError: return {} encoded_string_data = encoded_signed_request.partition('.')[2] # Pad with `=` to make string length a multiple of 4 # and thus prevent a base64 error padding = ''.ljust(4 - len(encoded_string_data) % 4, '=') padded_string = ''.join([encoded_string_data, padding]) # Convert to byte data for base64 encoded_byte_data = bytes(padded_string) signed_request = json.loads(urlsafe_b64decode(encoded_byte_data)) # Change Facebook locale's underscore to hyphen # ex. `en_US` to `en-US` try: locale = signed_request['user']['locale'] except KeyError: locale = None if locale: signed_request['user']['locale'] = locale.replace('_', '-') return signed_request def app_data_query_string_encode(app_data): return urllib.urlencode([('app_data[{key}]'.format(key=key), value) for key, value in app_data.items()]) def get_best_locale(locale): """ Returns the most appropriate locale from the list of supported locales. This can either be the locale itself (if it's supported), the main locale for that language if any or failing any of that the default `en-US`. Adapted from `activate_locale` in Affiliates (http://bit.ly/17if6nh). """ # Compare using lowercase locales since they become lowercase once # activated. supported_locales = [loc.lower() for loc in settings.FACEBOOK_LOCALES] # HACK: It's not totally clear to me where Django or tower do the matching # that equates locales like es-LA to es, and I'm scared enough of getting # it wrong to want to avoid it for the first release. So instead, we'll # activate the requested locale, and then check what locale got chosen by # django as the usable locale, and match that against our locale # whitelist. # TODO: Properly filter out locales prior to calling activate. old_locale = get_language() tower.activate(locale) lang = get_language() if lang.lower() not in supported_locales: # Try to activate just the language and use the resulting locale lang_prefix = lang.split('-')[0] tower.activate(lang_prefix) lang = get_language() if lang.lower() not in supported_locales: # Finally, try to find a locale with that language in the supported # locales. Otherwise, use default en-US. try: lang = next(locale for locale in settings.FACEBOOK_LOCALES if locale.startswith(lang_prefix)) except StopIteration: lang = 'en-US' tower.activate(old_locale) return lang def js_redirect(redirect_url, request): return l10n_utils.render(request, 'facebookapps/js-redirect.html', {'redirect_url': redirect_url})
2026-03-31T15:30:28
codeparrot_clean
8e5d08c1f79fc8ec8695b6c140b56b65
code
# Pi-Swarm Simulator is a simple graphical simulation environment for the Pi-Swarm robots # Copyright (C) 2014 Becky Naylor, Jon Timmis, University of York # 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/>. #All arena element classes are in this file #import external libraries import os, random, sys, math, itertools, operator, datetime, re, cProfile from framework import * #import simulator classes from robot import * from proxSensor import * #Room perimeter polygon, currently there should be just one of these class Room(): def __init__(self, world, xsize, ysize): self.xsize = xsize self.ysize = ysize #TODO: make centre relative to the screen, not hardcoded #Centre the room in the screen self.centrePoint = (0,ysize/2) self.walls = world.CreateBody(position=self.centrePoint, userData=self) #List of corner positions to create edges self.corners = [ (-xsize/2,-ysize/2), (-xsize/2,ysize/2), (xsize/2,ysize/2), (xsize/2,-ysize/2), (-xsize/2,-ysize/2) ] #Make vertices self.walls.CreateEdgeChain(self.corners) #Arena obstacles, provide the world to add them to. Can also provide a list of protected areas (of type b2body) class Obstacle: def __init__(self, world, obstacleid, room, protectedAreaList=0): self.obstacleid = obstacleid self.shape = "" #Pick random size obs_size = random.uniform(0.5,1.5) #Dice roll to decide object shape diceroll = random.randint(0,2) roomx = room.xsize roomy = room.ysize #square if diceroll == 0: self.shape = "square" obs_y_size = obs_size obstacle=b2PolygonShape(box=(obs_size, obs_size)) self.size = obs_size #rectangle elif diceroll == 1: self.shape = "rectangle" #generate y side too for rectangle obs_y_size = random.uniform(0.5,1.5) obstacle=b2PolygonShape(box=(obs_size, obs_y_size)) self.size = (obs_size, obs_y_size) #circle elif diceroll == 2: self.shape = "circle" obs_size = obs_size*2 obs_y_size = obs_size obstacle=b2CircleShape(radius=(obs_size)) self.size = obs_size positionAccepted = False while positionAccepted == False: #Pick random co-ordinates (xpos, ypos) = (random.uniform(-(float(roomx)/2)+obs_size,(float(roomx)/2)-obs_size), random.uniform(0+obs_y_size,roomy-obs_y_size)) self.fixtures = b2FixtureDef(shape=obstacle, density=1, friction=0.3) self.body = world.CreateStaticBody(position=(xpos,ypos), fixtures=self.fixtures, userData=self) #Check there are no protected areas e.g. powersockets at this point if protectedAreaList != 0: positionAccepted = True for protArea in protectedAreaList: overlapping = b2TestOverlap(self.fixtures.shape, 0, protArea.fixtures.shape, 0, self.body.transform, protArea.body.transform); #If the shape overlaps a protected area then we need to generate new coordinates if overlapping == True: positionAccepted = False #Destroy old shape before creating a new one if positionAccepted == False: world.DestroyBody(self.body) #Floor area where the robots recharge, specified size (x,y) and position (x,y) class PowerStrip: def __init__(self, world, powerid, room, position="none", size="none"): roomx = room.xsize roomy = room.ysize if size == "none": size = (1.5,1.5) if position == "none": #position = ((roomx/2)-size[0],roomy-size[1]) position = (-(roomx/2)+size[0],roomy-size[1]) #with size (3,2) and room (40,40) xpos = -17 and ypos = 2 is bottom left #with size (3,2) and room (40,40) xpos = -17 and ypos = 38 is top left #with size (3,2) and room (40,40) xpos = 17 and ypos = 38 is top right self.powerid = powerid self.size = size powerstrip=b2PolygonShape(box=self.size) self.fixtures = b2FixtureDef(shape=powerstrip, density=0, friction=0, isSensor=True, userData=self) self.body = world.CreateStaticBody(position=position, fixtures=self.fixtures) #Floor tile of specified size (x,y) and position (x,y) class FloorTile: def __init__(self, world, position, size): self.contacted = False #pygame seems to double the expected size, so (4.0,4.0) has 4.0 above centre point and 4.0 below - so halve it. size = (size[0]/2,size[1]/2) floortile=b2PolygonShape(box=size) self.fixtures = b2FixtureDef(shape=floortile, density=0, friction=0, isSensor=True, userData=self) self.body = world.CreateStaticBody(position=position, fixtures=self.fixtures)
2026-03-31T15:30:28
codeparrot_clean
34d15672ed23591cd462f920e8d63805
code
#!/usr/bin/python # -*- coding: utf-8 -*- # (c) 2013, Daniel Jaouen <dcj24@cornell.edu> # Based on homebrew (Andrew Dunham <andrew@du.nham.ca>) # # 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/>. import re DOCUMENTATION = ''' --- module: homebrew_tap author: Daniel Jaouen short_description: Tap a Homebrew repository. description: - Tap external Homebrew repositories. version_added: "1.6" options: tap: description: - The repository to tap. required: true state: description: - state of the repository. choices: [ 'present', 'absent' ] required: false default: 'present' requirements: [ homebrew ] ''' EXAMPLES = ''' homebrew_tap: tap=homebrew/dupes state=present homebrew_tap: tap=homebrew/dupes state=absent homebrew_tap: tap=homebrew/dupes,homebrew/science state=present ''' def a_valid_tap(tap): '''Returns True if the tap is valid.''' regex = re.compile(r'^([\w-]+)/(homebrew-)?([\w-]+)$') return regex.match(tap) def already_tapped(module, brew_path, tap): '''Returns True if already tapped.''' rc, out, err = module.run_command([ brew_path, 'tap', ]) taps = [tap_.strip().lower() for tap_ in out.split('\n') if tap_] return tap.lower() in taps def add_tap(module, brew_path, tap): '''Adds a single tap.''' failed, changed, msg = False, False, '' if not a_valid_tap(tap): failed = True msg = 'not a valid tap: %s' % tap elif not already_tapped(module, brew_path, tap): if module.check_mode: module.exit_json(changed=True) rc, out, err = module.run_command([ brew_path, 'tap', tap, ]) if already_tapped(module, brew_path, tap): changed = True msg = 'successfully tapped: %s' % tap else: failed = True msg = 'failed to tap: %s' % tap else: msg = 'already tapped: %s' % tap return (failed, changed, msg) def add_taps(module, brew_path, taps): '''Adds one or more taps.''' failed, unchanged, added, msg = False, 0, 0, '' for tap in taps: (failed, changed, msg) = add_tap(module, brew_path, tap) if failed: break if changed: added += 1 else: unchanged += 1 if failed: msg = 'added: %d, unchanged: %d, error: ' + msg msg = msg % (added, unchanged) elif added: changed = True msg = 'added: %d, unchanged: %d' % (added, unchanged) else: msg = 'added: %d, unchanged: %d' % (added, unchanged) return (failed, changed, msg) def remove_tap(module, brew_path, tap): '''Removes a single tap.''' failed, changed, msg = False, False, '' if not a_valid_tap(tap): failed = True msg = 'not a valid tap: %s' % tap elif already_tapped(module, brew_path, tap): if module.check_mode: module.exit_json(changed=True) rc, out, err = module.run_command([ brew_path, 'untap', tap, ]) if not already_tapped(module, brew_path, tap): changed = True msg = 'successfully untapped: %s' % tap else: failed = True msg = 'failed to untap: %s' % tap else: msg = 'already untapped: %s' % tap return (failed, changed, msg) def remove_taps(module, brew_path, taps): '''Removes one or more taps.''' failed, unchanged, removed, msg = False, 0, 0, '' for tap in taps: (failed, changed, msg) = remove_tap(module, brew_path, tap) if failed: break if changed: removed += 1 else: unchanged += 1 if failed: msg = 'removed: %d, unchanged: %d, error: ' + msg msg = msg % (removed, unchanged) elif removed: changed = True msg = 'removed: %d, unchanged: %d' % (removed, unchanged) else: msg = 'removed: %d, unchanged: %d' % (removed, unchanged) return (failed, changed, msg) def main(): module = AnsibleModule( argument_spec=dict( name=dict(aliases=['tap'], required=True), state=dict(default='present', choices=['present', 'absent']), ), supports_check_mode=True, ) brew_path = module.get_bin_path( 'brew', required=True, opt_dirs=['/usr/local/bin', '~/.linuxbrew/bin'] ) taps = module.params['name'].split(',') if module.params['state'] == 'present': failed, changed, msg = add_taps(module, brew_path, taps) if failed: module.fail_json(msg=msg) else: module.exit_json(changed=changed, msg=msg) elif module.params['state'] == 'absent': failed, changed, msg = remove_taps(module, brew_path, taps) if failed: module.fail_json(msg=msg) else: module.exit_json(changed=changed, msg=msg) # this is magic, see lib/ansible/module_common.py #<<INCLUDE_ANSIBLE_MODULE_COMMON>> main()
2026-03-31T15:30:28
codeparrot_clean
1b07e41ddf826141ed1912543ededbd3
code
"""Implementation of JSONEncoder """ import re from decimal import Decimal def _import_speedups(): try: import _speedups return _speedups.encode_basestring_ascii, _speedups.make_encoder except ImportError: return None, None c_encode_basestring_ascii, c_make_encoder = _import_speedups() from decoder import PosInf ESCAPE = re.compile(ur'[\x00-\x1f\\"\b\f\n\r\t\u2028\u2029]') ESCAPE_ASCII = re.compile(r'([\\"]|[^\ -~])') HAS_UTF8 = re.compile(r'[\x80-\xff]') ESCAPE_DCT = { '\\': '\\\\', '"': '\\"', '\b': '\\b', '\f': '\\f', '\n': '\\n', '\r': '\\r', '\t': '\\t', u'\u2028': '\\u2028', u'\u2029': '\\u2029', } for i in range(0x20): #ESCAPE_DCT.setdefault(chr(i), '\\u{0:04x}'.format(i)) ESCAPE_DCT.setdefault(chr(i), '\\u%04x' % (i,)) FLOAT_REPR = repr def encode_basestring(s): """Return a JSON representation of a Python string """ if isinstance(s, str) and HAS_UTF8.search(s) is not None: s = s.decode('utf-8') def replace(match): return ESCAPE_DCT[match.group(0)] return u'"' + ESCAPE.sub(replace, s) + u'"' def py_encode_basestring_ascii(s): """Return an ASCII-only JSON representation of a Python string """ if isinstance(s, str) and HAS_UTF8.search(s) is not None: s = s.decode('utf-8') def replace(match): s = match.group(0) try: return ESCAPE_DCT[s] except KeyError: n = ord(s) if n < 0x10000: #return '\\u{0:04x}'.format(n) return '\\u%04x' % (n,) else: # surrogate pair n -= 0x10000 s1 = 0xd800 | ((n >> 10) & 0x3ff) s2 = 0xdc00 | (n & 0x3ff) #return '\\u{0:04x}\\u{1:04x}'.format(s1, s2) return '\\u%04x\\u%04x' % (s1, s2) return '"' + str(ESCAPE_ASCII.sub(replace, s)) + '"' encode_basestring_ascii = ( c_encode_basestring_ascii or py_encode_basestring_ascii) class JSONEncoder(object): """Extensible JSON <http://json.org> encoder for Python data structures. Supports the following objects and types by default: +-------------------+---------------+ | Python | JSON | +===================+===============+ | dict, namedtuple | object | +-------------------+---------------+ | list, tuple | array | +-------------------+---------------+ | str, unicode | string | +-------------------+---------------+ | int, long, float | number | +-------------------+---------------+ | True | true | +-------------------+---------------+ | False | false | +-------------------+---------------+ | None | null | +-------------------+---------------+ To extend this to recognize other objects, subclass and implement a ``.default()`` method with another method that returns a serializable object for ``o`` if possible, otherwise it should call the superclass implementation (to raise ``TypeError``). """ item_separator = ', ' key_separator = ': ' def __init__(self, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, sort_keys=False, indent=None, separators=None, encoding='utf-8', default=None, use_decimal=True, namedtuple_as_object=True, tuple_as_array=True, bigint_as_string=False, item_sort_key=None): """Constructor for JSONEncoder, with sensible defaults. If skipkeys is false, then it is a TypeError to attempt encoding of keys that are not str, int, long, float or None. If skipkeys is True, such items are simply skipped. If ensure_ascii is true, the output is guaranteed to be str objects with all incoming unicode characters escaped. If ensure_ascii is false, the output will be unicode object. If check_circular is true, then lists, dicts, and custom encoded objects will be checked for circular references during encoding to prevent an infinite recursion (which would cause an OverflowError). Otherwise, no such check takes place. If allow_nan is true, then NaN, Infinity, and -Infinity will be encoded as such. This behavior is not JSON specification compliant, but is consistent with most JavaScript based encoders and decoders. Otherwise, it will be a ValueError to encode such floats. If sort_keys is true, then the output of dictionaries will be sorted by key; this is useful for regression tests to ensure that JSON serializations can be compared on a day-to-day basis. If indent is a string, then JSON array elements and object members will be pretty-printed with a newline followed by that string repeated for each level of nesting. ``None`` (the default) selects the most compact representation without any newlines. For backwards compatibility with versions of simplejson earlier than 2.1.0, an integer is also accepted and is converted to a string with that many spaces. If specified, separators should be a (item_separator, key_separator) tuple. The default is (', ', ': '). To get the most compact JSON representation you should specify (',', ':') to eliminate whitespace. If specified, default is a function that gets called for objects that can't otherwise be serialized. It should return a JSON encodable version of the object or raise a ``TypeError``. If encoding is not None, then all input strings will be transformed into unicode using that encoding prior to JSON-encoding. The default is UTF-8. If use_decimal is true (not the default), ``decimal.Decimal`` will be supported directly by the encoder. For the inverse, decode JSON with ``parse_float=decimal.Decimal``. If namedtuple_as_object is true (the default), objects with ``_asdict()`` methods will be encoded as JSON objects. If tuple_as_array is true (the default), tuple (and subclasses) will be encoded as JSON arrays. If bigint_as_string is true (not the default), ints 2**53 and higher or lower than -2**53 will be encoded as strings. This is to avoid the rounding that happens in Javascript otherwise. If specified, item_sort_key is a callable used to sort the items in each dictionary. This is useful if you want to sort items other than in alphabetical order by key. """ self.skipkeys = skipkeys self.ensure_ascii = ensure_ascii self.check_circular = check_circular self.allow_nan = allow_nan self.sort_keys = sort_keys self.use_decimal = use_decimal self.namedtuple_as_object = namedtuple_as_object self.tuple_as_array = tuple_as_array self.bigint_as_string = bigint_as_string self.item_sort_key = item_sort_key if indent is not None and not isinstance(indent, basestring): indent = indent * ' ' self.indent = indent if separators is not None: self.item_separator, self.key_separator = separators elif indent is not None: self.item_separator = ',' if default is not None: self.default = default self.encoding = encoding def default(self, o): """Implement this method in a subclass such that it returns a serializable object for ``o``, or calls the base implementation (to raise a ``TypeError``). For example, to support arbitrary iterators, you could implement default like this:: def default(self, o): try: iterable = iter(o) except TypeError: pass else: return list(iterable) return JSONEncoder.default(self, o) """ raise TypeError(repr(o) + " is not JSON serializable") def encode(self, o): """Return a JSON string representation of a Python data structure. >>> from simplejson import JSONEncoder >>> JSONEncoder().encode({"foo": ["bar", "baz"]}) '{"foo": ["bar", "baz"]}' """ # This is for extremely simple cases and benchmarks. if isinstance(o, basestring): if isinstance(o, str): _encoding = self.encoding if (_encoding is not None and not (_encoding == 'utf-8')): o = o.decode(_encoding) if self.ensure_ascii: return encode_basestring_ascii(o) else: return encode_basestring(o) # This doesn't pass the iterator directly to ''.join() because the # exceptions aren't as detailed. The list call should be roughly # equivalent to the PySequence_Fast that ''.join() would do. chunks = self.iterencode(o, _one_shot=True) if not isinstance(chunks, (list, tuple)): chunks = list(chunks) if self.ensure_ascii: return ''.join(chunks) else: return u''.join(chunks) def iterencode(self, o, _one_shot=False): """Encode the given object and yield each string representation as available. For example:: for chunk in JSONEncoder().iterencode(bigobject): mysocket.write(chunk) """ if self.check_circular: markers = {} else: markers = None if self.ensure_ascii: _encoder = encode_basestring_ascii else: _encoder = encode_basestring if self.encoding != 'utf-8': def _encoder(o, _orig_encoder=_encoder, _encoding=self.encoding): if isinstance(o, str): o = o.decode(_encoding) return _orig_encoder(o) def floatstr(o, allow_nan=self.allow_nan, _repr=FLOAT_REPR, _inf=PosInf, _neginf=-PosInf): # Check for specials. Note that this type of test is processor # and/or platform-specific, so do tests which don't depend on # the internals. if o != o: text = 'NaN' elif o == _inf: text = 'Infinity' elif o == _neginf: text = '-Infinity' else: return _repr(o) if not allow_nan: raise ValueError( "Out of range float values are not JSON compliant: " + repr(o)) return text key_memo = {} if (_one_shot and c_make_encoder is not None and self.indent is None): _iterencode = c_make_encoder( markers, self.default, _encoder, self.indent, self.key_separator, self.item_separator, self.sort_keys, self.skipkeys, self.allow_nan, key_memo, self.use_decimal, self.namedtuple_as_object, self.tuple_as_array, self.bigint_as_string, self.item_sort_key, Decimal) else: _iterencode = _make_iterencode( markers, self.default, _encoder, self.indent, floatstr, self.key_separator, self.item_separator, self.sort_keys, self.skipkeys, _one_shot, self.use_decimal, self.namedtuple_as_object, self.tuple_as_array, self.bigint_as_string, self.item_sort_key, Decimal=Decimal) try: return _iterencode(o, 0) finally: key_memo.clear() class JSONEncoderForHTML(JSONEncoder): """An encoder that produces JSON safe to embed in HTML. To embed JSON content in, say, a script tag on a web page, the characters &, < and > should be escaped. They cannot be escaped with the usual entities (e.g. &amp;) because they are not expanded within <script> tags. """ def encode(self, o): # Override JSONEncoder.encode because it has hacks for # performance that make things more complicated. chunks = self.iterencode(o, True) if self.ensure_ascii: return ''.join(chunks) else: return u''.join(chunks) def iterencode(self, o, _one_shot=False): chunks = super(JSONEncoderForHTML, self).iterencode(o, _one_shot) for chunk in chunks: chunk = chunk.replace('&', '\\u0026') chunk = chunk.replace('<', '\\u003c') chunk = chunk.replace('>', '\\u003e') yield chunk def _make_iterencode(markers, _default, _encoder, _indent, _floatstr, _key_separator, _item_separator, _sort_keys, _skipkeys, _one_shot, _use_decimal, _namedtuple_as_object, _tuple_as_array, _bigint_as_string, _item_sort_key, ## HACK: hand-optimized bytecode; turn globals into locals False=False, True=True, ValueError=ValueError, basestring=basestring, Decimal=Decimal, dict=dict, float=float, id=id, int=int, isinstance=isinstance, list=list, long=long, str=str, tuple=tuple, ): if _item_sort_key and not callable(_item_sort_key): raise TypeError("item_sort_key must be None or callable") def _iterencode_list(lst, _current_indent_level): if not lst: yield '[]' return if markers is not None: markerid = id(lst) if markerid in markers: raise ValueError("Circular reference detected") markers[markerid] = lst buf = '[' if _indent is not None: _current_indent_level += 1 newline_indent = '\n' + (_indent * _current_indent_level) separator = _item_separator + newline_indent buf += newline_indent else: newline_indent = None separator = _item_separator first = True for value in lst: if first: first = False else: buf = separator if isinstance(value, basestring): yield buf + _encoder(value) elif value is None: yield buf + 'null' elif value is True: yield buf + 'true' elif value is False: yield buf + 'false' elif isinstance(value, (int, long)): yield ((buf + str(value)) if (not _bigint_as_string or (-1 << 53) < value < (1 << 53)) else (buf + '"' + str(value) + '"')) elif isinstance(value, float): yield buf + _floatstr(value) elif _use_decimal and isinstance(value, Decimal): yield buf + str(value) else: yield buf if isinstance(value, list): chunks = _iterencode_list(value, _current_indent_level) else: _asdict = _namedtuple_as_object and getattr(value, '_asdict', None) if _asdict and callable(_asdict): chunks = _iterencode_dict(_asdict(), _current_indent_level) elif _tuple_as_array and isinstance(value, tuple): chunks = _iterencode_list(value, _current_indent_level) elif isinstance(value, dict): chunks = _iterencode_dict(value, _current_indent_level) else: chunks = _iterencode(value, _current_indent_level) for chunk in chunks: yield chunk if newline_indent is not None: _current_indent_level -= 1 yield '\n' + (_indent * _current_indent_level) yield ']' if markers is not None: del markers[markerid] def _iterencode_dict(dct, _current_indent_level): if not dct: yield '{}' return if markers is not None: markerid = id(dct) if markerid in markers: raise ValueError("Circular reference detected") markers[markerid] = dct yield '{' if _indent is not None: _current_indent_level += 1 newline_indent = '\n' + (_indent * _current_indent_level) item_separator = _item_separator + newline_indent yield newline_indent else: newline_indent = None item_separator = _item_separator first = True if _item_sort_key: items = dct.items() items.sort(key=_item_sort_key) elif _sort_keys: items = dct.items() items.sort(key=lambda kv: kv[0]) else: items = dct.iteritems() for key, value in items: if isinstance(key, basestring): pass # JavaScript is weakly typed for these, so it makes sense to # also allow them. Many encoders seem to do something like this. elif isinstance(key, float): key = _floatstr(key) elif key is True: key = 'true' elif key is False: key = 'false' elif key is None: key = 'null' elif isinstance(key, (int, long)): key = str(key) elif _skipkeys: continue else: raise TypeError("key " + repr(key) + " is not a string") if first: first = False else: yield item_separator yield _encoder(key) yield _key_separator if isinstance(value, basestring): yield _encoder(value) elif value is None: yield 'null' elif value is True: yield 'true' elif value is False: yield 'false' elif isinstance(value, (int, long)): yield (str(value) if (not _bigint_as_string or (-1 << 53) < value < (1 << 53)) else ('"' + str(value) + '"')) elif isinstance(value, float): yield _floatstr(value) elif _use_decimal and isinstance(value, Decimal): yield str(value) else: if isinstance(value, list): chunks = _iterencode_list(value, _current_indent_level) else: _asdict = _namedtuple_as_object and getattr(value, '_asdict', None) if _asdict and callable(_asdict): chunks = _iterencode_dict(_asdict(), _current_indent_level) elif _tuple_as_array and isinstance(value, tuple): chunks = _iterencode_list(value, _current_indent_level) elif isinstance(value, dict): chunks = _iterencode_dict(value, _current_indent_level) else: chunks = _iterencode(value, _current_indent_level) for chunk in chunks: yield chunk if newline_indent is not None: _current_indent_level -= 1 yield '\n' + (_indent * _current_indent_level) yield '}' if markers is not None: del markers[markerid] def _iterencode(o, _current_indent_level): if isinstance(o, basestring): yield _encoder(o) elif o is None: yield 'null' elif o is True: yield 'true' elif o is False: yield 'false' elif isinstance(o, (int, long)): yield (str(o) if (not _bigint_as_string or (-1 << 53) < o < (1 << 53)) else ('"' + str(o) + '"')) elif isinstance(o, float): yield _floatstr(o) elif isinstance(o, list): for chunk in _iterencode_list(o, _current_indent_level): yield chunk else: _asdict = _namedtuple_as_object and getattr(o, '_asdict', None) if _asdict and callable(_asdict): for chunk in _iterencode_dict(_asdict(), _current_indent_level): yield chunk elif (_tuple_as_array and isinstance(o, tuple)): for chunk in _iterencode_list(o, _current_indent_level): yield chunk elif isinstance(o, dict): for chunk in _iterencode_dict(o, _current_indent_level): yield chunk elif _use_decimal and isinstance(o, Decimal): yield str(o) else: if markers is not None: markerid = id(o) if markerid in markers: raise ValueError("Circular reference detected") markers[markerid] = o o = _default(o) for chunk in _iterencode(o, _current_indent_level): yield chunk if markers is not None: del markers[markerid] return _iterencode
2026-03-31T15:30:28
codeparrot_clean
5aef0c8dc6c4fa9769aa64b82e2ff2f0
code
""" Python Character Mapping Codec generated from 'VENDORS/MICSFT/PC/CP852.TXT' with gencodec.py. """#" import codecs ### Codec APIs class Codec(codecs.Codec): def encode(self,input,errors='strict'): return codecs.charmap_encode(input,errors,encoding_map) def decode(self,input,errors='strict'): return codecs.charmap_decode(input,errors,decoding_table) class IncrementalEncoder(codecs.IncrementalEncoder): def encode(self, input, final=False): return codecs.charmap_encode(input,self.errors,encoding_map)[0] class IncrementalDecoder(codecs.IncrementalDecoder): def decode(self, input, final=False): return codecs.charmap_decode(input,self.errors,decoding_table)[0] class StreamWriter(Codec,codecs.StreamWriter): pass class StreamReader(Codec,codecs.StreamReader): pass ### encodings module API def getregentry(): return codecs.CodecInfo( name='cp852', encode=Codec().encode, decode=Codec().decode, incrementalencoder=IncrementalEncoder, incrementaldecoder=IncrementalDecoder, streamreader=StreamReader, streamwriter=StreamWriter, ) ### Decoding Map decoding_map = codecs.make_identity_dict(range(256)) decoding_map.update({ 0x0080: 0x00c7, # LATIN CAPITAL LETTER C WITH CEDILLA 0x0081: 0x00fc, # LATIN SMALL LETTER U WITH DIAERESIS 0x0082: 0x00e9, # LATIN SMALL LETTER E WITH ACUTE 0x0083: 0x00e2, # LATIN SMALL LETTER A WITH CIRCUMFLEX 0x0084: 0x00e4, # LATIN SMALL LETTER A WITH DIAERESIS 0x0085: 0x016f, # LATIN SMALL LETTER U WITH RING ABOVE 0x0086: 0x0107, # LATIN SMALL LETTER C WITH ACUTE 0x0087: 0x00e7, # LATIN SMALL LETTER C WITH CEDILLA 0x0088: 0x0142, # LATIN SMALL LETTER L WITH STROKE 0x0089: 0x00eb, # LATIN SMALL LETTER E WITH DIAERESIS 0x008a: 0x0150, # LATIN CAPITAL LETTER O WITH DOUBLE ACUTE 0x008b: 0x0151, # LATIN SMALL LETTER O WITH DOUBLE ACUTE 0x008c: 0x00ee, # LATIN SMALL LETTER I WITH CIRCUMFLEX 0x008d: 0x0179, # LATIN CAPITAL LETTER Z WITH ACUTE 0x008e: 0x00c4, # LATIN CAPITAL LETTER A WITH DIAERESIS 0x008f: 0x0106, # LATIN CAPITAL LETTER C WITH ACUTE 0x0090: 0x00c9, # LATIN CAPITAL LETTER E WITH ACUTE 0x0091: 0x0139, # LATIN CAPITAL LETTER L WITH ACUTE 0x0092: 0x013a, # LATIN SMALL LETTER L WITH ACUTE 0x0093: 0x00f4, # LATIN SMALL LETTER O WITH CIRCUMFLEX 0x0094: 0x00f6, # LATIN SMALL LETTER O WITH DIAERESIS 0x0095: 0x013d, # LATIN CAPITAL LETTER L WITH CARON 0x0096: 0x013e, # LATIN SMALL LETTER L WITH CARON 0x0097: 0x015a, # LATIN CAPITAL LETTER S WITH ACUTE 0x0098: 0x015b, # LATIN SMALL LETTER S WITH ACUTE 0x0099: 0x00d6, # LATIN CAPITAL LETTER O WITH DIAERESIS 0x009a: 0x00dc, # LATIN CAPITAL LETTER U WITH DIAERESIS 0x009b: 0x0164, # LATIN CAPITAL LETTER T WITH CARON 0x009c: 0x0165, # LATIN SMALL LETTER T WITH CARON 0x009d: 0x0141, # LATIN CAPITAL LETTER L WITH STROKE 0x009e: 0x00d7, # MULTIPLICATION SIGN 0x009f: 0x010d, # LATIN SMALL LETTER C WITH CARON 0x00a0: 0x00e1, # LATIN SMALL LETTER A WITH ACUTE 0x00a1: 0x00ed, # LATIN SMALL LETTER I WITH ACUTE 0x00a2: 0x00f3, # LATIN SMALL LETTER O WITH ACUTE 0x00a3: 0x00fa, # LATIN SMALL LETTER U WITH ACUTE 0x00a4: 0x0104, # LATIN CAPITAL LETTER A WITH OGONEK 0x00a5: 0x0105, # LATIN SMALL LETTER A WITH OGONEK 0x00a6: 0x017d, # LATIN CAPITAL LETTER Z WITH CARON 0x00a7: 0x017e, # LATIN SMALL LETTER Z WITH CARON 0x00a8: 0x0118, # LATIN CAPITAL LETTER E WITH OGONEK 0x00a9: 0x0119, # LATIN SMALL LETTER E WITH OGONEK 0x00aa: 0x00ac, # NOT SIGN 0x00ab: 0x017a, # LATIN SMALL LETTER Z WITH ACUTE 0x00ac: 0x010c, # LATIN CAPITAL LETTER C WITH CARON 0x00ad: 0x015f, # LATIN SMALL LETTER S WITH CEDILLA 0x00ae: 0x00ab, # LEFT-POINTING DOUBLE ANGLE QUOTATION MARK 0x00af: 0x00bb, # RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK 0x00b0: 0x2591, # LIGHT SHADE 0x00b1: 0x2592, # MEDIUM SHADE 0x00b2: 0x2593, # DARK SHADE 0x00b3: 0x2502, # BOX DRAWINGS LIGHT VERTICAL 0x00b4: 0x2524, # BOX DRAWINGS LIGHT VERTICAL AND LEFT 0x00b5: 0x00c1, # LATIN CAPITAL LETTER A WITH ACUTE 0x00b6: 0x00c2, # LATIN CAPITAL LETTER A WITH CIRCUMFLEX 0x00b7: 0x011a, # LATIN CAPITAL LETTER E WITH CARON 0x00b8: 0x015e, # LATIN CAPITAL LETTER S WITH CEDILLA 0x00b9: 0x2563, # BOX DRAWINGS DOUBLE VERTICAL AND LEFT 0x00ba: 0x2551, # BOX DRAWINGS DOUBLE VERTICAL 0x00bb: 0x2557, # BOX DRAWINGS DOUBLE DOWN AND LEFT 0x00bc: 0x255d, # BOX DRAWINGS DOUBLE UP AND LEFT 0x00bd: 0x017b, # LATIN CAPITAL LETTER Z WITH DOT ABOVE 0x00be: 0x017c, # LATIN SMALL LETTER Z WITH DOT ABOVE 0x00bf: 0x2510, # BOX DRAWINGS LIGHT DOWN AND LEFT 0x00c0: 0x2514, # BOX DRAWINGS LIGHT UP AND RIGHT 0x00c1: 0x2534, # BOX DRAWINGS LIGHT UP AND HORIZONTAL 0x00c2: 0x252c, # BOX DRAWINGS LIGHT DOWN AND HORIZONTAL 0x00c3: 0x251c, # BOX DRAWINGS LIGHT VERTICAL AND RIGHT 0x00c4: 0x2500, # BOX DRAWINGS LIGHT HORIZONTAL 0x00c5: 0x253c, # BOX DRAWINGS LIGHT VERTICAL AND HORIZONTAL 0x00c6: 0x0102, # LATIN CAPITAL LETTER A WITH BREVE 0x00c7: 0x0103, # LATIN SMALL LETTER A WITH BREVE 0x00c8: 0x255a, # BOX DRAWINGS DOUBLE UP AND RIGHT 0x00c9: 0x2554, # BOX DRAWINGS DOUBLE DOWN AND RIGHT 0x00ca: 0x2569, # BOX DRAWINGS DOUBLE UP AND HORIZONTAL 0x00cb: 0x2566, # BOX DRAWINGS DOUBLE DOWN AND HORIZONTAL 0x00cc: 0x2560, # BOX DRAWINGS DOUBLE VERTICAL AND RIGHT 0x00cd: 0x2550, # BOX DRAWINGS DOUBLE HORIZONTAL 0x00ce: 0x256c, # BOX DRAWINGS DOUBLE VERTICAL AND HORIZONTAL 0x00cf: 0x00a4, # CURRENCY SIGN 0x00d0: 0x0111, # LATIN SMALL LETTER D WITH STROKE 0x00d1: 0x0110, # LATIN CAPITAL LETTER D WITH STROKE 0x00d2: 0x010e, # LATIN CAPITAL LETTER D WITH CARON 0x00d3: 0x00cb, # LATIN CAPITAL LETTER E WITH DIAERESIS 0x00d4: 0x010f, # LATIN SMALL LETTER D WITH CARON 0x00d5: 0x0147, # LATIN CAPITAL LETTER N WITH CARON 0x00d6: 0x00cd, # LATIN CAPITAL LETTER I WITH ACUTE 0x00d7: 0x00ce, # LATIN CAPITAL LETTER I WITH CIRCUMFLEX 0x00d8: 0x011b, # LATIN SMALL LETTER E WITH CARON 0x00d9: 0x2518, # BOX DRAWINGS LIGHT UP AND LEFT 0x00da: 0x250c, # BOX DRAWINGS LIGHT DOWN AND RIGHT 0x00db: 0x2588, # FULL BLOCK 0x00dc: 0x2584, # LOWER HALF BLOCK 0x00dd: 0x0162, # LATIN CAPITAL LETTER T WITH CEDILLA 0x00de: 0x016e, # LATIN CAPITAL LETTER U WITH RING ABOVE 0x00df: 0x2580, # UPPER HALF BLOCK 0x00e0: 0x00d3, # LATIN CAPITAL LETTER O WITH ACUTE 0x00e1: 0x00df, # LATIN SMALL LETTER SHARP S 0x00e2: 0x00d4, # LATIN CAPITAL LETTER O WITH CIRCUMFLEX 0x00e3: 0x0143, # LATIN CAPITAL LETTER N WITH ACUTE 0x00e4: 0x0144, # LATIN SMALL LETTER N WITH ACUTE 0x00e5: 0x0148, # LATIN SMALL LETTER N WITH CARON 0x00e6: 0x0160, # LATIN CAPITAL LETTER S WITH CARON 0x00e7: 0x0161, # LATIN SMALL LETTER S WITH CARON 0x00e8: 0x0154, # LATIN CAPITAL LETTER R WITH ACUTE 0x00e9: 0x00da, # LATIN CAPITAL LETTER U WITH ACUTE 0x00ea: 0x0155, # LATIN SMALL LETTER R WITH ACUTE 0x00eb: 0x0170, # LATIN CAPITAL LETTER U WITH DOUBLE ACUTE 0x00ec: 0x00fd, # LATIN SMALL LETTER Y WITH ACUTE 0x00ed: 0x00dd, # LATIN CAPITAL LETTER Y WITH ACUTE 0x00ee: 0x0163, # LATIN SMALL LETTER T WITH CEDILLA 0x00ef: 0x00b4, # ACUTE ACCENT 0x00f0: 0x00ad, # SOFT HYPHEN 0x00f1: 0x02dd, # DOUBLE ACUTE ACCENT 0x00f2: 0x02db, # OGONEK 0x00f3: 0x02c7, # CARON 0x00f4: 0x02d8, # BREVE 0x00f5: 0x00a7, # SECTION SIGN 0x00f6: 0x00f7, # DIVISION SIGN 0x00f7: 0x00b8, # CEDILLA 0x00f8: 0x00b0, # DEGREE SIGN 0x00f9: 0x00a8, # DIAERESIS 0x00fa: 0x02d9, # DOT ABOVE 0x00fb: 0x0171, # LATIN SMALL LETTER U WITH DOUBLE ACUTE 0x00fc: 0x0158, # LATIN CAPITAL LETTER R WITH CARON 0x00fd: 0x0159, # LATIN SMALL LETTER R WITH CARON 0x00fe: 0x25a0, # BLACK SQUARE 0x00ff: 0x00a0, # NO-BREAK SPACE }) ### Decoding Table decoding_table = ( u'\x00' # 0x0000 -> NULL u'\x01' # 0x0001 -> START OF HEADING u'\x02' # 0x0002 -> START OF TEXT u'\x03' # 0x0003 -> END OF TEXT u'\x04' # 0x0004 -> END OF TRANSMISSION u'\x05' # 0x0005 -> ENQUIRY u'\x06' # 0x0006 -> ACKNOWLEDGE u'\x07' # 0x0007 -> BELL u'\x08' # 0x0008 -> BACKSPACE u'\t' # 0x0009 -> HORIZONTAL TABULATION u'\n' # 0x000a -> LINE FEED u'\x0b' # 0x000b -> VERTICAL TABULATION u'\x0c' # 0x000c -> FORM FEED u'\r' # 0x000d -> CARRIAGE RETURN u'\x0e' # 0x000e -> SHIFT OUT u'\x0f' # 0x000f -> SHIFT IN u'\x10' # 0x0010 -> DATA LINK ESCAPE u'\x11' # 0x0011 -> DEVICE CONTROL ONE u'\x12' # 0x0012 -> DEVICE CONTROL TWO u'\x13' # 0x0013 -> DEVICE CONTROL THREE u'\x14' # 0x0014 -> DEVICE CONTROL FOUR u'\x15' # 0x0015 -> NEGATIVE ACKNOWLEDGE u'\x16' # 0x0016 -> SYNCHRONOUS IDLE u'\x17' # 0x0017 -> END OF TRANSMISSION BLOCK u'\x18' # 0x0018 -> CANCEL u'\x19' # 0x0019 -> END OF MEDIUM u'\x1a' # 0x001a -> SUBSTITUTE u'\x1b' # 0x001b -> ESCAPE u'\x1c' # 0x001c -> FILE SEPARATOR u'\x1d' # 0x001d -> GROUP SEPARATOR u'\x1e' # 0x001e -> RECORD SEPARATOR u'\x1f' # 0x001f -> UNIT SEPARATOR u' ' # 0x0020 -> SPACE u'!' # 0x0021 -> EXCLAMATION MARK u'"' # 0x0022 -> QUOTATION MARK u'#' # 0x0023 -> NUMBER SIGN u'$' # 0x0024 -> DOLLAR SIGN u'%' # 0x0025 -> PERCENT SIGN u'&' # 0x0026 -> AMPERSAND u"'" # 0x0027 -> APOSTROPHE u'(' # 0x0028 -> LEFT PARENTHESIS u')' # 0x0029 -> RIGHT PARENTHESIS u'*' # 0x002a -> ASTERISK u'+' # 0x002b -> PLUS SIGN u',' # 0x002c -> COMMA u'-' # 0x002d -> HYPHEN-MINUS u'.' # 0x002e -> FULL STOP u'/' # 0x002f -> SOLIDUS u'0' # 0x0030 -> DIGIT ZERO u'1' # 0x0031 -> DIGIT ONE u'2' # 0x0032 -> DIGIT TWO u'3' # 0x0033 -> DIGIT THREE u'4' # 0x0034 -> DIGIT FOUR u'5' # 0x0035 -> DIGIT FIVE u'6' # 0x0036 -> DIGIT SIX u'7' # 0x0037 -> DIGIT SEVEN u'8' # 0x0038 -> DIGIT EIGHT u'9' # 0x0039 -> DIGIT NINE u':' # 0x003a -> COLON u';' # 0x003b -> SEMICOLON u'<' # 0x003c -> LESS-THAN SIGN u'=' # 0x003d -> EQUALS SIGN u'>' # 0x003e -> GREATER-THAN SIGN u'?' # 0x003f -> QUESTION MARK u'@' # 0x0040 -> COMMERCIAL AT u'A' # 0x0041 -> LATIN CAPITAL LETTER A u'B' # 0x0042 -> LATIN CAPITAL LETTER B u'C' # 0x0043 -> LATIN CAPITAL LETTER C u'D' # 0x0044 -> LATIN CAPITAL LETTER D u'E' # 0x0045 -> LATIN CAPITAL LETTER E u'F' # 0x0046 -> LATIN CAPITAL LETTER F u'G' # 0x0047 -> LATIN CAPITAL LETTER G u'H' # 0x0048 -> LATIN CAPITAL LETTER H u'I' # 0x0049 -> LATIN CAPITAL LETTER I u'J' # 0x004a -> LATIN CAPITAL LETTER J u'K' # 0x004b -> LATIN CAPITAL LETTER K u'L' # 0x004c -> LATIN CAPITAL LETTER L u'M' # 0x004d -> LATIN CAPITAL LETTER M u'N' # 0x004e -> LATIN CAPITAL LETTER N u'O' # 0x004f -> LATIN CAPITAL LETTER O u'P' # 0x0050 -> LATIN CAPITAL LETTER P u'Q' # 0x0051 -> LATIN CAPITAL LETTER Q u'R' # 0x0052 -> LATIN CAPITAL LETTER R u'S' # 0x0053 -> LATIN CAPITAL LETTER S u'T' # 0x0054 -> LATIN CAPITAL LETTER T u'U' # 0x0055 -> LATIN CAPITAL LETTER U u'V' # 0x0056 -> LATIN CAPITAL LETTER V u'W' # 0x0057 -> LATIN CAPITAL LETTER W u'X' # 0x0058 -> LATIN CAPITAL LETTER X u'Y' # 0x0059 -> LATIN CAPITAL LETTER Y u'Z' # 0x005a -> LATIN CAPITAL LETTER Z u'[' # 0x005b -> LEFT SQUARE BRACKET u'\\' # 0x005c -> REVERSE SOLIDUS u']' # 0x005d -> RIGHT SQUARE BRACKET u'^' # 0x005e -> CIRCUMFLEX ACCENT u'_' # 0x005f -> LOW LINE u'`' # 0x0060 -> GRAVE ACCENT u'a' # 0x0061 -> LATIN SMALL LETTER A u'b' # 0x0062 -> LATIN SMALL LETTER B u'c' # 0x0063 -> LATIN SMALL LETTER C u'd' # 0x0064 -> LATIN SMALL LETTER D u'e' # 0x0065 -> LATIN SMALL LETTER E u'f' # 0x0066 -> LATIN SMALL LETTER F u'g' # 0x0067 -> LATIN SMALL LETTER G u'h' # 0x0068 -> LATIN SMALL LETTER H u'i' # 0x0069 -> LATIN SMALL LETTER I u'j' # 0x006a -> LATIN SMALL LETTER J u'k' # 0x006b -> LATIN SMALL LETTER K u'l' # 0x006c -> LATIN SMALL LETTER L u'm' # 0x006d -> LATIN SMALL LETTER M u'n' # 0x006e -> LATIN SMALL LETTER N u'o' # 0x006f -> LATIN SMALL LETTER O u'p' # 0x0070 -> LATIN SMALL LETTER P u'q' # 0x0071 -> LATIN SMALL LETTER Q u'r' # 0x0072 -> LATIN SMALL LETTER R u's' # 0x0073 -> LATIN SMALL LETTER S u't' # 0x0074 -> LATIN SMALL LETTER T u'u' # 0x0075 -> LATIN SMALL LETTER U u'v' # 0x0076 -> LATIN SMALL LETTER V u'w' # 0x0077 -> LATIN SMALL LETTER W u'x' # 0x0078 -> LATIN SMALL LETTER X u'y' # 0x0079 -> LATIN SMALL LETTER Y u'z' # 0x007a -> LATIN SMALL LETTER Z u'{' # 0x007b -> LEFT CURLY BRACKET u'|' # 0x007c -> VERTICAL LINE u'}' # 0x007d -> RIGHT CURLY BRACKET u'~' # 0x007e -> TILDE u'\x7f' # 0x007f -> DELETE u'\xc7' # 0x0080 -> LATIN CAPITAL LETTER C WITH CEDILLA u'\xfc' # 0x0081 -> LATIN SMALL LETTER U WITH DIAERESIS u'\xe9' # 0x0082 -> LATIN SMALL LETTER E WITH ACUTE u'\xe2' # 0x0083 -> LATIN SMALL LETTER A WITH CIRCUMFLEX u'\xe4' # 0x0084 -> LATIN SMALL LETTER A WITH DIAERESIS u'\u016f' # 0x0085 -> LATIN SMALL LETTER U WITH RING ABOVE u'\u0107' # 0x0086 -> LATIN SMALL LETTER C WITH ACUTE u'\xe7' # 0x0087 -> LATIN SMALL LETTER C WITH CEDILLA u'\u0142' # 0x0088 -> LATIN SMALL LETTER L WITH STROKE u'\xeb' # 0x0089 -> LATIN SMALL LETTER E WITH DIAERESIS u'\u0150' # 0x008a -> LATIN CAPITAL LETTER O WITH DOUBLE ACUTE u'\u0151' # 0x008b -> LATIN SMALL LETTER O WITH DOUBLE ACUTE u'\xee' # 0x008c -> LATIN SMALL LETTER I WITH CIRCUMFLEX u'\u0179' # 0x008d -> LATIN CAPITAL LETTER Z WITH ACUTE u'\xc4' # 0x008e -> LATIN CAPITAL LETTER A WITH DIAERESIS u'\u0106' # 0x008f -> LATIN CAPITAL LETTER C WITH ACUTE u'\xc9' # 0x0090 -> LATIN CAPITAL LETTER E WITH ACUTE u'\u0139' # 0x0091 -> LATIN CAPITAL LETTER L WITH ACUTE u'\u013a' # 0x0092 -> LATIN SMALL LETTER L WITH ACUTE u'\xf4' # 0x0093 -> LATIN SMALL LETTER O WITH CIRCUMFLEX u'\xf6' # 0x0094 -> LATIN SMALL LETTER O WITH DIAERESIS u'\u013d' # 0x0095 -> LATIN CAPITAL LETTER L WITH CARON u'\u013e' # 0x0096 -> LATIN SMALL LETTER L WITH CARON u'\u015a' # 0x0097 -> LATIN CAPITAL LETTER S WITH ACUTE u'\u015b' # 0x0098 -> LATIN SMALL LETTER S WITH ACUTE u'\xd6' # 0x0099 -> LATIN CAPITAL LETTER O WITH DIAERESIS u'\xdc' # 0x009a -> LATIN CAPITAL LETTER U WITH DIAERESIS u'\u0164' # 0x009b -> LATIN CAPITAL LETTER T WITH CARON u'\u0165' # 0x009c -> LATIN SMALL LETTER T WITH CARON u'\u0141' # 0x009d -> LATIN CAPITAL LETTER L WITH STROKE u'\xd7' # 0x009e -> MULTIPLICATION SIGN u'\u010d' # 0x009f -> LATIN SMALL LETTER C WITH CARON u'\xe1' # 0x00a0 -> LATIN SMALL LETTER A WITH ACUTE u'\xed' # 0x00a1 -> LATIN SMALL LETTER I WITH ACUTE u'\xf3' # 0x00a2 -> LATIN SMALL LETTER O WITH ACUTE u'\xfa' # 0x00a3 -> LATIN SMALL LETTER U WITH ACUTE u'\u0104' # 0x00a4 -> LATIN CAPITAL LETTER A WITH OGONEK u'\u0105' # 0x00a5 -> LATIN SMALL LETTER A WITH OGONEK u'\u017d' # 0x00a6 -> LATIN CAPITAL LETTER Z WITH CARON u'\u017e' # 0x00a7 -> LATIN SMALL LETTER Z WITH CARON u'\u0118' # 0x00a8 -> LATIN CAPITAL LETTER E WITH OGONEK u'\u0119' # 0x00a9 -> LATIN SMALL LETTER E WITH OGONEK u'\xac' # 0x00aa -> NOT SIGN u'\u017a' # 0x00ab -> LATIN SMALL LETTER Z WITH ACUTE u'\u010c' # 0x00ac -> LATIN CAPITAL LETTER C WITH CARON u'\u015f' # 0x00ad -> LATIN SMALL LETTER S WITH CEDILLA u'\xab' # 0x00ae -> LEFT-POINTING DOUBLE ANGLE QUOTATION MARK u'\xbb' # 0x00af -> RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK u'\u2591' # 0x00b0 -> LIGHT SHADE u'\u2592' # 0x00b1 -> MEDIUM SHADE u'\u2593' # 0x00b2 -> DARK SHADE u'\u2502' # 0x00b3 -> BOX DRAWINGS LIGHT VERTICAL u'\u2524' # 0x00b4 -> BOX DRAWINGS LIGHT VERTICAL AND LEFT u'\xc1' # 0x00b5 -> LATIN CAPITAL LETTER A WITH ACUTE u'\xc2' # 0x00b6 -> LATIN CAPITAL LETTER A WITH CIRCUMFLEX u'\u011a' # 0x00b7 -> LATIN CAPITAL LETTER E WITH CARON u'\u015e' # 0x00b8 -> LATIN CAPITAL LETTER S WITH CEDILLA u'\u2563' # 0x00b9 -> BOX DRAWINGS DOUBLE VERTICAL AND LEFT u'\u2551' # 0x00ba -> BOX DRAWINGS DOUBLE VERTICAL u'\u2557' # 0x00bb -> BOX DRAWINGS DOUBLE DOWN AND LEFT u'\u255d' # 0x00bc -> BOX DRAWINGS DOUBLE UP AND LEFT u'\u017b' # 0x00bd -> LATIN CAPITAL LETTER Z WITH DOT ABOVE u'\u017c' # 0x00be -> LATIN SMALL LETTER Z WITH DOT ABOVE u'\u2510' # 0x00bf -> BOX DRAWINGS LIGHT DOWN AND LEFT u'\u2514' # 0x00c0 -> BOX DRAWINGS LIGHT UP AND RIGHT u'\u2534' # 0x00c1 -> BOX DRAWINGS LIGHT UP AND HORIZONTAL u'\u252c' # 0x00c2 -> BOX DRAWINGS LIGHT DOWN AND HORIZONTAL u'\u251c' # 0x00c3 -> BOX DRAWINGS LIGHT VERTICAL AND RIGHT u'\u2500' # 0x00c4 -> BOX DRAWINGS LIGHT HORIZONTAL u'\u253c' # 0x00c5 -> BOX DRAWINGS LIGHT VERTICAL AND HORIZONTAL u'\u0102' # 0x00c6 -> LATIN CAPITAL LETTER A WITH BREVE u'\u0103' # 0x00c7 -> LATIN SMALL LETTER A WITH BREVE u'\u255a' # 0x00c8 -> BOX DRAWINGS DOUBLE UP AND RIGHT u'\u2554' # 0x00c9 -> BOX DRAWINGS DOUBLE DOWN AND RIGHT u'\u2569' # 0x00ca -> BOX DRAWINGS DOUBLE UP AND HORIZONTAL u'\u2566' # 0x00cb -> BOX DRAWINGS DOUBLE DOWN AND HORIZONTAL u'\u2560' # 0x00cc -> BOX DRAWINGS DOUBLE VERTICAL AND RIGHT u'\u2550' # 0x00cd -> BOX DRAWINGS DOUBLE HORIZONTAL u'\u256c' # 0x00ce -> BOX DRAWINGS DOUBLE VERTICAL AND HORIZONTAL u'\xa4' # 0x00cf -> CURRENCY SIGN u'\u0111' # 0x00d0 -> LATIN SMALL LETTER D WITH STROKE u'\u0110' # 0x00d1 -> LATIN CAPITAL LETTER D WITH STROKE u'\u010e' # 0x00d2 -> LATIN CAPITAL LETTER D WITH CARON u'\xcb' # 0x00d3 -> LATIN CAPITAL LETTER E WITH DIAERESIS u'\u010f' # 0x00d4 -> LATIN SMALL LETTER D WITH CARON u'\u0147' # 0x00d5 -> LATIN CAPITAL LETTER N WITH CARON u'\xcd' # 0x00d6 -> LATIN CAPITAL LETTER I WITH ACUTE u'\xce' # 0x00d7 -> LATIN CAPITAL LETTER I WITH CIRCUMFLEX u'\u011b' # 0x00d8 -> LATIN SMALL LETTER E WITH CARON u'\u2518' # 0x00d9 -> BOX DRAWINGS LIGHT UP AND LEFT u'\u250c' # 0x00da -> BOX DRAWINGS LIGHT DOWN AND RIGHT u'\u2588' # 0x00db -> FULL BLOCK u'\u2584' # 0x00dc -> LOWER HALF BLOCK u'\u0162' # 0x00dd -> LATIN CAPITAL LETTER T WITH CEDILLA u'\u016e' # 0x00de -> LATIN CAPITAL LETTER U WITH RING ABOVE u'\u2580' # 0x00df -> UPPER HALF BLOCK u'\xd3' # 0x00e0 -> LATIN CAPITAL LETTER O WITH ACUTE u'\xdf' # 0x00e1 -> LATIN SMALL LETTER SHARP S u'\xd4' # 0x00e2 -> LATIN CAPITAL LETTER O WITH CIRCUMFLEX u'\u0143' # 0x00e3 -> LATIN CAPITAL LETTER N WITH ACUTE u'\u0144' # 0x00e4 -> LATIN SMALL LETTER N WITH ACUTE u'\u0148' # 0x00e5 -> LATIN SMALL LETTER N WITH CARON u'\u0160' # 0x00e6 -> LATIN CAPITAL LETTER S WITH CARON u'\u0161' # 0x00e7 -> LATIN SMALL LETTER S WITH CARON u'\u0154' # 0x00e8 -> LATIN CAPITAL LETTER R WITH ACUTE u'\xda' # 0x00e9 -> LATIN CAPITAL LETTER U WITH ACUTE u'\u0155' # 0x00ea -> LATIN SMALL LETTER R WITH ACUTE u'\u0170' # 0x00eb -> LATIN CAPITAL LETTER U WITH DOUBLE ACUTE u'\xfd' # 0x00ec -> LATIN SMALL LETTER Y WITH ACUTE u'\xdd' # 0x00ed -> LATIN CAPITAL LETTER Y WITH ACUTE u'\u0163' # 0x00ee -> LATIN SMALL LETTER T WITH CEDILLA u'\xb4' # 0x00ef -> ACUTE ACCENT u'\xad' # 0x00f0 -> SOFT HYPHEN u'\u02dd' # 0x00f1 -> DOUBLE ACUTE ACCENT u'\u02db' # 0x00f2 -> OGONEK u'\u02c7' # 0x00f3 -> CARON u'\u02d8' # 0x00f4 -> BREVE u'\xa7' # 0x00f5 -> SECTION SIGN u'\xf7' # 0x00f6 -> DIVISION SIGN u'\xb8' # 0x00f7 -> CEDILLA u'\xb0' # 0x00f8 -> DEGREE SIGN u'\xa8' # 0x00f9 -> DIAERESIS u'\u02d9' # 0x00fa -> DOT ABOVE u'\u0171' # 0x00fb -> LATIN SMALL LETTER U WITH DOUBLE ACUTE u'\u0158' # 0x00fc -> LATIN CAPITAL LETTER R WITH CARON u'\u0159' # 0x00fd -> LATIN SMALL LETTER R WITH CARON u'\u25a0' # 0x00fe -> BLACK SQUARE u'\xa0' # 0x00ff -> NO-BREAK SPACE ) ### Encoding Map encoding_map = { 0x0000: 0x0000, # NULL 0x0001: 0x0001, # START OF HEADING 0x0002: 0x0002, # START OF TEXT 0x0003: 0x0003, # END OF TEXT 0x0004: 0x0004, # END OF TRANSMISSION 0x0005: 0x0005, # ENQUIRY 0x0006: 0x0006, # ACKNOWLEDGE 0x0007: 0x0007, # BELL 0x0008: 0x0008, # BACKSPACE 0x0009: 0x0009, # HORIZONTAL TABULATION 0x000a: 0x000a, # LINE FEED 0x000b: 0x000b, # VERTICAL TABULATION 0x000c: 0x000c, # FORM FEED 0x000d: 0x000d, # CARRIAGE RETURN 0x000e: 0x000e, # SHIFT OUT 0x000f: 0x000f, # SHIFT IN 0x0010: 0x0010, # DATA LINK ESCAPE 0x0011: 0x0011, # DEVICE CONTROL ONE 0x0012: 0x0012, # DEVICE CONTROL TWO 0x0013: 0x0013, # DEVICE CONTROL THREE 0x0014: 0x0014, # DEVICE CONTROL FOUR 0x0015: 0x0015, # NEGATIVE ACKNOWLEDGE 0x0016: 0x0016, # SYNCHRONOUS IDLE 0x0017: 0x0017, # END OF TRANSMISSION BLOCK 0x0018: 0x0018, # CANCEL 0x0019: 0x0019, # END OF MEDIUM 0x001a: 0x001a, # SUBSTITUTE 0x001b: 0x001b, # ESCAPE 0x001c: 0x001c, # FILE SEPARATOR 0x001d: 0x001d, # GROUP SEPARATOR 0x001e: 0x001e, # RECORD SEPARATOR 0x001f: 0x001f, # UNIT SEPARATOR 0x0020: 0x0020, # SPACE 0x0021: 0x0021, # EXCLAMATION MARK 0x0022: 0x0022, # QUOTATION MARK 0x0023: 0x0023, # NUMBER SIGN 0x0024: 0x0024, # DOLLAR SIGN 0x0025: 0x0025, # PERCENT SIGN 0x0026: 0x0026, # AMPERSAND 0x0027: 0x0027, # APOSTROPHE 0x0028: 0x0028, # LEFT PARENTHESIS 0x0029: 0x0029, # RIGHT PARENTHESIS 0x002a: 0x002a, # ASTERISK 0x002b: 0x002b, # PLUS SIGN 0x002c: 0x002c, # COMMA 0x002d: 0x002d, # HYPHEN-MINUS 0x002e: 0x002e, # FULL STOP 0x002f: 0x002f, # SOLIDUS 0x0030: 0x0030, # DIGIT ZERO 0x0031: 0x0031, # DIGIT ONE 0x0032: 0x0032, # DIGIT TWO 0x0033: 0x0033, # DIGIT THREE 0x0034: 0x0034, # DIGIT FOUR 0x0035: 0x0035, # DIGIT FIVE 0x0036: 0x0036, # DIGIT SIX 0x0037: 0x0037, # DIGIT SEVEN 0x0038: 0x0038, # DIGIT EIGHT 0x0039: 0x0039, # DIGIT NINE 0x003a: 0x003a, # COLON 0x003b: 0x003b, # SEMICOLON 0x003c: 0x003c, # LESS-THAN SIGN 0x003d: 0x003d, # EQUALS SIGN 0x003e: 0x003e, # GREATER-THAN SIGN 0x003f: 0x003f, # QUESTION MARK 0x0040: 0x0040, # COMMERCIAL AT 0x0041: 0x0041, # LATIN CAPITAL LETTER A 0x0042: 0x0042, # LATIN CAPITAL LETTER B 0x0043: 0x0043, # LATIN CAPITAL LETTER C 0x0044: 0x0044, # LATIN CAPITAL LETTER D 0x0045: 0x0045, # LATIN CAPITAL LETTER E 0x0046: 0x0046, # LATIN CAPITAL LETTER F 0x0047: 0x0047, # LATIN CAPITAL LETTER G 0x0048: 0x0048, # LATIN CAPITAL LETTER H 0x0049: 0x0049, # LATIN CAPITAL LETTER I 0x004a: 0x004a, # LATIN CAPITAL LETTER J 0x004b: 0x004b, # LATIN CAPITAL LETTER K 0x004c: 0x004c, # LATIN CAPITAL LETTER L 0x004d: 0x004d, # LATIN CAPITAL LETTER M 0x004e: 0x004e, # LATIN CAPITAL LETTER N 0x004f: 0x004f, # LATIN CAPITAL LETTER O 0x0050: 0x0050, # LATIN CAPITAL LETTER P 0x0051: 0x0051, # LATIN CAPITAL LETTER Q 0x0052: 0x0052, # LATIN CAPITAL LETTER R 0x0053: 0x0053, # LATIN CAPITAL LETTER S 0x0054: 0x0054, # LATIN CAPITAL LETTER T 0x0055: 0x0055, # LATIN CAPITAL LETTER U 0x0056: 0x0056, # LATIN CAPITAL LETTER V 0x0057: 0x0057, # LATIN CAPITAL LETTER W 0x0058: 0x0058, # LATIN CAPITAL LETTER X 0x0059: 0x0059, # LATIN CAPITAL LETTER Y 0x005a: 0x005a, # LATIN CAPITAL LETTER Z 0x005b: 0x005b, # LEFT SQUARE BRACKET 0x005c: 0x005c, # REVERSE SOLIDUS 0x005d: 0x005d, # RIGHT SQUARE BRACKET 0x005e: 0x005e, # CIRCUMFLEX ACCENT 0x005f: 0x005f, # LOW LINE 0x0060: 0x0060, # GRAVE ACCENT 0x0061: 0x0061, # LATIN SMALL LETTER A 0x0062: 0x0062, # LATIN SMALL LETTER B 0x0063: 0x0063, # LATIN SMALL LETTER C 0x0064: 0x0064, # LATIN SMALL LETTER D 0x0065: 0x0065, # LATIN SMALL LETTER E 0x0066: 0x0066, # LATIN SMALL LETTER F 0x0067: 0x0067, # LATIN SMALL LETTER G 0x0068: 0x0068, # LATIN SMALL LETTER H 0x0069: 0x0069, # LATIN SMALL LETTER I 0x006a: 0x006a, # LATIN SMALL LETTER J 0x006b: 0x006b, # LATIN SMALL LETTER K 0x006c: 0x006c, # LATIN SMALL LETTER L 0x006d: 0x006d, # LATIN SMALL LETTER M 0x006e: 0x006e, # LATIN SMALL LETTER N 0x006f: 0x006f, # LATIN SMALL LETTER O 0x0070: 0x0070, # LATIN SMALL LETTER P 0x0071: 0x0071, # LATIN SMALL LETTER Q 0x0072: 0x0072, # LATIN SMALL LETTER R 0x0073: 0x0073, # LATIN SMALL LETTER S 0x0074: 0x0074, # LATIN SMALL LETTER T 0x0075: 0x0075, # LATIN SMALL LETTER U 0x0076: 0x0076, # LATIN SMALL LETTER V 0x0077: 0x0077, # LATIN SMALL LETTER W 0x0078: 0x0078, # LATIN SMALL LETTER X 0x0079: 0x0079, # LATIN SMALL LETTER Y 0x007a: 0x007a, # LATIN SMALL LETTER Z 0x007b: 0x007b, # LEFT CURLY BRACKET 0x007c: 0x007c, # VERTICAL LINE 0x007d: 0x007d, # RIGHT CURLY BRACKET 0x007e: 0x007e, # TILDE 0x007f: 0x007f, # DELETE 0x00a0: 0x00ff, # NO-BREAK SPACE 0x00a4: 0x00cf, # CURRENCY SIGN 0x00a7: 0x00f5, # SECTION SIGN 0x00a8: 0x00f9, # DIAERESIS 0x00ab: 0x00ae, # LEFT-POINTING DOUBLE ANGLE QUOTATION MARK 0x00ac: 0x00aa, # NOT SIGN 0x00ad: 0x00f0, # SOFT HYPHEN 0x00b0: 0x00f8, # DEGREE SIGN 0x00b4: 0x00ef, # ACUTE ACCENT 0x00b8: 0x00f7, # CEDILLA 0x00bb: 0x00af, # RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK 0x00c1: 0x00b5, # LATIN CAPITAL LETTER A WITH ACUTE 0x00c2: 0x00b6, # LATIN CAPITAL LETTER A WITH CIRCUMFLEX 0x00c4: 0x008e, # LATIN CAPITAL LETTER A WITH DIAERESIS 0x00c7: 0x0080, # LATIN CAPITAL LETTER C WITH CEDILLA 0x00c9: 0x0090, # LATIN CAPITAL LETTER E WITH ACUTE 0x00cb: 0x00d3, # LATIN CAPITAL LETTER E WITH DIAERESIS 0x00cd: 0x00d6, # LATIN CAPITAL LETTER I WITH ACUTE 0x00ce: 0x00d7, # LATIN CAPITAL LETTER I WITH CIRCUMFLEX 0x00d3: 0x00e0, # LATIN CAPITAL LETTER O WITH ACUTE 0x00d4: 0x00e2, # LATIN CAPITAL LETTER O WITH CIRCUMFLEX 0x00d6: 0x0099, # LATIN CAPITAL LETTER O WITH DIAERESIS 0x00d7: 0x009e, # MULTIPLICATION SIGN 0x00da: 0x00e9, # LATIN CAPITAL LETTER U WITH ACUTE 0x00dc: 0x009a, # LATIN CAPITAL LETTER U WITH DIAERESIS 0x00dd: 0x00ed, # LATIN CAPITAL LETTER Y WITH ACUTE 0x00df: 0x00e1, # LATIN SMALL LETTER SHARP S 0x00e1: 0x00a0, # LATIN SMALL LETTER A WITH ACUTE 0x00e2: 0x0083, # LATIN SMALL LETTER A WITH CIRCUMFLEX 0x00e4: 0x0084, # LATIN SMALL LETTER A WITH DIAERESIS 0x00e7: 0x0087, # LATIN SMALL LETTER C WITH CEDILLA 0x00e9: 0x0082, # LATIN SMALL LETTER E WITH ACUTE 0x00eb: 0x0089, # LATIN SMALL LETTER E WITH DIAERESIS 0x00ed: 0x00a1, # LATIN SMALL LETTER I WITH ACUTE 0x00ee: 0x008c, # LATIN SMALL LETTER I WITH CIRCUMFLEX 0x00f3: 0x00a2, # LATIN SMALL LETTER O WITH ACUTE 0x00f4: 0x0093, # LATIN SMALL LETTER O WITH CIRCUMFLEX 0x00f6: 0x0094, # LATIN SMALL LETTER O WITH DIAERESIS 0x00f7: 0x00f6, # DIVISION SIGN 0x00fa: 0x00a3, # LATIN SMALL LETTER U WITH ACUTE 0x00fc: 0x0081, # LATIN SMALL LETTER U WITH DIAERESIS 0x00fd: 0x00ec, # LATIN SMALL LETTER Y WITH ACUTE 0x0102: 0x00c6, # LATIN CAPITAL LETTER A WITH BREVE 0x0103: 0x00c7, # LATIN SMALL LETTER A WITH BREVE 0x0104: 0x00a4, # LATIN CAPITAL LETTER A WITH OGONEK 0x0105: 0x00a5, # LATIN SMALL LETTER A WITH OGONEK 0x0106: 0x008f, # LATIN CAPITAL LETTER C WITH ACUTE 0x0107: 0x0086, # LATIN SMALL LETTER C WITH ACUTE 0x010c: 0x00ac, # LATIN CAPITAL LETTER C WITH CARON 0x010d: 0x009f, # LATIN SMALL LETTER C WITH CARON 0x010e: 0x00d2, # LATIN CAPITAL LETTER D WITH CARON 0x010f: 0x00d4, # LATIN SMALL LETTER D WITH CARON 0x0110: 0x00d1, # LATIN CAPITAL LETTER D WITH STROKE 0x0111: 0x00d0, # LATIN SMALL LETTER D WITH STROKE 0x0118: 0x00a8, # LATIN CAPITAL LETTER E WITH OGONEK 0x0119: 0x00a9, # LATIN SMALL LETTER E WITH OGONEK 0x011a: 0x00b7, # LATIN CAPITAL LETTER E WITH CARON 0x011b: 0x00d8, # LATIN SMALL LETTER E WITH CARON 0x0139: 0x0091, # LATIN CAPITAL LETTER L WITH ACUTE 0x013a: 0x0092, # LATIN SMALL LETTER L WITH ACUTE 0x013d: 0x0095, # LATIN CAPITAL LETTER L WITH CARON 0x013e: 0x0096, # LATIN SMALL LETTER L WITH CARON 0x0141: 0x009d, # LATIN CAPITAL LETTER L WITH STROKE 0x0142: 0x0088, # LATIN SMALL LETTER L WITH STROKE 0x0143: 0x00e3, # LATIN CAPITAL LETTER N WITH ACUTE 0x0144: 0x00e4, # LATIN SMALL LETTER N WITH ACUTE 0x0147: 0x00d5, # LATIN CAPITAL LETTER N WITH CARON 0x0148: 0x00e5, # LATIN SMALL LETTER N WITH CARON 0x0150: 0x008a, # LATIN CAPITAL LETTER O WITH DOUBLE ACUTE 0x0151: 0x008b, # LATIN SMALL LETTER O WITH DOUBLE ACUTE 0x0154: 0x00e8, # LATIN CAPITAL LETTER R WITH ACUTE 0x0155: 0x00ea, # LATIN SMALL LETTER R WITH ACUTE 0x0158: 0x00fc, # LATIN CAPITAL LETTER R WITH CARON 0x0159: 0x00fd, # LATIN SMALL LETTER R WITH CARON 0x015a: 0x0097, # LATIN CAPITAL LETTER S WITH ACUTE 0x015b: 0x0098, # LATIN SMALL LETTER S WITH ACUTE 0x015e: 0x00b8, # LATIN CAPITAL LETTER S WITH CEDILLA 0x015f: 0x00ad, # LATIN SMALL LETTER S WITH CEDILLA 0x0160: 0x00e6, # LATIN CAPITAL LETTER S WITH CARON 0x0161: 0x00e7, # LATIN SMALL LETTER S WITH CARON 0x0162: 0x00dd, # LATIN CAPITAL LETTER T WITH CEDILLA 0x0163: 0x00ee, # LATIN SMALL LETTER T WITH CEDILLA 0x0164: 0x009b, # LATIN CAPITAL LETTER T WITH CARON 0x0165: 0x009c, # LATIN SMALL LETTER T WITH CARON 0x016e: 0x00de, # LATIN CAPITAL LETTER U WITH RING ABOVE 0x016f: 0x0085, # LATIN SMALL LETTER U WITH RING ABOVE 0x0170: 0x00eb, # LATIN CAPITAL LETTER U WITH DOUBLE ACUTE 0x0171: 0x00fb, # LATIN SMALL LETTER U WITH DOUBLE ACUTE 0x0179: 0x008d, # LATIN CAPITAL LETTER Z WITH ACUTE 0x017a: 0x00ab, # LATIN SMALL LETTER Z WITH ACUTE 0x017b: 0x00bd, # LATIN CAPITAL LETTER Z WITH DOT ABOVE 0x017c: 0x00be, # LATIN SMALL LETTER Z WITH DOT ABOVE 0x017d: 0x00a6, # LATIN CAPITAL LETTER Z WITH CARON 0x017e: 0x00a7, # LATIN SMALL LETTER Z WITH CARON 0x02c7: 0x00f3, # CARON 0x02d8: 0x00f4, # BREVE 0x02d9: 0x00fa, # DOT ABOVE 0x02db: 0x00f2, # OGONEK 0x02dd: 0x00f1, # DOUBLE ACUTE ACCENT 0x2500: 0x00c4, # BOX DRAWINGS LIGHT HORIZONTAL 0x2502: 0x00b3, # BOX DRAWINGS LIGHT VERTICAL 0x250c: 0x00da, # BOX DRAWINGS LIGHT DOWN AND RIGHT 0x2510: 0x00bf, # BOX DRAWINGS LIGHT DOWN AND LEFT 0x2514: 0x00c0, # BOX DRAWINGS LIGHT UP AND RIGHT 0x2518: 0x00d9, # BOX DRAWINGS LIGHT UP AND LEFT 0x251c: 0x00c3, # BOX DRAWINGS LIGHT VERTICAL AND RIGHT 0x2524: 0x00b4, # BOX DRAWINGS LIGHT VERTICAL AND LEFT 0x252c: 0x00c2, # BOX DRAWINGS LIGHT DOWN AND HORIZONTAL 0x2534: 0x00c1, # BOX DRAWINGS LIGHT UP AND HORIZONTAL 0x253c: 0x00c5, # BOX DRAWINGS LIGHT VERTICAL AND HORIZONTAL 0x2550: 0x00cd, # BOX DRAWINGS DOUBLE HORIZONTAL 0x2551: 0x00ba, # BOX DRAWINGS DOUBLE VERTICAL 0x2554: 0x00c9, # BOX DRAWINGS DOUBLE DOWN AND RIGHT 0x2557: 0x00bb, # BOX DRAWINGS DOUBLE DOWN AND LEFT 0x255a: 0x00c8, # BOX DRAWINGS DOUBLE UP AND RIGHT 0x255d: 0x00bc, # BOX DRAWINGS DOUBLE UP AND LEFT 0x2560: 0x00cc, # BOX DRAWINGS DOUBLE VERTICAL AND RIGHT 0x2563: 0x00b9, # BOX DRAWINGS DOUBLE VERTICAL AND LEFT 0x2566: 0x00cb, # BOX DRAWINGS DOUBLE DOWN AND HORIZONTAL 0x2569: 0x00ca, # BOX DRAWINGS DOUBLE UP AND HORIZONTAL 0x256c: 0x00ce, # BOX DRAWINGS DOUBLE VERTICAL AND HORIZONTAL 0x2580: 0x00df, # UPPER HALF BLOCK 0x2584: 0x00dc, # LOWER HALF BLOCK 0x2588: 0x00db, # FULL BLOCK 0x2591: 0x00b0, # LIGHT SHADE 0x2592: 0x00b1, # MEDIUM SHADE 0x2593: 0x00b2, # DARK SHADE 0x25a0: 0x00fe, # BLACK SQUARE }
2026-03-31T15:30:28
codeparrot_clean
cba3bece941033336c59b6a29111a2f4
code
import pytest import numpy as np from numpy.core import ( array, arange, atleast_1d, atleast_2d, atleast_3d, block, vstack, hstack, newaxis, concatenate, stack ) from numpy.core.shape_base import (_block_dispatcher, _block_setup, _block_concatenate, _block_slicing) from numpy.testing import ( assert_, assert_raises, assert_array_equal, assert_equal, assert_raises_regex, assert_warns, IS_PYPY ) class TestAtleast1d: def test_0D_array(self): a = array(1) b = array(2) res = [atleast_1d(a), atleast_1d(b)] desired = [array([1]), array([2])] assert_array_equal(res, desired) def test_1D_array(self): a = array([1, 2]) b = array([2, 3]) res = [atleast_1d(a), atleast_1d(b)] desired = [array([1, 2]), array([2, 3])] assert_array_equal(res, desired) def test_2D_array(self): a = array([[1, 2], [1, 2]]) b = array([[2, 3], [2, 3]]) res = [atleast_1d(a), atleast_1d(b)] desired = [a, b] assert_array_equal(res, desired) def test_3D_array(self): a = array([[1, 2], [1, 2]]) b = array([[2, 3], [2, 3]]) a = array([a, a]) b = array([b, b]) res = [atleast_1d(a), atleast_1d(b)] desired = [a, b] assert_array_equal(res, desired) def test_r1array(self): """ Test to make sure equivalent Travis O's r1array function """ assert_(atleast_1d(3).shape == (1,)) assert_(atleast_1d(3j).shape == (1,)) assert_(atleast_1d(3.0).shape == (1,)) assert_(atleast_1d([[2, 3], [4, 5]]).shape == (2, 2)) class TestAtleast2d: def test_0D_array(self): a = array(1) b = array(2) res = [atleast_2d(a), atleast_2d(b)] desired = [array([[1]]), array([[2]])] assert_array_equal(res, desired) def test_1D_array(self): a = array([1, 2]) b = array([2, 3]) res = [atleast_2d(a), atleast_2d(b)] desired = [array([[1, 2]]), array([[2, 3]])] assert_array_equal(res, desired) def test_2D_array(self): a = array([[1, 2], [1, 2]]) b = array([[2, 3], [2, 3]]) res = [atleast_2d(a), atleast_2d(b)] desired = [a, b] assert_array_equal(res, desired) def test_3D_array(self): a = array([[1, 2], [1, 2]]) b = array([[2, 3], [2, 3]]) a = array([a, a]) b = array([b, b]) res = [atleast_2d(a), atleast_2d(b)] desired = [a, b] assert_array_equal(res, desired) def test_r2array(self): """ Test to make sure equivalent Travis O's r2array function """ assert_(atleast_2d(3).shape == (1, 1)) assert_(atleast_2d([3j, 1]).shape == (1, 2)) assert_(atleast_2d([[[3, 1], [4, 5]], [[3, 5], [1, 2]]]).shape == (2, 2, 2)) class TestAtleast3d: def test_0D_array(self): a = array(1) b = array(2) res = [atleast_3d(a), atleast_3d(b)] desired = [array([[[1]]]), array([[[2]]])] assert_array_equal(res, desired) def test_1D_array(self): a = array([1, 2]) b = array([2, 3]) res = [atleast_3d(a), atleast_3d(b)] desired = [array([[[1], [2]]]), array([[[2], [3]]])] assert_array_equal(res, desired) def test_2D_array(self): a = array([[1, 2], [1, 2]]) b = array([[2, 3], [2, 3]]) res = [atleast_3d(a), atleast_3d(b)] desired = [a[:,:, newaxis], b[:,:, newaxis]] assert_array_equal(res, desired) def test_3D_array(self): a = array([[1, 2], [1, 2]]) b = array([[2, 3], [2, 3]]) a = array([a, a]) b = array([b, b]) res = [atleast_3d(a), atleast_3d(b)] desired = [a, b] assert_array_equal(res, desired) class TestHstack: def test_non_iterable(self): assert_raises(TypeError, hstack, 1) def test_empty_input(self): assert_raises(ValueError, hstack, ()) def test_0D_array(self): a = array(1) b = array(2) res = hstack([a, b]) desired = array([1, 2]) assert_array_equal(res, desired) def test_1D_array(self): a = array([1]) b = array([2]) res = hstack([a, b]) desired = array([1, 2]) assert_array_equal(res, desired) def test_2D_array(self): a = array([[1], [2]]) b = array([[1], [2]]) res = hstack([a, b]) desired = array([[1, 1], [2, 2]]) assert_array_equal(res, desired) def test_generator(self): with assert_warns(FutureWarning): hstack((np.arange(3) for _ in range(2))) with assert_warns(FutureWarning): hstack(map(lambda x: x, np.ones((3, 2)))) class TestVstack: def test_non_iterable(self): assert_raises(TypeError, vstack, 1) def test_empty_input(self): assert_raises(ValueError, vstack, ()) def test_0D_array(self): a = array(1) b = array(2) res = vstack([a, b]) desired = array([[1], [2]]) assert_array_equal(res, desired) def test_1D_array(self): a = array([1]) b = array([2]) res = vstack([a, b]) desired = array([[1], [2]]) assert_array_equal(res, desired) def test_2D_array(self): a = array([[1], [2]]) b = array([[1], [2]]) res = vstack([a, b]) desired = array([[1], [2], [1], [2]]) assert_array_equal(res, desired) def test_2D_array2(self): a = array([1, 2]) b = array([1, 2]) res = vstack([a, b]) desired = array([[1, 2], [1, 2]]) assert_array_equal(res, desired) def test_generator(self): with assert_warns(FutureWarning): vstack((np.arange(3) for _ in range(2))) class TestConcatenate: def test_returns_copy(self): a = np.eye(3) b = np.concatenate([a]) b[0, 0] = 2 assert b[0, 0] != a[0, 0] def test_exceptions(self): # test axis must be in bounds for ndim in [1, 2, 3]: a = np.ones((1,)*ndim) np.concatenate((a, a), axis=0) # OK assert_raises(np.AxisError, np.concatenate, (a, a), axis=ndim) assert_raises(np.AxisError, np.concatenate, (a, a), axis=-(ndim + 1)) # Scalars cannot be concatenated assert_raises(ValueError, concatenate, (0,)) assert_raises(ValueError, concatenate, (np.array(0),)) # dimensionality must match assert_raises_regex( ValueError, r"all the input arrays must have same number of dimensions, but " r"the array at index 0 has 1 dimension\(s\) and the array at " r"index 1 has 2 dimension\(s\)", np.concatenate, (np.zeros(1), np.zeros((1, 1)))) # test shapes must match except for concatenation axis a = np.ones((1, 2, 3)) b = np.ones((2, 2, 3)) axis = list(range(3)) for i in range(3): np.concatenate((a, b), axis=axis[0]) # OK assert_raises_regex( ValueError, "all the input array dimensions for the concatenation axis " "must match exactly, but along dimension {}, the array at " "index 0 has size 1 and the array at index 1 has size 2" .format(i), np.concatenate, (a, b), axis=axis[1]) assert_raises(ValueError, np.concatenate, (a, b), axis=axis[2]) a = np.moveaxis(a, -1, 0) b = np.moveaxis(b, -1, 0) axis.append(axis.pop(0)) # No arrays to concatenate raises ValueError assert_raises(ValueError, concatenate, ()) def test_concatenate_axis_None(self): a = np.arange(4, dtype=np.float64).reshape((2, 2)) b = list(range(3)) c = ['x'] r = np.concatenate((a, a), axis=None) assert_equal(r.dtype, a.dtype) assert_equal(r.ndim, 1) r = np.concatenate((a, b), axis=None) assert_equal(r.size, a.size + len(b)) assert_equal(r.dtype, a.dtype) r = np.concatenate((a, b, c), axis=None, dtype="U") d = array(['0.0', '1.0', '2.0', '3.0', '0', '1', '2', 'x']) assert_array_equal(r, d) out = np.zeros(a.size + len(b)) r = np.concatenate((a, b), axis=None) rout = np.concatenate((a, b), axis=None, out=out) assert_(out is rout) assert_equal(r, rout) def test_large_concatenate_axis_None(self): # When no axis is given, concatenate uses flattened versions. # This also had a bug with many arrays (see gh-5979). x = np.arange(1, 100) r = np.concatenate(x, None) assert_array_equal(x, r) # This should probably be deprecated: r = np.concatenate(x, 100) # axis is >= MAXDIMS assert_array_equal(x, r) def test_concatenate(self): # Test concatenate function # One sequence returns unmodified (but as array) r4 = list(range(4)) assert_array_equal(concatenate((r4,)), r4) # Any sequence assert_array_equal(concatenate((tuple(r4),)), r4) assert_array_equal(concatenate((array(r4),)), r4) # 1D default concatenation r3 = list(range(3)) assert_array_equal(concatenate((r4, r3)), r4 + r3) # Mixed sequence types assert_array_equal(concatenate((tuple(r4), r3)), r4 + r3) assert_array_equal(concatenate((array(r4), r3)), r4 + r3) # Explicit axis specification assert_array_equal(concatenate((r4, r3), 0), r4 + r3) # Including negative assert_array_equal(concatenate((r4, r3), -1), r4 + r3) # 2D a23 = array([[10, 11, 12], [13, 14, 15]]) a13 = array([[0, 1, 2]]) res = array([[10, 11, 12], [13, 14, 15], [0, 1, 2]]) assert_array_equal(concatenate((a23, a13)), res) assert_array_equal(concatenate((a23, a13), 0), res) assert_array_equal(concatenate((a23.T, a13.T), 1), res.T) assert_array_equal(concatenate((a23.T, a13.T), -1), res.T) # Arrays much match shape assert_raises(ValueError, concatenate, (a23.T, a13.T), 0) # 3D res = arange(2 * 3 * 7).reshape((2, 3, 7)) a0 = res[..., :4] a1 = res[..., 4:6] a2 = res[..., 6:] assert_array_equal(concatenate((a0, a1, a2), 2), res) assert_array_equal(concatenate((a0, a1, a2), -1), res) assert_array_equal(concatenate((a0.T, a1.T, a2.T), 0), res.T) out = res.copy() rout = concatenate((a0, a1, a2), 2, out=out) assert_(out is rout) assert_equal(res, rout) @pytest.mark.skipif(IS_PYPY, reason="PYPY handles sq_concat, nb_add differently than cpython") def test_operator_concat(self): import operator a = array([1, 2]) b = array([3, 4]) n = [1,2] res = array([1, 2, 3, 4]) assert_raises(TypeError, operator.concat, a, b) assert_raises(TypeError, operator.concat, a, n) assert_raises(TypeError, operator.concat, n, a) assert_raises(TypeError, operator.concat, a, 1) assert_raises(TypeError, operator.concat, 1, a) def test_bad_out_shape(self): a = array([1, 2]) b = array([3, 4]) assert_raises(ValueError, concatenate, (a, b), out=np.empty(5)) assert_raises(ValueError, concatenate, (a, b), out=np.empty((4,1))) assert_raises(ValueError, concatenate, (a, b), out=np.empty((1,4))) concatenate((a, b), out=np.empty(4)) @pytest.mark.parametrize("axis", [None, 0]) @pytest.mark.parametrize("out_dtype", ["c8", "f4", "f8", ">f8", "i8", "S4"]) @pytest.mark.parametrize("casting", ['no', 'equiv', 'safe', 'same_kind', 'unsafe']) def test_out_and_dtype(self, axis, out_dtype, casting): # Compare usage of `out=out` with `dtype=out.dtype` out = np.empty(4, dtype=out_dtype) to_concat = (array([1.1, 2.2]), array([3.3, 4.4])) if not np.can_cast(to_concat[0], out_dtype, casting=casting): with assert_raises(TypeError): concatenate(to_concat, out=out, axis=axis, casting=casting) with assert_raises(TypeError): concatenate(to_concat, dtype=out.dtype, axis=axis, casting=casting) else: res_out = concatenate(to_concat, out=out, axis=axis, casting=casting) res_dtype = concatenate(to_concat, dtype=out.dtype, axis=axis, casting=casting) assert res_out is out assert_array_equal(out, res_dtype) assert res_dtype.dtype == out_dtype with assert_raises(TypeError): concatenate(to_concat, out=out, dtype=out_dtype, axis=axis) @pytest.mark.parametrize("axis", [None, 0]) @pytest.mark.parametrize("string_dt", ["S", "U", "S0", "U0"]) @pytest.mark.parametrize("arrs", [([0.],), ([0.], [1]), ([0], ["string"], [1.])]) def test_dtype_with_promotion(self, arrs, string_dt, axis): # Note that U0 and S0 should be deprecated eventually and changed to # actually give the empty string result (together with `np.array`) res = np.concatenate(arrs, axis=axis, dtype=string_dt, casting="unsafe") # The actual dtype should be identical to a cast (of a double array): assert res.dtype == np.array(1.).astype(string_dt).dtype @pytest.mark.parametrize("axis", [None, 0]) def test_string_dtype_does_not_inspect(self, axis): # The error here currently depends on NPY_USE_NEW_CASTINGIMPL as # the new version rejects using the "default string length" of 64. # The new behaviour is better, `np.array()` and `arr.astype()` would # have to be used instead. (currently only raises due to unsafe cast) with pytest.raises((ValueError, TypeError)): np.concatenate(([None], [1]), dtype="S", axis=axis) with pytest.raises((ValueError, TypeError)): np.concatenate(([None], [1]), dtype="U", axis=axis) @pytest.mark.parametrize("axis", [None, 0]) def test_subarray_error(self, axis): with pytest.raises(TypeError, match=".*subarray dtype"): np.concatenate(([1], [1]), dtype="(2,)i", axis=axis) def test_stack(): # non-iterable input assert_raises(TypeError, stack, 1) # 0d input for input_ in [(1, 2, 3), [np.int32(1), np.int32(2), np.int32(3)], [np.array(1), np.array(2), np.array(3)]]: assert_array_equal(stack(input_), [1, 2, 3]) # 1d input examples a = np.array([1, 2, 3]) b = np.array([4, 5, 6]) r1 = array([[1, 2, 3], [4, 5, 6]]) assert_array_equal(np.stack((a, b)), r1) assert_array_equal(np.stack((a, b), axis=1), r1.T) # all input types assert_array_equal(np.stack(list([a, b])), r1) assert_array_equal(np.stack(array([a, b])), r1) # all shapes for 1d input arrays = [np.random.randn(3) for _ in range(10)] axes = [0, 1, -1, -2] expected_shapes = [(10, 3), (3, 10), (3, 10), (10, 3)] for axis, expected_shape in zip(axes, expected_shapes): assert_equal(np.stack(arrays, axis).shape, expected_shape) assert_raises_regex(np.AxisError, 'out of bounds', stack, arrays, axis=2) assert_raises_regex(np.AxisError, 'out of bounds', stack, arrays, axis=-3) # all shapes for 2d input arrays = [np.random.randn(3, 4) for _ in range(10)] axes = [0, 1, 2, -1, -2, -3] expected_shapes = [(10, 3, 4), (3, 10, 4), (3, 4, 10), (3, 4, 10), (3, 10, 4), (10, 3, 4)] for axis, expected_shape in zip(axes, expected_shapes): assert_equal(np.stack(arrays, axis).shape, expected_shape) # empty arrays assert_(stack([[], [], []]).shape == (3, 0)) assert_(stack([[], [], []], axis=1).shape == (0, 3)) # out out = np.zeros_like(r1) np.stack((a, b), out=out) assert_array_equal(out, r1) # edge cases assert_raises_regex(ValueError, 'need at least one array', stack, []) assert_raises_regex(ValueError, 'must have the same shape', stack, [1, np.arange(3)]) assert_raises_regex(ValueError, 'must have the same shape', stack, [np.arange(3), 1]) assert_raises_regex(ValueError, 'must have the same shape', stack, [np.arange(3), 1], axis=1) assert_raises_regex(ValueError, 'must have the same shape', stack, [np.zeros((3, 3)), np.zeros(3)], axis=1) assert_raises_regex(ValueError, 'must have the same shape', stack, [np.arange(2), np.arange(3)]) # generator is deprecated with assert_warns(FutureWarning): result = stack((x for x in range(3))) assert_array_equal(result, np.array([0, 1, 2])) class TestBlock: @pytest.fixture(params=['block', 'force_concatenate', 'force_slicing']) def block(self, request): # blocking small arrays and large arrays go through different paths. # the algorithm is triggered depending on the number of element # copies required. # We define a test fixture that forces most tests to go through # both code paths. # Ultimately, this should be removed if a single algorithm is found # to be faster for both small and large arrays. def _block_force_concatenate(arrays): arrays, list_ndim, result_ndim, _ = _block_setup(arrays) return _block_concatenate(arrays, list_ndim, result_ndim) def _block_force_slicing(arrays): arrays, list_ndim, result_ndim, _ = _block_setup(arrays) return _block_slicing(arrays, list_ndim, result_ndim) if request.param == 'force_concatenate': return _block_force_concatenate elif request.param == 'force_slicing': return _block_force_slicing elif request.param == 'block': return block else: raise ValueError('Unknown blocking request. There is a typo in the tests.') def test_returns_copy(self, block): a = np.eye(3) b = block(a) b[0, 0] = 2 assert b[0, 0] != a[0, 0] def test_block_total_size_estimate(self, block): _, _, _, total_size = _block_setup([1]) assert total_size == 1 _, _, _, total_size = _block_setup([[1]]) assert total_size == 1 _, _, _, total_size = _block_setup([[1, 1]]) assert total_size == 2 _, _, _, total_size = _block_setup([[1], [1]]) assert total_size == 2 _, _, _, total_size = _block_setup([[1, 2], [3, 4]]) assert total_size == 4 def test_block_simple_row_wise(self, block): a_2d = np.ones((2, 2)) b_2d = 2 * a_2d desired = np.array([[1, 1, 2, 2], [1, 1, 2, 2]]) result = block([a_2d, b_2d]) assert_equal(desired, result) def test_block_simple_column_wise(self, block): a_2d = np.ones((2, 2)) b_2d = 2 * a_2d expected = np.array([[1, 1], [1, 1], [2, 2], [2, 2]]) result = block([[a_2d], [b_2d]]) assert_equal(expected, result) def test_block_with_1d_arrays_row_wise(self, block): # # # 1-D vectors are treated as row arrays a = np.array([1, 2, 3]) b = np.array([2, 3, 4]) expected = np.array([1, 2, 3, 2, 3, 4]) result = block([a, b]) assert_equal(expected, result) def test_block_with_1d_arrays_multiple_rows(self, block): a = np.array([1, 2, 3]) b = np.array([2, 3, 4]) expected = np.array([[1, 2, 3, 2, 3, 4], [1, 2, 3, 2, 3, 4]]) result = block([[a, b], [a, b]]) assert_equal(expected, result) def test_block_with_1d_arrays_column_wise(self, block): # # # 1-D vectors are treated as row arrays a_1d = np.array([1, 2, 3]) b_1d = np.array([2, 3, 4]) expected = np.array([[1, 2, 3], [2, 3, 4]]) result = block([[a_1d], [b_1d]]) assert_equal(expected, result) def test_block_mixed_1d_and_2d(self, block): a_2d = np.ones((2, 2)) b_1d = np.array([2, 2]) result = block([[a_2d], [b_1d]]) expected = np.array([[1, 1], [1, 1], [2, 2]]) assert_equal(expected, result) def test_block_complicated(self, block): # a bit more complicated one_2d = np.array([[1, 1, 1]]) two_2d = np.array([[2, 2, 2]]) three_2d = np.array([[3, 3, 3, 3, 3, 3]]) four_1d = np.array([4, 4, 4, 4, 4, 4]) five_0d = np.array(5) six_1d = np.array([6, 6, 6, 6, 6]) zero_2d = np.zeros((2, 6)) expected = np.array([[1, 1, 1, 2, 2, 2], [3, 3, 3, 3, 3, 3], [4, 4, 4, 4, 4, 4], [5, 6, 6, 6, 6, 6], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0]]) result = block([[one_2d, two_2d], [three_2d], [four_1d], [five_0d, six_1d], [zero_2d]]) assert_equal(result, expected) def test_nested(self, block): one = np.array([1, 1, 1]) two = np.array([[2, 2, 2], [2, 2, 2], [2, 2, 2]]) three = np.array([3, 3, 3]) four = np.array([4, 4, 4]) five = np.array(5) six = np.array([6, 6, 6, 6, 6]) zero = np.zeros((2, 6)) result = block([ [ block([ [one], [three], [four] ]), two ], [five, six], [zero] ]) expected = np.array([[1, 1, 1, 2, 2, 2], [3, 3, 3, 2, 2, 2], [4, 4, 4, 2, 2, 2], [5, 6, 6, 6, 6, 6], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0]]) assert_equal(result, expected) def test_3d(self, block): a000 = np.ones((2, 2, 2), int) * 1 a100 = np.ones((3, 2, 2), int) * 2 a010 = np.ones((2, 3, 2), int) * 3 a001 = np.ones((2, 2, 3), int) * 4 a011 = np.ones((2, 3, 3), int) * 5 a101 = np.ones((3, 2, 3), int) * 6 a110 = np.ones((3, 3, 2), int) * 7 a111 = np.ones((3, 3, 3), int) * 8 result = block([ [ [a000, a001], [a010, a011], ], [ [a100, a101], [a110, a111], ] ]) expected = array([[[1, 1, 4, 4, 4], [1, 1, 4, 4, 4], [3, 3, 5, 5, 5], [3, 3, 5, 5, 5], [3, 3, 5, 5, 5]], [[1, 1, 4, 4, 4], [1, 1, 4, 4, 4], [3, 3, 5, 5, 5], [3, 3, 5, 5, 5], [3, 3, 5, 5, 5]], [[2, 2, 6, 6, 6], [2, 2, 6, 6, 6], [7, 7, 8, 8, 8], [7, 7, 8, 8, 8], [7, 7, 8, 8, 8]], [[2, 2, 6, 6, 6], [2, 2, 6, 6, 6], [7, 7, 8, 8, 8], [7, 7, 8, 8, 8], [7, 7, 8, 8, 8]], [[2, 2, 6, 6, 6], [2, 2, 6, 6, 6], [7, 7, 8, 8, 8], [7, 7, 8, 8, 8], [7, 7, 8, 8, 8]]]) assert_array_equal(result, expected) def test_block_with_mismatched_shape(self, block): a = np.array([0, 0]) b = np.eye(2) assert_raises(ValueError, block, [a, b]) assert_raises(ValueError, block, [b, a]) to_block = [[np.ones((2,3)), np.ones((2,2))], [np.ones((2,2)), np.ones((2,2))]] assert_raises(ValueError, block, to_block) def test_no_lists(self, block): assert_equal(block(1), np.array(1)) assert_equal(block(np.eye(3)), np.eye(3)) def test_invalid_nesting(self, block): msg = 'depths are mismatched' assert_raises_regex(ValueError, msg, block, [1, [2]]) assert_raises_regex(ValueError, msg, block, [1, []]) assert_raises_regex(ValueError, msg, block, [[1], 2]) assert_raises_regex(ValueError, msg, block, [[], 2]) assert_raises_regex(ValueError, msg, block, [ [[1], [2]], [[3, 4]], [5] # missing brackets ]) def test_empty_lists(self, block): assert_raises_regex(ValueError, 'empty', block, []) assert_raises_regex(ValueError, 'empty', block, [[]]) assert_raises_regex(ValueError, 'empty', block, [[1], []]) def test_tuple(self, block): assert_raises_regex(TypeError, 'tuple', block, ([1, 2], [3, 4])) assert_raises_regex(TypeError, 'tuple', block, [(1, 2), (3, 4)]) def test_different_ndims(self, block): a = 1. b = 2 * np.ones((1, 2)) c = 3 * np.ones((1, 1, 3)) result = block([a, b, c]) expected = np.array([[[1., 2., 2., 3., 3., 3.]]]) assert_equal(result, expected) def test_different_ndims_depths(self, block): a = 1. b = 2 * np.ones((1, 2)) c = 3 * np.ones((1, 2, 3)) result = block([[a, b], [c]]) expected = np.array([[[1., 2., 2.], [3., 3., 3.], [3., 3., 3.]]]) assert_equal(result, expected) def test_block_memory_order(self, block): # 3D arr_c = np.zeros((3,)*3, order='C') arr_f = np.zeros((3,)*3, order='F') b_c = [[[arr_c, arr_c], [arr_c, arr_c]], [[arr_c, arr_c], [arr_c, arr_c]]] b_f = [[[arr_f, arr_f], [arr_f, arr_f]], [[arr_f, arr_f], [arr_f, arr_f]]] assert block(b_c).flags['C_CONTIGUOUS'] assert block(b_f).flags['F_CONTIGUOUS'] arr_c = np.zeros((3, 3), order='C') arr_f = np.zeros((3, 3), order='F') # 2D b_c = [[arr_c, arr_c], [arr_c, arr_c]] b_f = [[arr_f, arr_f], [arr_f, arr_f]] assert block(b_c).flags['C_CONTIGUOUS'] assert block(b_f).flags['F_CONTIGUOUS'] def test_block_dispatcher(): class ArrayLike: pass a = ArrayLike() b = ArrayLike() c = ArrayLike() assert_equal(list(_block_dispatcher(a)), [a]) assert_equal(list(_block_dispatcher([a])), [a]) assert_equal(list(_block_dispatcher([a, b])), [a, b]) assert_equal(list(_block_dispatcher([[a], [b, [c]]])), [a, b, c]) # don't recurse into non-lists assert_equal(list(_block_dispatcher((a, b))), [(a, b)])
2026-03-31T15:30:28
codeparrot_clean
b6c51f6353d92c1019fd6681b60624fe
code
# -*- 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 import openerp.addons.decimal_precision as dp class membership_invoice(osv.osv_memory): """Membership Invoice""" _name = "membership.invoice" _description = "Membership Invoice" _columns = { 'product_id': fields.many2one('product.product','Membership', required=True), 'member_price': fields.float('Member Price', digits_compute= dp.get_precision('Product Price'), required=True), } def onchange_product(self, cr, uid, ids, product_id=False): """This function returns value of product's member price based on product id. """ if not product_id: return {'value': {'member_price': False}} return {'value': {'member_price': self.pool.get('product.product').price_get(cr, uid, [product_id])[product_id]}} def membership_invoice(self, cr, uid, ids, context=None): mod_obj = self.pool.get('ir.model.data') partner_obj = self.pool.get('res.partner') datas = {} if context is None: context = {} data = self.browse(cr, uid, ids, context=context) if data: data = data[0] datas = { 'membership_product_id': data.product_id.id, 'amount': data.member_price } invoice_list = partner_obj.create_membership_invoice(cr, uid, context.get('active_ids', []), datas=datas, context=context) try: search_view_id = mod_obj.get_object_reference(cr, uid, 'account', 'view_account_invoice_filter')[1] except ValueError: search_view_id = False try: form_view_id = mod_obj.get_object_reference(cr, uid, 'account', 'invoice_form')[1] except ValueError: form_view_id = False return { 'domain': [('id', 'in', invoice_list)], 'name': 'Membership Invoices', 'view_type': 'form', 'view_mode': 'tree,form', 'res_model': 'account.invoice', 'type': 'ir.actions.act_window', 'views': [(False, 'tree'), (form_view_id, 'form')], 'search_view_id': search_view_id, } # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
2026-03-31T15:30:28
codeparrot_clean
15cffd52a1ac360e55605054da6bb453
code
# coding: utf-8 # pylint: disable=missing-docstring, invalid-name import flask import auth import config import model from main import app dropbox_config = dict( access_token_method='POST', access_token_url='https://api.dropbox.com/1/oauth2/token', authorize_url='https://www.dropbox.com/1/oauth2/authorize', base_url='https://www.dropbox.com/1/', consumer_key=config.CONFIG_DB.auth_dropbox_id, consumer_secret=config.CONFIG_DB.auth_dropbox_secret, ) dropbox = auth.create_oauth_app(dropbox_config, 'dropbox') @app.route('/_s/callback/dropbox/oauth-authorized/') def dropbox_authorized(): response = dropbox.authorized_response() if response is None: flask.flash('You denied the request to sign in.') return flask.redirect(flask.url_for('index')) flask.session['oauth_token'] = (response['access_token'], '') me = dropbox.get('account/info') user_db = retrieve_user_from_dropbox(me.data) return auth.signin_via_social(user_db) @dropbox.tokengetter def get_dropbox_oauth_token(): return flask.session.get('oauth_token') @app.route('/signin/dropbox/') def signin_dropbox(): scheme = 'https' if config.PRODUCTION else 'http' return auth.signin_oauth(dropbox, scheme) def retrieve_user_from_dropbox(response): auth_id = 'dropbox_%s' % response['uid'] user_db = model.User.get_by('auth_ids', auth_id) if user_db: return user_db return auth.create_or_get_user_db( auth_id=auth_id, email=response['email'], name=response['display_name'], username=response['display_name'], verified=True )
2026-03-31T15:30:28
codeparrot_clean
ca699f9e1cbdacee1db5fb2a8811e4f2
code
# encoding: utf-8 # module PyKDE4.kdeui # from /usr/lib/python3/dist-packages/PyKDE4/kdeui.cpython-34m-x86_64-linux-gnu.so # by generator 1.135 # no doc # imports import PyKDE4.kdecore as __PyKDE4_kdecore import PyQt4.QtCore as __PyQt4_QtCore import PyQt4.QtGui as __PyQt4_QtGui import PyQt4.QtSvg as __PyQt4_QtSvg class KButtonGroup(__PyQt4_QtGui.QGroupBox): # no doc def changed(self, *args, **kwargs): # real signature unknown pass def childEvent(self, *args, **kwargs): # real signature unknown pass def clicked(self, *args, **kwargs): # real signature unknown pass def id(self, *args, **kwargs): # real signature unknown pass def pressed(self, *args, **kwargs): # real signature unknown pass def released(self, *args, **kwargs): # real signature unknown pass def selected(self, *args, **kwargs): # real signature unknown pass def setSelected(self, *args, **kwargs): # real signature unknown pass def __init__(self, *args, **kwargs): # real signature unknown pass
2026-03-31T15:30:28
codeparrot_clean
0fc6152a9dc59b2bd67a4d29827ff008
code
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import print_function from setuptools import setup from setuptools.command.test import test as TestCommand import codecs import os import re here = os.path.abspath(os.path.dirname(__file__)) def read(*parts): # intentionally *not* adding an encoding option to open return codecs.open(os.path.join(here, *parts), 'r').read() def read(*parts): # intentionally *not* adding an encoding option to open return codecs.open(os.path.join(here, *parts), 'r').read() def find_version(*file_paths): version_file = read(*file_paths) version_match = re.search(r"^__version__ = ['\"]([^'\"]*)['\"]", version_file, re.M) if version_match: return version_match.group(1) raise RuntimeError("Unable to find version string.") long_description = read('README.rst') def check_dependencies(): import os on_rtd = os.environ.get('READTHEDOCS', None) == 'True' if on_rtd: return # Just make sure dependencies exist, I haven't rigorously # tested what the minimal versions that will work are # (help on that would be awesome) try: import numpy except ImportError: raise ImportError("pambox requires numpy") try: import scipy except ImportError: raise ImportError("pambox requires scipy") try: import matplotlib except ImportError: raise ImportError("pambox requires matplotlib") try: import pandas except ImportError: raise ImportError("pambox requires pandas") class PyTest(TestCommand): def finalize_options(self): TestCommand.finalize_options(self) self.test_args = ['--runslow', 'pambox/tests'] self.test_suite = True def run_tests(self): import pytest errcode = pytest.main(self.test_args) sys.exit(errcode) if __name__ == '__main__': import sys if not (len(sys.argv) >= 2 and ('--help' in sys.argv[1:] or sys.argv[1] in ('--help-commands', 'egg_info', '--version', 'clean'))): check_dependencies() setup( name='pambox', description='A Python toolbox for auditory modeling', author='Alexandre Chabot-Leclerc', author_email='pambox@alex.alexchabot.net', version=find_version('pambox', '__init__.py'), url='https://bitbucket.org/achabotl/pambox', license='Modified BSD License', tests_require=['pytest'], install_requires=[ 'six>=1.4.1', ], cmdclass={'test': PyTest}, long_description=long_description, packages=['pambox'], include_package_data=True, platforms='any', test_suite='pambox.tests', classifiers=[ 'Development Status :: 3 - Alpha', 'Intended Audience :: Science/Research', 'License :: OSI Approved :: BSD License', 'Natural Language :: English', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.4', 'Topic :: Scientific/Engineering', 'Operating System :: POSIX', 'Operating System :: Unix', 'Operating System :: MacOS' ], extras_require={ 'testing': ['pytest'] } )
2026-03-31T15:30:28
codeparrot_clean
5998dad6a2a6ff6980314f59470dc4fa
code
# Copyright (C) 2011 Midokura KK # Copyright (C) 2011 Nicira, Inc # Copyright 2011 OpenStack Foundation # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. """VIF drivers for libvirt.""" import copy from oslo.config import cfg from nova import exception from nova.i18n import _ from nova.i18n import _LE from nova.network import linux_net from nova.network import model as network_model from nova.openstack.common import log as logging from nova.openstack.common import processutils from nova import utils from nova.virt.libvirt import config as vconfig from nova.virt.libvirt import designer LOG = logging.getLogger(__name__) libvirt_vif_opts = [ cfg.BoolOpt('use_virtio_for_bridges', default=True, help='Use virtio for bridge interfaces with KVM/QEMU'), ] CONF = cfg.CONF CONF.register_opts(libvirt_vif_opts, 'libvirt') CONF.import_opt('use_ipv6', 'nova.netconf') DEV_PREFIX_ETH = 'eth' def is_vif_model_valid_for_virt(virt_type, vif_model): valid_models = { 'qemu': [network_model.VIF_MODEL_VIRTIO, network_model.VIF_MODEL_NE2K_PCI, network_model.VIF_MODEL_PCNET, network_model.VIF_MODEL_RTL8139, network_model.VIF_MODEL_E1000, network_model.VIF_MODEL_SPAPR_VLAN], 'kvm': [network_model.VIF_MODEL_VIRTIO, network_model.VIF_MODEL_NE2K_PCI, network_model.VIF_MODEL_PCNET, network_model.VIF_MODEL_RTL8139, network_model.VIF_MODEL_E1000, network_model.VIF_MODEL_SPAPR_VLAN], 'xen': [network_model.VIF_MODEL_NETFRONT, network_model.VIF_MODEL_NE2K_PCI, network_model.VIF_MODEL_PCNET, network_model.VIF_MODEL_RTL8139, network_model.VIF_MODEL_E1000], 'lxc': [], 'uml': [], } if vif_model is None: return True if virt_type not in valid_models: raise exception.UnsupportedVirtType(virt=virt_type) return vif_model in valid_models[virt_type] class LibvirtGenericVIFDriver(object): """Generic VIF driver for libvirt networking.""" def __init__(self, get_connection): self.get_connection = get_connection def _normalize_vif_type(self, vif_type): return vif_type.replace('2.1q', '2q') def get_vif_devname(self, vif): if 'devname' in vif: return vif['devname'] return ("nic" + vif['id'])[:network_model.NIC_NAME_LEN] def get_vif_devname_with_prefix(self, vif, prefix): devname = self.get_vif_devname(vif) return prefix + devname[3:] def get_base_config(self, instance, vif, image_meta, inst_type, virt_type): conf = vconfig.LibvirtConfigGuestInterface() # Default to letting libvirt / the hypervisor choose the model model = None driver = None # If the user has specified a 'vif_model' against the # image then honour that model if image_meta: vif_model = image_meta.get('properties', {}).get('hw_vif_model') if vif_model is not None: model = vif_model # Else if the virt type is KVM/QEMU, use virtio according # to the global config parameter if (model is None and virt_type in ('kvm', 'qemu') and CONF.libvirt.use_virtio_for_bridges): model = network_model.VIF_MODEL_VIRTIO # Workaround libvirt bug, where it mistakenly # enables vhost mode, even for non-KVM guests if (model == network_model.VIF_MODEL_VIRTIO and virt_type == "qemu"): driver = "qemu" if not is_vif_model_valid_for_virt(virt_type, model): raise exception.UnsupportedHardware(model=model, virt=virt_type) designer.set_vif_guest_frontend_config( conf, vif['address'], model, driver) return conf def get_bridge_name(self, vif): return vif['network']['bridge'] def get_ovs_interfaceid(self, vif): return vif.get('ovs_interfaceid') or vif['id'] def get_br_name(self, iface_id): return ("qbr" + iface_id)[:network_model.NIC_NAME_LEN] def get_veth_pair_names(self, iface_id): return (("qvb%s" % iface_id)[:network_model.NIC_NAME_LEN], ("qvo%s" % iface_id)[:network_model.NIC_NAME_LEN]) def get_firewall_required(self, vif): if vif.is_neutron_filtering_enabled(): return False if CONF.firewall_driver != "nova.virt.firewall.NoopFirewallDriver": return True return False def get_config_bridge(self, instance, vif, image_meta, inst_type, virt_type): """Get VIF configurations for bridge type.""" conf = self.get_base_config(instance, vif, image_meta, inst_type, virt_type) designer.set_vif_host_backend_bridge_config( conf, self.get_bridge_name(vif), self.get_vif_devname(vif)) mac_id = vif['address'].replace(':', '') name = "nova-instance-" + instance['name'] + "-" + mac_id if self.get_firewall_required(vif): conf.filtername = name designer.set_vif_bandwidth_config(conf, inst_type) return conf def get_config_ovs_bridge(self, instance, vif, image_meta, inst_type, virt_type): conf = self.get_base_config(instance, vif, image_meta, inst_type, virt_type) designer.set_vif_host_backend_ovs_config( conf, self.get_bridge_name(vif), self.get_ovs_interfaceid(vif), self.get_vif_devname(vif)) designer.set_vif_bandwidth_config(conf, inst_type) return conf def get_config_ovs_hybrid(self, instance, vif, image_meta, inst_type, virt_type): newvif = copy.deepcopy(vif) newvif['network']['bridge'] = self.get_br_name(vif['id']) return self.get_config_bridge(instance, newvif, image_meta, inst_type, virt_type) def get_config_ovs(self, instance, vif, image_meta, inst_type, virt_type): if self.get_firewall_required(vif) or vif.is_hybrid_plug_enabled(): return self.get_config_ovs_hybrid(instance, vif, image_meta, inst_type, virt_type) else: return self.get_config_ovs_bridge(instance, vif, image_meta, inst_type, virt_type) def get_config_ivs_hybrid(self, instance, vif, image_meta, inst_type, virt_type): newvif = copy.deepcopy(vif) newvif['network']['bridge'] = self.get_br_name(vif['id']) return self.get_config_bridge(instance, newvif, image_meta, inst_type, virt_type) def get_config_ivs_ethernet(self, instance, vif, image_meta, inst_type, virt_type): conf = self.get_base_config(instance, vif, image_meta, inst_type, virt_type) dev = self.get_vif_devname(vif) designer.set_vif_host_backend_ethernet_config(conf, dev) return conf def get_config_ivs(self, instance, vif, image_meta, inst_type, virt_type): if self.get_firewall_required(vif) or vif.is_hybrid_plug_enabled(): return self.get_config_ivs_hybrid(instance, vif, image_meta, inst_type, virt_type) else: return self.get_config_ivs_ethernet(instance, vif, image_meta, inst_type, virt_type) def get_config_802qbg(self, instance, vif, image_meta, inst_type, virt_type): conf = self.get_base_config(instance, vif, image_meta, inst_type, virt_type) params = vif["qbg_params"] designer.set_vif_host_backend_802qbg_config( conf, vif['network'].get_meta('interface'), params['managerid'], params['typeid'], params['typeidversion'], params['instanceid']) designer.set_vif_bandwidth_config(conf, inst_type) return conf def get_config_802qbh(self, instance, vif, image_meta, inst_type, virt_type): conf = self.get_base_config(instance, vif, image_meta, inst_type, virt_type) profile = vif["profile"] vif_details = vif["details"] net_type = 'direct' if vif['vnic_type'] == network_model.VNIC_TYPE_DIRECT: net_type = 'hostdev' designer.set_vif_host_backend_802qbh_config( conf, net_type, profile['pci_slot'], vif_details[network_model.VIF_DETAILS_PROFILEID]) designer.set_vif_bandwidth_config(conf, inst_type) return conf def get_config_hw_veb(self, instance, vif, image_meta, inst_type, virt_type): conf = self.get_base_config(instance, vif, image_meta, inst_type, virt_type) profile = vif["profile"] vif_details = vif["details"] net_type = 'direct' if vif['vnic_type'] == network_model.VNIC_TYPE_DIRECT: net_type = 'hostdev' designer.set_vif_host_backend_hw_veb( conf, net_type, profile['pci_slot'], vif_details[network_model.VIF_DETAILS_VLAN]) designer.set_vif_bandwidth_config(conf, inst_type) return conf def get_config_iovisor(self, instance, vif, image_meta, inst_type, virt_type): conf = self.get_base_config(instance, vif, image_meta, inst_type, virt_type) dev = self.get_vif_devname(vif) designer.set_vif_host_backend_ethernet_config(conf, dev) designer.set_vif_bandwidth_config(conf, inst_type) return conf def get_config_midonet(self, instance, vif, image_meta, inst_type, virt_type): conf = self.get_base_config(instance, vif, image_meta, inst_type, virt_type) dev = self.get_vif_devname(vif) designer.set_vif_host_backend_ethernet_config(conf, dev) return conf def get_config_mlnx_direct(self, instance, vif, image_meta, inst_type, virt_type): conf = self.get_base_config(instance, vif, image_meta, inst_type, virt_type) devname = self.get_vif_devname_with_prefix(vif, DEV_PREFIX_ETH) designer.set_vif_host_backend_direct_config(conf, devname) designer.set_vif_bandwidth_config(conf, inst_type) return conf def get_config(self, instance, vif, image_meta, inst_type, virt_type): vif_type = vif['type'] LOG.debug('vif_type=%(vif_type)s instance=%(instance)s ' 'vif=%(vif)s virt_type%(virt_type)s', {'vif_type': vif_type, 'instance': instance, 'vif': vif, 'virt_type': virt_type}) if vif_type is None: raise exception.NovaException( _("vif_type parameter must be present " "for this vif_driver implementation")) vif_slug = self._normalize_vif_type(vif_type) func = getattr(self, 'get_config_%s' % vif_slug, None) if not func: raise exception.NovaException( _("Unexpected vif_type=%s") % vif_type) return func(instance, vif, image_meta, inst_type, virt_type) def plug_bridge(self, instance, vif): """Ensure that the bridge exists, and add VIF to it.""" network = vif['network'] if (not network.get_meta('multi_host', False) and network.get_meta('should_create_bridge', False)): if network.get_meta('should_create_vlan', False): iface = CONF.vlan_interface or \ network.get_meta('bridge_interface') LOG.debug('Ensuring vlan %(vlan)s and bridge %(bridge)s', {'vlan': network.get_meta('vlan'), 'bridge': self.get_bridge_name(vif)}, instance=instance) linux_net.LinuxBridgeInterfaceDriver.ensure_vlan_bridge( network.get_meta('vlan'), self.get_bridge_name(vif), iface) else: iface = CONF.flat_interface or \ network.get_meta('bridge_interface') LOG.debug("Ensuring bridge %s", self.get_bridge_name(vif), instance=instance) linux_net.LinuxBridgeInterfaceDriver.ensure_bridge( self.get_bridge_name(vif), iface) def plug_ovs_bridge(self, instance, vif): """No manual plugging required.""" pass def plug_ovs_hybrid(self, instance, vif): """Plug using hybrid strategy Create a per-VIF linux bridge, then link that bridge to the OVS integration bridge via a veth device, setting up the other end of the veth device just like a normal OVS port. Then boot the VIF on the linux bridge using standard libvirt mechanisms. """ iface_id = self.get_ovs_interfaceid(vif) br_name = self.get_br_name(vif['id']) v1_name, v2_name = self.get_veth_pair_names(vif['id']) if not linux_net.device_exists(br_name): utils.execute('brctl', 'addbr', br_name, run_as_root=True) utils.execute('brctl', 'setfd', br_name, 0, run_as_root=True) utils.execute('brctl', 'stp', br_name, 'off', run_as_root=True) utils.execute('tee', ('/sys/class/net/%s/bridge/multicast_snooping' % br_name), process_input='0', run_as_root=True, check_exit_code=[0, 1]) if not linux_net.device_exists(v2_name): linux_net._create_veth_pair(v1_name, v2_name) utils.execute('ip', 'link', 'set', br_name, 'up', run_as_root=True) utils.execute('brctl', 'addif', br_name, v1_name, run_as_root=True) linux_net.create_ovs_vif_port(self.get_bridge_name(vif), v2_name, iface_id, vif['address'], instance['uuid']) def plug_ovs(self, instance, vif): if self.get_firewall_required(vif) or vif.is_hybrid_plug_enabled(): self.plug_ovs_hybrid(instance, vif) else: self.plug_ovs_bridge(instance, vif) def plug_ivs_ethernet(self, instance, vif): iface_id = self.get_ovs_interfaceid(vif) dev = self.get_vif_devname(vif) linux_net.create_tap_dev(dev) linux_net.create_ivs_vif_port(dev, iface_id, vif['address'], instance['uuid']) def plug_ivs_hybrid(self, instance, vif): """Plug using hybrid strategy (same as OVS) Create a per-VIF linux bridge, then link that bridge to the OVS integration bridge via a veth device, setting up the other end of the veth device just like a normal IVS port. Then boot the VIF on the linux bridge using standard libvirt mechanisms. """ iface_id = self.get_ovs_interfaceid(vif) br_name = self.get_br_name(vif['id']) v1_name, v2_name = self.get_veth_pair_names(vif['id']) if not linux_net.device_exists(br_name): utils.execute('brctl', 'addbr', br_name, run_as_root=True) utils.execute('brctl', 'setfd', br_name, 0, run_as_root=True) utils.execute('brctl', 'stp', br_name, 'off', run_as_root=True) utils.execute('tee', ('/sys/class/net/%s/bridge/multicast_snooping' % br_name), process_input='0', run_as_root=True, check_exit_code=[0, 1]) if not linux_net.device_exists(v2_name): linux_net._create_veth_pair(v1_name, v2_name) utils.execute('ip', 'link', 'set', br_name, 'up', run_as_root=True) utils.execute('brctl', 'addif', br_name, v1_name, run_as_root=True) linux_net.create_ivs_vif_port(v2_name, iface_id, vif['address'], instance['uuid']) def plug_ivs(self, instance, vif): if self.get_firewall_required(vif) or vif.is_hybrid_plug_enabled(): self.plug_ivs_hybrid(instance, vif) else: self.plug_ivs_ethernet(instance, vif) def plug_mlnx_direct(self, instance, vif): vnic_mac = vif['address'] device_id = instance['uuid'] fabric = vif.get_physical_network() if not fabric: raise exception.NetworkMissingPhysicalNetwork( network_uuid=vif['network']['id']) dev_name = self.get_vif_devname_with_prefix(vif, DEV_PREFIX_ETH) try: utils.execute('ebrctl', 'add-port', vnic_mac, device_id, fabric, network_model.VIF_TYPE_MLNX_DIRECT, dev_name, run_as_root=True) except processutils.ProcessExecutionError: LOG.exception(_LE("Failed while plugging vif"), instance=instance) def plug_802qbg(self, instance, vif): pass def plug_802qbh(self, instance, vif): pass def plug_hw_veb(self, instance, vif): if vif['vnic_type'] == network_model.VNIC_TYPE_MACVTAP: linux_net.set_vf_interface_vlan( vif['profile']['pci_slot'], mac_addr=vif['address'], vlan=vif['details'][network_model.VIF_DETAILS_VLAN]) def plug_midonet(self, instance, vif): """Plug into MidoNet's network port Bind the vif to a MidoNet virtual port. """ dev = self.get_vif_devname(vif) port_id = vif['id'] try: linux_net.create_tap_dev(dev) utils.execute('mm-ctl', '--bind-port', port_id, dev, run_as_root=True) except processutils.ProcessExecutionError: LOG.exception(_LE("Failed while plugging vif"), instance=instance) def plug_iovisor(self, instance, vif): """Plug using PLUMgrid IO Visor Driver Connect a network device to their respective Virtual Domain in PLUMgrid Platform. """ dev = self.get_vif_devname(vif) iface_id = vif['id'] linux_net.create_tap_dev(dev) net_id = vif['network']['id'] tenant_id = instance["project_id"] try: utils.execute('ifc_ctl', 'gateway', 'add_port', dev, run_as_root=True) utils.execute('ifc_ctl', 'gateway', 'ifup', dev, 'access_vm', vif['network']['label'] + "_" + iface_id, vif['address'], 'pgtag2=%s' % net_id, 'pgtag1=%s' % tenant_id, run_as_root=True) except processutils.ProcessExecutionError: LOG.exception(_LE("Failed while plugging vif"), instance=instance) def plug(self, instance, vif): vif_type = vif['type'] LOG.debug('vif_type=%(vif_type)s instance=%(instance)s ' 'vif=%(vif)s', {'vif_type': vif_type, 'instance': instance, 'vif': vif}) if vif_type is None: raise exception.VirtualInterfacePlugException( _("vif_type parameter must be present " "for this vif_driver implementation")) vif_slug = self._normalize_vif_type(vif_type) func = getattr(self, 'plug_%s' % vif_slug, None) if not func: raise exception.VirtualInterfacePlugException( _("Plug vif failed because of unexpected " "vif_type=%s") % vif_type) func(instance, vif) def unplug_bridge(self, instance, vif): """No manual unplugging required.""" pass def unplug_ovs_bridge(self, instance, vif): """No manual unplugging required.""" pass def unplug_ovs_hybrid(self, instance, vif): """UnPlug using hybrid strategy Unhook port from OVS, unhook port from bridge, delete bridge, and delete both veth devices. """ try: br_name = self.get_br_name(vif['id']) v1_name, v2_name = self.get_veth_pair_names(vif['id']) if linux_net.device_exists(br_name): utils.execute('brctl', 'delif', br_name, v1_name, run_as_root=True) utils.execute('ip', 'link', 'set', br_name, 'down', run_as_root=True) utils.execute('brctl', 'delbr', br_name, run_as_root=True) linux_net.delete_ovs_vif_port(self.get_bridge_name(vif), v2_name) except processutils.ProcessExecutionError: LOG.exception(_LE("Failed while unplugging vif"), instance=instance) def unplug_ovs(self, instance, vif): if self.get_firewall_required(vif) or vif.is_hybrid_plug_enabled(): self.unplug_ovs_hybrid(instance, vif) else: self.unplug_ovs_bridge(instance, vif) def unplug_ivs_ethernet(self, instance, vif): """Unplug the VIF by deleting the port from the bridge.""" try: linux_net.delete_ivs_vif_port(self.get_vif_devname(vif)) except processutils.ProcessExecutionError: LOG.exception(_LE("Failed while unplugging vif"), instance=instance) def unplug_ivs_hybrid(self, instance, vif): """UnPlug using hybrid strategy (same as OVS) Unhook port from IVS, unhook port from bridge, delete bridge, and delete both veth devices. """ try: br_name = self.get_br_name(vif['id']) v1_name, v2_name = self.get_veth_pair_names(vif['id']) utils.execute('brctl', 'delif', br_name, v1_name, run_as_root=True) utils.execute('ip', 'link', 'set', br_name, 'down', run_as_root=True) utils.execute('brctl', 'delbr', br_name, run_as_root=True) linux_net.delete_ivs_vif_port(v2_name) except processutils.ProcessExecutionError: LOG.exception(_LE("Failed while unplugging vif"), instance=instance) def unplug_ivs(self, instance, vif): if self.get_firewall_required(vif) or vif.is_hybrid_plug_enabled(): self.unplug_ivs_hybrid(instance, vif) else: self.unplug_ivs_ethernet(instance, vif) def unplug_mlnx_direct(self, instance, vif): vnic_mac = vif['address'] fabric = vif.get_physical_network() if not fabric: raise exception.NetworkMissingPhysicalNetwork( network_uuid=vif['network']['id']) try: utils.execute('ebrctl', 'del-port', fabric, vnic_mac, run_as_root=True) except processutils.ProcessExecutionError: LOG.exception(_LE("Failed while unplugging vif"), instance=instance) def unplug_802qbg(self, instance, vif): pass def unplug_802qbh(self, instance, vif): pass def unplug_hw_veb(self, instance, vif): if vif['vnic_type'] == network_model.VNIC_TYPE_MACVTAP: # The ip utility doesn't accept the MAC 00:00:00:00:00:00. # Therefore, keep the MAC unchanged. Later operations on # the same VF will not be affected by the existing MAC. linux_net.set_vf_interface_vlan(vif['profile']['pci_slot'], mac_addr=vif['address']) def unplug_midonet(self, instance, vif): """Unplug from MidoNet network port Unbind the vif from a MidoNet virtual port. """ dev = self.get_vif_devname(vif) port_id = vif['id'] try: utils.execute('mm-ctl', '--unbind-port', port_id, run_as_root=True) linux_net.delete_net_dev(dev) except processutils.ProcessExecutionError: LOG.exception(_LE("Failed while unplugging vif"), instance=instance) def unplug_iovisor(self, instance, vif): """Unplug using PLUMgrid IO Visor Driver Delete network device and to their respective connection to the Virtual Domain in PLUMgrid Platform. """ iface_id = vif['id'] dev = self.get_vif_devname(vif) try: utils.execute('ifc_ctl', 'gateway', 'ifdown', dev, 'access_vm', vif['network']['label'] + "_" + iface_id, vif['address'], run_as_root=True) utils.execute('ifc_ctl', 'gateway', 'del_port', dev, run_as_root=True) linux_net.delete_net_dev(dev) except processutils.ProcessExecutionError: LOG.exception(_LE("Failed while unplugging vif"), instance=instance) def unplug(self, instance, vif): vif_type = vif['type'] LOG.debug('vif_type=%(vif_type)s instance=%(instance)s ' 'vif=%(vif)s', {'vif_type': vif_type, 'instance': instance, 'vif': vif}) if vif_type is None: raise exception.NovaException( _("vif_type parameter must be present " "for this vif_driver implementation")) vif_slug = self._normalize_vif_type(vif_type) func = getattr(self, 'unplug_%s' % vif_slug, None) if not func: raise exception.NovaException( _("Unexpected vif_type=%s") % vif_type) func(instance, vif)
2026-03-31T15:30:28
codeparrot_clean
ab7f0dbcad10b29ceed2a4323ff1c100
code
# spn management # # Copyright Matthieu Patou mat@samba.org 2010 # # 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/>. # import samba.getopt as options import ldb from samba import provision from samba.samdb import SamDB from samba.auth import system_session from samba.netcmd.common import _get_user_realm_domain from samba.netcmd import ( Command, CommandError, SuperCommand, Option ) class cmd_spn_list(Command): """List spns of a given user.""" synopsis = "%prog <user> [options]" takes_optiongroups = { "sambaopts": options.SambaOptions, "credopts": options.CredentialsOptions, "versionopts": options.VersionOptions, } takes_args = ["user"] def run(self, user, credopts=None, sambaopts=None, versionopts=None): lp = sambaopts.get_loadparm() creds = credopts.get_credentials(lp) paths = provision.provision_paths_from_lp(lp, lp.get("realm")) sam = SamDB(paths.samdb, session_info=system_session(), credentials=creds, lp=lp) # TODO once I understand how, use the domain info to naildown # to the correct domain (cleaneduser, realm, domain) = _get_user_realm_domain(user) self.outf.write(cleaneduser+"\n") res = sam.search( expression="samaccountname=%s" % ldb.binary_encode(cleaneduser), scope=ldb.SCOPE_SUBTREE, attrs=["servicePrincipalName"]) if len(res) >0: spns = res[0].get("servicePrincipalName") found = False flag = ldb.FLAG_MOD_ADD if spns is not None: self.outf.write( "User %s has the following servicePrincipalName: \n" % res[0].dn) for e in spns: self.outf.write("\t %s\n" % e) else: self.outf.write("User %s has no servicePrincipalName" % res[0].dn) else: raise CommandError("User %s not found" % user) class cmd_spn_add(Command): """Create a new spn.""" synopsis = "%prog <name> <user> [options]" takes_optiongroups = { "sambaopts": options.SambaOptions, "credopts": options.CredentialsOptions, "versionopts": options.VersionOptions, } takes_options = [ Option("--force", help="Force the addition of the spn" " even it exists already", action="store_true"), ] takes_args = ["name", "user"] def run(self, name, user, force=False, credopts=None, sambaopts=None, versionopts=None): lp = sambaopts.get_loadparm() creds = credopts.get_credentials(lp) paths = provision.provision_paths_from_lp(lp, lp.get("realm")) sam = SamDB(paths.samdb, session_info=system_session(), credentials=creds, lp=lp) res = sam.search( expression="servicePrincipalName=%s" % ldb.binary_encode(name), scope=ldb.SCOPE_SUBTREE) if len(res) != 0 and not force: raise CommandError("Service principal %s already" " affected to another user" % name) (cleaneduser, realm, domain) = _get_user_realm_domain(user) res = sam.search( expression="samaccountname=%s" % ldb.binary_encode(cleaneduser), scope=ldb.SCOPE_SUBTREE, attrs=["servicePrincipalName"]) if len(res) >0: res[0].dn msg = ldb.Message() spns = res[0].get("servicePrincipalName") tab = [] found = False flag = ldb.FLAG_MOD_ADD if spns is not None: for e in spns: if str(e) == name: found = True tab.append(str(e)) flag = ldb.FLAG_MOD_REPLACE tab.append(name) msg.dn = res[0].dn msg["servicePrincipalName"] = ldb.MessageElement(tab, flag, "servicePrincipalName") if not found: sam.modify(msg) else: raise CommandError("Service principal %s already" " affected to %s" % (name, user)) else: raise CommandError("User %s not found" % user) class cmd_spn_delete(Command): """Delete a spn.""" synopsis = "%prog <name> [user] [options]" takes_optiongroups = { "sambaopts": options.SambaOptions, "credopts": options.CredentialsOptions, "versionopts": options.VersionOptions, } takes_args = ["name", "user?"] def run(self, name, user=None, credopts=None, sambaopts=None, versionopts=None): lp = sambaopts.get_loadparm() creds = credopts.get_credentials(lp) paths = provision.provision_paths_from_lp(lp, lp.get("realm")) sam = SamDB(paths.samdb, session_info=system_session(), credentials=creds, lp=lp) res = sam.search( expression="servicePrincipalName=%s" % ldb.binary_encode(name), scope=ldb.SCOPE_SUBTREE, attrs=["servicePrincipalName", "samAccountName"]) if len(res) >0: result = None if user is not None: (cleaneduser, realm, domain) = _get_user_realm_domain(user) for elem in res: if str(elem["samAccountName"]).lower() == cleaneduser: result = elem if result is None: raise CommandError("Unable to find user %s with" " spn %s" % (user, name)) else: if len(res) != 1: listUser = "" for r in res: listUser = "%s\n%s" % (listUser, str(r.dn)) raise CommandError("More than one user has the spn %s " "and no specific user was specified, list of users" " with this spn:%s" % (name, listUser)) else: result=res[0] msg = ldb.Message() spns = result.get("servicePrincipalName") tab = [] if spns is not None: for e in spns: if str(e) != name: tab.append(str(e)) flag = ldb.FLAG_MOD_REPLACE msg.dn = result.dn msg["servicePrincipalName"] = ldb.MessageElement(tab, flag, "servicePrincipalName") sam.modify(msg) else: raise CommandError("Service principal %s not affected" % name) class cmd_spn(SuperCommand): """Service Principal Name (SPN) management.""" subcommands = {} subcommands["add"] = cmd_spn_add() subcommands["list"] = cmd_spn_list() subcommands["delete"] = cmd_spn_delete()
2026-03-31T15:30:28
codeparrot_clean
c09eca95384b437ba8c6753da7976479
code
# -*- coding: utf-8 -*- """ Python Flight Mechanics Engine (PyFME). Copyright (c) AeroPython Development Team. Distributed under the terms of the MIT License. Trimmer ------- This module solves the problem of calculating the values of the state and control vectors that satisfy the state equations of the aircraft at the given condition. This cannot be done analytically because of the very complex functional dependence on the aerodynamic data. Instead, it must be done with a numerical algorithm which iteratively adjusts the independent variables until some solution criterion is met. """ from copy import deepcopy from warnings import warn from math import sqrt, sin, cos, tan, atan import numpy as np from scipy.optimize import least_squares from pyfme.utils.coordinates import wind2body from pyfme.models.constants import GRAVITY def steady_state_flight_trimmer(aircraft, system, env, TAS, controls_0, controls2trim=None, gamma=0.0, turn_rate=0.0, verbose=0): """Finds a combination of values of the state and control variables that correspond to a steady-state flight condition. Steady-state aircraft flight can be defined as a condition in which all of the motion variables are constant or zero. That is, the linear and angular velocity components are constant (or zero), thus all acceleration components are zero. Parameters ---------- aircraft : Aircraft Plane to be trimmed. system : System System for aircraft trimming. env : Environment Environment with the models for wind, atmosphere and gravity. TAS : float True Air Speed (m/s). controls_0 : dict Initial value guess for each control. If the control is not in `controls2trim` or `controls2trim` is `None` the control is considered fixed to that value during the trimming process. controls2trim : list, optional List with controls to be trimmed. If not given, no control is considered fixed. gamma : float, optional Flight path angle (rad). turn_rate : float, optional Turn rate, d(psi)/dt (rad/s). verbose : {0, 1, 2}, optional Level of algorithm's verbosity: * 0 (default) : work silently. * 1 : display a termination report. * 2 : display progress during iterations (not supported by 'lm' method). Returns ------- aircraft : Aircraft Trimmed plane. system : System Trimmed system. env : Environment Trimmed environment (gravity in body axis). results : dict Relevant parameters calculated during the aircraft trimming, including least square results. Notes ----- See section 3.4 in [1] for the algorithm description. See section 2.5 in [1] for the definition of steady-state flight condition. References ---------- .. [1] Stevens, BL and Lewis, FL, "Aircraft Control and Simulation", Wiley-lnterscience. """ # Creating a copy of these objects in order to not modify any attribute # inside this funciton. trimmed_ac = deepcopy(aircraft) trimmed_sys = deepcopy(system) trimmed_env = deepcopy(env) trimmed_ac.TAS = TAS trimmed_ac.Mach = aircraft.TAS / env.a trimmed_ac.q_inf = 0.5 * trimmed_env.rho * aircraft.TAS ** 2 # Update environment trimmed_env.update(trimmed_sys) # Check if every necessary control for the aircraft is given in controls_0. for ac_control in trimmed_ac.controls: if ac_control not in controls_0: raise ValueError("Control {} not given in controls_0: {}".format( ac_control, controls_0)) trimmed_ac.controls = controls_0 # If controls2trim is not given, trim for every control. if controls2trim is None: controls2trim = list(controls_0.keys()) # TODO: try to look for a good initialization method for alpha & beta initial_guess = [0.05 * np.sign(turn_rate), # alpha 0.001 * np.sign(turn_rate)] # beta for control in controls2trim: initial_guess.append(controls_0[control]) args = (trimmed_sys, trimmed_ac, trimmed_env, controls2trim, gamma, turn_rate) lower_bounds = [-0.5, -0.25] # Alpha and beta upper bounds. upper_bounds = [+0.5, +0.25] # Alpha and beta lower bounds. for ii in controls2trim: lower_bounds.append(aircraft.control_limits[ii][0]) upper_bounds.append(aircraft.control_limits[ii][1]) bounds = (lower_bounds, upper_bounds) results = least_squares(trimming_cost_func, x0=initial_guess, args=args, verbose=verbose, bounds=bounds) fun = results['fun'] cost = results['cost'] if cost > 1e-7 or any(abs(fun) > 1e-3): warn("Trim process did not converge", RuntimeWarning) trimmed_sys.set_initial_state_vector() results = {'alpha': trimmed_ac.alpha, 'beta': trimmed_ac.beta, 'u': trimmed_sys.u, 'v': trimmed_sys.v, 'w': trimmed_sys.w, 'p': trimmed_sys.p, 'q': trimmed_sys.q, 'r': trimmed_sys.r, 'theta': trimmed_sys.theta, 'phi': trimmed_sys.phi, 'ls_opt': results} for control in controls2trim: results[control] = trimmed_ac.controls[control] return trimmed_ac, trimmed_sys, trimmed_env, results def turn_coord_cons(turn_rate, alpha, beta, TAS, gamma=0): """Calculates phi for coordinated turn. """ g0 = GRAVITY G = turn_rate * TAS / g0 if abs(gamma) < 1e-8: phi = G * cos(beta) / (cos(alpha) - G * sin(alpha) * sin(beta)) phi = atan(phi) else: a = 1 - G * tan(alpha) * sin(beta) b = sin(gamma) / cos(beta) c = 1 + G ** 2 * cos(beta) ** 2 sq = sqrt(c * (1 - b ** 2) + G ** 2 * sin(beta) ** 2) num = (a - b ** 2) + b * tan(alpha) * sq den = a ** 2 - b ** 2 * (1 + c * tan(alpha) ** 2) phi = atan(G * cos(beta) / cos(alpha) * num / den) return phi def turn_coord_cons_horizontal_and_small_beta(turn_rate, alpha, TAS): """Calculates phi for coordinated turn given that gamma is equal to zero and beta is small (beta << 1). """ g0 = GRAVITY G = turn_rate * TAS / g0 phi = G / cos(alpha) phi = atan(phi) return phi def rate_of_climb_cons(gamma, alpha, beta, phi): """Calculates theta for the given ROC, wind angles, and roll angle. """ a = cos(alpha) * cos(beta) b = sin(phi) * sin(beta) + cos(phi) * sin(alpha) * cos(beta) sq = sqrt(a ** 2 - sin(gamma) ** 2 + b ** 2) theta = (a * b + sin(gamma) * sq) / (a ** 2 - sin(gamma) ** 2) theta = atan(theta) return theta def trimming_cost_func(trimmed_params, system, ac, env, controls2trim, gamma, turn_rate): """Function to optimize """ alpha = trimmed_params[0] beta = trimmed_params[1] new_controls = {} for ii, control in enumerate(controls2trim): new_controls[control] = trimmed_params[ii + 2] # Choose coordinated turn constrain equation: if abs(turn_rate) < 1e-8: phi = 0 else: phi = turn_coord_cons(turn_rate, alpha, beta, ac.TAS, gamma) system.euler_angles[2] = phi # Rate of climb constrain theta = rate_of_climb_cons(gamma, alpha, beta, phi) system.euler_angles[1] = theta # w = turn_rate * k_h # k_h = sin(theta) i_b + sin(phi) * cos(theta) j_b + cos(theta) * sin(phi) # w = p * i_b + q * j_b + r * k_b p = - turn_rate * sin(theta) q = turn_rate * sin(phi) * cos(theta) r = turn_rate * cos(theta) * sin(phi) system.vel_ang = np.array([p, q, r]) system.vel_body = wind2body((ac.TAS, 0, 0), alpha=alpha, beta=beta) env.update(system) ac.update(new_controls, system, env) forces, moments = ac.calculate_forces_and_moments() vel = np.concatenate((system.vel_body[:], system.vel_ang[:])) output = system.lamceq(0, vel, ac.mass, ac.inertia, forces, moments) return output
2026-03-31T15:30:28
codeparrot_clean
527ab39d7559fd198699ca30a8f11852
code
# # File : keil.py # This file is part of RT-Thread RTOS # COPYRIGHT (C) 2006 - 2015, RT-Thread Development Team # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License along # with this program; if not, write to the Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # # Change Logs: # Date Author Notes # 2015-01-20 Bernard Add copyright information # import os import sys import string import xml.etree.ElementTree as etree from xml.etree.ElementTree import SubElement from utils import _make_path_relative from utils import xml_indent fs_encoding = sys.getfilesystemencoding() def _get_filetype(fn): if fn.rfind('.cpp') != -1 or fn.rfind('.cxx') != -1: return 8 if fn.rfind('.c') != -1 or fn.rfind('.C') != -1: return 1 # assemble file type if fn.rfind('.s') != -1 or fn.rfind('.S') != -1: return 2 # header type if fn.rfind('.h') != -1: return 5 if fn.rfind('.lib') != -1: return 4 # other filetype return 5 def MDK4AddGroupForFN(ProjectFiles, parent, name, filename, project_path): group = SubElement(parent, 'Group') group_name = SubElement(group, 'GroupName') group_name.text = name name = os.path.basename(filename) path = os.path.dirname (filename) basename = os.path.basename(path) path = _make_path_relative(project_path, path) path = os.path.join(path, name) files = SubElement(group, 'Files') file = SubElement(files, 'File') file_name = SubElement(file, 'FileName') name = os.path.basename(path) if name.find('.cpp') != -1: obj_name = name.replace('.cpp', '.o') elif name.find('.c') != -1: obj_name = name.replace('.c', '.o') elif name.find('.s') != -1: obj_name = name.replace('.s', '.o') elif name.find('.S') != -1: obj_name = name.replace('.s', '.o') else: obj_name = name if ProjectFiles.count(obj_name): name = basename + '_' + name ProjectFiles.append(obj_name) file_name.text = name.decode(fs_encoding) file_type = SubElement(file, 'FileType') file_type.text = '%d' % _get_filetype(name) file_path = SubElement(file, 'FilePath') file_path.text = path.decode(fs_encoding) def MDK4AddLibToGroup(ProjectFiles, group, name, filename, project_path): name = os.path.basename(filename) path = os.path.dirname (filename) basename = os.path.basename(path) path = _make_path_relative(project_path, path) path = os.path.join(path, name) files = SubElement(group, 'Files') file = SubElement(files, 'File') file_name = SubElement(file, 'FileName') name = os.path.basename(path) if name.find('.cpp') != -1: obj_name = name.replace('.cpp', '.o') elif name.find('.c') != -1: obj_name = name.replace('.c', '.o') elif name.find('.s') != -1: obj_name = name.replace('.s', '.o') elif name.find('.S') != -1: obj_name = name.replace('.s', '.o') else: obj_name = name if ProjectFiles.count(obj_name): name = basename + '_' + name ProjectFiles.append(obj_name) file_name.text = name.decode(fs_encoding) file_type = SubElement(file, 'FileType') file_type.text = '%d' % _get_filetype(name) file_path = SubElement(file, 'FilePath') file_path.text = path.decode(fs_encoding) def MDK4AddGroup(ProjectFiles, parent, name, files, project_path): # don't add an empty group if len(files) == 0: return group = SubElement(parent, 'Group') group_name = SubElement(group, 'GroupName') group_name.text = name for f in files: fn = f.rfile() name = fn.name path = os.path.dirname(fn.abspath) basename = os.path.basename(path) path = _make_path_relative(project_path, path) path = os.path.join(path, name) files = SubElement(group, 'Files') file = SubElement(files, 'File') file_name = SubElement(file, 'FileName') name = os.path.basename(path) if name.find('.cpp') != -1: obj_name = name.replace('.cpp', '.o') elif name.find('.c') != -1: obj_name = name.replace('.c', '.o') elif name.find('.s') != -1: obj_name = name.replace('.s', '.o') elif name.find('.S') != -1: obj_name = name.replace('.s', '.o') if ProjectFiles.count(obj_name): name = basename + '_' + name ProjectFiles.append(obj_name) file_name.text = name.decode(fs_encoding) file_type = SubElement(file, 'FileType') file_type.text = '%d' % _get_filetype(name) file_path = SubElement(file, 'FilePath') file_path.text = path.decode(fs_encoding) return group # The common part of making MDK4/5 project def MDK45Project(tree, target, script): project_path = os.path.dirname(os.path.abspath(target)) root = tree.getroot() out = file(target, 'wb') out.write('<?xml version="1.0" encoding="UTF-8" standalone="no" ?>\n') CPPPATH = [] CPPDEFINES = [] LINKFLAGS = '' CCFLAGS = '' ProjectFiles = [] # add group groups = tree.find('Targets/Target/Groups') if groups is None: groups = SubElement(tree.find('Targets/Target'), 'Groups') groups.clear() # clean old groups for group in script: group_tree = MDK4AddGroup(ProjectFiles, groups, group['name'], group['src'], project_path) # for local CPPPATH/CPPDEFINES if (group_tree != None) and (group.has_key('LOCAL_CPPPATH') or group.has_key('LOCAL_CCFLAGS')): GroupOption = SubElement(group_tree, 'GroupOption') GroupArmAds = SubElement(GroupOption, 'GroupArmAds') Cads = SubElement(GroupArmAds, 'Cads') VariousControls = SubElement(Cads, 'VariousControls') MiscControls = SubElement(VariousControls, 'MiscControls') if group.has_key('LOCAL_CCFLAGS'): MiscControls.text = group['LOCAL_CCFLAGS'] else: MiscControls.text = ' ' Define = SubElement(VariousControls, 'Define') if group.has_key('LOCAL_CPPDEFINES'): Define.text = ', '.join(set(group['LOCAL_CPPDEFINES'])) else: Define.text = ' ' Undefine = SubElement(VariousControls, 'Undefine') Undefine.text = ' ' IncludePath = SubElement(VariousControls, 'IncludePath') if group.has_key('LOCAL_CPPPATH'): IncludePath.text = ';'.join([_make_path_relative(project_path, os.path.normpath(i)) for i in group['LOCAL_CPPPATH']]) else: IncludePath.text = ' ' # get each include path if group.has_key('CPPPATH') and group['CPPPATH']: if CPPPATH: CPPPATH += group['CPPPATH'] else: CPPPATH += group['CPPPATH'] # get each group's definitions if group.has_key('CPPDEFINES') and group['CPPDEFINES']: if CPPDEFINES: CPPDEFINES += group['CPPDEFINES'] else: CPPDEFINES += group['CPPDEFINES'] # get each group's link flags if group.has_key('LINKFLAGS') and group['LINKFLAGS']: if LINKFLAGS: LINKFLAGS += ' ' + group['LINKFLAGS'] else: LINKFLAGS += group['LINKFLAGS'] if group.has_key('LIBS') and group['LIBS']: for item in group['LIBS']: lib_path = '' for path_item in group['LIBPATH']: full_path = os.path.join(path_item, item + '.lib') if os.path.isfile(full_path): # has this library lib_path = full_path if lib_path != '': if (group_tree != None): MDK4AddLibToGroup(ProjectFiles, group_tree, group['name'], lib_path, project_path) else: MDK4AddGroupForFN(ProjectFiles, groups, group['name'], lib_path, project_path) # write include path, definitions and link flags IncludePath = tree.find('Targets/Target/TargetOption/TargetArmAds/Cads/VariousControls/IncludePath') IncludePath.text = ';'.join([_make_path_relative(project_path, os.path.normpath(i)) for i in CPPPATH]) Define = tree.find('Targets/Target/TargetOption/TargetArmAds/Cads/VariousControls/Define') Define.text = ', '.join(set(CPPDEFINES)) Misc = tree.find('Targets/Target/TargetOption/TargetArmAds/LDads/Misc') Misc.text = LINKFLAGS xml_indent(root) out.write(etree.tostring(root, encoding='utf-8')) out.close() def MDK4Project(target, script): template_tree = etree.parse('template.uvproj') MDK45Project(template_tree, target, script) # remove project.uvopt file project_uvopt = os.path.abspath(target).replace('uvproj', 'uvopt') if os.path.isfile(project_uvopt): os.unlink(project_uvopt) # copy uvopt file if os.path.exists('template.uvopt'): import shutil shutil.copy2('template.uvopt', 'project.uvopt') def MDK5Project(target, script): template_tree = etree.parse('template.uvprojx') MDK45Project(template_tree, target, script) # remove project.uvopt file project_uvopt = os.path.abspath(target).replace('uvprojx', 'uvoptx') if os.path.isfile(project_uvopt): os.unlink(project_uvopt) # copy uvopt file if os.path.exists('template.uvoptx'): import shutil shutil.copy2('template.uvoptx', 'project.uvoptx') def MDKProject(target, script): template = file('template.Uv2', "rb") lines = template.readlines() project = file(target, "wb") project_path = os.path.dirname(os.path.abspath(target)) line_index = 5 # write group for group in script: lines.insert(line_index, 'Group (%s)\r\n' % group['name']) line_index += 1 lines.insert(line_index, '\r\n') line_index += 1 # write file ProjectFiles = [] CPPPATH = [] CPPDEFINES = [] LINKFLAGS = '' CCFLAGS = '' # number of groups group_index = 1 for group in script: # print group['name'] # get each include path if group.has_key('CPPPATH') and group['CPPPATH']: if CPPPATH: CPPPATH += group['CPPPATH'] else: CPPPATH += group['CPPPATH'] # get each group's definitions if group.has_key('CPPDEFINES') and group['CPPDEFINES']: if CPPDEFINES: CPPDEFINES += ';' + group['CPPDEFINES'] else: CPPDEFINES += group['CPPDEFINES'] # get each group's link flags if group.has_key('LINKFLAGS') and group['LINKFLAGS']: if LINKFLAGS: LINKFLAGS += ' ' + group['LINKFLAGS'] else: LINKFLAGS += group['LINKFLAGS'] # generate file items for node in group['src']: fn = node.rfile() name = fn.name path = os.path.dirname(fn.abspath) basename = os.path.basename(path) path = _make_path_relative(project_path, path) path = os.path.join(path, name) if ProjectFiles.count(name): name = basename + '_' + name ProjectFiles.append(name) lines.insert(line_index, 'File %d,%d,<%s><%s>\r\n' % (group_index, _get_filetype(name), path, name)) line_index += 1 group_index = group_index + 1 lines.insert(line_index, '\r\n') line_index += 1 # remove repeat path paths = set() for path in CPPPATH: inc = _make_path_relative(project_path, os.path.normpath(path)) paths.add(inc) #.replace('\\', '/') paths = [i for i in paths] CPPPATH = string.join(paths, ';') definitions = [i for i in set(CPPDEFINES)] CPPDEFINES = string.join(definitions, ', ') while line_index < len(lines): if lines[line_index].startswith(' ADSCINCD '): lines[line_index] = ' ADSCINCD (' + CPPPATH + ')\r\n' if lines[line_index].startswith(' ADSLDMC ('): lines[line_index] = ' ADSLDMC (' + LINKFLAGS + ')\r\n' if lines[line_index].startswith(' ADSCDEFN ('): lines[line_index] = ' ADSCDEFN (' + CPPDEFINES + ')\r\n' line_index += 1 # write project for line in lines: project.write(line) project.close()
2026-03-31T15:30:28
codeparrot_clean
75734438292e7c1f373fb1b063652275
code
from __future__ import division, print_function from __future__ import absolute_import from __future__ import unicode_literals import numpy as np from numpy import array, nanmin, nanmax from sympy import Symbol from pysces import ModelMap, Scanner, ParScanner from numpy import NaN, abs from ...utils.model_graph import ModelGraph from ...utils.misc import silence_print, DotDict, formatter_factory, \ do_safe_state, find_min, find_max, get_value, stringify, \ scanner_range_setup from ...utils.plotting import Data2D def cctype(obj): return 'ccobjects' in str(type(obj)) @silence_print def get_state(mod, do_state=False): if do_state: mod.doState() ss = [getattr(mod, 'J_' + r) for r in mod.reactions] + \ [getattr(mod, s + '_ss') for s in mod.species] return ss class CCBase(object): """The base object for the control coefficients and control patterns""" def __init__(self, mod, name, expression, ltxe): super(CCBase, self).__init__() self.expression = expression self.mod = mod self._ltxe = ltxe self.name = name self._latex_name = '\\Sigma' self._analysis_method = 'symca' self._str_expression_ = None self._value = None self._latex_expression = None @property def latex_expression(self): if not self._latex_expression: self._latex_expression = self._ltxe.expression_to_latex( self.expression ) return self._latex_expression @property def latex_name(self): return self._latex_name @property def _str_expression(self): if not self._str_expression_: self._str_expression_ = str(self.expression) return self._str_expression_ @property def value(self): """The value property. Calls self._calc_value() when self._value is None and returns self._value""" self._calc_value() return self._value def _repr_latex_(self): return '$%s = %s = %.3f$' % (self.latex_name, self.latex_expression, self.value) def _calc_value(self): """Calculates the value of the expression""" keys = self.expression.atoms(Symbol) subsdict = {} for key in keys: str_key = str(key) subsdict[str_key] = getattr(self.mod, str_key) self._value = get_value(self._str_expression, subsdict) def __repr__(self): return self.expression.__repr__() def __add__(self, other): if cctype(other): return self.expression.__add__(other.expression) else: return self.expression.__add__(other) def __mul__(self, other): if cctype(other): return self.expression.__mul__(other.expression) else: return self.expression.__mul__(other) def __div__(self, other): if cctype(other): return self.expression.__div__(other.expression) else: return self.expression.__div__(other) def __pow__(self, other): if cctype(other): return self.expression.__pow__(other.expression) else: return self.expression.__pow__(other) class CCoef(CCBase): """The object the stores control coefficients. Inherits from CCBase""" def __init__(self, mod, name, expression, denominator, ltxe): super(CCoef, self).__init__(mod, name, expression, ltxe) self.numerator = expression self.denominator = denominator.expression self.expression = self.numerator / denominator.expression self.denominator_object = denominator self._latex_numerator = None self._latex_expression_full = None self._latex_expression = None self._latex_name = None self._abs_value = None self.control_patterns = None self._set_control_patterns() @property def abs_value(self): self._calc_abs_value() return self._abs_value @property def latex_numerator(self): if not self._latex_numerator: self._latex_numerator = self._ltxe.expression_to_latex( self.numerator ) return self._latex_numerator @property def latex_expression_full(self): if not self._latex_expression_full: full_expr = '\\frac{' + self.latex_numerator + '}{' \ + self.denominator_object.latex_expression + '}' self._latex_expression_full = full_expr return self._latex_expression_full @property def latex_expression(self): if not self._latex_expression: self._latex_expression = '(' + \ self.latex_numerator + ')' + '/~\\Sigma' return self._latex_expression @property def latex_name(self): if not self._latex_name: self._latex_name = self._ltxe.expression_to_latex( self.name ) return self._latex_name def _perscan_legacy(self, parameter, scan_range): scan_res = [list() for i in range(len(list(self.control_patterns.values())) + 1)] scan_res[0] = scan_range for parvalue in scan_range: state_valid = do_safe_state( self.mod, parameter, parvalue, type='mca') cc_abs_value = 0 for i, cp in enumerate(self.control_patterns.values()): if state_valid: cp_abs = abs(cp.value) scan_res[i + 1].append(cp_abs) cc_abs_value += cp_abs else: scan_res[i + 1].append(NaN) for i, cp in enumerate(self.control_patterns.values()): if state_valid: scan_res[i + 1][-1] = (scan_res[i + 1] [-1] / cc_abs_value) * 100 return scan_res def _valscan_legacy(self, parameter, scan_range): control_pattern_range = list(range(len(list(self.control_patterns.values())) + 2)) scan_res = [list() for i in control_pattern_range] scan_res[0] = scan_range for parvalue in scan_range: state_valid = do_safe_state(self.mod, parameter, parvalue, type='mca') cc_value = 0 for i, cp in enumerate(self.control_patterns.values()): if state_valid: cp_value = cp.value scan_res[i + 1].append(cp_value) cc_value += cp_value else: scan_res[i + 1].append(NaN) if state_valid: scan_res[i + 2].append(cc_value) else: scan_res[i + 2].append(NaN) return scan_res def _perscan(self, parameter, scan_range, par_scan=False, par_engine='multiproc'): val_scan_res = self._valscan(parameter, scan_range, par_scan, par_engine) points = len(scan_range) parameter = val_scan_res[:, 0].reshape(points, 1) cp_abs_vals = np.abs(val_scan_res[:, 1:-1]) cp_abs_sum = np.sum(cp_abs_vals, 1).reshape(points, 1) cp_abs_perc = (cp_abs_vals / cp_abs_sum) * 100 scan_res = np.hstack([parameter, cp_abs_perc]) return scan_res def _valscan(self, parameter, scan_range, par_scan=False, par_engine='multiproc'): needed_symbols = [parameter] + \ stringify(list(self.expression.atoms(Symbol))) # This is experimental if par_scan: scanner = ParScanner(self.mod, par_engine) else: scanner = Scanner(self.mod) scanner.quietRun = True start, end, points, log = scanner_range_setup(scan_range) scanner.addScanParameter(parameter, start=start, end=end, points=points, log=log) scanner.addUserOutput(*needed_symbols) scanner.Run() subs_dict = {} for i, symbol in enumerate(scanner.UserOutputList): subs_dict[symbol] = scanner.UserOutputResults[:, i] control_pattern_names = list(self.control_patterns.keys()) denom_expr = str(self.denominator) cp_numerators = [self.control_patterns[cp_name].numerator for cp_name in control_pattern_names] column_exprs = stringify(cp_numerators) parameter = subs_dict[parameter].reshape(points, 1) scan_res = [] denom_val = get_value(denom_expr, subs_dict) for expr in column_exprs: scan_res.append(get_value(expr, subs_dict) / denom_val) scan_res = np.array(scan_res).transpose() cc_vals = np.sum(scan_res, 1).reshape(points, 1) scan_res = np.hstack([parameter, scan_res, cc_vals]) return scan_res def do_par_scan(self, parameter, scan_range, scan_type='percentage', init_return=True, par_scan=False, par_engine='multiproc', force_legacy=False): assert scan_type in ['percentage', 'value'] init = getattr(self.mod, parameter) column_names = [parameter] + \ [cp.name for cp in list(self.control_patterns.values())] if scan_type == 'percentage': y_label = 'Control pattern percentage contribution' try: assert not force_legacy, 'Legacy scan requested' scan_res = self._perscan(parameter, scan_range, par_scan, par_engine) data_array = scan_res except Exception as exception: print('The parameter scan yielded the following error:') print(exception) print('Switching over to slower scan method and replacing') print('invalid steady states with NaN values.') scan_res = self._perscan_legacy(parameter, scan_range) data_array = array(scan_res, dtype=np.float).transpose() ylim = [nanmin(data_array[:, 1:]), nanmax(data_array[:, 1:]) * 1.1] elif scan_type == 'value': column_names = column_names + [self.name] y_label = 'Control coefficient/pattern value' try: assert not force_legacy, 'Legacy scan requested' scan_res = self._valscan(parameter, scan_range, par_scan, par_engine) data_array = scan_res except Exception as exception: print('The parameter scan yielded the following error:') print(exception) print('Switching over to slower scan method and replacing') print('invalid steady states with NaN values.') scan_res = self._valscan_legacy(parameter, scan_range) data_array = array(scan_res, dtype=np.float).transpose() ylim = [nanmin(data_array[:, 1:]), nanmax(data_array[:, 1:]) * 1.1] # print data_array.shape if init_return: self.mod.SetQuiet() setattr(self.mod, parameter, init) self.mod.doMca() self.mod.SetLoud() mm = ModelMap(self.mod) species = mm.hasSpecies() if parameter in species: x_label = '[%s]' % parameter.replace('_', ' ') else: x_label = parameter ax_properties = {'ylabel': y_label, 'xlabel': x_label, 'xscale': 'linear', 'yscale': 'linear', 'xlim': [find_min(scan_range), find_max(scan_range)], 'ylim': ylim} data = Data2D(mod=self.mod, column_names=column_names, data_array=data_array, ltxe=self._ltxe, analysis_method='symca', ax_properties=ax_properties, file_name=self.name) return data def _calc_abs_value(self): """Calculates the absolute numeric value of the control coefficient from the values of its control patterns.""" keys = self.expression.atoms(Symbol) subsdict = {} if len(keys) == 0: subsdict = None for key in keys: str_key = str(key) subsdict[str_key] = getattr(self.mod, str_key) for pattern in list(self.control_patterns.values()): pattern._calc_value(subsdict) self._abs_value = sum( [abs(pattern._value) for pattern in list(self.control_patterns.values())]) def _calc_value(self): """Calculates the numeric value of the control coefficient from the values of its control patterns.""" keys = self.expression.atoms(Symbol) subsdict = {} if len(keys) == 0: subsdict = None for key in keys: str_key = str(key) subsdict[str_key] = getattr(self.mod, str_key) for pattern in list(self.control_patterns.values()): pattern._calc_value(subsdict) self._value = sum( [pattern._value for pattern in list(self.control_patterns.values())]) def _set_control_patterns(self): """Divides control coefficient into control patterns and saves results in self.CPx where x is a number is the number of the control pattern as it appears in in control coefficient expression""" patterns = self.numerator.as_coeff_add()[1] if len(patterns) == 0: patterns = [self.numerator.as_coeff_add()[0]] cps = DotDict() cps._make_repr('v.name', 'v.value', formatter_factory()) for i, pattern in enumerate(patterns): name = 'CP{:3}'.format(i + 1).replace(' ', '0') cp = CPattern(self.mod, name, pattern, self.denominator_object, self, self._ltxe) setattr(self, name, cp) cps[name] = cp self.control_patterns = cps # assert self._check_control_patterns == True def _check_control_patterns(self): """Checks that all control patterns are either positive or negative""" all_same = False poscomp = [i.value > 0 for i in list(self.control_patterns.values())] negcomp = [i.value < 0 for i in list(self.control_patterns.values())] if all(poscomp): all_same = True elif all(negcomp): all_same = True return all_same def highlight_patterns(self, width=None, height=None, show_dummy_sinks=False, show_external_modifier_links=False, pos_dic=None): mg = ModelGraph(mod=self.mod, pos_dic=pos_dic, analysis_method=self._analysis_method) if height: mg.height = height if width: mg.width = width mg.highlight_cc(self, show_dummy_sinks, show_external_modifier_links) class CPattern(CCBase): """docstring for CPattern""" def __init__(self, mod, name, expression, denominator, parent, ltxe): super(CPattern, self).__init__(mod, name, expression, ltxe) self.numerator = expression self.denominator = denominator.expression self.expression = self.numerator / denominator.expression self.denominator_object = denominator self.parent = parent self._latex_numerator = None self._latex_expression_full = None self._latex_expression = None self._latex_name = None self._percentage = None def _calc_value(self, subsdict=None): """Calculates the value of the expression""" if subsdict is None: keys = self.expression.atoms(Symbol) subsdict = {} for key in keys: str_key = str(key) subsdict[str_key] = getattr(self.mod, str_key) self._value = get_value(self._str_expression, subsdict) @property def latex_numerator(self): if not self._latex_numerator: self._latex_numerator = self._ltxe.expression_to_latex( self.numerator ) return self._latex_numerator @property def latex_expression_full(self): if not self._latex_expression_full: full_expr = '\\frac{' + self.latex_numerator + '}{' \ + self.denominator_object.latex_expression + '}' self._latex_expression_full = full_expr return self._latex_expression_full @property def latex_expression(self): if not self._latex_expression: self._latex_expression = self.latex_numerator + '/~\\Sigma' return self._latex_expression @property def latex_name(self): if not self._latex_name: self._latex_name = self.name return self._latex_name @property def percentage(self): self._percentage = (abs(self.value) / self.parent.abs_value) * 100 return self._percentage
2026-03-31T15:30:28
codeparrot_clean
bae88ec7d59c2bcce13cc6901b83f5f2
code
# Copyright 2010 United States Government as represented by the # Administrator of the National Aeronautics and Space Administration. # Copyright 2011 Justin Santa Barbara # 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. """IPv6 address generation with account identifier embedded.""" import hashlib import netaddr from nova.i18n import _ def to_global(prefix, mac, project_id): project_hash = netaddr.IPAddress( int(hashlib.sha1(project_id).hexdigest()[:8], 16) << 32) static_num = netaddr.IPAddress(0xff << 24) try: mac_suffix = netaddr.EUI(mac).words[3:] int_addr = int(''.join(['%02x' % i for i in mac_suffix]), 16) mac_addr = netaddr.IPAddress(int_addr) maskIP = netaddr.IPNetwork(prefix).ip return (project_hash ^ static_num ^ mac_addr | maskIP).format() except netaddr.AddrFormatError: raise TypeError(_('Bad mac for to_global_ipv6: %s') % mac) except TypeError: raise TypeError(_('Bad prefix for to_global_ipv6: %s') % prefix) except NameError: raise TypeError(_('Bad project_id for to_global_ipv6: %s') % project_id) def to_mac(ipv6_address): address = netaddr.IPAddress(ipv6_address) mask1 = netaddr.IPAddress('::ff:ffff') mac = netaddr.EUI(int(address & mask1)).words return ':'.join(['02', '16', '3e'] + ['%02x' % i for i in mac[3:6]])
2026-03-31T15:30:28
codeparrot_clean
e5f0dc665dc8376f4c756fc5b839ea70
code
#!/usr/bin/env python # -*- coding: utf-8 -*- import csv import six import os try: import unittest2 as unittest except ImportError: import unittest from agate import csv_py3 from agate.exceptions import FieldSizeLimitError @unittest.skipIf(six.PY2, "Not supported in Python 2.") class TestReader(unittest.TestCase): def setUp(self): self.rows = [ ['number', 'text', 'boolean', 'date', 'datetime', 'timedelta'], ['1', 'a', 'True', '2015-11-04', '2015-11-04T12:22:00', '0:04:15'], ['2', '👍', 'False', '2015-11-05', '2015-11-04T12:45:00', '0:06:18'], ['', 'b', '', '', '', ''] ] def test_utf8(self): with open('examples/test.csv', encoding='utf-8') as f: rows = list(csv_py3.Reader(f)) for a, b in zip(self.rows, rows): self.assertEqual(a, b) def test_reader_alias(self): with open('examples/test.csv', encoding='utf-8') as f: rows = list(csv_py3.reader(f)) for a, b in zip(self.rows, rows): self.assertEqual(a, b) def test_properties(self): with open('examples/test.csv', encoding='utf-8') as f: reader = csv_py3.Reader(f) self.assertEqual(reader.dialect.delimiter, ',') self.assertEqual(reader.line_num, 0) next(reader) self.assertEqual(reader.line_num, 1) def test_line_numbers(self): with open('examples/test.csv', encoding='utf-8') as f: rows = list(csv_py3.Reader(f, line_numbers=True)) sample_rows = [ ['line_numbers', 'number', 'text', 'boolean', 'date', 'datetime', 'timedelta'], ['1', '1', 'a', 'True', '2015-11-04', '2015-11-04T12:22:00', '0:04:15'], ['2', '2', u'👍', 'False', '2015-11-05', '2015-11-04T12:45:00', '0:06:18'], ['3', '', 'b', '', '', '', ''] ] for a, b in zip(sample_rows, rows): self.assertEqual(a, b) @unittest.skipIf(six.PY2, "Not supported in Python 2.") class TestFieldSizeLimit(unittest.TestCase): def setUp(self): self.lim = csv.field_size_limit() with open('.test.csv', 'w', encoding='utf-8') as f: f.write('a' * 10) def tearDown(self): # Resetting limit to avoid failure in other tests. csv.field_size_limit(self.lim) os.remove('.test.csv') def test_field_size_limit(self): # Testing field_size_limit for failure. Creating data using str * int. with open('.test.csv', 'r', encoding='utf-8') as f: c = csv_py3.Reader(f, field_size_limit=9) try: c.__next__() except FieldSizeLimitError: pass else: raise AssertionError('Expected FieldSizeLimitError') # Now testing higher field_size_limit. with open('.test.csv', 'r', encoding='utf-8') as f: c = csv_py3.Reader(f, field_size_limit=11) self.assertEqual(['a' * 10], c.__next__()) @unittest.skipIf(six.PY2, "Not supported in Python 2.") class TestWriter(unittest.TestCase): def test_utf8(self): output = six.StringIO() writer = csv_py3.Writer(output) writer.writerow(['a', 'b', 'c']) writer.writerow(['1', '2', '3']) writer.writerow(['4', '5', u'ʤ']) written = six.StringIO(output.getvalue()) reader = csv_py3.Reader(written) self.assertEqual(next(reader), ['a', 'b', 'c']) self.assertEqual(next(reader), ['1', '2', '3']) self.assertEqual(next(reader), ['4', '5', u'ʤ']) def test_writer_alias(self): output = six.StringIO() writer = csv_py3.writer(output) writer.writerow(['a', 'b', 'c']) writer.writerow(['1', '2', '3']) writer.writerow(['4', '5', u'ʤ']) written = six.StringIO(output.getvalue()) reader = csv_py3.reader(written) self.assertEqual(next(reader), ['a', 'b', 'c']) self.assertEqual(next(reader), ['1', '2', '3']) self.assertEqual(next(reader), ['4', '5', u'ʤ']) def test_line_numbers(self): output = six.StringIO() writer = csv_py3.Writer(output, line_numbers=True) writer.writerow(['a', 'b', 'c']) writer.writerow(['1', '2', '3']) writer.writerow(['4', '5', u'ʤ']) written = six.StringIO(output.getvalue()) reader = csv_py3.Reader(written) self.assertEqual(next(reader), ['line_number', 'a', 'b', 'c']) self.assertEqual(next(reader), ['1', '1', '2', '3']) self.assertEqual(next(reader), ['2', '4', '5', u'ʤ']) def test_writerows(self): output = six.StringIO() writer = csv_py3.Writer(output) writer.writerows([ ['a', 'b', 'c'], ['1', '2', '3'], ['4', '5', u'ʤ'] ]) written = six.StringIO(output.getvalue()) reader = csv_py3.Reader(written) self.assertEqual(next(reader), ['a', 'b', 'c']) self.assertEqual(next(reader), ['1', '2', '3']) self.assertEqual(next(reader), ['4', '5', u'ʤ']) @unittest.skipIf(six.PY2, "Not supported in Python 2.") class TestDictReader(unittest.TestCase): def setUp(self): self.rows = [ ['number', 'text', 'boolean', 'date', 'datetime', 'timedelta'], ['1', 'a', 'True', '2015-11-04', '2015-11-04T12:22:00', '0:04:15'], ['2', '👍', 'False', '2015-11-05', '2015-11-04T12:45:00', '0:06:18'], ['', 'b', '', '', '', ''] ] self.f = open('examples/test.csv', encoding='utf-8') def tearDown(self): self.f.close() def test_reader(self): reader = csv_py3.DictReader(self.f) self.assertEqual(next(reader), dict(zip(self.rows[0], self.rows[1]))) def test_reader_alias(self): reader = csv_py3.DictReader(self.f) self.assertEqual(next(reader), dict(zip(self.rows[0], self.rows[1]))) @unittest.skipIf(six.PY2, "Not supported in Python 2.") class TestDictWriter(unittest.TestCase): def setUp(self): self.output = six.StringIO() def tearDown(self): self.output.close() def test_writer(self): writer = csv_py3.DictWriter(self.output, ['a', 'b', 'c']) writer.writeheader() writer.writerow({ u'a': u'1', u'b': u'2', u'c': u'☃' }) result = self.output.getvalue() self.assertEqual(result, 'a,b,c\n1,2,☃\n') def test_writer_alias(self): writer = csv_py3.DictWriter(self.output, ['a', 'b', 'c']) writer.writeheader() writer.writerow({ u'a': u'1', u'b': u'2', u'c': u'☃' }) result = self.output.getvalue() self.assertEqual(result, 'a,b,c\n1,2,☃\n') def test_line_numbers(self): writer = csv_py3.DictWriter(self.output, ['a', 'b', 'c'], line_numbers=True) writer.writeheader() writer.writerow({ u'a': u'1', u'b': u'2', u'c': u'☃' }) result = self.output.getvalue() self.assertEqual(result, 'line_number,a,b,c\n1,1,2,☃\n') def test_writerows(self): writer = csv_py3.DictWriter(self.output, ['a', 'b', 'c'], line_numbers=True) writer.writeheader() writer.writerows([{ u'a': u'1', u'b': u'2', u'c': u'☃' }]) result = self.output.getvalue() self.assertEqual(result, 'line_number,a,b,c\n1,1,2,☃\n') @unittest.skipIf(six.PY2, "Not supported in Python 2.") class TestSniffer(unittest.TestCase): def setUp(self): pass def test_sniffer(self): with open('examples/test.csv', encoding='utf-8') as f: contents = f.read() self.assertEqual(csv_py3.Sniffer().sniff(contents).__dict__, csv.Sniffer().sniff(contents).__dict__)
2026-03-31T15:30:28
codeparrot_clean
449440ac06b7ef1e2894f9f807edaafa
code
""" This module contains general purpose URL functions not found in the standard library. Some of the functions that used to be imported from this module have been moved to the w3lib.url module. Always import those from there instead. """ import posixpath from six.moves.urllib.parse import (ParseResult, urlunparse, urldefrag, urlparse, parse_qsl, urlencode, unquote) # scrapy.utils.url was moved to w3lib.url and import * ensures this # move doesn't break old code from w3lib.url import * from w3lib.url import _safe_chars from scrapy.utils.python import to_native_str def url_is_from_any_domain(url, domains): """Return True if the url belongs to any of the given domains""" host = parse_url(url).netloc.lower() if not host: return False domains = [d.lower() for d in domains] return any((host == d) or (host.endswith('.%s' % d)) for d in domains) def url_is_from_spider(url, spider): """Return True if the url belongs to the given spider""" return url_is_from_any_domain(url, [spider.name] + list(getattr(spider, 'allowed_domains', []))) def url_has_any_extension(url, extensions): return posixpath.splitext(parse_url(url).path)[1].lower() in extensions def canonicalize_url(url, keep_blank_values=True, keep_fragments=False, encoding=None): """Canonicalize the given url by applying the following procedures: - sort query arguments, first by key, then by value - percent encode paths and query arguments. non-ASCII characters are percent-encoded using UTF-8 (RFC-3986) - normalize all spaces (in query arguments) '+' (plus symbol) - normalize percent encodings case (%2f -> %2F) - remove query arguments with blank values (unless keep_blank_values is True) - remove fragments (unless keep_fragments is True) The url passed can be a str or unicode, while the url returned is always a str. For examples see the tests in tests/test_utils_url.py """ scheme, netloc, path, params, query, fragment = parse_url(url) keyvals = parse_qsl(query, keep_blank_values) keyvals.sort() query = urlencode(keyvals) # XXX: copied from w3lib.url.safe_url_string to add encoding argument # path = to_native_str(path, encoding) # path = moves.urllib.parse.quote(path, _safe_chars, encoding='latin1') or '/' path = safe_url_string(_unquotepath(path)) or '/' fragment = '' if not keep_fragments else fragment return urlunparse((scheme, netloc.lower(), path, params, query, fragment)) def _unquotepath(path): for reserved in ('2f', '2F', '3f', '3F'): path = path.replace('%' + reserved, '%25' + reserved.upper()) return unquote(path) def parse_url(url, encoding=None): """Return urlparsed url from the given argument (which could be an already parsed url) """ if isinstance(url, ParseResult): return url return urlparse(to_native_str(url, encoding)) def escape_ajax(url): """ Return the crawleable url according to: http://code.google.com/web/ajaxcrawling/docs/getting-started.html >>> escape_ajax("www.example.com/ajax.html#!key=value") 'www.example.com/ajax.html?_escaped_fragment_=key%3Dvalue' >>> escape_ajax("www.example.com/ajax.html?k1=v1&k2=v2#!key=value") 'www.example.com/ajax.html?k1=v1&k2=v2&_escaped_fragment_=key%3Dvalue' >>> escape_ajax("www.example.com/ajax.html?#!key=value") 'www.example.com/ajax.html?_escaped_fragment_=key%3Dvalue' >>> escape_ajax("www.example.com/ajax.html#!") 'www.example.com/ajax.html?_escaped_fragment_=' URLs that are not "AJAX crawlable" (according to Google) returned as-is: >>> escape_ajax("www.example.com/ajax.html#key=value") 'www.example.com/ajax.html#key=value' >>> escape_ajax("www.example.com/ajax.html#") 'www.example.com/ajax.html#' >>> escape_ajax("www.example.com/ajax.html") 'www.example.com/ajax.html' """ defrag, frag = urldefrag(url) if not frag.startswith('!'): return url return add_or_replace_parameter(defrag, '_escaped_fragment_', frag[1:])
2026-03-31T15:30:28
codeparrot_clean
405112d9f26b498d5770ceb79cdb1d25
code
# ScratchABlock - Program analysis and decompilation framework # # Copyright (c) 2015-2018 Paul Sokolovsky # # 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/>. """Interprocedural transformation passes""" from graph import Graph from core import is_addr import progdb from utils import maybesorted import utils def build_callgraph(): "Build program callgraph from progdb." callgraph = Graph() for addr, props in progdb.FUNC_DB_BY_ADDR.items(): callgraph.add_node(props["label"]) for addr, props in progdb.FUNC_DB_BY_ADDR.items(): for callee in props.get("calls", []): if callee in callgraph: callgraph.add_edge(props["label"], callee) callgraph.number_postorder_forest() return callgraph def calc_callsites_live_out(cg, callee): """Calculate function's callsites_live_out property. Go thru function's callers (using callgraph), and union their calls_live_out information pertinent to this function. """ callers = maybesorted(cg.pred(callee)) # If there're no callers, will return empty set, which # is formally correct - if there're no callers, the # function is dead. However, realistically that means # that callers aren't known, and we should treat that # specially. call_lo_union = set() for c in callers: clo = progdb.FUNC_DB[c].get("calls_live_out", []) #print(" %s: calls_live_out: %s" % (c, utils.repr_stable(clo))) for bbaddr, callee_expr, live_out in clo: if is_addr(callee_expr) and callee_expr.addr == callee: print(" %s: calls_live_out[%s]: %s" % (c, callee, utils.repr_stable((bbaddr, callee_expr, live_out)))) call_lo_union.update(live_out) progdb.FUNC_DB[callee]["callsites_live_out"] = call_lo_union return call_lo_union def collect_returns(): import progdb import arch for addr, props in progdb.FUNC_DB.items(): if "modifieds" in props and "callsites_live_out" in props: props["returns"] = arch.ret_filter(set(props["modifieds"]) & set(props["callsites_live_out"]))
2026-03-31T15:30:28
codeparrot_clean
ac96e7d347f86ec64c2ad28da6c583ed
code
#!/usr/bin/python # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Ansible is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Ansible. If not, see <http://www.gnu.org/licenses/>. DOCUMENTATION = ''' --- module: ec2_ami_find version_added: '2.0' short_description: Searches for AMIs to obtain the AMI ID and other information description: - Returns list of matching AMIs with AMI ID, along with other useful information - Can search AMIs with different owners - Can search by matching tag(s), by AMI name and/or other criteria - Results can be sorted and sliced author: "Tom Bamford (@tombamford)" notes: - This module is not backwards compatible with the previous version of the ec2_search_ami module which worked only for Ubuntu AMIs listed on cloud-images.ubuntu.com. - See the example below for a suggestion of how to search by distro/release. options: region: description: - The AWS region to use. required: true aliases: [ 'aws_region', 'ec2_region' ] owner: description: - Search AMIs owned by the specified owner - Can specify an AWS account ID, or one of the special IDs 'self', 'amazon' or 'aws-marketplace' - If not specified, all EC2 AMIs in the specified region will be searched. - You can include wildcards in many of the search options. An asterisk (*) matches zero or more characters, and a question mark (?) matches exactly one character. You can escape special characters using a backslash (\) before the character. For example, a value of \*amazon\?\\ searches for the literal string *amazon?\. required: false default: null ami_id: description: - An AMI ID to match. default: null required: false ami_tags: description: - A hash/dictionary of tags to match for the AMI. default: null required: false architecture: description: - An architecture type to match (e.g. x86_64). default: null required: false hypervisor: description: - A hypervisor type type to match (e.g. xen). default: null required: false is_public: description: - Whether or not the image(s) are public. choices: ['yes', 'no'] default: null required: false name: description: - An AMI name to match. default: null required: false platform: description: - Platform type to match. default: null required: false sort: description: - Optional attribute which with to sort the results. - If specifying 'tag', the 'tag_name' parameter is required. choices: ['name', 'description', 'tag'] default: null required: false sort_tag: description: - Tag name with which to sort results. - Required when specifying 'sort=tag'. default: null required: false sort_order: description: - Order in which to sort results. - Only used when the 'sort' parameter is specified. choices: ['ascending', 'descending'] default: 'ascending' required: false sort_start: description: - Which result to start with (when sorting). - Corresponds to Python slice notation. default: null required: false sort_end: description: - Which result to end with (when sorting). - Corresponds to Python slice notation. default: null required: false state: description: - AMI state to match. default: 'available' required: false virtualization_type: description: - Virtualization type to match (e.g. hvm). default: null required: false no_result_action: description: - What to do when no results are found. - "'success' reports success and returns an empty array" - "'fail' causes the module to report failure" choices: ['success', 'fail'] default: 'success' required: false requirements: - "python >= 2.6" - boto ''' EXAMPLES = ''' # Note: These examples do not set authentication details, see the AWS Guide for details. # Search for the AMI tagged "project:website" - ec2_ami_find: owner: self ami_tags: project: website no_result_action: fail register: ami_find # Search for the latest Ubuntu 14.04 AMI - ec2_ami_find: name: "ubuntu/images/ebs/ubuntu-trusty-14.04-amd64-server-*" owner: 099720109477 sort: name sort_order: descending sort_end: 1 register: ami_find # Launch an EC2 instance - ec2: image: "{{ ami_find.results[0].ami_id }}" instance_type: m3.medium key_name: mykey wait: yes ''' try: import boto.ec2 HAS_BOTO=True except ImportError: HAS_BOTO=False import json def main(): argument_spec = ec2_argument_spec() argument_spec.update(dict( region = dict(required=True, aliases = ['aws_region', 'ec2_region']), owner = dict(required=False, default=None), ami_id = dict(required=False), ami_tags = dict(required=False, type='dict', aliases = ['search_tags', 'image_tags']), architecture = dict(required=False), hypervisor = dict(required=False), is_public = dict(required=False), name = dict(required=False), platform = dict(required=False), sort = dict(required=False, default=None, choices=['name', 'description', 'tag']), sort_tag = dict(required=False), sort_order = dict(required=False, default='ascending', choices=['ascending', 'descending']), sort_start = dict(required=False), sort_end = dict(required=False), state = dict(required=False, default='available'), virtualization_type = dict(required=False), no_result_action = dict(required=False, default='success', choices = ['success', 'fail']), ) ) module = AnsibleModule( argument_spec=argument_spec, ) if not HAS_BOTO: module.fail_json(msg='boto required for this module, install via pip or your package manager') ami_id = module.params.get('ami_id') ami_tags = module.params.get('ami_tags') architecture = module.params.get('architecture') hypervisor = module.params.get('hypervisor') is_public = module.params.get('is_public') name = module.params.get('name') owner = module.params.get('owner') platform = module.params.get('platform') sort = module.params.get('sort') sort_tag = module.params.get('sort_tag') sort_order = module.params.get('sort_order') sort_start = module.params.get('sort_start') sort_end = module.params.get('sort_end') state = module.params.get('state') virtualization_type = module.params.get('virtualization_type') no_result_action = module.params.get('no_result_action') filter = {'state': state} if ami_id: filter['image_id'] = ami_id if ami_tags: for tag in ami_tags: filter['tag:'+tag] = ami_tags[tag] if architecture: filter['architecture'] = architecture if hypervisor: filter['hypervisor'] = hypervisor if is_public: filter['is_public'] = is_public if name: filter['name'] = name if platform: filter['platform'] = platform if virtualization_type: filter['virtualization_type'] = virtualization_type ec2 = ec2_connect(module) images_result = ec2.get_all_images(owners=owner, filters=filter) if no_result_action == 'fail' and len(images_result) == 0: module.fail_json(msg="No AMIs matched the attributes: %s" % json.dumps(filter)) results = [] for image in images_result: data = { 'ami_id': image.id, 'architecture': image.architecture, 'description': image.description, 'is_public': image.is_public, 'name': image.name, 'owner_id': image.owner_id, 'platform': image.platform, 'root_device_name': image.root_device_name, 'root_device_type': image.root_device_type, 'state': image.state, 'tags': image.tags, 'virtualization_type': image.virtualization_type, } if image.kernel_id: data['kernel_id'] = image.kernel_id if image.ramdisk_id: data['ramdisk_id'] = image.ramdisk_id results.append(data) if sort == 'tag': if not sort_tag: module.fail_json(msg="'sort_tag' option must be given with 'sort=tag'") results.sort(key=lambda e: e['tags'][sort_tag], reverse=(sort_order=='descending')) elif sort: results.sort(key=lambda e: e[sort], reverse=(sort_order=='descending')) try: if sort and sort_start and sort_end: results = results[int(sort_start):int(sort_end)] elif sort and sort_start: results = results[int(sort_start):] elif sort and sort_end: results = results[:int(sort_end)] except TypeError: module.fail_json(msg="Please supply numeric values for sort_start and/or sort_end") module.exit_json(results=results) # import module snippets from ansible.module_utils.basic import * from ansible.module_utils.ec2 import * if __name__ == '__main__': main()
2026-03-31T15:30:28
codeparrot_clean
6d50b992d25696b529936f3736c48d8f
code
from __future__ import unicode_literals from __future__ import print_function from __future__ import division from __future__ import absolute_import # # In the current iteration, there is a client object that can be loaded from # the filesystem into the database and its settings loaded from the database. # There are no special settings (e.g. active/inactive). # # I have no idea how this will be used, but it is nice^H^H^H^H, unit tested code, # so let us keep it around a bit longer # # Ah but this assumes that the settings file is in `emission/clients/` and we # just deleted that entire directory. Changing this to conf for now... from future import standard_library standard_library.install_aliases() from builtins import str from builtins import * from builtins import object import json import logging import dateutil.parser from datetime import datetime # Our imports from emission.core.get_database import get_profile_db, get_client_db class Client(object): def __init__(self, clientName): # TODO: write background process to ensure that there is only one client with each name # Maybe clean up unused clients? self.clientName = clientName self.settings_filename = "conf/clients/%s.settings.json" % self.clientName self.__reload() # Smart settings call, which returns the override settings if the client is # active, and def getSettings(self): logging.debug("For client %s, returning settings %s" % (self.clientName, self.clientJSON['client_settings'])) return self.clientJSON['client_settings'] def __reload(self): self.clientJSON = None if self.clientName is not None: self.clientJSON = get_client_db().find_one({'name': self.clientName}) # Figure out if the JSON object here should always be passed in # Having it be passed in is a lot more flexible # Let's compromise for now by passing it in and seeing how much of a hassle it is # That will also ensure that the update_client script is not a complete NOP def __update(self, newEntry): get_client_db().update({'name': self.clientName}, newEntry, upsert = True) self.__reload() def update(self, createKey = True): import uuid newEntry = json.load(open(self.settings_filename)) if createKey: newEntry['key'] = str(uuid.uuid4()) # logging.info("Updating with new entry %s" % newEntry) self.__update(newEntry) return newEntry['key'] def getClientKey(self): if self.clientJSON is None: return None logging.debug("About to return %s from JSON %s" % (self.clientJSON['key'], self.clientJSON)) return self.clientJSON['key'] def clientSpecificSetters(self, uuid, sectionId, predictedModeMap): return None
2026-03-31T15:30:28
codeparrot_clean
866cc39e27c0e840e2cf8c270ba7d1e0
code
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright (c) 2015 clowwindy # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. from __future__ import absolute_import, division, print_function, \ with_statement import os import sys import argparse if __name__ == '__main__': parser = argparse.ArgumentParser(description='See README') parser.add_argument('-c', '--count', default=3, type=int, help='with how many failure times it should be ' 'considered as an attack') config = parser.parse_args() ips = {} banned = set() for line in sys.stdin: if 'can not parse header when' in line: ip = line.split()[-1].split(':')[0] if ip not in ips: ips[ip] = 1 print(ip) sys.stdout.flush() else: ips[ip] += 1 if ip not in banned and ips[ip] >= config.count: banned.add(ip) cmd = 'iptables -A INPUT -s %s -j DROP' % ip print(cmd, file=sys.stderr) sys.stderr.flush() os.system(cmd)
2026-03-31T15:30:28
codeparrot_clean
7cd1ffe7bc697d793ca99669691ebbdd
code
# Copyright 2013 Josh Durgin # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import datetime import iso8601 from lxml import etree import mock from oslo_config import cfg from oslo_utils import timeutils import webob from cinder.api import extensions from cinder.api.v1 import volumes from cinder import context from cinder import db from cinder import exception from cinder import test from cinder.tests.unit.api import fakes from cinder.tests.unit.api.v2 import stubs from cinder.tests.unit import fake_notifier from cinder.tests.unit import fake_volume from cinder.tests.unit.image import fake as fake_image from cinder.volume import api as volume_api NS = '{http://docs.openstack.org/api/openstack-block-storage/1.0/content}' TEST_SNAPSHOT_UUID = '00000000-0000-0000-0000-000000000001' CONF = cfg.CONF def stub_snapshot_get(self, context, snapshot_id): if snapshot_id != TEST_SNAPSHOT_UUID: raise exception.NotFound return {'id': snapshot_id, 'volume_id': 12, 'status': 'available', 'volume_size': 100, 'created_at': None, 'display_name': 'Default name', 'display_description': 'Default description', } class VolumeApiTest(test.TestCase): def setUp(self): super(VolumeApiTest, self).setUp() self.ext_mgr = extensions.ExtensionManager() self.ext_mgr.extensions = {} fake_image.stub_out_image_service(self.stubs) self.controller = volumes.VolumeController(self.ext_mgr) self.flags(host='fake', notification_driver=[fake_notifier.__name__]) self.stubs.Set(db, 'volume_get_all', stubs.stub_volume_get_all) self.stubs.Set(db, 'service_get_all_by_topic', stubs.stub_service_get_all_by_topic) self.stubs.Set(volume_api.API, 'delete', stubs.stub_volume_delete) def test_volume_create(self): self.stubs.Set(volume_api.API, "create", stubs.stub_volume_api_create) self.stubs.Set(db, 'volume_type_get', stubs.stub_volume_type_get) vol = {"size": 100, "display_name": "Volume Test Name", "display_description": "Volume Test Desc", "availability_zone": "zone1:host1"} body = {"volume": vol} req = fakes.HTTPRequest.blank('/v1/volumes') res_dict = self.controller.create(req, body) expected = {'volume': {'status': 'fakestatus', 'display_description': 'Volume Test Desc', 'availability_zone': 'zone1:host1', 'display_name': 'Volume Test Name', 'attachments': [], 'multiattach': 'false', 'bootable': 'false', 'volume_type': 'vol_type_name', 'snapshot_id': None, 'source_volid': None, 'metadata': {}, 'id': '1', 'created_at': datetime.datetime( 1900, 1, 1, 1, 1, 1, tzinfo=iso8601.iso8601.Utc()), 'size': 100, 'encrypted': False}} self.assertEqual(expected, res_dict) def test_volume_create_with_type(self): vol_type = CONF.default_volume_type db.volume_type_create(context.get_admin_context(), dict(name=vol_type, extra_specs={})) db_vol_type = db.volume_type_get_by_name(context.get_admin_context(), vol_type) vol = {"size": 100, "display_name": "Volume Test Name", "display_description": "Volume Test Desc", "availability_zone": "zone1:host1", "volume_type": "FakeTypeName"} body = {"volume": vol} req = fakes.HTTPRequest.blank('/v1/volumes') # Raise 404 when type name isn't valid self.assertRaises(webob.exc.HTTPNotFound, self.controller.create, req, body) # Use correct volume type name vol.update(dict(volume_type=CONF.default_volume_type)) body.update(dict(volume=vol)) res_dict = self.controller.create(req, body) self.assertIn('id', res_dict['volume']) self.assertEqual(1, len(res_dict)) self.assertEqual(db_vol_type['name'], res_dict['volume']['volume_type']) # Use correct volume type id vol.update(dict(volume_type=db_vol_type['id'])) body.update(dict(volume=vol)) res_dict = self.controller.create(req, body) self.assertIn('id', res_dict['volume']) self.assertEqual(1, len(res_dict)) self.assertEqual(db_vol_type['name'], res_dict['volume']['volume_type']) def test_volume_creation_fails_with_bad_size(self): vol = {"size": '', "display_name": "Volume Test Name", "display_description": "Volume Test Desc", "availability_zone": "zone1:host1"} body = {"volume": vol} req = fakes.HTTPRequest.blank('/v1/volumes') self.assertRaises(exception.InvalidInput, self.controller.create, req, body) def test_volume_creation_fails_with_bad_availability_zone(self): vol = {"size": '1', "name": "Volume Test Name", "description": "Volume Test Desc", "availability_zone": "zonen:hostn"} body = {"volume": vol} req = fakes.HTTPRequest.blank('/v2/volumes') self.assertRaises(exception.InvalidInput, self.controller.create, req, body) def test_volume_create_with_image_id(self): self.stubs.Set(volume_api.API, "create", stubs.stub_volume_api_create) self.stubs.Set(db, 'volume_type_get', stubs.stub_volume_type_get) self.ext_mgr.extensions = {'os-image-create': 'fake'} test_id = "c905cedb-7281-47e4-8a62-f26bc5fc4c77" vol = {"size": '1', "display_name": "Volume Test Name", "display_description": "Volume Test Desc", "availability_zone": "nova", "imageRef": test_id} expected = {'volume': {'status': 'fakestatus', 'display_description': 'Volume Test Desc', 'availability_zone': 'nova', 'display_name': 'Volume Test Name', 'encrypted': False, 'attachments': [], 'multiattach': 'false', 'bootable': 'false', 'volume_type': 'vol_type_name', 'image_id': test_id, 'snapshot_id': None, 'source_volid': None, 'metadata': {}, 'id': '1', 'created_at': datetime.datetime( 1900, 1, 1, 1, 1, 1, tzinfo=iso8601.iso8601.Utc()), 'size': 1}} body = {"volume": vol} req = fakes.HTTPRequest.blank('/v1/volumes') res_dict = self.controller.create(req, body) self.assertEqual(expected, res_dict) def test_volume_create_with_image_id_is_integer(self): self.stubs.Set(volume_api.API, "create", stubs.stub_volume_create) self.ext_mgr.extensions = {'os-image-create': 'fake'} vol = {"size": '1', "display_name": "Volume Test Name", "display_description": "Volume Test Desc", "availability_zone": "cinder", "imageRef": 1234} body = {"volume": vol} req = fakes.HTTPRequest.blank('/v1/volumes') self.assertRaises(webob.exc.HTTPBadRequest, self.controller.create, req, body) def test_volume_create_with_image_id_not_uuid_format(self): self.stubs.Set(volume_api.API, "create", stubs.stub_volume_create) self.ext_mgr.extensions = {'os-image-create': 'fake'} vol = {"size": '1', "display_name": "Volume Test Name", "display_description": "Volume Test Desc", "availability_zone": "cinder", "imageRef": '12345'} body = {"volume": vol} req = fakes.HTTPRequest.blank('/v1/volumes') self.assertRaises(webob.exc.HTTPBadRequest, self.controller.create, req, body) def test_volume_create_with_image_id_with_empty_string(self): self.stubs.Set(volume_api.API, "create", stubs.stub_volume_create) self.ext_mgr.extensions = {'os-image-create': 'fake'} vol = {"size": 1, "display_name": "Volume Test Name", "display_description": "Volume Test Desc", "availability_zone": "cinder", "imageRef": ''} body = {"volume": vol} req = fakes.HTTPRequest.blank('/v1/volumes') self.assertRaises(webob.exc.HTTPBadRequest, self.controller.create, req, body) @mock.patch.object(db, 'volume_admin_metadata_get', return_value={'attached_mode': 'rw', 'readonly': 'False'}) @mock.patch.object(db, 'volume_type_get', side_effect=stubs.stub_volume_type_get) @mock.patch.object(volume_api.API, 'get', side_effect=stubs.stub_volume_api_get, autospec=True) @mock.patch.object(volume_api.API, 'update', side_effect=stubs.stub_volume_update, autospec=True) def test_volume_update(self, *args): updates = { "display_name": "Updated Test Name", } body = {"volume": updates} req = fakes.HTTPRequest.blank('/v1/volumes/1') self.assertEqual(0, len(self.notifier.notifications)) res_dict = self.controller.update(req, '1', body) expected = {'volume': { 'status': 'fakestatus', 'display_description': 'displaydesc', 'availability_zone': 'fakeaz', 'display_name': 'Updated Test Name', 'encrypted': False, 'attachments': [], 'multiattach': 'false', 'bootable': 'false', 'volume_type': 'vol_type_name', 'snapshot_id': None, 'source_volid': None, 'metadata': {'attached_mode': 'rw', 'readonly': 'False'}, 'id': '1', 'created_at': datetime.datetime(1900, 1, 1, 1, 1, 1, tzinfo=iso8601.iso8601.Utc()), 'size': 1}} self.assertEqual(expected, res_dict) self.assertEqual(2, len(self.notifier.notifications)) @mock.patch.object(db, 'volume_admin_metadata_get', return_value={"qos_max_iops": 2000, "readonly": "False", "attached_mode": "rw"}) @mock.patch.object(db, 'volume_type_get', side_effect=stubs.stub_volume_type_get) @mock.patch.object(volume_api.API, 'get', side_effect=stubs.stub_volume_api_get, autospec=True) @mock.patch.object(volume_api.API, 'update', side_effect=stubs.stub_volume_update, autospec=True) def test_volume_update_metadata(self, *args): updates = { "metadata": {"qos_max_iops": 2000} } body = {"volume": updates} req = fakes.HTTPRequest.blank('/v1/volumes/1') self.assertEqual(0, len(self.notifier.notifications)) res_dict = self.controller.update(req, '1', body) expected = {'volume': { 'status': 'fakestatus', 'display_description': 'displaydesc', 'availability_zone': 'fakeaz', 'display_name': 'displayname', 'encrypted': False, 'attachments': [], 'multiattach': 'false', 'bootable': 'false', 'volume_type': 'vol_type_name', 'snapshot_id': None, 'source_volid': None, 'metadata': {"qos_max_iops": '2000', "readonly": "False", "attached_mode": "rw"}, 'id': '1', 'created_at': datetime.datetime(1900, 1, 1, 1, 1, 1, tzinfo=iso8601.iso8601.Utc()), 'size': 1 }} self.assertEqual(expected, res_dict) self.assertEqual(2, len(self.notifier.notifications)) def test_volume_update_with_admin_metadata(self): def stubs_volume_admin_metadata_get(context, volume_id): return {'key': 'value', 'readonly': 'True'} self.stubs.Set(db, 'volume_admin_metadata_get', stubs_volume_admin_metadata_get) self.stubs.Set(volume_api.API, "update", stubs.stub_volume_update) volume = stubs.stub_volume("1") del volume['name'] del volume['volume_type'] del volume['volume_type_id'] volume['metadata'] = {'key': 'value'} db.volume_create(context.get_admin_context(), volume) db.volume_admin_metadata_update(context.get_admin_context(), "1", {"readonly": "True", "invisible_key": "invisible_value"}, False) values = {'volume_id': '1', } attachment = db.volume_attach(context.get_admin_context(), values) db.volume_attached(context.get_admin_context(), attachment['id'], stubs.FAKE_UUID, None, '/') updates = { "display_name": "Updated Test Name", } body = {"volume": updates} req = fakes.HTTPRequest.blank('/v1/volumes/1') self.assertEqual(0, len(self.notifier.notifications)) admin_ctx = context.RequestContext('admin', 'fakeproject', True) req.environ['cinder.context'] = admin_ctx res_dict = self.controller.update(req, '1', body) expected = {'volume': { 'status': 'in-use', 'display_description': 'displaydesc', 'availability_zone': 'fakeaz', 'display_name': 'Updated Test Name', 'encrypted': False, 'attachments': [{ 'attachment_id': attachment['id'], 'id': '1', 'volume_id': '1', 'server_id': stubs.FAKE_UUID, 'host_name': None, 'device': '/' }], 'multiattach': 'false', 'bootable': 'false', 'volume_type': None, 'snapshot_id': None, 'source_volid': None, 'metadata': {'key': 'value', 'readonly': 'True'}, 'id': '1', 'created_at': datetime.datetime(1900, 1, 1, 1, 1, 1, tzinfo=iso8601.iso8601.Utc()), 'size': 1}} self.assertEqual(expected, res_dict) self.assertEqual(2, len(self.notifier.notifications)) def test_update_empty_body(self): body = {} req = fakes.HTTPRequest.blank('/v1/volumes/1') self.assertRaises(webob.exc.HTTPUnprocessableEntity, self.controller.update, req, '1', body) def test_update_invalid_body(self): body = {'display_name': 'missing top level volume key'} req = fakes.HTTPRequest.blank('/v1/volumes/1') self.assertRaises(webob.exc.HTTPUnprocessableEntity, self.controller.update, req, '1', body) def test_update_not_found(self): self.stubs.Set(volume_api.API, "get", stubs.stub_volume_get_notfound) updates = { "display_name": "Updated Test Name", } body = {"volume": updates} req = fakes.HTTPRequest.blank('/v1/volumes/1') self.assertRaises(webob.exc.HTTPNotFound, self.controller.update, req, '1', body) def test_volume_list(self): def stubs_volume_admin_metadata_get(context, volume_id): return {'attached_mode': 'rw', 'readonly': 'False'} self.stubs.Set(db, 'volume_admin_metadata_get', stubs_volume_admin_metadata_get) self.stubs.Set(volume_api.API, 'get_all', stubs.stub_volume_api_get_all_by_project) self.stubs.Set(db, 'volume_type_get', stubs.stub_volume_type_get) req = fakes.HTTPRequest.blank('/v1/volumes') res_dict = self.controller.index(req) expected = {'volumes': [{'status': 'fakestatus', 'display_description': 'displaydesc', 'availability_zone': 'fakeaz', 'display_name': 'displayname', 'encrypted': False, 'attachments': [], 'multiattach': 'false', 'bootable': 'false', 'volume_type': 'vol_type_name', 'snapshot_id': None, 'source_volid': None, 'metadata': {'attached_mode': 'rw', 'readonly': 'False'}, 'id': '1', 'created_at': datetime.datetime( 1900, 1, 1, 1, 1, 1, tzinfo=iso8601.iso8601.Utc()), 'size': 1}]} self.assertEqual(expected, res_dict) # Finally test that we cached the returned volumes self.assertEqual(1, len(req.cached_resource())) def test_volume_list_with_admin_metadata(self): volume = stubs.stub_volume("1") del volume['name'] del volume['volume_type'] del volume['volume_type_id'] volume['metadata'] = {'key': 'value'} db.volume_create(context.get_admin_context(), volume) db.volume_admin_metadata_update(context.get_admin_context(), "1", {"readonly": "True", "invisible_key": "invisible_value"}, False) values = {'volume_id': '1', } attachment = db.volume_attach(context.get_admin_context(), values) db.volume_attached(context.get_admin_context(), attachment['id'], stubs.FAKE_UUID, None, '/') req = fakes.HTTPRequest.blank('/v1/volumes') admin_ctx = context.RequestContext('admin', 'fakeproject', True) req.environ['cinder.context'] = admin_ctx res_dict = self.controller.index(req) expected = {'volumes': [{'status': 'in-use', 'display_description': 'displaydesc', 'availability_zone': 'fakeaz', 'display_name': 'displayname', 'encrypted': False, 'attachments': [ {'attachment_id': attachment['id'], 'device': '/', 'server_id': stubs.FAKE_UUID, 'host_name': None, 'id': '1', 'volume_id': '1'}], 'multiattach': 'false', 'bootable': 'false', 'volume_type': None, 'snapshot_id': None, 'source_volid': None, 'metadata': {'key': 'value', 'readonly': 'True'}, 'id': '1', 'created_at': datetime.datetime( 1900, 1, 1, 1, 1, 1, tzinfo=iso8601.iso8601.Utc()), 'size': 1}]} self.assertEqual(expected, res_dict) @mock.patch.object(db, 'volume_admin_metadata_get', return_value={'attached_mode': 'rw', 'readonly': 'False'}) def test_volume_list_detail(self, *args): self.stubs.Set(volume_api.API, 'get_all', stubs.stub_volume_api_get_all_by_project) self.stubs.Set(db, 'volume_type_get', stubs.stub_volume_type_get) req = fakes.HTTPRequest.blank('/v1/volumes/detail') res_dict = self.controller.index(req) expected = {'volumes': [{'status': 'fakestatus', 'display_description': 'displaydesc', 'availability_zone': 'fakeaz', 'display_name': 'displayname', 'encrypted': False, 'attachments': [], 'multiattach': 'false', 'bootable': 'false', 'volume_type': 'vol_type_name', 'snapshot_id': None, 'source_volid': None, 'metadata': {'attached_mode': 'rw', 'readonly': 'False'}, 'id': '1', 'created_at': datetime.datetime( 1900, 1, 1, 1, 1, 1, tzinfo=iso8601.iso8601.Utc()), 'size': 1}]} self.assertEqual(expected, res_dict) # Finally test that we cached the returned volumes self.assertEqual(1, len(req.cached_resource())) def test_volume_list_detail_with_admin_metadata(self): volume = stubs.stub_volume("1") del volume['name'] del volume['volume_type'] del volume['volume_type_id'] volume['metadata'] = {'key': 'value'} db.volume_create(context.get_admin_context(), volume) db.volume_admin_metadata_update(context.get_admin_context(), "1", {"readonly": "True", "invisible_key": "invisible_value"}, False) values = {'volume_id': '1', } attachment = db.volume_attach(context.get_admin_context(), values) db.volume_attached(context.get_admin_context(), attachment['id'], stubs.FAKE_UUID, None, '/') req = fakes.HTTPRequest.blank('/v1/volumes/detail') admin_ctx = context.RequestContext('admin', 'fakeproject', True) req.environ['cinder.context'] = admin_ctx res_dict = self.controller.index(req) expected = {'volumes': [{'status': 'in-use', 'display_description': 'displaydesc', 'availability_zone': 'fakeaz', 'display_name': 'displayname', 'encrypted': False, 'attachments': [ {'attachment_id': attachment['id'], 'device': '/', 'server_id': stubs.FAKE_UUID, 'host_name': None, 'id': '1', 'volume_id': '1'}], 'multiattach': 'false', 'bootable': 'false', 'volume_type': None, 'snapshot_id': None, 'source_volid': None, 'metadata': {'key': 'value', 'readonly': 'True'}, 'id': '1', 'created_at': datetime.datetime( 1900, 1, 1, 1, 1, 1, tzinfo=iso8601.iso8601.Utc()), 'size': 1}]} self.assertEqual(expected, res_dict) @mock.patch.object(db, 'volume_admin_metadata_get', return_value={'attached_mode': 'rw', 'readonly': 'False'}) @mock.patch.object(volume_api.API, 'get', side_effect=stubs.stub_volume_api_get, autospec=True) @mock.patch.object(db, 'volume_type_get', side_effect=stubs.stub_volume_type_get, autospec=True) def test_volume_show(self, *args): req = fakes.HTTPRequest.blank('/v1/volumes/1') res_dict = self.controller.show(req, '1') expected = {'volume': {'status': 'fakestatus', 'display_description': 'displaydesc', 'availability_zone': 'fakeaz', 'display_name': 'displayname', 'encrypted': False, 'attachments': [], 'multiattach': 'false', 'bootable': 'false', 'volume_type': 'vol_type_name', 'snapshot_id': None, 'source_volid': None, 'metadata': {'attached_mode': 'rw', 'readonly': 'False'}, 'id': '1', 'created_at': datetime.datetime( 1900, 1, 1, 1, 1, 1, tzinfo=iso8601.iso8601.Utc()), 'size': 1}} self.assertEqual(expected, res_dict) # Finally test that we cached the returned volume self.assertIsNotNone(req.cached_resource_by_id('1')) def test_volume_show_no_attachments(self): def stub_volume_get(self, context, volume_id, **kwargs): vol = stubs.stub_volume(volume_id, attach_status='detached') return fake_volume.fake_volume_obj(context, **vol) self.stubs.Set(volume_api.API, 'get', stub_volume_get) self.stubs.Set(db, 'volume_type_get', stubs.stub_volume_type_get) req = fakes.HTTPRequest.blank('/v1/volumes/1') res_dict = self.controller.show(req, '1') expected = {'volume': {'status': 'fakestatus', 'display_description': 'displaydesc', 'availability_zone': 'fakeaz', 'display_name': 'displayname', 'encrypted': False, 'attachments': [], 'multiattach': 'false', 'bootable': 'false', 'volume_type': 'vol_type_name', 'snapshot_id': None, 'source_volid': None, 'metadata': {'readonly': 'False'}, 'id': '1', 'created_at': datetime.datetime( 1900, 1, 1, 1, 1, 1, tzinfo=iso8601.iso8601.Utc()), 'size': 1}} self.assertEqual(expected, res_dict) def test_volume_show_bootable(self): def stub_volume_get(self, context, volume_id, **kwargs): vol = (stubs.stub_volume(volume_id, volume_glance_metadata=dict(foo='bar'))) return fake_volume.fake_volume_obj(context, **vol) self.stubs.Set(volume_api.API, 'get', stub_volume_get) self.stubs.Set(db, 'volume_type_get', stubs.stub_volume_type_get) req = fakes.HTTPRequest.blank('/v1/volumes/1') res_dict = self.controller.show(req, '1') expected = {'volume': {'status': 'fakestatus', 'display_description': 'displaydesc', 'availability_zone': 'fakeaz', 'display_name': 'displayname', 'encrypted': False, 'attachments': [], 'multiattach': 'false', 'bootable': 'true', 'volume_type': 'vol_type_name', 'snapshot_id': None, 'source_volid': None, 'metadata': {'attached_mode': 'rw', 'readonly': 'False'}, 'id': '1', 'created_at': datetime.datetime( 1900, 1, 1, 1, 1, 1, tzinfo=iso8601.iso8601.Utc()), 'size': 1}} self.assertEqual(expected, res_dict) def test_volume_show_no_volume(self): self.stubs.Set(volume_api.API, "get", stubs.stub_volume_get_notfound) req = fakes.HTTPRequest.blank('/v1/volumes/1') self.assertRaises(webob.exc.HTTPNotFound, self.controller.show, req, 1) # Finally test that we did not cache anything self.assertIsNone(req.cached_resource_by_id('1')) def test_volume_detail_limit_offset(self): def volume_detail_limit_offset(is_admin): def stub_volume_get_all_by_project(context, project_id, marker, limit, sort_keys=None, sort_dirs=None, filters=None, viewable_admin_meta=False, offset=None): return [ stubs.stub_volume(1, display_name='vol1'), stubs.stub_volume(2, display_name='vol2'), ] self.stubs.Set(db, 'volume_get_all_by_project', stub_volume_get_all_by_project) self.stubs.Set(db, 'volume_get', stubs.stub_volume_get_db) self.stubs.Set(db, 'volume_type_get', stubs.stub_volume_type_get) req = fakes.HTTPRequest.blank('/v1/volumes/detail?limit=2\ &offset=1', use_admin_context=is_admin) res_dict = self.controller.index(req) volumes = res_dict['volumes'] self.assertEqual(1, len(volumes)) self.assertEqual('2', volumes[0]['id']) # admin case volume_detail_limit_offset(is_admin=True) # non_admin case volume_detail_limit_offset(is_admin=False) def test_volume_show_with_admin_metadata(self): volume = stubs.stub_volume("1") del volume['name'] del volume['volume_type'] del volume['volume_type_id'] volume['metadata'] = {'key': 'value'} db.volume_create(context.get_admin_context(), volume) db.volume_admin_metadata_update(context.get_admin_context(), "1", {"readonly": "True", "invisible_key": "invisible_value"}, False) values = {'volume_id': '1', } attachment = db.volume_attach(context.get_admin_context(), values) db.volume_attached(context.get_admin_context(), attachment['id'], stubs.FAKE_UUID, None, '/') req = fakes.HTTPRequest.blank('/v1/volumes/1') admin_ctx = context.RequestContext('admin', 'fakeproject', True) req.environ['cinder.context'] = admin_ctx res_dict = self.controller.show(req, '1') expected = {'volume': {'status': 'in-use', 'display_description': 'displaydesc', 'availability_zone': 'fakeaz', 'display_name': 'displayname', 'encrypted': False, 'attachments': [ {'attachment_id': attachment['id'], 'device': '/', 'server_id': stubs.FAKE_UUID, 'host_name': None, 'id': '1', 'volume_id': '1'}], 'multiattach': 'false', 'bootable': 'false', 'volume_type': None, 'snapshot_id': None, 'source_volid': None, 'metadata': {'key': 'value', 'readonly': 'True'}, 'id': '1', 'created_at': datetime.datetime( 1900, 1, 1, 1, 1, 1, tzinfo=iso8601.iso8601.Utc()), 'size': 1}} self.assertEqual(expected, res_dict) def test_volume_show_with_encrypted_volume(self): def stub_volume_get(self, context, volume_id, **kwargs): vol = stubs.stub_volume(volume_id, encryption_key_id='fake_id') return fake_volume.fake_volume_obj(context, **vol) self.stubs.Set(volume_api.API, 'get', stub_volume_get) self.stubs.Set(db, 'volume_type_get', stubs.stub_volume_type_get) req = fakes.HTTPRequest.blank('/v1/volumes/1') res_dict = self.controller.show(req, 1) self.assertEqual(True, res_dict['volume']['encrypted']) def test_volume_show_with_unencrypted_volume(self): self.stubs.Set(volume_api.API, 'get', stubs.stub_volume_api_get) self.stubs.Set(db, 'volume_type_get', stubs.stub_volume_type_get) req = fakes.HTTPRequest.blank('/v1/volumes/1') res_dict = self.controller.show(req, 1) self.assertEqual(False, res_dict['volume']['encrypted']) def test_volume_delete(self): self.stubs.Set(volume_api.API, 'get', stubs.stub_volume_api_get) req = fakes.HTTPRequest.blank('/v1/volumes/1') resp = self.controller.delete(req, 1) self.assertEqual(202, resp.status_int) def test_volume_delete_no_volume(self): self.stubs.Set(volume_api.API, "get", stubs.stub_volume_get_notfound) req = fakes.HTTPRequest.blank('/v1/volumes/1') self.assertRaises(webob.exc.HTTPNotFound, self.controller.delete, req, 1) def test_admin_list_volumes_limited_to_project(self): self.stubs.Set(db, 'volume_get_all_by_project', stubs.stub_volume_get_all_by_project) self.stubs.Set(db, 'volume_type_get', stubs.stub_volume_type_get) req = fakes.HTTPRequest.blank('/v1/fake/volumes', use_admin_context=True) res = self.controller.index(req) self.assertIn('volumes', res) self.assertEqual(1, len(res['volumes'])) def test_admin_list_volumes_all_tenants(self): self.stubs.Set(db, 'volume_type_get', stubs.stub_volume_type_get) req = fakes.HTTPRequest.blank('/v1/fake/volumes?all_tenants=1', use_admin_context=True) res = self.controller.index(req) self.assertIn('volumes', res) self.assertEqual(3, len(res['volumes'])) def test_all_tenants_non_admin_gets_all_tenants(self): self.stubs.Set(db, 'volume_get_all_by_project', stubs.stub_volume_get_all_by_project) self.stubs.Set(db, 'volume_get', stubs.stub_volume_get_db) self.stubs.Set(db, 'volume_type_get', stubs.stub_volume_type_get) req = fakes.HTTPRequest.blank('/v1/fake/volumes?all_tenants=1') res = self.controller.index(req) self.assertIn('volumes', res) self.assertEqual(1, len(res['volumes'])) def test_non_admin_get_by_project(self): self.stubs.Set(db, 'volume_get_all_by_project', stubs.stub_volume_get_all_by_project) self.stubs.Set(db, 'volume_get', stubs.stub_volume_get_db) self.stubs.Set(db, 'volume_type_get', stubs.stub_volume_type_get) req = fakes.HTTPRequest.blank('/v1/fake/volumes') res = self.controller.index(req) self.assertIn('volumes', res) self.assertEqual(1, len(res['volumes'])) @mock.patch('cinder.volume.api.API.get_all') def test_get_volumes_filter_with_string(self, get_all): req = mock.MagicMock() req.GET.copy.return_value = {'display_name': 'Volume-573108026'} context = mock.Mock() req.environ = {'cinder.context': context} self.controller._items(req, mock.Mock) get_all.assert_called_once_with( context, sort_dirs=['desc'], viewable_admin_meta=True, sort_keys=['created_at'], limit=None, filters={'display_name': 'Volume-573108026'}, marker=None) @mock.patch('cinder.volume.api.API.get_all') def test_get_volumes_filter_with_list(self, get_all): req = mock.MagicMock() req.GET.copy.return_value = {'id': "['1', '2', '3']"} context = mock.Mock() req.environ = {'cinder.context': context} self.controller._items(req, mock.Mock) get_all.assert_called_once_with( context, sort_dirs=['desc'], viewable_admin_meta=True, sort_keys=['created_at'], limit=None, filters={'id': ['1', '2', '3']}, marker=None) @mock.patch('cinder.volume.api.API.get_all') def test_get_volumes_filter_with_expression(self, get_all): req = mock.MagicMock() req.GET.copy.return_value = {'id': "d+"} context = mock.Mock() req.environ = {'cinder.context': context} self.controller._items(req, mock.Mock) get_all.assert_called_once_with( context, sort_dirs=['desc'], viewable_admin_meta=True, sort_keys=['created_at'], limit=None, filters={'id': 'd+'}, marker=None) class VolumeSerializerTest(test.TestCase): def _verify_volume_attachment(self, attach, tree): for attr in ('id', 'volume_id', 'server_id', 'device'): self.assertEqual(str(attach[attr]), tree.get(attr)) def _verify_volume(self, vol, tree): self.assertEqual(NS + 'volume', tree.tag) for attr in ('id', 'status', 'size', 'availability_zone', 'created_at', 'display_name', 'display_description', 'volume_type', 'bootable', 'snapshot_id'): self.assertEqual(str(vol[attr]), tree.get(attr)) for child in tree: self.assertIn(child.tag, (NS + 'attachments', NS + 'metadata')) if child.tag == 'attachments': self.assertEqual(1, len(child)) self.assertEqual('attachment', child[0].tag) self._verify_volume_attachment(vol['attachments'][0], child[0]) elif child.tag == 'metadata': not_seen = set(vol['metadata'].keys()) for gr_child in child: self.assertIn(gr_child.get("key"), not_seen) self.assertEqual(str(vol['metadata'][gr_child.get("key")]), gr_child.text) not_seen.remove(gr_child.get('key')) self.assertEqual(0, len(not_seen)) def test_volume_show_create_serializer(self): serializer = volumes.VolumeTemplate() raw_volume = dict( id='vol_id', status='vol_status', size=1024, availability_zone='vol_availability', bootable='false', created_at=timeutils.utcnow(), attachments=[dict(id='vol_id', volume_id='vol_id', server_id='instance_uuid', device='/foo')], display_name='vol_name', display_description='vol_desc', volume_type='vol_type', snapshot_id='snap_id', source_volid='source_volid', metadata=dict(foo='bar', baz='quux', ), ) text = serializer.serialize(dict(volume=raw_volume)) tree = etree.fromstring(text) self._verify_volume(raw_volume, tree) def test_volume_index_detail_serializer(self): serializer = volumes.VolumesTemplate() raw_volumes = [dict(id='vol1_id', status='vol1_status', size=1024, availability_zone='vol1_availability', bootable='true', created_at=timeutils.utcnow(), attachments=[dict(id='vol1_id', volume_id='vol1_id', server_id='instance_uuid', device='/foo1')], display_name='vol1_name', display_description='vol1_desc', volume_type='vol1_type', snapshot_id='snap1_id', source_volid=None, metadata=dict(foo='vol1_foo', bar='vol1_bar', ), ), dict(id='vol2_id', status='vol2_status', size=1024, availability_zone='vol2_availability', bootable='true', created_at=timeutils.utcnow(), attachments=[dict(id='vol2_id', volume_id='vol2_id', server_id='instance_uuid', device='/foo2')], display_name='vol2_name', display_description='vol2_desc', volume_type='vol2_type', snapshot_id='snap2_id', source_volid=None, metadata=dict(foo='vol2_foo', bar='vol2_bar', ), )] text = serializer.serialize(dict(volumes=raw_volumes)) tree = etree.fromstring(text) self.assertEqual(NS + 'volumes', tree.tag) self.assertEqual(len(raw_volumes), len(tree)) for idx, child in enumerate(tree): self._verify_volume(raw_volumes[idx], child) class TestVolumeCreateRequestXMLDeserializer(test.TestCase): def setUp(self): super(TestVolumeCreateRequestXMLDeserializer, self).setUp() self.deserializer = volumes.CreateDeserializer() def test_minimal_volume(self): self_request = """ <volume xmlns="http://docs.openstack.org/compute/api/v1.1" size="1"></volume>""" request = self.deserializer.deserialize(self_request) expected = {"volume": {"size": "1", }, } self.assertEqual(expected, request['body']) def test_display_name(self): self_request = """ <volume xmlns="http://docs.openstack.org/compute/api/v1.1" size="1" display_name="Volume-xml"></volume>""" request = self.deserializer.deserialize(self_request) expected = { "volume": { "size": "1", "display_name": "Volume-xml", }, } self.assertEqual(expected, request['body']) def test_display_description(self): self_request = """ <volume xmlns="http://docs.openstack.org/compute/api/v1.1" size="1" display_name="Volume-xml" display_description="description"></volume>""" request = self.deserializer.deserialize(self_request) expected = { "volume": { "size": "1", "display_name": "Volume-xml", "display_description": "description", }, } self.assertEqual(expected, request['body']) def test_volume_type(self): self_request = """ <volume xmlns="http://docs.openstack.org/compute/api/v1.1" size="1" display_name="Volume-xml" display_description="description" volume_type="289da7f8-6440-407c-9fb4-7db01ec49164"></volume>""" request = self.deserializer.deserialize(self_request) expected = { "volume": { "size": "1", "display_name": "Volume-xml", "display_description": "description", "volume_type": "289da7f8-6440-407c-9fb4-7db01ec49164", }, } self.assertEqual(expected, request['body']) def test_availability_zone(self): self_request = """ <volume xmlns="http://docs.openstack.org/compute/api/v1.1" size="1" display_name="Volume-xml" display_description="description" volume_type="289da7f8-6440-407c-9fb4-7db01ec49164" availability_zone="us-east1"></volume>""" request = self.deserializer.deserialize(self_request) expected = { "volume": { "size": "1", "display_name": "Volume-xml", "display_description": "description", "volume_type": "289da7f8-6440-407c-9fb4-7db01ec49164", "availability_zone": "us-east1", }, } self.assertEqual(expected, request['body']) def test_metadata(self): self_request = """ <volume xmlns="http://docs.openstack.org/compute/api/v1.1" display_name="Volume-xml" size="1"> <metadata><meta key="Type">work</meta></metadata></volume>""" request = self.deserializer.deserialize(self_request) expected = { "volume": { "display_name": "Volume-xml", "size": "1", "metadata": { "Type": "work", }, }, } self.assertEqual(expected, request['body']) def test_full_volume(self): self_request = """ <volume xmlns="http://docs.openstack.org/compute/api/v1.1" size="1" display_name="Volume-xml" display_description="description" volume_type="289da7f8-6440-407c-9fb4-7db01ec49164" availability_zone="us-east1"> <metadata><meta key="Type">work</meta></metadata></volume>""" request = self.deserializer.deserialize(self_request) expected = { "volume": { "size": "1", "display_name": "Volume-xml", "display_description": "description", "volume_type": "289da7f8-6440-407c-9fb4-7db01ec49164", "availability_zone": "us-east1", "metadata": { "Type": "work", }, }, } self.assertEqual(expected, request['body']) def test_imageref(self): self_request = """ <volume xmlns="http://docs.openstack.org/volume/api/v1" size="1" display_name="Volume-xml" display_description="description" imageRef="4a90189d-d702-4c7c-87fc-6608c554d737"></volume>""" request = self.deserializer.deserialize(self_request) expected = { "volume": { "size": "1", "display_name": "Volume-xml", "display_description": "description", "imageRef": "4a90189d-d702-4c7c-87fc-6608c554d737", }, } self.assertEqual(expected, request['body']) def test_snapshot_id(self): self_request = """ <volume xmlns="http://docs.openstack.org/volume/api/v1" size="1" display_name="Volume-xml" display_description="description" snapshot_id="4a90189d-d702-4c7c-87fc-6608c554d737"></volume>""" request = self.deserializer.deserialize(self_request) expected = { "volume": { "size": "1", "display_name": "Volume-xml", "display_description": "description", "snapshot_id": "4a90189d-d702-4c7c-87fc-6608c554d737", }, } self.assertEqual(expected, request['body']) def test_source_volid(self): self_request = """ <volume xmlns="http://docs.openstack.org/volume/api/v1" size="1" display_name="Volume-xml" display_description="description" source_volid="4a90189d-d702-4c7c-87fc-6608c554d737"></volume>""" request = self.deserializer.deserialize(self_request) expected = { "volume": { "size": "1", "display_name": "Volume-xml", "display_description": "description", "source_volid": "4a90189d-d702-4c7c-87fc-6608c554d737", }, } self.assertEqual(expected, request['body']) class VolumesUnprocessableEntityTestCase(test.TestCase): """Tests of places we throw 422 Unprocessable Entity from.""" def setUp(self): super(VolumesUnprocessableEntityTestCase, self).setUp() self.ext_mgr = extensions.ExtensionManager() self.ext_mgr.extensions = {} self.controller = volumes.VolumeController(self.ext_mgr) def _unprocessable_volume_create(self, body): req = fakes.HTTPRequest.blank('/v2/fake/volumes') req.method = 'POST' self.assertRaises(webob.exc.HTTPUnprocessableEntity, self.controller.create, req, body) def test_create_no_body(self): self._unprocessable_volume_create(body=None) def test_create_missing_volume(self): body = {'foo': {'a': 'b'}} self._unprocessable_volume_create(body=body) def test_create_malformed_entity(self): body = {'volume': 'string'} self._unprocessable_volume_create(body=body)
2026-03-31T15:30:29
codeparrot_clean
4b0972e806fe550bc186e4f99282f002
code
Constraints DEFINITIONS ::= BEGIN -- Single Value SingleValue ::= INTEGER (1) SingleValue2 ::= INTEGER (1..20) predefined INTEGER ::= 1 SingleValue3 ::= INTEGER (predefined | 5 | 10) Range2to19 ::= INTEGER (1<..<20) Range10to20 ::= INTEGER (10..20) ContainedSubtype ::= INTEGER (INCLUDES Range10to20) -- Some ranges for additional constrained number testing. LongLong ::= INTEGER (0..18446744073709551615) Range256to65536 ::= INTEGER (256..65536) SemiConstrained ::= INTEGER (100..MAX) NegSemiConstrained ::= INTEGER (-128..MAX) SemiConstrainedExt ::= INTEGER (42..MAX, ...) NegSemiConstrainedExt ::= INTEGER (-128..MAX, ...) SemiNamed ::= INTEGER {a(100), b(200)} (100..MAX) -- Extensions -- LongLongExt ::= INTEGER (0..18446744073709551615, ..., -5000..-1) Range256to65536Ext ::= INTEGER (256..65536, ..., 1000000..9000000) -- Union of single values Sv1 ::= INTEGER (2|3|17) Sv2 ::= INTEGER (2|3|17, ...) Sv3 ::= INTEGER {a(2),b(3),z(17)} (2|3|17, ...) -- Other constraints FixedSize ::= OCTET STRING (SIZE(10)) FixedSize2 ::= OCTET STRING (SIZE(10|20)) VariableSize ::= OCTET STRING (SIZE(1..10)) PemittedAlphabet ::= PrintableString (FROM ("a"|"yx")) AliasAddress ::=CHOICE { e164 IA5String (SIZE (1..128) ^ FROM ("0123456789#*,")), h323-ID BMPString (SIZE (1..256)), ... } Obj ::= OBJECT IDENTIFIER -- OTP-4559: a referenced type that has a permitted alphabet constraint -- Example from H323-MESSAGES ver (11/2000) TBCD-STRING ::= IA5String (FROM ("0123456789#*abc")) ANSI-41-UIM ::= SEQUENCE { imsi [0] TBCD-STRING(SIZE (3..16)) OPTIONAL, esn [1] TBCD-STRING(SIZE (16)) OPTIONAL } -- OTP-4869: a BIT STRING constrained by SIZE(C) was encoded wrong -- when C was larger than 16. There was also an error when encodeing -- in compact_bit_string mode. IP ::= SEQUENCE { perm SEQUENCE OF INTEGER (0..15), key BIT STRING (SIZE (128)), bool BOOLEAN OPTIONAL } -- add for OTP-3558 and OTP-4917 Day ::= ENUMERATED{monday(0),tuesday(1),wednesday(2),thursday(3),friday(4),saturday(5),sunday(6)} Wednesday ::= Day(wednesday) Thing ::= INTEGER {fred (0),fred2 (1),fred3 (2)} AnotherThing ::= Thing (fred | fred2) OneMoreThing ::= INTEGER {wilma(0), fred(1), betty(3), barney(2)} OneMoreThing-1 ::= OneMoreThing (wilma | fred) OneMoreThing-2 ::= OneMoreThing (fred | barney) I ::= INTEGER (0|15..269) -- OTP-5457 X1 ::= INTEGER (1..4 | 8 | 10 | 20) -- OTP-9946 -- OTP-5511 maxNrOfCellPortionsPerCell-1 INTEGER ::= 35 CellPortionID ::= INTEGER (0..maxNrOfCellPortionsPerCell-1,...) -- OTP-6763 T ::= IA5String (SIZE (1|2), ..., SIZE (1|2|3)) -- Dubuisson 268 T2 ::= IA5String (SIZE (1|2, ..., 3)) -- equal with T -- OTP-8046 DateAndTime ::= VisibleString (PATTERN "\d#2/\d#2/\d#4-\d#2:\d#2") -- DD/MM/YYYY-HH:MM -- OTP-6828 HandoverCommand-r8-IEs ::= SEQUENCE { handoverCommandMessage OCTET STRING (CONTAINING MyType), ... } MoreCompact ::= OCTET STRING (CONTAINING MyType ENCODED BY {joint-iso-itu-t asn1 packed-encoding(3) basic(0) unaligned(1)}) MyType ::= SEQUENCE {a INTEGER, b INTEGER} Document ::= OCTET STRING (ENCODED BY pdf) pdf OBJECT IDENTIFIER ::= {1,2,3,4,5} ShorterExt ::= IA5String (SIZE (5, ...)) SeqOverlapping ::= SEQUENCE { v Overlapping } SeqNonOverlapping ::= SEQUENCE { v NonOverlapping } Overlapping ::= INTEGER (7280..7560 | 7580..7680 | 7910..8210 | 8600..8940 | 9250..9600 | 14759..15109 | 15250..15590 | 18050..18800 | 19300..19950 | 21100..21700 | 26200..26900 | 18500..19900 | 20100..20250 | 21100..21700 | 23000..24000 | 24960..26900) -- The same intervals, but merged and sorted -- NonOverlapping ::= INTEGER (7280..7560 | 7580..7680 | 7910..8210 | 8600..8940 | 9250..9600 | 14759..15109 | 15250..15590 | 18050..19950 | 20100..20250 | 21100..21700 | 23000..24000 | 24960..26900) -- -- Test INTEGER constraints from fields in objects. -- INT-HOLDER ::= CLASS { &id INTEGER UNIQUE, &obj INT-HOLDER OPTIONAL } WITH SYNTAX { ID &id [OBJ &obj] } int-holder-1 INT-HOLDER ::= { ID 2 } int-holder-2 INT-HOLDER ::= { ID 4 OBJ int-holder-1 } IntObjectConstr ::= INTEGER (int-holder-2.&obj.&id..int-holder-2.&id) -- -- INTEGER constraints defined using named INTEGERs. -- ConstrainedNamedInt ::= INTEGER {v1(42)} (v1) constrainedNamedInt-1 INTEGER {v1(42)} (v1) ::= 42 constrainedNamedInt-2 ConstrainedNamedInt ::= 100 SeqWithNamedInt ::= SEQUENCE { int INTEGER {v2(7)} (v2) } -- -- Cover simpletable constraint checking code. -- ContentInfo ::= SEQUENCE { contentType ContentType } Contents TYPE-IDENTIFIER ::= { {OCTET STRING IDENTIFIED BY {2 1 1 1 1 1 1}} } ContentType ::= TYPE-IDENTIFIER.&id({Contents}) END
2026-03-31T15:30:29
codeparrot_clean
75854523396b4cdd5dbeb4d4ec3a9b7f
code
from mock import Mock from ceph_deploy import install class TestSanitizeArgs(object): def setup(self): self.args = Mock() # set the default behavior we set in cli.py self.args.default_release = False self.args.stable = None def test_args_release_not_specified(self): self.args.release = None result = install.sanitize_args(self.args) # XXX # we should get `args.release` to be the latest release # but we don't want to be updating this test every single # time there is a new default value, and we can't programatically # change that. Future improvement: make the default release a # variable in `ceph_deploy/__init__.py` assert result.default_release is True def test_args_release_is_specified(self): self.args.release = 'dumpling' result = install.sanitize_args(self.args) assert result.default_release is False def test_args_release_stable_is_used(self): self.args.stable = 'dumpling' result = install.sanitize_args(self.args) assert result.release == 'dumpling' def test_args_stable_is_not_used(self): self.args.release = 'dumpling' result = install.sanitize_args(self.args) assert result.stable is None class TestDetectComponents(object): def setup(self): self.args = Mock() # default values for install_* flags self.args.install_all = False self.args.install_mds = False self.args.install_mon = False self.args.install_osd = False self.args.install_rgw = False self.args.install_tests = False self.args.install_common = False self.args.repo = False self.distro = Mock() def test_install_with_repo_option_returns_no_packages(self): self.args.repo = True result = install.detect_components(self.args, self.distro) assert result == [] def test_install_all_returns_all_packages_deb(self): self.args.install_all = True self.distro.is_rpm = False self.distro.is_deb = True result = sorted(install.detect_components(self.args, self.distro)) assert result == sorted([ 'ceph-osd', 'ceph-mds', 'ceph-mon', 'radosgw' ]) def test_install_all_with_other_options_returns_all_packages_deb(self): self.distro.is_rpm = False self.distro.is_deb = True self.args.install_all = True self.args.install_mds = True self.args.install_mon = True self.args.install_osd = True result = sorted(install.detect_components(self.args, self.distro)) assert result == sorted([ 'ceph-osd', 'ceph-mds', 'ceph-mon', 'radosgw' ]) def test_install_all_returns_all_packages_rpm(self): self.args.install_all = True result = sorted(install.detect_components(self.args, self.distro)) assert result == sorted([ 'ceph-osd', 'ceph-mds', 'ceph-mon', 'ceph-radosgw' ]) def test_install_all_with_other_options_returns_all_packages_rpm(self): self.args.install_all = True self.args.install_mds = True self.args.install_mon = True self.args.install_osd = True result = sorted(install.detect_components(self.args, self.distro)) assert result == sorted([ 'ceph-osd', 'ceph-mds', 'ceph-mon', 'ceph-radosgw' ]) def test_install_only_one_component(self): self.args.install_osd = True result = install.detect_components(self.args, self.distro) assert result == ['ceph-osd'] def test_install_a_couple_of_components(self): self.args.install_osd = True self.args.install_mds = True result = sorted(install.detect_components(self.args, self.distro)) assert result == sorted(['ceph-osd', 'ceph-mds']) def test_install_tests(self): self.args.install_tests = True result = sorted(install.detect_components(self.args, self.distro)) assert result == sorted(['ceph-test']) def test_install_all_should_be_default_when_no_options_passed(self): result = sorted(install.detect_components(self.args, self.distro)) assert result == sorted([ 'ceph-osd', 'ceph-mds', 'ceph-mon', 'ceph-radosgw' ])
2026-03-31T15:30:29
codeparrot_clean
ac8e06fd4622b4b4d8eb2261044a6d29
code
import numpy as np class ParameterTransformation(object): def forward(self, external_value): raise NotImplementedError("You have to implement this") def backward(self, internal_value): raise NotImplementedError("You have to implement this") class LogarithmicTransformation(ParameterTransformation): def forward(self, external_value): # Throw an error if taking the logarithm of a negative number (or nan) with np.errstate(invalid='raise'): res = np.log10(external_value) return res def backward(self, internal_value): return 10**internal_value _known_transformations = {'log10': LogarithmicTransformation} def get_transformation(transformation_name): """ Returns an instance of a transformation by name :param transformation_name: :return: instance of transformation with provided name """ if not transformation_name in _known_transformations: raise ValueError("Transformation %s is not known" % transformation_name) else: return _known_transformations[transformation_name]()
2026-03-31T15:30:29
codeparrot_clean
dde4358d2ba0b2b8d7fbd8449edfebcb
code
# -*- encoding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (c) 2011 Cubic ERP - Teradata SAC. (http://cubicerp.com). # # WARNING: This program as such is intended to be used by professional # programmers who take the whole responsability of assessing all potential # consequences resulting from its eventual inadequacies and bugs # End users who are looking for a ready-to-use solution with commercial # garantees and support are strongly adviced to contract a Free Software # Service Company # # This program is Free Software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA # ############################################################################## # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
2026-03-31T15:30:29
codeparrot_clean
ea71db912edeb2fbf74d8f6f2a07cf40
code
""" The `compat` module provides support for backwards compatibility with older versions of Django/Python, and compatibility wrappers around optional packages. """ # flake8: noqa from __future__ import unicode_literals import django from django.conf import settings from django.db import connection, transaction from django.utils import six from django.views.generic import View try: import importlib # Available in Python 3.1+ except ImportError: from django.utils import importlib # Will be removed in Django 1.9 def unicode_repr(instance): # Get the repr of an instance, but ensure it is a unicode string # on both python 3 (already the case) and 2 (not the case). if six.PY2: return repr(instance).decode('utf-8') return repr(instance) def unicode_to_repr(value): # Coerce a unicode string to the correct repr return type, depending on # the Python version. We wrap all our `__repr__` implementations with # this and then use unicode throughout internally. if six.PY2: return value.encode('utf-8') return value def unicode_http_header(value): # Coerce HTTP header value to unicode. if isinstance(value, six.binary_type): return value.decode('iso-8859-1') return value def total_seconds(timedelta): # TimeDelta.total_seconds() is only available in Python 2.7 if hasattr(timedelta, 'total_seconds'): return timedelta.total_seconds() else: return (timedelta.days * 86400.0) + float(timedelta.seconds) + (timedelta.microseconds / 1000000.0) def distinct(queryset, base): if settings.DATABASES[queryset.db]["ENGINE"] == "django.db.backends.oracle": # distinct analogue for Oracle users return base.filter(pk__in=set(queryset.values_list('pk', flat=True))) return queryset.distinct() # OrderedDict only available in Python 2.7. # This will always be the case in Django 1.7 and above, as these versions # no longer support Python 2.6. # For Django <= 1.6 and Python 2.6 fall back to SortedDict. try: from collections import OrderedDict except ImportError: from django.utils.datastructures import SortedDict as OrderedDict # contrib.postgres only supported from 1.8 onwards. try: from django.contrib.postgres import fields as postgres_fields except ImportError: postgres_fields = None # django-filter is optional try: import django_filters except ImportError: django_filters = None if django.VERSION >= (1, 6): def clean_manytomany_helptext(text): return text else: # Up to version 1.5 many to many fields automatically suffix # the `help_text` attribute with hardcoded text. def clean_manytomany_helptext(text): if text.endswith(' Hold down "Control", or "Command" on a Mac, to select more than one.'): text = text[:-69] return text # Django-guardian is optional. Import only if guardian is in INSTALLED_APPS # Fixes (#1712). We keep the try/except for the test suite. guardian = None try: import guardian import guardian.shortcuts # Fixes #1624 except ImportError: pass def get_model_name(model_cls): try: return model_cls._meta.model_name except AttributeError: # < 1.6 used module_name instead of model_name return model_cls._meta.module_name # MinValueValidator, MaxValueValidator et al. only accept `message` in 1.8+ if django.VERSION >= (1, 8): from django.core.validators import MinValueValidator, MaxValueValidator from django.core.validators import MinLengthValidator, MaxLengthValidator else: from django.core.validators import MinValueValidator as DjangoMinValueValidator from django.core.validators import MaxValueValidator as DjangoMaxValueValidator from django.core.validators import MinLengthValidator as DjangoMinLengthValidator from django.core.validators import MaxLengthValidator as DjangoMaxLengthValidator class MinValueValidator(DjangoMinValueValidator): def __init__(self, *args, **kwargs): self.message = kwargs.pop('message', self.message) super(MinValueValidator, self).__init__(*args, **kwargs) class MaxValueValidator(DjangoMaxValueValidator): def __init__(self, *args, **kwargs): self.message = kwargs.pop('message', self.message) super(MaxValueValidator, self).__init__(*args, **kwargs) class MinLengthValidator(DjangoMinLengthValidator): def __init__(self, *args, **kwargs): self.message = kwargs.pop('message', self.message) super(MinLengthValidator, self).__init__(*args, **kwargs) class MaxLengthValidator(DjangoMaxLengthValidator): def __init__(self, *args, **kwargs): self.message = kwargs.pop('message', self.message) super(MaxLengthValidator, self).__init__(*args, **kwargs) # URLValidator only accepts `message` in 1.6+ if django.VERSION >= (1, 6): from django.core.validators import URLValidator else: from django.core.validators import URLValidator as DjangoURLValidator class URLValidator(DjangoURLValidator): def __init__(self, *args, **kwargs): self.message = kwargs.pop('message', self.message) super(URLValidator, self).__init__(*args, **kwargs) # EmailValidator requires explicit regex prior to 1.6+ if django.VERSION >= (1, 6): from django.core.validators import EmailValidator else: from django.core.validators import EmailValidator as DjangoEmailValidator from django.core.validators import email_re class EmailValidator(DjangoEmailValidator): def __init__(self, *args, **kwargs): super(EmailValidator, self).__init__(email_re, *args, **kwargs) # PATCH method is not implemented by Django if 'patch' not in View.http_method_names: View.http_method_names = View.http_method_names + ['patch'] # Markdown is optional try: import markdown def apply_markdown(text): """ Simple wrapper around :func:`markdown.markdown` to set the base level of '#' style headers to <h2>. """ extensions = ['headerid(level=2)'] safe_mode = False md = markdown.Markdown(extensions=extensions, safe_mode=safe_mode) return md.convert(text) except ImportError: apply_markdown = None # `separators` argument to `json.dumps()` differs between 2.x and 3.x # See: http://bugs.python.org/issue22767 if six.PY3: SHORT_SEPARATORS = (',', ':') LONG_SEPARATORS = (', ', ': ') INDENT_SEPARATORS = (',', ': ') else: SHORT_SEPARATORS = (b',', b':') LONG_SEPARATORS = (b', ', b': ') INDENT_SEPARATORS = (b',', b': ') if django.VERSION >= (1, 8): from django.db.models import DurationField from django.utils.dateparse import parse_duration from django.utils.duration import duration_string else: DurationField = duration_string = parse_duration = None def set_rollback(): if hasattr(transaction, 'set_rollback'): if connection.settings_dict.get('ATOMIC_REQUESTS', False): # If running in >=1.6 then mark a rollback as required, # and allow it to be handled by Django. if connection.in_atomic_block: transaction.set_rollback(True) elif transaction.is_managed(): # Otherwise handle it explicitly if in managed mode. if transaction.is_dirty(): transaction.rollback() transaction.leave_transaction_management() else: # transaction not managed pass
2026-03-31T15:30:29
codeparrot_clean
258f1ae3b23c94f9c441370968a2e595
code
from shop.models.ordermodel import OrderExtraInfo, Order from django.test.testcases import TestCase from django.contrib.auth.models import User from shop.tests.util import Mock from shop.shop_api import ShopAPI from decimal import Decimal class ShopApiTestCase(TestCase): def setUp(self): self.user = User.objects.create(username="test", email="test@example.com") self.request = Mock() setattr(self.request, 'user', None) self.order = Order() self.order.order_subtotal = Decimal('10.95') self.order.order_total = Decimal('10.95') self.order.shipping_cost = Decimal('0') self.order.shipping_address_text = 'shipping address example' self.order.billing_address_text = 'billing address example' self.order.save() def test_add_extra_info(self): api = ShopAPI() api.add_extra_info(self.order, 'test') # Assert that an ExtraOrderInfo item was created oei = OrderExtraInfo.objects.get(order=self.order) self.assertEqual(oei.text, 'test') def test_is_order_paid(self): api = ShopAPI() # Ensure deprecated method still works res = api.is_order_payed(self.order) self.assertEqual(res, False) res = api.is_order_paid(self.order) self.assertEqual(res, False) def test_is_order_complete(self): api = ShopAPI() res = api.is_order_completed(self.order) self.assertEqual(res, False) def test_get_order_total(self): api = ShopAPI() res = api.get_order_total(self.order) self.assertEqual(res, Decimal('10.95')) def test_get_order_subtotal(self): api = ShopAPI() res = api.get_order_subtotal(self.order) self.assertEqual(res, Decimal('10.95')) def test_get_order_short_name(self): api = ShopAPI() res = api.get_order_short_name(self.order) self.assertEqual(res, '1-10.95') def test_get_order_unique_id(self): api = ShopAPI() res = api.get_order_unique_id(self.order) self.assertEqual(res, 1) def test_get_order_for_id(self): api = ShopAPI() res = api.get_order_for_id(1) self.assertEqual(res, self.order)
2026-03-31T15:30:29
codeparrot_clean
5a8e2a5ed89bec054117e892a63ca333
code
# coding=utf-8 # Copyright 2014 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import (nested_scopes, generators, division, absolute_import, with_statement, print_function, unicode_literals) import base64 import os import random import re _default_keep_words = [ 'AAAAAAAAAAA=', 'analysis', 'anonfun', 'apply', 'beta', 'class', 'classes', 'com', 'd', 'home', 'jar', 'jars', 'java', 'javac', 'jvm', 'lib', 'library', 'pants', 'rt', 'scala', 'scalac', 'src', 'unapply', 'users', 'web' ] _default_word_map = { 'foursquare': 'acme', 'benjy': 'kermit' } # TODO: Move somewhere more general? Could also be used to anonymize source files. class Anonymizer(object): """Anonymizes names in analysis files. Will replace all words in word_map with the corresponding value. Will replace all other words with a random word from word_list, except for words in keep. Replacements are 1:1, and therefore invertible. Useful for obfuscating real-life analysis files so we can use them in tests without leaking proprietary information. """ # Utility method for anonymizing base64-encoded binary data in analysis files. @staticmethod def _random_base64_string(): n = random.randint(20, 200) return base64.b64encode(os.urandom(n)) # Break on delimiters (digits, space, forward slash, dash, underscore, dollar, period) and on # upper-case letters. _DELIMITER = r'\d|\s|/|-|_|\$|\.' _UPPER = r'[A-Z]' _UPPER_CASE_RE = re.compile(r'^%s$' % _UPPER) _DELIMITER_RE = re.compile(r'^%s$' % _DELIMITER) _BREAK_ON_RE = re.compile(r'(%s|%s)' % (_DELIMITER, _UPPER)) # Capture what we broke on. # Valid replacement words must be all lower-case letters, with no apostrophes etc. _WORD_RE = re.compile(r'^[a-z]+$') def __init__(self, word_list, word_map=None, keep=None, strict=False): self._translations = {} self._reverse_translations = {} # Init from args. for k, v in (_default_word_map if word_map is None else word_map).items(): self._add_translation(k, v) for w in _default_keep_words if keep is None else keep: self._add_translation(w, w) # Prepare list of candidate translations. self._unused_words = list( set(filter(Anonymizer._WORD_RE.match, word_list)) - set(self._translations.values()) - set(self._translations.keys())) random.shuffle(self._unused_words) self._strict = strict # If we're not strict and we run out of replacement words, we count how many more words # we need, so we can give a useful error message to that effect. self._words_needed = 0 def words_needed(self): return self._words_needed def check_for_comprehensiveness(self): if self._words_needed: raise Exception('Need %d more words in word_list for full anonymization.' % self._words_needed) def convert(self, s): parts = Anonymizer._BREAK_ON_RE.split(s) parts_iter = iter(parts) converted_parts = [] for part in parts_iter: if part == '' or Anonymizer._DELIMITER_RE.match(part): converted_parts.append(part) elif Anonymizer._UPPER_CASE_RE.match(part): # Join to the rest of the word, if any. token = part try: token += parts_iter.next() except StopIteration: pass converted_parts.append(self._convert_single_token(token)) else: converted_parts.append(self._convert_single_token(part)) return ''.join(converted_parts) def convert_base64_string(self, s): translation = self._translations.get(s) if translation is None: translation = Anonymizer._random_base64_string() self._add_translation(s, translation) return translation def _convert_single_token(self, token): lower = token.lower() translation = self._translations.get(lower) if translation is None: if not self._unused_words: if self._strict: raise Exception('Ran out of words to translate to.') else: self._words_needed += 1 translation = lower else: translation = self._unused_words.pop() self._add_translation(lower, translation) # Use the same capitalization as the original word. if token[0].isupper(): return translation.capitalize() else: return translation def _add_translation(self, frm, to): if frm in self._translations: raise Exception('Word already has translation: %s -> %s' % (frm, self._translations[frm])) if to in self._reverse_translations: raise Exception('Translation target already used: %s -> %s' % (self._reverse_translations[to], to)) self._translations[frm] = to self._reverse_translations[to] = frm
2026-03-31T15:30:29
codeparrot_clean
3af6fafa5338919733a8acce57fef759
code
# (c) 2013 Joost Yervante Damad <joost@damad.be> # License: GPL import os, os.path, glob import coffee.pycoffee as pycoffee class Meta: def __init__(self, meta): if not 'desc' in meta: meta['desc'] = '' if not 'parent' in meta: meta['parent'] = None self.meta = meta for k in meta: self.__dict__[k] = meta[k] self.child_ids = [] class Library: def __init__(self, name, directory): self.name = name self.directory = directory self.exists = os.path.exists(self.directory) self.is_dir = True self.readonly = False if self.exists: self.is_dir = os.path.isdir(self.directory) self.readonly = not os.access(self.directory, os.W_OK) self.meta_list = [] self.fail_list = [] self.meta_by_id = {} self.scan() def scan(self, select_id = None): self.meta_list = [] self.fail_list = [] if not self.exists: return for path in glob.glob(self.directory + '/*.coffee'): with open(path) as f: code = f.read() meta = pycoffee.eval_coffee_meta(code) if not 'name' in meta or not 'id' in meta: self.fail_list.append(meta) continue meta['readonly'] = not os.access(path, os.W_OK) meta['filename'] = path self.meta_list.append(meta) self.meta_list = [Meta(meta) for meta in self.meta_list] self.meta_list.sort(key=lambda x: x.name) self.meta_by_id = {} for meta in self.meta_list: self.meta_by_id[meta.id] = meta self.meta_by_name = {} for meta in self.meta_list: self.meta_by_name[meta.name] = meta # scan child relationships found_as_child = [] for meta in self.meta_list: if meta.parent != None and meta.parent in self.meta_by_id: self.meta_by_id[meta.parent].child_ids.append(meta.id) found_as_child.append(meta.id) self.root_meta_list = filter(lambda meta: meta.id not in found_as_child, self.meta_list)
2026-03-31T15:30:29
codeparrot_clean
d4857909cdc515503ba5971969e954a4
code
""" =========================================== Robust linear model estimation using RANSAC =========================================== In this example we see how to robustly fit a linear model to faulty data using the RANSAC algorithm. """ import numpy as np from matplotlib import pyplot as plt from sklearn import linear_model, datasets n_samples = 1000 n_outliers = 50 X, y, coef = datasets.make_regression(n_samples=n_samples, n_features=1, n_informative=1, noise=10, coef=True, random_state=0) # Add outlier data np.random.seed(0) X[:n_outliers] = 3 + 0.5 * np.random.normal(size=(n_outliers, 1)) y[:n_outliers] = -3 + 10 * np.random.normal(size=n_outliers) # Fit line using all data model = linear_model.LinearRegression() model.fit(X, y) # Robustly fit linear model with RANSAC algorithm model_ransac = linear_model.RANSACRegressor(linear_model.LinearRegression()) model_ransac.fit(X, y) inlier_mask = model_ransac.inlier_mask_ outlier_mask = np.logical_not(inlier_mask) # Predict data of estimated models line_X = np.arange(-5, 5) line_y = model.predict(line_X[:, np.newaxis]) line_y_ransac = model_ransac.predict(line_X[:, np.newaxis]) # Compare estimated coefficients print("Estimated coefficients (true, normal, RANSAC):") print(coef, model.coef_, model_ransac.estimator_.coef_) lw = 2 plt.scatter(X[inlier_mask], y[inlier_mask], color='yellowgreen', marker='.', label='Inliers') plt.scatter(X[outlier_mask], y[outlier_mask], color='gold', marker='.', label='Outliers') plt.plot(line_X, line_y, color='navy', linestyle='-', linewidth=lw, label='Linear regressor') plt.plot(line_X, line_y_ransac, color='cornflowerblue', linestyle='-', linewidth=lw, label='RANSAC regressor') plt.legend(loc='lower right') plt.show()
2026-03-31T15:30:29
codeparrot_clean
a854c71a5152a20da4434365780adaff
code
from chainer.utils import argument PRIORITY_WRITER = 300 PRIORITY_EDITOR = 200 PRIORITY_READER = 100 class Extension(object): """Base class of trainer extensions. Extension of :class:`Trainer` is a callable object that takes the trainer object as the argument. It also provides some default configurations as its attributes, e.g. the default trigger and the default priority. This class provides a set of typical default values for these attributes. There are three ways to define users' own extensions: inheriting this class, decorating closures by :func:`make_extension`, or using any callable including lambda functions as extensions. Decorator can slightly reduce the overhead and is much easier to use, while this class provides more flexibility (for example, it can have methods to configure the behavior). Using a lambda function allows one-line coding for simple purposes, but users have to specify the configurations as arguments to :meth:`Trainer.extend`. For a callable not inheriting this class, the default configurations of this class are used unless the user explicitly specifies them in :meth:`Trainer.extend` method. Attributes: trigger: Default value of trigger for this extension. It is set to ``(1, 'iteration')`` by default. priority: Default priority of the extension. It is set to ``PRIORITY_READER`` by default. ~Extension.name: Name of the extension. It is set to ``None`` by default. This value will be overwritten when registering an extension to a trainer. See :meth:`chainer.training.Trainer.extend` for details. """ trigger = 1, 'iteration' priority = PRIORITY_READER name = None @property def default_name(self): """Default name of the extension. It is the name of the class by default. Implementation can override this property, or provide a class attribute to hide it. """ return type(self).__name__ def __call__(self, trainer): """Invokes the extension. Implementations should override this operator. This method is called at iterations which the corresponding trigger accepts. Args: trainer (Trainer): Trainer object that calls this operator. """ raise NotImplementedError( 'Extension implementation must override __call__.') def __getattr__(self, name): if name == 'invoke_before_training': raise AttributeError( 'invoke_before_training has been removed since Chainer ' 'v2.0.0. Use Extension.initialize instead.') raise AttributeError('{} object has no attribute {}'.format( type(self).__name__, name)) def finalize(self): """Finalizes the extension. This method is called at the end of the training loop. """ pass def initialize(self, trainer): """Initializes up the trainer state. This method is called before entering the training loop. An extension that modifies the state of :class:`~chainer.training.Trainer` can override this method to initialize it. When the trainer has been restored from a snapshot, this method has to recover an appropriate part of the state of the trainer. For example, :class:`~chainer.training.extensions.ExponentialShift` extension changes the optimizer's hyperparameter at each invocation. Note that the hyperparameter is not saved to the snapshot; it is the responsibility of the extension to recover the hyperparameter. The :class:`~chainer.training.extensions.ExponentialShift` extension recovers it in its ``initialize`` method if it has been loaded from a snapshot, or just setting the initial value otherwise. Args: trainer (Trainer): Trainer object that runs the training loop. """ pass def on_error(self, trainer, exc, tb): """Handles the error raised during training before finalization. This method is called when an exception is thrown during the training loop, before finalize. An extension that needs different error handling from finalize, can override this method to handle errors. Args: trainer (Trainer): Trainer object that runs the training loop. exc (Exception): arbitrary exception thrown during update loop. tb (traceback): traceback object of the exception """ pass def serialize(self, serializer): """Serializes the extension state. It is called when a trainer that owns this extension is serialized. It serializes nothing by default. """ pass def make_extension(trigger=None, default_name=None, priority=None, finalizer=None, initializer=None, on_error=None, **kwargs): """Decorator to make given functions into trainer extensions. This decorator just adds some attributes to a given function. The value of the attributes are given by the arguments of this decorator. See :class:`Extension` for details of trainer extensions. Most of the default values of arguments also follow those for this class. Args: trigger: Default trigger of the extension. default_name: Default name of the extension. The name of a given function is used by default. priority (int): Default priority of the extension. finalizer: Finalizer function of this extension. It is called at the end of the training loop. initializer: Initializer function of this extension. It is called at the beginning of the training loop. on_error: Error handler callback function of this extension. It is called after an error is raised during the trainer loop. """ if kwargs: msg = ('invoke_before_training has been removed since Chainer v2.0.0. ' 'Use initializer= instead.') argument.check_unexpected_kwargs(kwargs, invoke_before_training=msg) argument.assert_kwargs_empty(kwargs) if trigger is None: trigger = Extension.trigger if priority is None: priority = Extension.priority def decorator(ext): ext.trigger = trigger ext.default_name = default_name or ext.__name__ ext.priority = priority ext.finalize = finalizer ext.on_error = on_error ext.initialize = initializer return ext return decorator
2026-03-31T15:30:29
codeparrot_clean
734d5605ff8a93945bab6f00ebfe5784
code
######################## BEGIN LICENSE BLOCK ######################## # The Original Code is Mozilla Universal charset detector code. # # The Initial Developer of the Original Code is # Netscape Communications Corporation. # Portions created by the Initial Developer are Copyright (C) 2001 # the Initial Developer. All Rights Reserved. # # Contributor(s): # Mark Pilgrim - port to Python # Shy Shalom - original C code # Proofpoint, Inc. # # 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 ######################### import sys from . import constants from .charsetprober import CharSetProber class MultiByteCharSetProber(CharSetProber): def __init__(self): CharSetProber.__init__(self) self._mDistributionAnalyzer = None self._mCodingSM = None self._mLastChar = [0, 0] def reset(self): CharSetProber.reset(self) if self._mCodingSM: self._mCodingSM.reset() if self._mDistributionAnalyzer: self._mDistributionAnalyzer.reset() self._mLastChar = [0, 0] def get_charset_name(self): pass def feed(self, aBuf): aLen = len(aBuf) for i in range(0, aLen): codingState = self._mCodingSM.next_state(aBuf[i]) if codingState == constants.eError: if constants._debug: sys.stderr.write(self.get_charset_name() + ' prober hit error at byte ' + str(i) + '\n') self._mState = constants.eNotMe break elif codingState == constants.eItsMe: self._mState = constants.eFoundIt break elif codingState == constants.eStart: charLen = self._mCodingSM.get_current_charlen() if i == 0: self._mLastChar[1] = aBuf[0] self._mDistributionAnalyzer.feed(self._mLastChar, charLen) else: self._mDistributionAnalyzer.feed(aBuf[i - 1:i + 1], charLen) self._mLastChar[0] = aBuf[aLen - 1] if self.get_state() == constants.eDetecting: if (self._mDistributionAnalyzer.got_enough_data() and (self.get_confidence() > constants.SHORTCUT_THRESHOLD)): self._mState = constants.eFoundIt return self.get_state() def get_confidence(self): return self._mDistributionAnalyzer.get_confidence()
2026-03-31T15:30:29
codeparrot_clean
3451948a7f1a9604e768e6a781bfaca7
code
""" """ import os.path import git REPO_ROOT = os.path.abspath(os.path.dirname(__file__)) DATA_DIR = os.path.join(REPO_ROOT, 'data') CURRENT_EXECUTION_VERSION = 16 NEW_AND_MODIFIED = '.' REMOVED = '-A' COMMIT_MSG='-m "Automated commit {index}. Running through."'.format(index=CURRENT_EXECUTION_VERSION) VERSION_TAG = 'v1.0.{build}'.format(build=CURRENT_EXECUTION_VERSION) print("Repo root: " + REPO_ROOT) print("Data directory: " + DATA_DIR) repo = git.Repo(REPO_ROOT) git_driver = repo.git # Making some changes that we can commit. new_file = os.path.join(DATA_DIR, "created {number}.txt".format(number=CURRENT_EXECUTION_VERSION)) old_file = os.path.join(DATA_DIR, "created {number}.txt".format(number=CURRENT_EXECUTION_VERSION-1)) modifiable_file = os.path.join(DATA_DIR, "modifiable.txt".format(number=CURRENT_EXECUTION_VERSION-1)) with open(new_file, mode='w') as fout: contents = "Created file {number}".format(number=CURRENT_EXECUTION_VERSION) fout.write(contents) with open(modifiable_file, mode='a') as fout: contents = "Modified {number} times.\n".format(number=CURRENT_EXECUTION_VERSION) fout.write(contents) if os.path.exists(old_file): print("Removing file: " + old_file) os.remove(old_file) print("Repo is dirty: " + repr(repo.is_dirty())) # Adding new and modified, and deleting removed files from the repo. print('Adding new and modified....') git_driver.add(NEW_AND_MODIFIED) print('Removing deleted from tree....') git_driver.add(REMOVED) print(git_driver.status()) print('Committing changes....') print(git_driver.commit(COMMIT_MSG)) # Let's tag this version if the tag doesn't exist and push it preventing override. if VERSION_TAG not in repo.tags: print('Tagging repository with: {tag}....'.format(tag=VERSION_TAG)) repo.create_tag(VERSION_TAG, message='Annotated tag {version}'.format(version=VERSION_TAG)) print('Pushing changes....') git_driver.push('--follow-tags')
2026-03-31T15:30:29
codeparrot_clean
5402594786ee41e206c115a0cebd24d6
code
# -*- coding: utf-8 -*- """ *************************************************************************** EditScriptDialog.py --------------------- Date : December 2012 Copyright : (C) 2012 by Alexander Bruy Email : alexander dot bruy at gmail dot com *************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * *************************************************************************** """ from processing.modeler.ModelerUtils import ModelerUtils __author__ = 'Alexander Bruy' __date__ = 'December 2012' __copyright__ = '(C) 2012, Alexander Bruy' # This will get replaced with a git SHA1 when you do a git archive __revision__ = '$Format:%H$' import codecs import sys import json from PyQt4.QtCore import * from PyQt4.QtGui import * from PyQt4.Qsci import * from qgis.core import * from qgis.utils import iface from processing.gui.ParametersDialog import ParametersDialog from processing.gui.HelpEditionDialog import HelpEditionDialog from processing.algs.r.RAlgorithm import RAlgorithm from processing.algs.r.RUtils import RUtils from processing.script.ScriptAlgorithm import ScriptAlgorithm from processing.script.ScriptUtils import ScriptUtils from processing.ui.ui_DlgScriptEditor import Ui_DlgScriptEditor import processing.resources_rc class ScriptEditorDialog(QDialog, Ui_DlgScriptEditor): SCRIPT_PYTHON = 0 SCRIPT_R = 1 hasChanged = False def __init__(self, algType, alg): QDialog.__init__(self) self.setupUi(self) self.setWindowFlags(Qt.WindowMinimizeButtonHint | Qt.WindowMaximizeButtonHint | Qt.WindowCloseButtonHint) # Set icons self.btnSave.setIcon( QgsApplication.getThemeIcon('/mActionFileSave.svg')) self.btnSaveAs.setIcon( QgsApplication.getThemeIcon('/mActionFileSaveAs.svg')) self.btnEditHelp.setIcon(QIcon(':/processing/images/edithelp.png')) self.btnRun.setIcon(QIcon(':/processing/images/runalgorithm.png')) self.btnCut.setIcon(QgsApplication.getThemeIcon('/mActionEditCut.png')) self.btnCopy.setIcon( QgsApplication.getThemeIcon('/mActionEditCopy.png')) self.btnPaste.setIcon( QgsApplication.getThemeIcon('/mActionEditPaste.png')) self.btnUndo.setIcon(QgsApplication.getThemeIcon('/mActionUndo.png')) self.btnRedo.setIcon(QgsApplication.getThemeIcon('/mActionRedo.png')) # Connect signals and slots self.btnSave.clicked.connect(self.save) self.btnSaveAs.clicked.connect(self.saveAs) self.btnEditHelp.clicked.connect(self.editHelp) self.btnRun.clicked.connect(self.runAlgorithm) self.btnCut.clicked.connect(self.editor.cut) self.btnCopy.clicked.connect(self.editor.copy) self.btnPaste.clicked.connect(self.editor.paste) self.btnUndo.clicked.connect(self.editor.undo) self.btnRedo.clicked.connect(self.editor.redo) self.editor.textChanged.connect(lambda: self.setHasChanged(True)) self.alg = alg self.algType = algType if self.alg is not None: self.filename = self.alg.descriptionFile self.editor.setText(self.alg.script) else: self.filename = None self.update = False self.help = None self.setHasChanged(False) self.editor.setLexerType(self.algType) def editHelp(self): if self.alg is None: if self.algType == self.SCRIPT_PYTHON: alg = ScriptAlgorithm(None, unicode(self.editor.text())) elif self.algType == self.SCRIPT_R: alg = RAlgorithm(None, unicode(self.editor.text())) else: alg = self.alg dlg = HelpEditionDialog(alg) dlg.exec_() # We store the description string in case there were not saved # because there was no filename defined yet if self.alg is None and dlg.descriptions: self.help = dlg.descriptions def save(self): self.saveScript(False) def saveAs(self): self.saveScript(True) def saveScript(self, saveAs): if self.filename is None or saveAs: if self.algType == self.SCRIPT_PYTHON: scriptDir = ScriptUtils.scriptsFolder() filterName = self.tr('Python scripts (*.py)') elif self.algType == self.SCRIPT_R: scriptDir = RUtils.RScriptsFolder() filterName = self.tr('Processing R script (*.rsx)') self.filename = unicode(QFileDialog.getSaveFileName(self, self.tr('Save script'), scriptDir, filterName)) if self.filename: if self.algType == self.SCRIPT_PYTHON \ and not self.filename.lower().endswith('.py'): self.filename += '.py' if self.algType == self.SCRIPT_R \ and not self.filename.lower().endswith('.rsx'): self.filename += '.rsx' text = unicode(self.editor.text()) if self.alg is not None: self.alg.script = text try: with codecs.open(self.filename, 'w', encoding='utf-8') as fout: fout.write(text) except IOError: QMessageBox.warning(self, self.tr('I/O error'), self.tr('Unable to save edits. Reason:\n %s') % unicode(sys.exc_info()[1])) return self.update = True # If help strings were defined before saving the script for # the first time, we do it here if self.help: with open(self.filename + '.help', 'w') as f: json.dump(self.help, f) self.help = None self.setHasChanged(False) else: self.filename = None def setHasChanged(self, hasChanged): self.hasChanged = hasChanged self.btnSave.setEnabled(hasChanged) def runAlgorithm(self): if self.algType == self.SCRIPT_PYTHON: alg = ScriptAlgorithm(None, unicode(self.editor.text())) alg.provider = ModelerUtils.providers['script'] if self.algType == self.SCRIPT_R: alg = RAlgorithm(None, unicode(self.editor.text())) alg.provider = ModelerUtils.providers['r'] dlg = alg.getCustomParametersDialog() if not dlg: dlg = ParametersDialog(alg) canvas = iface.mapCanvas() prevMapTool = canvas.mapTool() dlg.show() dlg.exec_() if canvas.mapTool() != prevMapTool: try: canvas.mapTool().reset() except: pass canvas.setMapTool(prevMapTool)
2026-03-31T15:30:29
codeparrot_clean
a53f934bedcbfd4ebde78739b5f62e3a
code
#!/usr/bin/env python """Check if a '(data page)' for a biomolecule exists""" __author__ = "Kenny Billiau" __copyright__ = "2014, GMD" __license__ = "GPL v2" __version__ = "0.1" import sys import urllib2 import re import downloadinchi as inchi import openpyxl as px import urllib def get_molecules_from_xlsx(fn): workbook = px.load_workbook(fn) page = workbook.get_sheet_by_name(name='Wikipedia') res = [] for row in page.range('A7:E208'): if row[4].value not in ('#N/A', None): res.append(row[0].value) return res def main(argv): links = [] if len(argv) == 0: lines = inchi.get_page('https://en.wikipedia.org/wiki/List_of_biomolecules') links = inchi.get_molecule_links(lines) else: links = get_molecules_from_xlsx(argv[0]) pageid_re = re.compile('pageid') for title in links: print(title + ' '), url = urllib2.urlopen("https://en.wikipedia.org/w/api.php?action=query&format=yaml&titles=%s" % urllib.quote(title + '_(data_page)')) lines = url.read() if len(pageid_re.findall(lines)) > 0: print 'found' else: print 'NOT FOUND' if __name__ == '__main__': main(sys.argv[1:])
2026-03-31T15:30:29
codeparrot_clean
3a1e35619317eb26f078098bba626e3b
code
from django.core.urlresolvers import reverse from rest_framework.compat import patterns, url from rest_framework.test import APITestCase from rest_framework.tests.models import NullableForeignKeySource from rest_framework.tests.serializers import NullableFKSourceSerializer from rest_framework.tests.views import NullableFKSourceDetail urlpatterns = patterns( '', url(r'^objects/(?P<pk>\d+)/$', NullableFKSourceDetail.as_view(), name='object-detail'), ) class NullableForeignKeyTests(APITestCase): """ DRF should be able to handle nullable foreign keys when a test Client POST/PUT request is made with its own serialized object. """ urls = 'rest_framework.tests.test_nullable_fields' def test_updating_object_with_null_fk(self): obj = NullableForeignKeySource(name='example', target=None) obj.save() serialized_data = NullableFKSourceSerializer(obj).data response = self.client.put(reverse('object-detail', args=[obj.pk]), serialized_data) self.assertEqual(response.data, serialized_data)
2026-03-31T15:30:29
codeparrot_clean
f551b529c3c393f075a4a78638096d90
code
"""Shadow-volume implementation A volume is cast by a light from an edgeset, it's basically the volume of space which is shadowed by the given edgeset/object. """ from OpenGLContext.arrays import * from OpenGL.GL import * import weakref class Volume( object ): """A shadow-volume object This object represents the shadow cast by a single light and a single occluder of that light. It is rendered (along with all other volumes for a given light) into the stencil buffer to determine what parts of the scene are lit by the light. XXX doesn't yet handle single-edges for faces or (more cricitally) clock-wise windings """ forwardIndices = () sideType = 0 # GL_TRIANGLES or GL_QUADS backFaces = () edgeSet = None # weakref to edge-set light = None # weakref to light def __init__( self, edgeSet, sourceVector ): """Initialize the shadow volume edgeSet -- pointer to the edge set from which we retrieve most of our geometric data sourceVector -- the homogenous coordinates of the shadow-casting light. """ self.edgeSet = weakref.proxy( edgeSet ) self.sourceVector = sourceVector self.calculate() def calculate( self ): """Calculate the shadow-volume's shape Returns segments*2*3 array where each item in the array has the property that it defines a face of the shadow volume like so: A,B = segment (2 3-item arrays) for point lights (Quads): Ax,Ay,Az,1.0 Bx,By,Bz,1.0 Bx,By,Bz,0.0 Ax,Ay,Az,0.0 for directional lights: Ax,Ay,Az,1.0 Bx,By,Bz,1.0 0,0,0,0 Which is fed into the "equation 14" or "equation 15" of the article. Note that this is pre-calculated to not require switching calculations on the face when doing the later transformation to a shadow volume. (i.e. in the article there are two different cases for whether the "first" or "second" face is facing the lights, I've folded them together). need certain things when we're done: set of light-facing-faces set of rearward-facing-faces (projected to infinity) set of edge-faces (silouhette projected to infinity) # the first two are currently missing # should do those as indices into the points array """ #sourceVector is the light position, with the fourth-item #of the vector being 1.0 for point lights and 0.0 #for directional lights sourceVector = self.sourceVector positional = sourceVector[-1] if positional: # is a positional light self.sideType = GL_QUADS else: self.sideType = GL_TRIANGLES edges1 = self.singleEdges( sourceVector ) edges2 = self.doubleEdges( sourceVector ) self.shadowCaps( sourceVector ) # now compound the two sources together # these are all now edges to be turned into # faces for the sides of the shadow-volume edges1 = concatenate( (edges1, edges2) ) # calculate the edge-faces here... if self.sideType == GL_QUADS: l = array( sourceVector[:3], 'd' ) points = zeros( (len(edges1)*4,4), 'd' ) points[1::4,:3] = edges1[:,1] # B points[0::4,:3] = edges1[:,0] # A # A.w and B.w are always one (in this code) # so we can simplify a few of the equations... points[3::4,:3] = ( edges1[:,0] * positional # A*l.w - l # l*A.w == l* 1.0 == l ) points[2::4,:3] = ( edges1[:,1] * positional - l # B*l.w - l*B.w ) points[0::4,3] = 1 points[1::4,3] = 1 else: # Triangles l = - array( sourceVector, 'd' ) points = zeros( (len(edges1)*3,4), 'd' ) points[0::3,:3] = edges1[:,1] # B points[1::3,:3] = edges1[:,0] # A points[2::3,:] = l # A*l.w - l*A.w points[0::3,3] = 1 points[1::3,3] = 1 self.edges = points def doubleEdges( self, sourceVector ): """Calculate double-face-edges for given sourceVector Returns an Nx2x3 array of line-segment coordinates """ doubleEdges = self.edgeSet.doubleEdges doubleVectors = self.edgeSet.doubleVectors if not doubleEdges: return zeros( (0,2,3),'d') indices = arange(0,len(doubleVectors)) ### Calculate the forward and backward-facing triangle-sets... mults = greater( dot(doubleVectors, sourceVector ), 0 ) #indices -> only those which are edges # if one is and one isn't, then it's a silouhette edge indices = nonzero( equal( sum( mults, 1 # second axis ), 1 # everything that isn't 0 or 2 in this case ) )[0] # just care about first dimension # vectors is now just those which are edges... vectors = take( doubleVectors, indices, 0 ) edges = take( doubleEdges, indices, 0 ) # mults gives a map which filters the doubleIndices value # mults is now just those edges which are part of the silouhette mults = take( mults, indices, 0 ) # the set of silouhette vertices where the second face faces... vectors1 = compress( mults[:,1], edges,0 ) # the set of vertices where the first face faces... vectors2 = compress( mults[:,0], edges,0 ) # these need to have their coord-order swapped to allow # for uniform treatment... a = vectors2[:,1::2][:] b = vectors2[:,::2][:] vectors2 = zeros(shape(vectors2),'d') vectors2[:,1::2] = b vectors2[:,::2] = a # the vector-sets are now homogenous, so we concatenate and # return the result return concatenate((vectors2,vectors1)) def singleEdges( self, sourceVector ): """Calculate single-face-edges for given sourceVector Returns an Nx2x3 array of line-segment coordinates """ # if the face is facing, then is an edge, otherwise not singleEdges = self.edgeSet.singleEdges singleVectors = self.edgeSet.singleVectors if not singleVectors: return zeros( (0,2,3),'d') indices = nonzero( greater( dot(singleVectors, sourceVector ), 0 ) ) return take( singleEdges, indices, 0 ) def shadowCaps( self, sourceVector): """Calculate the shadow-volume caps Forward cap is just indices into the points array Backward cap requires a new points array """ ### Calculate the forward/backward face-sets directions = dot(self.edgeSet.planeEquations, sourceVector) def expand( forwardIndices ): """Expand a set into point-indices from tri-indices""" forwardIndices = repeat(forwardIndices,3,0) forwardIndices[1::3] +=1 forwardIndices[2::3] +=2 return forwardIndices self.forwardIndices = expand(nonzero(greater(directions,0))[0]) # backward is trickier, as we need to project to infinity # from the light position if sourceVector[-1]: backwardIndices = expand(nonzero(less_equal(directions,0))[0]) ### Now need to project backward with this equation: ## Vertex4f(V.x*L.w-L.x*V.w, V.y*L.w-L.y*V.w,V.z*L.w-L.z*V.w, 0); ## where V is the given vertex and L is our sourceVector ## and the source V.w is 1.0 (model-space) ## V.x *L.w - L.x, L = array(sourceVector,'d') V = take( self.edgeSet.points, backwardIndices,0 ) set = zeros((len(V),4),'d') set[:,0:3] = (V[:,0:3]*L[-1])-L[0:3] self.backwardPoints = set def render( self, mode=None ): """Render the shadow-volume """ if mode.stencil: # XXX these shouldn't be here, but we're making sure # the state really is what we want during testing if not self.edgeSet.ccw: glFrontFace( GL_CW ) try: if __debug__: if mode.debugShadowNoStencil: glStencilMask( 0 ) if not mode.debugShadowNoFrontFaces: # now render front-facing polygons glStencilOp(GL_KEEP, GL_KEEP, GL_INCR); glCullFace(GL_BACK); if __debug__: if mode.debugShadowVolume: glColorMask(0,1,0,0) ## as far as I can see, there is no way for either ## the cap or the boot to change anything on this pass, ## so why bother rendering them? if not mode.debugShadowNoCaps: self._render_cap() if not mode.debugShadowNoEdges: self._render_edges() if not mode.debugShadowNoBoots: self._render_boot() if mode.debugShadowSilouhette: glColorMask(0,1,1,0) self._debug_render_silouhette() if __debug__: glColorMask(0,0,0,0) if not mode.debugShadowNoBackFaces: glStencilOp(GL_KEEP,GL_KEEP,GL_DECR); glCullFace(GL_FRONT); if __debug__: if mode.debugShadowVolume: glColorMask(1,0,0,0) if not mode.debugShadowNoCaps: self._render_cap() if not mode.debugShadowNoEdges: self._render_edges() if not mode.debugShadowNoBoots: self._render_boot() finally: glFrontFace( GL_CCW ) if __debug__: glColorMask(0,0,0,0); glStencilMask( ~0 ) def _render_cap( self ): """Render the shadow-volume cap (forward-facing faces)""" if self.forwardIndices is not None: glVertexPointerd( self.edgeSet.points ) glEnableClientState(GL_VERTEX_ARRAY); glDrawElementsui( GL_TRIANGLES, self.forwardIndices, ) glDisableClientState(GL_VERTEX_ARRAY); def _render_boot( self ): """Render the shadow-volume boot (backward-facing faces projected)""" if self.sideType != GL_TRIANGLES and self.backwardPoints is not None: # if triangles, the volume converges to a point, so there # can be no back-facing polygons... glVertexPointerd(self.backwardPoints ) glEnableClientState(GL_VERTEX_ARRAY); glDrawArrays(GL_TRIANGLES, 0, len(self.backwardPoints)) glDisableClientState(GL_VERTEX_ARRAY); def _render_edges( self ): """Render the shadow-volume edges""" # ignore mode while building... if self.edges is not None: glEnableClientState(GL_VERTEX_ARRAY); glVertexPointerd(self.edges ) assert self.sideType != 0, """%s _render_edges called before sideType determined"""%( self.__class__ ) glDrawArrays( self.sideType, 0, len(self.edges)) glDisableClientState(GL_VERTEX_ARRAY); def _debug_render_silouhette( self ): """Debug render of silouhette as lines with current colour""" ### debug-rendering-mode ## draws edges as blue lines... from OpenGL.GLUT import glutWireSphere if self.sideType == GL_TRIANGLES: step = 3 else: step = 4 Bs = self.edges[0::step] As = self.edges[1::step] glBegin( GL_LINES ) for A,B in map(None, As, Bs): glColor3f( 0,0,1.0) glVertex4dv( A ) glColor3f( 0,1.0,.5) glVertex4dv( B ) glEnd( ) glPushMatrix() glTranslate( *self.sourceVector[:3]) glutWireSphere( .2,8,8) glPopMatrix()
2026-03-31T15:30:29
codeparrot_clean
86914940cbfe717193ac3563ca480575
code
from django.core.management import BaseCommand from geonode.gazetteer.models import GazetteerEntry from geonode.maps.models import Layer class Command(BaseCommand): help = """ Assigns usernames to all gazetteer features that do not have an associated username yet. """ args = '[none]' # TODO update this to new version def handle(self, *args, **kwargs): gaz_layers = GazetteerEntry.objects.filter( username__isnull=True).values('layer_name').distinct() print ("Found %d layers in gazetteer with unasssigned users") % len(gaz_layers) for gl in gaz_layers: lname = gl['layer_name'] try: layer = Layer.objects.get(name=lname) username = layer.owner.username print("Assigning features for %s to %s") % (layer.name, username) GazetteerEntry.objects.filter( layer_name__exact=lname).update(username=username) except Layer.DoesNotExist: print("Layer %s no longer exists, removing from gazetteer" % lname) GazetteerEntry.objects.filter(layer_name__exact=lname).delete() print("Complete")
2026-03-31T15:30:29
codeparrot_clean
a47c3efa161976fba6da0f95e13a8fb2
code
from __future__ import unicode_literals import re from .common import InfoExtractor from ..utils import ( js_to_json, remove_end, ) class HellPornoIE(InfoExtractor): _VALID_URL = r'https?://(?:www\.)?hellporno\.com/videos/(?P<id>[^/]+)' _TEST = { 'url': 'http://hellporno.com/videos/dixie-is-posing-with-naked-ass-very-erotic/', 'md5': '1fee339c610d2049699ef2aa699439f1', 'info_dict': { 'id': '149116', 'display_id': 'dixie-is-posing-with-naked-ass-very-erotic', 'ext': 'mp4', 'title': 'Dixie is posing with naked ass very erotic', 'thumbnail': 're:https?://.*\.jpg$', 'age_limit': 18, } } def _real_extract(self, url): display_id = self._match_id(url) webpage = self._download_webpage(url, display_id) title = remove_end(self._html_search_regex( r'<title>([^<]+)</title>', webpage, 'title'), ' - Hell Porno') flashvars = self._parse_json(self._search_regex( r'var\s+flashvars\s*=\s*({.+?});', webpage, 'flashvars'), display_id, transform_source=js_to_json) video_id = flashvars.get('video_id') thumbnail = flashvars.get('preview_url') ext = flashvars.get('postfix', '.mp4')[1:] formats = [] for video_url_key in ['video_url', 'video_alt_url']: video_url = flashvars.get(video_url_key) if not video_url: continue video_text = flashvars.get('%s_text' % video_url_key) fmt = { 'url': video_url, 'ext': ext, 'format_id': video_text, } m = re.search(r'^(?P<height>\d+)[pP]', video_text) if m: fmt['height'] = int(m.group('height')) formats.append(fmt) self._sort_formats(formats) categories = self._html_search_meta( 'keywords', webpage, 'categories', default='').split(',') return { 'id': video_id, 'display_id': display_id, 'title': title, 'thumbnail': thumbnail, 'categories': categories, 'age_limit': 18, 'formats': formats, }
2026-03-31T15:30:29
codeparrot_clean
062815c3fe807b258223a6c54c3bd5f5
code
""" Low-level helpers for the SecureTransport bindings. These are Python functions that are not directly related to the high-level APIs but are necessary to get them to work. They include a whole bunch of low-level CoreFoundation messing about and memory management. The concerns in this module are almost entirely about trying to avoid memory leaks and providing appropriate and useful assistance to the higher-level code. """ import base64 import ctypes import itertools import re import os import ssl import tempfile from .bindings import Security, CoreFoundation, CFConst # This regular expression is used to grab PEM data out of a PEM bundle. _PEM_CERTS_RE = re.compile( b"-----BEGIN CERTIFICATE-----\n(.*?)\n-----END CERTIFICATE-----", re.DOTALL ) def _cf_data_from_bytes(bytestring): """ Given a bytestring, create a CFData object from it. This CFData object must be CFReleased by the caller. """ return CoreFoundation.CFDataCreate( CoreFoundation.kCFAllocatorDefault, bytestring, len(bytestring) ) def _cf_dictionary_from_tuples(tuples): """ Given a list of Python tuples, create an associated CFDictionary. """ dictionary_size = len(tuples) # We need to get the dictionary keys and values out in the same order. keys = (t[0] for t in tuples) values = (t[1] for t in tuples) cf_keys = (CoreFoundation.CFTypeRef * dictionary_size)(*keys) cf_values = (CoreFoundation.CFTypeRef * dictionary_size)(*values) return CoreFoundation.CFDictionaryCreate( CoreFoundation.kCFAllocatorDefault, cf_keys, cf_values, dictionary_size, CoreFoundation.kCFTypeDictionaryKeyCallBacks, CoreFoundation.kCFTypeDictionaryValueCallBacks, ) def _cf_string_to_unicode(value): """ Creates a Unicode string from a CFString object. Used entirely for error reporting. Yes, it annoys me quite a lot that this function is this complex. """ value_as_void_p = ctypes.cast(value, ctypes.POINTER(ctypes.c_void_p)) string = CoreFoundation.CFStringGetCStringPtr( value_as_void_p, CFConst.kCFStringEncodingUTF8 ) if string is None: buffer = ctypes.create_string_buffer(1024) result = CoreFoundation.CFStringGetCString( value_as_void_p, buffer, 1024, CFConst.kCFStringEncodingUTF8 ) if not result: raise OSError('Error copying C string from CFStringRef') string = buffer.value if string is not None: string = string.decode('utf-8') return string def _assert_no_error(error, exception_class=None): """ Checks the return code and throws an exception if there is an error to report """ if error == 0: return cf_error_string = Security.SecCopyErrorMessageString(error, None) output = _cf_string_to_unicode(cf_error_string) CoreFoundation.CFRelease(cf_error_string) if output is None or output == u'': output = u'OSStatus %s' % error if exception_class is None: exception_class = ssl.SSLError raise exception_class(output) def _cert_array_from_pem(pem_bundle): """ Given a bundle of certs in PEM format, turns them into a CFArray of certs that can be used to validate a cert chain. """ der_certs = [ base64.b64decode(match.group(1)) for match in _PEM_CERTS_RE.finditer(pem_bundle) ] if not der_certs: raise ssl.SSLError("No root certificates specified") cert_array = CoreFoundation.CFArrayCreateMutable( CoreFoundation.kCFAllocatorDefault, 0, ctypes.byref(CoreFoundation.kCFTypeArrayCallBacks) ) if not cert_array: raise ssl.SSLError("Unable to allocate memory!") try: for der_bytes in der_certs: certdata = _cf_data_from_bytes(der_bytes) if not certdata: raise ssl.SSLError("Unable to allocate memory!") cert = Security.SecCertificateCreateWithData( CoreFoundation.kCFAllocatorDefault, certdata ) CoreFoundation.CFRelease(certdata) if not cert: raise ssl.SSLError("Unable to build cert object!") CoreFoundation.CFArrayAppendValue(cert_array, cert) CoreFoundation.CFRelease(cert) except Exception: # We need to free the array before the exception bubbles further. # We only want to do that if an error occurs: otherwise, the caller # should free. CoreFoundation.CFRelease(cert_array) return cert_array def _is_cert(item): """ Returns True if a given CFTypeRef is a certificate. """ expected = Security.SecCertificateGetTypeID() return CoreFoundation.CFGetTypeID(item) == expected def _is_identity(item): """ Returns True if a given CFTypeRef is an identity. """ expected = Security.SecIdentityGetTypeID() return CoreFoundation.CFGetTypeID(item) == expected def _temporary_keychain(): """ This function creates a temporary Mac keychain that we can use to work with credentials. This keychain uses a one-time password and a temporary file to store the data. We expect to have one keychain per socket. The returned SecKeychainRef must be freed by the caller, including calling SecKeychainDelete. Returns a tuple of the SecKeychainRef and the path to the temporary directory that contains it. """ # Unfortunately, SecKeychainCreate requires a path to a keychain. This # means we cannot use mkstemp to use a generic temporary file. Instead, # we're going to create a temporary directory and a filename to use there. # This filename will be 8 random bytes expanded into base64. We also need # some random bytes to password-protect the keychain we're creating, so we # ask for 40 random bytes. random_bytes = os.urandom(40) filename = base64.b64encode(random_bytes[:8]).decode('utf-8') password = base64.b64encode(random_bytes[8:]) # Must be valid UTF-8 tempdirectory = tempfile.mkdtemp() keychain_path = os.path.join(tempdirectory, filename).encode('utf-8') # We now want to create the keychain itself. keychain = Security.SecKeychainRef() status = Security.SecKeychainCreate( keychain_path, len(password), password, False, None, ctypes.byref(keychain) ) _assert_no_error(status) # Having created the keychain, we want to pass it off to the caller. return keychain, tempdirectory def _load_items_from_file(keychain, path): """ Given a single file, loads all the trust objects from it into arrays and the keychain. Returns a tuple of lists: the first list is a list of identities, the second a list of certs. """ certificates = [] identities = [] result_array = None with open(path, 'rb') as f: raw_filedata = f.read() try: filedata = CoreFoundation.CFDataCreate( CoreFoundation.kCFAllocatorDefault, raw_filedata, len(raw_filedata) ) result_array = CoreFoundation.CFArrayRef() result = Security.SecItemImport( filedata, # cert data None, # Filename, leaving it out for now None, # What the type of the file is, we don't care None, # what's in the file, we don't care 0, # import flags None, # key params, can include passphrase in the future keychain, # The keychain to insert into ctypes.byref(result_array) # Results ) _assert_no_error(result) # A CFArray is not very useful to us as an intermediary # representation, so we are going to extract the objects we want # and then free the array. We don't need to keep hold of keys: the # keychain already has them! result_count = CoreFoundation.CFArrayGetCount(result_array) for index in range(result_count): item = CoreFoundation.CFArrayGetValueAtIndex( result_array, index ) item = ctypes.cast(item, CoreFoundation.CFTypeRef) if _is_cert(item): CoreFoundation.CFRetain(item) certificates.append(item) elif _is_identity(item): CoreFoundation.CFRetain(item) identities.append(item) finally: if result_array: CoreFoundation.CFRelease(result_array) CoreFoundation.CFRelease(filedata) return (identities, certificates) def _load_client_cert_chain(keychain, *paths): """ Load certificates and maybe keys from a number of files. Has the end goal of returning a CFArray containing one SecIdentityRef, and then zero or more SecCertificateRef objects, suitable for use as a client certificate trust chain. """ # Ok, the strategy. # # This relies on knowing that macOS will not give you a SecIdentityRef # unless you have imported a key into a keychain. This is a somewhat # artificial limitation of macOS (for example, it doesn't necessarily # affect iOS), but there is nothing inside Security.framework that lets you # get a SecIdentityRef without having a key in a keychain. # # So the policy here is we take all the files and iterate them in order. # Each one will use SecItemImport to have one or more objects loaded from # it. We will also point at a keychain that macOS can use to work with the # private key. # # Once we have all the objects, we'll check what we actually have. If we # already have a SecIdentityRef in hand, fab: we'll use that. Otherwise, # we'll take the first certificate (which we assume to be our leaf) and # ask the keychain to give us a SecIdentityRef with that cert's associated # key. # # We'll then return a CFArray containing the trust chain: one # SecIdentityRef and then zero-or-more SecCertificateRef objects. The # responsibility for freeing this CFArray will be with the caller. This # CFArray must remain alive for the entire connection, so in practice it # will be stored with a single SSLSocket, along with the reference to the # keychain. certificates = [] identities = [] # Filter out bad paths. paths = (path for path in paths if path) try: for file_path in paths: new_identities, new_certs = _load_items_from_file( keychain, file_path ) identities.extend(new_identities) certificates.extend(new_certs) # Ok, we have everything. The question is: do we have an identity? If # not, we want to grab one from the first cert we have. if not identities: new_identity = Security.SecIdentityRef() status = Security.SecIdentityCreateWithCertificate( keychain, certificates[0], ctypes.byref(new_identity) ) _assert_no_error(status) identities.append(new_identity) # We now want to release the original certificate, as we no longer # need it. CoreFoundation.CFRelease(certificates.pop(0)) # We now need to build a new CFArray that holds the trust chain. trust_chain = CoreFoundation.CFArrayCreateMutable( CoreFoundation.kCFAllocatorDefault, 0, ctypes.byref(CoreFoundation.kCFTypeArrayCallBacks), ) for item in itertools.chain(identities, certificates): # ArrayAppendValue does a CFRetain on the item. That's fine, # because the finally block will release our other refs to them. CoreFoundation.CFArrayAppendValue(trust_chain, item) return trust_chain finally: for obj in itertools.chain(identities, certificates): CoreFoundation.CFRelease(obj)
2026-03-31T15:30:29
codeparrot_clean
439ce690296e7db043d80e21a8c0be96
code
def getSocialData(post): # Get Thread Object threadObject = post["thread"] domain_rank = threadObject["domain_rank"] #domain_rank #print 'domain_rank:' + str(domain_rank) socialObject = threadObject["social"] #social data object facebookData = socialObject["facebook"] #facebook data #print 'facebook data:' + str(facebookData["likes"]) + ', ' + str(facebookData["comments"]) + ', ' + str(facebookData["shares"]) fb_likes = facebookData["likes"] fb_comments = facebookData["comments"] fb_shares = facebookData["shares"] gplusData = socialObject["gplus"] #gplus data #print 'gplus data:' + str(gplusData["shares"]) g_shares = gplusData["shares"] pinterestData = socialObject["pinterest"] #pinterest data #print 'pinterest data:' + str(pinterestData["shares"]) pin_shares = pinterestData["shares"] linkedinData = socialObject["linkedin"] #linkedin data #print 'linked data:' + str(linkedinData["shares"]) linkedin_shares = linkedinData["shares"] stumbleduponData= socialObject["stumbledupon"] #print 'lstumbleduponData:' + str(stumbleduponData["shares"]) su_shares = stumbleduponData["shares"] vkData = socialObject["vk"] #print 'vkData:' + str(vkData["shares"]) vk_shares = vkData["shares"] social_impact = (fb_likes + fb_comments + fb_shares + g_shares + pin_shares + linkedin_shares + su_shares + vk_shares) #print str(social_impact) return social_impact
2026-03-31T15:30:29
codeparrot_clean
a85e09948ca1f78a105399dd83ef44d5
code
""" Author: James Ma Email stuff here: jamesmawm@gmail.com """ """ API doumentation: https://www.interactivebrokers.com/en/software/api/apiguide/java/reqhistoricaldata.htm https://www.interactivebrokers.com/en/software/api/apiguide/tables/tick_types.htm """ FIELD_BID_SIZE = 0 FIELD_BID_PRICE = 1 FIELD_ASK_PRICE = 2 FIELD_ASK_SIZE = 3 FIELD_LAST_PRICE = 4 FIELD_LAST_SIZE = 5 FIELD_HIGH = 6 FIELD_LOW = 7 FIELD_VOLUME = 8 FIELD_CLOSE_PRICE = 9 FIELD_AVG_VOLUME = 21 FIELD_BID_EXCH = 32 FIELD_ASK_EXCH = 33 FIELD_AUCTION_VOLUME = 34 FIELD_AUCTION_PRICE = 35 FIELD_LAST_TIMESTAMP = 45 FIELD_HALTED = 49 FIELD_TRADE_COUNT = 54 FIELD_TRADE_RATE = 55 FIELD_VOLUME_RATE = 56 FIELD_HALTED_NOT_HALTED = 0 FIELD_HALTED_IS_HALTED = 1 FIELD_HALTED_BY_VOLATILITY = 2 DURATION_1_HR = '3600 S' DURATION_1_MIN = "60 S" DURATION_1_DAY = '1 D' BAR_SIZE_5_SEC = '5 secs' BAR_SIZE_1_MIN = '1 min' RTH_ALL = 0 RTH_ONLY_TRADING_HRS = 1 WHAT_TO_SHOW_TRADES = "TRADES" WHAT_TO_SHOW_MID_PT = "MIDPOINT" WHAT_TO_SHOW_BID = "BID" WHAT_TO_SHOW_ASK = "ASK" WHAT_TO_SHOW_BID_ASK = "BID_ASK" WHAT_TO_SHOW_HVOL = "HISTORICAL_VOLATILITY" WHAT_TO_SHOW_OPT_IMPV = "OPTION_IMPLIED_VOLATILITY" DATEFORMAT_STRING = 1 DATEFORMAT_UNIX_TS = 2 MSG_TYPE_HISTORICAL_DATA = "historicalData" MSG_TYPE_UPDATE_PORTFOLIO = "updatePortfolio" MSG_TYPE_MANAGED_ACCOUNTS = "managedAccounts" MSG_TYPE_NEXT_ORDER_ID = "nextValidId" MSG_TYPE_TICK_PRICE = "tickPrice" MSG_TYPE_TICK_STRING = "tickString" MSG_TYPE_STICK_SIZE = "tickSize" DATE_TIME_FORMAT = "%Y%m%d %H:%M:%S" DATE_TIME_FORMAT_LONG = "%Y-%m-%d %H:%M:%S" DATE_TIME_FORMAT_LONG_MILLISECS = "%Y-%m-%d %H:%M:%S.%f" GENERIC_TICKS_NONE = '' GENERIC_TICKS_RTVOLUME = "233" SNAPSHOT_NONE = False SNAPSHOT_TRUE = True ORDER_TYPE_MARKET = "MKT" ORDER_TYPE_LIMIT = "LMT" ORDER_ACTION_SELL = "SELL" ORDER_ACTION_BUY = "BUY"
2026-03-31T15:30:29
codeparrot_clean
874590fcd6ff4b50e076a5d13d4ed509
code
# file openpyxl/shared/password_hasher.py # Copyright (c) 2010 openpyxl # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. # # @license: http://www.opensource.org/licenses/mit-license.php # @author: Eric Gazoni """Basic password hashing.""" def hash_password(plaintext_password=''): """Create a password hash from a given string. This method is based on the algorithm provided by Daniel Rentz of OpenOffice and the PEAR package Spreadsheet_Excel_Writer by Xavier Noguer <xnoguer@rezebra.com>. """ password = 0x0000 i = 1 for char in plaintext_password: value = ord(char) << i rotated_bits = value >> 15 value &= 0x7fff password ^= (value | rotated_bits) i += 1 password ^= len(plaintext_password) password ^= 0xCE4B return str(hex(password)).upper()[2:]
2026-03-31T15:30:29
codeparrot_clean
3079d89aaa58e6af76fc955c154fc745
code
# -*- 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 . import test_access_rights checks = [ test_access_rights, ] # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
2026-03-31T15:30:29
codeparrot_clean
7ff7bb11b540544dbbaf8a1fab34ad8c
code
# -*- test-case-name: twisted.internet.test.test_endpoints -*- # Copyright (c) 2007-2010 Twisted Matrix Laboratories. # See LICENSE for details. """ Implementations of L{IStreamServerEndpoint} and L{IStreamClientEndpoint} that wrap the L{IReactorTCP}, L{IReactorSSL}, and L{IReactorUNIX} interfaces. This also implements an extensible mini-language for describing endpoints, parsed by the L{clientFromString} and L{serverFromString} functions. @since: 10.1 """ from zope.interface import implements, directlyProvides import warnings from twisted.internet import interfaces, defer, error from twisted.internet.protocol import ClientFactory, Protocol from twisted.plugin import getPlugins from twisted.internet.interfaces import IStreamServerEndpointStringParser from twisted.internet.interfaces import IStreamClientEndpointStringParser from twisted.python.filepath import FilePath __all__ = ["clientFromString", "serverFromString", "TCP4ServerEndpoint", "TCP4ClientEndpoint", "UNIXServerEndpoint", "UNIXClientEndpoint", "SSL4ServerEndpoint", "SSL4ClientEndpoint"] class _WrappingProtocol(Protocol): """ Wrap another protocol in order to notify my user when a connection has been made. @ivar _connectedDeferred: The L{Deferred} that will callback with the C{wrappedProtocol} when it is connected. @ivar _wrappedProtocol: An L{IProtocol} provider that will be connected. """ def __init__(self, connectedDeferred, wrappedProtocol): """ @param connectedDeferred: The L{Deferred} that will callback with the C{wrappedProtocol} when it is connected. @param wrappedProtocol: An L{IProtocol} provider that will be connected. """ self._connectedDeferred = connectedDeferred self._wrappedProtocol = wrappedProtocol if interfaces.IHalfCloseableProtocol.providedBy( self._wrappedProtocol): directlyProvides(self, interfaces.IHalfCloseableProtocol) def connectionMade(self): """ Connect the C{self._wrappedProtocol} to our C{self.transport} and callback C{self._connectedDeferred} with the C{self._wrappedProtocol} """ self._wrappedProtocol.makeConnection(self.transport) self._connectedDeferred.callback(self._wrappedProtocol) def dataReceived(self, data): """ Proxy C{dataReceived} calls to our C{self._wrappedProtocol} """ return self._wrappedProtocol.dataReceived(data) def connectionLost(self, reason): """ Proxy C{connectionLost} calls to our C{self._wrappedProtocol} """ return self._wrappedProtocol.connectionLost(reason) def readConnectionLost(self): """ Proxy L{IHalfCloseableProtocol.readConnectionLost} to our C{self._wrappedProtocol} """ self._wrappedProtocol.readConnectionLost() def writeConnectionLost(self): """ Proxy L{IHalfCloseableProtocol.writeConnectionLost} to our C{self._wrappedProtocol} """ self._wrappedProtocol.writeConnectionLost() class _WrappingFactory(ClientFactory): """ Wrap a factory in order to wrap the protocols it builds. @ivar _wrappedFactory: A provider of I{IProtocolFactory} whose buildProtocol method will be called and whose resulting protocol will be wrapped. @ivar _onConnection: An L{Deferred} that fires when the protocol is connected """ protocol = _WrappingProtocol def __init__(self, wrappedFactory, canceller): """ @param wrappedFactory: A provider of I{IProtocolFactory} whose buildProtocol method will be called and whose resulting protocol will be wrapped. @param canceller: An object that will be called to cancel the L{self._onConnection} L{Deferred} """ self._wrappedFactory = wrappedFactory self._onConnection = defer.Deferred(canceller=canceller) def buildProtocol(self, addr): """ Proxy C{buildProtocol} to our C{self._wrappedFactory} or errback the C{self._onConnection} L{Deferred}. @return: An instance of L{_WrappingProtocol} or C{None} """ try: proto = self._wrappedFactory.buildProtocol(addr) except: self._onConnection.errback() else: return self.protocol(self._onConnection, proto) def clientConnectionFailed(self, connector, reason): """ Errback the C{self._onConnection} L{Deferred} when the client connection fails. """ self._onConnection.errback(reason) class TCP4ServerEndpoint(object): """ TCP server endpoint with an IPv4 configuration @ivar _reactor: An L{IReactorTCP} provider. @type _port: int @ivar _port: The port number on which to listen for incoming connections. @type _backlog: int @ivar _backlog: size of the listen queue @type _interface: str @ivar _interface: the hostname to bind to, defaults to '' (all) """ implements(interfaces.IStreamServerEndpoint) def __init__(self, reactor, port, backlog=50, interface=''): """ @param reactor: An L{IReactorTCP} provider. @param port: The port number used listening @param backlog: size of the listen queue @param interface: the hostname to bind to, defaults to '' (all) """ self._reactor = reactor self._port = port self._listenArgs = dict(backlog=50, interface='') self._backlog = backlog self._interface = interface def listen(self, protocolFactory): """ Implement L{IStreamServerEndpoint.listen} to listen on a TCP socket """ return defer.execute(self._reactor.listenTCP, self._port, protocolFactory, backlog=self._backlog, interface=self._interface) class TCP4ClientEndpoint(object): """ TCP client endpoint with an IPv4 configuration. @ivar _reactor: An L{IReactorTCP} provider. @type _host: str @ivar _host: The hostname to connect to as a C{str} @type _port: int @ivar _port: The port to connect to as C{int} @type _timeout: int @ivar _timeout: number of seconds to wait before assuming the connection has failed. @type _bindAddress: tuple @type _bindAddress: a (host, port) tuple of local address to bind to, or None. """ implements(interfaces.IStreamClientEndpoint) def __init__(self, reactor, host, port, timeout=30, bindAddress=None): """ @param reactor: An L{IReactorTCP} provider @param host: A hostname, used when connecting @param port: The port number, used when connecting @param timeout: number of seconds to wait before assuming the connection has failed. @param bindAddress: a (host, port tuple of local address to bind to, or None. """ self._reactor = reactor self._host = host self._port = port self._timeout = timeout self._bindAddress = bindAddress def connect(self, protocolFactory): """ Implement L{IStreamClientEndpoint.connect} to connect via TCP. """ def _canceller(deferred): connector.stopConnecting() deferred.errback( error.ConnectingCancelledError(connector.getDestination())) try: wf = _WrappingFactory(protocolFactory, _canceller) connector = self._reactor.connectTCP( self._host, self._port, wf, timeout=self._timeout, bindAddress=self._bindAddress) return wf._onConnection except: return defer.fail() class SSL4ServerEndpoint(object): """ SSL secured TCP server endpoint with an IPv4 configuration. @ivar _reactor: An L{IReactorSSL} provider. @type _host: str @ivar _host: The hostname to connect to as a C{str} @type _port: int @ivar _port: The port to connect to as C{int} @type _sslContextFactory: L{OpenSSLCertificateOptions} @var _sslContextFactory: SSL Configuration information as an L{OpenSSLCertificateOptions} @type _backlog: int @ivar _backlog: size of the listen queue @type _interface: str @ivar _interface: the hostname to bind to, defaults to '' (all) """ implements(interfaces.IStreamServerEndpoint) def __init__(self, reactor, port, sslContextFactory, backlog=50, interface=''): """ @param reactor: An L{IReactorSSL} provider. @param port: The port number used listening @param sslContextFactory: An instance of L{twisted.internet._sslverify.OpenSSLCertificateOptions}. @param timeout: number of seconds to wait before assuming the connection has failed. @param bindAddress: a (host, port tuple of local address to bind to, or None. """ self._reactor = reactor self._port = port self._sslContextFactory = sslContextFactory self._backlog = backlog self._interface = interface def listen(self, protocolFactory): """ Implement L{IStreamServerEndpoint.listen} to listen for SSL on a TCP socket. """ return defer.execute(self._reactor.listenSSL, self._port, protocolFactory, contextFactory=self._sslContextFactory, backlog=self._backlog, interface=self._interface) class SSL4ClientEndpoint(object): """ SSL secured TCP client endpoint with an IPv4 configuration @ivar _reactor: An L{IReactorSSL} provider. @type _host: str @ivar _host: The hostname to connect to as a C{str} @type _port: int @ivar _port: The port to connect to as C{int} @type _sslContextFactory: L{OpenSSLCertificateOptions} @var _sslContextFactory: SSL Configuration information as an L{OpenSSLCertificateOptions} @type _timeout: int @ivar _timeout: number of seconds to wait before assuming the connection has failed. @type _bindAddress: tuple @ivar _bindAddress: a (host, port) tuple of local address to bind to, or None. """ implements(interfaces.IStreamClientEndpoint) def __init__(self, reactor, host, port, sslContextFactory, timeout=30, bindAddress=None): """ @param reactor: An L{IReactorSSL} provider. @param host: A hostname, used when connecting @param port: The port number, used when connecting @param sslContextFactory: SSL Configuration information as An instance of L{OpenSSLCertificateOptions}. @param timeout: number of seconds to wait before assuming the connection has failed. @param bindAddress: a (host, port tuple of local address to bind to, or None. """ self._reactor = reactor self._host = host self._port = port self._sslContextFactory = sslContextFactory self._timeout = timeout self._bindAddress = bindAddress def connect(self, protocolFactory): """ Implement L{IStreamClientEndpoint.connect} to connect with SSL over TCP. """ def _canceller(deferred): connector.stopConnecting() deferred.errback( error.ConnectingCancelledError(connector.getDestination())) try: wf = _WrappingFactory(protocolFactory, _canceller) connector = self._reactor.connectSSL( self._host, self._port, wf, self._sslContextFactory, timeout=self._timeout, bindAddress=self._bindAddress) return wf._onConnection except: return defer.fail() class UNIXServerEndpoint(object): """ UnixSocket server endpoint. @type path: str @ivar path: a path to a unix socket on the filesystem. @type _listenArgs: dict @ivar _listenArgs: A C{dict} of keyword args that will be passed to L{IReactorUNIX.listenUNIX} @var _reactor: An L{IReactorTCP} provider. """ implements(interfaces.IStreamServerEndpoint) def __init__(self, reactor, address, backlog=50, mode=0666, wantPID=0): """ @param reactor: An L{IReactorUNIX} provider. @param address: The path to the Unix socket file, used when listening @param listenArgs: An optional dict of keyword args that will be passed to L{IReactorUNIX.listenUNIX} @param backlog: number of connections to allow in backlog. @param mode: mode to set on the unix socket. This parameter is deprecated. Permissions should be set on the directory which contains the UNIX socket. @param wantPID: if True, create a pidfile for the socket. """ self._reactor = reactor self._address = address self._backlog = backlog self._mode = mode self._wantPID = wantPID def listen(self, protocolFactory): """ Implement L{IStreamServerEndpoint.listen} to listen on a UNIX socket. """ return defer.execute(self._reactor.listenUNIX, self._address, protocolFactory, backlog=self._backlog, mode=self._mode, wantPID=self._wantPID) class UNIXClientEndpoint(object): """ UnixSocket client endpoint. @type _path: str @ivar _path: a path to a unix socket on the filesystem. @type _timeout: int @ivar _timeout: number of seconds to wait before assuming the connection has failed. @type _checkPID: bool @ivar _checkPID: if True, check for a pid file to verify that a server is listening. @var _reactor: An L{IReactorUNIX} provider. """ implements(interfaces.IStreamClientEndpoint) def __init__(self, reactor, path, timeout=30, checkPID=0): """ @param reactor: An L{IReactorUNIX} provider. @param path: The path to the Unix socket file, used when connecting @param timeout: number of seconds to wait before assuming the connection has failed. @param checkPID: if True, check for a pid file to verify that a server is listening. """ self._reactor = reactor self._path = path self._timeout = timeout self._checkPID = checkPID def connect(self, protocolFactory): """ Implement L{IStreamClientEndpoint.connect} to connect via a UNIX Socket """ def _canceller(deferred): connector.stopConnecting() deferred.errback( error.ConnectingCancelledError(connector.getDestination())) try: wf = _WrappingFactory(protocolFactory, _canceller) connector = self._reactor.connectUNIX( self._path, wf, timeout=self._timeout, checkPID=self._checkPID) return wf._onConnection except: return defer.fail() def _parseTCP(factory, port, interface="", backlog=50): """ Internal parser function for L{_parseServer} to convert the string arguments for a TCP(IPv4) stream endpoint into the structured arguments. @param factory: the protocol factory being parsed, or C{None}. (This was a leftover argument from when this code was in C{strports}, and is now mostly None and unused.) @type factory: L{IProtocolFactory} or C{NoneType} @param port: the integer port number to bind @type port: C{str} @param interface: the interface IP to listen on @param backlog: the length of the listen queue @type backlog: C{str} @return: a 2-tuple of (args, kwargs), describing the parameters to L{IReactorTCP.listenTCP} (or, modulo argument 2, the factory, arguments to L{TCP4ServerEndpoint}. """ return (int(port), factory), {'interface': interface, 'backlog': int(backlog)} def _parseUNIX(factory, address, mode='666', backlog=50, lockfile=True): """ Internal parser function for L{_parseServer} to convert the string arguments for a UNIX (AF_UNIX/SOCK_STREAM) stream endpoint into the structured arguments. @param factory: the protocol factory being parsed, or C{None}. (This was a leftover argument from when this code was in C{strports}, and is now mostly None and unused.) @type factory: L{IProtocolFactory} or C{NoneType} @param address: the pathname of the unix socket @type address: C{str} @param backlog: the length of the listen queue @type backlog: C{str} @param lockfile: A string '0' or '1', mapping to True and False respectively. See the C{wantPID} argument to C{listenUNIX} @return: a 2-tuple of (args, kwargs), describing the parameters to L{IReactorTCP.listenUNIX} (or, modulo argument 2, the factory, arguments to L{UNIXServerEndpoint}. """ return ( (address, factory), {'mode': int(mode, 8), 'backlog': int(backlog), 'wantPID': bool(int(lockfile))}) def _parseSSL(factory, port, privateKey="server.pem", certKey=None, sslmethod=None, interface='', backlog=50): """ Internal parser function for L{_parseServer} to convert the string arguments for an SSL (over TCP/IPv4) stream endpoint into the structured arguments. @param factory: the protocol factory being parsed, or C{None}. (This was a leftover argument from when this code was in C{strports}, and is now mostly None and unused.) @type factory: L{IProtocolFactory} or C{NoneType} @param port: the integer port number to bind @type port: C{str} @param interface: the interface IP to listen on @param backlog: the length of the listen queue @type backlog: C{str} @param privateKey: The file name of a PEM format private key file. @type privateKey: C{str} @param certKey: The file name of a PEM format certificate file. @type certKey: C{str} @param sslmethod: The string name of an SSL method, based on the name of a constant in C{OpenSSL.SSL}. Must be one of: "SSLv23_METHOD", "SSLv2_METHOD", "SSLv3_METHOD", "TLSv1_METHOD". @type sslmethod: C{str} @return: a 2-tuple of (args, kwargs), describing the parameters to L{IReactorSSL.listenSSL} (or, modulo argument 2, the factory, arguments to L{SSL4ServerEndpoint}. """ from twisted.internet import ssl if certKey is None: certKey = privateKey kw = {} if sslmethod is not None: kw['sslmethod'] = getattr(ssl.SSL, sslmethod) cf = ssl.DefaultOpenSSLContextFactory(privateKey, certKey, **kw) return ((int(port), factory, cf), {'interface': interface, 'backlog': int(backlog)}) _serverParsers = {"tcp": _parseTCP, "unix": _parseUNIX, "ssl": _parseSSL} _OP, _STRING = range(2) def _tokenize(description): """ Tokenize a strports string and yield each token. @param description: a string as described by L{serverFromString} or L{clientFromString}. @return: an iterable of 2-tuples of (L{_OP} or L{_STRING}, string). Tuples starting with L{_OP} will contain a second element of either ':' (i.e. 'next parameter') or '=' (i.e. 'assign parameter value'). For example, the string 'hello:greet\=ing=world' would result in a generator yielding these values:: _STRING, 'hello' _OP, ':' _STRING, 'greet=ing' _OP, '=' _STRING, 'world' """ current = '' ops = ':=' nextOps = {':': ':=', '=': ':'} description = iter(description) for n in description: if n in ops: yield _STRING, current yield _OP, n current = '' ops = nextOps[n] elif n == '\\': current += description.next() else: current += n yield _STRING, current def _parse(description): """ Convert a description string into a list of positional and keyword parameters, using logic vaguely like what Python does. @param description: a string as described by L{serverFromString} or L{clientFromString}. @return: a 2-tuple of C{(args, kwargs)}, where 'args' is a list of all ':'-separated C{str}s not containing an '=' and 'kwargs' is a map of all C{str}s which do contain an '='. For example, the result of C{_parse('a:b:d=1:c')} would be C{(['a', 'b', 'c'], {'d': '1'})}. """ args, kw = [], {} def add(sofar): if len(sofar) == 1: args.append(sofar[0]) else: kw[sofar[0]] = sofar[1] sofar = () for (type, value) in _tokenize(description): if type is _STRING: sofar += (value,) elif value == ':': add(sofar) sofar = () add(sofar) return args, kw # Mappings from description "names" to endpoint constructors. _endpointServerFactories = { 'TCP': TCP4ServerEndpoint, 'SSL': SSL4ServerEndpoint, 'UNIX': UNIXServerEndpoint, } _endpointClientFactories = { 'TCP': TCP4ClientEndpoint, 'SSL': SSL4ClientEndpoint, 'UNIX': UNIXClientEndpoint, } _NO_DEFAULT = object() def _parseServer(description, factory, default=None): """ Parse a stports description into a 2-tuple of arguments and keyword values. @param description: A description in the format explained by L{serverFromString}. @type description: C{str} @param factory: A 'factory' argument; this is left-over from twisted.application.strports, it's not really used. @type factory: L{IProtocolFactory} or L{None} @param default: Deprecated argument, specifying the default parser mode to use for unqualified description strings (those which do not have a ':' and prefix). @type default: C{str} or C{NoneType} @return: a 3-tuple of (plugin or name, arguments, keyword arguments) """ args, kw = _parse(description) if not args or (len(args) == 1 and not kw): deprecationMessage = ( "Unqualified strport description passed to 'service'." "Use qualified endpoint descriptions; for example, 'tcp:%s'." % (description,)) if default is None: default = 'tcp' warnings.warn( deprecationMessage, category=DeprecationWarning, stacklevel=4) elif default is _NO_DEFAULT: raise ValueError(deprecationMessage) # If the default has been otherwise specified, the user has already # been warned. args[0:0] = [default] endpointType = args[0] parser = _serverParsers.get(endpointType) if parser is None: for plugin in getPlugins(IStreamServerEndpointStringParser): if plugin.prefix == endpointType: return (plugin, args[1:], kw) raise ValueError("Unknown endpoint type: '%s'" % (endpointType,)) return (endpointType.upper(),) + parser(factory, *args[1:], **kw) def _serverFromStringLegacy(reactor, description, default): """ Underlying implementation of L{serverFromString} which avoids exposing the deprecated 'default' argument to anything but L{strports.service}. """ nameOrPlugin, args, kw = _parseServer(description, None, default) if type(nameOrPlugin) is not str: plugin = nameOrPlugin return plugin.parseStreamServer(reactor, *args, **kw) else: name = nameOrPlugin # Chop out the factory. args = args[:1] + args[2:] return _endpointServerFactories[name](reactor, *args, **kw) def serverFromString(reactor, description): """ Construct a stream server endpoint from an endpoint description string. The format for server endpoint descriptions is a simple string. It is a prefix naming the type of endpoint, then a colon, then the arguments for that endpoint. For example, you can call it like this to create an endpoint that will listen on TCP port 80:: serverFromString(reactor, "tcp:80") Additional arguments may be specified as keywords, separated with colons. For example, you can specify the interface for a TCP server endpoint to bind to like this:: serverFromString(reactor, "tcp:80:interface=127.0.0.1") SSL server endpoints may be specified with the 'ssl' prefix, and the private key and certificate files may be specified by the C{privateKey} and C{certKey} arguments:: serverFromString(reactor, "ssl:443:privateKey=key.pem:certKey=crt.pem") If a private key file name (C{privateKey}) isn't provided, a "server.pem" file is assumed to exist which contains the private key. If the certificate file name (C{certKey}) isn't provided, the private key file is assumed to contain the certificate as well. You may escape colons in arguments with a backslash, which you will need to use if you want to specify a full pathname argument on Windows:: serverFromString(reactor, "ssl:443:privateKey=C\\:/key.pem:certKey=C\\:/cert.pem") finally, the 'unix' prefix may be used to specify a filesystem UNIX socket, optionally with a 'mode' argument to specify the mode of the socket file created by C{listen}:: serverFromString(reactor, "unix:/var/run/finger") serverFromString(reactor, "unix:/var/run/finger:mode=660") This function is also extensible; new endpoint types may be registered as L{IStreamServerEndpointStringParser} plugins. See that interface for more information. @param reactor: The server endpoint will be constructed with this reactor. @param description: The strports description to parse. @return: A new endpoint which can be used to listen with the parameters given by by C{description}. @rtype: L{IStreamServerEndpoint<twisted.internet.interfaces.IStreamServerEndpoint>} @raise ValueError: when the 'description' string cannot be parsed. @since: 10.2 """ return _serverFromStringLegacy(reactor, description, _NO_DEFAULT) def quoteStringArgument(argument): """ Quote an argument to L{serverFromString} and L{clientFromString}. Since arguments are separated with colons and colons are escaped with backslashes, some care is necessary if, for example, you have a pathname, you may be tempted to interpolate into a string like this:: serverFromString("ssl:443:privateKey=%s" % (myPathName,)) This may appear to work, but will have portability issues (Windows pathnames, for example). Usually you should just construct the appropriate endpoint type rather than interpolating strings, which in this case would be L{SSL4ServerEndpoint}. There are some use-cases where you may need to generate such a string, though; for example, a tool to manipulate a configuration file which has strports descriptions in it. To be correct in those cases, do this instead:: serverFromString("ssl:443:privateKey=%s" % (quoteStringArgument(myPathName),)) @param argument: The part of the endpoint description string you want to pass through. @type argument: C{str} @return: The quoted argument. @rtype: C{str} """ return argument.replace('\\', '\\\\').replace(':', '\\:') def _parseClientTCP(**kwargs): """ Perform any argument value coercion necessary for TCP client parameters. Valid keyword arguments to this function are all L{IReactorTCP.connectTCP} arguments. @return: The coerced values as a C{dict}. """ kwargs['port'] = int(kwargs['port']) try: kwargs['timeout'] = int(kwargs['timeout']) except KeyError: pass return kwargs def _loadCAsFromDir(directoryPath): """ Load certificate-authority certificate objects in a given directory. @param directoryPath: a L{FilePath} pointing at a directory to load .pem files from. @return: a C{list} of L{OpenSSL.crypto.X509} objects. """ from twisted.internet import ssl caCerts = {} for child in directoryPath.children(): if not child.basename().split('.')[-1].lower() == 'pem': continue try: data = child.getContent() except IOError: # Permission denied, corrupt disk, we don't care. continue try: theCert = ssl.Certificate.loadPEM(data) except ssl.SSL.Error: # Duplicate certificate, invalid certificate, etc. We don't care. pass else: caCerts[theCert.digest()] = theCert.original return caCerts.values() def _parseClientSSL(**kwargs): """ Perform any argument value coercion necessary for SSL client parameters. Valid keyword arguments to this function are all L{IReactorSSL.connectSSL} arguments except for C{contextFactory}. Instead, C{certKey} (the path name of the certificate file) C{privateKey} (the path name of the private key associated with the certificate) are accepted and used to construct a context factory. @param caCertsDir: The one parameter which is not part of L{IReactorSSL.connectSSL}'s signature, this is a path name used to construct a list of certificate authority certificates. The directory will be scanned for files ending in C{.pem}, all of which will be considered valid certificate authorities for this connection. @type caCertsDir: C{str} @return: The coerced values as a C{dict}. """ from twisted.internet import ssl kwargs = _parseClientTCP(**kwargs) certKey = kwargs.pop('certKey', None) privateKey = kwargs.pop('privateKey', None) caCertsDir = kwargs.pop('caCertsDir', None) if certKey is not None: certx509 = ssl.Certificate.loadPEM( FilePath(certKey).getContent()).original else: certx509 = None if privateKey is not None: privateKey = ssl.PrivateCertificate.loadPEM( FilePath(privateKey).getContent()).privateKey.original else: privateKey = None if caCertsDir is not None: verify = True caCerts = _loadCAsFromDir(FilePath(caCertsDir)) else: verify = False caCerts = None kwargs['sslContextFactory'] = ssl.CertificateOptions( method=ssl.SSL.SSLv23_METHOD, certificate=certx509, privateKey=privateKey, verify=verify, caCerts=caCerts ) return kwargs def _parseClientUNIX(**kwargs): """ Perform any argument value coercion necessary for UNIX client parameters. Valid keyword arguments to this function are all L{IReactorUNIX.connectUNIX} arguments except for C{checkPID}. Instead, C{lockfile} is accepted and has the same meaning. @return: The coerced values as a C{dict}. """ try: kwargs['checkPID'] = bool(int(kwargs.pop('lockfile'))) except KeyError: pass try: kwargs['timeout'] = int(kwargs['timeout']) except KeyError: pass return kwargs _clientParsers = { 'TCP': _parseClientTCP, 'SSL': _parseClientSSL, 'UNIX': _parseClientUNIX, } def clientFromString(reactor, description): """ Construct a client endpoint from a description string. Client description strings are much like server description strings, although they take all of their arguments as keywords, since even the simplest client endpoint (plain TCP) requires at least 2 arguments (host and port) to construct. You can create a TCP client endpoint with the 'host' and 'port' arguments, like so:: clientFromString(reactor, "tcp:host=www.example.com:port=80") or an SSL client endpoint with those arguments, plus the arguments used by the server SSL, for a client certificate:: clientFromString(reactor, "ssl:host=web.example.com:port=443:" "privateKey=foo.pem:certKey=foo.pem") to specify your certificate trust roots, you can identify a directory with PEM files in it with the C{caCertsDir} argument:: clientFromString(reactor, "ssl:host=web.example.com:port=443:" "caCertsDir=/etc/ssl/certs") This function is also extensible; new endpoint types may be registered as L{IStreamClientEndpointStringParser} plugins. See that interface for more information. @param reactor: The client endpoint will be constructed with this reactor. @param description: The strports description to parse. @return: A new endpoint which can be used to connect with the parameters given by by C{description}. @rtype: L{IStreamClientEndpoint<twisted.internet.interfaces.IStreamClientEndpoint>} @since: 10.2 """ args, kwargs = _parse(description) aname = args.pop(0) name = aname.upper() for plugin in getPlugins(IStreamClientEndpointStringParser): if plugin.prefix.upper() == name: return plugin.parseStreamClient(*args, **kwargs) if name not in _clientParsers: raise ValueError("Unknown endpoint type: %r" % (aname,)) kwargs = _clientParsers[name](*args, **kwargs) return _endpointClientFactories[name](reactor, **kwargs)
2026-03-31T15:30:29
codeparrot_clean
8590fc20be83560928e768cc710930cf
code
# -*- coding: utf-8 -*- # # Mocha documentation build configuration file, created by # sphinx-quickstart on Thu Nov 13 00:43:40 2014. # # This file is execfile()d with the current directory set to its # containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. import sys import os # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. #sys.path.insert(0, os.path.abspath('.')) sys.path.insert(0, os.path.abspath("sphinx")) import julia # -- General configuration ------------------------------------------------ # If your documentation needs a minimal Sphinx version, state it here. #needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom # ones. extensions = [ 'sphinx.ext.mathjax', 'julia' ] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix of source filenames. source_suffix = '.rst' # The encoding of source files. #source_encoding = 'utf-8-sig' # The master toctree document. master_doc = 'index' # General information about the project. project = u'Mocha' copyright = u'2014, pluskid' # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. version = '0.0.9' # The full version, including alpha/beta/rc tags. release = '0.0.9' # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. #language = None # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: #today = '' # Else, today_fmt is used as the format for a strftime call. #today_fmt = '%B %d, %Y' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. exclude_patterns = ['_build'] # The reST default role (used for this markup: `text`) to use for all # documents. #default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. #add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). #add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. #show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # A list of ignored prefixes for module index sorting. #modindex_common_prefix = [] primary_domain = 'jl' highlight_language = 'julia' # If true, keep warnings as "system message" paragraphs in the built documents. #keep_warnings = False # -- Options for HTML output ---------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin theme html_theme = 'default' import os on_rtd = os.environ.get('READTHEDOCS', None) == 'True' if not on_rtd: # only import and set the theme if we're building docs locally try: import sphinx_rtd_theme html_theme = "sphinx_rtd_theme" html_theme_path = [sphinx_rtd_theme.get_html_theme_path()] except: pass # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. #html_theme_options = {} # Add any paths that contain custom themes here, relative to this directory. #html_theme_path = [] # The name for this set of Sphinx documents. If None, it defaults to # "<project> v<release> documentation". #html_title = None # A shorter title for the navigation bar. Default is the same as html_title. #html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. #html_logo = None # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. #html_favicon = None # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ['_static'] # Add any extra paths that contain custom files (such as robots.txt or # .htaccess) here, relative to this directory. These files are copied # directly to the root of the documentation. #html_extra_path = [] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. #html_last_updated_fmt = '%b %d, %Y' # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. #html_use_smartypants = True # Custom sidebar templates, maps document names to template names. #html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. #html_additional_pages = {} # If false, no module index is generated. #html_domain_indices = True # If false, no index is generated. #html_use_index = True # If true, the index is split into individual pages for each letter. #html_split_index = False # If true, links to the reST sources are added to the pages. #html_show_sourcelink = True # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. #html_show_sphinx = True # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. #html_show_copyright = True # If true, an OpenSearch description file will be output, and all pages will # contain a <link> tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. #html_use_opensearch = '' # This is the file name suffix for HTML files (e.g. ".xhtml"). #html_file_suffix = None # Output file base name for HTML help builder. htmlhelp_basename = 'Mochadoc' # -- Options for LaTeX output --------------------------------------------- latex_elements = { # The paper size ('letterpaper' or 'a4paper'). #'papersize': 'letterpaper', # The font size ('10pt', '11pt' or '12pt'). #'pointsize': '10pt', # Additional stuff for the LaTeX preamble. #'preamble': '', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, # author, documentclass [howto, manual, or own class]). latex_documents = [ ('index', 'Mocha.tex', u'Mocha Documentation', u'pluskid', 'manual'), ] # The name of an image file (relative to this directory) to place at the top of # the title page. #latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. #latex_use_parts = False # If true, show page references after internal links. #latex_show_pagerefs = False # If true, show URL addresses after external links. #latex_show_urls = False # Documents to append as an appendix to all manuals. #latex_appendices = [] # If false, no module index is generated. #latex_domain_indices = True # -- Options for manual page output --------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ ('index', 'mocha', u'Mocha Documentation', [u'pluskid'], 1) ] # If true, show URL addresses after external links. #man_show_urls = False # -- Options for Texinfo output ------------------------------------------- # Grouping the document tree into Texinfo files. List of tuples # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ ('index', 'Mocha', u'Mocha Documentation', u'pluskid', 'Mocha', 'One line description of project.', 'Miscellaneous'), ] # Documents to append as an appendix to all manuals. #texinfo_appendices = [] # If false, no module index is generated. #texinfo_domain_indices = True # How to display URL addresses: 'footnote', 'no', or 'inline'. #texinfo_show_urls = 'footnote' # If true, do not generate a @detailmenu in the "Top" node's menu. #texinfo_no_detailmenu = False
2026-03-31T15:30:29
codeparrot_clean
9acae38e1fd3de9e5b706af6bb852a90
code
#!/usr/bin/env python # LOG ANALYZER # by Kevin Yang # # Assumes VERY MUCH THIS FORMAT: # [<time>] <event> -> <data> import sys, re import numpy as np def find_outliers(array, mean = None, std = None, m = 6): if mean == None: mean = np.mean(array) if std == None: std = np.std(array) return array[abs(array - mean) >= m * std] if __name__ == "__main__": log_file = open(sys.argv[1]) regex = re.compile(r"\[(?P<time>\d+)\] (?P<event>\w*) -> (?P<data>.*)") events = [] for line in log_file: match = re.search(regex, line) if match == None: print("error parsing line: " + line) continue event = { "time" : match.group("time"), "event" : match.group("event"), "data" : eval(match.group("data")), } events.append(event) if len(events) <= 0: exit() data_query = dict([(key, []) for key in events[0]["data"].keys()]) for event in events: for key in data_query.keys(): data_query[key].append(event["data"][key]) for query, data in data_query.items(): data_query[query] = { "data" : np.array(data) } # calculations for query, stats in data_query.items(): data = stats["data"] stats["median"] = np.median(data) stats["mean"] = np.mean(data) stats["min"] = np.min(data) stats["max"] = np.max(data) stats["std"] = np.std(data) stats["outliers"] = find_outliers(data, stats["mean"], stats["std"]) # output for query, stats in data_query.items(): print(query + ":") for stat, value in stats.items(): print("\t%s: %s" % (stat, str(value))) print("")
2026-03-31T15:30:29
codeparrot_clean
bcf6c14829195a901de5a5a65c34a000
code
#!/usr/bin/python """Interface to journalctl.""" from time import time import json import re import subprocess from ansible.module_utils.basic import AnsibleModule class InvalidMatcherRegexp(Exception): """Exception class for invalid matcher regexp.""" pass class InvalidLogEntry(Exception): """Exception class for invalid / non-json log entries.""" pass class LogInputSubprocessError(Exception): """Exception class for errors that occur while executing a subprocess.""" pass def main(): """Scan a given list of "log_matchers" for journalctl messages containing given patterns. "log_matchers" is a list of dicts consisting of three keys that help fine-tune log searching: 'start_regexp', 'regexp', and 'unit'. Sample "log_matchers" list: [ { 'start_regexp': r'Beginning of systemd unit', 'regexp': r'the specific log message to find', 'unit': 'etcd', } ] """ module = AnsibleModule( argument_spec=dict( log_count_limit=dict(type="int", default=500), log_matchers=dict(type="list", required=True), ), ) timestamp_limit_seconds = time() - 60 * 60 # 1 hour log_count_limit = module.params["log_count_limit"] log_matchers = module.params["log_matchers"] matched_regexp, errors = get_log_matches(log_matchers, log_count_limit, timestamp_limit_seconds) module.exit_json( changed=False, failed=bool(errors), errors=errors, matched=matched_regexp, ) def get_log_matches(matchers, log_count_limit, timestamp_limit_seconds): """Return a list of up to log_count_limit matches for each matcher. Log entries are only considered if newer than timestamp_limit_seconds. """ matched_regexp = [] errors = [] for matcher in matchers: try: log_output = get_log_output(matcher) except LogInputSubprocessError as err: errors.append(str(err)) continue try: matched = find_matches(log_output, matcher, log_count_limit, timestamp_limit_seconds) if matched: matched_regexp.append(matcher.get("regexp", "")) except InvalidMatcherRegexp as err: errors.append(str(err)) except InvalidLogEntry as err: errors.append(str(err)) return matched_regexp, errors def get_log_output(matcher): """Return an iterator on the logs of a given matcher.""" try: cmd_output = subprocess.Popen(list([ '/bin/journalctl', '-ru', matcher.get("unit", ""), '--output', 'json', ]), stdout=subprocess.PIPE) return iter(cmd_output.stdout.readline, '') except subprocess.CalledProcessError as exc: msg = "Could not obtain journalctl logs for the specified systemd unit: {}: {}" raise LogInputSubprocessError(msg.format(matcher.get("unit", "<missing>"), str(exc))) except OSError as exc: raise LogInputSubprocessError(str(exc)) def find_matches(log_output, matcher, log_count_limit, timestamp_limit_seconds): """Return log messages matched in iterable log_output by a given matcher. Ignore any log_output items older than timestamp_limit_seconds. """ try: regexp = re.compile(matcher.get("regexp", "")) start_regexp = re.compile(matcher.get("start_regexp", "")) except re.error as err: msg = "A log matcher object was provided with an invalid regular expression: {}" raise InvalidMatcherRegexp(msg.format(str(err))) matched = None for log_count, line in enumerate(log_output): if log_count >= log_count_limit: break try: obj = json.loads(line) # don't need to look past the most recent service restart if start_regexp.match(obj["MESSAGE"]): break log_timestamp_seconds = float(obj["__REALTIME_TIMESTAMP"]) / 1000000 if log_timestamp_seconds < timestamp_limit_seconds: break if regexp.match(obj["MESSAGE"]): matched = line break except ValueError: msg = "Log entry for systemd unit {} contained invalid json syntax: {}" raise InvalidLogEntry(msg.format(matcher.get("unit"), line)) return matched if __name__ == '__main__': main()
2026-03-31T15:30:29
codeparrot_clean
2346b4da33ed100f43b2b0454009feb8
code
# Copyright 2012 United States Government as represented by the # Administrator of the National Aeronautics and Space Administration. # All Rights Reserved. # # Copyright 2012 Cisco Systems, Inc. # Copyright 2012 NEC Corporation # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from __future__ import absolute_import import collections import logging import netaddr from django.conf import settings from django.utils.translation import ugettext_lazy as _ from neutronclient.common import exceptions as neutron_exc from neutronclient.v2_0 import client as neutron_client import six from horizon import messages from horizon.utils.memoized import memoized # noqa from openstack_dashboard.api import base from openstack_dashboard.api import network_base from openstack_dashboard.api import nova from openstack_dashboard import policy LOG = logging.getLogger(__name__) IP_VERSION_DICT = {4: 'IPv4', 6: 'IPv6'} OFF_STATE = 'OFF' ON_STATE = 'ON' ROUTER_INTERFACE_OWNERS = ( 'network:router_interface', 'network:router_interface_distributed' ) class NeutronAPIDictWrapper(base.APIDictWrapper): def __init__(self, apidict): if 'admin_state_up' in apidict: if apidict['admin_state_up']: apidict['admin_state'] = 'UP' else: apidict['admin_state'] = 'DOWN' # Django cannot handle a key name with ':', so use '__'. apidict.update({ key.replace(':', '__'): value for key, value in apidict.items() if ':' in key }) super(NeutronAPIDictWrapper, self).__init__(apidict) def set_id_as_name_if_empty(self, length=8): try: if not self._apidict['name']: id = self._apidict['id'] if length: id = id[:length] self._apidict['name'] = '(%s)' % id except KeyError: pass def items(self): return self._apidict.items() @property def name_or_id(self): return (self._apidict.get('name') or '(%s)' % self._apidict['id'][:13]) class Agent(NeutronAPIDictWrapper): """Wrapper for neutron agents.""" class Network(NeutronAPIDictWrapper): """Wrapper for neutron Networks.""" def to_dict(self): d = dict(super(NeutronAPIDictWrapper, self).to_dict()) d['subnets'] = [s.to_dict() for s in d['subnets']] return d class Subnet(NeutronAPIDictWrapper): """Wrapper for neutron subnets.""" def __init__(self, apidict): apidict['ipver_str'] = get_ipver_str(apidict['ip_version']) super(Subnet, self).__init__(apidict) class SubnetPool(NeutronAPIDictWrapper): """Wrapper for neutron subnetpools.""" class Port(NeutronAPIDictWrapper): """Wrapper for neutron ports.""" def __init__(self, apidict): if 'mac_learning_enabled' in apidict: apidict['mac_state'] = \ ON_STATE if apidict['mac_learning_enabled'] else OFF_STATE super(Port, self).__init__(apidict) class Profile(NeutronAPIDictWrapper): """Wrapper for neutron profiles.""" _attrs = ['profile_id', 'name', 'segment_type', 'segment_range', 'sub_type', 'multicast_ip_index', 'multicast_ip_range'] class Router(NeutronAPIDictWrapper): """Wrapper for neutron routers.""" class RouterStaticRoute(NeutronAPIDictWrapper): """Wrapper for neutron routes extra route.""" def __init__(self, route): super(RouterStaticRoute, self).__init__(route) # Horizon references id property for table operations self.id = route['nexthop'] + ":" + route['destination'] class SecurityGroup(NeutronAPIDictWrapper): # Required attributes: id, name, description, tenant_id, rules def __init__(self, sg, sg_dict=None): if sg_dict is None: sg_dict = {sg['id']: sg['name']} sg['rules'] = [SecurityGroupRule(rule, sg_dict) for rule in sg['security_group_rules']] super(SecurityGroup, self).__init__(sg) def to_dict(self): return {k: self._apidict[k] for k in self._apidict if k != 'rules'} @six.python_2_unicode_compatible class SecurityGroupRule(NeutronAPIDictWrapper): # Required attributes: # id, parent_group_id # ip_protocol, from_port, to_port, ip_range, group # ethertype, direction (Neutron specific) def _get_secgroup_name(self, sg_id, sg_dict): if sg_id: if sg_dict is None: sg_dict = {} # If sg name not found in sg_dict, # first two parts of UUID is used as sg name. return sg_dict.get(sg_id, sg_id[:13]) else: return u'' def __init__(self, sgr, sg_dict=None): # In Neutron, if both remote_ip_prefix and remote_group_id are None, # it means all remote IP range is allowed, i.e., 0.0.0.0/0 or ::/0. if not sgr['remote_ip_prefix'] and not sgr['remote_group_id']: if sgr['ethertype'] == 'IPv6': sgr['remote_ip_prefix'] = '::/0' else: sgr['remote_ip_prefix'] = '0.0.0.0/0' rule = { 'id': sgr['id'], 'parent_group_id': sgr['security_group_id'], 'direction': sgr['direction'], 'ethertype': sgr['ethertype'], 'ip_protocol': sgr['protocol'], 'from_port': sgr['port_range_min'], 'to_port': sgr['port_range_max'], } cidr = sgr['remote_ip_prefix'] rule['ip_range'] = {'cidr': cidr} if cidr else {} group = self._get_secgroup_name(sgr['remote_group_id'], sg_dict) rule['group'] = {'name': group} if group else {} super(SecurityGroupRule, self).__init__(rule) def __str__(self): if 'name' in self.group: remote = self.group['name'] elif 'cidr' in self.ip_range: remote = self.ip_range['cidr'] else: remote = 'ANY' direction = 'to' if self.direction == 'egress' else 'from' if self.from_port: if self.from_port == self.to_port: proto_port = ("%s/%s" % (self.from_port, self.ip_protocol.lower())) else: proto_port = ("%s-%s/%s" % (self.from_port, self.to_port, self.ip_protocol.lower())) elif self.ip_protocol: try: ip_proto = int(self.ip_protocol) proto_port = "ip_proto=%d" % ip_proto except Exception: # well-defined IP protocol name like TCP, UDP, ICMP. proto_port = self.ip_protocol else: proto_port = '' return (_('ALLOW %(ethertype)s %(proto_port)s ' '%(direction)s %(remote)s') % {'ethertype': self.ethertype, 'proto_port': proto_port, 'remote': remote, 'direction': direction}) class SecurityGroupManager(network_base.SecurityGroupManager): backend = 'neutron' def __init__(self, request): self.request = request self.client = neutronclient(request) def _list(self, **filters): secgroups = self.client.list_security_groups(**filters) return [SecurityGroup(sg) for sg in secgroups.get('security_groups')] def list(self): tenant_id = self.request.user.tenant_id return self._list(tenant_id=tenant_id) def _sg_name_dict(self, sg_id, rules): """Create a mapping dict from secgroup id to its name.""" related_ids = set([sg_id]) related_ids |= set(filter(None, [r['remote_group_id'] for r in rules])) related_sgs = self.client.list_security_groups(id=related_ids, fields=['id', 'name']) related_sgs = related_sgs.get('security_groups') return dict((sg['id'], sg['name']) for sg in related_sgs) def get(self, sg_id): secgroup = self.client.show_security_group(sg_id).get('security_group') sg_dict = self._sg_name_dict(sg_id, secgroup['security_group_rules']) return SecurityGroup(secgroup, sg_dict) def create(self, name, desc): body = {'security_group': {'name': name, 'description': desc, 'tenant_id': self.request.user.project_id}} secgroup = self.client.create_security_group(body) return SecurityGroup(secgroup.get('security_group')) def update(self, sg_id, name, desc): body = {'security_group': {'name': name, 'description': desc}} secgroup = self.client.update_security_group(sg_id, body) return SecurityGroup(secgroup.get('security_group')) def delete(self, sg_id): self.client.delete_security_group(sg_id) def rule_create(self, parent_group_id, direction=None, ethertype=None, ip_protocol=None, from_port=None, to_port=None, cidr=None, group_id=None): if not cidr: cidr = None if from_port < 0: from_port = None if to_port < 0: to_port = None if isinstance(ip_protocol, int) and ip_protocol < 0: ip_protocol = None body = {'security_group_rule': {'security_group_id': parent_group_id, 'direction': direction, 'ethertype': ethertype, 'protocol': ip_protocol, 'port_range_min': from_port, 'port_range_max': to_port, 'remote_ip_prefix': cidr, 'remote_group_id': group_id}} rule = self.client.create_security_group_rule(body) rule = rule.get('security_group_rule') sg_dict = self._sg_name_dict(parent_group_id, [rule]) return SecurityGroupRule(rule, sg_dict) def rule_delete(self, sgr_id): self.client.delete_security_group_rule(sgr_id) def list_by_instance(self, instance_id): """Gets security groups of an instance.""" ports = port_list(self.request, device_id=instance_id) sg_ids = [] for p in ports: sg_ids += p.security_groups return self._list(id=set(sg_ids)) if sg_ids else [] def update_instance_security_group(self, instance_id, new_security_group_ids): ports = port_list(self.request, device_id=instance_id) for p in ports: params = {'security_groups': new_security_group_ids} port_update(self.request, p.id, **params) class FloatingIp(base.APIDictWrapper): _attrs = ['id', 'ip', 'fixed_ip', 'port_id', 'instance_id', 'instance_type', 'pool'] def __init__(self, fip): fip['ip'] = fip['floating_ip_address'] fip['fixed_ip'] = fip['fixed_ip_address'] fip['pool'] = fip['floating_network_id'] super(FloatingIp, self).__init__(fip) class FloatingIpPool(base.APIDictWrapper): pass class FloatingIpTarget(base.APIDictWrapper): pass class FloatingIpManager(network_base.FloatingIpManager): device_owner_map = { 'compute:': 'compute', 'neutron:LOADBALANCER': 'loadbalancer', } def __init__(self, request): self.request = request self.client = neutronclient(request) def list_pools(self): search_opts = {'router:external': True} return [FloatingIpPool(pool) for pool in self.client.list_networks(**search_opts).get('networks')] def _get_instance_type_from_device_owner(self, device_owner): for key, value in self.device_owner_map.items(): if device_owner.startswith(key): return value return device_owner def _set_instance_info(self, fip, port=None): if fip['port_id']: if not port: port = port_get(self.request, fip['port_id']) fip['instance_id'] = port.device_id fip['instance_type'] = self._get_instance_type_from_device_owner( port.device_owner) else: fip['instance_id'] = None fip['instance_type'] = None def list(self, all_tenants=False, **search_opts): if not all_tenants: tenant_id = self.request.user.tenant_id # In Neutron, list_floatingips returns Floating IPs from # all tenants when the API is called with admin role, so # we need to filter them with tenant_id. search_opts['tenant_id'] = tenant_id port_search_opts = {'tenant_id': tenant_id} else: port_search_opts = {} fips = self.client.list_floatingips(**search_opts) fips = fips.get('floatingips') # Get port list to add instance_id to floating IP list # instance_id is stored in device_id attribute ports = port_list(self.request, **port_search_opts) port_dict = collections.OrderedDict([(p['id'], p) for p in ports]) for fip in fips: self._set_instance_info(fip, port_dict.get(fip['port_id'])) return [FloatingIp(fip) for fip in fips] def get(self, floating_ip_id): fip = self.client.show_floatingip(floating_ip_id).get('floatingip') self._set_instance_info(fip) return FloatingIp(fip) def allocate(self, pool): body = {'floatingip': {'floating_network_id': pool, 'tenant_id': self.request.user.project_id}} fip = self.client.create_floatingip(body).get('floatingip') self._set_instance_info(fip) return FloatingIp(fip) def release(self, floating_ip_id): self.client.delete_floatingip(floating_ip_id) def associate(self, floating_ip_id, port_id): # NOTE: In Neutron Horizon floating IP support, port_id is # "<port_id>_<ip_address>" format to identify multiple ports. pid, ip_address = port_id.split('_', 1) update_dict = {'port_id': pid, 'fixed_ip_address': ip_address} self.client.update_floatingip(floating_ip_id, {'floatingip': update_dict}) def disassociate(self, floating_ip_id): update_dict = {'port_id': None} self.client.update_floatingip(floating_ip_id, {'floatingip': update_dict}) def _get_reachable_subnets(self, ports): if not is_enabled_by_config('enable_fip_topology_check', True): # All subnets are reachable from external network return set( p.fixed_ips[0]['subnet_id'] for p in ports if p.fixed_ips ) # Retrieve subnet list reachable from external network ext_net_ids = [ext_net.id for ext_net in self.list_pools()] gw_routers = [r.id for r in router_list(self.request) if (r.external_gateway_info and r.external_gateway_info.get('network_id') in ext_net_ids)] reachable_subnets = set([p.fixed_ips[0]['subnet_id'] for p in ports if ((p.device_owner in ROUTER_INTERFACE_OWNERS) and (p.device_id in gw_routers))]) # we have to include any shared subnets as well because we may not # have permission to see the router interface to infer connectivity shared = set([s.id for n in network_list(self.request, shared=True) for s in n.subnets]) return reachable_subnets | shared def list_targets(self): tenant_id = self.request.user.tenant_id ports = port_list(self.request, tenant_id=tenant_id) servers, has_more = nova.server_list(self.request) server_dict = collections.OrderedDict( [(s.id, s.name) for s in servers]) reachable_subnets = self._get_reachable_subnets(ports) if is_service_enabled(self.request, config_name='enable_lb', ext_name='lbaas'): # Also get the loadbalancer VIPs vip_dict = {v['port_id']: v['name'] for v in self.client.list_vips().get('vips', [])} else: vip_dict = {} targets = [] for p in ports: # Remove network ports from Floating IP targets if p.device_owner.startswith('network:'): continue port_id = p.id server_name = server_dict.get(p.device_id) or vip_dict.get(port_id) for ip in p.fixed_ips: if ip['subnet_id'] not in reachable_subnets: continue target = {'name': '%s: %s' % (server_name, ip['ip_address']), 'id': '%s_%s' % (port_id, ip['ip_address']), 'port_id': port_id, 'instance_id': p.device_id} targets.append(FloatingIpTarget(target)) return targets def _target_ports_by_instance(self, instance_id): if not instance_id: return None search_opts = {'device_id': instance_id} return port_list(self.request, **search_opts) def get_target_id_by_instance(self, instance_id, target_list=None): if target_list is not None: targets = [target for target in target_list if target['instance_id'] == instance_id] if not targets: return None return targets[0]['id'] else: # In Neutron one port can have multiple ip addresses, so this # method picks up the first one and generate target id. ports = self._target_ports_by_instance(instance_id) if not ports: return None return '{0}_{1}'.format(ports[0].id, ports[0].fixed_ips[0]['ip_address']) def list_target_id_by_instance(self, instance_id, target_list=None): if target_list is not None: return [target['id'] for target in target_list if target['instance_id'] == instance_id] else: ports = self._target_ports_by_instance(instance_id) return ['{0}_{1}'.format(p.id, p.fixed_ips[0]['ip_address']) for p in ports] def is_simple_associate_supported(self): # NOTE: There are two reason that simple association support # needs more considerations. (1) Neutron does not support the # default floating IP pool at the moment. It can be avoided # in case where only one floating IP pool exists. # (2) Neutron floating IP is associated with each VIF and # we need to check whether such VIF is only one for an instance # to enable simple association support. return False def is_supported(self): network_config = getattr(settings, 'OPENSTACK_NEUTRON_NETWORK', {}) return network_config.get('enable_router', True) def get_ipver_str(ip_version): """Convert an ip version number to a human-friendly string.""" return IP_VERSION_DICT.get(ip_version, '') @memoized def neutronclient(request): insecure = getattr(settings, 'OPENSTACK_SSL_NO_VERIFY', False) cacert = getattr(settings, 'OPENSTACK_SSL_CACERT', None) c = neutron_client.Client(token=request.user.token.id, auth_url=base.url_for(request, 'identity'), endpoint_url=base.url_for(request, 'network'), insecure=insecure, ca_cert=cacert) return c def list_resources_with_long_filters(list_method, filter_attr, filter_values, **params): """List neutron resources with handling RequestURITooLong exception. If filter parameters are long, list resources API request leads to 414 error (URL is too long). For such case, this method split list parameters specified by a list_field argument into chunks and call the specified list_method repeatedly. :param list_method: Method used to retrieve resource list. :param filter_attr: attribute name to be filtered. The value corresponding to this attribute is specified by "filter_values". If you want to specify more attributes for a filter condition, pass them as keyword arguments like "attr2=values2". :param filter_values: values of "filter_attr" to be filtered. If filter_values are too long and the total URI length exceed the maximum length supported by the neutron server, filter_values will be split into sub lists if filter_values is a list. :param params: parameters to pass a specified listing API call without any changes. You can specify more filter conditions in addition to a pair of filter_attr and filter_values. """ try: params[filter_attr] = filter_values return list_method(**params) except neutron_exc.RequestURITooLong as uri_len_exc: # The URI is too long because of too many filter values. # Use the excess attribute of the exception to know how many # filter values can be inserted into a single request. # We consider only the filter condition from (filter_attr, # filter_values) and do not consider other filter conditions # which may be specified in **params. if type(filter_values) != list: filter_values = [filter_values] # Length of each query filter is: # <key>=<value>& (e.g., id=<uuid>) # The length will be key_len + value_maxlen + 2 all_filter_len = sum(len(filter_attr) + len(val) + 2 for val in filter_values) allowed_filter_len = all_filter_len - uri_len_exc.excess val_maxlen = max(len(val) for val in filter_values) filter_maxlen = len(filter_attr) + val_maxlen + 2 chunk_size = allowed_filter_len / filter_maxlen resources = [] for i in range(0, len(filter_values), chunk_size): params[filter_attr] = filter_values[i:i + chunk_size] resources.extend(list_method(**params)) return resources def network_list(request, **params): LOG.debug("network_list(): params=%s", params) networks = neutronclient(request).list_networks(**params).get('networks') # Get subnet list to expand subnet info in network list. subnets = subnet_list(request) subnet_dict = dict([(s['id'], s) for s in subnets]) # Expand subnet list from subnet_id to values. for n in networks: # Due to potential timing issues, we can't assume the subnet_dict data # is in sync with the network data. n['subnets'] = [subnet_dict[s] for s in n.get('subnets', []) if s in subnet_dict] return [Network(n) for n in networks] def network_list_for_tenant(request, tenant_id, **params): """Return a network list available for the tenant. The list contains networks owned by the tenant and public networks. If requested_networks specified, it searches requested_networks only. """ LOG.debug("network_list_for_tenant(): tenant_id=%s, params=%s" % (tenant_id, params)) # If a user has admin role, network list returned by Neutron API # contains networks that do not belong to that tenant. # So we need to specify tenant_id when calling network_list(). networks = network_list(request, tenant_id=tenant_id, shared=False, **params) # In the current Neutron API, there is no way to retrieve # both owner networks and public networks in a single API call. networks += network_list(request, shared=True, **params) return networks def network_get(request, network_id, expand_subnet=True, **params): LOG.debug("network_get(): netid=%s, params=%s" % (network_id, params)) network = neutronclient(request).show_network(network_id, **params).get('network') if expand_subnet: if request.user.tenant_id == network['tenant_id'] or network['shared']: # Since the number of subnets per network must be small, # call subnet_get() for each subnet instead of calling # subnet_list() once. network['subnets'] = [subnet_get(request, sid) for sid in network['subnets']] return Network(network) def network_create(request, **kwargs): """Create a network object. :param request: request context :param tenant_id: (optional) tenant id of the network created :param name: (optional) name of the network created :returns: Network object """ LOG.debug("network_create(): kwargs = %s" % kwargs) # In the case network profiles are being used, profile id is needed. if 'net_profile_id' in kwargs: kwargs['n1kv:profile'] = kwargs.pop('net_profile_id') if 'tenant_id' not in kwargs: kwargs['tenant_id'] = request.user.project_id body = {'network': kwargs} network = neutronclient(request).create_network(body=body).get('network') return Network(network) def network_update(request, network_id, **kwargs): LOG.debug("network_update(): netid=%s, params=%s" % (network_id, kwargs)) body = {'network': kwargs} network = neutronclient(request).update_network(network_id, body=body).get('network') return Network(network) def network_delete(request, network_id): LOG.debug("network_delete(): netid=%s" % network_id) neutronclient(request).delete_network(network_id) def subnet_list(request, **params): LOG.debug("subnet_list(): params=%s" % (params)) subnets = neutronclient(request).list_subnets(**params).get('subnets') return [Subnet(s) for s in subnets] def subnet_get(request, subnet_id, **params): LOG.debug("subnet_get(): subnetid=%s, params=%s" % (subnet_id, params)) subnet = neutronclient(request).show_subnet(subnet_id, **params).get('subnet') return Subnet(subnet) def subnet_create(request, network_id, **kwargs): """Create a subnet on a specified network. :param request: request context :param network_id: network id a subnet is created on :param cidr: (optional) subnet IP address range :param ip_version: (optional) IP version (4 or 6) :param gateway_ip: (optional) IP address of gateway :param tenant_id: (optional) tenant id of the subnet created :param name: (optional) name of the subnet created :param subnetpool_id: (optional) subnetpool to allocate prefix from :param prefixlen: (optional) length of prefix to allocate :returns: Subnet object Although both cidr+ip_version and subnetpool_id+preifxlen is listed as optional you MUST pass along one of the combinations to get a successful result. """ LOG.debug("subnet_create(): netid=%s, kwargs=%s" % (network_id, kwargs)) body = {'subnet': {'network_id': network_id}} if 'tenant_id' not in kwargs: kwargs['tenant_id'] = request.user.project_id body['subnet'].update(kwargs) subnet = neutronclient(request).create_subnet(body=body).get('subnet') return Subnet(subnet) def subnet_update(request, subnet_id, **kwargs): LOG.debug("subnet_update(): subnetid=%s, kwargs=%s" % (subnet_id, kwargs)) body = {'subnet': kwargs} subnet = neutronclient(request).update_subnet(subnet_id, body=body).get('subnet') return Subnet(subnet) def subnet_delete(request, subnet_id): LOG.debug("subnet_delete(): subnetid=%s" % subnet_id) neutronclient(request).delete_subnet(subnet_id) def subnetpool_list(request, **params): LOG.debug("subnetpool_list(): params=%s" % (params)) subnetpools = \ neutronclient(request).list_subnetpools(**params).get('subnetpools') return [SubnetPool(s) for s in subnetpools] def subnetpool_get(request, subnetpool_id, **params): LOG.debug("subnetpool_get(): subnetpoolid=%s, params=%s" % (subnetpool_id, params)) subnetpool = \ neutronclient(request).show_subnetpool(subnetpool_id, **params).get('subnetpool') return SubnetPool(subnetpool) def subnetpool_create(request, name, prefixes, **kwargs): """Create a subnetpool. ip_version is auto-detected in back-end. Parameters: request -- Request context name -- Name for subnetpool prefixes -- List of prefixes for pool Keyword Arguments (optional): min_prefixlen -- Minimum prefix length for allocations from pool max_prefixlen -- Maximum prefix length for allocations from pool default_prefixlen -- Default prefix length for allocations from pool default_quota -- Default quota for allocations from pool shared -- Subnetpool should be shared (Admin-only) tenant_id -- Owner of subnetpool Returns: SubnetPool object """ LOG.debug("subnetpool_create(): name=%s, prefixes=%s, kwargs=%s" % (name, prefixes, kwargs)) body = {'subnetpool': {'name': name, 'prefixes': prefixes, } } if 'tenant_id' not in kwargs: kwargs['tenant_id'] = request.user.project_id body['subnetpool'].update(kwargs) subnetpool = \ neutronclient(request).create_subnetpool(body=body).get('subnetpool') return SubnetPool(subnetpool) def subnetpool_update(request, subnetpool_id, **kwargs): LOG.debug("subnetpool_update(): subnetpoolid=%s, kwargs=%s" % (subnetpool_id, kwargs)) body = {'subnetpool': kwargs} subnetpool = \ neutronclient(request).update_subnetpool(subnetpool_id, body=body).get('subnetpool') return SubnetPool(subnetpool) def subnetpool_delete(request, subnetpool_id): LOG.debug("subnetpool_delete(): subnetpoolid=%s" % subnetpool_id) return neutronclient(request).delete_subnetpool(subnetpool_id) def port_list(request, **params): LOG.debug("port_list(): params=%s" % (params)) ports = neutronclient(request).list_ports(**params).get('ports') return [Port(p) for p in ports] def port_get(request, port_id, **params): LOG.debug("port_get(): portid=%s, params=%s" % (port_id, params)) port = neutronclient(request).show_port(port_id, **params).get('port') return Port(port) def unescape_port_kwargs(**kwargs): for key in kwargs: if '__' in key: kwargs[':'.join(key.split('__'))] = kwargs.pop(key) return kwargs def port_create(request, network_id, **kwargs): """Create a port on a specified network. :param request: request context :param network_id: network id a subnet is created on :param device_id: (optional) device id attached to the port :param tenant_id: (optional) tenant id of the port created :param name: (optional) name of the port created :returns: Port object """ LOG.debug("port_create(): netid=%s, kwargs=%s" % (network_id, kwargs)) # In the case policy profiles are being used, profile id is needed. if 'policy_profile_id' in kwargs: kwargs['n1kv:profile'] = kwargs.pop('policy_profile_id') kwargs = unescape_port_kwargs(**kwargs) body = {'port': {'network_id': network_id}} if 'tenant_id' not in kwargs: kwargs['tenant_id'] = request.user.project_id body['port'].update(kwargs) port = neutronclient(request).create_port(body=body).get('port') return Port(port) def port_delete(request, port_id): LOG.debug("port_delete(): portid=%s" % port_id) neutronclient(request).delete_port(port_id) def port_update(request, port_id, **kwargs): LOG.debug("port_update(): portid=%s, kwargs=%s" % (port_id, kwargs)) kwargs = unescape_port_kwargs(**kwargs) body = {'port': kwargs} port = neutronclient(request).update_port(port_id, body=body).get('port') return Port(port) def profile_list(request, type_p, **params): LOG.debug("profile_list(): " "profile_type=%(profile_type)s, params=%(params)s", {'profile_type': type_p, 'params': params}) if type_p == 'network': profiles = neutronclient(request).list_network_profiles( **params).get('network_profiles') elif type_p == 'policy': profiles = neutronclient(request).list_policy_profiles( **params).get('policy_profiles') return [Profile(n) for n in profiles] def profile_get(request, profile_id, **params): LOG.debug("profile_get(): " "profileid=%(profileid)s, params=%(params)s", {'profileid': profile_id, 'params': params}) profile = neutronclient(request).show_network_profile( profile_id, **params).get('network_profile') return Profile(profile) def profile_create(request, **kwargs): LOG.debug("profile_create(): kwargs=%s", kwargs) body = {'network_profile': {}} body['network_profile'].update(kwargs) profile = neutronclient(request).create_network_profile( body=body).get('network_profile') return Profile(profile) def profile_delete(request, profile_id): LOG.debug("profile_delete(): profile_id=%s", profile_id) neutronclient(request).delete_network_profile(profile_id) def profile_update(request, profile_id, **kwargs): LOG.debug("profile_update(): " "profileid=%(profileid)s, kwargs=%(kwargs)s", {'profileid': profile_id, 'kwargs': kwargs}) body = {'network_profile': kwargs} profile = neutronclient(request).update_network_profile( profile_id, body=body).get('network_profile') return Profile(profile) def profile_bindings_list(request, type_p, **params): LOG.debug("profile_bindings_list(): " "profile_type=%(profile_type)s params=%(params)s", {'profile_type': type_p, 'params': params}) if type_p == 'network': bindings = neutronclient(request).list_network_profile_bindings( **params).get('network_profile_bindings') elif type_p == 'policy': bindings = neutronclient(request).list_policy_profile_bindings( **params).get('policy_profile_bindings') return [Profile(n) for n in bindings] def router_create(request, **kwargs): LOG.debug("router_create():, kwargs=%s" % kwargs) body = {'router': {}} if 'tenant_id' not in kwargs: kwargs['tenant_id'] = request.user.project_id body['router'].update(kwargs) router = neutronclient(request).create_router(body=body).get('router') return Router(router) def router_update(request, r_id, **kwargs): LOG.debug("router_update(): router_id=%s, kwargs=%s" % (r_id, kwargs)) body = {'router': {}} body['router'].update(kwargs) router = neutronclient(request).update_router(r_id, body=body) return Router(router['router']) def router_get(request, router_id, **params): router = neutronclient(request).show_router(router_id, **params).get('router') return Router(router) def router_list(request, **params): routers = neutronclient(request).list_routers(**params).get('routers') return [Router(r) for r in routers] def router_delete(request, router_id): neutronclient(request).delete_router(router_id) def router_add_interface(request, router_id, subnet_id=None, port_id=None): body = {} if subnet_id: body['subnet_id'] = subnet_id if port_id: body['port_id'] = port_id client = neutronclient(request) return client.add_interface_router(router_id, body) def router_remove_interface(request, router_id, subnet_id=None, port_id=None): body = {} if subnet_id: body['subnet_id'] = subnet_id if port_id: body['port_id'] = port_id neutronclient(request).remove_interface_router(router_id, body) def router_add_gateway(request, router_id, network_id): body = {'network_id': network_id} neutronclient(request).add_gateway_router(router_id, body) def router_remove_gateway(request, router_id): neutronclient(request).remove_gateway_router(router_id) def router_static_route_list(request, router_id=None): router = router_get(request, router_id) try: routes = [RouterStaticRoute(r) for r in router.routes] except AttributeError: LOG.debug("router_static_route_list(): router_id=%s, " "router=%s", (router_id, router)) return [] return routes def router_static_route_remove(request, router_id, route_ids): currentroutes = router_static_route_list(request, router_id=router_id) newroutes = [] for oldroute in currentroutes: if oldroute.id not in route_ids: newroutes.append({'nexthop': oldroute.nexthop, 'destination': oldroute.destination}) body = {'routes': newroutes} new = router_update(request, router_id, **body) return new def router_static_route_add(request, router_id, newroute): body = {} currentroutes = router_static_route_list(request, router_id=router_id) body['routes'] = [newroute] + [{'nexthop': r.nexthop, 'destination': r.destination} for r in currentroutes] new = router_update(request, router_id, **body) return new def tenant_quota_get(request, tenant_id): return base.QuotaSet(neutronclient(request).show_quota(tenant_id)['quota']) def tenant_quota_update(request, tenant_id, **kwargs): quotas = {'quota': kwargs} return neutronclient(request).update_quota(tenant_id, quotas) def agent_list(request, **params): agents = neutronclient(request).list_agents(**params) return [Agent(a) for a in agents['agents']] def list_dhcp_agent_hosting_networks(request, network, **params): agents = neutronclient(request).list_dhcp_agent_hosting_networks(network, **params) return [Agent(a) for a in agents['agents']] def add_network_to_dhcp_agent(request, dhcp_agent, network_id): body = {'network_id': network_id} return neutronclient(request).add_network_to_dhcp_agent(dhcp_agent, body) def remove_network_from_dhcp_agent(request, dhcp_agent, network_id): return neutronclient(request).remove_network_from_dhcp_agent(dhcp_agent, network_id) def provider_list(request): providers = neutronclient(request).list_service_providers() return providers['service_providers'] def servers_update_addresses(request, servers, all_tenants=False): """Retrieve servers networking information from Neutron if enabled. Should be used when up to date networking information is required, and Nova's networking info caching mechanism is not fast enough. """ # Get all (filtered for relevant servers) information from Neutron try: ports = list_resources_with_long_filters( port_list, 'device_id', [instance.id for instance in servers], request=request) fips = FloatingIpManager(request) if fips.is_supported(): floating_ips = list_resources_with_long_filters( fips.list, 'port_id', [port.id for port in ports], all_tenants=all_tenants) else: floating_ips = [] networks = list_resources_with_long_filters( network_list, 'id', set([port.network_id for port in ports]), request=request) except Exception: error_message = _('Unable to connect to Neutron.') LOG.error(error_message) messages.error(request, error_message) return # Map instance to its ports instances_ports = collections.defaultdict(list) for port in ports: instances_ports[port.device_id].append(port) # Map port to its floating ips ports_floating_ips = collections.defaultdict(list) for fip in floating_ips: ports_floating_ips[fip.port_id].append(fip) # Map network id to its name network_names = dict(((network.id, network.name) for network in networks)) for server in servers: try: addresses = _server_get_addresses( request, server, instances_ports, ports_floating_ips, network_names) except Exception as e: LOG.error(six.text_type(e)) else: server.addresses = addresses def _server_get_addresses(request, server, ports, floating_ips, network_names): def _format_address(mac, ip, type): try: version = netaddr.IPAddress(ip).version except Exception as e: error_message = _('Unable to parse IP address %s.') % ip LOG.error(error_message) messages.error(request, error_message) raise e return {u'OS-EXT-IPS-MAC:mac_addr': mac, u'version': version, u'addr': ip, u'OS-EXT-IPS:type': type} addresses = collections.defaultdict(list) instance_ports = ports.get(server.id, []) for port in instance_ports: network_name = network_names.get(port.network_id) if network_name is not None: for fixed_ip in port.fixed_ips: addresses[network_name].append( _format_address(port.mac_address, fixed_ip['ip_address'], u'fixed')) port_fips = floating_ips.get(port.id, []) for fip in port_fips: addresses[network_name].append( _format_address(port.mac_address, fip.floating_ip_address, u'floating')) return dict(addresses) @memoized def list_extensions(request): extensions_list = neutronclient(request).list_extensions() if 'extensions' in extensions_list: return extensions_list['extensions'] else: return {} @memoized def is_extension_supported(request, extension_alias): extensions = list_extensions(request) for extension in extensions: if extension['alias'] == extension_alias: return True else: return False def is_enabled_by_config(name, default=True): network_config = getattr(settings, 'OPENSTACK_NEUTRON_NETWORK', {}) return network_config.get(name, default) @memoized def is_service_enabled(request, config_name, ext_name): return (is_enabled_by_config(config_name) and is_extension_supported(request, ext_name)) @memoized def is_quotas_extension_supported(request): return (is_enabled_by_config('enable_quotas', False) and is_extension_supported(request, 'quotas')) # Using this mechanism till a better plugin/sub-plugin detection # mechanism is available. # When using specific plugins the profile_support can be # turned on if needed to configure and/or use profiles. # Since this is a temporary mechanism used to detect profile_support # @memorize is not being used. # TODO(absubram): Change this config variable check with # subplugin/plugin detection API when it becomes available. def is_port_profiles_supported(): network_config = getattr(settings, 'OPENSTACK_NEUTRON_NETWORK', {}) # Can be used to check for vendor specific plugin profile_support = network_config.get('profile_support', None) if str(profile_support).lower() == 'cisco': return True # FEATURE_MAP is used to define: # - related neutron extension name (key: "extension") # - corresponding dashboard config (key: "config") # - RBAC policies (key: "poclies") # If a key is not contained, the corresponding permission check is skipped. FEATURE_MAP = { 'dvr': { 'extension': 'dvr', 'config': { 'name': 'enable_distributed_router', 'default': False, }, 'policies': { 'get': 'get_router:distributed', 'create': 'create_router:distributed', 'update': 'update_router:distributed', } }, 'l3-ha': { 'extension': 'l3-ha', 'config': {'name': 'enable_ha_router', 'default': False}, 'policies': { 'get': 'get_router:ha', 'create': 'create_router:ha', 'update': 'update_router:ha', } }, } def get_feature_permission(request, feature, operation=None): """Check if a feature-specific field can be displayed. This method check a permission for a feature-specific field. Such field is usually provided through Neutron extension. :param request: Request Object :param feature: feature name defined in FEATURE_MAP :param operation (optional): Operation type. The valid value should be defined in FEATURE_MAP[feature]['policies'] It must be specified if FEATURE_MAP[feature] has 'policies'. """ network_config = getattr(settings, 'OPENSTACK_NEUTRON_NETWORK', {}) feature_info = FEATURE_MAP.get(feature) if not feature_info: # Translators: Only used inside Horizon code and invisible to users raise ValueError(_("The requested feature '%(feature)s' is unknown. " "Please make sure to specify a feature defined " "in FEATURE_MAP.")) # Check dashboard settings feature_config = feature_info.get('config') if feature_config: if not network_config.get(feature_config['name'], feature_config['default']): return False # Check policy feature_policies = feature_info.get('policies') policy_check = getattr(settings, "POLICY_CHECK_FUNCTION", None) if feature_policies and policy_check: policy_name = feature_policies.get(operation) if not policy_name: # Translators: Only used inside Horizon code and invisible to users raise ValueError(_("The 'operation' parameter for " "get_feature_permission '%(feature)s' " "is invalid. It should be one of %(allowed)s") % {'feature': feature, 'allowed': ' '.join(feature_policies.keys())}) role = (('network', policy_name),) if not policy.check(role, request): return False # Check if a required extension is enabled feature_extension = feature_info.get('extension') if feature_extension: try: return is_extension_supported(request, feature_extension) except Exception: msg = (_("Failed to check Neutron '%s' extension is not supported") % feature_extension) LOG.info(msg) return False # If all checks are passed, now a given feature is allowed. return True
2026-03-31T15:30:29
codeparrot_clean
4dd0feec045b7a75a189eb4a14496ea6
code
# -*- encoding: utf-8 -*- ############################################################################### # Module Writen to OpenERP, Open Source Management Solution # Copyright (c) 2013 Vauxoo C.A. (http://openerp.com.ve/) # All Rights Reserved ############# Credits ######################################################### # Coded by: Juan Marzquez (Tecvemar, c.a.) <jmarquez@tecvemar.com.ve> # Katherine Zaoral <katherine.zaoral@vauxoo.com> # Planified by: # Juan Marquez <jmarquez@tecvemar.com.ve> # Humberto Arocha <hbto@vauxoo.com> # Audited by: Humberto Arocha <hbto@vauxoo.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, osv from openerp.tools.translate import _ import openerp.pooler import openerp.addons.decimal_precision as dp import time class customs_form(osv.osv): _name = 'customs.form' _description = '' def name_get(self, cr, uid, ids, context): if not len(ids): return [] res = [] so_brw = self.browse(cr, uid, ids, context) for item in so_brw: res.append((item.id, 'F86 # %s - %s' % (item.name, item.ref or ''))) return res def _amount_total(self, cr, uid, ids, field_name, arg, context=None): res = {} for f86 in self.browse(cr, uid, ids, context=context): amount_total = 0.0 for line in f86.cfl_ids: amount_total += line.amount res[f86.id] = amount_total return res def _default_cfl_ids(self, cr, uid, context=None): """ Gets default cfl_ids from customs_duty. """ obj_ct = self.pool.get('customs.duty') ct_ids = obj_ct.search(cr, uid, [], context=context) res = [] for id in ct_ids: vat = obj_ct.browse(cr, uid, id, context=context) res.append({'tax_code': id, 'amount': 0.0, 'vat_detail': vat.vat_detail}) return res def _gen_account_move_line(self, company_id, account_id, partner_id, name, debit, credit): return (0, 0, { 'auto': True, 'company_id': company_id, 'account_id': account_id, 'partner_id': partner_id, 'name': name[:64], 'debit': debit, 'credit': credit, 'reconcile': False, }) _columns = { 'name': fields.char('Form #', size=16, required=True, readonly=True, states={'draft': [('readonly', False)]}), 'ref': fields.char('Reference', size=64, required=False, readonly=True, states={'draft': [('readonly', False)]}), 'date': fields.date('Date', required=True, readonly=True, states={'draft': [('readonly', False)]}, select=True), 'company_id': fields.many2one('res.company', 'Company', required=True, readonly=True, ondelete='restrict'), 'broker_id': fields.many2one('res.partner', 'Broker', change_default=True, readonly=True, states={'draft': [('readonly', False)]}, ondelete='restrict'), 'ref_reg': fields.char('Reg. number', size=16, required=False, readonly=True, states={'draft': [('readonly', False)]}), 'date_reg': fields.date('Reg. date', required=False, readonly=True, states={'draft': [('readonly', False)]}, select=True), 'ref_liq': fields.char('Liq. number', size=16, required=False, readonly=True, states={'draft': [('readonly', False)]}), 'date_liq': fields.date('liq. date', required=True, readonly=True, states={'draft': [('readonly', False)]}, select=True), 'customs_facility_id': fields.many2one( 'customs.facility', 'Customs Facility', change_default=True, readonly=True, states={'draft': [('readonly', False)]}, ondelete='restrict'), 'cfl_ids': fields.one2many('customs.form.line', 'customs_form_id', 'Tax lines', readonly=True, states={'draft': [('readonly', False)]}), 'amount_total': fields.function(_amount_total, method=True, type='float', string='Amount total', store=False), 'move_id': fields.many2one('account.move', 'Account move', ondelete='restrict', select=True, readonly=True, help="The move of this entry line."), 'narration': fields.text('Notes', readonly=False), 'state': fields.selection([('draft', 'Draft'), ('open', 'Open'), ('done', 'Done'), ('cancel', 'Cancelled')], string='State', required=True, readonly=True), } _defaults = { 'date': lambda *a: time.strftime('%Y-%m-%d'), 'company_id': lambda self, cr, uid, c: self.pool.get('res.company')._company_default_get(cr, uid, 'customs.form', context=c), 'cfl_ids': _default_cfl_ids, 'state': lambda *a: 'draft', } _sql_constraints = [ ('name_uniq', 'UNIQUE(name)', 'The form # must be unique!'), ] def create_account_move_lines(self, cr, uid, f86, context=None): """ Creates the account.move.lines from cfl_ids detail except for taxes with "vat_detail", in this case create debits from cfl_ids.imex_tax_line and get debit account from account_tax model """ lines = [] context = context or {} company_id = context.get('f86_company_id') rp_obj = self.pool.get('res.partner') #~ expenses for line in f86.cfl_ids: debits = [] acc_part_brw = rp_obj._find_accounting_partner(line.tax_code.partner_id) if line.tax_code.vat_detail: for vat in line.imex_tax_line: if vat.tax_amount: debits.append( {'account_id': vat.tax_id.account_collected_id.id, 'amount': vat.tax_amount, 'tax_info': ' (%s)' % vat.tax_id.name}) else: if line.amount: debits.append({'account_id': line.tax_code.account_id.id, 'amount': line.amount, 'tax_info': ''}) credit_account_id = \ acc_part_brw.property_account_payable.id for debit in debits: if not debit['account_id'] or not credit_account_id: raise osv.except_osv( _('Error!'), _('No account found, please check \ customs taxes settings (%s)') % line.tax_code.name) lines.append( self._gen_account_move_line( company_id, debit['account_id'], acc_part_brw.id, '[%s] %s - %s%s' % (line.tax_code.code, line.tax_code.ref, line.tax_code.name, debit['tax_info']), debit['amount'], 0.0) ) lines.append(self._gen_account_move_line( company_id, credit_account_id, acc_part_brw.id, 'F86 #%s - %s' % (f86.name, line.tax_code.name), 0.0, line.amount)) lines.reverse() # set real order ;-) return lines def create_account_move(self, cr, uid, ids, context=None): context = context or {} so_brw = self.browse(cr, uid, ids, context=context) for f86 in so_brw: if f86.move_id: # ~ The move is already done, nothing to do return [] obj_move = self.pool.get('account.move') obj_cfg = self.pool.get('customs.form.config') company_id = self.pool.get('res.users').browse( cr, uid, uid, context=context).company_id.id cfg_id = obj_cfg.search(cr, uid, [('company_id', '=', company_id)], context=context) if cfg_id: f86_cfg = obj_cfg.browse(cr, uid, cfg_id[0], context=context) else: raise osv.except_osv(_('Error!'), _('Please set a valid configuration in \ the imex settings')) context.update({'f86_company_id': company_id, 'f86_config': f86_cfg}) move_ids = [] for f86 in so_brw: move = { 'ref': 'F86 #%s' % f86.name, 'journal_id': f86_cfg.journal_id.id, 'date': f86.date_liq, 'company_id': company_id, 'state': 'draft', 'to_check': False, 'narration': _('Form 86 # %s\n\tReference: %s\n\tBroker: %s') % (f86.name, f86.ref or '', f86.broker_id.name or ''), } lines = self.create_account_move_lines(cr, uid, f86, context=context) if lines: move.update({'line_id': lines}) move_id = obj_move.create(cr, uid, move, context=context) obj_move.post(cr, uid, [move_id], context=context) if move_id: move_ids.append(move_id) self.write(cr, uid, f86.id, {'move_id': move_id}, context=context) return move_ids def button_draft(self, cr, uid, ids, context=None): context = context or {} vals = {'state': 'draft'} return self.write(cr, uid, ids, vals, context=context) def button_open(self, cr, uid, ids, context=None): context = context or {} vals = {'state': 'open'} return self.write(cr, uid, ids, vals, context=context) def button_done(self, cr, uid, ids, context=None): context = context or {} self.create_account_move(cr, uid, ids, context=context) vals = {'state': 'done'} return self.write(cr, uid, ids, vals, context=context) def button_cancel(self, cr, uid, ids, context=None): context = context or {} f86 = self.browse(cr, uid, ids[0], context=context) f86_move_id = f86.move_id.id if f86 and f86.move_id else False vals = {'state': 'cancel', 'move_id': 0} if f86_move_id: self.pool.get('account.move').unlink(cr, uid, [f86_move_id], context=context) return self.write(cr, uid, ids, vals, context=context) def test_draft(self, cr, uid, ids, *args): return True def test_open(self, cr, uid, ids, *args): ids = isinstance(ids, (int, long)) and [ids] or ids for f86 in self.browse(cr, uid, ids, context={}): if f86.amount_total <= 0: raise osv.except_osv(_('Warning!'), _('You must indicate a amount')) vat_invoices = [] # for tax (vat) related invoices for line in f86.cfl_ids: if line.vat_detail: vat_total = line.amount for vat in line.imex_tax_line: vat_total -= vat.tax_amount if vat.imex_inv_id.id not in vat_invoices: vat_invoices.append(vat.imex_inv_id.id) if abs(vat_total) > 0.001: raise osv.except_osv( _('Warning!'), _('The vat detail data does not correspond with ' 'vat amount in line: %s') % line.tax_code.name) return True def test_done(self, cr, uid, ids, *args): return True def test_cancel(self, cr, uid, ids, *args): if len(ids) != 1: raise osv.except_osv( _('Error!'), _('Multiple operations not allowed')) for f86 in self.browse(cr, uid, ids, context=None): #~ Validate account_move.state != draft if f86.move_id and f86.move_id.state != 'draft': raise osv.except_osv( _('Error!'), _('Can\'t cancel a import while account move state <> \ "Draft" (%s)') % f86.move_id.name) return True class customs_form_line(osv.osv): _name = 'customs.form.line' _description = '' _rec_name = 'tax_code' _columns = { 'customs_form_id': fields.many2one('customs.form', 'Customs', required=True, ondelete='cascade'), 'tax_code': fields.many2one('customs.duty', 'Tax', ondelete='restrict', required=True, readonly=False), 'amount': fields.float('Amount', required=True, digits_compute=dp.get_precision('Account')), 'imex_tax_line': fields.one2many( 'account.invoice.tax', 'cfl_id', 'Vat lines', attrs="{'readonly':[('vat_detail','=',True)], \ 'required':[('vat_detail','=',True)]}"), 'vat_detail': fields.related('tax_code', 'vat_detail', type='boolean', string='Tax detail', store=False, readonly=True) } _defaults = { } _sql_constraints = [ ('code_uniq', 'UNIQUE(customs_form_id,tax_code)', 'The code must be unique! (for this form)'), ]
2026-03-31T15:30:29
codeparrot_clean
52a8160a8c82ce9b1df54056c401907f
code
# coding=utf-8 # Copyright 2014 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import (absolute_import, division, generators, nested_scopes, print_function, unicode_literals, with_statement) from collections import namedtuple from pants.reporting.report import Report class Reporter(object): """Formats and emits reports. Subclasses implement the callback methods, to provide specific reporting functionality, e.g., to console or to browser. """ # Generic reporting settings. # log_level: Display log messages up to this level. # subsettings: subclass-specific settings. Settings = namedtuple('Settings', ['log_level']) def __init__(self, run_tracker, settings): self.run_tracker = run_tracker self.settings = settings def open(self): """Begin the report.""" pass def close(self): """End the report.""" pass def start_workunit(self, workunit): """A new workunit has started.""" pass def end_workunit(self, workunit): """A workunit has finished.""" pass def handle_log(self, workunit, level, *msg_elements): """Handle a message logged by pants code. level: One of the constants above. Each element in msg_elements is either a message or a (message, detail) pair. A subclass must show the message, but may choose to show the detail in some sensible way (e.g., when the message text is clicked on in a browser). This convenience implementation filters by log level and then delegates to do_handle_log. """ if level <= self.level_for_workunit(workunit, self.settings.log_level): self.do_handle_log(workunit, level, *msg_elements) def do_handle_log(self, workunit, level, *msg_elements): """Handle a message logged by pants code, after it's passed the log level check.""" pass def handle_output(self, workunit, label, s): """Handle output captured from an invoked tool (e.g., javac). workunit: The innermost WorkUnit in which the tool was invoked. label: Classifies the output e.g., 'stdout' for output captured from a tool's stdout or 'debug' for debug output captured from a tool's logfiles. s: The content captured. """ pass def is_under_main_root(self, workunit): """Is the workunit running under the main thread's root.""" return self.run_tracker.is_under_main_root(workunit) def level_for_workunit(self, workunit, default_level): if workunit.log_config and workunit.log_config.level: # The value of the level option is a string defined in global_options.py if workunit.log_config.level == 'warn': return Report.WARN if workunit.log_config.level == 'debug': return Report.DEBUG if workunit.log_config.level == 'info': return Report.INFO return default_level def use_color_for_workunit(self, workunit, default_use_colors): if workunit.log_config and workunit.log_config.colors is not None: return workunit.log_config.colors return default_use_colors
2026-03-31T15:30:29
codeparrot_clean
d722b4df340932678c09d58c04242f84
code
# Copyright (c) 1999-2008 Mark D. Hill and David A. Wood # Copyright (c) 2009 The Hewlett-Packard Development Company # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer; # redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution; # neither the name of the copyright holders nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from slicc.ast.AST import AST class StatementListAST(AST): def __init__(self, slicc, statements): super(StatementListAST, self).__init__(slicc) if not isinstance(statements, (list, tuple)): statements = [ statements ] self.statements = statements def __repr__(self): return "[StatementListAST: %r]" % self.statements def generate(self, code, return_type): for statement in self.statements: statement.generate(code, return_type) def findResources(self, resources): for statement in self.statements: statement.findResources(resources)
2026-03-31T15:30:29
codeparrot_clean
f168f59176afad9e32bb7c1f02d2353c
code
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## import project_timesheet import report # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
2026-03-31T15:30:29
codeparrot_clean
2dfdaf92bd15fd193ff9a623af402e44
code
# -*- coding: utf-8 -*- # # OWL Monitor documentation build configuration file, created by # sphinx-quickstart on Fri Apr 29 14:54:08 2016. # # This file is execfile()d with the current directory set to its # containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. import sys import os import shlex # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. #sys.path.insert(0, os.path.abspath('.')) # -- General configuration ------------------------------------------------ # If your documentation needs a minimal Sphinx version, state it here. #needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom # ones. extensions = [] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix(es) of source filenames. # You can specify multiple suffix as a list of string: # source_suffix = ['.rst', '.md'] source_suffix = '.rst' # The encoding of source files. #source_encoding = 'utf-8-sig' # The master toctree document. master_doc = 'index' # General information about the project. project = u'OWL Monitor' copyright = u'2016, RSC' author = u'RSC' # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. version = '0.0.1' # The full version, including alpha/beta/rc tags. release = '0.0.1' # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. # # This is also used if you do content translation via gettext catalogs. # Usually you set "language" from the command line for these cases. language = 'fr' # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: #today = '' # Else, today_fmt is used as the format for a strftime call. #today_fmt = '%B %d, %Y' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. exclude_patterns = ['_build'] # The reST default role (used for this markup: `text`) to use for all # documents. #default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. #add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). #add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. #show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # A list of ignored prefixes for module index sorting. #modindex_common_prefix = [] # If true, keep warnings as "system message" paragraphs in the built documents. #keep_warnings = False # If true, `todo` and `todoList` produce output, else they produce nothing. todo_include_todos = False # -- Options for HTML output ---------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. html_theme = 'alabaster' # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. #html_theme_options = {} # Add any paths that contain custom themes here, relative to this directory. #html_theme_path = [] # The name for this set of Sphinx documents. If None, it defaults to # "<project> v<release> documentation". #html_title = None # A shorter title for the navigation bar. Default is the same as html_title. #html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. #html_logo = None # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. #html_favicon = None # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ['_static'] # Add any extra paths that contain custom files (such as robots.txt or # .htaccess) here, relative to this directory. These files are copied # directly to the root of the documentation. #html_extra_path = [] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. #html_last_updated_fmt = '%b %d, %Y' # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. #html_use_smartypants = True # Custom sidebar templates, maps document names to template names. #html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. #html_additional_pages = {} # If false, no module index is generated. #html_domain_indices = True # If false, no index is generated. #html_use_index = True # If true, the index is split into individual pages for each letter. #html_split_index = False # If true, links to the reST sources are added to the pages. #html_show_sourcelink = True # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. #html_show_sphinx = True # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. #html_show_copyright = True # If true, an OpenSearch description file will be output, and all pages will # contain a <link> tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. #html_use_opensearch = '' # This is the file name suffix for HTML files (e.g. ".xhtml"). #html_file_suffix = None # Language to be used for generating the HTML full-text search index. # Sphinx supports the following languages: # 'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja' # 'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr' #html_search_language = 'en' # A dictionary with options for the search language support, empty by default. # Now only 'ja' uses this config value #html_search_options = {'type': 'default'} # The name of a javascript file (relative to the configuration directory) that # implements a search results scorer. If empty, the default will be used. #html_search_scorer = 'scorer.js' # Output file base name for HTML help builder. htmlhelp_basename = 'OWLMonitordoc' # -- Options for LaTeX output --------------------------------------------- latex_elements = { # The paper size ('letterpaper' or 'a4paper'). #'papersize': 'letterpaper', # The font size ('10pt', '11pt' or '12pt'). #'pointsize': '10pt', # Additional stuff for the LaTeX preamble. #'preamble': '', # Latex figure (float) alignment #'figure_align': 'htbp', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, # author, documentclass [howto, manual, or own class]). latex_documents = [ (master_doc, 'OWLMonitor.tex', u'OWL Monitor Documentation', u'RSC', 'manual'), ] # The name of an image file (relative to this directory) to place at the top of # the title page. #latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. #latex_use_parts = False # If true, show page references after internal links. #latex_show_pagerefs = False # If true, show URL addresses after external links. #latex_show_urls = False # Documents to append as an appendix to all manuals. #latex_appendices = [] # If false, no module index is generated. #latex_domain_indices = True # -- Options for manual page output --------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ (master_doc, 'owlmonitor', u'OWL Monitor Documentation', [author], 1) ] # If true, show URL addresses after external links. #man_show_urls = False # -- Options for Texinfo output ------------------------------------------- # Grouping the document tree into Texinfo files. List of tuples # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ (master_doc, 'OWLMonitor', u'OWL Monitor Documentation', author, 'OWLMonitor', 'One line description of project.', 'Miscellaneous'), ] # Documents to append as an appendix to all manuals. #texinfo_appendices = [] # If false, no module index is generated. #texinfo_domain_indices = True # How to display URL addresses: 'footnote', 'no', or 'inline'. #texinfo_show_urls = 'footnote' # If true, do not generate a @detailmenu in the "Top" node's menu. #texinfo_no_detailmenu = False
2026-03-31T15:30:29
codeparrot_clean
168733ded33e1c555cff6b7cecf7b2ea
code
import cgi import errno import mimetypes import os import posixpath import re import shutil import stat import sys import tempfile from optparse import make_option from os import path import django from django.template import Template, Context from django.utils import archive from django.utils.six.moves.urllib.request import urlretrieve from django.utils._os import rmtree_errorhandler from django.core.management.base import BaseCommand, CommandError from django.core.management.utils import handle_extensions _drive_re = re.compile('^([a-z]):', re.I) _url_drive_re = re.compile('^([a-z])[:|]', re.I) class TemplateCommand(BaseCommand): """ Copies either a Django application layout template or a Django project layout template into the specified directory. :param style: A color style object (see django.core.management.color). :param app_or_project: The string 'app' or 'project'. :param name: The name of the application or project. :param directory: The directory to which the template should be copied. :param options: The additional variables passed to project or app templates """ args = "[name] [optional destination directory]" option_list = BaseCommand.option_list + ( make_option('--template', action='store', dest='template', help='The path or URL to load the template from.'), make_option('--extension', '-e', dest='extensions', action='append', default=['py'], help='The file extension(s) to render (default: "py"). ' 'Separate multiple extensions with commas, or use ' '-e multiple times.'), make_option('--name', '-n', dest='files', action='append', default=[], help='The file name(s) to render. ' 'Separate multiple extensions with commas, or use ' '-n multiple times.') ) requires_system_checks = False # Can't import settings during this command, because they haven't # necessarily been created. can_import_settings = False # The supported URL schemes url_schemes = ['http', 'https', 'ftp'] # Can't perform any active locale changes during this command, because # setting might not be available at all. leave_locale_alone = True def handle(self, app_or_project, name, target=None, **options): self.app_or_project = app_or_project self.paths_to_remove = [] self.verbosity = int(options.get('verbosity')) self.validate_name(name, app_or_project) # if some directory is given, make sure it's nicely expanded if target is None: top_dir = path.join(os.getcwd(), name) try: os.makedirs(top_dir) except OSError as e: if e.errno == errno.EEXIST: message = "'%s' already exists" % top_dir else: message = e raise CommandError(message) else: top_dir = os.path.abspath(path.expanduser(target)) if not os.path.exists(top_dir): raise CommandError("Destination directory '%s' does not " "exist, please create it first." % top_dir) extensions = tuple( handle_extensions(options.get('extensions'), ignored=())) extra_files = [] for file in options.get('files'): extra_files.extend(map(lambda x: x.strip(), file.split(','))) if self.verbosity >= 2: self.stdout.write("Rendering %s template files with " "extensions: %s\n" % (app_or_project, ', '.join(extensions))) self.stdout.write("Rendering %s template files with " "filenames: %s\n" % (app_or_project, ', '.join(extra_files))) base_name = '%s_name' % app_or_project base_subdir = '%s_template' % app_or_project base_directory = '%s_directory' % app_or_project if django.VERSION[-2] != 'final': docs_version = 'dev' else: docs_version = '%d.%d' % django.VERSION[:2] context = Context(dict(options, **{ base_name: name, base_directory: top_dir, 'docs_version': docs_version, }), autoescape=False) # Setup a stub settings environment for template rendering from django.conf import settings if not settings.configured: settings.configure() template_dir = self.handle_template(options.get('template'), base_subdir) prefix_length = len(template_dir) + 1 for root, dirs, files in os.walk(template_dir): path_rest = root[prefix_length:] relative_dir = path_rest.replace(base_name, name) if relative_dir: target_dir = path.join(top_dir, relative_dir) if not path.exists(target_dir): os.mkdir(target_dir) for dirname in dirs[:]: if dirname.startswith('.') or dirname == '__pycache__': dirs.remove(dirname) for filename in files: if filename.endswith(('.pyo', '.pyc', '.py.class')): # Ignore some files as they cause various breakages. continue old_path = path.join(root, filename) new_path = path.join(top_dir, relative_dir, filename.replace(base_name, name)) if path.exists(new_path): raise CommandError("%s already exists, overlaying a " "project or app into an existing " "directory won't replace conflicting " "files" % new_path) # Only render the Python files, as we don't want to # accidentally render Django templates files with open(old_path, 'rb') as template_file: content = template_file.read() if filename.endswith(extensions) or filename in extra_files: content = content.decode('utf-8') template = Template(content) content = template.render(context) content = content.encode('utf-8') with open(new_path, 'wb') as new_file: new_file.write(content) if self.verbosity >= 2: self.stdout.write("Creating %s\n" % new_path) try: shutil.copymode(old_path, new_path) self.make_writeable(new_path) except OSError: self.stderr.write( "Notice: Couldn't set permission bits on %s. You're " "probably using an uncommon filesystem setup. No " "problem." % new_path, self.style.NOTICE) if self.paths_to_remove: if self.verbosity >= 2: self.stdout.write("Cleaning up temporary files.\n") for path_to_remove in self.paths_to_remove: if path.isfile(path_to_remove): os.remove(path_to_remove) else: shutil.rmtree(path_to_remove, onerror=rmtree_errorhandler) def handle_template(self, template, subdir): """ Determines where the app or project templates are. Use django.__path__[0] as the default because we don't know into which directory Django has been installed. """ if template is None: return path.join(django.__path__[0], 'conf', subdir) else: if template.startswith('file://'): template = template[7:] expanded_template = path.expanduser(template) expanded_template = path.normpath(expanded_template) if path.isdir(expanded_template): return expanded_template if self.is_url(template): # downloads the file and returns the path absolute_path = self.download(template) else: absolute_path = path.abspath(expanded_template) if path.exists(absolute_path): return self.extract(absolute_path) raise CommandError("couldn't handle %s template %s." % (self.app_or_project, template)) def validate_name(self, name, app_or_project): if name is None: raise CommandError("you must provide %s %s name" % ( "an" if app_or_project == "app" else "a", app_or_project)) # If it's not a valid directory name. if not re.search(r'^[_a-zA-Z]\w*$', name): # Provide a smart error message, depending on the error. if not re.search(r'^[_a-zA-Z]', name): message = 'make sure the name begins with a letter or underscore' else: message = 'use only numbers, letters and underscores' raise CommandError("%r is not a valid %s name. Please %s." % (name, app_or_project, message)) def download(self, url): """ Downloads the given URL and returns the file name. """ def cleanup_url(url): tmp = url.rstrip('/') filename = tmp.split('/')[-1] if url.endswith('/'): display_url = tmp + '/' else: display_url = url return filename, display_url prefix = 'django_%s_template_' % self.app_or_project tempdir = tempfile.mkdtemp(prefix=prefix, suffix='_download') self.paths_to_remove.append(tempdir) filename, display_url = cleanup_url(url) if self.verbosity >= 2: self.stdout.write("Downloading %s\n" % display_url) try: the_path, info = urlretrieve(url, path.join(tempdir, filename)) except IOError as e: raise CommandError("couldn't download URL %s to %s: %s" % (url, filename, e)) used_name = the_path.split('/')[-1] # Trying to get better name from response headers content_disposition = info.get('content-disposition') if content_disposition: _, params = cgi.parse_header(content_disposition) guessed_filename = params.get('filename') or used_name else: guessed_filename = used_name # Falling back to content type guessing ext = self.splitext(guessed_filename)[1] content_type = info.get('content-type') if not ext and content_type: ext = mimetypes.guess_extension(content_type) if ext: guessed_filename += ext # Move the temporary file to a filename that has better # chances of being recognized by the archive utils if used_name != guessed_filename: guessed_path = path.join(tempdir, guessed_filename) shutil.move(the_path, guessed_path) return guessed_path # Giving up return the_path def splitext(self, the_path): """ Like os.path.splitext, but takes off .tar, too """ base, ext = posixpath.splitext(the_path) if base.lower().endswith('.tar'): ext = base[-4:] + ext base = base[:-4] return base, ext def extract(self, filename): """ Extracts the given file to a temporarily and returns the path of the directory with the extracted content. """ prefix = 'django_%s_template_' % self.app_or_project tempdir = tempfile.mkdtemp(prefix=prefix, suffix='_extract') self.paths_to_remove.append(tempdir) if self.verbosity >= 2: self.stdout.write("Extracting %s\n" % filename) try: archive.extract(filename, tempdir) return tempdir except (archive.ArchiveException, IOError) as e: raise CommandError("couldn't extract file %s to %s: %s" % (filename, tempdir, e)) def is_url(self, template): """ Returns True if the name looks like a URL """ if ':' not in template: return False scheme = template.split(':', 1)[0].lower() return scheme in self.url_schemes def make_writeable(self, filename): """ Make sure that the file is writeable. Useful if our source is read-only. """ if sys.platform.startswith('java'): # On Jython there is no os.access() return if not os.access(filename, os.W_OK): st = os.stat(filename) new_permissions = stat.S_IMODE(st.st_mode) | stat.S_IWUSR os.chmod(filename, new_permissions)
2026-03-31T15:30:29
codeparrot_clean
e5c7b75eacdad8c20395aa08410770d9
code
#!/usr/bin/env python ### -- [2012-03-04 14:56:03] FlowRate and FlowSize anomaly parameter has be changed as ### -- ratio instead of absolute value ##-- [2012-04-08 22:31:20] Add GenAnomalyDot ##-- [2012-04-09 18:31:22] refactoring the whole file ## -- [2012-04-10 01:14:07] FLOW_RATE can work ##-- [2012-04-10 17:16:27] add _infect_modulator, make anomaly more general # import numpy as np import sys sys.path.append("..") import settings from util import Load from mod_util import choose_ip_addr import cPickle as pickle # from numpy import cumsum, diff def cumsum(it): total = 0 for x in it: total += x yield total def diff(x): res = [] for i in xrange(len(x)-1): res.append(x[i+1]-x[i]) return res def get_pos(l, v): """index of largest element in l that is less than v""" for i in xrange(len(l)): if l[i] < v : continue return i - 1 def insert_break_pt(b, dur, num): """b is a break point that will break dur, for example, if b = 35, and dur = (20, 20, 10), num = (1, 2, 1)the result will be (20, 15, 5, 10), the new num will be (1, 2, 2, 1)""" t = [0] + list(cumsum( dur )) nt = copy.deepcopy(t) new_num = list(copy.deepcopy(num)) i = get_pos(t, b) if i is None: raise Exception('[insert_break_pt], maybe you have insert an anomaly in an unsuitable time? ') elif i == -1 or i == len(t) - 1: return dur, num, i+1; else: nt.insert(i+1, b) new_num.insert(i+1, num[i]) new_dur = list(diff(nt)) return new_dur, new_num, i+1 class BadConfigError(Exception): def __init__(self, value): self.value = value def __str__(self): return repr(self.value) import copy class Anomaly(object): """basis class for anomaly. Its subclass will provide run() method ano_desc: **T**: start, end time for the anomaly **change**: a dictionary specify how the attributes of the existing modules are changed. the value is a string, if the first char is '=', it means change the attribute to the value behind '='. If the first char is '+', it means add the attribute by the value behind '+'. Likewise if the first char is 'x', it means multiply the attribute by the value behind 'x'. for example: change = {'flow_size_mean':'x2', 'flow_arrival_rate':'=6', 'flow_size_var=+3'}, means: change the flow_size_mean to two times of the orginal value, change flow_arrival_rate to be 6 and add the flow_size_var by 3. """ def __init__(self, ano_desc): self.ano_desc = ano_desc self.ano_node = None def get_profile_with_ano(self, mod_start, mod_profile, ano_t): """in fs, one modulator can only one behaviour toe simulate the change of behaviour of the modulator, the abnormal haviour will be generator by new modulators.""" start, end = ano_t start -= mod_start end -= mod_start d, n, i1 = insert_break_pt(start, mod_profile[0], mod_profile[1]) d, n, i2 = insert_break_pt(end, d, n) normal_profile_1 = ( tuple(d[:i1]), tuple(n[:i1]) ) abnormal_profile = ( tuple(d[i1:i2]), tuple(n[i1:i2]) ) normal_profile_2 = ( tuple(d[i2:]), tuple(n[i2:]) ) return normal_profile_1, abnormal_profile, normal_profile_2 # def cut_profile(profile, status): # """cut into three pieces""" def _infect_modulator(self, ano_t, m_id, mod): ano_node = self.ano_node generator = ano_node.generator mod_start = eval(mod['start']) mod_profile = mod['profile'] np1, ap, np2 = self.get_profile_with_ano(mod_start, mod_profile, ano_t) s_id = mod['generator'] # get id for source generator ano_node.add_modulator(start=str(mod_start), profile=np1, generator = [generator[s_id]]) start, end = ano_t # st = mod_start + float(np.sum(np1[0])) st = mod_start + float(sum(np1[0])) assert(st == start) self.new_generator = generator[s_id].get_new_gen(self.ano_desc['change']) ano_node.add_modulator(start=str(start), profile=ap, generator = [ self.new_generator ]) # export para to help to export ano flo self._export_ano_flow_para(self.new_generator) # st = mod_start + float(np.sum(np1[0])) + float(np.sum(ap[0])) st = mod_start + float(sum(np1[0])) + float(sum(ap[0])) assert(st == end) ano_node.add_modulator(start=str(end), profile=np2, generator=[ generator[s_id] ]) # delete original modulator del ano_node.modulator[m_id] del ano_node.generator[s_id] def _export_ano_flow_para(self, new_generator): """export para to help to export ano flows""" ano_flow_para = copy.deepcopy(new_generator.para) ano_flow_para['ano_type'] = self.ano_desc['anoType'] pickle.dump(ano_flow_para, open(settings.EXPORT_ABNORMAL_FLOW_PARA_FILE, 'w')) # For export abnormal flows def run(self, net): """inject itself into the network""" self.ano_node = net.node_list[self.ano_desc['ano_node_seq']] ano_t = self.ano_desc['T'] m_back = copy.deepcopy(self.ano_node.modulator) for m_id, mod in m_back.iteritems(): # infect each modulator, change attribute by ratio self._infect_modulator(ano_t, m_id, mod) class AddModulatorAnomaly(Anomaly): """instead of changing parameters of existing modulators, simply add new modulators ano_desc: - **dst_nodes**: the destination node of the modulators, will add one modulator for each dst_nodes - **gen_desc**: the descriptor for the generator of the modulator - **T**: a two element list or tuple, the start, end time for the anomaly. """ def run(self, net): self.ano_node = net.node_list[self.ano_desc['ano_node_seq']] self.net = net self._config_traffic() def _config_traffic(self): """add modulator to each srv""" nn = len(self.net.node_list) srv_node_list = [self.net.node_list[i] for i in xrange(nn) if i in self.ano_desc['dst_nodes'] ] start, end = self.ano_desc['T'] for srv_node in srv_node_list: gen_desc = Load(self.ano_desc['gen_desc']) gen_desc['ipsrc'] = choose_ip_addr(self.ano_node.ipdests).rsplit('/')[0] gen_desc['ipdst'] = choose_ip_addr(srv_node.ipdests).rsplit('/')[0] self.ano_node.add_modulator(start=str(start), profile='((%d,),(1,))' %(end-start), generator=[get_generator(gen_desc)] ) from Edge import NEdge from Node import NNode from Generator import get_generator class AtypicalUserAnomaly(Anomaly): """anomaly of atypical user. an atypical user joins to the network during some time. Atypical user refer those user has large IP distance with users in the network.""" ATIP = None # Atypical IP Set. Will Select IP from this set and add a node with atypical ip idx = 0 # A indicator to seperate the IP that has been selected or not NAME = 'AtypicaUser' def __init__(self, ano_desc): """link_to is a list of variables representing the connection to all other nodes * link_to[i] == 1 means there is link from atypical node to node i. * link_to[i] == -1 means there is link from node i to this atypical node. """ self.ano_desc = ano_desc Anomaly.__init__(self, ano_desc) if self.ATIP == None: self.ATIP = ano_desc['ATIP'] self.net = None self.ano_node = None def _change_topology(self): link_to = self.ano_desc['link_to'] link_attr = self.ano_desc['link_attr'] for i in xrange(len(link_to)): if link_to[i] == 1: edge = NEdge(self.ano_node, self.net.node_list[i], link_attr ) elif link_to[i] == -1: edge = NEdge(self.net.node_list[i], self.ano._ode, link_attr ) else: raise ValueError('unknown link_to value') self.net.add_edge(edge) def _config_traffic(self): nn = len(self.net.node_list) srv_node_list = [self.net.node_list[i] for i in xrange(nn) if i in self.net.net_desc['srv_list'] ] start, end = self.ano_desc['T'] for srv_node in srv_node_list: gen_desc = Load(self.ano_desc['gen_desc']) gen_desc['ipsrc'] = choose_ip_addr(self.ano_node.ipdests).rsplit('/')[0] gen_desc['ipdst'] = choose_ip_addr(srv_node.ipdests).rsplit('/')[0] self.ano_node.add_modulator(start=str(start), profile='((%d,),(1,))' %(end-start), generator=get_generator(gen_desc) ) def _get_ano_node(self): ipdest = [ self.ATIP[self.idx] ] self.idx += 1 nn = len(self.net.node_list) # Add by J.W self.ano_node = NNode(ipdest, nn) self._config_traffic() def _export_ip_addr(self): fid = open(settings.EXPORT_ABNORMAL_FLOW_PARA_FILE, 'w') fid.write( ' '.join([str(i) for i in self.ano_node.ipdests]) ) fid.close() def _export_ano_flow_para(self): """export para to help to export ano flows""" self._export_ip_addr() def run(self, net): '''will add a node for atypical user to the network. The IP address for atypical user is selected from. settings.atypical_ip_file''' self.net = net self._get_ano_node() net.add_node(self.ano_node) self._change_topology() self._export_ano_flow_para() class TargetOneServer(Anomaly): """Only change the behaviour in one server ano_desc should have id **srv_id** of that sever node""" def run(self, net): self.ano_node = net.node_list[self.ano_desc['ano_node_seq']] ano_t = self.ano_desc['T'] srv_id = self.ano_desc['srv_id'] srv_ip_addr = net.node_list[srv_id].ipdests m_back = copy.deepcopy(self.ano_node.modulator) for m_id, mod in m_back.iteritems(): # For each modulator s_id = mod['generator'] # get id for source generator if self.ano_node.generator[s_id]['ipdst'] not in srv_ip_addr: continue self._infect_modulator(ano_t, m_id, mod)
2026-03-31T15:30:29
codeparrot_clean
691b720ed962395528dc3ee33cc2dbb1
code
import os def post_register_types(root_module): enabled_features = os.environ['NS3_ENABLED_FEATURES'].split(',') if 'EmuFdNetDevice' not in enabled_features: if 'ns3::EmuFdNetDeviceHelper'in root_module: root_module.classes.remove(root_module['ns3::EmuFdNetDeviceHelper']) if 'TapFdNetDevice' not in enabled_features: if 'ns3::TapFdNetDeviceHelper'in root_module: root_module.classes.remove(root_module['ns3::TapFdNetDeviceHelper']) if 'PlanetLabFdNetDevice' not in enabled_features: if 'ns3::PlanetLabFdNetDeviceHelper'in root_module: root_module.classes.remove(root_module['ns3::PlanetLabFdNetDeviceHelper']) if 'FdNetDevice' not in enabled_features: for clsname in ['FdNetDevice', 'FdNetDeviceHelper', 'FdNetDeviceFdReader']: if 'ns3::%s' % clsname in root_module: root_module.classes.remove(root_module['ns3::%s' % clsname]) if 'ns3::FdNetDeviceHelper::EncapsulationMode' in root_module: root_module.enums.remove(root_module['ns3::FdNetDeviceHelper::EncapsulationMode'])
2026-03-31T15:30:29
codeparrot_clean
73df0da3fa0896cb0116565c269d4a87
code
import tweepy from zope import interface from twisted.application import service from twisted.internet import defer, threads, reactor from piped import exceptions, log, resource, util class MyTwitterProvider(object): # state that we are a resource provider, so that the piped plugin system finds us interface.classProvides(resource.IResourceProvider) def __init__(self): # we store the apis by the account name since we might have # multiple consumers of the same api. self._api_by_name = dict() def configure(self, runtime_environment): # look up the twitter account configurations: self.twitter_configs = runtime_environment.get_configuration_value('twitter', dict()) for account_name, account_config in self.twitter_configs.items(): auth = tweepy.BasicAuthHandler(**account_config['auth']) self._api_by_name[account_name] = tweepy.API(auth) # tell the resource manager that we can provide the named twitter accounts runtime_environment.resource_manager.register('twitter.%s' % account_name, provider=self) def add_consumer(self, resource_dependency): # since we registered for 'twitter.<account_name>', we can find the account_name requested by splitting: twitter, account_name = resource_dependency.provider.split('.') # give the tweepy API instance to the resource: resource_dependency.on_resource_ready(self._api_by_name[account_name])
2026-03-31T15:30:29
codeparrot_clean
f207daf177516aa9cff21050f8f0f045
code
# Copyright (c) 2013, Frappe Technologies Pvt. Ltd. and contributors # For license information, please see license.txt from __future__ import unicode_literals import frappe from frappe import _ def execute(filters=None): if not filters: filters = {} columns = get_columns() employees = get_employees(filters) departments_result = get_department(filters) departments = [] if departments_result: for department in departments_result: departments.append(department) chart = get_chart_data(departments,employees) return columns, employees, None, chart def get_columns(): return [ _("Employee") + ":Link/Employee:120", _("Name") + ":Data:200", _("Date of Birth")+ ":Date:100", _("Branch") + ":Link/Branch:120", _("Department") + ":Link/Department:120", _("Designation") + ":Link/Designation:120", _("Gender") + "::60", _("Company") + ":Link/Company:120" ] def get_conditions(filters): conditions = "" if filters.get("department"): conditions += " and department = '%s'" % \ filters["department"].replace("'", "\\'") return conditions def get_employees(filters): conditions = get_conditions(filters) return frappe.db.sql("""select name, employee_name, date_of_birth, branch, department, designation, gender, company from `tabEmployee` where status = 'Active' %s""" % conditions, as_list=1) def get_department(filters): return frappe.db.sql("""select name from `tabDepartment`""" , as_list=1) def get_chart_data(departments,employees): if not departments: departments = [] datasets = [] for department in departments: if department: total_employee = frappe.db.sql("""select count(*) from \ `tabEmployee` where \ department = %s""" ,(department[0]), as_list=1) datasets.append(total_employee[0][0]) chart = { "data": { 'labels': departments, 'datasets': [{'name': 'Employees','values': datasets}] } } chart["type"] = "bar" return chart
2026-03-31T15:30:29
codeparrot_clean
adf4c45b82b3629045213832ba6b5e48
code
#!/usr/bin/env python class UnionFind: def __init__(self): self.parent = {} self.rank = {} def root(self, a): current_item = a path = [] while self.parent[current_item] != current_item: path.append(current_item) current_item = self.parent[current_item] for node in path: self.parent[node] = current_item return current_item def connected(self, a, b): return self.root(a) == self.root(b) def find(self, a): return self.root(a) def create(self, a): if a not in self.parent: self.parent[a] = a self.rank[a] = 1 def union(self, a, b): self.create(a) self.create(b) a_root = self.root(a) b_root = self.root(b) if self.rank[a_root] > self.rank[b_root]: self.parent[b_root] = a_root self.rank[a_root] += self.rank[b_root] else: self.parent[a_root] = b_root self.rank[b_root] += self.rank[a_root] def count(self, a): if a not in self.parent: return 0 return self.rank[self.root(a)] def main(): union_find = UnionFind() union_find.union(1, 3) union_find.union(1, 4) union_find.union(2, 5) union_find.union(5, 6) union_find.union(7, 8) union_find.union(7, 9) union_find.union(3, 9) for i in range(1, 10): print( "{} is in group {} with {} elements".format( i, union_find.find(i), union_find.count(i) ) ) if __name__ == "__main__": main()
2026-03-31T15:30:29
codeparrot_clean
e3104610453ca80cbd0fa3c19d248e7e
code
#!/usr/bin/python2 from distutils.core import setup, Extension from os import getenv from distutils.command.build_ext import build_ext as _build_ext from distutils.command.install_lib import install_lib as _install_lib class build_ext(_build_ext): def finalize_options(self): _build_ext.finalize_options(self) self.build_lib = build_lib self.build_temp = build_tmp class install_lib(_install_lib): def finalize_options(self): _install_lib.finalize_options(self) self.build_dir = build_lib cflags = getenv('CFLAGS', '').split() # switch off several checks (need to be at the end of cflags list) cflags += ['-fno-strict-aliasing', '-Wno-write-strings', '-Wno-unused-parameter' ] build_lib = getenv('PYTHON_EXTBUILD_LIB') build_tmp = getenv('PYTHON_EXTBUILD_TMP') libtraceevent = getenv('LIBTRACEEVENT') libapikfs = getenv('LIBAPI') ext_sources = [f.strip() for f in file('util/python-ext-sources') if len(f.strip()) > 0 and f[0] != '#'] perf = Extension('perf', sources = ext_sources, include_dirs = ['util/include'], extra_compile_args = cflags, extra_objects = [libtraceevent, libapikfs], ) setup(name='perf', version='0.1', description='Interface with the Linux profiling infrastructure', author='Arnaldo Carvalho de Melo', author_email='acme@redhat.com', license='GPLv2', url='http://perf.wiki.kernel.org', ext_modules=[perf], cmdclass={'build_ext': build_ext, 'install_lib': install_lib})
2026-03-31T15:30:29