nwo
stringlengths
5
106
sha
stringlengths
40
40
path
stringlengths
4
174
language
stringclasses
1 value
identifier
stringlengths
1
140
parameters
stringlengths
0
87.7k
argument_list
stringclasses
1 value
return_statement
stringlengths
0
426k
docstring
stringlengths
0
64.3k
docstring_summary
stringlengths
0
26.3k
docstring_tokens
list
function
stringlengths
18
4.83M
function_tokens
list
url
stringlengths
83
304
Georce/lepus
5b01bae82b5dc1df00c9e058989e2eb9b89ff333
lepus/pymongo-2.7/ez_setup.py
python
download_file_insecure
(url, target)
Use Python to download the file, even though it cannot authenticate the connection.
Use Python to download the file, even though it cannot authenticate the connection.
[ "Use", "Python", "to", "download", "the", "file", "even", "though", "it", "cannot", "authenticate", "the", "connection", "." ]
def download_file_insecure(url, target): """ Use Python to download the file, even though it cannot authenticate the connection. """ try: from urllib.request import urlopen except ImportError: from urllib2 import urlopen src = dst = None try: src = urlopen(url) # Read/write all in one block, so we don't create a corrupt file # if the download is interrupted. data = src.read() dst = open(target, "wb") dst.write(data) finally: if src: src.close() if dst: dst.close()
[ "def", "download_file_insecure", "(", "url", ",", "target", ")", ":", "try", ":", "from", "urllib", ".", "request", "import", "urlopen", "except", "ImportError", ":", "from", "urllib2", "import", "urlopen", "src", "=", "dst", "=", "None", "try", ":", "src", "=", "urlopen", "(", "url", ")", "# Read/write all in one block, so we don't create a corrupt file", "# if the download is interrupted.", "data", "=", "src", ".", "read", "(", ")", "dst", "=", "open", "(", "target", ",", "\"wb\"", ")", "dst", ".", "write", "(", "data", ")", "finally", ":", "if", "src", ":", "src", ".", "close", "(", ")", "if", "dst", ":", "dst", ".", "close", "(", ")" ]
https://github.com/Georce/lepus/blob/5b01bae82b5dc1df00c9e058989e2eb9b89ff333/lepus/pymongo-2.7/ez_setup.py#L231-L252
pyparallel/pyparallel
11e8c6072d48c8f13641925d17b147bf36ee0ba3
Lib/site-packages/Cython-0.23.4-py3.3-win-amd64.egg/Cython/Compiler/MemoryView.py
python
put_acquire_memoryviewslice
(lhs_cname, lhs_type, lhs_pos, rhs, code, have_gil=False, first_assignment=True)
We can avoid decreffing the lhs if we know it is the first assignment
We can avoid decreffing the lhs if we know it is the first assignment
[ "We", "can", "avoid", "decreffing", "the", "lhs", "if", "we", "know", "it", "is", "the", "first", "assignment" ]
def put_acquire_memoryviewslice(lhs_cname, lhs_type, lhs_pos, rhs, code, have_gil=False, first_assignment=True): "We can avoid decreffing the lhs if we know it is the first assignment" assert rhs.type.is_memoryviewslice pretty_rhs = rhs.result_in_temp() or rhs.is_simple() if pretty_rhs: rhstmp = rhs.result() else: rhstmp = code.funcstate.allocate_temp(lhs_type, manage_ref=False) code.putln("%s = %s;" % (rhstmp, rhs.result_as(lhs_type))) # Allow uninitialized assignment #code.putln(code.put_error_if_unbound(lhs_pos, rhs.entry)) put_assign_to_memviewslice(lhs_cname, rhs, rhstmp, lhs_type, code, have_gil=have_gil, first_assignment=first_assignment) if not pretty_rhs: code.funcstate.release_temp(rhstmp)
[ "def", "put_acquire_memoryviewslice", "(", "lhs_cname", ",", "lhs_type", ",", "lhs_pos", ",", "rhs", ",", "code", ",", "have_gil", "=", "False", ",", "first_assignment", "=", "True", ")", ":", "assert", "rhs", ".", "type", ".", "is_memoryviewslice", "pretty_rhs", "=", "rhs", ".", "result_in_temp", "(", ")", "or", "rhs", ".", "is_simple", "(", ")", "if", "pretty_rhs", ":", "rhstmp", "=", "rhs", ".", "result", "(", ")", "else", ":", "rhstmp", "=", "code", ".", "funcstate", ".", "allocate_temp", "(", "lhs_type", ",", "manage_ref", "=", "False", ")", "code", ".", "putln", "(", "\"%s = %s;\"", "%", "(", "rhstmp", ",", "rhs", ".", "result_as", "(", "lhs_type", ")", ")", ")", "# Allow uninitialized assignment", "#code.putln(code.put_error_if_unbound(lhs_pos, rhs.entry))", "put_assign_to_memviewslice", "(", "lhs_cname", ",", "rhs", ",", "rhstmp", ",", "lhs_type", ",", "code", ",", "have_gil", "=", "have_gil", ",", "first_assignment", "=", "first_assignment", ")", "if", "not", "pretty_rhs", ":", "code", ".", "funcstate", ".", "release_temp", "(", "rhstmp", ")" ]
https://github.com/pyparallel/pyparallel/blob/11e8c6072d48c8f13641925d17b147bf36ee0ba3/Lib/site-packages/Cython-0.23.4-py3.3-win-amd64.egg/Cython/Compiler/MemoryView.py#L86-L104
AppScale/gts
46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9
AppServer/google/appengine/ext/mapreduce/shuffler.py
python
_HashingGCSOutputWriter.__init__
(self, filehandles)
Constructor. Args: filehandles: list of file handles that this writer outputs to.
Constructor.
[ "Constructor", "." ]
def __init__(self, filehandles): """Constructor. Args: filehandles: list of file handles that this writer outputs to. """ self._filehandles = filehandles self._pools = [None] * len(filehandles)
[ "def", "__init__", "(", "self", ",", "filehandles", ")", ":", "self", ".", "_filehandles", "=", "filehandles", "self", ".", "_pools", "=", "[", "None", "]", "*", "len", "(", "filehandles", ")" ]
https://github.com/AppScale/gts/blob/46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9/AppServer/google/appengine/ext/mapreduce/shuffler.py#L435-L442
viblo/pymunk
77647ca037d5ceabd728f20f37d2da8a3bfb73a0
pymunk/space.py
python
Space._remove_body
(self, body: "Body")
Removes a body from the space
Removes a body from the space
[ "Removes", "a", "body", "from", "the", "space" ]
def _remove_body(self, body: "Body") -> None: """Removes a body from the space""" assert body in self._bodies, "body not in space, already removed?" body._space = None # During GC at program exit sometimes the shape might already be removed. Then skip this step. if cp.cpSpaceContainsBody(self._space, body._body): cp.cpSpaceRemoveBody(self._space, body._body) del self._bodies[body]
[ "def", "_remove_body", "(", "self", ",", "body", ":", "\"Body\"", ")", "->", "None", ":", "assert", "body", "in", "self", ".", "_bodies", ",", "\"body not in space, already removed?\"", "body", ".", "_space", "=", "None", "# During GC at program exit sometimes the shape might already be removed. Then skip this step.", "if", "cp", ".", "cpSpaceContainsBody", "(", "self", ".", "_space", ",", "body", ".", "_body", ")", ":", "cp", ".", "cpSpaceRemoveBody", "(", "self", ".", "_space", ",", "body", ".", "_body", ")", "del", "self", ".", "_bodies", "[", "body", "]" ]
https://github.com/viblo/pymunk/blob/77647ca037d5ceabd728f20f37d2da8a3bfb73a0/pymunk/space.py#L476-L483
JelteF/PyLaTeX
1a73261b771ae15afbb3ca5f06d4ba61328f1c62
pylatex/document.py
python
Document.generate_pdf
(self, filepath=None, *, clean=True, clean_tex=True, compiler=None, compiler_args=None, silent=True)
Generate a pdf file from the document. Args ---- filepath: str The name of the file (without .pdf), if it is `None` the ``default_filepath`` attribute will be used. clean: bool Whether non-pdf files created that are created during compilation should be removed. clean_tex: bool Also remove the generated tex file. compiler: `str` or `None` The name of the LaTeX compiler to use. If it is None, PyLaTeX will choose a fitting one on its own. Starting with ``latexmk`` and then ``pdflatex``. compiler_args: `list` or `None` Extra arguments that should be passed to the LaTeX compiler. If this is None it defaults to an empty list. silent: bool Whether to hide compiler output
Generate a pdf file from the document.
[ "Generate", "a", "pdf", "file", "from", "the", "document", "." ]
def generate_pdf(self, filepath=None, *, clean=True, clean_tex=True, compiler=None, compiler_args=None, silent=True): """Generate a pdf file from the document. Args ---- filepath: str The name of the file (without .pdf), if it is `None` the ``default_filepath`` attribute will be used. clean: bool Whether non-pdf files created that are created during compilation should be removed. clean_tex: bool Also remove the generated tex file. compiler: `str` or `None` The name of the LaTeX compiler to use. If it is None, PyLaTeX will choose a fitting one on its own. Starting with ``latexmk`` and then ``pdflatex``. compiler_args: `list` or `None` Extra arguments that should be passed to the LaTeX compiler. If this is None it defaults to an empty list. silent: bool Whether to hide compiler output """ if compiler_args is None: compiler_args = [] # In case of newer python with the use of the cwd parameter # one can avoid to physically change the directory # to the destination folder python_cwd_available = sys.version_info >= (3, 6) filepath = self._select_filepath(filepath) if not os.path.basename(filepath): filepath = os.path.join(os.path.abspath(filepath), 'default_basename') else: filepath = os.path.abspath(filepath) cur_dir = os.getcwd() dest_dir = os.path.dirname(filepath) if not python_cwd_available: os.chdir(dest_dir) self.generate_tex(filepath) if compiler is not None: compilers = ((compiler, []),) else: latexmk_args = ['--pdf'] compilers = ( ('latexmk', latexmk_args), ('pdflatex', []) ) main_arguments = ['--interaction=nonstopmode', filepath + '.tex'] check_output_kwargs = {} if python_cwd_available: check_output_kwargs = {'cwd': dest_dir} os_error = None for compiler, arguments in compilers: command = [compiler] + arguments + compiler_args + main_arguments try: output = subprocess.check_output(command, stderr=subprocess.STDOUT, **check_output_kwargs) except (OSError, IOError) as e: # Use FileNotFoundError when python 2 is dropped os_error = e if os_error.errno == errno.ENOENT: # If compiler does not exist, try next in the list continue raise except subprocess.CalledProcessError as e: # For all other errors print the output and raise the error print(e.output.decode()) raise else: if not silent: print(output.decode()) if clean: try: # Try latexmk cleaning first subprocess.check_output(['latexmk', '-c', filepath], stderr=subprocess.STDOUT, **check_output_kwargs) except (OSError, IOError, subprocess.CalledProcessError): # Otherwise just remove some file extensions. extensions = ['aux', 'log', 'out', 'fls', 'fdb_latexmk'] for ext in extensions: try: os.remove(filepath + '.' + ext) except (OSError, IOError) as e: # Use FileNotFoundError when python 2 is dropped if e.errno != errno.ENOENT: raise rm_temp_dir() if clean_tex: os.remove(filepath + '.tex') # Remove generated tex file # Compilation has finished, so no further compilers have to be # tried break else: # Notify user that none of the compilers worked. raise(CompilerError( 'No LaTex compiler was found\n' 'Either specify a LaTex compiler ' 'or make sure you have latexmk or pdfLaTex installed.' )) if not python_cwd_available: os.chdir(cur_dir)
[ "def", "generate_pdf", "(", "self", ",", "filepath", "=", "None", ",", "*", ",", "clean", "=", "True", ",", "clean_tex", "=", "True", ",", "compiler", "=", "None", ",", "compiler_args", "=", "None", ",", "silent", "=", "True", ")", ":", "if", "compiler_args", "is", "None", ":", "compiler_args", "=", "[", "]", "# In case of newer python with the use of the cwd parameter", "# one can avoid to physically change the directory", "# to the destination folder", "python_cwd_available", "=", "sys", ".", "version_info", ">=", "(", "3", ",", "6", ")", "filepath", "=", "self", ".", "_select_filepath", "(", "filepath", ")", "if", "not", "os", ".", "path", ".", "basename", "(", "filepath", ")", ":", "filepath", "=", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "abspath", "(", "filepath", ")", ",", "'default_basename'", ")", "else", ":", "filepath", "=", "os", ".", "path", ".", "abspath", "(", "filepath", ")", "cur_dir", "=", "os", ".", "getcwd", "(", ")", "dest_dir", "=", "os", ".", "path", ".", "dirname", "(", "filepath", ")", "if", "not", "python_cwd_available", ":", "os", ".", "chdir", "(", "dest_dir", ")", "self", ".", "generate_tex", "(", "filepath", ")", "if", "compiler", "is", "not", "None", ":", "compilers", "=", "(", "(", "compiler", ",", "[", "]", ")", ",", ")", "else", ":", "latexmk_args", "=", "[", "'--pdf'", "]", "compilers", "=", "(", "(", "'latexmk'", ",", "latexmk_args", ")", ",", "(", "'pdflatex'", ",", "[", "]", ")", ")", "main_arguments", "=", "[", "'--interaction=nonstopmode'", ",", "filepath", "+", "'.tex'", "]", "check_output_kwargs", "=", "{", "}", "if", "python_cwd_available", ":", "check_output_kwargs", "=", "{", "'cwd'", ":", "dest_dir", "}", "os_error", "=", "None", "for", "compiler", ",", "arguments", "in", "compilers", ":", "command", "=", "[", "compiler", "]", "+", "arguments", "+", "compiler_args", "+", "main_arguments", "try", ":", "output", "=", "subprocess", ".", "check_output", "(", "command", ",", "stderr", "=", "subprocess", ".", "STDOUT", ",", "*", "*", "check_output_kwargs", ")", "except", "(", "OSError", ",", "IOError", ")", "as", "e", ":", "# Use FileNotFoundError when python 2 is dropped", "os_error", "=", "e", "if", "os_error", ".", "errno", "==", "errno", ".", "ENOENT", ":", "# If compiler does not exist, try next in the list", "continue", "raise", "except", "subprocess", ".", "CalledProcessError", "as", "e", ":", "# For all other errors print the output and raise the error", "print", "(", "e", ".", "output", ".", "decode", "(", ")", ")", "raise", "else", ":", "if", "not", "silent", ":", "print", "(", "output", ".", "decode", "(", ")", ")", "if", "clean", ":", "try", ":", "# Try latexmk cleaning first", "subprocess", ".", "check_output", "(", "[", "'latexmk'", ",", "'-c'", ",", "filepath", "]", ",", "stderr", "=", "subprocess", ".", "STDOUT", ",", "*", "*", "check_output_kwargs", ")", "except", "(", "OSError", ",", "IOError", ",", "subprocess", ".", "CalledProcessError", ")", ":", "# Otherwise just remove some file extensions.", "extensions", "=", "[", "'aux'", ",", "'log'", ",", "'out'", ",", "'fls'", ",", "'fdb_latexmk'", "]", "for", "ext", "in", "extensions", ":", "try", ":", "os", ".", "remove", "(", "filepath", "+", "'.'", "+", "ext", ")", "except", "(", "OSError", ",", "IOError", ")", "as", "e", ":", "# Use FileNotFoundError when python 2 is dropped", "if", "e", ".", "errno", "!=", "errno", ".", "ENOENT", ":", "raise", "rm_temp_dir", "(", ")", "if", "clean_tex", ":", "os", ".", "remove", "(", "filepath", "+", "'.tex'", ")", "# Remove generated tex file", "# Compilation has finished, so no further compilers have to be", "# tried", "break", "else", ":", "# Notify user that none of the compilers worked.", "raise", "(", "CompilerError", "(", "'No LaTex compiler was found\\n'", "'Either specify a LaTex compiler '", "'or make sure you have latexmk or pdfLaTex installed.'", ")", ")", "if", "not", "python_cwd_available", ":", "os", ".", "chdir", "(", "cur_dir", ")" ]
https://github.com/JelteF/PyLaTeX/blob/1a73261b771ae15afbb3ca5f06d4ba61328f1c62/pylatex/document.py#L180-L305
praekeltfoundation/vumi
b74b5dac95df778519f54c670a353e4bda496df9
vumi/dispatchers/base.py
python
BaseDispatchRouter.dispatch_inbound_event
(self, msg)
Dispatch an event to a publisher. :param vumi.message.TransportEvent msg: Message to dispatch.
Dispatch an event to a publisher.
[ "Dispatch", "an", "event", "to", "a", "publisher", "." ]
def dispatch_inbound_event(self, msg): """Dispatch an event to a publisher. :param vumi.message.TransportEvent msg: Message to dispatch. """ raise NotImplementedError()
[ "def", "dispatch_inbound_event", "(", "self", ",", "msg", ")", ":", "raise", "NotImplementedError", "(", ")" ]
https://github.com/praekeltfoundation/vumi/blob/b74b5dac95df778519f54c670a353e4bda496df9/vumi/dispatchers/base.py#L199-L205
wxWidgets/Phoenix
b2199e299a6ca6d866aa6f3d0888499136ead9d6
wx/lib/agw/flatnotebook.py
python
PageContainer.OnMouseMove
(self, event)
Handles the ``wx.EVT_MOTION`` event for :class:`PageContainer`. :param `event`: a :class:`MouseEvent` event to be processed.
Handles the ``wx.EVT_MOTION`` event for :class:`PageContainer`.
[ "Handles", "the", "wx", ".", "EVT_MOTION", "event", "for", ":", "class", ":", "PageContainer", "." ]
def OnMouseMove(self, event): """ Handles the ``wx.EVT_MOTION`` event for :class:`PageContainer`. :param `event`: a :class:`MouseEvent` event to be processed. """ if self._pagesInfoVec and self.IsShown(): xButtonStatus = self._nXButtonStatus xTabButtonStatus = self._nTabXButtonStatus rightButtonStatus = self._nRightButtonStatus leftButtonStatus = self._nLeftButtonStatus dropDownButtonStatus = self._nArrowDownButtonStatus agwStyle = self.GetParent().GetAGWWindowStyleFlag() self._nXButtonStatus = FNB_BTN_NONE self._nRightButtonStatus = FNB_BTN_NONE self._nLeftButtonStatus = FNB_BTN_NONE self._nTabXButtonStatus = FNB_BTN_NONE self._nArrowDownButtonStatus = FNB_BTN_NONE bRedrawTabs = False self._nHoveringOverTabIndex = -1 where, tabIdx = self.HitTest(event.GetPosition()) if where == FNB_X: if event.LeftIsDown(): self._nXButtonStatus = (self._nLeftClickZone==FNB_X and [FNB_BTN_PRESSED] or [FNB_BTN_NONE])[0] else: self._nXButtonStatus = FNB_BTN_HOVER elif where == FNB_DROP_DOWN_ARROW: if event.LeftIsDown(): self._nArrowDownButtonStatus = (self._nLeftClickZone==FNB_DROP_DOWN_ARROW and [FNB_BTN_PRESSED] or [FNB_BTN_NONE])[0] else: self._nArrowDownButtonStatus = FNB_BTN_HOVER elif where == FNB_TAB_X: if event.LeftIsDown(): self._nTabXButtonStatus = (self._nLeftClickZone==FNB_TAB_X and [FNB_BTN_PRESSED] or [FNB_BTN_NONE])[0] else: self._nTabXButtonStatus = FNB_BTN_HOVER elif where == FNB_RIGHT_ARROW: if event.LeftIsDown(): self._nRightButtonStatus = (self._nLeftClickZone==FNB_RIGHT_ARROW and [FNB_BTN_PRESSED] or [FNB_BTN_NONE])[0] else: self._nRightButtonStatus = FNB_BTN_HOVER elif where == FNB_LEFT_ARROW: if event.LeftIsDown(): self._nLeftButtonStatus = (self._nLeftClickZone==FNB_LEFT_ARROW and [FNB_BTN_PRESSED] or [FNB_BTN_NONE])[0] else: self._nLeftButtonStatus = FNB_BTN_HOVER elif where == FNB_TAB: # Call virtual method for showing tooltip self.ShowTabTooltip(tabIdx) if not self.GetEnabled(tabIdx): # Set the cursor to be 'No-entry' self.SetCursor(wx.Cursor(wx.CURSOR_NO_ENTRY)) self._setCursor = True else: self._nHoveringOverTabIndex = tabIdx if self._setCursor: self.SetCursor(wx.Cursor(wx.CURSOR_ARROW)) self._setCursor = False # Support for drag and drop if event.Dragging() and not (agwStyle & FNB_NODRAG): self._isdragging = True draginfo = FNBDragInfo(self, tabIdx) drginfo = pickle.dumps(draginfo) dataobject = wx.CustomDataObject(FNB_DataFormat) dataobject.SetData(drginfo) dragSource = FNBDropSource(self) dragSource.SetData(dataobject) dragSource.DoDragDrop(wx.Drag_DefaultMove) if self._nHoveringOverTabIndex != self._nHoveringOverLastTabIndex: self._nHoveringOverLastTabIndex = self._nHoveringOverTabIndex if self._nHoveringOverTabIndex >= 0: bRedrawTabs = True bRedrawX = self._nXButtonStatus != xButtonStatus bRedrawRight = self._nRightButtonStatus != rightButtonStatus bRedrawLeft = self._nLeftButtonStatus != leftButtonStatus bRedrawTabX = self._nTabXButtonStatus != xTabButtonStatus bRedrawDropArrow = self._nArrowDownButtonStatus != dropDownButtonStatus render = self._mgr.GetRenderer(agwStyle) if (bRedrawX or bRedrawRight or bRedrawLeft or bRedrawTabX or bRedrawDropArrow or bRedrawTabs): dc = wx.ClientDC(self) if bRedrawX: render.DrawX(self, dc) if bRedrawLeft: render.DrawLeftArrow(self, dc) if bRedrawRight: render.DrawRightArrow(self, dc) if bRedrawTabX or bRedrawTabs: self.Refresh() if bRedrawDropArrow: render.DrawDropDownArrow(self, dc) event.Skip()
[ "def", "OnMouseMove", "(", "self", ",", "event", ")", ":", "if", "self", ".", "_pagesInfoVec", "and", "self", ".", "IsShown", "(", ")", ":", "xButtonStatus", "=", "self", ".", "_nXButtonStatus", "xTabButtonStatus", "=", "self", ".", "_nTabXButtonStatus", "rightButtonStatus", "=", "self", ".", "_nRightButtonStatus", "leftButtonStatus", "=", "self", ".", "_nLeftButtonStatus", "dropDownButtonStatus", "=", "self", ".", "_nArrowDownButtonStatus", "agwStyle", "=", "self", ".", "GetParent", "(", ")", ".", "GetAGWWindowStyleFlag", "(", ")", "self", ".", "_nXButtonStatus", "=", "FNB_BTN_NONE", "self", ".", "_nRightButtonStatus", "=", "FNB_BTN_NONE", "self", ".", "_nLeftButtonStatus", "=", "FNB_BTN_NONE", "self", ".", "_nTabXButtonStatus", "=", "FNB_BTN_NONE", "self", ".", "_nArrowDownButtonStatus", "=", "FNB_BTN_NONE", "bRedrawTabs", "=", "False", "self", ".", "_nHoveringOverTabIndex", "=", "-", "1", "where", ",", "tabIdx", "=", "self", ".", "HitTest", "(", "event", ".", "GetPosition", "(", ")", ")", "if", "where", "==", "FNB_X", ":", "if", "event", ".", "LeftIsDown", "(", ")", ":", "self", ".", "_nXButtonStatus", "=", "(", "self", ".", "_nLeftClickZone", "==", "FNB_X", "and", "[", "FNB_BTN_PRESSED", "]", "or", "[", "FNB_BTN_NONE", "]", ")", "[", "0", "]", "else", ":", "self", ".", "_nXButtonStatus", "=", "FNB_BTN_HOVER", "elif", "where", "==", "FNB_DROP_DOWN_ARROW", ":", "if", "event", ".", "LeftIsDown", "(", ")", ":", "self", ".", "_nArrowDownButtonStatus", "=", "(", "self", ".", "_nLeftClickZone", "==", "FNB_DROP_DOWN_ARROW", "and", "[", "FNB_BTN_PRESSED", "]", "or", "[", "FNB_BTN_NONE", "]", ")", "[", "0", "]", "else", ":", "self", ".", "_nArrowDownButtonStatus", "=", "FNB_BTN_HOVER", "elif", "where", "==", "FNB_TAB_X", ":", "if", "event", ".", "LeftIsDown", "(", ")", ":", "self", ".", "_nTabXButtonStatus", "=", "(", "self", ".", "_nLeftClickZone", "==", "FNB_TAB_X", "and", "[", "FNB_BTN_PRESSED", "]", "or", "[", "FNB_BTN_NONE", "]", ")", "[", "0", "]", "else", ":", "self", ".", "_nTabXButtonStatus", "=", "FNB_BTN_HOVER", "elif", "where", "==", "FNB_RIGHT_ARROW", ":", "if", "event", ".", "LeftIsDown", "(", ")", ":", "self", ".", "_nRightButtonStatus", "=", "(", "self", ".", "_nLeftClickZone", "==", "FNB_RIGHT_ARROW", "and", "[", "FNB_BTN_PRESSED", "]", "or", "[", "FNB_BTN_NONE", "]", ")", "[", "0", "]", "else", ":", "self", ".", "_nRightButtonStatus", "=", "FNB_BTN_HOVER", "elif", "where", "==", "FNB_LEFT_ARROW", ":", "if", "event", ".", "LeftIsDown", "(", ")", ":", "self", ".", "_nLeftButtonStatus", "=", "(", "self", ".", "_nLeftClickZone", "==", "FNB_LEFT_ARROW", "and", "[", "FNB_BTN_PRESSED", "]", "or", "[", "FNB_BTN_NONE", "]", ")", "[", "0", "]", "else", ":", "self", ".", "_nLeftButtonStatus", "=", "FNB_BTN_HOVER", "elif", "where", "==", "FNB_TAB", ":", "# Call virtual method for showing tooltip", "self", ".", "ShowTabTooltip", "(", "tabIdx", ")", "if", "not", "self", ".", "GetEnabled", "(", "tabIdx", ")", ":", "# Set the cursor to be 'No-entry'", "self", ".", "SetCursor", "(", "wx", ".", "Cursor", "(", "wx", ".", "CURSOR_NO_ENTRY", ")", ")", "self", ".", "_setCursor", "=", "True", "else", ":", "self", ".", "_nHoveringOverTabIndex", "=", "tabIdx", "if", "self", ".", "_setCursor", ":", "self", ".", "SetCursor", "(", "wx", ".", "Cursor", "(", "wx", ".", "CURSOR_ARROW", ")", ")", "self", ".", "_setCursor", "=", "False", "# Support for drag and drop", "if", "event", ".", "Dragging", "(", ")", "and", "not", "(", "agwStyle", "&", "FNB_NODRAG", ")", ":", "self", ".", "_isdragging", "=", "True", "draginfo", "=", "FNBDragInfo", "(", "self", ",", "tabIdx", ")", "drginfo", "=", "pickle", ".", "dumps", "(", "draginfo", ")", "dataobject", "=", "wx", ".", "CustomDataObject", "(", "FNB_DataFormat", ")", "dataobject", ".", "SetData", "(", "drginfo", ")", "dragSource", "=", "FNBDropSource", "(", "self", ")", "dragSource", ".", "SetData", "(", "dataobject", ")", "dragSource", ".", "DoDragDrop", "(", "wx", ".", "Drag_DefaultMove", ")", "if", "self", ".", "_nHoveringOverTabIndex", "!=", "self", ".", "_nHoveringOverLastTabIndex", ":", "self", ".", "_nHoveringOverLastTabIndex", "=", "self", ".", "_nHoveringOverTabIndex", "if", "self", ".", "_nHoveringOverTabIndex", ">=", "0", ":", "bRedrawTabs", "=", "True", "bRedrawX", "=", "self", ".", "_nXButtonStatus", "!=", "xButtonStatus", "bRedrawRight", "=", "self", ".", "_nRightButtonStatus", "!=", "rightButtonStatus", "bRedrawLeft", "=", "self", ".", "_nLeftButtonStatus", "!=", "leftButtonStatus", "bRedrawTabX", "=", "self", ".", "_nTabXButtonStatus", "!=", "xTabButtonStatus", "bRedrawDropArrow", "=", "self", ".", "_nArrowDownButtonStatus", "!=", "dropDownButtonStatus", "render", "=", "self", ".", "_mgr", ".", "GetRenderer", "(", "agwStyle", ")", "if", "(", "bRedrawX", "or", "bRedrawRight", "or", "bRedrawLeft", "or", "bRedrawTabX", "or", "bRedrawDropArrow", "or", "bRedrawTabs", ")", ":", "dc", "=", "wx", ".", "ClientDC", "(", "self", ")", "if", "bRedrawX", ":", "render", ".", "DrawX", "(", "self", ",", "dc", ")", "if", "bRedrawLeft", ":", "render", ".", "DrawLeftArrow", "(", "self", ",", "dc", ")", "if", "bRedrawRight", ":", "render", ".", "DrawRightArrow", "(", "self", ",", "dc", ")", "if", "bRedrawTabX", "or", "bRedrawTabs", ":", "self", ".", "Refresh", "(", ")", "if", "bRedrawDropArrow", ":", "render", ".", "DrawDropDownArrow", "(", "self", ",", "dc", ")", "event", ".", "Skip", "(", ")" ]
https://github.com/wxWidgets/Phoenix/blob/b2199e299a6ca6d866aa6f3d0888499136ead9d6/wx/lib/agw/flatnotebook.py#L5748-L5883
titusjan/argos
5a9c31a8a9a2ca825bbf821aa1e685740e3682d7
argos/qt/treemodels.py
python
BaseTreeModel.parent
(self, index)
return self.createIndex(parentItem.childNumber(), 0, parentItem)
Returns the parent of the model item with the given index. If the item has no parent, an invalid QModelIndex is returned. A common convention used in models that expose tree data structures is that only items in the first column have children. For that case, when reimplementing this function in a subclass the column of the returned QModelIndex would be 0. (This is done here.) When reimplementing this function in a subclass, be careful to avoid calling QModelIndex member functions, such as QModelIndex.parent(), since indexes belonging to your model will simply call your implementation, leading to infinite recursion.
Returns the parent of the model item with the given index. If the item has no parent, an invalid QModelIndex is returned.
[ "Returns", "the", "parent", "of", "the", "model", "item", "with", "the", "given", "index", ".", "If", "the", "item", "has", "no", "parent", "an", "invalid", "QModelIndex", "is", "returned", "." ]
def parent(self, index): """ Returns the parent of the model item with the given index. If the item has no parent, an invalid QModelIndex is returned. A common convention used in models that expose tree data structures is that only items in the first column have children. For that case, when reimplementing this function in a subclass the column of the returned QModelIndex would be 0. (This is done here.) When reimplementing this function in a subclass, be careful to avoid calling QModelIndex member functions, such as QModelIndex.parent(), since indexes belonging to your model will simply call your implementation, leading to infinite recursion. """ if not index.isValid(): return QtCore.QModelIndex() childItem = self.getItem(index, altItem=self.invisibleRootTreeItem) parentItem = childItem.parentItem if parentItem == self.invisibleRootTreeItem: return QtCore.QModelIndex() return self.createIndex(parentItem.childNumber(), 0, parentItem)
[ "def", "parent", "(", "self", ",", "index", ")", ":", "if", "not", "index", ".", "isValid", "(", ")", ":", "return", "QtCore", ".", "QModelIndex", "(", ")", "childItem", "=", "self", ".", "getItem", "(", "index", ",", "altItem", "=", "self", ".", "invisibleRootTreeItem", ")", "parentItem", "=", "childItem", ".", "parentItem", "if", "parentItem", "==", "self", ".", "invisibleRootTreeItem", ":", "return", "QtCore", ".", "QModelIndex", "(", ")", "return", "self", ".", "createIndex", "(", "parentItem", ".", "childNumber", "(", ")", ",", "0", ",", "parentItem", ")" ]
https://github.com/titusjan/argos/blob/5a9c31a8a9a2ca825bbf821aa1e685740e3682d7/argos/qt/treemodels.py#L210-L231
learningequality/ka-lite
571918ea668013dcf022286ea85eff1c5333fb8b
kalite/packages/bundled/django/middleware/common.py
python
_is_internal_request
(domain, referer)
return referer is not None and re.match("^https?://%s/" % re.escape(domain), referer)
Returns true if the referring URL is the same domain as the current request.
Returns true if the referring URL is the same domain as the current request.
[ "Returns", "true", "if", "the", "referring", "URL", "is", "the", "same", "domain", "as", "the", "current", "request", "." ]
def _is_internal_request(domain, referer): """ Returns true if the referring URL is the same domain as the current request. """ # Different subdomains are treated as different domains. return referer is not None and re.match("^https?://%s/" % re.escape(domain), referer)
[ "def", "_is_internal_request", "(", "domain", ",", "referer", ")", ":", "# Different subdomains are treated as different domains.", "return", "referer", "is", "not", "None", "and", "re", ".", "match", "(", "\"^https?://%s/\"", "%", "re", ".", "escape", "(", "domain", ")", ",", "referer", ")" ]
https://github.com/learningequality/ka-lite/blob/571918ea668013dcf022286ea85eff1c5333fb8b/kalite/packages/bundled/django/middleware/common.py#L162-L167
Behappy123/market-maker
aaed8cf8c994771e0a6ff070ce19b15efbfbd1c4
market_maker/bitmex.py
python
BitMEX._curl_bitmex
(self, api, query=None, postdict=None, timeout=3, verb=None, rethrow_errors=False)
return response.json()
Send a request to BitMEX Servers.
Send a request to BitMEX Servers.
[ "Send", "a", "request", "to", "BitMEX", "Servers", "." ]
def _curl_bitmex(self, api, query=None, postdict=None, timeout=3, verb=None, rethrow_errors=False): """Send a request to BitMEX Servers.""" # Handle URL url = self.base_url + api # Default to POST if data is attached, GET otherwise if not verb: verb = 'POST' if postdict else 'GET' # Auth: Use Access Token by default, API Key/Secret if provided auth = AccessTokenAuth(self.token) if self.apiKey: auth = APIKeyAuthWithExpires(self.apiKey, self.apiSecret) def maybe_exit(e): if rethrow_errors: raise e else: exit(1) # Make the request try: req = requests.Request(verb, url, json=postdict, auth=auth, params=query) prepped = self.session.prepare_request(req) response = self.session.send(prepped, timeout=timeout) # Make non-200s throw response.raise_for_status() except requests.exceptions.HTTPError as e: # 401 - Auth error. This is fatal with API keys. if response.status_code == 401: self.logger.error("Login information or API Key incorrect, please check and restart.") self.logger.error("Error: " + response.text) if postdict: self.logger.error(postdict) # Always exit, even if rethrow_errors, because this is fatal exit(1) return self._curl_bitmex(api, query, postdict, timeout, verb) # 404, can be thrown if order canceled does not exist. elif response.status_code == 404: if verb == 'DELETE': self.logger.error("Order not found: %s" % postdict['orderID']) return self.logger.error("Unable to contact the BitMEX API (404). " + "Request: %s \n %s" % (url, json.dumps(postdict))) maybe_exit(e) # 429, ratelimit elif response.status_code == 429: self.logger.error("Ratelimited on current request. Sleeping, then trying again. Try fewer " + "order pairs or contact [email protected] to raise your limits. " + "Request: %s \n %s" % (url, json.dumps(postdict))) sleep(1) return self._curl_bitmex(api, query, postdict, timeout, verb) # 503 - BitMEX temporary downtime, likely due to a deploy. Try again elif response.status_code == 503: self.logger.warning("Unable to contact the BitMEX API (503), retrying. " + "Request: %s \n %s" % (url, json.dumps(postdict))) sleep(1) return self._curl_bitmex(api, query, postdict, timeout, verb) # Duplicate clOrdID: that's fine, probably a deploy, go get the order and return it elif (response.status_code == 400 and response.json()['error'] and response.json()['error']['message'] == 'Duplicate clOrdID'): order = self._curl_bitmex('/order', query={'filter': json.dumps({'clOrdID': postdict['clOrdID']})}, verb='GET')[0] if ( order['orderQty'] != postdict['quantity'] or order['price'] != postdict['price'] or order['symbol'] != postdict['symbol']): raise Exception('Attempted to recover from duplicate clOrdID, but order returned from API ' + 'did not match POST.\nPOST data: %s\nReturned order: %s' % ( json.dumps(postdict), json.dumps(order))) # All good return order # Unknown Error else: self.logger.error("Unhandled Error: %s: %s" % (e, response.text)) self.logger.error("Endpoint was: %s %s: %s" % (verb, api, json.dumps(postdict))) maybe_exit(e) except requests.exceptions.Timeout as e: # Timeout, re-run this request self.logger.warning("Timed out, retrying...") return self._curl_bitmex(api, query, postdict, timeout, verb) except requests.exceptions.ConnectionError as e: self.logger.warning("Unable to contact the BitMEX API (ConnectionError). Please check the URL. Retrying. " + "Request: %s \n %s" % (url, json.dumps(postdict))) sleep(1) return self._curl_bitmex(api, query, postdict, timeout, verb) return response.json()
[ "def", "_curl_bitmex", "(", "self", ",", "api", ",", "query", "=", "None", ",", "postdict", "=", "None", ",", "timeout", "=", "3", ",", "verb", "=", "None", ",", "rethrow_errors", "=", "False", ")", ":", "# Handle URL", "url", "=", "self", ".", "base_url", "+", "api", "# Default to POST if data is attached, GET otherwise", "if", "not", "verb", ":", "verb", "=", "'POST'", "if", "postdict", "else", "'GET'", "# Auth: Use Access Token by default, API Key/Secret if provided", "auth", "=", "AccessTokenAuth", "(", "self", ".", "token", ")", "if", "self", ".", "apiKey", ":", "auth", "=", "APIKeyAuthWithExpires", "(", "self", ".", "apiKey", ",", "self", ".", "apiSecret", ")", "def", "maybe_exit", "(", "e", ")", ":", "if", "rethrow_errors", ":", "raise", "e", "else", ":", "exit", "(", "1", ")", "# Make the request", "try", ":", "req", "=", "requests", ".", "Request", "(", "verb", ",", "url", ",", "json", "=", "postdict", ",", "auth", "=", "auth", ",", "params", "=", "query", ")", "prepped", "=", "self", ".", "session", ".", "prepare_request", "(", "req", ")", "response", "=", "self", ".", "session", ".", "send", "(", "prepped", ",", "timeout", "=", "timeout", ")", "# Make non-200s throw", "response", ".", "raise_for_status", "(", ")", "except", "requests", ".", "exceptions", ".", "HTTPError", "as", "e", ":", "# 401 - Auth error. This is fatal with API keys.", "if", "response", ".", "status_code", "==", "401", ":", "self", ".", "logger", ".", "error", "(", "\"Login information or API Key incorrect, please check and restart.\"", ")", "self", ".", "logger", ".", "error", "(", "\"Error: \"", "+", "response", ".", "text", ")", "if", "postdict", ":", "self", ".", "logger", ".", "error", "(", "postdict", ")", "# Always exit, even if rethrow_errors, because this is fatal", "exit", "(", "1", ")", "return", "self", ".", "_curl_bitmex", "(", "api", ",", "query", ",", "postdict", ",", "timeout", ",", "verb", ")", "# 404, can be thrown if order canceled does not exist.", "elif", "response", ".", "status_code", "==", "404", ":", "if", "verb", "==", "'DELETE'", ":", "self", ".", "logger", ".", "error", "(", "\"Order not found: %s\"", "%", "postdict", "[", "'orderID'", "]", ")", "return", "self", ".", "logger", ".", "error", "(", "\"Unable to contact the BitMEX API (404). \"", "+", "\"Request: %s \\n %s\"", "%", "(", "url", ",", "json", ".", "dumps", "(", "postdict", ")", ")", ")", "maybe_exit", "(", "e", ")", "# 429, ratelimit", "elif", "response", ".", "status_code", "==", "429", ":", "self", ".", "logger", ".", "error", "(", "\"Ratelimited on current request. Sleeping, then trying again. Try fewer \"", "+", "\"order pairs or contact [email protected] to raise your limits. \"", "+", "\"Request: %s \\n %s\"", "%", "(", "url", ",", "json", ".", "dumps", "(", "postdict", ")", ")", ")", "sleep", "(", "1", ")", "return", "self", ".", "_curl_bitmex", "(", "api", ",", "query", ",", "postdict", ",", "timeout", ",", "verb", ")", "# 503 - BitMEX temporary downtime, likely due to a deploy. Try again", "elif", "response", ".", "status_code", "==", "503", ":", "self", ".", "logger", ".", "warning", "(", "\"Unable to contact the BitMEX API (503), retrying. \"", "+", "\"Request: %s \\n %s\"", "%", "(", "url", ",", "json", ".", "dumps", "(", "postdict", ")", ")", ")", "sleep", "(", "1", ")", "return", "self", ".", "_curl_bitmex", "(", "api", ",", "query", ",", "postdict", ",", "timeout", ",", "verb", ")", "# Duplicate clOrdID: that's fine, probably a deploy, go get the order and return it", "elif", "(", "response", ".", "status_code", "==", "400", "and", "response", ".", "json", "(", ")", "[", "'error'", "]", "and", "response", ".", "json", "(", ")", "[", "'error'", "]", "[", "'message'", "]", "==", "'Duplicate clOrdID'", ")", ":", "order", "=", "self", ".", "_curl_bitmex", "(", "'/order'", ",", "query", "=", "{", "'filter'", ":", "json", ".", "dumps", "(", "{", "'clOrdID'", ":", "postdict", "[", "'clOrdID'", "]", "}", ")", "}", ",", "verb", "=", "'GET'", ")", "[", "0", "]", "if", "(", "order", "[", "'orderQty'", "]", "!=", "postdict", "[", "'quantity'", "]", "or", "order", "[", "'price'", "]", "!=", "postdict", "[", "'price'", "]", "or", "order", "[", "'symbol'", "]", "!=", "postdict", "[", "'symbol'", "]", ")", ":", "raise", "Exception", "(", "'Attempted to recover from duplicate clOrdID, but order returned from API '", "+", "'did not match POST.\\nPOST data: %s\\nReturned order: %s'", "%", "(", "json", ".", "dumps", "(", "postdict", ")", ",", "json", ".", "dumps", "(", "order", ")", ")", ")", "# All good", "return", "order", "# Unknown Error", "else", ":", "self", ".", "logger", ".", "error", "(", "\"Unhandled Error: %s: %s\"", "%", "(", "e", ",", "response", ".", "text", ")", ")", "self", ".", "logger", ".", "error", "(", "\"Endpoint was: %s %s: %s\"", "%", "(", "verb", ",", "api", ",", "json", ".", "dumps", "(", "postdict", ")", ")", ")", "maybe_exit", "(", "e", ")", "except", "requests", ".", "exceptions", ".", "Timeout", "as", "e", ":", "# Timeout, re-run this request", "self", ".", "logger", ".", "warning", "(", "\"Timed out, retrying...\"", ")", "return", "self", ".", "_curl_bitmex", "(", "api", ",", "query", ",", "postdict", ",", "timeout", ",", "verb", ")", "except", "requests", ".", "exceptions", ".", "ConnectionError", "as", "e", ":", "self", ".", "logger", ".", "warning", "(", "\"Unable to contact the BitMEX API (ConnectionError). Please check the URL. Retrying. \"", "+", "\"Request: %s \\n %s\"", "%", "(", "url", ",", "json", ".", "dumps", "(", "postdict", ")", ")", ")", "sleep", "(", "1", ")", "return", "self", ".", "_curl_bitmex", "(", "api", ",", "query", ",", "postdict", ",", "timeout", ",", "verb", ")", "return", "response", ".", "json", "(", ")" ]
https://github.com/Behappy123/market-maker/blob/aaed8cf8c994771e0a6ff070ce19b15efbfbd1c4/market_maker/bitmex.py#L184-L282
shiyanhui/FileHeader
f347cc134021fb0b710694b71c57742476f5fd2b
jinja2/nodes.py
python
Node.iter_fields
(self, exclude=None, only=None)
This method iterates over all fields that are defined and yields ``(key, value)`` tuples. Per default all fields are returned, but it's possible to limit that to some fields by providing the `only` parameter or to exclude some using the `exclude` parameter. Both should be sets or tuples of field names.
This method iterates over all fields that are defined and yields ``(key, value)`` tuples. Per default all fields are returned, but it's possible to limit that to some fields by providing the `only` parameter or to exclude some using the `exclude` parameter. Both should be sets or tuples of field names.
[ "This", "method", "iterates", "over", "all", "fields", "that", "are", "defined", "and", "yields", "(", "key", "value", ")", "tuples", ".", "Per", "default", "all", "fields", "are", "returned", "but", "it", "s", "possible", "to", "limit", "that", "to", "some", "fields", "by", "providing", "the", "only", "parameter", "or", "to", "exclude", "some", "using", "the", "exclude", "parameter", ".", "Both", "should", "be", "sets", "or", "tuples", "of", "field", "names", "." ]
def iter_fields(self, exclude=None, only=None): """This method iterates over all fields that are defined and yields ``(key, value)`` tuples. Per default all fields are returned, but it's possible to limit that to some fields by providing the `only` parameter or to exclude some using the `exclude` parameter. Both should be sets or tuples of field names. """ for name in self.fields: if (exclude is only is None) or \ (exclude is not None and name not in exclude) or \ (only is not None and name in only): try: yield name, getattr(self, name) except AttributeError: pass
[ "def", "iter_fields", "(", "self", ",", "exclude", "=", "None", ",", "only", "=", "None", ")", ":", "for", "name", "in", "self", ".", "fields", ":", "if", "(", "exclude", "is", "only", "is", "None", ")", "or", "(", "exclude", "is", "not", "None", "and", "name", "not", "in", "exclude", ")", "or", "(", "only", "is", "not", "None", "and", "name", "in", "only", ")", ":", "try", ":", "yield", "name", ",", "getattr", "(", "self", ",", "name", ")", "except", "AttributeError", ":", "pass" ]
https://github.com/shiyanhui/FileHeader/blob/f347cc134021fb0b710694b71c57742476f5fd2b/jinja2/nodes.py#L148-L162
erdewit/ib_insync
9674fe974c07ca3afaf70673ae296f1d19f028dc
ib_insync/ticker.py
python
TickerUpdateEvent.trades
(self)
return Tickfilter((4, 5, 48, 68, 71), self)
Emit trade ticks.
Emit trade ticks.
[ "Emit", "trade", "ticks", "." ]
def trades(self) -> "Tickfilter": """Emit trade ticks.""" return Tickfilter((4, 5, 48, 68, 71), self)
[ "def", "trades", "(", "self", ")", "->", "\"Tickfilter\"", ":", "return", "Tickfilter", "(", "(", "4", ",", "5", ",", "48", ",", "68", ",", "71", ")", ",", "self", ")" ]
https://github.com/erdewit/ib_insync/blob/9674fe974c07ca3afaf70673ae296f1d19f028dc/ib_insync/ticker.py#L156-L158
berkeleydeeprlcourse/homework_fall2019
e9725d8aba926e2fe1c743f881884111b44e33bb
hw3/cs285/infrastructure/atari_wrappers.py
python
MaxAndSkipEnv.__init__
(self, env, skip=4)
Return only every `skip`-th frame
Return only every `skip`-th frame
[ "Return", "only", "every", "skip", "-", "th", "frame" ]
def __init__(self, env, skip=4): """Return only every `skip`-th frame""" gym.Wrapper.__init__(self, env) # most recent raw observations (for max pooling across time steps) self._obs_buffer = np.zeros((2,)+env.observation_space.shape, dtype=np.uint8) self._skip = skip
[ "def", "__init__", "(", "self", ",", "env", ",", "skip", "=", "4", ")", ":", "gym", ".", "Wrapper", ".", "__init__", "(", "self", ",", "env", ")", "# most recent raw observations (for max pooling across time steps)", "self", ".", "_obs_buffer", "=", "np", ".", "zeros", "(", "(", "2", ",", ")", "+", "env", ".", "observation_space", ".", "shape", ",", "dtype", "=", "np", ".", "uint8", ")", "self", ".", "_skip", "=", "skip" ]
https://github.com/berkeleydeeprlcourse/homework_fall2019/blob/e9725d8aba926e2fe1c743f881884111b44e33bb/hw3/cs285/infrastructure/atari_wrappers.py#L96-L101
SteveDoyle2/pyNastran
eda651ac2d4883d95a34951f8a002ff94f642a1a
pyNastran/dev/bdf_vectorized2/bdf_vectorized.py
python
BDF_.update_card
(self, card_name: str, icard: int, ifield: int, value: Union[int, float, str])
return obj
Updates a Nastran card based on standard Nastran optimization names Parameters ---------- card_name : str the name of the card (e.g. GRID) icard : int the unique 1-based index identifier for the card (e.g. the GRID id) ifield : int the index on the card (e.g. X on GRID card as an integer representing the field number) value : varies the value to assign Returns ------- obj : varies the corresponding object (e.g. the GRID object) # On GRID 100, set Cp (2) to 42 >>> model.update_card('GRID', 100, 2, 42) # On GRID 100, set X (3) to 43. >>> model.update_card('GRID', 100, 3, 43.)
Updates a Nastran card based on standard Nastran optimization names
[ "Updates", "a", "Nastran", "card", "based", "on", "standard", "Nastran", "optimization", "names" ]
def update_card(self, card_name: str, icard: int, ifield: int, value: Union[int, float, str]) -> None: """ Updates a Nastran card based on standard Nastran optimization names Parameters ---------- card_name : str the name of the card (e.g. GRID) icard : int the unique 1-based index identifier for the card (e.g. the GRID id) ifield : int the index on the card (e.g. X on GRID card as an integer representing the field number) value : varies the value to assign Returns ------- obj : varies the corresponding object (e.g. the GRID object) # On GRID 100, set Cp (2) to 42 >>> model.update_card('GRID', 100, 2, 42) # On GRID 100, set X (3) to 43. >>> model.update_card('GRID', 100, 3, 43.) """ #rslot_map = self.get_rslot_map(reset_type_to_slot_map=False) for key in self.card_count: assert isinstance(key, str), f'key={key!r}' if key not in self._type_to_slot_map: msg = 'add %r to self._type_to_slot_map\n%s' % (key, str(self._type_to_slot_map)) raise RuntimeError(msg) #_slot_to_type_map['nodes'] : ['GRID'] #_type_to_slot_map['GRID'] : ['nodes'] # get the storage object try: field_str = self._type_to_slot_map[card_name] # 'nodes' except KeyError: msg = 'Updating card card_name=%r is not supported\nkeys=%s' % ( card_name, list(self._type_to_slot_map.keys())) raise KeyError(msg) objs = getattr(self, field_str) # self.nodes # get the specific card try: obj = objs[icard] except KeyError: msg = 'Could not find %s ID=%r' % (card_name, icard) raise KeyError(msg) # update the card obj.update_field(ifield, value) return obj
[ "def", "update_card", "(", "self", ",", "card_name", ":", "str", ",", "icard", ":", "int", ",", "ifield", ":", "int", ",", "value", ":", "Union", "[", "int", ",", "float", ",", "str", "]", ")", "->", "None", ":", "#rslot_map = self.get_rslot_map(reset_type_to_slot_map=False)", "for", "key", "in", "self", ".", "card_count", ":", "assert", "isinstance", "(", "key", ",", "str", ")", ",", "f'key={key!r}'", "if", "key", "not", "in", "self", ".", "_type_to_slot_map", ":", "msg", "=", "'add %r to self._type_to_slot_map\\n%s'", "%", "(", "key", ",", "str", "(", "self", ".", "_type_to_slot_map", ")", ")", "raise", "RuntimeError", "(", "msg", ")", "#_slot_to_type_map['nodes'] : ['GRID']", "#_type_to_slot_map['GRID'] : ['nodes']", "# get the storage object", "try", ":", "field_str", "=", "self", ".", "_type_to_slot_map", "[", "card_name", "]", "# 'nodes'", "except", "KeyError", ":", "msg", "=", "'Updating card card_name=%r is not supported\\nkeys=%s'", "%", "(", "card_name", ",", "list", "(", "self", ".", "_type_to_slot_map", ".", "keys", "(", ")", ")", ")", "raise", "KeyError", "(", "msg", ")", "objs", "=", "getattr", "(", "self", ",", "field_str", ")", "# self.nodes", "# get the specific card", "try", ":", "obj", "=", "objs", "[", "icard", "]", "except", "KeyError", ":", "msg", "=", "'Could not find %s ID=%r'", "%", "(", "card_name", ",", "icard", ")", "raise", "KeyError", "(", "msg", ")", "# update the card", "obj", ".", "update_field", "(", "ifield", ",", "value", ")", "return", "obj" ]
https://github.com/SteveDoyle2/pyNastran/blob/eda651ac2d4883d95a34951f8a002ff94f642a1a/pyNastran/dev/bdf_vectorized2/bdf_vectorized.py#L1794-L1854
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_flaskbb/Python-2.7.9/Lib/pickletools.py
python
OpcodeInfo.__init__
(self, name, code, arg, stack_before, stack_after, proto, doc)
[]
def __init__(self, name, code, arg, stack_before, stack_after, proto, doc): assert isinstance(name, str) self.name = name assert isinstance(code, str) assert len(code) == 1 self.code = code assert arg is None or isinstance(arg, ArgumentDescriptor) self.arg = arg assert isinstance(stack_before, list) for x in stack_before: assert isinstance(x, StackObject) self.stack_before = stack_before assert isinstance(stack_after, list) for x in stack_after: assert isinstance(x, StackObject) self.stack_after = stack_after assert isinstance(proto, int) and 0 <= proto <= 2 self.proto = proto assert isinstance(doc, str) self.doc = doc
[ "def", "__init__", "(", "self", ",", "name", ",", "code", ",", "arg", ",", "stack_before", ",", "stack_after", ",", "proto", ",", "doc", ")", ":", "assert", "isinstance", "(", "name", ",", "str", ")", "self", ".", "name", "=", "name", "assert", "isinstance", "(", "code", ",", "str", ")", "assert", "len", "(", "code", ")", "==", "1", "self", ".", "code", "=", "code", "assert", "arg", "is", "None", "or", "isinstance", "(", "arg", ",", "ArgumentDescriptor", ")", "self", ".", "arg", "=", "arg", "assert", "isinstance", "(", "stack_before", ",", "list", ")", "for", "x", "in", "stack_before", ":", "assert", "isinstance", "(", "x", ",", "StackObject", ")", "self", ".", "stack_before", "=", "stack_before", "assert", "isinstance", "(", "stack_after", ",", "list", ")", "for", "x", "in", "stack_after", ":", "assert", "isinstance", "(", "x", ",", "StackObject", ")", "self", ".", "stack_after", "=", "stack_after", "assert", "isinstance", "(", "proto", ",", "int", ")", "and", "0", "<=", "proto", "<=", "2", "self", ".", "proto", "=", "proto", "assert", "isinstance", "(", "doc", ",", "str", ")", "self", ".", "doc", "=", "doc" ]
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_flaskbb/Python-2.7.9/Lib/pickletools.py#L854-L880
iopsgroup/imoocc
de810eb6d4c1697b7139305925a5b0ba21225f3f
extra_apps/xadmin/filters.py
python
BaseFilter.has_output
(self)
Returns True if some choices would be output for this filter.
Returns True if some choices would be output for this filter.
[ "Returns", "True", "if", "some", "choices", "would", "be", "output", "for", "this", "filter", "." ]
def has_output(self): """ Returns True if some choices would be output for this filter. """ raise NotImplementedError
[ "def", "has_output", "(", "self", ")", ":", "raise", "NotImplementedError" ]
https://github.com/iopsgroup/imoocc/blob/de810eb6d4c1697b7139305925a5b0ba21225f3f/extra_apps/xadmin/filters.py#L55-L59
ring04h/wyportmap
c4201e2313504e780a7f25238eba2a2d3223e739
sqlalchemy/sql/operators.py
python
Operators.__invert__
(self)
return self.operate(inv)
Implement the ``~`` operator. When used with SQL expressions, results in a NOT operation, equivalent to :func:`~.expression.not_`, that is:: ~a is equivalent to:: from sqlalchemy import not_ not_(a)
Implement the ``~`` operator.
[ "Implement", "the", "~", "operator", "." ]
def __invert__(self): """Implement the ``~`` operator. When used with SQL expressions, results in a NOT operation, equivalent to :func:`~.expression.not_`, that is:: ~a is equivalent to:: from sqlalchemy import not_ not_(a) """ return self.operate(inv)
[ "def", "__invert__", "(", "self", ")", ":", "return", "self", ".", "operate", "(", "inv", ")" ]
https://github.com/ring04h/wyportmap/blob/c4201e2313504e780a7f25238eba2a2d3223e739/sqlalchemy/sql/operators.py#L90-L105
mayank93/Twitter-Sentiment-Analysis
f095c6ca6bf69787582b5dabb140fefaf278eb37
front-end/web2py/site-packages/python-ldap-2.4.3/build/lib.linux-x86_64-2.7/ldif.py
python
LDIFWriter._needs_base64_encoding
(self,attr_type,attr_value)
return self._base64_attrs.has_key(attr_type.lower()) or \ not safe_string_re.search(attr_value) is None
returns 1 if attr_value has to be base-64 encoded because of special chars or because attr_type is in self._base64_attrs
returns 1 if attr_value has to be base-64 encoded because of special chars or because attr_type is in self._base64_attrs
[ "returns", "1", "if", "attr_value", "has", "to", "be", "base", "-", "64", "encoded", "because", "of", "special", "chars", "or", "because", "attr_type", "is", "in", "self", ".", "_base64_attrs" ]
def _needs_base64_encoding(self,attr_type,attr_value): """ returns 1 if attr_value has to be base-64 encoded because of special chars or because attr_type is in self._base64_attrs """ return self._base64_attrs.has_key(attr_type.lower()) or \ not safe_string_re.search(attr_value) is None
[ "def", "_needs_base64_encoding", "(", "self", ",", "attr_type", ",", "attr_value", ")", ":", "return", "self", ".", "_base64_attrs", ".", "has_key", "(", "attr_type", ".", "lower", "(", ")", ")", "or", "not", "safe_string_re", ".", "search", "(", "attr_value", ")", "is", "None" ]
https://github.com/mayank93/Twitter-Sentiment-Analysis/blob/f095c6ca6bf69787582b5dabb140fefaf278eb37/front-end/web2py/site-packages/python-ldap-2.4.3/build/lib.linux-x86_64-2.7/ldif.py#L122-L128
securesystemslab/zippy
ff0e84ac99442c2c55fe1d285332cfd4e185e089
zippy/lib-python/3/tarfile.py
python
TarFile.__enter__
(self)
return self
[]
def __enter__(self): self._check() return self
[ "def", "__enter__", "(", "self", ")", ":", "self", ".", "_check", "(", ")", "return", "self" ]
https://github.com/securesystemslab/zippy/blob/ff0e84ac99442c2c55fe1d285332cfd4e185e089/zippy/lib-python/3/tarfile.py#L2526-L2528
mdiazcl/fuzzbunch-debian
2b76c2249ade83a389ae3badb12a1bd09901fd2c
windows/fuzzbunch/pyreadline/modes/basemode.py
python
BaseMode.possible_completions
(self, e)
List the possible completions of the text before point.
List the possible completions of the text before point.
[ "List", "the", "possible", "completions", "of", "the", "text", "before", "point", "." ]
def possible_completions(self, e): # (M-?) '''List the possible completions of the text before point. ''' completions = self._get_completions() self._display_completions(completions)
[ "def", "possible_completions", "(", "self", ",", "e", ")", ":", "# (M-?)", "completions", "=", "self", ".", "_get_completions", "(", ")", "self", ".", "_display_completions", "(", "completions", ")" ]
https://github.com/mdiazcl/fuzzbunch-debian/blob/2b76c2249ade83a389ae3badb12a1bd09901fd2c/windows/fuzzbunch/pyreadline/modes/basemode.py#L204-L207
ifwe/digsby
f5fe00244744aa131e07f09348d10563f3d8fa99
digsby/src/gui/uberwidgets/uberbook/tabbar.py
python
TabBar.OnMotion
(self,event)
Positioning updates during drag and drop
Positioning updates during drag and drop
[ "Positioning", "updates", "during", "drag", "and", "drop" ]
def OnMotion(self,event): 'Positioning updates during drag and drop' if event.LeftIsDown() and (self.dragorigin or self.Manager.source): self.DragCalc(event.Position)
[ "def", "OnMotion", "(", "self", ",", "event", ")", ":", "if", "event", ".", "LeftIsDown", "(", ")", "and", "(", "self", ".", "dragorigin", "or", "self", ".", "Manager", ".", "source", ")", ":", "self", ".", "DragCalc", "(", "event", ".", "Position", ")" ]
https://github.com/ifwe/digsby/blob/f5fe00244744aa131e07f09348d10563f3d8fa99/digsby/src/gui/uberwidgets/uberbook/tabbar.py#L182-L186
007gzs/dingtalk-sdk
7979da2e259fdbc571728cae2425a04dbc65850a
dingtalk/client/api/taobao.py
python
TbTianMaoXinLingShou.tmall_nr_order_confirm
( self, param1, buyer_id='0' )
return self._top_request( "tmall.nr.order.confirm", { "param1": param1, "buyer_id": buyer_id } )
确认订单价格 贩卖机计算商品价格,用于透出给消费者; 文档地址:https://open-doc.dingtalk.com/docs/api.htm?apiId=37633 :param param1: 请求参数 :param buyer_id: 可用于透传的买家id,常用于外部技术体系的买家信息透传
确认订单价格 贩卖机计算商品价格,用于透出给消费者; 文档地址:https://open-doc.dingtalk.com/docs/api.htm?apiId=37633
[ "确认订单价格", "贩卖机计算商品价格,用于透出给消费者;", "文档地址:https", ":", "//", "open", "-", "doc", ".", "dingtalk", ".", "com", "/", "docs", "/", "api", ".", "htm?apiId", "=", "37633" ]
def tmall_nr_order_confirm( self, param1, buyer_id='0' ): """ 确认订单价格 贩卖机计算商品价格,用于透出给消费者; 文档地址:https://open-doc.dingtalk.com/docs/api.htm?apiId=37633 :param param1: 请求参数 :param buyer_id: 可用于透传的买家id,常用于外部技术体系的买家信息透传 """ return self._top_request( "tmall.nr.order.confirm", { "param1": param1, "buyer_id": buyer_id } )
[ "def", "tmall_nr_order_confirm", "(", "self", ",", "param1", ",", "buyer_id", "=", "'0'", ")", ":", "return", "self", ".", "_top_request", "(", "\"tmall.nr.order.confirm\"", ",", "{", "\"param1\"", ":", "param1", ",", "\"buyer_id\"", ":", "buyer_id", "}", ")" ]
https://github.com/007gzs/dingtalk-sdk/blob/7979da2e259fdbc571728cae2425a04dbc65850a/dingtalk/client/api/taobao.py#L98111-L98130
OpenEndedGroup/Field
4f7c8edfb01bb0ccc927b78d3c500f018a4ae37c
Contents/lib/python/decimal.py
python
Decimal.__rsub__
(self, other, context=None)
return other.__sub__(self, context=context)
Return other - self
Return other - self
[ "Return", "other", "-", "self" ]
def __rsub__(self, other, context=None): """Return other - self""" other = _convert_other(other) if other is NotImplemented: return other return other.__sub__(self, context=context)
[ "def", "__rsub__", "(", "self", ",", "other", ",", "context", "=", "None", ")", ":", "other", "=", "_convert_other", "(", "other", ")", "if", "other", "is", "NotImplemented", ":", "return", "other", "return", "other", ".", "__sub__", "(", "self", ",", "context", "=", "context", ")" ]
https://github.com/OpenEndedGroup/Field/blob/4f7c8edfb01bb0ccc927b78d3c500f018a4ae37c/Contents/lib/python/decimal.py#L1050-L1056
openstack/sahara
c4f4d29847d5bcca83d49ef7e9a3378458462a79
sahara/conductor/api.py
python
LocalApi.job_execution_get
(self, context, job_execution)
return self._manager.job_execution_get(context, _get_id(job_execution))
Return the JobExecution or None if it does not exist.
Return the JobExecution or None if it does not exist.
[ "Return", "the", "JobExecution", "or", "None", "if", "it", "does", "not", "exist", "." ]
def job_execution_get(self, context, job_execution): """Return the JobExecution or None if it does not exist.""" return self._manager.job_execution_get(context, _get_id(job_execution))
[ "def", "job_execution_get", "(", "self", ",", "context", ",", "job_execution", ")", ":", "return", "self", ".", "_manager", ".", "job_execution_get", "(", "context", ",", "_get_id", "(", "job_execution", ")", ")" ]
https://github.com/openstack/sahara/blob/c4f4d29847d5bcca83d49ef7e9a3378458462a79/sahara/conductor/api.py#L325-L328
yt-project/yt
dc7b24f9b266703db4c843e329c6c8644d47b824
doc/helper_scripts/parse_cb_list.py
python
write_docstring
(f, name, cls)
[]
def write_docstring(f, name, cls): if not hasattr(cls, "_type_name") or cls._type_name is None: return for clsi in inspect.getmro(cls): docstring = inspect.getdoc(clsi.__init__) if docstring is not None: break clsname = cls._type_name sig = inspect.formatargspec(*inspect.getargspec(cls.__init__)) sig = sig.replace("**kwargs", "**field_parameters") clsproxy = f"yt.visualization.plot_modifications.{cls.__name__}" # docstring = "\n".join([" %s" % line for line in docstring.split("\n")]) # print(docstring) f.write( template % dict( clsname=clsname, sig=sig, clsproxy=clsproxy, docstring="\n".join(tw.wrap(docstring)), ) )
[ "def", "write_docstring", "(", "f", ",", "name", ",", "cls", ")", ":", "if", "not", "hasattr", "(", "cls", ",", "\"_type_name\"", ")", "or", "cls", ".", "_type_name", "is", "None", ":", "return", "for", "clsi", "in", "inspect", ".", "getmro", "(", "cls", ")", ":", "docstring", "=", "inspect", ".", "getdoc", "(", "clsi", ".", "__init__", ")", "if", "docstring", "is", "not", "None", ":", "break", "clsname", "=", "cls", ".", "_type_name", "sig", "=", "inspect", ".", "formatargspec", "(", "*", "inspect", ".", "getargspec", "(", "cls", ".", "__init__", ")", ")", "sig", "=", "sig", ".", "replace", "(", "\"**kwargs\"", ",", "\"**field_parameters\"", ")", "clsproxy", "=", "f\"yt.visualization.plot_modifications.{cls.__name__}\"", "# docstring = \"\\n\".join([\" %s\" % line for line in docstring.split(\"\\n\")])", "# print(docstring)", "f", ".", "write", "(", "template", "%", "dict", "(", "clsname", "=", "clsname", ",", "sig", "=", "sig", ",", "clsproxy", "=", "clsproxy", ",", "docstring", "=", "\"\\n\"", ".", "join", "(", "tw", ".", "wrap", "(", "docstring", ")", ")", ",", ")", ")" ]
https://github.com/yt-project/yt/blob/dc7b24f9b266703db4c843e329c6c8644d47b824/doc/helper_scripts/parse_cb_list.py#L23-L44
Komodo/KomodoEdit
61edab75dce2bdb03943b387b0608ea36f548e8e
src/codeintel/play/core.py
python
Window.ClearBackground
(*args, **kwargs)
return _core.Window_ClearBackground(*args, **kwargs)
ClearBackground() Clears the window by filling it with the current background colour. Does not cause an erase background event to be generated.
ClearBackground()
[ "ClearBackground", "()" ]
def ClearBackground(*args, **kwargs): """ ClearBackground() Clears the window by filling it with the current background colour. Does not cause an erase background event to be generated. """ return _core.Window_ClearBackground(*args, **kwargs)
[ "def", "ClearBackground", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_core", ".", "Window_ClearBackground", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/Komodo/KomodoEdit/blob/61edab75dce2bdb03943b387b0608ea36f548e8e/src/codeintel/play/core.py#L6395-L6402
ztosec/hunter
4ee5cca8dc5fc5d7e631e935517bd0f493c30a37
HunterCelery/common/redis_util.py
python
RedisManage.get_redis_pool
(cls)
return RedisManage.__redis_pool
获取redis连接池 :return:
获取redis连接池 :return:
[ "获取redis连接池", ":", "return", ":" ]
def get_redis_pool(cls): """ 获取redis连接池 :return: """ redis_config = get_system_config()["redis"] redis_host = redis_config["host"] redis_port = redis_config["port"] redis_password = redis_config["password"] max_connections = redis_config["max_connections"] if not hasattr(RedisManage, "__redis_pool") or not RedisManage.__redis_pool: RedisManage.__redis_pool = redis.ConnectionPool(host=redis_host, port=redis_port, password=redis_password, decode_responses=True, max_connections=max_connections) return RedisManage.__redis_pool
[ "def", "get_redis_pool", "(", "cls", ")", ":", "redis_config", "=", "get_system_config", "(", ")", "[", "\"redis\"", "]", "redis_host", "=", "redis_config", "[", "\"host\"", "]", "redis_port", "=", "redis_config", "[", "\"port\"", "]", "redis_password", "=", "redis_config", "[", "\"password\"", "]", "max_connections", "=", "redis_config", "[", "\"max_connections\"", "]", "if", "not", "hasattr", "(", "RedisManage", ",", "\"__redis_pool\"", ")", "or", "not", "RedisManage", ".", "__redis_pool", ":", "RedisManage", ".", "__redis_pool", "=", "redis", ".", "ConnectionPool", "(", "host", "=", "redis_host", ",", "port", "=", "redis_port", ",", "password", "=", "redis_password", ",", "decode_responses", "=", "True", ",", "max_connections", "=", "max_connections", ")", "return", "RedisManage", ".", "__redis_pool" ]
https://github.com/ztosec/hunter/blob/4ee5cca8dc5fc5d7e631e935517bd0f493c30a37/HunterCelery/common/redis_util.py#L44-L57
pythonarcade/arcade
1ee3eb1900683213e8e8df93943327c2ea784564
arcade/sprite_list/sprite_list.py
python
SpriteList.extend
(self, sprites: Union[list, "SpriteList"])
Extends the current list with the given list :param list sprites: list of Sprites to add to the list
Extends the current list with the given list
[ "Extends", "the", "current", "list", "with", "the", "given", "list" ]
def extend(self, sprites: Union[list, "SpriteList"]): """ Extends the current list with the given list :param list sprites: list of Sprites to add to the list """ for sprite in sprites: self.append(sprite)
[ "def", "extend", "(", "self", ",", "sprites", ":", "Union", "[", "list", ",", "\"SpriteList\"", "]", ")", ":", "for", "sprite", "in", "sprites", ":", "self", ".", "append", "(", "sprite", ")" ]
https://github.com/pythonarcade/arcade/blob/1ee3eb1900683213e8e8df93943327c2ea784564/arcade/sprite_list/sprite_list.py#L546-L553
mozilla-services/socorro
8bff4a90e9e3320eabe7e067adbe0e89f6a39ba7
socorro/signature/cmd_signature.py
python
OutputBase.data
(self, crash_id, old_sig, result, verbose)
Outputs a data point :arg str crash_id: the crash id for the signature generated :arg str old_sig: the old signature retrieved in the processed crash :arg Result result: the signature result :arg boolean verbose: whether or not to be verbose
Outputs a data point
[ "Outputs", "a", "data", "point" ]
def data(self, crash_id, old_sig, result, verbose): """Outputs a data point :arg str crash_id: the crash id for the signature generated :arg str old_sig: the old signature retrieved in the processed crash :arg Result result: the signature result :arg boolean verbose: whether or not to be verbose """ pass
[ "def", "data", "(", "self", ",", "crash_id", ",", "old_sig", ",", "result", ",", "verbose", ")", ":", "pass" ]
https://github.com/mozilla-services/socorro/blob/8bff4a90e9e3320eabe7e067adbe0e89f6a39ba7/socorro/signature/cmd_signature.py#L58-L67
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_flaskbb/lib/python2.7/site-packages/whoosh/query/spans.py
python
SpanQuery.__eq__
(self, other)
return (other and self.__class__ is other.__class__ and self.q == other.q)
[]
def __eq__(self, other): return (other and self.__class__ is other.__class__ and self.q == other.q)
[ "def", "__eq__", "(", "self", ",", "other", ")", ":", "return", "(", "other", "and", "self", ".", "__class__", "is", "other", ".", "__class__", "and", "self", ".", "q", "==", "other", ".", "q", ")" ]
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_flaskbb/lib/python2.7/site-packages/whoosh/query/spans.py#L274-L276
vmware/vsphere-automation-sdk-python
ba7d4e0742f58a641dfed9538ecbbb1db4f3891e
samples/vmc/networks_nsxv/public_ip_crud.py
python
PublicIPsCrud.delete_public_ip
(self)
[]
def delete_public_ip(self): if self.cleanup: self.vmc_client.orgs.sddcs.Publicips.delete( org=self.org_id, sddc=self.sddc_id, id=self.ip_id) print('\n# Example: Public IP "{}" is deleted'.format(self.notes))
[ "def", "delete_public_ip", "(", "self", ")", ":", "if", "self", ".", "cleanup", ":", "self", ".", "vmc_client", ".", "orgs", ".", "sddcs", ".", "Publicips", ".", "delete", "(", "org", "=", "self", ".", "org_id", ",", "sddc", "=", "self", ".", "sddc_id", ",", "id", "=", "self", ".", "ip_id", ")", "print", "(", "'\\n# Example: Public IP \"{}\" is deleted'", ".", "format", "(", "self", ".", "notes", ")", ")" ]
https://github.com/vmware/vsphere-automation-sdk-python/blob/ba7d4e0742f58a641dfed9538ecbbb1db4f3891e/samples/vmc/networks_nsxv/public_ip_crud.py#L123-L127
nucleic/enaml
65c2a2a2d765e88f2e1103046680571894bb41ed
enaml/qt/docking/layout_handling.py
python
_plug_border_west
(area, widget, frame, guide)
return _split_root_helper(area, Qt.Horizontal, frame, False)
Plug the frame to the west border of the area.
Plug the frame to the west border of the area.
[ "Plug", "the", "frame", "to", "the", "west", "border", "of", "the", "area", "." ]
def _plug_border_west(area, widget, frame, guide): """ Plug the frame to the west border of the area. """ return _split_root_helper(area, Qt.Horizontal, frame, False)
[ "def", "_plug_border_west", "(", "area", ",", "widget", ",", "frame", ",", "guide", ")", ":", "return", "_split_root_helper", "(", "area", ",", "Qt", ".", "Horizontal", ",", "frame", ",", "False", ")" ]
https://github.com/nucleic/enaml/blob/65c2a2a2d765e88f2e1103046680571894bb41ed/enaml/qt/docking/layout_handling.py#L387-L391
Guake/guake
6dc23f34cc679a9a697ef4e93799344b56001cef
guake/prefs.py
python
PrefsCallbacks.on_window_horizontal_displacement_value_changed
(self, spin)
Changes the value of window-horizontal-displacement
Changes the value of window-horizontal-displacement
[ "Changes", "the", "value", "of", "window", "-", "horizontal", "-", "displacement" ]
def on_window_horizontal_displacement_value_changed(self, spin): """Changes the value of window-horizontal-displacement""" self.settings.general.set_int("window-horizontal-displacement", int(spin.get_value()))
[ "def", "on_window_horizontal_displacement_value_changed", "(", "self", ",", "spin", ")", ":", "self", ".", "settings", ".", "general", ".", "set_int", "(", "\"window-horizontal-displacement\"", ",", "int", "(", "spin", ".", "get_value", "(", ")", ")", ")" ]
https://github.com/Guake/guake/blob/6dc23f34cc679a9a697ef4e93799344b56001cef/guake/prefs.py#L593-L595
giantbranch/python-hacker-code
addbc8c73e7e6fb9e4fcadcec022fa1d3da4b96d
我手敲的代码(中文注释)/chapter11/volatility/plugins/malware/apihooks.py
python
Hook.__init__
(self, hook_type, hook_mode, function_name, function_address = None, hook_address = None, hook_module = None, victim_module = None)
Initalize a hook class instance. @params hook_type: one of the HOOK_TYPE_* constants @params hook_mode: one of the HOOK_MODE_* constants @params function_name: name of the function being hooked @params function_address: address of the hooked function in process or kernel memory. @params hook_address: address where the hooked function actually points. @params hook_module: the _LDR_DATA_TABLE_ENTRY of the hooking module (owner of the hook_address). note: this can be None if the module cannot be identified. @params victim_module: the _LDR_DATA_TABLE_ENTRY of the module being hooked (contains the function_address). note: this can be a string if checking IAT hooks.
Initalize a hook class instance.
[ "Initalize", "a", "hook", "class", "instance", "." ]
def __init__(self, hook_type, hook_mode, function_name, function_address = None, hook_address = None, hook_module = None, victim_module = None): """ Initalize a hook class instance. @params hook_type: one of the HOOK_TYPE_* constants @params hook_mode: one of the HOOK_MODE_* constants @params function_name: name of the function being hooked @params function_address: address of the hooked function in process or kernel memory. @params hook_address: address where the hooked function actually points. @params hook_module: the _LDR_DATA_TABLE_ENTRY of the hooking module (owner of the hook_address). note: this can be None if the module cannot be identified. @params victim_module: the _LDR_DATA_TABLE_ENTRY of the module being hooked (contains the function_address). note: this can be a string if checking IAT hooks. """ self.hook_mode = hook_mode self.hook_type = hook_type self.function_name = function_name self.function_address = function_address self.hook_address = hook_address self.hook_module = hook_module self.victim_module = victim_module # List of tuples: address, data pairs self.disassembled_hops = []
[ "def", "__init__", "(", "self", ",", "hook_type", ",", "hook_mode", ",", "function_name", ",", "function_address", "=", "None", ",", "hook_address", "=", "None", ",", "hook_module", "=", "None", ",", "victim_module", "=", "None", ")", ":", "self", ".", "hook_mode", "=", "hook_mode", "self", ".", "hook_type", "=", "hook_type", "self", ".", "function_name", "=", "function_name", "self", ".", "function_address", "=", "function_address", "self", ".", "hook_address", "=", "hook_address", "self", ".", "hook_module", "=", "hook_module", "self", ".", "victim_module", "=", "victim_module", "# List of tuples: address, data pairs", "self", ".", "disassembled_hops", "=", "[", "]" ]
https://github.com/giantbranch/python-hacker-code/blob/addbc8c73e7e6fb9e4fcadcec022fa1d3da4b96d/我手敲的代码(中文注释)/chapter11/volatility/plugins/malware/apihooks.py#L165-L199
mailpile/Mailpile
b5e4b85fd1e584951d6d13af362ab28821466eea
mailpile/util.py
python
string_to_intlist
(text)
Converts a string into an array of integers
Converts a string into an array of integers
[ "Converts", "a", "string", "into", "an", "array", "of", "integers" ]
def string_to_intlist(text): """Converts a string into an array of integers""" try: return [ord(c) for c in text.encode('utf-8')] except (UnicodeEncodeError, UnicodeDecodeError): return [ord(c) for c in text]
[ "def", "string_to_intlist", "(", "text", ")", ":", "try", ":", "return", "[", "ord", "(", "c", ")", "for", "c", "in", "text", ".", "encode", "(", "'utf-8'", ")", "]", "except", "(", "UnicodeEncodeError", ",", "UnicodeDecodeError", ")", ":", "return", "[", "ord", "(", "c", ")", "for", "c", "in", "text", "]" ]
https://github.com/mailpile/Mailpile/blob/b5e4b85fd1e584951d6d13af362ab28821466eea/mailpile/util.py#L457-L462
kanzure/nanoengineer
874e4c9f8a9190f093625b267f9767e19f82e6c4
cad/src/exprs/world.py
python
World._append_node
(self, index, node)
return
not sure if this should be private... API revised 070205, ought to rename it more (and #doc it)
not sure if this should be private... API revised 070205, ought to rename it more (and #doc it)
[ "not", "sure", "if", "this", "should", "be", "private", "...", "API", "revised", "070205", "ought", "to", "rename", "it", "more", "(", "and", "#doc", "it", ")" ]
def _append_node(self, index, node):#070201 new feature ###e SHOULD RENAME [070205] "not sure if this should be private... API revised 070205, ought to rename it more (and #doc it)" ## self._nodeset = dict(self._nodeset) ## ###KLUGE: copy it first, to make sure it gets change-tracked. Inefficient when long! ###BUG in the above: # doesn't work, since the change to it is not tracked, since the old and new values compare equal! (guess) #k note that LvalForState may also not keep a deep enough copy of the old value in doing the compare, # to not be fooled by the direct modification of the dict (in the sense of that mod escaping its notice, even later)! # (i'm not sure -- needs review, e.g. about whether bugs of this kind will go undetected and be too hard to catch) ## self._nodeset[index] = node newset = dict(self._nodeset) newset[index] = node self._nodeset = newset # this ought to compare different and cause changetracking (assuming the index was in fact new) ###e OPTIM IDEA: can we modify it, then set it to itself? No, because LvalForState will compare saved & new value -- # the same mutable object! We need to fix that, but a workaround is to set it to None and then set it to itself again. # That ought to work fine. ####TRYIT but then fix LvalForState so we can tell it we modified its mutable contents. [070228] return
[ "def", "_append_node", "(", "self", ",", "index", ",", "node", ")", ":", "#070201 new feature ###e SHOULD RENAME [070205]", "## self._nodeset = dict(self._nodeset)", "## ###KLUGE: copy it first, to make sure it gets change-tracked. Inefficient when long!", "###BUG in the above:", "# doesn't work, since the change to it is not tracked, since the old and new values compare equal! (guess)", "#k note that LvalForState may also not keep a deep enough copy of the old value in doing the compare,", "# to not be fooled by the direct modification of the dict (in the sense of that mod escaping its notice, even later)!", "# (i'm not sure -- needs review, e.g. about whether bugs of this kind will go undetected and be too hard to catch)", "## self._nodeset[index] = node", "newset", "=", "dict", "(", "self", ".", "_nodeset", ")", "newset", "[", "index", "]", "=", "node", "self", ".", "_nodeset", "=", "newset", "# this ought to compare different and cause changetracking (assuming the index was in fact new)", "###e OPTIM IDEA: can we modify it, then set it to itself? No, because LvalForState will compare saved & new value --", "# the same mutable object! We need to fix that, but a workaround is to set it to None and then set it to itself again.", "# That ought to work fine. ####TRYIT but then fix LvalForState so we can tell it we modified its mutable contents. [070228]", "return" ]
https://github.com/kanzure/nanoengineer/blob/874e4c9f8a9190f093625b267f9767e19f82e6c4/cad/src/exprs/world.py#L164-L180
sabri-zaki/EasY_HaCk
2a39ac384dd0d6fc51c0dd22e8d38cece683fdb9
.modules/.sqlmap/lib/request/connect.py
python
Connect.getPage
(**kwargs)
return page, responseHeaders, code
This method connects to the target URL or proxy and returns the target URL page content
This method connects to the target URL or proxy and returns the target URL page content
[ "This", "method", "connects", "to", "the", "target", "URL", "or", "proxy", "and", "returns", "the", "target", "URL", "page", "content" ]
def getPage(**kwargs): """ This method connects to the target URL or proxy and returns the target URL page content """ start = time.time() if isinstance(conf.delay, (int, float)) and conf.delay > 0: time.sleep(conf.delay) if conf.offline: return None, None, None elif conf.dummy or conf.murphyRate and randomInt() % conf.murphyRate == 0: if conf.murphyRate: time.sleep(randomInt() % (MAX_MURPHY_SLEEP_TIME + 1)) return getUnicode(randomStr(int(randomInt()), alphabet=[chr(_) for _ in xrange(256)]), {}, int(randomInt())), None, None if not conf.murphyRate else randomInt(3) threadData = getCurrentThreadData() with kb.locks.request: kb.requestCounter += 1 threadData.lastRequestUID = kb.requestCounter url = kwargs.get("url", None) or conf.url get = kwargs.get("get", None) post = kwargs.get("post", None) method = kwargs.get("method", None) cookie = kwargs.get("cookie", None) ua = kwargs.get("ua", None) or conf.agent referer = kwargs.get("referer", None) or conf.referer host = kwargs.get("host", None) or conf.host direct_ = kwargs.get("direct", False) multipart = kwargs.get("multipart", None) silent = kwargs.get("silent", False) raise404 = kwargs.get("raise404", True) timeout = kwargs.get("timeout", None) or conf.timeout auxHeaders = kwargs.get("auxHeaders", None) response = kwargs.get("response", False) ignoreTimeout = kwargs.get("ignoreTimeout", False) or kb.ignoreTimeout or conf.ignoreTimeouts refreshing = kwargs.get("refreshing", False) retrying = kwargs.get("retrying", False) crawling = kwargs.get("crawling", False) checking = kwargs.get("checking", False) skipRead = kwargs.get("skipRead", False) if multipart: post = multipart websocket_ = url.lower().startswith("ws") if not urlparse.urlsplit(url).netloc: url = urlparse.urljoin(conf.url, url) # flag to know if we are dealing with the same target host target = checkSameHost(url, conf.url) if not retrying: # Reset the number of connection retries threadData.retriesCount = 0 # fix for known issue when urllib2 just skips the other part of provided # url splitted with space char while urlencoding it in the later phase url = url.replace(" ", "%20") if "://" not in url: url = "http://%s" % url conn = None page = None code = None status = None _ = urlparse.urlsplit(url) requestMsg = u"HTTP request [#%d]:\r\n%s " % (threadData.lastRequestUID, method or (HTTPMETHOD.POST if post is not None else HTTPMETHOD.GET)) requestMsg += getUnicode(("%s%s" % (_.path or "/", ("?%s" % _.query) if _.query else "")) if not any((refreshing, crawling, checking)) else url) responseMsg = u"HTTP response " requestHeaders = u"" responseHeaders = None logHeaders = u"" skipLogTraffic = False raise404 = raise404 and not kb.ignoreNotFound # support for non-latin (e.g. cyrillic) URLs as urllib/urllib2 doesn't # support those by default url = asciifyUrl(url) try: socket.setdefaulttimeout(timeout) if direct_: if '?' in url: url, params = url.split('?', 1) params = urlencode(params) url = "%s?%s" % (url, params) elif any((refreshing, crawling, checking)): pass elif target: if conf.forceSSL and urlparse.urlparse(url).scheme != "https": url = re.sub(r"(?i)\Ahttp:", "https:", url) url = re.sub(r"(?i):80/", ":443/", url) if PLACE.GET in conf.parameters and not get: get = conf.parameters[PLACE.GET] if not conf.skipUrlEncode: get = urlencode(get, limit=True) if get: if '?' in url: url = "%s%s%s" % (url, DEFAULT_GET_POST_DELIMITER, get) requestMsg += "%s%s" % (DEFAULT_GET_POST_DELIMITER, get) else: url = "%s?%s" % (url, get) requestMsg += "?%s" % get if PLACE.POST in conf.parameters and not post and method != HTTPMETHOD.GET: post = conf.parameters[PLACE.POST] elif get: url = "%s?%s" % (url, get) requestMsg += "?%s" % get requestMsg += " %s" % httplib.HTTPConnection._http_vsn_str # Prepare HTTP headers headers = forgeHeaders({HTTP_HEADER.COOKIE: cookie, HTTP_HEADER.USER_AGENT: ua, HTTP_HEADER.REFERER: referer, HTTP_HEADER.HOST: host}, base=None if target else {}) if HTTP_HEADER.COOKIE in headers: cookie = headers[HTTP_HEADER.COOKIE] if kb.authHeader: headers[HTTP_HEADER.AUTHORIZATION] = kb.authHeader if kb.proxyAuthHeader: headers[HTTP_HEADER.PROXY_AUTHORIZATION] = kb.proxyAuthHeader if not getHeader(headers, HTTP_HEADER.ACCEPT): headers[HTTP_HEADER.ACCEPT] = HTTP_ACCEPT_HEADER_VALUE if not getHeader(headers, HTTP_HEADER.HOST) or not target: headers[HTTP_HEADER.HOST] = getHostHeader(url) if not getHeader(headers, HTTP_HEADER.ACCEPT_ENCODING): headers[HTTP_HEADER.ACCEPT_ENCODING] = HTTP_ACCEPT_ENCODING_HEADER_VALUE if kb.pageCompress else "identity" if post is not None and not multipart and not getHeader(headers, HTTP_HEADER.CONTENT_TYPE): headers[HTTP_HEADER.CONTENT_TYPE] = POST_HINT_CONTENT_TYPES.get(kb.postHint, DEFAULT_CONTENT_TYPE) if headers.get(HTTP_HEADER.CONTENT_TYPE) == POST_HINT_CONTENT_TYPES[POST_HINT.MULTIPART]: warnMsg = "missing 'boundary parameter' in '%s' header. " % HTTP_HEADER.CONTENT_TYPE warnMsg += "Will try to reconstruct" singleTimeWarnMessage(warnMsg) boundary = findMultipartPostBoundary(conf.data) if boundary: headers[HTTP_HEADER.CONTENT_TYPE] = "%s; boundary=%s" % (headers[HTTP_HEADER.CONTENT_TYPE], boundary) if conf.keepAlive: headers[HTTP_HEADER.CONNECTION] = "keep-alive" # Reset header values to original in case of provided request file if target and conf.requestFile: headers = forgeHeaders({HTTP_HEADER.COOKIE: cookie}) if auxHeaders: headers = forgeHeaders(auxHeaders, headers) for key, value in headers.items(): del headers[key] value = unicodeencode(value, kb.pageEncoding) for char in (r"\r", r"\n"): value = re.sub(r"(%s)([^ \t])" % char, r"\g<1>\t\g<2>", value) headers[unicodeencode(key, kb.pageEncoding)] = value.strip("\r\n") url = unicodeencode(url) post = unicodeencode(post) if websocket_: ws = websocket.WebSocket() ws.settimeout(timeout) ws.connect(url, header=("%s: %s" % _ for _ in headers.items() if _[0] not in ("Host",)), cookie=cookie) # WebSocket will add Host field of headers automatically ws.send(urldecode(post or "")) page = ws.recv() ws.close() code = ws.status status = httplib.responses[code] class _(dict): pass responseHeaders = _(ws.getheaders()) responseHeaders.headers = ["%s: %s\r\n" % (_[0].capitalize(), _[1]) for _ in responseHeaders.items()] requestHeaders += "\r\n".join(["%s: %s" % (getUnicode(key.capitalize() if isinstance(key, basestring) else key), getUnicode(value)) for (key, value) in responseHeaders.items()]) requestMsg += "\r\n%s" % requestHeaders if post is not None: requestMsg += "\r\n\r\n%s" % getUnicode(post) requestMsg += "\r\n" threadData.lastRequestMsg = requestMsg logger.log(CUSTOM_LOGGING.TRAFFIC_OUT, requestMsg) else: if method and method not in (HTTPMETHOD.GET, HTTPMETHOD.POST): method = unicodeencode(method) req = MethodRequest(url, post, headers) req.set_method(method) elif url is not None: req = urllib2.Request(url, post, headers) else: return None, None, None requestHeaders += "\r\n".join(["%s: %s" % (getUnicode(key.capitalize() if isinstance(key, basestring) else key), getUnicode(value)) for (key, value) in req.header_items()]) if not getRequestHeader(req, HTTP_HEADER.COOKIE) and conf.cj: conf.cj._policy._now = conf.cj._now = int(time.time()) cookies = conf.cj._cookies_for_request(req) requestHeaders += "\r\n%s" % ("Cookie: %s" % ";".join("%s=%s" % (getUnicode(cookie.name), getUnicode(cookie.value)) for cookie in cookies)) if post is not None: if not getRequestHeader(req, HTTP_HEADER.CONTENT_LENGTH): requestHeaders += "\r\n%s: %d" % (string.capwords(HTTP_HEADER.CONTENT_LENGTH), len(post)) if not getRequestHeader(req, HTTP_HEADER.CONNECTION): requestHeaders += "\r\n%s: %s" % (HTTP_HEADER.CONNECTION, "close" if not conf.keepAlive else "keep-alive") requestMsg += "\r\n%s" % requestHeaders if post is not None: requestMsg += "\r\n\r\n%s" % getUnicode(post) requestMsg += "\r\n" if not multipart: threadData.lastRequestMsg = requestMsg logger.log(CUSTOM_LOGGING.TRAFFIC_OUT, requestMsg) if conf.cj: for cookie in conf.cj: if cookie.value is None: cookie.value = "" else: for char in (r"\r", r"\n"): cookie.value = re.sub(r"(%s)([^ \t])" % char, r"\g<1>\t\g<2>", cookie.value) conn = urllib2.urlopen(req) if not kb.authHeader and getRequestHeader(req, HTTP_HEADER.AUTHORIZATION) and (conf.authType or "").lower() == AUTH_TYPE.BASIC.lower(): kb.authHeader = getRequestHeader(req, HTTP_HEADER.AUTHORIZATION) if not kb.proxyAuthHeader and getRequestHeader(req, HTTP_HEADER.PROXY_AUTHORIZATION): kb.proxyAuthHeader = getRequestHeader(req, HTTP_HEADER.PROXY_AUTHORIZATION) # Return response object if response: return conn, None, None # Get HTTP response if hasattr(conn, "redurl"): page = (threadData.lastRedirectMsg[1] if kb.redirectChoice == REDIRECTION.NO else Connect._connReadProxy(conn)) if not skipRead else None skipLogTraffic = kb.redirectChoice == REDIRECTION.NO code = conn.redcode else: page = Connect._connReadProxy(conn) if not skipRead else None if conn: code = (code or conn.code) if conn.code == kb.originalCode else conn.code # do not override redirection code (for comparison purposes) responseHeaders = conn.info() responseHeaders[URI_HTTP_HEADER] = conn.geturl() kb.serverHeader = responseHeaders.get(HTTP_HEADER.SERVER, kb.serverHeader) else: code = None responseHeaders = {} page = decodePage(page, responseHeaders.get(HTTP_HEADER.CONTENT_ENCODING), responseHeaders.get(HTTP_HEADER.CONTENT_TYPE)) status = getUnicode(conn.msg) if conn and getattr(conn, "msg", None) else None kb.connErrorCounter = 0 if not refreshing: refresh = responseHeaders.get(HTTP_HEADER.REFRESH, "").split("url=")[-1].strip() if extractRegexResult(META_REFRESH_REGEX, page): refresh = extractRegexResult(META_REFRESH_REGEX, page) debugMsg = "got HTML meta refresh header" logger.debug(debugMsg) if refresh: if kb.alwaysRefresh is None: msg = "sqlmap got a refresh request " msg += "(redirect like response common to login pages). " msg += "Do you want to apply the refresh " msg += "from now on (or stay on the original page)? [Y/n]" kb.alwaysRefresh = readInput(msg, default='Y', boolean=True) if kb.alwaysRefresh: if re.search(r"\Ahttps?://", refresh, re.I): url = refresh else: url = urlparse.urljoin(url, refresh) threadData.lastRedirectMsg = (threadData.lastRequestUID, page) kwargs["refreshing"] = True kwargs["url"] = url kwargs["get"] = None kwargs["post"] = None try: return Connect._getPageProxy(**kwargs) except SqlmapSyntaxException: pass # Explicit closing of connection object if conn and not conf.keepAlive: try: if hasattr(conn.fp, '_sock'): conn.fp._sock.close() conn.close() except Exception, ex: warnMsg = "problem occurred during connection closing ('%s')" % getSafeExString(ex) logger.warn(warnMsg) except SqlmapConnectionException, ex: if conf.proxyList and not kb.threadException: warnMsg = "unable to connect to the target URL ('%s')" % ex logger.critical(warnMsg) threadData.retriesCount = conf.retries return Connect._retryProxy(**kwargs) else: raise except urllib2.HTTPError, ex: page = None responseHeaders = None if checking: return None, None, None try: page = ex.read() if not skipRead else None responseHeaders = ex.info() responseHeaders[URI_HTTP_HEADER] = ex.geturl() page = decodePage(page, responseHeaders.get(HTTP_HEADER.CONTENT_ENCODING), responseHeaders.get(HTTP_HEADER.CONTENT_TYPE)) except socket.timeout: warnMsg = "connection timed out while trying " warnMsg += "to get error page information (%d)" % ex.code logger.warn(warnMsg) return None, None, None except KeyboardInterrupt: raise except: pass finally: page = page if isinstance(page, unicode) else getUnicode(page) code = ex.code status = getSafeExString(ex) kb.originalCode = kb.originalCode or code threadData.lastHTTPError = (threadData.lastRequestUID, code, status) kb.httpErrorCodes[code] = kb.httpErrorCodes.get(code, 0) + 1 responseMsg += "[#%d] (%s %s):\r\n" % (threadData.lastRequestUID, code, status) if responseHeaders: logHeaders = "\r\n".join(["%s: %s" % (getUnicode(key.capitalize() if isinstance(key, basestring) else key), getUnicode(value)) for (key, value) in responseHeaders.items()]) logHTTPTraffic(requestMsg, "%s%s\r\n\r\n%s" % (responseMsg, logHeaders, (page or "")[:MAX_CONNECTION_CHUNK_SIZE]), start, time.time()) skipLogTraffic = True if conf.verbose <= 5: responseMsg += getUnicode(logHeaders) elif conf.verbose > 5: responseMsg += "%s\r\n\r\n%s" % (logHeaders, (page or "")[:MAX_CONNECTION_CHUNK_SIZE]) if not multipart: logger.log(CUSTOM_LOGGING.TRAFFIC_IN, responseMsg) if ex.code != conf.ignoreCode: if ex.code == httplib.UNAUTHORIZED: errMsg = "not authorized, try to provide right HTTP " errMsg += "authentication type and valid credentials (%d)" % code raise SqlmapConnectionException(errMsg) elif ex.code == httplib.NOT_FOUND: if raise404: errMsg = "page not found (%d)" % code raise SqlmapConnectionException(errMsg) else: debugMsg = "page not found (%d)" % code singleTimeLogMessage(debugMsg, logging.DEBUG) elif ex.code == httplib.GATEWAY_TIMEOUT: if ignoreTimeout: return None if not conf.ignoreTimeouts else "", None, None else: warnMsg = "unable to connect to the target URL (%d - %s)" % (ex.code, httplib.responses[ex.code]) if threadData.retriesCount < conf.retries and not kb.threadException: warnMsg += ". sqlmap is going to retry the request" logger.critical(warnMsg) return Connect._retryProxy(**kwargs) elif kb.testMode: logger.critical(warnMsg) return None, None, None else: raise SqlmapConnectionException(warnMsg) else: debugMsg = "got HTTP error code: %d (%s)" % (code, status) logger.debug(debugMsg) except (urllib2.URLError, socket.error, socket.timeout, httplib.HTTPException, struct.error, binascii.Error, ProxyError, SqlmapCompressionException, WebSocketException, TypeError, ValueError): tbMsg = traceback.format_exc() if checking: return None, None, None elif "no host given" in tbMsg: warnMsg = "invalid URL address used (%s)" % repr(url) raise SqlmapSyntaxException(warnMsg) elif "forcibly closed" in tbMsg or "Connection is already closed" in tbMsg: warnMsg = "connection was forcibly closed by the target URL" elif "timed out" in tbMsg: if kb.testMode and kb.testType not in (None, PAYLOAD.TECHNIQUE.TIME, PAYLOAD.TECHNIQUE.STACKED): singleTimeWarnMessage("there is a possibility that the target (or WAF/IPS) is dropping 'suspicious' requests") kb.droppingRequests = True warnMsg = "connection timed out to the target URL" elif "Connection reset" in tbMsg: if not conf.disablePrecon: singleTimeWarnMessage("turning off pre-connect mechanism because of connection reset(s)") conf.disablePrecon = True if kb.testMode: singleTimeWarnMessage("there is a possibility that the target (or WAF/IPS) is resetting 'suspicious' requests") kb.droppingRequests = True warnMsg = "connection reset to the target URL" elif "URLError" in tbMsg or "error" in tbMsg: warnMsg = "unable to connect to the target URL" match = re.search(r"Errno \d+\] ([^>]+)", tbMsg) if match: warnMsg += " ('%s')" % match.group(1).strip() elif "NTLM" in tbMsg: warnMsg = "there has been a problem with NTLM authentication" elif "Invalid header name" in tbMsg: # (e.g. PostgreSQL ::Text payload) return None, None, None elif "BadStatusLine" in tbMsg: warnMsg = "connection dropped or unknown HTTP " warnMsg += "status code received" if not conf.agent and not conf.randomAgent: warnMsg += ". Try to force the HTTP User-Agent " warnMsg += "header with option '--user-agent' or switch '--random-agent'" elif "IncompleteRead" in tbMsg: warnMsg = "there was an incomplete read error while retrieving data " warnMsg += "from the target URL" elif "Handshake status" in tbMsg: status = re.search(r"Handshake status ([\d]{3})", tbMsg) errMsg = "websocket handshake status %s" % status.group(1) if status else "unknown" raise SqlmapConnectionException(errMsg) elif "SqlmapCompressionException" in tbMsg: warnMsg = "problems with response (de)compression" retrying = True else: warnMsg = "unable to connect to the target URL" if "BadStatusLine" not in tbMsg and any((conf.proxy, conf.tor)): warnMsg += " or proxy" if silent: return None, None, None with kb.locks.connError: kb.connErrorCounter += 1 if kb.connErrorCounter >= MAX_CONSECUTIVE_CONNECTION_ERRORS and kb.connErrorChoice is None: message = "there seems to be a continuous problem with connection to the target. " message += "Are you sure that you want to continue " message += "with further target testing? [y/N] " kb.connErrorChoice = readInput(message, default='N', boolean=True) if kb.connErrorChoice is False: raise SqlmapConnectionException(warnMsg) if "forcibly closed" in tbMsg: logger.critical(warnMsg) return None, None, None elif ignoreTimeout and any(_ in tbMsg for _ in ("timed out", "IncompleteRead")): return None if not conf.ignoreTimeouts else "", None, None elif threadData.retriesCount < conf.retries and not kb.threadException: warnMsg += ". sqlmap is going to retry the request" if not retrying: warnMsg += "(s)" logger.critical(warnMsg) else: logger.debug(warnMsg) return Connect._retryProxy(**kwargs) elif kb.testMode or kb.multiThreadMode: logger.critical(warnMsg) return None, None, None else: raise SqlmapConnectionException(warnMsg) finally: if isinstance(page, basestring) and not isinstance(page, unicode): if HTTP_HEADER.CONTENT_TYPE in (responseHeaders or {}) and not re.search(TEXT_CONTENT_TYPE_REGEX, responseHeaders[HTTP_HEADER.CONTENT_TYPE]): page = unicode(page, errors="ignore") else: page = getUnicode(page) socket.setdefaulttimeout(conf.timeout) processResponse(page, responseHeaders, status) if conn and getattr(conn, "redurl", None): _ = urlparse.urlsplit(conn.redurl) _ = ("%s%s" % (_.path or "/", ("?%s" % _.query) if _.query else "")) requestMsg = re.sub(r"(\n[A-Z]+ ).+?( HTTP/\d)", r"\g<1>%s\g<2>" % getUnicode(_).replace("\\", "\\\\"), requestMsg, 1) if kb.resendPostOnRedirect is False: requestMsg = re.sub(r"(\[#\d+\]:\n)POST ", r"\g<1>GET ", requestMsg) requestMsg = re.sub(r"(?i)Content-length: \d+\n", "", requestMsg) requestMsg = re.sub(r"(?s)\n\n.+", "\n", requestMsg) responseMsg += "[#%d] (%d %s):\r\n" % (threadData.lastRequestUID, conn.code, status) else: responseMsg += "[#%d] (%s %s):\r\n" % (threadData.lastRequestUID, code, status) if responseHeaders: logHeaders = "\r\n".join(["%s: %s" % (getUnicode(key.capitalize() if isinstance(key, basestring) else key), getUnicode(value)) for (key, value) in responseHeaders.items()]) if not skipLogTraffic: logHTTPTraffic(requestMsg, "%s%s\r\n\r\n%s" % (responseMsg, logHeaders, (page or "")[:MAX_CONNECTION_CHUNK_SIZE]), start, time.time()) if conf.verbose <= 5: responseMsg += getUnicode(logHeaders) elif conf.verbose > 5: responseMsg += "%s\r\n\r\n%s" % (logHeaders, (page or "")[:MAX_CONNECTION_CHUNK_SIZE]) if not multipart: logger.log(CUSTOM_LOGGING.TRAFFIC_IN, responseMsg) return page, responseHeaders, code
[ "def", "getPage", "(", "*", "*", "kwargs", ")", ":", "start", "=", "time", ".", "time", "(", ")", "if", "isinstance", "(", "conf", ".", "delay", ",", "(", "int", ",", "float", ")", ")", "and", "conf", ".", "delay", ">", "0", ":", "time", ".", "sleep", "(", "conf", ".", "delay", ")", "if", "conf", ".", "offline", ":", "return", "None", ",", "None", ",", "None", "elif", "conf", ".", "dummy", "or", "conf", ".", "murphyRate", "and", "randomInt", "(", ")", "%", "conf", ".", "murphyRate", "==", "0", ":", "if", "conf", ".", "murphyRate", ":", "time", ".", "sleep", "(", "randomInt", "(", ")", "%", "(", "MAX_MURPHY_SLEEP_TIME", "+", "1", ")", ")", "return", "getUnicode", "(", "randomStr", "(", "int", "(", "randomInt", "(", ")", ")", ",", "alphabet", "=", "[", "chr", "(", "_", ")", "for", "_", "in", "xrange", "(", "256", ")", "]", ")", ",", "{", "}", ",", "int", "(", "randomInt", "(", ")", ")", ")", ",", "None", ",", "None", "if", "not", "conf", ".", "murphyRate", "else", "randomInt", "(", "3", ")", "threadData", "=", "getCurrentThreadData", "(", ")", "with", "kb", ".", "locks", ".", "request", ":", "kb", ".", "requestCounter", "+=", "1", "threadData", ".", "lastRequestUID", "=", "kb", ".", "requestCounter", "url", "=", "kwargs", ".", "get", "(", "\"url\"", ",", "None", ")", "or", "conf", ".", "url", "get", "=", "kwargs", ".", "get", "(", "\"get\"", ",", "None", ")", "post", "=", "kwargs", ".", "get", "(", "\"post\"", ",", "None", ")", "method", "=", "kwargs", ".", "get", "(", "\"method\"", ",", "None", ")", "cookie", "=", "kwargs", ".", "get", "(", "\"cookie\"", ",", "None", ")", "ua", "=", "kwargs", ".", "get", "(", "\"ua\"", ",", "None", ")", "or", "conf", ".", "agent", "referer", "=", "kwargs", ".", "get", "(", "\"referer\"", ",", "None", ")", "or", "conf", ".", "referer", "host", "=", "kwargs", ".", "get", "(", "\"host\"", ",", "None", ")", "or", "conf", ".", "host", "direct_", "=", "kwargs", ".", "get", "(", "\"direct\"", ",", "False", ")", "multipart", "=", "kwargs", ".", "get", "(", "\"multipart\"", ",", "None", ")", "silent", "=", "kwargs", ".", "get", "(", "\"silent\"", ",", "False", ")", "raise404", "=", "kwargs", ".", "get", "(", "\"raise404\"", ",", "True", ")", "timeout", "=", "kwargs", ".", "get", "(", "\"timeout\"", ",", "None", ")", "or", "conf", ".", "timeout", "auxHeaders", "=", "kwargs", ".", "get", "(", "\"auxHeaders\"", ",", "None", ")", "response", "=", "kwargs", ".", "get", "(", "\"response\"", ",", "False", ")", "ignoreTimeout", "=", "kwargs", ".", "get", "(", "\"ignoreTimeout\"", ",", "False", ")", "or", "kb", ".", "ignoreTimeout", "or", "conf", ".", "ignoreTimeouts", "refreshing", "=", "kwargs", ".", "get", "(", "\"refreshing\"", ",", "False", ")", "retrying", "=", "kwargs", ".", "get", "(", "\"retrying\"", ",", "False", ")", "crawling", "=", "kwargs", ".", "get", "(", "\"crawling\"", ",", "False", ")", "checking", "=", "kwargs", ".", "get", "(", "\"checking\"", ",", "False", ")", "skipRead", "=", "kwargs", ".", "get", "(", "\"skipRead\"", ",", "False", ")", "if", "multipart", ":", "post", "=", "multipart", "websocket_", "=", "url", ".", "lower", "(", ")", ".", "startswith", "(", "\"ws\"", ")", "if", "not", "urlparse", ".", "urlsplit", "(", "url", ")", ".", "netloc", ":", "url", "=", "urlparse", ".", "urljoin", "(", "conf", ".", "url", ",", "url", ")", "# flag to know if we are dealing with the same target host", "target", "=", "checkSameHost", "(", "url", ",", "conf", ".", "url", ")", "if", "not", "retrying", ":", "# Reset the number of connection retries", "threadData", ".", "retriesCount", "=", "0", "# fix for known issue when urllib2 just skips the other part of provided", "# url splitted with space char while urlencoding it in the later phase", "url", "=", "url", ".", "replace", "(", "\" \"", ",", "\"%20\"", ")", "if", "\"://\"", "not", "in", "url", ":", "url", "=", "\"http://%s\"", "%", "url", "conn", "=", "None", "page", "=", "None", "code", "=", "None", "status", "=", "None", "_", "=", "urlparse", ".", "urlsplit", "(", "url", ")", "requestMsg", "=", "u\"HTTP request [#%d]:\\r\\n%s \"", "%", "(", "threadData", ".", "lastRequestUID", ",", "method", "or", "(", "HTTPMETHOD", ".", "POST", "if", "post", "is", "not", "None", "else", "HTTPMETHOD", ".", "GET", ")", ")", "requestMsg", "+=", "getUnicode", "(", "(", "\"%s%s\"", "%", "(", "_", ".", "path", "or", "\"/\"", ",", "(", "\"?%s\"", "%", "_", ".", "query", ")", "if", "_", ".", "query", "else", "\"\"", ")", ")", "if", "not", "any", "(", "(", "refreshing", ",", "crawling", ",", "checking", ")", ")", "else", "url", ")", "responseMsg", "=", "u\"HTTP response \"", "requestHeaders", "=", "u\"\"", "responseHeaders", "=", "None", "logHeaders", "=", "u\"\"", "skipLogTraffic", "=", "False", "raise404", "=", "raise404", "and", "not", "kb", ".", "ignoreNotFound", "# support for non-latin (e.g. cyrillic) URLs as urllib/urllib2 doesn't", "# support those by default", "url", "=", "asciifyUrl", "(", "url", ")", "try", ":", "socket", ".", "setdefaulttimeout", "(", "timeout", ")", "if", "direct_", ":", "if", "'?'", "in", "url", ":", "url", ",", "params", "=", "url", ".", "split", "(", "'?'", ",", "1", ")", "params", "=", "urlencode", "(", "params", ")", "url", "=", "\"%s?%s\"", "%", "(", "url", ",", "params", ")", "elif", "any", "(", "(", "refreshing", ",", "crawling", ",", "checking", ")", ")", ":", "pass", "elif", "target", ":", "if", "conf", ".", "forceSSL", "and", "urlparse", ".", "urlparse", "(", "url", ")", ".", "scheme", "!=", "\"https\"", ":", "url", "=", "re", ".", "sub", "(", "r\"(?i)\\Ahttp:\"", ",", "\"https:\"", ",", "url", ")", "url", "=", "re", ".", "sub", "(", "r\"(?i):80/\"", ",", "\":443/\"", ",", "url", ")", "if", "PLACE", ".", "GET", "in", "conf", ".", "parameters", "and", "not", "get", ":", "get", "=", "conf", ".", "parameters", "[", "PLACE", ".", "GET", "]", "if", "not", "conf", ".", "skipUrlEncode", ":", "get", "=", "urlencode", "(", "get", ",", "limit", "=", "True", ")", "if", "get", ":", "if", "'?'", "in", "url", ":", "url", "=", "\"%s%s%s\"", "%", "(", "url", ",", "DEFAULT_GET_POST_DELIMITER", ",", "get", ")", "requestMsg", "+=", "\"%s%s\"", "%", "(", "DEFAULT_GET_POST_DELIMITER", ",", "get", ")", "else", ":", "url", "=", "\"%s?%s\"", "%", "(", "url", ",", "get", ")", "requestMsg", "+=", "\"?%s\"", "%", "get", "if", "PLACE", ".", "POST", "in", "conf", ".", "parameters", "and", "not", "post", "and", "method", "!=", "HTTPMETHOD", ".", "GET", ":", "post", "=", "conf", ".", "parameters", "[", "PLACE", ".", "POST", "]", "elif", "get", ":", "url", "=", "\"%s?%s\"", "%", "(", "url", ",", "get", ")", "requestMsg", "+=", "\"?%s\"", "%", "get", "requestMsg", "+=", "\" %s\"", "%", "httplib", ".", "HTTPConnection", ".", "_http_vsn_str", "# Prepare HTTP headers", "headers", "=", "forgeHeaders", "(", "{", "HTTP_HEADER", ".", "COOKIE", ":", "cookie", ",", "HTTP_HEADER", ".", "USER_AGENT", ":", "ua", ",", "HTTP_HEADER", ".", "REFERER", ":", "referer", ",", "HTTP_HEADER", ".", "HOST", ":", "host", "}", ",", "base", "=", "None", "if", "target", "else", "{", "}", ")", "if", "HTTP_HEADER", ".", "COOKIE", "in", "headers", ":", "cookie", "=", "headers", "[", "HTTP_HEADER", ".", "COOKIE", "]", "if", "kb", ".", "authHeader", ":", "headers", "[", "HTTP_HEADER", ".", "AUTHORIZATION", "]", "=", "kb", ".", "authHeader", "if", "kb", ".", "proxyAuthHeader", ":", "headers", "[", "HTTP_HEADER", ".", "PROXY_AUTHORIZATION", "]", "=", "kb", ".", "proxyAuthHeader", "if", "not", "getHeader", "(", "headers", ",", "HTTP_HEADER", ".", "ACCEPT", ")", ":", "headers", "[", "HTTP_HEADER", ".", "ACCEPT", "]", "=", "HTTP_ACCEPT_HEADER_VALUE", "if", "not", "getHeader", "(", "headers", ",", "HTTP_HEADER", ".", "HOST", ")", "or", "not", "target", ":", "headers", "[", "HTTP_HEADER", ".", "HOST", "]", "=", "getHostHeader", "(", "url", ")", "if", "not", "getHeader", "(", "headers", ",", "HTTP_HEADER", ".", "ACCEPT_ENCODING", ")", ":", "headers", "[", "HTTP_HEADER", ".", "ACCEPT_ENCODING", "]", "=", "HTTP_ACCEPT_ENCODING_HEADER_VALUE", "if", "kb", ".", "pageCompress", "else", "\"identity\"", "if", "post", "is", "not", "None", "and", "not", "multipart", "and", "not", "getHeader", "(", "headers", ",", "HTTP_HEADER", ".", "CONTENT_TYPE", ")", ":", "headers", "[", "HTTP_HEADER", ".", "CONTENT_TYPE", "]", "=", "POST_HINT_CONTENT_TYPES", ".", "get", "(", "kb", ".", "postHint", ",", "DEFAULT_CONTENT_TYPE", ")", "if", "headers", ".", "get", "(", "HTTP_HEADER", ".", "CONTENT_TYPE", ")", "==", "POST_HINT_CONTENT_TYPES", "[", "POST_HINT", ".", "MULTIPART", "]", ":", "warnMsg", "=", "\"missing 'boundary parameter' in '%s' header. \"", "%", "HTTP_HEADER", ".", "CONTENT_TYPE", "warnMsg", "+=", "\"Will try to reconstruct\"", "singleTimeWarnMessage", "(", "warnMsg", ")", "boundary", "=", "findMultipartPostBoundary", "(", "conf", ".", "data", ")", "if", "boundary", ":", "headers", "[", "HTTP_HEADER", ".", "CONTENT_TYPE", "]", "=", "\"%s; boundary=%s\"", "%", "(", "headers", "[", "HTTP_HEADER", ".", "CONTENT_TYPE", "]", ",", "boundary", ")", "if", "conf", ".", "keepAlive", ":", "headers", "[", "HTTP_HEADER", ".", "CONNECTION", "]", "=", "\"keep-alive\"", "# Reset header values to original in case of provided request file", "if", "target", "and", "conf", ".", "requestFile", ":", "headers", "=", "forgeHeaders", "(", "{", "HTTP_HEADER", ".", "COOKIE", ":", "cookie", "}", ")", "if", "auxHeaders", ":", "headers", "=", "forgeHeaders", "(", "auxHeaders", ",", "headers", ")", "for", "key", ",", "value", "in", "headers", ".", "items", "(", ")", ":", "del", "headers", "[", "key", "]", "value", "=", "unicodeencode", "(", "value", ",", "kb", ".", "pageEncoding", ")", "for", "char", "in", "(", "r\"\\r\"", ",", "r\"\\n\"", ")", ":", "value", "=", "re", ".", "sub", "(", "r\"(%s)([^ \\t])\"", "%", "char", ",", "r\"\\g<1>\\t\\g<2>\"", ",", "value", ")", "headers", "[", "unicodeencode", "(", "key", ",", "kb", ".", "pageEncoding", ")", "]", "=", "value", ".", "strip", "(", "\"\\r\\n\"", ")", "url", "=", "unicodeencode", "(", "url", ")", "post", "=", "unicodeencode", "(", "post", ")", "if", "websocket_", ":", "ws", "=", "websocket", ".", "WebSocket", "(", ")", "ws", ".", "settimeout", "(", "timeout", ")", "ws", ".", "connect", "(", "url", ",", "header", "=", "(", "\"%s: %s\"", "%", "_", "for", "_", "in", "headers", ".", "items", "(", ")", "if", "_", "[", "0", "]", "not", "in", "(", "\"Host\"", ",", ")", ")", ",", "cookie", "=", "cookie", ")", "# WebSocket will add Host field of headers automatically", "ws", ".", "send", "(", "urldecode", "(", "post", "or", "\"\"", ")", ")", "page", "=", "ws", ".", "recv", "(", ")", "ws", ".", "close", "(", ")", "code", "=", "ws", ".", "status", "status", "=", "httplib", ".", "responses", "[", "code", "]", "class", "_", "(", "dict", ")", ":", "pass", "responseHeaders", "=", "_", "(", "ws", ".", "getheaders", "(", ")", ")", "responseHeaders", ".", "headers", "=", "[", "\"%s: %s\\r\\n\"", "%", "(", "_", "[", "0", "]", ".", "capitalize", "(", ")", ",", "_", "[", "1", "]", ")", "for", "_", "in", "responseHeaders", ".", "items", "(", ")", "]", "requestHeaders", "+=", "\"\\r\\n\"", ".", "join", "(", "[", "\"%s: %s\"", "%", "(", "getUnicode", "(", "key", ".", "capitalize", "(", ")", "if", "isinstance", "(", "key", ",", "basestring", ")", "else", "key", ")", ",", "getUnicode", "(", "value", ")", ")", "for", "(", "key", ",", "value", ")", "in", "responseHeaders", ".", "items", "(", ")", "]", ")", "requestMsg", "+=", "\"\\r\\n%s\"", "%", "requestHeaders", "if", "post", "is", "not", "None", ":", "requestMsg", "+=", "\"\\r\\n\\r\\n%s\"", "%", "getUnicode", "(", "post", ")", "requestMsg", "+=", "\"\\r\\n\"", "threadData", ".", "lastRequestMsg", "=", "requestMsg", "logger", ".", "log", "(", "CUSTOM_LOGGING", ".", "TRAFFIC_OUT", ",", "requestMsg", ")", "else", ":", "if", "method", "and", "method", "not", "in", "(", "HTTPMETHOD", ".", "GET", ",", "HTTPMETHOD", ".", "POST", ")", ":", "method", "=", "unicodeencode", "(", "method", ")", "req", "=", "MethodRequest", "(", "url", ",", "post", ",", "headers", ")", "req", ".", "set_method", "(", "method", ")", "elif", "url", "is", "not", "None", ":", "req", "=", "urllib2", ".", "Request", "(", "url", ",", "post", ",", "headers", ")", "else", ":", "return", "None", ",", "None", ",", "None", "requestHeaders", "+=", "\"\\r\\n\"", ".", "join", "(", "[", "\"%s: %s\"", "%", "(", "getUnicode", "(", "key", ".", "capitalize", "(", ")", "if", "isinstance", "(", "key", ",", "basestring", ")", "else", "key", ")", ",", "getUnicode", "(", "value", ")", ")", "for", "(", "key", ",", "value", ")", "in", "req", ".", "header_items", "(", ")", "]", ")", "if", "not", "getRequestHeader", "(", "req", ",", "HTTP_HEADER", ".", "COOKIE", ")", "and", "conf", ".", "cj", ":", "conf", ".", "cj", ".", "_policy", ".", "_now", "=", "conf", ".", "cj", ".", "_now", "=", "int", "(", "time", ".", "time", "(", ")", ")", "cookies", "=", "conf", ".", "cj", ".", "_cookies_for_request", "(", "req", ")", "requestHeaders", "+=", "\"\\r\\n%s\"", "%", "(", "\"Cookie: %s\"", "%", "\";\"", ".", "join", "(", "\"%s=%s\"", "%", "(", "getUnicode", "(", "cookie", ".", "name", ")", ",", "getUnicode", "(", "cookie", ".", "value", ")", ")", "for", "cookie", "in", "cookies", ")", ")", "if", "post", "is", "not", "None", ":", "if", "not", "getRequestHeader", "(", "req", ",", "HTTP_HEADER", ".", "CONTENT_LENGTH", ")", ":", "requestHeaders", "+=", "\"\\r\\n%s: %d\"", "%", "(", "string", ".", "capwords", "(", "HTTP_HEADER", ".", "CONTENT_LENGTH", ")", ",", "len", "(", "post", ")", ")", "if", "not", "getRequestHeader", "(", "req", ",", "HTTP_HEADER", ".", "CONNECTION", ")", ":", "requestHeaders", "+=", "\"\\r\\n%s: %s\"", "%", "(", "HTTP_HEADER", ".", "CONNECTION", ",", "\"close\"", "if", "not", "conf", ".", "keepAlive", "else", "\"keep-alive\"", ")", "requestMsg", "+=", "\"\\r\\n%s\"", "%", "requestHeaders", "if", "post", "is", "not", "None", ":", "requestMsg", "+=", "\"\\r\\n\\r\\n%s\"", "%", "getUnicode", "(", "post", ")", "requestMsg", "+=", "\"\\r\\n\"", "if", "not", "multipart", ":", "threadData", ".", "lastRequestMsg", "=", "requestMsg", "logger", ".", "log", "(", "CUSTOM_LOGGING", ".", "TRAFFIC_OUT", ",", "requestMsg", ")", "if", "conf", ".", "cj", ":", "for", "cookie", "in", "conf", ".", "cj", ":", "if", "cookie", ".", "value", "is", "None", ":", "cookie", ".", "value", "=", "\"\"", "else", ":", "for", "char", "in", "(", "r\"\\r\"", ",", "r\"\\n\"", ")", ":", "cookie", ".", "value", "=", "re", ".", "sub", "(", "r\"(%s)([^ \\t])\"", "%", "char", ",", "r\"\\g<1>\\t\\g<2>\"", ",", "cookie", ".", "value", ")", "conn", "=", "urllib2", ".", "urlopen", "(", "req", ")", "if", "not", "kb", ".", "authHeader", "and", "getRequestHeader", "(", "req", ",", "HTTP_HEADER", ".", "AUTHORIZATION", ")", "and", "(", "conf", ".", "authType", "or", "\"\"", ")", ".", "lower", "(", ")", "==", "AUTH_TYPE", ".", "BASIC", ".", "lower", "(", ")", ":", "kb", ".", "authHeader", "=", "getRequestHeader", "(", "req", ",", "HTTP_HEADER", ".", "AUTHORIZATION", ")", "if", "not", "kb", ".", "proxyAuthHeader", "and", "getRequestHeader", "(", "req", ",", "HTTP_HEADER", ".", "PROXY_AUTHORIZATION", ")", ":", "kb", ".", "proxyAuthHeader", "=", "getRequestHeader", "(", "req", ",", "HTTP_HEADER", ".", "PROXY_AUTHORIZATION", ")", "# Return response object", "if", "response", ":", "return", "conn", ",", "None", ",", "None", "# Get HTTP response", "if", "hasattr", "(", "conn", ",", "\"redurl\"", ")", ":", "page", "=", "(", "threadData", ".", "lastRedirectMsg", "[", "1", "]", "if", "kb", ".", "redirectChoice", "==", "REDIRECTION", ".", "NO", "else", "Connect", ".", "_connReadProxy", "(", "conn", ")", ")", "if", "not", "skipRead", "else", "None", "skipLogTraffic", "=", "kb", ".", "redirectChoice", "==", "REDIRECTION", ".", "NO", "code", "=", "conn", ".", "redcode", "else", ":", "page", "=", "Connect", ".", "_connReadProxy", "(", "conn", ")", "if", "not", "skipRead", "else", "None", "if", "conn", ":", "code", "=", "(", "code", "or", "conn", ".", "code", ")", "if", "conn", ".", "code", "==", "kb", ".", "originalCode", "else", "conn", ".", "code", "# do not override redirection code (for comparison purposes)", "responseHeaders", "=", "conn", ".", "info", "(", ")", "responseHeaders", "[", "URI_HTTP_HEADER", "]", "=", "conn", ".", "geturl", "(", ")", "kb", ".", "serverHeader", "=", "responseHeaders", ".", "get", "(", "HTTP_HEADER", ".", "SERVER", ",", "kb", ".", "serverHeader", ")", "else", ":", "code", "=", "None", "responseHeaders", "=", "{", "}", "page", "=", "decodePage", "(", "page", ",", "responseHeaders", ".", "get", "(", "HTTP_HEADER", ".", "CONTENT_ENCODING", ")", ",", "responseHeaders", ".", "get", "(", "HTTP_HEADER", ".", "CONTENT_TYPE", ")", ")", "status", "=", "getUnicode", "(", "conn", ".", "msg", ")", "if", "conn", "and", "getattr", "(", "conn", ",", "\"msg\"", ",", "None", ")", "else", "None", "kb", ".", "connErrorCounter", "=", "0", "if", "not", "refreshing", ":", "refresh", "=", "responseHeaders", ".", "get", "(", "HTTP_HEADER", ".", "REFRESH", ",", "\"\"", ")", ".", "split", "(", "\"url=\"", ")", "[", "-", "1", "]", ".", "strip", "(", ")", "if", "extractRegexResult", "(", "META_REFRESH_REGEX", ",", "page", ")", ":", "refresh", "=", "extractRegexResult", "(", "META_REFRESH_REGEX", ",", "page", ")", "debugMsg", "=", "\"got HTML meta refresh header\"", "logger", ".", "debug", "(", "debugMsg", ")", "if", "refresh", ":", "if", "kb", ".", "alwaysRefresh", "is", "None", ":", "msg", "=", "\"sqlmap got a refresh request \"", "msg", "+=", "\"(redirect like response common to login pages). \"", "msg", "+=", "\"Do you want to apply the refresh \"", "msg", "+=", "\"from now on (or stay on the original page)? [Y/n]\"", "kb", ".", "alwaysRefresh", "=", "readInput", "(", "msg", ",", "default", "=", "'Y'", ",", "boolean", "=", "True", ")", "if", "kb", ".", "alwaysRefresh", ":", "if", "re", ".", "search", "(", "r\"\\Ahttps?://\"", ",", "refresh", ",", "re", ".", "I", ")", ":", "url", "=", "refresh", "else", ":", "url", "=", "urlparse", ".", "urljoin", "(", "url", ",", "refresh", ")", "threadData", ".", "lastRedirectMsg", "=", "(", "threadData", ".", "lastRequestUID", ",", "page", ")", "kwargs", "[", "\"refreshing\"", "]", "=", "True", "kwargs", "[", "\"url\"", "]", "=", "url", "kwargs", "[", "\"get\"", "]", "=", "None", "kwargs", "[", "\"post\"", "]", "=", "None", "try", ":", "return", "Connect", ".", "_getPageProxy", "(", "*", "*", "kwargs", ")", "except", "SqlmapSyntaxException", ":", "pass", "# Explicit closing of connection object", "if", "conn", "and", "not", "conf", ".", "keepAlive", ":", "try", ":", "if", "hasattr", "(", "conn", ".", "fp", ",", "'_sock'", ")", ":", "conn", ".", "fp", ".", "_sock", ".", "close", "(", ")", "conn", ".", "close", "(", ")", "except", "Exception", ",", "ex", ":", "warnMsg", "=", "\"problem occurred during connection closing ('%s')\"", "%", "getSafeExString", "(", "ex", ")", "logger", ".", "warn", "(", "warnMsg", ")", "except", "SqlmapConnectionException", ",", "ex", ":", "if", "conf", ".", "proxyList", "and", "not", "kb", ".", "threadException", ":", "warnMsg", "=", "\"unable to connect to the target URL ('%s')\"", "%", "ex", "logger", ".", "critical", "(", "warnMsg", ")", "threadData", ".", "retriesCount", "=", "conf", ".", "retries", "return", "Connect", ".", "_retryProxy", "(", "*", "*", "kwargs", ")", "else", ":", "raise", "except", "urllib2", ".", "HTTPError", ",", "ex", ":", "page", "=", "None", "responseHeaders", "=", "None", "if", "checking", ":", "return", "None", ",", "None", ",", "None", "try", ":", "page", "=", "ex", ".", "read", "(", ")", "if", "not", "skipRead", "else", "None", "responseHeaders", "=", "ex", ".", "info", "(", ")", "responseHeaders", "[", "URI_HTTP_HEADER", "]", "=", "ex", ".", "geturl", "(", ")", "page", "=", "decodePage", "(", "page", ",", "responseHeaders", ".", "get", "(", "HTTP_HEADER", ".", "CONTENT_ENCODING", ")", ",", "responseHeaders", ".", "get", "(", "HTTP_HEADER", ".", "CONTENT_TYPE", ")", ")", "except", "socket", ".", "timeout", ":", "warnMsg", "=", "\"connection timed out while trying \"", "warnMsg", "+=", "\"to get error page information (%d)\"", "%", "ex", ".", "code", "logger", ".", "warn", "(", "warnMsg", ")", "return", "None", ",", "None", ",", "None", "except", "KeyboardInterrupt", ":", "raise", "except", ":", "pass", "finally", ":", "page", "=", "page", "if", "isinstance", "(", "page", ",", "unicode", ")", "else", "getUnicode", "(", "page", ")", "code", "=", "ex", ".", "code", "status", "=", "getSafeExString", "(", "ex", ")", "kb", ".", "originalCode", "=", "kb", ".", "originalCode", "or", "code", "threadData", ".", "lastHTTPError", "=", "(", "threadData", ".", "lastRequestUID", ",", "code", ",", "status", ")", "kb", ".", "httpErrorCodes", "[", "code", "]", "=", "kb", ".", "httpErrorCodes", ".", "get", "(", "code", ",", "0", ")", "+", "1", "responseMsg", "+=", "\"[#%d] (%s %s):\\r\\n\"", "%", "(", "threadData", ".", "lastRequestUID", ",", "code", ",", "status", ")", "if", "responseHeaders", ":", "logHeaders", "=", "\"\\r\\n\"", ".", "join", "(", "[", "\"%s: %s\"", "%", "(", "getUnicode", "(", "key", ".", "capitalize", "(", ")", "if", "isinstance", "(", "key", ",", "basestring", ")", "else", "key", ")", ",", "getUnicode", "(", "value", ")", ")", "for", "(", "key", ",", "value", ")", "in", "responseHeaders", ".", "items", "(", ")", "]", ")", "logHTTPTraffic", "(", "requestMsg", ",", "\"%s%s\\r\\n\\r\\n%s\"", "%", "(", "responseMsg", ",", "logHeaders", ",", "(", "page", "or", "\"\"", ")", "[", ":", "MAX_CONNECTION_CHUNK_SIZE", "]", ")", ",", "start", ",", "time", ".", "time", "(", ")", ")", "skipLogTraffic", "=", "True", "if", "conf", ".", "verbose", "<=", "5", ":", "responseMsg", "+=", "getUnicode", "(", "logHeaders", ")", "elif", "conf", ".", "verbose", ">", "5", ":", "responseMsg", "+=", "\"%s\\r\\n\\r\\n%s\"", "%", "(", "logHeaders", ",", "(", "page", "or", "\"\"", ")", "[", ":", "MAX_CONNECTION_CHUNK_SIZE", "]", ")", "if", "not", "multipart", ":", "logger", ".", "log", "(", "CUSTOM_LOGGING", ".", "TRAFFIC_IN", ",", "responseMsg", ")", "if", "ex", ".", "code", "!=", "conf", ".", "ignoreCode", ":", "if", "ex", ".", "code", "==", "httplib", ".", "UNAUTHORIZED", ":", "errMsg", "=", "\"not authorized, try to provide right HTTP \"", "errMsg", "+=", "\"authentication type and valid credentials (%d)\"", "%", "code", "raise", "SqlmapConnectionException", "(", "errMsg", ")", "elif", "ex", ".", "code", "==", "httplib", ".", "NOT_FOUND", ":", "if", "raise404", ":", "errMsg", "=", "\"page not found (%d)\"", "%", "code", "raise", "SqlmapConnectionException", "(", "errMsg", ")", "else", ":", "debugMsg", "=", "\"page not found (%d)\"", "%", "code", "singleTimeLogMessage", "(", "debugMsg", ",", "logging", ".", "DEBUG", ")", "elif", "ex", ".", "code", "==", "httplib", ".", "GATEWAY_TIMEOUT", ":", "if", "ignoreTimeout", ":", "return", "None", "if", "not", "conf", ".", "ignoreTimeouts", "else", "\"\"", ",", "None", ",", "None", "else", ":", "warnMsg", "=", "\"unable to connect to the target URL (%d - %s)\"", "%", "(", "ex", ".", "code", ",", "httplib", ".", "responses", "[", "ex", ".", "code", "]", ")", "if", "threadData", ".", "retriesCount", "<", "conf", ".", "retries", "and", "not", "kb", ".", "threadException", ":", "warnMsg", "+=", "\". sqlmap is going to retry the request\"", "logger", ".", "critical", "(", "warnMsg", ")", "return", "Connect", ".", "_retryProxy", "(", "*", "*", "kwargs", ")", "elif", "kb", ".", "testMode", ":", "logger", ".", "critical", "(", "warnMsg", ")", "return", "None", ",", "None", ",", "None", "else", ":", "raise", "SqlmapConnectionException", "(", "warnMsg", ")", "else", ":", "debugMsg", "=", "\"got HTTP error code: %d (%s)\"", "%", "(", "code", ",", "status", ")", "logger", ".", "debug", "(", "debugMsg", ")", "except", "(", "urllib2", ".", "URLError", ",", "socket", ".", "error", ",", "socket", ".", "timeout", ",", "httplib", ".", "HTTPException", ",", "struct", ".", "error", ",", "binascii", ".", "Error", ",", "ProxyError", ",", "SqlmapCompressionException", ",", "WebSocketException", ",", "TypeError", ",", "ValueError", ")", ":", "tbMsg", "=", "traceback", ".", "format_exc", "(", ")", "if", "checking", ":", "return", "None", ",", "None", ",", "None", "elif", "\"no host given\"", "in", "tbMsg", ":", "warnMsg", "=", "\"invalid URL address used (%s)\"", "%", "repr", "(", "url", ")", "raise", "SqlmapSyntaxException", "(", "warnMsg", ")", "elif", "\"forcibly closed\"", "in", "tbMsg", "or", "\"Connection is already closed\"", "in", "tbMsg", ":", "warnMsg", "=", "\"connection was forcibly closed by the target URL\"", "elif", "\"timed out\"", "in", "tbMsg", ":", "if", "kb", ".", "testMode", "and", "kb", ".", "testType", "not", "in", "(", "None", ",", "PAYLOAD", ".", "TECHNIQUE", ".", "TIME", ",", "PAYLOAD", ".", "TECHNIQUE", ".", "STACKED", ")", ":", "singleTimeWarnMessage", "(", "\"there is a possibility that the target (or WAF/IPS) is dropping 'suspicious' requests\"", ")", "kb", ".", "droppingRequests", "=", "True", "warnMsg", "=", "\"connection timed out to the target URL\"", "elif", "\"Connection reset\"", "in", "tbMsg", ":", "if", "not", "conf", ".", "disablePrecon", ":", "singleTimeWarnMessage", "(", "\"turning off pre-connect mechanism because of connection reset(s)\"", ")", "conf", ".", "disablePrecon", "=", "True", "if", "kb", ".", "testMode", ":", "singleTimeWarnMessage", "(", "\"there is a possibility that the target (or WAF/IPS) is resetting 'suspicious' requests\"", ")", "kb", ".", "droppingRequests", "=", "True", "warnMsg", "=", "\"connection reset to the target URL\"", "elif", "\"URLError\"", "in", "tbMsg", "or", "\"error\"", "in", "tbMsg", ":", "warnMsg", "=", "\"unable to connect to the target URL\"", "match", "=", "re", ".", "search", "(", "r\"Errno \\d+\\] ([^>]+)\"", ",", "tbMsg", ")", "if", "match", ":", "warnMsg", "+=", "\" ('%s')\"", "%", "match", ".", "group", "(", "1", ")", ".", "strip", "(", ")", "elif", "\"NTLM\"", "in", "tbMsg", ":", "warnMsg", "=", "\"there has been a problem with NTLM authentication\"", "elif", "\"Invalid header name\"", "in", "tbMsg", ":", "# (e.g. PostgreSQL ::Text payload)", "return", "None", ",", "None", ",", "None", "elif", "\"BadStatusLine\"", "in", "tbMsg", ":", "warnMsg", "=", "\"connection dropped or unknown HTTP \"", "warnMsg", "+=", "\"status code received\"", "if", "not", "conf", ".", "agent", "and", "not", "conf", ".", "randomAgent", ":", "warnMsg", "+=", "\". Try to force the HTTP User-Agent \"", "warnMsg", "+=", "\"header with option '--user-agent' or switch '--random-agent'\"", "elif", "\"IncompleteRead\"", "in", "tbMsg", ":", "warnMsg", "=", "\"there was an incomplete read error while retrieving data \"", "warnMsg", "+=", "\"from the target URL\"", "elif", "\"Handshake status\"", "in", "tbMsg", ":", "status", "=", "re", ".", "search", "(", "r\"Handshake status ([\\d]{3})\"", ",", "tbMsg", ")", "errMsg", "=", "\"websocket handshake status %s\"", "%", "status", ".", "group", "(", "1", ")", "if", "status", "else", "\"unknown\"", "raise", "SqlmapConnectionException", "(", "errMsg", ")", "elif", "\"SqlmapCompressionException\"", "in", "tbMsg", ":", "warnMsg", "=", "\"problems with response (de)compression\"", "retrying", "=", "True", "else", ":", "warnMsg", "=", "\"unable to connect to the target URL\"", "if", "\"BadStatusLine\"", "not", "in", "tbMsg", "and", "any", "(", "(", "conf", ".", "proxy", ",", "conf", ".", "tor", ")", ")", ":", "warnMsg", "+=", "\" or proxy\"", "if", "silent", ":", "return", "None", ",", "None", ",", "None", "with", "kb", ".", "locks", ".", "connError", ":", "kb", ".", "connErrorCounter", "+=", "1", "if", "kb", ".", "connErrorCounter", ">=", "MAX_CONSECUTIVE_CONNECTION_ERRORS", "and", "kb", ".", "connErrorChoice", "is", "None", ":", "message", "=", "\"there seems to be a continuous problem with connection to the target. \"", "message", "+=", "\"Are you sure that you want to continue \"", "message", "+=", "\"with further target testing? [y/N] \"", "kb", ".", "connErrorChoice", "=", "readInput", "(", "message", ",", "default", "=", "'N'", ",", "boolean", "=", "True", ")", "if", "kb", ".", "connErrorChoice", "is", "False", ":", "raise", "SqlmapConnectionException", "(", "warnMsg", ")", "if", "\"forcibly closed\"", "in", "tbMsg", ":", "logger", ".", "critical", "(", "warnMsg", ")", "return", "None", ",", "None", ",", "None", "elif", "ignoreTimeout", "and", "any", "(", "_", "in", "tbMsg", "for", "_", "in", "(", "\"timed out\"", ",", "\"IncompleteRead\"", ")", ")", ":", "return", "None", "if", "not", "conf", ".", "ignoreTimeouts", "else", "\"\"", ",", "None", ",", "None", "elif", "threadData", ".", "retriesCount", "<", "conf", ".", "retries", "and", "not", "kb", ".", "threadException", ":", "warnMsg", "+=", "\". sqlmap is going to retry the request\"", "if", "not", "retrying", ":", "warnMsg", "+=", "\"(s)\"", "logger", ".", "critical", "(", "warnMsg", ")", "else", ":", "logger", ".", "debug", "(", "warnMsg", ")", "return", "Connect", ".", "_retryProxy", "(", "*", "*", "kwargs", ")", "elif", "kb", ".", "testMode", "or", "kb", ".", "multiThreadMode", ":", "logger", ".", "critical", "(", "warnMsg", ")", "return", "None", ",", "None", ",", "None", "else", ":", "raise", "SqlmapConnectionException", "(", "warnMsg", ")", "finally", ":", "if", "isinstance", "(", "page", ",", "basestring", ")", "and", "not", "isinstance", "(", "page", ",", "unicode", ")", ":", "if", "HTTP_HEADER", ".", "CONTENT_TYPE", "in", "(", "responseHeaders", "or", "{", "}", ")", "and", "not", "re", ".", "search", "(", "TEXT_CONTENT_TYPE_REGEX", ",", "responseHeaders", "[", "HTTP_HEADER", ".", "CONTENT_TYPE", "]", ")", ":", "page", "=", "unicode", "(", "page", ",", "errors", "=", "\"ignore\"", ")", "else", ":", "page", "=", "getUnicode", "(", "page", ")", "socket", ".", "setdefaulttimeout", "(", "conf", ".", "timeout", ")", "processResponse", "(", "page", ",", "responseHeaders", ",", "status", ")", "if", "conn", "and", "getattr", "(", "conn", ",", "\"redurl\"", ",", "None", ")", ":", "_", "=", "urlparse", ".", "urlsplit", "(", "conn", ".", "redurl", ")", "_", "=", "(", "\"%s%s\"", "%", "(", "_", ".", "path", "or", "\"/\"", ",", "(", "\"?%s\"", "%", "_", ".", "query", ")", "if", "_", ".", "query", "else", "\"\"", ")", ")", "requestMsg", "=", "re", ".", "sub", "(", "r\"(\\n[A-Z]+ ).+?( HTTP/\\d)\"", ",", "r\"\\g<1>%s\\g<2>\"", "%", "getUnicode", "(", "_", ")", ".", "replace", "(", "\"\\\\\"", ",", "\"\\\\\\\\\"", ")", ",", "requestMsg", ",", "1", ")", "if", "kb", ".", "resendPostOnRedirect", "is", "False", ":", "requestMsg", "=", "re", ".", "sub", "(", "r\"(\\[#\\d+\\]:\\n)POST \"", ",", "r\"\\g<1>GET \"", ",", "requestMsg", ")", "requestMsg", "=", "re", ".", "sub", "(", "r\"(?i)Content-length: \\d+\\n\"", ",", "\"\"", ",", "requestMsg", ")", "requestMsg", "=", "re", ".", "sub", "(", "r\"(?s)\\n\\n.+\"", ",", "\"\\n\"", ",", "requestMsg", ")", "responseMsg", "+=", "\"[#%d] (%d %s):\\r\\n\"", "%", "(", "threadData", ".", "lastRequestUID", ",", "conn", ".", "code", ",", "status", ")", "else", ":", "responseMsg", "+=", "\"[#%d] (%s %s):\\r\\n\"", "%", "(", "threadData", ".", "lastRequestUID", ",", "code", ",", "status", ")", "if", "responseHeaders", ":", "logHeaders", "=", "\"\\r\\n\"", ".", "join", "(", "[", "\"%s: %s\"", "%", "(", "getUnicode", "(", "key", ".", "capitalize", "(", ")", "if", "isinstance", "(", "key", ",", "basestring", ")", "else", "key", ")", ",", "getUnicode", "(", "value", ")", ")", "for", "(", "key", ",", "value", ")", "in", "responseHeaders", ".", "items", "(", ")", "]", ")", "if", "not", "skipLogTraffic", ":", "logHTTPTraffic", "(", "requestMsg", ",", "\"%s%s\\r\\n\\r\\n%s\"", "%", "(", "responseMsg", ",", "logHeaders", ",", "(", "page", "or", "\"\"", ")", "[", ":", "MAX_CONNECTION_CHUNK_SIZE", "]", ")", ",", "start", ",", "time", ".", "time", "(", ")", ")", "if", "conf", ".", "verbose", "<=", "5", ":", "responseMsg", "+=", "getUnicode", "(", "logHeaders", ")", "elif", "conf", ".", "verbose", ">", "5", ":", "responseMsg", "+=", "\"%s\\r\\n\\r\\n%s\"", "%", "(", "logHeaders", ",", "(", "page", "or", "\"\"", ")", "[", ":", "MAX_CONNECTION_CHUNK_SIZE", "]", ")", "if", "not", "multipart", ":", "logger", ".", "log", "(", "CUSTOM_LOGGING", ".", "TRAFFIC_IN", ",", "responseMsg", ")", "return", "page", ",", "responseHeaders", ",", "code" ]
https://github.com/sabri-zaki/EasY_HaCk/blob/2a39ac384dd0d6fc51c0dd22e8d38cece683fdb9/.modules/.sqlmap/lib/request/connect.py#L224-L769
edisonlz/fastor
342078a18363ac41d3c6b1ab29dbdd44fdb0b7b3
base/site-packages/django/core/cache/backends/base.py
python
BaseCache.set
(self, key, value, timeout=DEFAULT_TIMEOUT, version=None)
Set a value in the cache. If timeout is given, that timeout will be used for the key; otherwise the default cache timeout will be used.
Set a value in the cache. If timeout is given, that timeout will be used for the key; otherwise the default cache timeout will be used.
[ "Set", "a", "value", "in", "the", "cache", ".", "If", "timeout", "is", "given", "that", "timeout", "will", "be", "used", "for", "the", "key", ";", "otherwise", "the", "default", "cache", "timeout", "will", "be", "used", "." ]
def set(self, key, value, timeout=DEFAULT_TIMEOUT, version=None): """ Set a value in the cache. If timeout is given, that timeout will be used for the key; otherwise the default cache timeout will be used. """ raise NotImplementedError
[ "def", "set", "(", "self", ",", "key", ",", "value", ",", "timeout", "=", "DEFAULT_TIMEOUT", ",", "version", "=", "None", ")", ":", "raise", "NotImplementedError" ]
https://github.com/edisonlz/fastor/blob/342078a18363ac41d3c6b1ab29dbdd44fdb0b7b3/base/site-packages/django/core/cache/backends/base.py#L108-L113
bnpy/bnpy
d5b311e8f58ccd98477f4a0c8a4d4982e3fca424
bnpy/allocmodel/topics/HDPTopicUtil.py
python
calcELBO
(**kwargs)
return Lnon + Llinear
Calculate ELBO objective for provided model state. Returns ------- L : scalar float L is the value of the objective function at provided state.
Calculate ELBO objective for provided model state.
[ "Calculate", "ELBO", "objective", "for", "provided", "model", "state", "." ]
def calcELBO(**kwargs): """ Calculate ELBO objective for provided model state. Returns ------- L : scalar float L is the value of the objective function at provided state. """ Llinear = calcELBO_LinearTerms(**kwargs) Lnon = calcELBO_NonlinearTerms(**kwargs) if isinstance(Lnon, dict): Llinear.update(Lnon) return Llinear return Lnon + Llinear
[ "def", "calcELBO", "(", "*", "*", "kwargs", ")", ":", "Llinear", "=", "calcELBO_LinearTerms", "(", "*", "*", "kwargs", ")", "Lnon", "=", "calcELBO_NonlinearTerms", "(", "*", "*", "kwargs", ")", "if", "isinstance", "(", "Lnon", ",", "dict", ")", ":", "Llinear", ".", "update", "(", "Lnon", ")", "return", "Llinear", "return", "Lnon", "+", "Llinear" ]
https://github.com/bnpy/bnpy/blob/d5b311e8f58ccd98477f4a0c8a4d4982e3fca424/bnpy/allocmodel/topics/HDPTopicUtil.py#L25-L38
Kyubyong/expressive_tacotron
49293bbe6eb6034e2e214483c49fcf709ffbf878
utils.py
python
learning_rate_decay
(init_lr, global_step, warmup_steps=4000.)
return init_lr * warmup_steps ** 0.5 * tf.minimum(step * warmup_steps ** -1.5, step ** -0.5)
Noam scheme from tensor2tensor
Noam scheme from tensor2tensor
[ "Noam", "scheme", "from", "tensor2tensor" ]
def learning_rate_decay(init_lr, global_step, warmup_steps=4000.): '''Noam scheme from tensor2tensor''' step = tf.cast(global_step + 1, dtype=tf.float32) return init_lr * warmup_steps ** 0.5 * tf.minimum(step * warmup_steps ** -1.5, step ** -0.5)
[ "def", "learning_rate_decay", "(", "init_lr", ",", "global_step", ",", "warmup_steps", "=", "4000.", ")", ":", "step", "=", "tf", ".", "cast", "(", "global_step", "+", "1", ",", "dtype", "=", "tf", ".", "float32", ")", "return", "init_lr", "*", "warmup_steps", "**", "0.5", "*", "tf", ".", "minimum", "(", "step", "*", "warmup_steps", "**", "-", "1.5", ",", "step", "**", "-", "0.5", ")" ]
https://github.com/Kyubyong/expressive_tacotron/blob/49293bbe6eb6034e2e214483c49fcf709ffbf878/utils.py#L126-L129
Qirky/FoxDot
76318f9630bede48ff3994146ed644affa27bfa4
FoxDot/lib/Patterns/Main.py
python
Cycle.__init__
(self, *args)
[]
def __init__(self, *args): Pattern.__init__(self, list(args))
[ "def", "__init__", "(", "self", ",", "*", "args", ")", ":", "Pattern", ".", "__init__", "(", "self", ",", "list", "(", "args", ")", ")" ]
https://github.com/Qirky/FoxDot/blob/76318f9630bede48ff3994146ed644affa27bfa4/FoxDot/lib/Patterns/Main.py#L1050-L1051
GNS3/gns3-server
aff06572d4173df945ad29ea8feb274f7885d9e4
gns3server/compute/dynamips/nios/nio_udp.py
python
NIOUDP.rhost
(self)
return self._rhost
Returns the remote host :returns: remote address/host
Returns the remote host
[ "Returns", "the", "remote", "host" ]
def rhost(self): """ Returns the remote host :returns: remote address/host """ return self._rhost
[ "def", "rhost", "(", "self", ")", ":", "return", "self", ".", "_rhost" ]
https://github.com/GNS3/gns3-server/blob/aff06572d4173df945ad29ea8feb274f7885d9e4/gns3server/compute/dynamips/nios/nio_udp.py#L118-L125
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_hxb2/lib/python3.5/site-packages/wheel/signatures/djbec.py
python
xpt_add
(pt1, pt2)
return (X3, Y3, Z3, T3)
[]
def xpt_add(pt1, pt2): (X1, Y1, Z1, T1) = pt1 (X2, Y2, Z2, T2) = pt2 A = ((Y1 - X1) * (Y2 + X2)) % q B = ((Y1 + X1) * (Y2 - X2)) % q C = (Z1 * 2 * T2) % q D = (T1 * 2 * Z2) % q E = (D + C) % q F = (B - A) % q G = (B + A) % q H = (D - C) % q X3 = (E * F) % q Y3 = (G * H) % q Z3 = (F * G) % q T3 = (E * H) % q return (X3, Y3, Z3, T3)
[ "def", "xpt_add", "(", "pt1", ",", "pt2", ")", ":", "(", "X1", ",", "Y1", ",", "Z1", ",", "T1", ")", "=", "pt1", "(", "X2", ",", "Y2", ",", "Z2", ",", "T2", ")", "=", "pt2", "A", "=", "(", "(", "Y1", "-", "X1", ")", "*", "(", "Y2", "+", "X2", ")", ")", "%", "q", "B", "=", "(", "(", "Y1", "+", "X1", ")", "*", "(", "Y2", "-", "X2", ")", ")", "%", "q", "C", "=", "(", "Z1", "*", "2", "*", "T2", ")", "%", "q", "D", "=", "(", "T1", "*", "2", "*", "Z2", ")", "%", "q", "E", "=", "(", "D", "+", "C", ")", "%", "q", "F", "=", "(", "B", "-", "A", ")", "%", "q", "G", "=", "(", "B", "+", "A", ")", "%", "q", "H", "=", "(", "D", "-", "C", ")", "%", "q", "X3", "=", "(", "E", "*", "F", ")", "%", "q", "Y3", "=", "(", "G", "*", "H", ")", "%", "q", "Z3", "=", "(", "F", "*", "G", ")", "%", "q", "T3", "=", "(", "E", "*", "H", ")", "%", "q", "return", "(", "X3", ",", "Y3", ",", "Z3", ",", "T3", ")" ]
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_hxb2/lib/python3.5/site-packages/wheel/signatures/djbec.py#L101-L116
holzschu/Carnets
44effb10ddfc6aa5c8b0687582a724ba82c6b547
Library/lib/python3.7/site-packages/matplotlib-3.0.3-py3.7-macosx-10.9-x86_64.egg/matplotlib/transforms.py
python
Transform.transform_affine
(self, values)
return self.get_affine().transform(values)
Performs only the affine part of this transformation on the given array of values. ``transform(values)`` is always equivalent to ``transform_affine(transform_non_affine(values))``. In non-affine transformations, this is generally a no-op. In affine transformations, this is equivalent to ``transform(values)``. Accepts a numpy array of shape (N x :attr:`input_dims`) and returns a numpy array of shape (N x :attr:`output_dims`). Alternatively, accepts a numpy array of length :attr:`input_dims` and returns a numpy array of length :attr:`output_dims`.
Performs only the affine part of this transformation on the given array of values.
[ "Performs", "only", "the", "affine", "part", "of", "this", "transformation", "on", "the", "given", "array", "of", "values", "." ]
def transform_affine(self, values): """ Performs only the affine part of this transformation on the given array of values. ``transform(values)`` is always equivalent to ``transform_affine(transform_non_affine(values))``. In non-affine transformations, this is generally a no-op. In affine transformations, this is equivalent to ``transform(values)``. Accepts a numpy array of shape (N x :attr:`input_dims`) and returns a numpy array of shape (N x :attr:`output_dims`). Alternatively, accepts a numpy array of length :attr:`input_dims` and returns a numpy array of length :attr:`output_dims`. """ return self.get_affine().transform(values)
[ "def", "transform_affine", "(", "self", ",", "values", ")", ":", "return", "self", ".", "get_affine", "(", ")", ".", "transform", "(", "values", ")" ]
https://github.com/holzschu/Carnets/blob/44effb10ddfc6aa5c8b0687582a724ba82c6b547/Library/lib/python3.7/site-packages/matplotlib-3.0.3-py3.7-macosx-10.9-x86_64.egg/matplotlib/transforms.py#L1438-L1456
jython/frozen-mirror
b8d7aa4cee50c0c0fe2f4b235dd62922dd0f3f99
Lib/javapath.py
python
normpath
(path)
return slashes + string.joinfields(comps, sep)
Normalize path, eliminating double slashes, etc.
Normalize path, eliminating double slashes, etc.
[ "Normalize", "path", "eliminating", "double", "slashes", "etc", "." ]
def normpath(path): """Normalize path, eliminating double slashes, etc.""" sep = os.sep if sep == '\\': path = path.replace("/", sep) curdir = os.curdir pardir = os.pardir import string # Treat initial slashes specially slashes = '' while path[:1] == sep: slashes = slashes + sep path = path[1:] comps = string.splitfields(path, sep) i = 0 while i < len(comps): if comps[i] == curdir: del comps[i] while i < len(comps) and comps[i] == '': del comps[i] elif comps[i] == pardir and i > 0 and comps[i-1] not in ('', pardir): del comps[i-1:i+1] i = i-1 elif comps[i] == '' and i > 0 and comps[i-1] <> '': del comps[i] else: i = i+1 # If the path is now empty, substitute '.' if not comps and not slashes: comps.append(curdir) return slashes + string.joinfields(comps, sep)
[ "def", "normpath", "(", "path", ")", ":", "sep", "=", "os", ".", "sep", "if", "sep", "==", "'\\\\'", ":", "path", "=", "path", ".", "replace", "(", "\"/\"", ",", "sep", ")", "curdir", "=", "os", ".", "curdir", "pardir", "=", "os", ".", "pardir", "import", "string", "# Treat initial slashes specially", "slashes", "=", "''", "while", "path", "[", ":", "1", "]", "==", "sep", ":", "slashes", "=", "slashes", "+", "sep", "path", "=", "path", "[", "1", ":", "]", "comps", "=", "string", ".", "splitfields", "(", "path", ",", "sep", ")", "i", "=", "0", "while", "i", "<", "len", "(", "comps", ")", ":", "if", "comps", "[", "i", "]", "==", "curdir", ":", "del", "comps", "[", "i", "]", "while", "i", "<", "len", "(", "comps", ")", "and", "comps", "[", "i", "]", "==", "''", ":", "del", "comps", "[", "i", "]", "elif", "comps", "[", "i", "]", "==", "pardir", "and", "i", ">", "0", "and", "comps", "[", "i", "-", "1", "]", "not", "in", "(", "''", ",", "pardir", ")", ":", "del", "comps", "[", "i", "-", "1", ":", "i", "+", "1", "]", "i", "=", "i", "-", "1", "elif", "comps", "[", "i", "]", "==", "''", "and", "i", ">", "0", "and", "comps", "[", "i", "-", "1", "]", "<>", "''", ":", "del", "comps", "[", "i", "]", "else", ":", "i", "=", "i", "+", "1", "# If the path is now empty, substitute '.'", "if", "not", "comps", "and", "not", "slashes", ":", "comps", ".", "append", "(", "curdir", ")", "return", "slashes", "+", "string", ".", "joinfields", "(", "comps", ",", "sep", ")" ]
https://github.com/jython/frozen-mirror/blob/b8d7aa4cee50c0c0fe2f4b235dd62922dd0f3f99/Lib/javapath.py#L220-L250
google/tf-quant-finance
8fd723689ebf27ff4bb2bd2acb5f6091c5e07309
tf_quant_finance/math/pde/grids.py
python
uniform_grid
(minimums, maximums, sizes, dtype=None, validate_args=False, name=None)
Creates a grid spec for a uniform grid. A uniform grid is characterized by having a constant gap between neighboring points along each axis. Note that the shape of all three parameters must be fully defined and equal to each other. The shape is used to determine the dimension of the grid. Args: minimums: Real `Tensor` of rank 1 containing the lower end points of the grid. Must have the same shape as those of `maximums` and `sizes` args. maximums: `Tensor` of the same dtype and shape as `minimums`. The upper endpoints of the grid. sizes: Integer `Tensor` of the same shape as `minimums`. The size of the grid in each axis. Each entry must be greater than or equal to 2 (i.e. the sizes include the end points). For example, if minimums = [0.] and maximums = [1.] and sizes = [3], the grid will have three points at [0.0, 0.5, 1.0]. dtype: Optional tf.dtype. The default dtype to use for the grid. validate_args: Python boolean indicating whether to validate the supplied arguments. The validation checks performed are (a) `maximums` > `minimums` (b) `sizes` >= 2. name: Python str. The name prefixed to the ops created by this function. If not supplied, the default name 'uniform_grid_spec' is used. Returns: The grid locations as projected along each axis. One `Tensor` of shape `[..., n]`, where `n` is the number of points along that axis. The first dimensions are the batch shape. The grid itself can be seen as a cartesian product of the locations array. Raises: ValueError if the shape of maximums, minimums and sizes are not fully defined or they are not identical to each other or they are not rank 1.
Creates a grid spec for a uniform grid.
[ "Creates", "a", "grid", "spec", "for", "a", "uniform", "grid", "." ]
def uniform_grid(minimums, maximums, sizes, dtype=None, validate_args=False, name=None): """Creates a grid spec for a uniform grid. A uniform grid is characterized by having a constant gap between neighboring points along each axis. Note that the shape of all three parameters must be fully defined and equal to each other. The shape is used to determine the dimension of the grid. Args: minimums: Real `Tensor` of rank 1 containing the lower end points of the grid. Must have the same shape as those of `maximums` and `sizes` args. maximums: `Tensor` of the same dtype and shape as `minimums`. The upper endpoints of the grid. sizes: Integer `Tensor` of the same shape as `minimums`. The size of the grid in each axis. Each entry must be greater than or equal to 2 (i.e. the sizes include the end points). For example, if minimums = [0.] and maximums = [1.] and sizes = [3], the grid will have three points at [0.0, 0.5, 1.0]. dtype: Optional tf.dtype. The default dtype to use for the grid. validate_args: Python boolean indicating whether to validate the supplied arguments. The validation checks performed are (a) `maximums` > `minimums` (b) `sizes` >= 2. name: Python str. The name prefixed to the ops created by this function. If not supplied, the default name 'uniform_grid_spec' is used. Returns: The grid locations as projected along each axis. One `Tensor` of shape `[..., n]`, where `n` is the number of points along that axis. The first dimensions are the batch shape. The grid itself can be seen as a cartesian product of the locations array. Raises: ValueError if the shape of maximums, minimums and sizes are not fully defined or they are not identical to each other or they are not rank 1. """ with tf.compat.v1.name_scope(name, 'uniform_grid', [minimums, maximums, sizes]): minimums = tf.convert_to_tensor(minimums, dtype=dtype, name='minimums') maximums = tf.convert_to_tensor(maximums, dtype=dtype, name='maximums') sizes = tf.convert_to_tensor(sizes, name='sizes') # Check that the shape of `sizes` is statically defined. if not _check_shapes_fully_defined(minimums, maximums, sizes): raise ValueError('The shapes of minimums, maximums and sizes ' 'must be fully defined.') if not (minimums.shape == maximums.shape and minimums.shape == sizes.shape): raise ValueError('The shapes of minimums, maximums and sizes must be ' 'identical.') if len(minimums.shape.as_list()) != 1: raise ValueError('The minimums, maximums and sizes must all be rank 1.') control_deps = [] if validate_args: control_deps = [ tf.compat.v1.debugging.assert_greater(maximums, minimums), tf.compat.v1.debugging.assert_greater_equal(sizes, 2) ] with tf.compat.v1.control_dependencies(control_deps): dim = sizes.shape[0] locations = [ tf.linspace(minimums[i], maximums[i], num=sizes[i]) for i in range(dim) ] return locations
[ "def", "uniform_grid", "(", "minimums", ",", "maximums", ",", "sizes", ",", "dtype", "=", "None", ",", "validate_args", "=", "False", ",", "name", "=", "None", ")", ":", "with", "tf", ".", "compat", ".", "v1", ".", "name_scope", "(", "name", ",", "'uniform_grid'", ",", "[", "minimums", ",", "maximums", ",", "sizes", "]", ")", ":", "minimums", "=", "tf", ".", "convert_to_tensor", "(", "minimums", ",", "dtype", "=", "dtype", ",", "name", "=", "'minimums'", ")", "maximums", "=", "tf", ".", "convert_to_tensor", "(", "maximums", ",", "dtype", "=", "dtype", ",", "name", "=", "'maximums'", ")", "sizes", "=", "tf", ".", "convert_to_tensor", "(", "sizes", ",", "name", "=", "'sizes'", ")", "# Check that the shape of `sizes` is statically defined.", "if", "not", "_check_shapes_fully_defined", "(", "minimums", ",", "maximums", ",", "sizes", ")", ":", "raise", "ValueError", "(", "'The shapes of minimums, maximums and sizes '", "'must be fully defined.'", ")", "if", "not", "(", "minimums", ".", "shape", "==", "maximums", ".", "shape", "and", "minimums", ".", "shape", "==", "sizes", ".", "shape", ")", ":", "raise", "ValueError", "(", "'The shapes of minimums, maximums and sizes must be '", "'identical.'", ")", "if", "len", "(", "minimums", ".", "shape", ".", "as_list", "(", ")", ")", "!=", "1", ":", "raise", "ValueError", "(", "'The minimums, maximums and sizes must all be rank 1.'", ")", "control_deps", "=", "[", "]", "if", "validate_args", ":", "control_deps", "=", "[", "tf", ".", "compat", ".", "v1", ".", "debugging", ".", "assert_greater", "(", "maximums", ",", "minimums", ")", ",", "tf", ".", "compat", ".", "v1", ".", "debugging", ".", "assert_greater_equal", "(", "sizes", ",", "2", ")", "]", "with", "tf", ".", "compat", ".", "v1", ".", "control_dependencies", "(", "control_deps", ")", ":", "dim", "=", "sizes", ".", "shape", "[", "0", "]", "locations", "=", "[", "tf", ".", "linspace", "(", "minimums", "[", "i", "]", ",", "maximums", "[", "i", "]", ",", "num", "=", "sizes", "[", "i", "]", ")", "for", "i", "in", "range", "(", "dim", ")", "]", "return", "locations" ]
https://github.com/google/tf-quant-finance/blob/8fd723689ebf27ff4bb2bd2acb5f6091c5e07309/tf_quant_finance/math/pde/grids.py#L22-L92
EnableSecurity/wafw00f
3257c48d45ffb2f6504629aa3c5d529f1b886c1b
wafw00f/plugins/sonicwall.py
python
is_waf
(self)
return False
[]
def is_waf(self): schemes = [ self.matchHeader(('Server', 'SonicWALL')), self.matchContent(r"<(title|h\d{1})>Web Site Blocked"), self.matchContent(r'\+?nsa_banner') ] if any(i for i in schemes): return True return False
[ "def", "is_waf", "(", "self", ")", ":", "schemes", "=", "[", "self", ".", "matchHeader", "(", "(", "'Server'", ",", "'SonicWALL'", ")", ")", ",", "self", ".", "matchContent", "(", "r\"<(title|h\\d{1})>Web Site Blocked\"", ")", ",", "self", ".", "matchContent", "(", "r'\\+?nsa_banner'", ")", "]", "if", "any", "(", "i", "for", "i", "in", "schemes", ")", ":", "return", "True", "return", "False" ]
https://github.com/EnableSecurity/wafw00f/blob/3257c48d45ffb2f6504629aa3c5d529f1b886c1b/wafw00f/plugins/sonicwall.py#L10-L18
brechtm/rinohtype
d03096f9b1b0ba2d821a25356d84dc6d3028c96c
src/rinoh/backend/pdf/xobject/purepng.py
python
_readable.read
(self, n)
return r
Read `n` chars from buffer
Read `n` chars from buffer
[ "Read", "n", "chars", "from", "buffer" ]
def read(self, n): """Read `n` chars from buffer""" r = self.buf[self.offset:self.offset + n] if isinstance(r, array): r = r.tostring() self.offset += n return r
[ "def", "read", "(", "self", ",", "n", ")", ":", "r", "=", "self", ".", "buf", "[", "self", ".", "offset", ":", "self", ".", "offset", "+", "n", "]", "if", "isinstance", "(", "r", ",", "array", ")", ":", "r", "=", "r", ".", "tostring", "(", ")", "self", ".", "offset", "+=", "n", "return", "r" ]
https://github.com/brechtm/rinohtype/blob/d03096f9b1b0ba2d821a25356d84dc6d3028c96c/src/rinoh/backend/pdf/xobject/purepng.py#L2071-L2077
securesystemslab/zippy
ff0e84ac99442c2c55fe1d285332cfd4e185e089
zippy/benchmarks/src/benchmarks/sympy/sympy/matrices/expressions/blockmatrix.py
python
bc_matadd
(expr)
[]
def bc_matadd(expr): args = sift(expr.args, lambda M: isinstance(M, BlockMatrix)) blocks = args[True] if not blocks: return expr nonblocks = args[False] block = blocks[0] for b in blocks[1:]: block = block._blockadd(b) if nonblocks: return MatAdd(*nonblocks) + block else: return block
[ "def", "bc_matadd", "(", "expr", ")", ":", "args", "=", "sift", "(", "expr", ".", "args", ",", "lambda", "M", ":", "isinstance", "(", "M", ",", "BlockMatrix", ")", ")", "blocks", "=", "args", "[", "True", "]", "if", "not", "blocks", ":", "return", "expr", "nonblocks", "=", "args", "[", "False", "]", "block", "=", "blocks", "[", "0", "]", "for", "b", "in", "blocks", "[", "1", ":", "]", ":", "block", "=", "block", ".", "_blockadd", "(", "b", ")", "if", "nonblocks", ":", "return", "MatAdd", "(", "*", "nonblocks", ")", "+", "block", "else", ":", "return", "block" ]
https://github.com/securesystemslab/zippy/blob/ff0e84ac99442c2c55fe1d285332cfd4e185e089/zippy/benchmarks/src/benchmarks/sympy/sympy/matrices/expressions/blockmatrix.py#L297-L310
tp4a/teleport
1fafd34f1f775d2cf80ea4af6e44468d8e0b24ad
server/www/packages/packages-linux/x64/tornado/iostream.py
python
IOStream.connect
( self: _IOStreamType, address: tuple, server_hostname: str = None )
return future
Connects the socket to a remote address without blocking. May only be called if the socket passed to the constructor was not previously connected. The address parameter is in the same format as for `socket.connect <socket.socket.connect>` for the type of socket passed to the IOStream constructor, e.g. an ``(ip, port)`` tuple. Hostnames are accepted here, but will be resolved synchronously and block the IOLoop. If you have a hostname instead of an IP address, the `.TCPClient` class is recommended instead of calling this method directly. `.TCPClient` will do asynchronous DNS resolution and handle both IPv4 and IPv6. If ``callback`` is specified, it will be called with no arguments when the connection is completed; if not this method returns a `.Future` (whose result after a successful connection will be the stream itself). In SSL mode, the ``server_hostname`` parameter will be used for certificate validation (unless disabled in the ``ssl_options``) and SNI (if supported; requires Python 2.7.9+). Note that it is safe to call `IOStream.write <BaseIOStream.write>` while the connection is pending, in which case the data will be written as soon as the connection is ready. Calling `IOStream` read methods before the socket is connected works on some platforms but is non-portable. .. versionchanged:: 4.0 If no callback is given, returns a `.Future`. .. versionchanged:: 4.2 SSL certificates are validated by default; pass ``ssl_options=dict(cert_reqs=ssl.CERT_NONE)`` or a suitably-configured `ssl.SSLContext` to the `SSLIOStream` constructor to disable. .. versionchanged:: 6.0 The ``callback`` argument was removed. Use the returned `.Future` instead.
Connects the socket to a remote address without blocking.
[ "Connects", "the", "socket", "to", "a", "remote", "address", "without", "blocking", "." ]
def connect( self: _IOStreamType, address: tuple, server_hostname: str = None ) -> "Future[_IOStreamType]": """Connects the socket to a remote address without blocking. May only be called if the socket passed to the constructor was not previously connected. The address parameter is in the same format as for `socket.connect <socket.socket.connect>` for the type of socket passed to the IOStream constructor, e.g. an ``(ip, port)`` tuple. Hostnames are accepted here, but will be resolved synchronously and block the IOLoop. If you have a hostname instead of an IP address, the `.TCPClient` class is recommended instead of calling this method directly. `.TCPClient` will do asynchronous DNS resolution and handle both IPv4 and IPv6. If ``callback`` is specified, it will be called with no arguments when the connection is completed; if not this method returns a `.Future` (whose result after a successful connection will be the stream itself). In SSL mode, the ``server_hostname`` parameter will be used for certificate validation (unless disabled in the ``ssl_options``) and SNI (if supported; requires Python 2.7.9+). Note that it is safe to call `IOStream.write <BaseIOStream.write>` while the connection is pending, in which case the data will be written as soon as the connection is ready. Calling `IOStream` read methods before the socket is connected works on some platforms but is non-portable. .. versionchanged:: 4.0 If no callback is given, returns a `.Future`. .. versionchanged:: 4.2 SSL certificates are validated by default; pass ``ssl_options=dict(cert_reqs=ssl.CERT_NONE)`` or a suitably-configured `ssl.SSLContext` to the `SSLIOStream` constructor to disable. .. versionchanged:: 6.0 The ``callback`` argument was removed. Use the returned `.Future` instead. """ self._connecting = True future = Future() # type: Future[_IOStreamType] self._connect_future = typing.cast("Future[IOStream]", future) try: self.socket.connect(address) except socket.error as e: # In non-blocking mode we expect connect() to raise an # exception with EINPROGRESS or EWOULDBLOCK. # # On freebsd, other errors such as ECONNREFUSED may be # returned immediately when attempting to connect to # localhost, so handle them the same way as an error # reported later in _handle_connect. if ( errno_from_exception(e) not in _ERRNO_INPROGRESS and errno_from_exception(e) not in _ERRNO_WOULDBLOCK ): if future is None: gen_log.warning( "Connect error on fd %s: %s", self.socket.fileno(), e ) self.close(exc_info=e) return future self._add_io_state(self.io_loop.WRITE) return future
[ "def", "connect", "(", "self", ":", "_IOStreamType", ",", "address", ":", "tuple", ",", "server_hostname", ":", "str", "=", "None", ")", "->", "\"Future[_IOStreamType]\"", ":", "self", ".", "_connecting", "=", "True", "future", "=", "Future", "(", ")", "# type: Future[_IOStreamType]", "self", ".", "_connect_future", "=", "typing", ".", "cast", "(", "\"Future[IOStream]\"", ",", "future", ")", "try", ":", "self", ".", "socket", ".", "connect", "(", "address", ")", "except", "socket", ".", "error", "as", "e", ":", "# In non-blocking mode we expect connect() to raise an", "# exception with EINPROGRESS or EWOULDBLOCK.", "#", "# On freebsd, other errors such as ECONNREFUSED may be", "# returned immediately when attempting to connect to", "# localhost, so handle them the same way as an error", "# reported later in _handle_connect.", "if", "(", "errno_from_exception", "(", "e", ")", "not", "in", "_ERRNO_INPROGRESS", "and", "errno_from_exception", "(", "e", ")", "not", "in", "_ERRNO_WOULDBLOCK", ")", ":", "if", "future", "is", "None", ":", "gen_log", ".", "warning", "(", "\"Connect error on fd %s: %s\"", ",", "self", ".", "socket", ".", "fileno", "(", ")", ",", "e", ")", "self", ".", "close", "(", "exc_info", "=", "e", ")", "return", "future", "self", ".", "_add_io_state", "(", "self", ".", "io_loop", ".", "WRITE", ")", "return", "future" ]
https://github.com/tp4a/teleport/blob/1fafd34f1f775d2cf80ea4af6e44468d8e0b24ad/server/www/packages/packages-linux/x64/tornado/iostream.py#L1175-L1246
huchunxu/ros_exploring
d09506c4dcb4487be791cceb52ba7c764e614fd8
robot_learning/tensorflow_object_detection/object_detection/core/preprocessor.py
python
random_adjust_brightness
(image, max_delta=0.2)
Randomly adjusts brightness. Makes sure the output image is still between 0 and 1. Args: image: rank 3 float32 tensor contains 1 image -> [height, width, channels] with pixel values varying between [0, 1]. max_delta: how much to change the brightness. A value between [0, 1). Returns: image: image which is the same shape as input image. boxes: boxes which is the same shape as input boxes.
Randomly adjusts brightness.
[ "Randomly", "adjusts", "brightness", "." ]
def random_adjust_brightness(image, max_delta=0.2): """Randomly adjusts brightness. Makes sure the output image is still between 0 and 1. Args: image: rank 3 float32 tensor contains 1 image -> [height, width, channels] with pixel values varying between [0, 1]. max_delta: how much to change the brightness. A value between [0, 1). Returns: image: image which is the same shape as input image. boxes: boxes which is the same shape as input boxes. """ with tf.name_scope('RandomAdjustBrightness', values=[image]): image = tf.image.random_brightness(image, max_delta) image = tf.clip_by_value(image, clip_value_min=0.0, clip_value_max=1.0) return image
[ "def", "random_adjust_brightness", "(", "image", ",", "max_delta", "=", "0.2", ")", ":", "with", "tf", ".", "name_scope", "(", "'RandomAdjustBrightness'", ",", "values", "=", "[", "image", "]", ")", ":", "image", "=", "tf", ".", "image", ".", "random_brightness", "(", "image", ",", "max_delta", ")", "image", "=", "tf", ".", "clip_by_value", "(", "image", ",", "clip_value_min", "=", "0.0", ",", "clip_value_max", "=", "1.0", ")", "return", "image" ]
https://github.com/huchunxu/ros_exploring/blob/d09506c4dcb4487be791cceb52ba7c764e614fd8/robot_learning/tensorflow_object_detection/object_detection/core/preprocessor.py#L431-L448
openstack/ceilometer
9325ae36dc9066073b79fdfbe4757b14536679c7
ceilometer/objectstore/swift.py
python
_Base._neaten_url
(endpoint, tenant_id, reseller_prefix)
return urlparse.urljoin(endpoint.split('/v1')[0].rstrip('/') + '/', 'v1/' + reseller_prefix + tenant_id)
Transform the registered url to standard and valid format.
Transform the registered url to standard and valid format.
[ "Transform", "the", "registered", "url", "to", "standard", "and", "valid", "format", "." ]
def _neaten_url(endpoint, tenant_id, reseller_prefix): """Transform the registered url to standard and valid format.""" return urlparse.urljoin(endpoint.split('/v1')[0].rstrip('/') + '/', 'v1/' + reseller_prefix + tenant_id)
[ "def", "_neaten_url", "(", "endpoint", ",", "tenant_id", ",", "reseller_prefix", ")", ":", "return", "urlparse", ".", "urljoin", "(", "endpoint", ".", "split", "(", "'/v1'", ")", "[", "0", "]", ".", "rstrip", "(", "'/'", ")", "+", "'/'", ",", "'v1/'", "+", "reseller_prefix", "+", "tenant_id", ")" ]
https://github.com/openstack/ceilometer/blob/9325ae36dc9066073b79fdfbe4757b14536679c7/ceilometer/objectstore/swift.py#L104-L107
mlflow/mlflow
364aca7daf0fcee3ec407ae0b1b16d9cb3085081
mlflow/experiments.py
python
generate_csv_with_runs
(experiment_id, filename)
Generate CSV with all runs for an experiment
Generate CSV with all runs for an experiment
[ "Generate", "CSV", "with", "all", "runs", "for", "an", "experiment" ]
def generate_csv_with_runs(experiment_id, filename): # type: (str, str) -> None """ Generate CSV with all runs for an experiment """ runs = fluent.search_runs(experiment_ids=experiment_id) if filename: runs.to_csv(filename, index=False) print( "Experiment with ID %s has been exported as a CSV to file: %s." % (experiment_id, filename) ) else: print(runs.to_csv(index=False))
[ "def", "generate_csv_with_runs", "(", "experiment_id", ",", "filename", ")", ":", "# type: (str, str) -> None", "runs", "=", "fluent", ".", "search_runs", "(", "experiment_ids", "=", "experiment_id", ")", "if", "filename", ":", "runs", ".", "to_csv", "(", "filename", ",", "index", "=", "False", ")", "print", "(", "\"Experiment with ID %s has been exported as a CSV to file: %s.\"", "%", "(", "experiment_id", ",", "filename", ")", ")", "else", ":", "print", "(", "runs", ".", "to_csv", "(", "index", "=", "False", ")", ")" ]
https://github.com/mlflow/mlflow/blob/364aca7daf0fcee3ec407ae0b1b16d9cb3085081/mlflow/experiments.py#L129-L142
DataDog/integrations-core
934674b29d94b70ccc008f76ea172d0cdae05e1e
solr/datadog_checks/solr/config_models/instance.py
python
InstanceConfig._final_validation
(cls, values)
return validation.core.finalize_config(getattr(validators, 'finalize_instance', identity)(values))
[]
def _final_validation(cls, values): return validation.core.finalize_config(getattr(validators, 'finalize_instance', identity)(values))
[ "def", "_final_validation", "(", "cls", ",", "values", ")", ":", "return", "validation", ".", "core", ".", "finalize_config", "(", "getattr", "(", "validators", ",", "'finalize_instance'", ",", "identity", ")", "(", "values", ")", ")" ]
https://github.com/DataDog/integrations-core/blob/934674b29d94b70ccc008f76ea172d0cdae05e1e/solr/datadog_checks/solr/config_models/instance.py#L70-L71
choasup/SIN
4851efb7b1c64180026e51ab8abcd95265c0602c
lib/datasets/coco.py
python
coco._load_proposals
(self, method, gt_roidb)
return self.create_roidb_from_box_list(box_list, gt_roidb)
Load pre-computed proposals in the format provided by Jan Hosang: http://www.mpi-inf.mpg.de/departments/computer-vision-and-multimodal- computing/research/object-recognition-and-scene-understanding/how- good-are-detection-proposals-really/ For MCG, use boxes from http://www.eecs.berkeley.edu/Research/Projects/ CS/vision/grouping/mcg/ and convert the file layout using lib/datasets/tools/mcg_munge.py.
Load pre-computed proposals in the format provided by Jan Hosang: http://www.mpi-inf.mpg.de/departments/computer-vision-and-multimodal- computing/research/object-recognition-and-scene-understanding/how- good-are-detection-proposals-really/ For MCG, use boxes from http://www.eecs.berkeley.edu/Research/Projects/ CS/vision/grouping/mcg/ and convert the file layout using lib/datasets/tools/mcg_munge.py.
[ "Load", "pre", "-", "computed", "proposals", "in", "the", "format", "provided", "by", "Jan", "Hosang", ":", "http", ":", "//", "www", ".", "mpi", "-", "inf", ".", "mpg", ".", "de", "/", "departments", "/", "computer", "-", "vision", "-", "and", "-", "multimodal", "-", "computing", "/", "research", "/", "object", "-", "recognition", "-", "and", "-", "scene", "-", "understanding", "/", "how", "-", "good", "-", "are", "-", "detection", "-", "proposals", "-", "really", "/", "For", "MCG", "use", "boxes", "from", "http", ":", "//", "www", ".", "eecs", ".", "berkeley", ".", "edu", "/", "Research", "/", "Projects", "/", "CS", "/", "vision", "/", "grouping", "/", "mcg", "/", "and", "convert", "the", "file", "layout", "using", "lib", "/", "datasets", "/", "tools", "/", "mcg_munge", ".", "py", "." ]
def _load_proposals(self, method, gt_roidb): """ Load pre-computed proposals in the format provided by Jan Hosang: http://www.mpi-inf.mpg.de/departments/computer-vision-and-multimodal- computing/research/object-recognition-and-scene-understanding/how- good-are-detection-proposals-really/ For MCG, use boxes from http://www.eecs.berkeley.edu/Research/Projects/ CS/vision/grouping/mcg/ and convert the file layout using lib/datasets/tools/mcg_munge.py. """ box_list = [] top_k = self.config['top_k'] valid_methods = [ 'MCG', 'selective_search', 'edge_boxes_AR', 'edge_boxes_70'] assert method in valid_methods print 'Loading {} boxes'.format(method) for i, index in enumerate(self._image_index): if i % 1000 == 0: print '{:d} / {:d}'.format(i + 1, len(self._image_index)) box_file = osp.join( cfg.DATA_DIR, 'coco_proposals', method, 'mat', self._get_box_file(index)) raw_data = sio.loadmat(box_file)['boxes'] boxes = np.maximum(raw_data - 1, 0).astype(np.uint16) if method == 'MCG': # Boxes from the MCG website are in (y1, x1, y2, x2) order boxes = boxes[:, (1, 0, 3, 2)] # Remove duplicate boxes and very small boxes and then take top k keep = ds_utils.unique_boxes(boxes) boxes = boxes[keep, :] keep = ds_utils.filter_small_boxes(boxes, self.config['min_size']) boxes = boxes[keep, :] boxes = boxes[:top_k, :] box_list.append(boxes) # Sanity check im_ann = self._COCO.loadImgs(index)[0] width = im_ann['width'] height = im_ann['height'] ds_utils.validate_boxes(boxes, width=width, height=height) return self.create_roidb_from_box_list(box_list, gt_roidb)
[ "def", "_load_proposals", "(", "self", ",", "method", ",", "gt_roidb", ")", ":", "box_list", "=", "[", "]", "top_k", "=", "self", ".", "config", "[", "'top_k'", "]", "valid_methods", "=", "[", "'MCG'", ",", "'selective_search'", ",", "'edge_boxes_AR'", ",", "'edge_boxes_70'", "]", "assert", "method", "in", "valid_methods", "print", "'Loading {} boxes'", ".", "format", "(", "method", ")", "for", "i", ",", "index", "in", "enumerate", "(", "self", ".", "_image_index", ")", ":", "if", "i", "%", "1000", "==", "0", ":", "print", "'{:d} / {:d}'", ".", "format", "(", "i", "+", "1", ",", "len", "(", "self", ".", "_image_index", ")", ")", "box_file", "=", "osp", ".", "join", "(", "cfg", ".", "DATA_DIR", ",", "'coco_proposals'", ",", "method", ",", "'mat'", ",", "self", ".", "_get_box_file", "(", "index", ")", ")", "raw_data", "=", "sio", ".", "loadmat", "(", "box_file", ")", "[", "'boxes'", "]", "boxes", "=", "np", ".", "maximum", "(", "raw_data", "-", "1", ",", "0", ")", ".", "astype", "(", "np", ".", "uint16", ")", "if", "method", "==", "'MCG'", ":", "# Boxes from the MCG website are in (y1, x1, y2, x2) order", "boxes", "=", "boxes", "[", ":", ",", "(", "1", ",", "0", ",", "3", ",", "2", ")", "]", "# Remove duplicate boxes and very small boxes and then take top k", "keep", "=", "ds_utils", ".", "unique_boxes", "(", "boxes", ")", "boxes", "=", "boxes", "[", "keep", ",", ":", "]", "keep", "=", "ds_utils", ".", "filter_small_boxes", "(", "boxes", ",", "self", ".", "config", "[", "'min_size'", "]", ")", "boxes", "=", "boxes", "[", "keep", ",", ":", "]", "boxes", "=", "boxes", "[", ":", "top_k", ",", ":", "]", "box_list", ".", "append", "(", "boxes", ")", "# Sanity check", "im_ann", "=", "self", ".", "_COCO", ".", "loadImgs", "(", "index", ")", "[", "0", "]", "width", "=", "im_ann", "[", "'width'", "]", "height", "=", "im_ann", "[", "'height'", "]", "ds_utils", ".", "validate_boxes", "(", "boxes", ",", "width", "=", "width", ",", "height", "=", "height", ")", "return", "self", ".", "create_roidb_from_box_list", "(", "box_list", ",", "gt_roidb", ")" ]
https://github.com/choasup/SIN/blob/4851efb7b1c64180026e51ab8abcd95265c0602c/lib/datasets/coco.py#L162-L207
OpenCobolIDE/OpenCobolIDE
c78d0d335378e5fe0a5e74f53c19b68b55e85388
open_cobol_ide/extlibs/pygments/lexers/templates.py
python
EvoqueXmlLexer.__init__
(self, **options)
[]
def __init__(self, **options): super(EvoqueXmlLexer, self).__init__(XmlLexer, EvoqueLexer, **options)
[ "def", "__init__", "(", "self", ",", "*", "*", "options", ")", ":", "super", "(", "EvoqueXmlLexer", ",", "self", ")", ".", "__init__", "(", "XmlLexer", ",", "EvoqueLexer", ",", "*", "*", "options", ")" ]
https://github.com/OpenCobolIDE/OpenCobolIDE/blob/c78d0d335378e5fe0a5e74f53c19b68b55e85388/open_cobol_ide/extlibs/pygments/lexers/templates.py#L1485-L1487
wbond/oscrypto
d40c62577706682a0f6da5616ad09964f1c9137d
oscrypto/_pkcs1.py
python
_mgf1
(hash_algorithm, seed, mask_length)
return output[0:mask_length]
The PKCS#1 MGF1 mask generation algorithm :param hash_algorithm: The string name of the hash algorithm to use: "sha1", "sha224", "sha256", "sha384", "sha512" :param seed: A byte string to use as the seed for the mask :param mask_length: The desired mask length, as an integer :return: A byte string of the mask
The PKCS#1 MGF1 mask generation algorithm
[ "The", "PKCS#1", "MGF1", "mask", "generation", "algorithm" ]
def _mgf1(hash_algorithm, seed, mask_length): """ The PKCS#1 MGF1 mask generation algorithm :param hash_algorithm: The string name of the hash algorithm to use: "sha1", "sha224", "sha256", "sha384", "sha512" :param seed: A byte string to use as the seed for the mask :param mask_length: The desired mask length, as an integer :return: A byte string of the mask """ if not isinstance(seed, byte_cls): raise TypeError(pretty_message( ''' seed must be a byte string, not %s ''', type_name(seed) )) if not isinstance(mask_length, int_types): raise TypeError(pretty_message( ''' mask_length must be an integer, not %s ''', type_name(mask_length) )) if mask_length < 1: raise ValueError(pretty_message( ''' mask_length must be greater than 0 - is %s ''', repr(mask_length) )) if hash_algorithm not in set(['sha1', 'sha224', 'sha256', 'sha384', 'sha512']): raise ValueError(pretty_message( ''' hash_algorithm must be one of "sha1", "sha224", "sha256", "sha384", "sha512", not %s ''', repr(hash_algorithm) )) output = b'' hash_length = { 'sha1': 20, 'sha224': 28, 'sha256': 32, 'sha384': 48, 'sha512': 64 }[hash_algorithm] iterations = int(math.ceil(mask_length / hash_length)) pack = struct.Struct(b'>I').pack hash_func = getattr(hashlib, hash_algorithm) for counter in range(0, iterations): b = pack(counter) output += hash_func(seed + b).digest() return output[0:mask_length]
[ "def", "_mgf1", "(", "hash_algorithm", ",", "seed", ",", "mask_length", ")", ":", "if", "not", "isinstance", "(", "seed", ",", "byte_cls", ")", ":", "raise", "TypeError", "(", "pretty_message", "(", "'''\n seed must be a byte string, not %s\n '''", ",", "type_name", "(", "seed", ")", ")", ")", "if", "not", "isinstance", "(", "mask_length", ",", "int_types", ")", ":", "raise", "TypeError", "(", "pretty_message", "(", "'''\n mask_length must be an integer, not %s\n '''", ",", "type_name", "(", "mask_length", ")", ")", ")", "if", "mask_length", "<", "1", ":", "raise", "ValueError", "(", "pretty_message", "(", "'''\n mask_length must be greater than 0 - is %s\n '''", ",", "repr", "(", "mask_length", ")", ")", ")", "if", "hash_algorithm", "not", "in", "set", "(", "[", "'sha1'", ",", "'sha224'", ",", "'sha256'", ",", "'sha384'", ",", "'sha512'", "]", ")", ":", "raise", "ValueError", "(", "pretty_message", "(", "'''\n hash_algorithm must be one of \"sha1\", \"sha224\", \"sha256\", \"sha384\",\n \"sha512\", not %s\n '''", ",", "repr", "(", "hash_algorithm", ")", ")", ")", "output", "=", "b''", "hash_length", "=", "{", "'sha1'", ":", "20", ",", "'sha224'", ":", "28", ",", "'sha256'", ":", "32", ",", "'sha384'", ":", "48", ",", "'sha512'", ":", "64", "}", "[", "hash_algorithm", "]", "iterations", "=", "int", "(", "math", ".", "ceil", "(", "mask_length", "/", "hash_length", ")", ")", "pack", "=", "struct", ".", "Struct", "(", "b'>I'", ")", ".", "pack", "hash_func", "=", "getattr", "(", "hashlib", ",", "hash_algorithm", ")", "for", "counter", "in", "range", "(", "0", ",", "iterations", ")", ":", "b", "=", "pack", "(", "counter", ")", "output", "+=", "hash_func", "(", "seed", "+", "b", ")", ".", "digest", "(", ")", "return", "output", "[", "0", ":", "mask_length", "]" ]
https://github.com/wbond/oscrypto/blob/d40c62577706682a0f6da5616ad09964f1c9137d/oscrypto/_pkcs1.py#L314-L384
boostorg/build
aaa95bba19a7acb07badb1929737c67583b14ba0
src/build/property_set.py
python
PropertySet.conditional
(self)
return self.conditional_
Returns conditional properties.
Returns conditional properties.
[ "Returns", "conditional", "properties", "." ]
def conditional (self): """ Returns conditional properties. """ return self.conditional_
[ "def", "conditional", "(", "self", ")", ":", "return", "self", ".", "conditional_" ]
https://github.com/boostorg/build/blob/aaa95bba19a7acb07badb1929737c67583b14ba0/src/build/property_set.py#L297-L300
tp4a/teleport
1fafd34f1f775d2cf80ea4af6e44468d8e0b24ad
server/www/packages/packages-windows/x86/pyasn1/type/univ.py
python
Real.__radd__
(self, value)
return self + value
[]
def __radd__(self, value): return self + value
[ "def", "__radd__", "(", "self", ",", "value", ")", ":", "return", "self", "+", "value" ]
https://github.com/tp4a/teleport/blob/1fafd34f1f775d2cf80ea4af6e44468d8e0b24ad/server/www/packages/packages-windows/x86/pyasn1/type/univ.py#L1419-L1420
GoogleCloudPlatform/professional-services
0c707aa97437f3d154035ef8548109b7882f71da
examples/cloudml-sentiment-analysis/scoring.py
python
run
(project, model, size, input_path, batch_size, random_seed=None)
return results
Runs prediction job on sample of labelled reviews and analyzes results. Args: project: `str`, GCP project id. model: `str`, name of Cloud ML Engine model. size: `int`, number of reviews to process. input_path: `str`, path to input data (reviews). batch_size: `int`, size of predictions batches. random_seed: `int`, random seed for sub-sample selection. Returns: Dictionary of `str` to `float` mapping metric names to the corresponding scores. Raises: ValueError: If the total number of review found don't match the number of files. ValueError: If the size of output is not greater than `0`. ValueError: If the number of predictions returned by API dont match input.
Runs prediction job on sample of labelled reviews and analyzes results.
[ "Runs", "prediction", "job", "on", "sample", "of", "labelled", "reviews", "and", "analyzes", "results", "." ]
def run(project, model, size, input_path, batch_size, random_seed=None): """Runs prediction job on sample of labelled reviews and analyzes results. Args: project: `str`, GCP project id. model: `str`, name of Cloud ML Engine model. size: `int`, number of reviews to process. input_path: `str`, path to input data (reviews). batch_size: `int`, size of predictions batches. random_seed: `int`, random seed for sub-sample selection. Returns: Dictionary of `str` to `float` mapping metric names to the corresponding scores. Raises: ValueError: If the total number of review found don't match the number of files. ValueError: If the size of output is not greater than `0`. ValueError: If the number of predictions returned by API dont match input. """ if random_seed is not None: np.random.seed(random_seed) def _get_probas(subdir): """Computes predicted probabilities from records in input directory.""" instances = format_input(os.path.join(input_path, subdir), size) # Checks that the number of records matches the number of files (expected # exactly one review per file. if len(instances) != size: raise ValueError( 'Number of reviews found dont match the number of files.') probas = collections.defaultdict(lambda: []) step = int(size / batch_size) if batch_size else size start = 0 failed_predictions = 0 while start < len(instances): to_predict = instances[start:(start+step)] try: predictions = predict_json(project, model, to_predict) except KeyboardInterrupt: raise except: # pylint: disable=bare-except logging.info('Error: %s', sys.exc_info()[0]) failed_predictions += len(to_predict) else: for pred in predictions: for proba, cl in zip(pred[_SCORES_KEY], pred[_CLASSES_KEY]): probas[cl].append(proba) start += step probas_positive = np.array(probas[str(constants.POSITIVE_SENTIMENT_LABEL)]) if not len(probas_positive): # pylint: disable=g-explicit-length-test raise ValueError('Size of output expected to be greater than `0`.') if len(probas_positive) + failed_predictions != size: raise ValueError( 'Number of predictions returned by API dont match input.') return probas_positive, failed_predictions neg_probas, neg_failed = _get_probas(constants.SUBDIR_NEGATIVE) pos_probas, pos_failed = _get_probas(constants.SUBDIR_POSITIVE) pos_label = constants.POSITIVE_SENTIMENT_LABEL neg_label = constants.NEGATIVE_SENTIMENT_LABEL target = [] for label, proba in zip([pos_label, neg_label], [pos_probas, neg_probas]): target.append(label * np.ones(proba.shape)) target = np.array(np.concatenate(target), dtype=np.int32) probas = np.concatenate([pos_probas, neg_probas]) results = analyze(probas, target) results['num_failed'] = neg_failed + pos_failed results['num_succeeded'] = len(target) return results
[ "def", "run", "(", "project", ",", "model", ",", "size", ",", "input_path", ",", "batch_size", ",", "random_seed", "=", "None", ")", ":", "if", "random_seed", "is", "not", "None", ":", "np", ".", "random", ".", "seed", "(", "random_seed", ")", "def", "_get_probas", "(", "subdir", ")", ":", "\"\"\"Computes predicted probabilities from records in input directory.\"\"\"", "instances", "=", "format_input", "(", "os", ".", "path", ".", "join", "(", "input_path", ",", "subdir", ")", ",", "size", ")", "# Checks that the number of records matches the number of files (expected", "# exactly one review per file.", "if", "len", "(", "instances", ")", "!=", "size", ":", "raise", "ValueError", "(", "'Number of reviews found dont match the number of files.'", ")", "probas", "=", "collections", ".", "defaultdict", "(", "lambda", ":", "[", "]", ")", "step", "=", "int", "(", "size", "/", "batch_size", ")", "if", "batch_size", "else", "size", "start", "=", "0", "failed_predictions", "=", "0", "while", "start", "<", "len", "(", "instances", ")", ":", "to_predict", "=", "instances", "[", "start", ":", "(", "start", "+", "step", ")", "]", "try", ":", "predictions", "=", "predict_json", "(", "project", ",", "model", ",", "to_predict", ")", "except", "KeyboardInterrupt", ":", "raise", "except", ":", "# pylint: disable=bare-except", "logging", ".", "info", "(", "'Error: %s'", ",", "sys", ".", "exc_info", "(", ")", "[", "0", "]", ")", "failed_predictions", "+=", "len", "(", "to_predict", ")", "else", ":", "for", "pred", "in", "predictions", ":", "for", "proba", ",", "cl", "in", "zip", "(", "pred", "[", "_SCORES_KEY", "]", ",", "pred", "[", "_CLASSES_KEY", "]", ")", ":", "probas", "[", "cl", "]", ".", "append", "(", "proba", ")", "start", "+=", "step", "probas_positive", "=", "np", ".", "array", "(", "probas", "[", "str", "(", "constants", ".", "POSITIVE_SENTIMENT_LABEL", ")", "]", ")", "if", "not", "len", "(", "probas_positive", ")", ":", "# pylint: disable=g-explicit-length-test", "raise", "ValueError", "(", "'Size of output expected to be greater than `0`.'", ")", "if", "len", "(", "probas_positive", ")", "+", "failed_predictions", "!=", "size", ":", "raise", "ValueError", "(", "'Number of predictions returned by API dont match input.'", ")", "return", "probas_positive", ",", "failed_predictions", "neg_probas", ",", "neg_failed", "=", "_get_probas", "(", "constants", ".", "SUBDIR_NEGATIVE", ")", "pos_probas", ",", "pos_failed", "=", "_get_probas", "(", "constants", ".", "SUBDIR_POSITIVE", ")", "pos_label", "=", "constants", ".", "POSITIVE_SENTIMENT_LABEL", "neg_label", "=", "constants", ".", "NEGATIVE_SENTIMENT_LABEL", "target", "=", "[", "]", "for", "label", ",", "proba", "in", "zip", "(", "[", "pos_label", ",", "neg_label", "]", ",", "[", "pos_probas", ",", "neg_probas", "]", ")", ":", "target", ".", "append", "(", "label", "*", "np", ".", "ones", "(", "proba", ".", "shape", ")", ")", "target", "=", "np", ".", "array", "(", "np", ".", "concatenate", "(", "target", ")", ",", "dtype", "=", "np", ".", "int32", ")", "probas", "=", "np", ".", "concatenate", "(", "[", "pos_probas", ",", "neg_probas", "]", ")", "results", "=", "analyze", "(", "probas", ",", "target", ")", "results", "[", "'num_failed'", "]", "=", "neg_failed", "+", "pos_failed", "results", "[", "'num_succeeded'", "]", "=", "len", "(", "target", ")", "return", "results" ]
https://github.com/GoogleCloudPlatform/professional-services/blob/0c707aa97437f3d154035ef8548109b7882f71da/examples/cloudml-sentiment-analysis/scoring.py#L166-L244
gwastro/pycbc
1e1c85534b9dba8488ce42df693230317ca63dea
pycbc/types/array.py
python
Array.inner
(self, other)
Return the inner product of the array with complex conjugation.
Return the inner product of the array with complex conjugation.
[ "Return", "the", "inner", "product", "of", "the", "array", "with", "complex", "conjugation", "." ]
def inner(self, other): """ Return the inner product of the array with complex conjugation. """ err_msg = "This function is a stub that should be overridden using " err_msg += "the scheme. You shouldn't be seeing this error!" raise ValueError(err_msg)
[ "def", "inner", "(", "self", ",", "other", ")", ":", "err_msg", "=", "\"This function is a stub that should be overridden using \"", "err_msg", "+=", "\"the scheme. You shouldn't be seeing this error!\"", "raise", "ValueError", "(", "err_msg", ")" ]
https://github.com/gwastro/pycbc/blob/1e1c85534b9dba8488ce42df693230317ca63dea/pycbc/types/array.py#L669-L674
Project-Platypus/Platypus
a4e56410a772798e905407e99f80d03b86296ad3
platypus/core.py
python
Generator.__init__
(self)
[]
def __init__(self): super(Generator, self).__init__()
[ "def", "__init__", "(", "self", ")", ":", "super", "(", "Generator", ",", "self", ")", ".", "__init__", "(", ")" ]
https://github.com/Project-Platypus/Platypus/blob/a4e56410a772798e905407e99f80d03b86296ad3/platypus/core.py#L214-L215
datacenter/acitoolkit
629b84887dd0f0183b81efc8adb16817f985541a
acitoolkit/aciphysobject.py
python
Linecard.__init__
(self, arg0=None, arg1=None, slot=None, parent=None)
Initialize the basic object. It will create the name of the linecard and set the type before calling the base class __init__ method. If arg1 is an instance of a Node, then pod, and node are derived from the Node and the slot_id is from arg0. If arg1 is not a Node, then arg0 is the pod, arg1 is the node id, and slot is the slot_id In other words, this Linecard object can either be initialized by `>>> lc = Linecard(slot_id, parent_switch)` or `>>> lc = Linecard(pod_id, node_id, slot_id)` or `>>> lc = Linecard(pod_id, node_id, slot_id, parent_switch)` :param arg0: pod_id if arg1 is a node_id, slot_id if arg1 is of type Node :param arg1: node_id string or parent Node of type Node :param slot: slot_id if arg1 is node_id Not required if arg1 is a Node :param parent: parent switch of type Node. Not required if arg1 is used instead. :returns: None
Initialize the basic object. It will create the name of the linecard and set the type before calling the base class __init__ method. If arg1 is an instance of a Node, then pod, and node are derived from the Node and the slot_id is from arg0. If arg1 is not a Node, then arg0 is the pod, arg1 is the node id, and slot is the slot_id
[ "Initialize", "the", "basic", "object", ".", "It", "will", "create", "the", "name", "of", "the", "linecard", "and", "set", "the", "type", "before", "calling", "the", "base", "class", "__init__", "method", ".", "If", "arg1", "is", "an", "instance", "of", "a", "Node", "then", "pod", "and", "node", "are", "derived", "from", "the", "Node", "and", "the", "slot_id", "is", "from", "arg0", ".", "If", "arg1", "is", "not", "a", "Node", "then", "arg0", "is", "the", "pod", "arg1", "is", "the", "node", "id", "and", "slot", "is", "the", "slot_id" ]
def __init__(self, arg0=None, arg1=None, slot=None, parent=None): """Initialize the basic object. It will create the name of the linecard and set the type before calling the base class __init__ method. If arg1 is an instance of a Node, then pod, and node are derived from the Node and the slot_id is from arg0. If arg1 is not a Node, then arg0 is the pod, arg1 is the node id, and slot is the slot_id In other words, this Linecard object can either be initialized by `>>> lc = Linecard(slot_id, parent_switch)` or `>>> lc = Linecard(pod_id, node_id, slot_id)` or `>>> lc = Linecard(pod_id, node_id, slot_id, parent_switch)` :param arg0: pod_id if arg1 is a node_id, slot_id if arg1 is of type Node :param arg1: node_id string or parent Node of type Node :param slot: slot_id if arg1 is node_id Not required if arg1 is a Node :param parent: parent switch of type Node. Not required if arg1 is used instead. :returns: None """ if isinstance(arg1, self._get_parent_class()): slot_id = arg0 pod = arg1.pod node = arg1.node parent = arg1 else: slot_id = slot pod = arg0 node = arg1 self.type = 'linecard' self.check_parent(parent) super(Linecard, self).__init__(pod, node, slot_id, parent) self.name = 'Lc-' + '/'.join([str(pod), str(node), str(slot_id)])
[ "def", "__init__", "(", "self", ",", "arg0", "=", "None", ",", "arg1", "=", "None", ",", "slot", "=", "None", ",", "parent", "=", "None", ")", ":", "if", "isinstance", "(", "arg1", ",", "self", ".", "_get_parent_class", "(", ")", ")", ":", "slot_id", "=", "arg0", "pod", "=", "arg1", ".", "pod", "node", "=", "arg1", ".", "node", "parent", "=", "arg1", "else", ":", "slot_id", "=", "slot", "pod", "=", "arg0", "node", "=", "arg1", "self", ".", "type", "=", "'linecard'", "self", ".", "check_parent", "(", "parent", ")", "super", "(", "Linecard", ",", "self", ")", ".", "__init__", "(", "pod", ",", "node", ",", "slot_id", ",", "parent", ")", "self", ".", "name", "=", "'Lc-'", "+", "'/'", ".", "join", "(", "[", "str", "(", "pod", ")", ",", "str", "(", "node", ")", ",", "str", "(", "slot_id", ")", "]", ")" ]
https://github.com/datacenter/acitoolkit/blob/629b84887dd0f0183b81efc8adb16817f985541a/acitoolkit/aciphysobject.py#L249-L290
emcconville/wand
03682680c351645f16c3b8ea23bde79fbb270305
wand/image.py
python
BaseImage.compression
(self)
return COMPRESSION_TYPES[compression_index]
(:class:`basestring`) The type of image compression. It's a string from :const:`COMPRESSION_TYPES` list. It also can be set. .. versionadded:: 0.3.6 .. versionchanged:: 0.5.2 Setting :attr:`compression` now sets both `image_info` and `images` in the internal image stack.
(:class:`basestring`) The type of image compression. It's a string from :const:`COMPRESSION_TYPES` list. It also can be set.
[ "(", ":", "class", ":", "basestring", ")", "The", "type", "of", "image", "compression", ".", "It", "s", "a", "string", "from", ":", "const", ":", "COMPRESSION_TYPES", "list", ".", "It", "also", "can", "be", "set", "." ]
def compression(self): """(:class:`basestring`) The type of image compression. It's a string from :const:`COMPRESSION_TYPES` list. It also can be set. .. versionadded:: 0.3.6 .. versionchanged:: 0.5.2 Setting :attr:`compression` now sets both `image_info` and `images` in the internal image stack. """ compression_index = library.MagickGetImageCompression(self.wand) return COMPRESSION_TYPES[compression_index]
[ "def", "compression", "(", "self", ")", ":", "compression_index", "=", "library", ".", "MagickGetImageCompression", "(", "self", ".", "wand", ")", "return", "COMPRESSION_TYPES", "[", "compression_index", "]" ]
https://github.com/emcconville/wand/blob/03682680c351645f16c3b8ea23bde79fbb270305/wand/image.py#L1635-L1646
krintoxi/NoobSec-Toolkit
38738541cbc03cedb9a3b3ed13b629f781ad64f6
NoobSecToolkit - MAC OSX/tools/inject/lib/core/common.py
python
arrayizeValue
(value)
return value
Makes a list out of value if it is not already a list or tuple itself >>> arrayizeValue(u'1') [u'1']
Makes a list out of value if it is not already a list or tuple itself
[ "Makes", "a", "list", "out", "of", "value", "if", "it", "is", "not", "already", "a", "list", "or", "tuple", "itself" ]
def arrayizeValue(value): """ Makes a list out of value if it is not already a list or tuple itself >>> arrayizeValue(u'1') [u'1'] """ if not isListLike(value): value = [value] return value
[ "def", "arrayizeValue", "(", "value", ")", ":", "if", "not", "isListLike", "(", "value", ")", ":", "value", "=", "[", "value", "]", "return", "value" ]
https://github.com/krintoxi/NoobSec-Toolkit/blob/38738541cbc03cedb9a3b3ed13b629f781ad64f6/NoobSecToolkit - MAC OSX/tools/inject/lib/core/common.py#L2798-L2809
aws/aws-parallelcluster
f1fe5679a01c524e7ea904c329bd6d17318c6cd9
cli/src/pcluster/models/imagebuilder.py
python
ImageBuilder.export_logs
( self, bucket: str, bucket_prefix: str = None, keep_s3_objects: bool = False, start_time: datetime = None, end_time: datetime = None, output_file: str = None, )
Export image builder's logs in the given output path, by using given bucket as a temporary folder. :param bucket: S3 bucket to be used to export cluster logs data :param bucket_prefix: Key path under which exported logs data will be stored in s3 bucket, also serves as top-level directory in resulting archive :param keep_s3_objects: Keep the exported objects exports to S3. The default behavior is to delete them :param start_time: Start time of interval of interest for log events. ISO 8601 format: YYYY-MM-DDThh:mm:ssTZD :param end_time: End time of interval of interest for log events. ISO 8601 format: YYYY-MM-DDThh:mm:ssTZD
Export image builder's logs in the given output path, by using given bucket as a temporary folder.
[ "Export", "image", "builder", "s", "logs", "in", "the", "given", "output", "path", "by", "using", "given", "bucket", "as", "a", "temporary", "folder", "." ]
def export_logs( self, bucket: str, bucket_prefix: str = None, keep_s3_objects: bool = False, start_time: datetime = None, end_time: datetime = None, output_file: str = None, ): """ Export image builder's logs in the given output path, by using given bucket as a temporary folder. :param bucket: S3 bucket to be used to export cluster logs data :param bucket_prefix: Key path under which exported logs data will be stored in s3 bucket, also serves as top-level directory in resulting archive :param keep_s3_objects: Keep the exported objects exports to S3. The default behavior is to delete them :param start_time: Start time of interval of interest for log events. ISO 8601 format: YYYY-MM-DDThh:mm:ssTZD :param end_time: End time of interval of interest for log events. ISO 8601 format: YYYY-MM-DDThh:mm:ssTZD """ # check stack stack_exists = self._stack_exists() if not stack_exists: LOGGER.debug("CloudFormation Stack for Image %s does not exist.", self.image_id) try: with tempfile.TemporaryDirectory() as output_tempdir: # Create root folder for the archive archive_name = f"{self.image_id}-logs-{datetime.now().strftime('%Y%m%d%H%M')}" root_archive_dir = os.path.join(output_tempdir, archive_name) os.makedirs(root_archive_dir, exist_ok=True) if AWSApi.instance().logs.log_group_exists(self._log_group_name): # Export logs from CloudWatch export_logs_filters = self._init_export_logs_filters(start_time, end_time) logs_exporter = CloudWatchLogsExporter( resource_id=self.image_id, log_group_name=self._log_group_name, bucket=bucket, output_dir=root_archive_dir, bucket_prefix=bucket_prefix, keep_s3_objects=keep_s3_objects, ) logs_exporter.execute( start_time=export_logs_filters.start_time, end_time=export_logs_filters.end_time ) else: LOGGER.info( "Log streams not yet available for %s, only CFN Stack events will be exported.", {self.image_id} ) if stack_exists: # Get stack events and write them into a file stack_events_file = os.path.join(root_archive_dir, self._stack_events_stream_name) export_stack_events(self.stack.name, stack_events_file) archive_path = create_logs_archive(root_archive_dir, output_file) if output_file: return output_file else: s3_path = upload_archive(bucket, bucket_prefix, archive_path) return create_s3_presigned_url(s3_path) except Exception as e: raise ImageBuilderActionError(f"Unexpected error when exporting image's logs: {e}")
[ "def", "export_logs", "(", "self", ",", "bucket", ":", "str", ",", "bucket_prefix", ":", "str", "=", "None", ",", "keep_s3_objects", ":", "bool", "=", "False", ",", "start_time", ":", "datetime", "=", "None", ",", "end_time", ":", "datetime", "=", "None", ",", "output_file", ":", "str", "=", "None", ",", ")", ":", "# check stack", "stack_exists", "=", "self", ".", "_stack_exists", "(", ")", "if", "not", "stack_exists", ":", "LOGGER", ".", "debug", "(", "\"CloudFormation Stack for Image %s does not exist.\"", ",", "self", ".", "image_id", ")", "try", ":", "with", "tempfile", ".", "TemporaryDirectory", "(", ")", "as", "output_tempdir", ":", "# Create root folder for the archive", "archive_name", "=", "f\"{self.image_id}-logs-{datetime.now().strftime('%Y%m%d%H%M')}\"", "root_archive_dir", "=", "os", ".", "path", ".", "join", "(", "output_tempdir", ",", "archive_name", ")", "os", ".", "makedirs", "(", "root_archive_dir", ",", "exist_ok", "=", "True", ")", "if", "AWSApi", ".", "instance", "(", ")", ".", "logs", ".", "log_group_exists", "(", "self", ".", "_log_group_name", ")", ":", "# Export logs from CloudWatch", "export_logs_filters", "=", "self", ".", "_init_export_logs_filters", "(", "start_time", ",", "end_time", ")", "logs_exporter", "=", "CloudWatchLogsExporter", "(", "resource_id", "=", "self", ".", "image_id", ",", "log_group_name", "=", "self", ".", "_log_group_name", ",", "bucket", "=", "bucket", ",", "output_dir", "=", "root_archive_dir", ",", "bucket_prefix", "=", "bucket_prefix", ",", "keep_s3_objects", "=", "keep_s3_objects", ",", ")", "logs_exporter", ".", "execute", "(", "start_time", "=", "export_logs_filters", ".", "start_time", ",", "end_time", "=", "export_logs_filters", ".", "end_time", ")", "else", ":", "LOGGER", ".", "info", "(", "\"Log streams not yet available for %s, only CFN Stack events will be exported.\"", ",", "{", "self", ".", "image_id", "}", ")", "if", "stack_exists", ":", "# Get stack events and write them into a file", "stack_events_file", "=", "os", ".", "path", ".", "join", "(", "root_archive_dir", ",", "self", ".", "_stack_events_stream_name", ")", "export_stack_events", "(", "self", ".", "stack", ".", "name", ",", "stack_events_file", ")", "archive_path", "=", "create_logs_archive", "(", "root_archive_dir", ",", "output_file", ")", "if", "output_file", ":", "return", "output_file", "else", ":", "s3_path", "=", "upload_archive", "(", "bucket", ",", "bucket_prefix", ",", "archive_path", ")", "return", "create_s3_presigned_url", "(", "s3_path", ")", "except", "Exception", "as", "e", ":", "raise", "ImageBuilderActionError", "(", "f\"Unexpected error when exporting image's logs: {e}\"", ")" ]
https://github.com/aws/aws-parallelcluster/blob/f1fe5679a01c524e7ea904c329bd6d17318c6cd9/cli/src/pcluster/models/imagebuilder.py#L672-L734
scrapy/scrapy
b04cfa48328d5d5749dca6f50fa34e0cfc664c89
scrapy/core/scraper.py
python
Scraper.handle_spider_error
(self, _failure: Failure, request: Request, response: Response, spider: Spider)
[]
def handle_spider_error(self, _failure: Failure, request: Request, response: Response, spider: Spider) -> None: exc = _failure.value if isinstance(exc, CloseSpider): self.crawler.engine.close_spider(spider, exc.reason or 'cancelled') return logkws = self.logformatter.spider_error(_failure, request, response, spider) logger.log( *logformatter_adapter(logkws), exc_info=failure_to_exc_info(_failure), extra={'spider': spider} ) self.signals.send_catch_log( signal=signals.spider_error, failure=_failure, response=response, spider=spider ) self.crawler.stats.inc_value( f"spider_exceptions/{_failure.value.__class__.__name__}", spider=spider )
[ "def", "handle_spider_error", "(", "self", ",", "_failure", ":", "Failure", ",", "request", ":", "Request", ",", "response", ":", "Response", ",", "spider", ":", "Spider", ")", "->", "None", ":", "exc", "=", "_failure", ".", "value", "if", "isinstance", "(", "exc", ",", "CloseSpider", ")", ":", "self", ".", "crawler", ".", "engine", ".", "close_spider", "(", "spider", ",", "exc", ".", "reason", "or", "'cancelled'", ")", "return", "logkws", "=", "self", ".", "logformatter", ".", "spider_error", "(", "_failure", ",", "request", ",", "response", ",", "spider", ")", "logger", ".", "log", "(", "*", "logformatter_adapter", "(", "logkws", ")", ",", "exc_info", "=", "failure_to_exc_info", "(", "_failure", ")", ",", "extra", "=", "{", "'spider'", ":", "spider", "}", ")", "self", ".", "signals", ".", "send_catch_log", "(", "signal", "=", "signals", ".", "spider_error", ",", "failure", "=", "_failure", ",", "response", "=", "response", ",", "spider", "=", "spider", ")", "self", ".", "crawler", ".", "stats", ".", "inc_value", "(", "f\"spider_exceptions/{_failure.value.__class__.__name__}\"", ",", "spider", "=", "spider", ")" ]
https://github.com/scrapy/scrapy/blob/b04cfa48328d5d5749dca6f50fa34e0cfc664c89/scrapy/core/scraper.py#L167-L186
scipopt/PySCIPOpt
31527a80d8d0c2b706a26b34d93602aeea5f785f
examples/unfinished/staff_sched_mo.py
python
staff_mo
(I,T,N,J,S,c,b)
return model
staff: staff scheduling Parameters: - I: set of members in the staff - T: number of periods in a cycle - N: number of working periods required for staff's elements in a cycle - J: set of shifts in each period (shift 0 == rest) - S: subset of shifts that must be kept at least consecutive days - c[i,t,j]: cost of a shit j of staff's element i on period t - b[t,j]: number of staff elements required in period t, shift j Returns a model with no objective function.
staff: staff scheduling Parameters: - I: set of members in the staff - T: number of periods in a cycle - N: number of working periods required for staff's elements in a cycle - J: set of shifts in each period (shift 0 == rest) - S: subset of shifts that must be kept at least consecutive days - c[i,t,j]: cost of a shit j of staff's element i on period t - b[t,j]: number of staff elements required in period t, shift j Returns a model with no objective function.
[ "staff", ":", "staff", "scheduling", "Parameters", ":", "-", "I", ":", "set", "of", "members", "in", "the", "staff", "-", "T", ":", "number", "of", "periods", "in", "a", "cycle", "-", "N", ":", "number", "of", "working", "periods", "required", "for", "staff", "s", "elements", "in", "a", "cycle", "-", "J", ":", "set", "of", "shifts", "in", "each", "period", "(", "shift", "0", "==", "rest", ")", "-", "S", ":", "subset", "of", "shifts", "that", "must", "be", "kept", "at", "least", "consecutive", "days", "-", "c", "[", "i", "t", "j", "]", ":", "cost", "of", "a", "shit", "j", "of", "staff", "s", "element", "i", "on", "period", "t", "-", "b", "[", "t", "j", "]", ":", "number", "of", "staff", "elements", "required", "in", "period", "t", "shift", "j", "Returns", "a", "model", "with", "no", "objective", "function", "." ]
def staff_mo(I,T,N,J,S,c,b): """ staff: staff scheduling Parameters: - I: set of members in the staff - T: number of periods in a cycle - N: number of working periods required for staff's elements in a cycle - J: set of shifts in each period (shift 0 == rest) - S: subset of shifts that must be kept at least consecutive days - c[i,t,j]: cost of a shit j of staff's element i on period t - b[t,j]: number of staff elements required in period t, shift j Returns a model with no objective function. """ Ts = range(1,T+1) model = Model("staff scheduling -- multiobjective version") x,y = {},{} for t in Ts: for j in J: for i in I: x[i,t,j] = model.addVar(vtype="B", name="x(%s,%s,%s)" % (i,t,j)) y[t,j] = model.addVar(vtype="C", name="y(%s,%s)" % (t,j)) C = model.addVar(vtype="C", name="cost") U = model.addVar(vtype="C", name="uncovered") model.addCons(C >= quicksum(c[i,t,j]*x[i,t,j] for i in I for t in Ts for j in J if j != 0), "Cost") model.addCons(U >= quicksum(y[t,j] for t in Ts for j in J if j != 0), "Uncovered") for t in Ts: for j in J: if j == 0: continue model.addCons(quicksum(x[i,t,j] for i in I) >= b[t,j] - y[t,j], "Cover(%s,%s)" % (t,j)) for i in I: model.addCons(quicksum(x[i,t,j] for t in Ts for j in J if j != 0) == N, "Work(%s)"%i) for t in Ts: model.addCons(quicksum(x[i,t,j] for j in J) == 1, "Assign(%s,%s)" % (i,t)) for j in J: if j != 0: model.addCons(x[i,t,j] + quicksum(x[i,t,k] for k in J if k != j and k != 0) <= 1,\ "Require(%s,%s,%s)" % (i,t,j)) for t in range(2,T): for j in S: model.addCons(x[i,t-1,j] + x[i,t+1,j] >= x[i,t,j], "SameShift(%s,%s,%s)" % (i,t,j)) model.data = x,y,C,U return model
[ "def", "staff_mo", "(", "I", ",", "T", ",", "N", ",", "J", ",", "S", ",", "c", ",", "b", ")", ":", "Ts", "=", "range", "(", "1", ",", "T", "+", "1", ")", "model", "=", "Model", "(", "\"staff scheduling -- multiobjective version\"", ")", "x", ",", "y", "=", "{", "}", ",", "{", "}", "for", "t", "in", "Ts", ":", "for", "j", "in", "J", ":", "for", "i", "in", "I", ":", "x", "[", "i", ",", "t", ",", "j", "]", "=", "model", ".", "addVar", "(", "vtype", "=", "\"B\"", ",", "name", "=", "\"x(%s,%s,%s)\"", "%", "(", "i", ",", "t", ",", "j", ")", ")", "y", "[", "t", ",", "j", "]", "=", "model", ".", "addVar", "(", "vtype", "=", "\"C\"", ",", "name", "=", "\"y(%s,%s)\"", "%", "(", "t", ",", "j", ")", ")", "C", "=", "model", ".", "addVar", "(", "vtype", "=", "\"C\"", ",", "name", "=", "\"cost\"", ")", "U", "=", "model", ".", "addVar", "(", "vtype", "=", "\"C\"", ",", "name", "=", "\"uncovered\"", ")", "model", ".", "addCons", "(", "C", ">=", "quicksum", "(", "c", "[", "i", ",", "t", ",", "j", "]", "*", "x", "[", "i", ",", "t", ",", "j", "]", "for", "i", "in", "I", "for", "t", "in", "Ts", "for", "j", "in", "J", "if", "j", "!=", "0", ")", ",", "\"Cost\"", ")", "model", ".", "addCons", "(", "U", ">=", "quicksum", "(", "y", "[", "t", ",", "j", "]", "for", "t", "in", "Ts", "for", "j", "in", "J", "if", "j", "!=", "0", ")", ",", "\"Uncovered\"", ")", "for", "t", "in", "Ts", ":", "for", "j", "in", "J", ":", "if", "j", "==", "0", ":", "continue", "model", ".", "addCons", "(", "quicksum", "(", "x", "[", "i", ",", "t", ",", "j", "]", "for", "i", "in", "I", ")", ">=", "b", "[", "t", ",", "j", "]", "-", "y", "[", "t", ",", "j", "]", ",", "\"Cover(%s,%s)\"", "%", "(", "t", ",", "j", ")", ")", "for", "i", "in", "I", ":", "model", ".", "addCons", "(", "quicksum", "(", "x", "[", "i", ",", "t", ",", "j", "]", "for", "t", "in", "Ts", "for", "j", "in", "J", "if", "j", "!=", "0", ")", "==", "N", ",", "\"Work(%s)\"", "%", "i", ")", "for", "t", "in", "Ts", ":", "model", ".", "addCons", "(", "quicksum", "(", "x", "[", "i", ",", "t", ",", "j", "]", "for", "j", "in", "J", ")", "==", "1", ",", "\"Assign(%s,%s)\"", "%", "(", "i", ",", "t", ")", ")", "for", "j", "in", "J", ":", "if", "j", "!=", "0", ":", "model", ".", "addCons", "(", "x", "[", "i", ",", "t", ",", "j", "]", "+", "quicksum", "(", "x", "[", "i", ",", "t", ",", "k", "]", "for", "k", "in", "J", "if", "k", "!=", "j", "and", "k", "!=", "0", ")", "<=", "1", ",", "\"Require(%s,%s,%s)\"", "%", "(", "i", ",", "t", ",", "j", ")", ")", "for", "t", "in", "range", "(", "2", ",", "T", ")", ":", "for", "j", "in", "S", ":", "model", ".", "addCons", "(", "x", "[", "i", ",", "t", "-", "1", ",", "j", "]", "+", "x", "[", "i", ",", "t", "+", "1", ",", "j", "]", ">=", "x", "[", "i", ",", "t", ",", "j", "]", ",", "\"SameShift(%s,%s,%s)\"", "%", "(", "i", ",", "t", ",", "j", ")", ")", "model", ".", "data", "=", "x", ",", "y", ",", "C", ",", "U", "return", "model" ]
https://github.com/scipopt/PySCIPOpt/blob/31527a80d8d0c2b706a26b34d93602aeea5f785f/examples/unfinished/staff_sched_mo.py#L13-L62
natewong1313/bird-bot
0a76dca2157c021c6cd5734928b1ffcf46a2b3b2
sites/bestbuy.py
python
BestBuy.__init__
(self,task_id,status_signal,image_signal,product,profile,proxy,monitor_delay,error_delay)
[]
def __init__(self,task_id,status_signal,image_signal,product,profile,proxy,monitor_delay,error_delay): self.status_signal,self.image_signal,self.product,self.profile,self.monitor_delay,self.error_delay = status_signal,image_signal,product,profile,float(monitor_delay),float(error_delay) self.session = requests.Session() if proxy != False: self.session.proxies.update(proxy) self.status_signal.emit({"msg":"Starting","status":"normal"}) tas_data = self.get_tas_data() product_image = self.monitor() self.atc() self.start_checkout() self.submit_shipping() self.submit_payment(tas_data) while True: success,jwt = self.submit_order() if not success and jwt != None: transaction_id = self.handle_3dsecure(jwt) self.submit_card(transaction_id) else: if success: send_webhook("OP","Bestbuy",self.profile["profile_name"],task_id,product_image) else: if settings.browser_on_failed: self.status_signal.emit({"msg":"Browser Ready","status":"alt","url":"https://www.bestbuy.com/checkout/r/fulfillment","cookies":[{"name":cookie.name,"value":cookie.value,"domain":cookie.domain} for cookie in self.session.cookies]}) send_webhook("B","Bestbuy",self.profile["profile_name"],task_id,product_image) else: send_webhook("PF","Bestbuy",self.profile["profile_name"],task_id,product_image) break
[ "def", "__init__", "(", "self", ",", "task_id", ",", "status_signal", ",", "image_signal", ",", "product", ",", "profile", ",", "proxy", ",", "monitor_delay", ",", "error_delay", ")", ":", "self", ".", "status_signal", ",", "self", ".", "image_signal", ",", "self", ".", "product", ",", "self", ".", "profile", ",", "self", ".", "monitor_delay", ",", "self", ".", "error_delay", "=", "status_signal", ",", "image_signal", ",", "product", ",", "profile", ",", "float", "(", "monitor_delay", ")", ",", "float", "(", "error_delay", ")", "self", ".", "session", "=", "requests", ".", "Session", "(", ")", "if", "proxy", "!=", "False", ":", "self", ".", "session", ".", "proxies", ".", "update", "(", "proxy", ")", "self", ".", "status_signal", ".", "emit", "(", "{", "\"msg\"", ":", "\"Starting\"", ",", "\"status\"", ":", "\"normal\"", "}", ")", "tas_data", "=", "self", ".", "get_tas_data", "(", ")", "product_image", "=", "self", ".", "monitor", "(", ")", "self", ".", "atc", "(", ")", "self", ".", "start_checkout", "(", ")", "self", ".", "submit_shipping", "(", ")", "self", ".", "submit_payment", "(", "tas_data", ")", "while", "True", ":", "success", ",", "jwt", "=", "self", ".", "submit_order", "(", ")", "if", "not", "success", "and", "jwt", "!=", "None", ":", "transaction_id", "=", "self", ".", "handle_3dsecure", "(", "jwt", ")", "self", ".", "submit_card", "(", "transaction_id", ")", "else", ":", "if", "success", ":", "send_webhook", "(", "\"OP\"", ",", "\"Bestbuy\"", ",", "self", ".", "profile", "[", "\"profile_name\"", "]", ",", "task_id", ",", "product_image", ")", "else", ":", "if", "settings", ".", "browser_on_failed", ":", "self", ".", "status_signal", ".", "emit", "(", "{", "\"msg\"", ":", "\"Browser Ready\"", ",", "\"status\"", ":", "\"alt\"", ",", "\"url\"", ":", "\"https://www.bestbuy.com/checkout/r/fulfillment\"", ",", "\"cookies\"", ":", "[", "{", "\"name\"", ":", "cookie", ".", "name", ",", "\"value\"", ":", "cookie", ".", "value", ",", "\"domain\"", ":", "cookie", ".", "domain", "}", "for", "cookie", "in", "self", ".", "session", ".", "cookies", "]", "}", ")", "send_webhook", "(", "\"B\"", ",", "\"Bestbuy\"", ",", "self", ".", "profile", "[", "\"profile_name\"", "]", ",", "task_id", ",", "product_image", ")", "else", ":", "send_webhook", "(", "\"PF\"", ",", "\"Bestbuy\"", ",", "self", ".", "profile", "[", "\"profile_name\"", "]", ",", "task_id", ",", "product_image", ")", "break" ]
https://github.com/natewong1313/bird-bot/blob/0a76dca2157c021c6cd5734928b1ffcf46a2b3b2/sites/bestbuy.py#L12-L38
cagbal/ros_people_object_detection_tensorflow
982ffd4a54b8059638f5cd4aa167299c7fc9e61f
src/action_recognition.py
python
ActionRecognitionNode.__init__
(self)
[]
def __init__(self): super(ActionRecognitionNode, self).__init__() # init the node rospy.init_node('action_recognition_node', anonymous=False) # Get the parameters (image_topic, output_topic, recognition_interval, buffer_size) \ = self.get_parameters() self._bridge = CvBridge() # Advertise the result of Action Recognition self.pub_rec = rospy.Publisher(output_topic, \ ActionRecognitionmsg, queue_size=1) # This amount of break will be given between each prediction self.recognition_interval = recognition_interval # Counter for number of frames self.frame_count = 0 # frame buffer size self.buffer_size = buffer_size # Frame buffer self.frame_buffer = [] # Get the labels self.labels = self.initialize_database() # Create the graph object self._graph = tf.Graph() # Initialite the model self.initialize_model() self.sub_image =rospy.Subscriber(image_topic, Image, self.rgb_callback) # spin rospy.spin()
[ "def", "__init__", "(", "self", ")", ":", "super", "(", "ActionRecognitionNode", ",", "self", ")", ".", "__init__", "(", ")", "# init the node", "rospy", ".", "init_node", "(", "'action_recognition_node'", ",", "anonymous", "=", "False", ")", "# Get the parameters", "(", "image_topic", ",", "output_topic", ",", "recognition_interval", ",", "buffer_size", ")", "=", "self", ".", "get_parameters", "(", ")", "self", ".", "_bridge", "=", "CvBridge", "(", ")", "# Advertise the result of Action Recognition", "self", ".", "pub_rec", "=", "rospy", ".", "Publisher", "(", "output_topic", ",", "ActionRecognitionmsg", ",", "queue_size", "=", "1", ")", "# This amount of break will be given between each prediction", "self", ".", "recognition_interval", "=", "recognition_interval", "# Counter for number of frames", "self", ".", "frame_count", "=", "0", "# frame buffer size", "self", ".", "buffer_size", "=", "buffer_size", "# Frame buffer", "self", ".", "frame_buffer", "=", "[", "]", "# Get the labels", "self", ".", "labels", "=", "self", ".", "initialize_database", "(", ")", "# Create the graph object", "self", ".", "_graph", "=", "tf", ".", "Graph", "(", ")", "# Initialite the model", "self", ".", "initialize_model", "(", ")", "self", ".", "sub_image", "=", "rospy", ".", "Subscriber", "(", "image_topic", ",", "Image", ",", "self", ".", "rgb_callback", ")", "# spin", "rospy", ".", "spin", "(", ")" ]
https://github.com/cagbal/ros_people_object_detection_tensorflow/blob/982ffd4a54b8059638f5cd4aa167299c7fc9e61f/src/action_recognition.py#L43-L84
hyperledger/aries-cloudagent-python
2f36776e99f6053ae92eed8123b5b1b2e891c02a
aries_cloudagent/protocols/connections/v1_0/models/connection_detail.py
python
ConnectionDetail.did_doc
(self)
return self._did_doc
Accessor for the connection DID Document. Returns: The DIDDoc for this connection
Accessor for the connection DID Document.
[ "Accessor", "for", "the", "connection", "DID", "Document", "." ]
def did_doc(self) -> DIDDoc: """ Accessor for the connection DID Document. Returns: The DIDDoc for this connection """ return self._did_doc
[ "def", "did_doc", "(", "self", ")", "->", "DIDDoc", ":", "return", "self", ".", "_did_doc" ]
https://github.com/hyperledger/aries-cloudagent-python/blob/2f36776e99f6053ae92eed8123b5b1b2e891c02a/aries_cloudagent/protocols/connections/v1_0/models/connection_detail.py#L73-L81
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_flaskbb/Python-2.7.9/Tools/bgen/bgen/bgenObjectDefinition.py
python
ObjectDefinition.outputSetattr
(self)
[]
def outputSetattr(self): Output() Output("#define %s_setattr NULL", self.prefix)
[ "def", "outputSetattr", "(", "self", ")", ":", "Output", "(", ")", "Output", "(", "\"#define %s_setattr NULL\"", ",", "self", ".", "prefix", ")" ]
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_flaskbb/Python-2.7.9/Tools/bgen/bgen/bgenObjectDefinition.py#L173-L175
maas/maas
db2f89970c640758a51247c59bf1ec6f60cf4ab5
src/maasserver/models/tag.py
python
Tag.save
(self, *args, populate=True, **kwargs)
Save this tag. :param populate: Whether or not to call `populate_nodes` if the definition has changed.
Save this tag.
[ "Save", "this", "tag", "." ]
def save(self, *args, populate=True, **kwargs): """Save this tag. :param populate: Whether or not to call `populate_nodes` if the definition has changed. """ super().save(*args, **kwargs) if populate and (self.definition != self._original_definition): self.populate_nodes() self._original_definition = self.definition
[ "def", "save", "(", "self", ",", "*", "args", ",", "populate", "=", "True", ",", "*", "*", "kwargs", ")", ":", "super", "(", ")", ".", "save", "(", "*", "args", ",", "*", "*", "kwargs", ")", "if", "populate", "and", "(", "self", ".", "definition", "!=", "self", ".", "_original_definition", ")", ":", "self", ".", "populate_nodes", "(", ")", "self", ".", "_original_definition", "=", "self", ".", "definition" ]
https://github.com/maas/maas/blob/db2f89970c640758a51247c59bf1ec6f60cf4ab5/src/maasserver/models/tag.py#L141-L150
oracle/oci-python-sdk
3c1604e4e212008fb6718e2f68cdb5ef71fd5793
src/oci/_vendor/urllib3/_collections.py
python
RecentlyUsedContainer.__delitem__
(self, key)
[]
def __delitem__(self, key): with self.lock: value = self._container.pop(key) if self.dispose_func: self.dispose_func(value)
[ "def", "__delitem__", "(", "self", ",", "key", ")", ":", "with", "self", ".", "lock", ":", "value", "=", "self", ".", "_container", ".", "pop", "(", "key", ")", "if", "self", ".", "dispose_func", ":", "self", ".", "dispose_func", "(", "value", ")" ]
https://github.com/oracle/oci-python-sdk/blob/3c1604e4e212008fb6718e2f68cdb5ef71fd5793/src/oci/_vendor/urllib3/_collections.py#L81-L86
coddingtonbear/jirafs
ad8daffe054a24b58c0fb1cd249dcbb96cd9ed90
jirafs/migrations.py
python
migration_0017
(repo, init=False, **kwargs)
Set initial branch name if not set.
Set initial branch name if not set.
[ "Set", "initial", "branch", "name", "if", "not", "set", "." ]
def migration_0017(repo, init=False, **kwargs): """Set initial branch name if not set.""" repo.run_git_command("config", "init.defaultBranch", "master") set_repo_version(repo, 17)
[ "def", "migration_0017", "(", "repo", ",", "init", "=", "False", ",", "*", "*", "kwargs", ")", ":", "repo", ".", "run_git_command", "(", "\"config\"", ",", "\"init.defaultBranch\"", ",", "\"master\"", ")", "set_repo_version", "(", "repo", ",", "17", ")" ]
https://github.com/coddingtonbear/jirafs/blob/ad8daffe054a24b58c0fb1cd249dcbb96cd9ed90/jirafs/migrations.py#L407-L410
pytransitions/transitions
9663094f4566c016b11563e7a7d6d3802593845c
transitions/extensions/nesting.py
python
HierarchicalMachine.get_global_name
(self, state=None, join=True)
return self.state_cls.separator.join(domains) if join else domains
[]
def get_global_name(self, state=None, join=True): domains = copy.copy(self.prefix_path) if state: state_name = state.name if hasattr(state, 'name') else state if state_name in self.states: domains.append(state_name) else: raise ValueError("State '{0}' not found in local states.".format(state)) return self.state_cls.separator.join(domains) if join else domains
[ "def", "get_global_name", "(", "self", ",", "state", "=", "None", ",", "join", "=", "True", ")", ":", "domains", "=", "copy", ".", "copy", "(", "self", ".", "prefix_path", ")", "if", "state", ":", "state_name", "=", "state", ".", "name", "if", "hasattr", "(", "state", ",", "'name'", ")", "else", "state", "if", "state_name", "in", "self", ".", "states", ":", "domains", ".", "append", "(", "state_name", ")", "else", ":", "raise", "ValueError", "(", "\"State '{0}' not found in local states.\"", ".", "format", "(", "state", ")", ")", "return", "self", ".", "state_cls", ".", "separator", ".", "join", "(", "domains", ")", "if", "join", "else", "domains" ]
https://github.com/pytransitions/transitions/blob/9663094f4566c016b11563e7a7d6d3802593845c/transitions/extensions/nesting.py#L618-L626
celery/celery
95015a1d5a60d94d8e1e02da4b9cf16416c747e2
celery/utils/functional.py
python
seq_concat_item
(seq, item)
return seq + (item,) if isinstance(seq, tuple) else seq + [item]
Return copy of sequence seq with item added. Returns: Sequence: if seq is a tuple, the result will be a tuple, otherwise it depends on the implementation of ``__add__``.
Return copy of sequence seq with item added.
[ "Return", "copy", "of", "sequence", "seq", "with", "item", "added", "." ]
def seq_concat_item(seq, item): """Return copy of sequence seq with item added. Returns: Sequence: if seq is a tuple, the result will be a tuple, otherwise it depends on the implementation of ``__add__``. """ return seq + (item,) if isinstance(seq, tuple) else seq + [item]
[ "def", "seq_concat_item", "(", "seq", ",", "item", ")", ":", "return", "seq", "+", "(", "item", ",", ")", "if", "isinstance", "(", "seq", ",", "tuple", ")", "else", "seq", "+", "[", "item", "]" ]
https://github.com/celery/celery/blob/95015a1d5a60d94d8e1e02da4b9cf16416c747e2/celery/utils/functional.py#L367-L374
pantsbuild/pex
473c6ac732ed4bc338b4b20a9ec930d1d722c9b4
pex/vendor/_vendored/setuptools/setuptools/command/easy_install.py
python
easy_install._fix_install_dir_for_user_site
(self)
Fix the install_dir if "--user" was used.
Fix the install_dir if "--user" was used.
[ "Fix", "the", "install_dir", "if", "--", "user", "was", "used", "." ]
def _fix_install_dir_for_user_site(self): """ Fix the install_dir if "--user" was used. """ if not self.user or not site.ENABLE_USER_SITE: return self.create_home_path() if self.install_userbase is None: msg = "User base directory is not specified" raise DistutilsPlatformError(msg) self.install_base = self.install_platbase = self.install_userbase scheme_name = os.name.replace('posix', 'unix') + '_user' self.select_scheme(scheme_name)
[ "def", "_fix_install_dir_for_user_site", "(", "self", ")", ":", "if", "not", "self", ".", "user", "or", "not", "site", ".", "ENABLE_USER_SITE", ":", "return", "self", ".", "create_home_path", "(", ")", "if", "self", ".", "install_userbase", "is", "None", ":", "msg", "=", "\"User base directory is not specified\"", "raise", "DistutilsPlatformError", "(", "msg", ")", "self", ".", "install_base", "=", "self", ".", "install_platbase", "=", "self", ".", "install_userbase", "scheme_name", "=", "os", ".", "name", ".", "replace", "(", "'posix'", ",", "'unix'", ")", "+", "'_user'", "self", ".", "select_scheme", "(", "scheme_name", ")" ]
https://github.com/pantsbuild/pex/blob/473c6ac732ed4bc338b4b20a9ec930d1d722c9b4/pex/vendor/_vendored/setuptools/setuptools/command/easy_install.py#L431-L444
linxid/Machine_Learning_Study_Path
558e82d13237114bbb8152483977806fc0c222af
Machine Learning In Action/Chapter4-NaiveBayes/venv/Lib/site-packages/pip/_vendor/packaging/version.py
python
LegacyVersion.local
(self)
return None
[]
def local(self): return None
[ "def", "local", "(", "self", ")", ":", "return", "None" ]
https://github.com/linxid/Machine_Learning_Study_Path/blob/558e82d13237114bbb8152483977806fc0c222af/Machine Learning In Action/Chapter4-NaiveBayes/venv/Lib/site-packages/pip/_vendor/packaging/version.py#L93-L94
buke/GreenOdoo
3d8c55d426fb41fdb3f2f5a1533cfe05983ba1df
runtime/python/lib/python2.7/site-packages/psycopg2/extras.py
python
register_composite
(name, conn_or_curs, globally=False, factory=None)
return caster
Register a typecaster to convert a composite type into a tuple. :param name: the name of a PostgreSQL composite type, e.g. created using the |CREATE TYPE|_ command :param conn_or_curs: a connection or cursor used to find the type oid and components; the typecaster is registered in a scope limited to this object, unless *globally* is set to `!True` :param globally: if `!False` (default) register the typecaster only on *conn_or_curs*, otherwise register it globally :param factory: if specified it should be a `CompositeCaster` subclass: use it to :ref:`customize how to cast composite types <custom-composite>` :return: the registered `CompositeCaster` or *factory* instance responsible for the conversion
Register a typecaster to convert a composite type into a tuple.
[ "Register", "a", "typecaster", "to", "convert", "a", "composite", "type", "into", "a", "tuple", "." ]
def register_composite(name, conn_or_curs, globally=False, factory=None): """Register a typecaster to convert a composite type into a tuple. :param name: the name of a PostgreSQL composite type, e.g. created using the |CREATE TYPE|_ command :param conn_or_curs: a connection or cursor used to find the type oid and components; the typecaster is registered in a scope limited to this object, unless *globally* is set to `!True` :param globally: if `!False` (default) register the typecaster only on *conn_or_curs*, otherwise register it globally :param factory: if specified it should be a `CompositeCaster` subclass: use it to :ref:`customize how to cast composite types <custom-composite>` :return: the registered `CompositeCaster` or *factory* instance responsible for the conversion """ if factory is None: factory = CompositeCaster caster = factory._from_db(name, conn_or_curs) _ext.register_type(caster.typecaster, not globally and conn_or_curs or None) if caster.array_typecaster is not None: _ext.register_type(caster.array_typecaster, not globally and conn_or_curs or None) return caster
[ "def", "register_composite", "(", "name", ",", "conn_or_curs", ",", "globally", "=", "False", ",", "factory", "=", "None", ")", ":", "if", "factory", "is", "None", ":", "factory", "=", "CompositeCaster", "caster", "=", "factory", ".", "_from_db", "(", "name", ",", "conn_or_curs", ")", "_ext", ".", "register_type", "(", "caster", ".", "typecaster", ",", "not", "globally", "and", "conn_or_curs", "or", "None", ")", "if", "caster", ".", "array_typecaster", "is", "not", "None", ":", "_ext", ".", "register_type", "(", "caster", ".", "array_typecaster", ",", "not", "globally", "and", "conn_or_curs", "or", "None", ")", "return", "caster" ]
https://github.com/buke/GreenOdoo/blob/3d8c55d426fb41fdb3f2f5a1533cfe05983ba1df/runtime/python/lib/python2.7/site-packages/psycopg2/extras.py#L940-L964
deanishe/alfred-vpn-manager
f5d0dd1433ea69b1517d4866a12b1118097057b9
src/vpn.py
python
VPNApp.filter_connections
(self, name=None, active=True)
return connections
Return connections with matching name and state.
Return connections with matching name and state.
[ "Return", "connections", "with", "matching", "name", "and", "state", "." ]
def filter_connections(self, name=None, active=True): """Return connections with matching name and state.""" connections = self.connections if name: connections = [c for c in connections if c.name == name] if active: connections = [c for c in connections if c.active] else: connections = [c for c in connections if not c.active] return connections
[ "def", "filter_connections", "(", "self", ",", "name", "=", "None", ",", "active", "=", "True", ")", ":", "connections", "=", "self", ".", "connections", "if", "name", ":", "connections", "=", "[", "c", "for", "c", "in", "connections", "if", "c", ".", "name", "==", "name", "]", "if", "active", ":", "connections", "=", "[", "c", "for", "c", "in", "connections", "if", "c", ".", "active", "]", "else", ":", "connections", "=", "[", "c", "for", "c", "in", "connections", "if", "not", "c", ".", "active", "]", "return", "connections" ]
https://github.com/deanishe/alfred-vpn-manager/blob/f5d0dd1433ea69b1517d4866a12b1118097057b9/src/vpn.py#L165-L175
reahl/reahl
86aac47c3a9b5b98e9f77dad4939034a02d54d46
reahl-sqlalchemysupport/reahl/sqlalchemysupport/sqlalchemysupport.py
python
pk_name
(table_name)
return 'pk_%s' % table_name
Returns the name that will be used in the database for a primary key, given: :arg table_name: The name of the table to which the primary key belongs.
Returns the name that will be used in the database for a primary key, given:
[ "Returns", "the", "name", "that", "will", "be", "used", "in", "the", "database", "for", "a", "primary", "key", "given", ":" ]
def pk_name(table_name): """Returns the name that will be used in the database for a primary key, given: :arg table_name: The name of the table to which the primary key belongs. """ return 'pk_%s' % table_name
[ "def", "pk_name", "(", "table_name", ")", ":", "return", "'pk_%s'", "%", "table_name" ]
https://github.com/reahl/reahl/blob/86aac47c3a9b5b98e9f77dad4939034a02d54d46/reahl-sqlalchemysupport/reahl/sqlalchemysupport/sqlalchemysupport.py#L86-L91
lovelylain/pyctp
fd304de4b50c4ddc31a4190b1caaeb5dec66bc5d
futures2/ctp/ApiStruct.py
python
CombinationLeg.__init__
(self, CombInstrumentID='', LegID=0, LegInstrumentID='', Direction=D_Buy, LegMultiple=0, ImplyLevel=0)
[]
def __init__(self, CombInstrumentID='', LegID=0, LegInstrumentID='', Direction=D_Buy, LegMultiple=0, ImplyLevel=0): self.CombInstrumentID = 'InstrumentID' #组合合约代码, char[31] self.LegID = '' #单腿编号, int self.LegInstrumentID = 'InstrumentID' #单腿合约代码, char[31] self.Direction = '' #买卖方向, char self.LegMultiple = '' #单腿乘数, int self.ImplyLevel = ''
[ "def", "__init__", "(", "self", ",", "CombInstrumentID", "=", "''", ",", "LegID", "=", "0", ",", "LegInstrumentID", "=", "''", ",", "Direction", "=", "D_Buy", ",", "LegMultiple", "=", "0", ",", "ImplyLevel", "=", "0", ")", ":", "self", ".", "CombInstrumentID", "=", "'InstrumentID'", "#组合合约代码, char[31]", "self", ".", "LegID", "=", "''", "#单腿编号, int", "self", ".", "LegInstrumentID", "=", "'InstrumentID'", "#单腿合约代码, char[31]", "self", ".", "Direction", "=", "''", "#买卖方向, char", "self", ".", "LegMultiple", "=", "''", "#单腿乘数, int", "self", ".", "ImplyLevel", "=", "''" ]
https://github.com/lovelylain/pyctp/blob/fd304de4b50c4ddc31a4190b1caaeb5dec66bc5d/futures2/ctp/ApiStruct.py#L4261-L4267
jython/jython3
def4f8ec47cb7a9c799ea4c745f12badf92c5769
lib-python/3.5.1/distutils/dist.py
python
Distribution.print_commands
(self)
Print out a help message listing all available commands with a description of each. The list is divided into "standard commands" (listed in distutils.command.__all__) and "extra commands" (mentioned in self.cmdclass, but not a standard command). The descriptions come from the command class attribute 'description'.
Print out a help message listing all available commands with a description of each. The list is divided into "standard commands" (listed in distutils.command.__all__) and "extra commands" (mentioned in self.cmdclass, but not a standard command). The descriptions come from the command class attribute 'description'.
[ "Print", "out", "a", "help", "message", "listing", "all", "available", "commands", "with", "a", "description", "of", "each", ".", "The", "list", "is", "divided", "into", "standard", "commands", "(", "listed", "in", "distutils", ".", "command", ".", "__all__", ")", "and", "extra", "commands", "(", "mentioned", "in", "self", ".", "cmdclass", "but", "not", "a", "standard", "command", ")", ".", "The", "descriptions", "come", "from", "the", "command", "class", "attribute", "description", "." ]
def print_commands(self): """Print out a help message listing all available commands with a description of each. The list is divided into "standard commands" (listed in distutils.command.__all__) and "extra commands" (mentioned in self.cmdclass, but not a standard command). The descriptions come from the command class attribute 'description'. """ import distutils.command std_commands = distutils.command.__all__ is_std = {} for cmd in std_commands: is_std[cmd] = 1 extra_commands = [] for cmd in self.cmdclass.keys(): if not is_std.get(cmd): extra_commands.append(cmd) max_length = 0 for cmd in (std_commands + extra_commands): if len(cmd) > max_length: max_length = len(cmd) self.print_command_list(std_commands, "Standard commands", max_length) if extra_commands: print() self.print_command_list(extra_commands, "Extra commands", max_length)
[ "def", "print_commands", "(", "self", ")", ":", "import", "distutils", ".", "command", "std_commands", "=", "distutils", ".", "command", ".", "__all__", "is_std", "=", "{", "}", "for", "cmd", "in", "std_commands", ":", "is_std", "[", "cmd", "]", "=", "1", "extra_commands", "=", "[", "]", "for", "cmd", "in", "self", ".", "cmdclass", ".", "keys", "(", ")", ":", "if", "not", "is_std", ".", "get", "(", "cmd", ")", ":", "extra_commands", ".", "append", "(", "cmd", ")", "max_length", "=", "0", "for", "cmd", "in", "(", "std_commands", "+", "extra_commands", ")", ":", "if", "len", "(", "cmd", ")", ">", "max_length", ":", "max_length", "=", "len", "(", "cmd", ")", "self", ".", "print_command_list", "(", "std_commands", ",", "\"Standard commands\"", ",", "max_length", ")", "if", "extra_commands", ":", "print", "(", ")", "self", ".", "print_command_list", "(", "extra_commands", ",", "\"Extra commands\"", ",", "max_length", ")" ]
https://github.com/jython/jython3/blob/def4f8ec47cb7a9c799ea4c745f12badf92c5769/lib-python/3.5.1/distutils/dist.py#L717-L748
khanhnamle1994/natural-language-processing
01d450d5ac002b0156ef4cf93a07cb508c1bcdc5
assignment1/.env/lib/python2.7/site-packages/pkg_resources/__init__.py
python
Distribution.clone
(self, **kw)
return self.__class__(**kw)
Copy this distribution, substituting in any changed keyword args
Copy this distribution, substituting in any changed keyword args
[ "Copy", "this", "distribution", "substituting", "in", "any", "changed", "keyword", "args" ]
def clone(self, **kw): """Copy this distribution, substituting in any changed keyword args""" names = 'project_name version py_version platform location precedence' for attr in names.split(): kw.setdefault(attr, getattr(self, attr, None)) kw.setdefault('metadata', self._provider) return self.__class__(**kw)
[ "def", "clone", "(", "self", ",", "*", "*", "kw", ")", ":", "names", "=", "'project_name version py_version platform location precedence'", "for", "attr", "in", "names", ".", "split", "(", ")", ":", "kw", ".", "setdefault", "(", "attr", ",", "getattr", "(", "self", ",", "attr", ",", "None", ")", ")", "kw", ".", "setdefault", "(", "'metadata'", ",", "self", ".", "_provider", ")", "return", "self", ".", "__class__", "(", "*", "*", "kw", ")" ]
https://github.com/khanhnamle1994/natural-language-processing/blob/01d450d5ac002b0156ef4cf93a07cb508c1bcdc5/assignment1/.env/lib/python2.7/site-packages/pkg_resources/__init__.py#L2871-L2877
tp4a/teleport
1fafd34f1f775d2cf80ea4af6e44468d8e0b24ad
server/www/packages/packages-darwin/x64/pyasn1/type/univ.py
python
ObjectIdentifier.__radd__
(self, other)
return self.clone(other + self._value)
[]
def __radd__(self, other): return self.clone(other + self._value)
[ "def", "__radd__", "(", "self", ",", "other", ")", ":", "return", "self", ".", "clone", "(", "other", "+", "self", ".", "_value", ")" ]
https://github.com/tp4a/teleport/blob/1fafd34f1f775d2cf80ea4af6e44468d8e0b24ad/server/www/packages/packages-darwin/x64/pyasn1/type/univ.py#L1139-L1140
pymedusa/Medusa
1405fbb6eb8ef4d20fcca24c32ddca52b11f0f38
lib/pkg_resources/_vendor/packaging/specifiers.py
python
BaseSpecifier.__str__
(self)
Returns the str representation of this Specifier like object. This should be representative of the Specifier itself.
Returns the str representation of this Specifier like object. This should be representative of the Specifier itself.
[ "Returns", "the", "str", "representation", "of", "this", "Specifier", "like", "object", ".", "This", "should", "be", "representative", "of", "the", "Specifier", "itself", "." ]
def __str__(self) -> str: """ Returns the str representation of this Specifier like object. This should be representative of the Specifier itself. """
[ "def", "__str__", "(", "self", ")", "->", "str", ":" ]
https://github.com/pymedusa/Medusa/blob/1405fbb6eb8ef4d20fcca24c32ddca52b11f0f38/lib/pkg_resources/_vendor/packaging/specifiers.py#L41-L45
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_hxb2/lib/python3.5/site-packages/django/db/backends/mysql/base.py
python
DatabaseWrapper.is_usable
(self)
[]
def is_usable(self): try: self.connection.ping() except Database.Error: return False else: return True
[ "def", "is_usable", "(", "self", ")", ":", "try", ":", "self", ".", "connection", ".", "ping", "(", ")", "except", "Database", ".", "Error", ":", "return", "False", "else", ":", "return", "True" ]
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_hxb2/lib/python3.5/site-packages/django/db/backends/mysql/base.py#L357-L363
khanhnamle1994/natural-language-processing
01d450d5ac002b0156ef4cf93a07cb508c1bcdc5
assignment1/.env/lib/python2.7/site-packages/numpy/polynomial/hermite_e.py
python
hermeval2d
(x, y, c)
return c
Evaluate a 2-D HermiteE series at points (x, y). This function returns the values: .. math:: p(x,y) = \\sum_{i,j} c_{i,j} * He_i(x) * He_j(y) The parameters `x` and `y` are converted to arrays only if they are tuples or a lists, otherwise they are treated as a scalars and they must have the same shape after conversion. In either case, either `x` and `y` or their elements must support multiplication and addition both with themselves and with the elements of `c`. If `c` is a 1-D array a one is implicitly appended to its shape to make it 2-D. The shape of the result will be c.shape[2:] + x.shape. Parameters ---------- x, y : array_like, compatible objects The two dimensional series is evaluated at the points `(x, y)`, where `x` and `y` must have the same shape. If `x` or `y` is a list or tuple, it is first converted to an ndarray, otherwise it is left unchanged and if it isn't an ndarray it is treated as a scalar. c : array_like Array of coefficients ordered so that the coefficient of the term of multi-degree i,j is contained in ``c[i,j]``. If `c` has dimension greater than two the remaining indices enumerate multiple sets of coefficients. Returns ------- values : ndarray, compatible object The values of the two dimensional polynomial at points formed with pairs of corresponding values from `x` and `y`. See Also -------- hermeval, hermegrid2d, hermeval3d, hermegrid3d Notes ----- .. versionadded::1.7.0
Evaluate a 2-D HermiteE series at points (x, y).
[ "Evaluate", "a", "2", "-", "D", "HermiteE", "series", "at", "points", "(", "x", "y", ")", "." ]
def hermeval2d(x, y, c): """ Evaluate a 2-D HermiteE series at points (x, y). This function returns the values: .. math:: p(x,y) = \\sum_{i,j} c_{i,j} * He_i(x) * He_j(y) The parameters `x` and `y` are converted to arrays only if they are tuples or a lists, otherwise they are treated as a scalars and they must have the same shape after conversion. In either case, either `x` and `y` or their elements must support multiplication and addition both with themselves and with the elements of `c`. If `c` is a 1-D array a one is implicitly appended to its shape to make it 2-D. The shape of the result will be c.shape[2:] + x.shape. Parameters ---------- x, y : array_like, compatible objects The two dimensional series is evaluated at the points `(x, y)`, where `x` and `y` must have the same shape. If `x` or `y` is a list or tuple, it is first converted to an ndarray, otherwise it is left unchanged and if it isn't an ndarray it is treated as a scalar. c : array_like Array of coefficients ordered so that the coefficient of the term of multi-degree i,j is contained in ``c[i,j]``. If `c` has dimension greater than two the remaining indices enumerate multiple sets of coefficients. Returns ------- values : ndarray, compatible object The values of the two dimensional polynomial at points formed with pairs of corresponding values from `x` and `y`. See Also -------- hermeval, hermegrid2d, hermeval3d, hermegrid3d Notes ----- .. versionadded::1.7.0 """ try: x, y = np.array((x, y), copy=0) except: raise ValueError('x, y are incompatible') c = hermeval(x, c) c = hermeval(y, c, tensor=False) return c
[ "def", "hermeval2d", "(", "x", ",", "y", ",", "c", ")", ":", "try", ":", "x", ",", "y", "=", "np", ".", "array", "(", "(", "x", ",", "y", ")", ",", "copy", "=", "0", ")", "except", ":", "raise", "ValueError", "(", "'x, y are incompatible'", ")", "c", "=", "hermeval", "(", "x", ",", "c", ")", "c", "=", "hermeval", "(", "y", ",", "c", ",", "tensor", "=", "False", ")", "return", "c" ]
https://github.com/khanhnamle1994/natural-language-processing/blob/01d450d5ac002b0156ef4cf93a07cb508c1bcdc5/assignment1/.env/lib/python2.7/site-packages/numpy/polynomial/hermite_e.py#L946-L999
llSourcell/AI_Artist
3038c06c2e389b9c919c881c9a169efe2fd7810e
lib/python2.7/site-packages/pip/_vendor/pkg_resources/__init__.py
python
_SetuptoolsVersionMixin.__lt__
(self, other)
[]
def __lt__(self, other): if isinstance(other, tuple): return tuple(self) < other else: return super(_SetuptoolsVersionMixin, self).__lt__(other)
[ "def", "__lt__", "(", "self", ",", "other", ")", ":", "if", "isinstance", "(", "other", ",", "tuple", ")", ":", "return", "tuple", "(", "self", ")", "<", "other", "else", ":", "return", "super", "(", "_SetuptoolsVersionMixin", ",", "self", ")", ".", "__lt__", "(", "other", ")" ]
https://github.com/llSourcell/AI_Artist/blob/3038c06c2e389b9c919c881c9a169efe2fd7810e/lib/python2.7/site-packages/pip/_vendor/pkg_resources/__init__.py#L100-L104
gammapy/gammapy
735b25cd5bbed35e2004d633621896dcd5295e8b
gammapy/maps/hpx/geom.py
python
HpxGeom._create_lookup
(self, region)
Create local-to-global pixel lookup table.
Create local-to-global pixel lookup table.
[ "Create", "local", "-", "to", "-", "global", "pixel", "lookup", "table", "." ]
def _create_lookup(self, region): """Create local-to-global pixel lookup table.""" if isinstance(region, str): ipix = [ self.get_index_list(nside, self._nest, region) for nside in self._nside.flat ] self._ipix = [ ravel_hpx_index((p, i * np.ones_like(p)), np.ravel(self.npix_max)) for i, p in enumerate(ipix) ] self._region = region self._indxschm = "EXPLICIT" self._npix = np.array([len(t) for t in self._ipix]) if self.nside.ndim > 1: self._npix = self._npix.reshape(self.nside.shape) self._ipix = np.concatenate(self._ipix) elif isinstance(region, tuple): region = [np.asarray(t) for t in region] m = np.any(np.stack([t >= 0 for t in region]), axis=0) region = [t[m] for t in region] self._ipix = ravel_hpx_index(region, self.npix_max) self._ipix = np.unique(self._ipix) region = unravel_hpx_index(self._ipix, self.npix_max) self._region = "explicit" self._indxschm = "EXPLICIT" if len(region) == 1: self._npix = np.array([len(region[0])]) else: self._npix = np.zeros(self.shape_axes, dtype=int) idx = np.ravel_multi_index(region[1:], self.shape_axes) cnt = np.unique(idx, return_counts=True) self._npix.flat[cnt[0]] = cnt[1] elif region is None: self._region = None self._indxschm = "IMPLICIT" self._npix = self.npix_max else: raise ValueError(f"Invalid region string: {region!r}")
[ "def", "_create_lookup", "(", "self", ",", "region", ")", ":", "if", "isinstance", "(", "region", ",", "str", ")", ":", "ipix", "=", "[", "self", ".", "get_index_list", "(", "nside", ",", "self", ".", "_nest", ",", "region", ")", "for", "nside", "in", "self", ".", "_nside", ".", "flat", "]", "self", ".", "_ipix", "=", "[", "ravel_hpx_index", "(", "(", "p", ",", "i", "*", "np", ".", "ones_like", "(", "p", ")", ")", ",", "np", ".", "ravel", "(", "self", ".", "npix_max", ")", ")", "for", "i", ",", "p", "in", "enumerate", "(", "ipix", ")", "]", "self", ".", "_region", "=", "region", "self", ".", "_indxschm", "=", "\"EXPLICIT\"", "self", ".", "_npix", "=", "np", ".", "array", "(", "[", "len", "(", "t", ")", "for", "t", "in", "self", ".", "_ipix", "]", ")", "if", "self", ".", "nside", ".", "ndim", ">", "1", ":", "self", ".", "_npix", "=", "self", ".", "_npix", ".", "reshape", "(", "self", ".", "nside", ".", "shape", ")", "self", ".", "_ipix", "=", "np", ".", "concatenate", "(", "self", ".", "_ipix", ")", "elif", "isinstance", "(", "region", ",", "tuple", ")", ":", "region", "=", "[", "np", ".", "asarray", "(", "t", ")", "for", "t", "in", "region", "]", "m", "=", "np", ".", "any", "(", "np", ".", "stack", "(", "[", "t", ">=", "0", "for", "t", "in", "region", "]", ")", ",", "axis", "=", "0", ")", "region", "=", "[", "t", "[", "m", "]", "for", "t", "in", "region", "]", "self", ".", "_ipix", "=", "ravel_hpx_index", "(", "region", ",", "self", ".", "npix_max", ")", "self", ".", "_ipix", "=", "np", ".", "unique", "(", "self", ".", "_ipix", ")", "region", "=", "unravel_hpx_index", "(", "self", ".", "_ipix", ",", "self", ".", "npix_max", ")", "self", ".", "_region", "=", "\"explicit\"", "self", ".", "_indxschm", "=", "\"EXPLICIT\"", "if", "len", "(", "region", ")", "==", "1", ":", "self", ".", "_npix", "=", "np", ".", "array", "(", "[", "len", "(", "region", "[", "0", "]", ")", "]", ")", "else", ":", "self", ".", "_npix", "=", "np", ".", "zeros", "(", "self", ".", "shape_axes", ",", "dtype", "=", "int", ")", "idx", "=", "np", ".", "ravel_multi_index", "(", "region", "[", "1", ":", "]", ",", "self", ".", "shape_axes", ")", "cnt", "=", "np", ".", "unique", "(", "idx", ",", "return_counts", "=", "True", ")", "self", ".", "_npix", ".", "flat", "[", "cnt", "[", "0", "]", "]", "=", "cnt", "[", "1", "]", "elif", "region", "is", "None", ":", "self", ".", "_region", "=", "None", "self", ".", "_indxschm", "=", "\"IMPLICIT\"", "self", ".", "_npix", "=", "self", ".", "npix_max", "else", ":", "raise", "ValueError", "(", "f\"Invalid region string: {region!r}\"", ")" ]
https://github.com/gammapy/gammapy/blob/735b25cd5bbed35e2004d633621896dcd5295e8b/gammapy/maps/hpx/geom.py#L94-L137
ericgazoni/openpyxl
c55988e4904d4337ce4c35ab8b7dc305bca9de23
openpyxl/worksheet/worksheet.py
python
Worksheet.title
(self, value)
Set a sheet title, ensuring it is valid. Limited to 31 characters, no special characters.
Set a sheet title, ensuring it is valid. Limited to 31 characters, no special characters.
[ "Set", "a", "sheet", "title", "ensuring", "it", "is", "valid", ".", "Limited", "to", "31", "characters", "no", "special", "characters", "." ]
def title(self, value): """Set a sheet title, ensuring it is valid. Limited to 31 characters, no special characters.""" if self.bad_title_char_re.search(value): msg = 'Invalid character found in sheet title' raise SheetTitleException(msg) value = self.unique_sheet_name(value) if len(value) > 31: msg = 'Maximum 31 characters allowed in sheet title' raise SheetTitleException(msg) self._title = value
[ "def", "title", "(", "self", ",", "value", ")", ":", "if", "self", ".", "bad_title_char_re", ".", "search", "(", "value", ")", ":", "msg", "=", "'Invalid character found in sheet title'", "raise", "SheetTitleException", "(", "msg", ")", "value", "=", "self", ".", "unique_sheet_name", "(", "value", ")", "if", "len", "(", "value", ")", ">", "31", ":", "msg", "=", "'Maximum 31 characters allowed in sheet title'", "raise", "SheetTitleException", "(", "msg", ")", "self", ".", "_title", "=", "value" ]
https://github.com/ericgazoni/openpyxl/blob/c55988e4904d4337ce4c35ab8b7dc305bca9de23/openpyxl/worksheet/worksheet.py#L183-L193
mesalock-linux/mesapy
ed546d59a21b36feb93e2309d5c6b75aa0ad95c9
lib-python/2.7/zipfile.py
python
ZipFile.extractall
(self, path=None, members=None, pwd=None)
Extract all members from the archive to the current working directory. `path' specifies a different directory to extract to. `members' is optional and must be a subset of the list returned by namelist().
Extract all members from the archive to the current working directory. `path' specifies a different directory to extract to. `members' is optional and must be a subset of the list returned by namelist().
[ "Extract", "all", "members", "from", "the", "archive", "to", "the", "current", "working", "directory", ".", "path", "specifies", "a", "different", "directory", "to", "extract", "to", ".", "members", "is", "optional", "and", "must", "be", "a", "subset", "of", "the", "list", "returned", "by", "namelist", "()", "." ]
def extractall(self, path=None, members=None, pwd=None): """Extract all members from the archive to the current working directory. `path' specifies a different directory to extract to. `members' is optional and must be a subset of the list returned by namelist(). """ if members is None: members = self.namelist() for zipinfo in members: self.extract(zipinfo, path, pwd)
[ "def", "extractall", "(", "self", ",", "path", "=", "None", ",", "members", "=", "None", ",", "pwd", "=", "None", ")", ":", "if", "members", "is", "None", ":", "members", "=", "self", ".", "namelist", "(", ")", "for", "zipinfo", "in", "members", ":", "self", ".", "extract", "(", "zipinfo", ",", "path", ",", "pwd", ")" ]
https://github.com/mesalock-linux/mesapy/blob/ed546d59a21b36feb93e2309d5c6b75aa0ad95c9/lib-python/2.7/zipfile.py#L1038-L1048
tdamdouni/Pythonista
3e082d53b6b9b501a3c8cf3251a8ad4c8be9c2ad
scenes/mydirectory.py
python
dir_contents
(path)
return files, folders
get all dirs and files from path
get all dirs and files from path
[ "get", "all", "dirs", "and", "files", "from", "path" ]
def dir_contents(path): """get all dirs and files from path""" try: contents = listdir(path) except: print('***ERROR with ', path) sys.exit() # print(contents) # tmp = [isfile(path + "\\" + el) for el in contents] # print(tmp) files = [] folders = [] for i, item in enumerate(contents): if isfile(path+sep+contents[i]): files += [item] elif isdir(path+sep+contents[i]): folders += [item] return files, folders
[ "def", "dir_contents", "(", "path", ")", ":", "try", ":", "contents", "=", "listdir", "(", "path", ")", "except", ":", "print", "(", "'***ERROR with '", ",", "path", ")", "sys", ".", "exit", "(", ")", "#\tprint(contents)", "#\ttmp = [isfile(path + \"\\\\\" + el) for el in contents]", "#\tprint(tmp)", "files", "=", "[", "]", "folders", "=", "[", "]", "for", "i", ",", "item", "in", "enumerate", "(", "contents", ")", ":", "if", "isfile", "(", "path", "+", "sep", "+", "contents", "[", "i", "]", ")", ":", "files", "+=", "[", "item", "]", "elif", "isdir", "(", "path", "+", "sep", "+", "contents", "[", "i", "]", ")", ":", "folders", "+=", "[", "item", "]", "return", "files", ",", "folders" ]
https://github.com/tdamdouni/Pythonista/blob/3e082d53b6b9b501a3c8cf3251a8ad4c8be9c2ad/scenes/mydirectory.py#L14-L31
jtpereyda/boofuzz
64badab7257117bcadab35e903d723223dde9203
boofuzz/ifuzz_logger.py
python
IFuzzLogger.log_check
(self, description)
Records a check on the system under test. AKA "instrumentation check." :param description: Received data. :type description: str :return: None :rtype: None
Records a check on the system under test. AKA "instrumentation check."
[ "Records", "a", "check", "on", "the", "system", "under", "test", ".", "AKA", "instrumentation", "check", "." ]
def log_check(self, description): """ Records a check on the system under test. AKA "instrumentation check." :param description: Received data. :type description: str :return: None :rtype: None """ raise NotImplementedError
[ "def", "log_check", "(", "self", ",", "description", ")", ":", "raise", "NotImplementedError" ]
https://github.com/jtpereyda/boofuzz/blob/64badab7257117bcadab35e903d723223dde9203/boofuzz/ifuzz_logger.py#L113-L123
twisted/twisted
dee676b040dd38b847ea6fb112a712cb5e119490
src/twisted/mail/interfaces.py
python
IDomain.exists
(user)
Check whether a user exists in this domain. @type user: L{User} @param user: A user. @rtype: no-argument callable which returns L{IMessageSMTP} provider @return: A function which takes no arguments and returns a message receiver for the user. @raise SMTPBadRcpt: When the given user does not exist in this domain.
Check whether a user exists in this domain.
[ "Check", "whether", "a", "user", "exists", "in", "this", "domain", "." ]
def exists(user): """ Check whether a user exists in this domain. @type user: L{User} @param user: A user. @rtype: no-argument callable which returns L{IMessageSMTP} provider @return: A function which takes no arguments and returns a message receiver for the user. @raise SMTPBadRcpt: When the given user does not exist in this domain. """
[ "def", "exists", "(", "user", ")", ":" ]
https://github.com/twisted/twisted/blob/dee676b040dd38b847ea6fb112a712cb5e119490/src/twisted/mail/interfaces.py#L223-L235
getpatchwork/patchwork
60a7b11d12f9e1a6bd08d787d37066c8d89a52ae
patchwork/api/__init__.py
python
_get_attribute
(self, instance)
return relationship.all() if hasattr(relationship, 'all') else relationship
[]
def _get_attribute(self, instance): # Can't have any relationships if not created if hasattr(instance, 'pk') and instance.pk is None: return [] try: relationship = get_attribute(instance, self.source_attrs) except (KeyError, AttributeError) as exc: if self.default is not empty: return self.get_default() if self.allow_null: return None if not self.required: raise SkipField() msg = ( 'Got {exc_type} when attempting to get a value for field ' '`{field}` on serializer `{serializer}`.\nThe serializer ' 'field might be named incorrectly and not match ' 'any attribute or key on the `{instance}` instance.\n' 'Original exception text was: {exc}.'.format( exc_type=type(exc).__name__, field=self.field_name, serializer=self.parent.__class__.__name__, instance=instance.__class__.__name__, exc=exc ) ) raise type(exc)(msg) return relationship.all() if hasattr(relationship, 'all') else relationship
[ "def", "_get_attribute", "(", "self", ",", "instance", ")", ":", "# Can't have any relationships if not created", "if", "hasattr", "(", "instance", ",", "'pk'", ")", "and", "instance", ".", "pk", "is", "None", ":", "return", "[", "]", "try", ":", "relationship", "=", "get_attribute", "(", "instance", ",", "self", ".", "source_attrs", ")", "except", "(", "KeyError", ",", "AttributeError", ")", "as", "exc", ":", "if", "self", ".", "default", "is", "not", "empty", ":", "return", "self", ".", "get_default", "(", ")", "if", "self", ".", "allow_null", ":", "return", "None", "if", "not", "self", ".", "required", ":", "raise", "SkipField", "(", ")", "msg", "=", "(", "'Got {exc_type} when attempting to get a value for field '", "'`{field}` on serializer `{serializer}`.\\nThe serializer '", "'field might be named incorrectly and not match '", "'any attribute or key on the `{instance}` instance.\\n'", "'Original exception text was: {exc}.'", ".", "format", "(", "exc_type", "=", "type", "(", "exc", ")", ".", "__name__", ",", "field", "=", "self", ".", "field_name", ",", "serializer", "=", "self", ".", "parent", ".", "__class__", ".", "__name__", ",", "instance", "=", "instance", ".", "__class__", ".", "__name__", ",", "exc", "=", "exc", ")", ")", "raise", "type", "(", "exc", ")", "(", "msg", ")", "return", "relationship", ".", "all", "(", ")", "if", "hasattr", "(", "relationship", ",", "'all'", ")", "else", "relationship" ]
https://github.com/getpatchwork/patchwork/blob/60a7b11d12f9e1a6bd08d787d37066c8d89a52ae/patchwork/api/__init__.py#L18-L47
borgbase/vorta
23c47673c009bdef8baebb0b9cdf5e78c07fe373
src/vorta/utils.py
python
get_directory_size
(dir_path, exclude_patterns_re)
return data_size_filtered, files_count_filtered
Get number of files only and total size in bytes from a path. Based off https://stackoverflow.com/a/17936789
Get number of files only and total size in bytes from a path. Based off https://stackoverflow.com/a/17936789
[ "Get", "number", "of", "files", "only", "and", "total", "size", "in", "bytes", "from", "a", "path", ".", "Based", "off", "https", ":", "//", "stackoverflow", ".", "com", "/", "a", "/", "17936789" ]
def get_directory_size(dir_path, exclude_patterns_re): ''' Get number of files only and total size in bytes from a path. Based off https://stackoverflow.com/a/17936789 ''' data_size_filtered = 0 seen = set() seen_filtered = set() for curr_path, _, file_names in os.walk(dir_path): for file_name in file_names: file_path = os.path.join(curr_path, file_name) # Ignore symbolic links, since borg doesn't follow them if os.path.islink(file_path): continue is_excluded = False for pattern in exclude_patterns_re: if re.match(pattern, file_path) is not None: is_excluded = True break try: stat = os.stat(file_path) if stat.st_ino not in seen: # Visit each file only once seen.add(stat.st_ino) if not is_excluded: data_size_filtered += stat.st_size seen_filtered.add(stat.st_ino) except (FileNotFoundError, PermissionError): continue files_count_filtered = len(seen_filtered) return data_size_filtered, files_count_filtered
[ "def", "get_directory_size", "(", "dir_path", ",", "exclude_patterns_re", ")", ":", "data_size_filtered", "=", "0", "seen", "=", "set", "(", ")", "seen_filtered", "=", "set", "(", ")", "for", "curr_path", ",", "_", ",", "file_names", "in", "os", ".", "walk", "(", "dir_path", ")", ":", "for", "file_name", "in", "file_names", ":", "file_path", "=", "os", ".", "path", ".", "join", "(", "curr_path", ",", "file_name", ")", "# Ignore symbolic links, since borg doesn't follow them", "if", "os", ".", "path", ".", "islink", "(", "file_path", ")", ":", "continue", "is_excluded", "=", "False", "for", "pattern", "in", "exclude_patterns_re", ":", "if", "re", ".", "match", "(", "pattern", ",", "file_path", ")", "is", "not", "None", ":", "is_excluded", "=", "True", "break", "try", ":", "stat", "=", "os", ".", "stat", "(", "file_path", ")", "if", "stat", ".", "st_ino", "not", "in", "seen", ":", "# Visit each file only once", "seen", ".", "add", "(", "stat", ".", "st_ino", ")", "if", "not", "is_excluded", ":", "data_size_filtered", "+=", "stat", ".", "st_size", "seen_filtered", ".", "add", "(", "stat", ".", "st_ino", ")", "except", "(", "FileNotFoundError", ",", "PermissionError", ")", ":", "continue", "files_count_filtered", "=", "len", "(", "seen_filtered", ")", "return", "data_size_filtered", ",", "files_count_filtered" ]
https://github.com/borgbase/vorta/blob/23c47673c009bdef8baebb0b9cdf5e78c07fe373/src/vorta/utils.py#L118-L151
golismero/golismero
7d605b937e241f51c1ca4f47b20f755eeefb9d76
thirdparty_libs/nltk/corpus/reader/propbank.py
python
PropbankCorpusReader.verbs
(self)
return StreamBackedCorpusView(self.abspath(self._verbsfile), read_line_block, encoding=self.encoding(self._verbsfile))
:return: a corpus view that acts as a list of all verb lemmas in this corpus (from the verbs.txt file).
:return: a corpus view that acts as a list of all verb lemmas in this corpus (from the verbs.txt file).
[ ":", "return", ":", "a", "corpus", "view", "that", "acts", "as", "a", "list", "of", "all", "verb", "lemmas", "in", "this", "corpus", "(", "from", "the", "verbs", ".", "txt", "file", ")", "." ]
def verbs(self): """ :return: a corpus view that acts as a list of all verb lemmas in this corpus (from the verbs.txt file). """ return StreamBackedCorpusView(self.abspath(self._verbsfile), read_line_block, encoding=self.encoding(self._verbsfile))
[ "def", "verbs", "(", "self", ")", ":", "return", "StreamBackedCorpusView", "(", "self", ".", "abspath", "(", "self", ".", "_verbsfile", ")", ",", "read_line_block", ",", "encoding", "=", "self", ".", "encoding", "(", "self", ".", "_verbsfile", ")", ")" ]
https://github.com/golismero/golismero/blob/7d605b937e241f51c1ca4f47b20f755eeefb9d76/thirdparty_libs/nltk/corpus/reader/propbank.py#L132-L139
gitpython-developers/GitPython
fac603789d66c0fd7c26e75debb41b06136c5026
git/config.py
python
GitConfigParser.optionxform
(self, optionstr: str)
return optionstr
Do not transform options in any way when writing
Do not transform options in any way when writing
[ "Do", "not", "transform", "options", "in", "any", "way", "when", "writing" ]
def optionxform(self, optionstr: str) -> str: """Do not transform options in any way when writing""" return optionstr
[ "def", "optionxform", "(", "self", ",", "optionstr", ":", "str", ")", "->", "str", ":", "return", "optionstr" ]
https://github.com/gitpython-developers/GitPython/blob/fac603789d66c0fd7c26e75debb41b06136c5026/git/config.py#L387-L389