Dataset Viewer (First 5GB)
Auto-converted to Parquet Duplicate
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
End of preview. Expand in Data Studio

No dataset card yet

Downloads last month
-