nwo
stringlengths
5
86
sha
stringlengths
40
40
path
stringlengths
4
189
language
stringclasses
1 value
identifier
stringlengths
1
94
parameters
stringlengths
2
4.03k
argument_list
stringclasses
1 value
return_statement
stringlengths
0
11.5k
docstring
stringlengths
1
33.2k
docstring_summary
stringlengths
0
5.15k
docstring_tokens
list
function
stringlengths
34
151k
function_tokens
list
url
stringlengths
90
278
mongodb/mongo
d8ff665343ad29cf286ee2cf4a1960d29371937b
buildscripts/task_generation/generated_config.py
python
GeneratedConfiguration.write_all_to_dir
(self, directory: str)
Write all the configuration files to the given directory. :param directory: Directory to write to.
Write all the configuration files to the given directory.
[ "Write", "all", "the", "configuration", "files", "to", "the", "given", "directory", "." ]
def write_all_to_dir(self, directory: str) -> None: """ Write all the configuration files to the given directory. :param directory: Directory to write to. """ for item in self.file_list: item.write_to_dir(directory)
[ "def", "write_all_to_dir", "(", "self", ",", "directory", ":", "str", ")", "->", "None", ":", "for", "item", "in", "self", ".", "file_list", ":", "item", ".", "write_to_dir", "(", "directory", ")" ]
https://github.com/mongodb/mongo/blob/d8ff665343ad29cf286ee2cf4a1960d29371937b/buildscripts/task_generation/generated_config.py#L36-L43
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/lib/agw/thumbnailctrl.py
python
ScrolledThumbnail.__init__
(self, parent, id=wx.ID_ANY, pos=wx.DefaultPosition, size=wx.DefaultSize, thumboutline=THUMB_OUTLINE_IMAGE, thumbfilter=THUMB_FILTER_IMAGES, imagehandler=PILImageHandler)
Default class constructor. :param `parent`: parent window. Must not be ``None``; :param `id`: window identifier. A value of -1 indicates a default value; :param `pos`: the control position. A value of (-1, -1) indicates a default position, chosen by either the windowing system or wxPython, depending on platform; :param `size`: the control size. A value of (-1, -1) indicates a default size, chosen by either the windowing system or wxPython, depending on platform; :param `thumboutline`: outline style for :class:`ScrolledThumbnail`, which may be: =========================== ======= ================================== Outline Flag Value Description =========================== ======= ================================== ``THUMB_OUTLINE_NONE`` 0 No outline is drawn on selection ``THUMB_OUTLINE_FULL`` 1 Full outline (image+caption) is drawn on selection ``THUMB_OUTLINE_RECT`` 2 Only thumbnail bounding rectangle is drawn on selection (default) ``THUMB_OUTLINE_IMAGE`` 4 Only image bounding rectangle is drawn. =========================== ======= ================================== :param `thumbfilter`: filter for image/video/audio files. Actually only ``THUMB_FILTER_IMAGES`` is implemented; :param `imagehandler`: can be :class:`PILImageHandler` if PIL is installed (faster), or :class:`NativeImageHandler` which only uses wxPython image methods.
Default class constructor.
[ "Default", "class", "constructor", "." ]
def __init__(self, parent, id=wx.ID_ANY, pos=wx.DefaultPosition, size=wx.DefaultSize, thumboutline=THUMB_OUTLINE_IMAGE, thumbfilter=THUMB_FILTER_IMAGES, imagehandler=PILImageHandler): """ Default class constructor. :param `parent`: parent window. Must not be ``None``; :param `id`: window identifier. A value of -1 indicates a default value; :param `pos`: the control position. A value of (-1, -1) indicates a default position, chosen by either the windowing system or wxPython, depending on platform; :param `size`: the control size. A value of (-1, -1) indicates a default size, chosen by either the windowing system or wxPython, depending on platform; :param `thumboutline`: outline style for :class:`ScrolledThumbnail`, which may be: =========================== ======= ================================== Outline Flag Value Description =========================== ======= ================================== ``THUMB_OUTLINE_NONE`` 0 No outline is drawn on selection ``THUMB_OUTLINE_FULL`` 1 Full outline (image+caption) is drawn on selection ``THUMB_OUTLINE_RECT`` 2 Only thumbnail bounding rectangle is drawn on selection (default) ``THUMB_OUTLINE_IMAGE`` 4 Only image bounding rectangle is drawn. =========================== ======= ================================== :param `thumbfilter`: filter for image/video/audio files. Actually only ``THUMB_FILTER_IMAGES`` is implemented; :param `imagehandler`: can be :class:`PILImageHandler` if PIL is installed (faster), or :class:`NativeImageHandler` which only uses wxPython image methods. """ wx.ScrolledWindow.__init__(self, parent, id, pos, size) self.SetThumbSize(96, 80) self._tOutline = thumboutline self._filter = thumbfilter self._imageHandler = imagehandler() self._selected = -1 self._pointed = -1 self._labelcontrol = None self._pmenu = None self._gpmenu = None self._dragging = False self._checktext = False self._orient = THUMB_VERTICAL self._dropShadow = True self._tCaptionHeight = [] self._selectedarray = [] self._tTextHeight = 16 self._tCaptionBorder = 8 self._tOutlineNotSelected = True self._mouseeventhandled = False self._highlight = False self._zoomfactor = 1.4 self.SetCaptionFont() self._items = [] self._enabletooltip = False self._parent = parent self._selectioncolour = "#009EFF" self.grayPen = wx.Pen("#A2A2D2", 1, wx.SHORT_DASH) self.grayPen.SetJoin(wx.JOIN_MITER) self.SetBackgroundColour(wx.SystemSettings_GetColour(wx.SYS_COLOUR_LISTBOX)) t, b, s = getShadow() self.shadow = wx.MemoryDC() self.shadow.SelectObject(s) self.ShowFileNames(True) self.Bind(wx.EVT_LEFT_DOWN, self.OnMouseDown) self.Bind(wx.EVT_LEFT_UP, self.OnMouseUp) self.Bind(wx.EVT_LEFT_DCLICK, self.OnMouseDClick) self.Bind(wx.EVT_RIGHT_DOWN, self.OnMouseDown) self.Bind(wx.EVT_RIGHT_UP, self.OnMouseUp) self.Bind(wx.EVT_MOTION, self.OnMouseMove) self.Bind(wx.EVT_LEAVE_WINDOW, self.OnMouseLeave) self.Bind(EVT_THUMBNAILS_THUMB_CHANGED, self.OnThumbChanged) self.Bind(wx.EVT_CHAR, self.OnChar) self.Bind(wx.EVT_MOUSEWHEEL, self.OnMouseWheel) self.Bind(wx.EVT_SIZE, self.OnResize) self.Bind(wx.EVT_ERASE_BACKGROUND, lambda x: None) self.Bind(wx.EVT_PAINT, self.OnPaint)
[ "def", "__init__", "(", "self", ",", "parent", ",", "id", "=", "wx", ".", "ID_ANY", ",", "pos", "=", "wx", ".", "DefaultPosition", ",", "size", "=", "wx", ".", "DefaultSize", ",", "thumboutline", "=", "THUMB_OUTLINE_IMAGE", ",", "thumbfilter", "=", "THUMB_FILTER_IMAGES", ",", "imagehandler", "=", "PILImageHandler", ")", ":", "wx", ".", "ScrolledWindow", ".", "__init__", "(", "self", ",", "parent", ",", "id", ",", "pos", ",", "size", ")", "self", ".", "SetThumbSize", "(", "96", ",", "80", ")", "self", ".", "_tOutline", "=", "thumboutline", "self", ".", "_filter", "=", "thumbfilter", "self", ".", "_imageHandler", "=", "imagehandler", "(", ")", "self", ".", "_selected", "=", "-", "1", "self", ".", "_pointed", "=", "-", "1", "self", ".", "_labelcontrol", "=", "None", "self", ".", "_pmenu", "=", "None", "self", ".", "_gpmenu", "=", "None", "self", ".", "_dragging", "=", "False", "self", ".", "_checktext", "=", "False", "self", ".", "_orient", "=", "THUMB_VERTICAL", "self", ".", "_dropShadow", "=", "True", "self", ".", "_tCaptionHeight", "=", "[", "]", "self", ".", "_selectedarray", "=", "[", "]", "self", ".", "_tTextHeight", "=", "16", "self", ".", "_tCaptionBorder", "=", "8", "self", ".", "_tOutlineNotSelected", "=", "True", "self", ".", "_mouseeventhandled", "=", "False", "self", ".", "_highlight", "=", "False", "self", ".", "_zoomfactor", "=", "1.4", "self", ".", "SetCaptionFont", "(", ")", "self", ".", "_items", "=", "[", "]", "self", ".", "_enabletooltip", "=", "False", "self", ".", "_parent", "=", "parent", "self", ".", "_selectioncolour", "=", "\"#009EFF\"", "self", ".", "grayPen", "=", "wx", ".", "Pen", "(", "\"#A2A2D2\"", ",", "1", ",", "wx", ".", "SHORT_DASH", ")", "self", ".", "grayPen", ".", "SetJoin", "(", "wx", ".", "JOIN_MITER", ")", "self", ".", "SetBackgroundColour", "(", "wx", ".", "SystemSettings_GetColour", "(", "wx", ".", "SYS_COLOUR_LISTBOX", ")", ")", "t", ",", "b", ",", "s", "=", "getShadow", "(", ")", "self", ".", "shadow", "=", "wx", ".", "MemoryDC", "(", ")", "self", ".", "shadow", ".", "SelectObject", "(", "s", ")", "self", ".", "ShowFileNames", "(", "True", ")", "self", ".", "Bind", "(", "wx", ".", "EVT_LEFT_DOWN", ",", "self", ".", "OnMouseDown", ")", "self", ".", "Bind", "(", "wx", ".", "EVT_LEFT_UP", ",", "self", ".", "OnMouseUp", ")", "self", ".", "Bind", "(", "wx", ".", "EVT_LEFT_DCLICK", ",", "self", ".", "OnMouseDClick", ")", "self", ".", "Bind", "(", "wx", ".", "EVT_RIGHT_DOWN", ",", "self", ".", "OnMouseDown", ")", "self", ".", "Bind", "(", "wx", ".", "EVT_RIGHT_UP", ",", "self", ".", "OnMouseUp", ")", "self", ".", "Bind", "(", "wx", ".", "EVT_MOTION", ",", "self", ".", "OnMouseMove", ")", "self", ".", "Bind", "(", "wx", ".", "EVT_LEAVE_WINDOW", ",", "self", ".", "OnMouseLeave", ")", "self", ".", "Bind", "(", "EVT_THUMBNAILS_THUMB_CHANGED", ",", "self", ".", "OnThumbChanged", ")", "self", ".", "Bind", "(", "wx", ".", "EVT_CHAR", ",", "self", ".", "OnChar", ")", "self", ".", "Bind", "(", "wx", ".", "EVT_MOUSEWHEEL", ",", "self", ".", "OnMouseWheel", ")", "self", ".", "Bind", "(", "wx", ".", "EVT_SIZE", ",", "self", ".", "OnResize", ")", "self", ".", "Bind", "(", "wx", ".", "EVT_ERASE_BACKGROUND", ",", "lambda", "x", ":", "None", ")", "self", ".", "Bind", "(", "wx", ".", "EVT_PAINT", ",", "self", ".", "OnPaint", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/thumbnailctrl.py#L1078-L1162
mindspore-ai/mindspore
fb8fd3338605bb34fa5cea054e535a8b1d753fab
mindspore/python/mindspore/numpy/math_ops.py
python
rad2deg
(x, dtype=None)
return _apply_tensor_op(convert, x, dtype=dtype)
Converts angles from radians to degrees. Args: x (Tensor): Angles in radians. dtype (:class:`mindspore.dtype`, optional): Defaults to None. Overrides the dtype of the output Tensor. Returns: Tensor, the corresponding angle in degrees. This is a tensor scalar if `x` is a tensor scalar. Supported Platforms: ``Ascend`` ``GPU`` ``CPU`` Examples: >>> import mindspore.numpy as np >>> x = np.asarray([1, 2, 3, -4, -5]) >>> output = np.rad2deg(x) >>> print(output) [ 57.295776 114.59155 171.88733 -229.1831 -286.47888 ]
Converts angles from radians to degrees.
[ "Converts", "angles", "from", "radians", "to", "degrees", "." ]
def rad2deg(x, dtype=None): """ Converts angles from radians to degrees. Args: x (Tensor): Angles in radians. dtype (:class:`mindspore.dtype`, optional): Defaults to None. Overrides the dtype of the output Tensor. Returns: Tensor, the corresponding angle in degrees. This is a tensor scalar if `x` is a tensor scalar. Supported Platforms: ``Ascend`` ``GPU`` ``CPU`` Examples: >>> import mindspore.numpy as np >>> x = np.asarray([1, 2, 3, -4, -5]) >>> output = np.rad2deg(x) >>> print(output) [ 57.295776 114.59155 171.88733 -229.1831 -286.47888 ] """ _check_input_tensor(x) def convert(a): return a * 180.0 / pi return _apply_tensor_op(convert, x, dtype=dtype)
[ "def", "rad2deg", "(", "x", ",", "dtype", "=", "None", ")", ":", "_check_input_tensor", "(", "x", ")", "def", "convert", "(", "a", ")", ":", "return", "a", "*", "180.0", "/", "pi", "return", "_apply_tensor_op", "(", "convert", ",", "x", ",", "dtype", "=", "dtype", ")" ]
https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/numpy/math_ops.py#L229-L256
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/tools/compatibility/ast_edits.py
python
_PastaEditVisitor._maybe_rename
(self, parent, node, full_name)
Replace node (Attribute or Name) with a node representing full_name.
Replace node (Attribute or Name) with a node representing full_name.
[ "Replace", "node", "(", "Attribute", "or", "Name", ")", "with", "a", "node", "representing", "full_name", "." ]
def _maybe_rename(self, parent, node, full_name): """Replace node (Attribute or Name) with a node representing full_name.""" new_name = self._api_change_spec.symbol_renames.get(full_name, None) if new_name: self.add_log(INFO, node.lineno, node.col_offset, "Renamed %r to %r" % (full_name, new_name)) new_node = full_name_node(new_name, node.ctx) ast.copy_location(new_node, node) pasta.ast_utils.replace_child(parent, node, new_node) return True else: return False
[ "def", "_maybe_rename", "(", "self", ",", "parent", ",", "node", ",", "full_name", ")", ":", "new_name", "=", "self", ".", "_api_change_spec", ".", "symbol_renames", ".", "get", "(", "full_name", ",", "None", ")", "if", "new_name", ":", "self", ".", "add_log", "(", "INFO", ",", "node", ".", "lineno", ",", "node", ".", "col_offset", ",", "\"Renamed %r to %r\"", "%", "(", "full_name", ",", "new_name", ")", ")", "new_node", "=", "full_name_node", "(", "new_name", ",", "node", ".", "ctx", ")", "ast", ".", "copy_location", "(", "new_node", ",", "node", ")", "pasta", ".", "ast_utils", ".", "replace_child", "(", "parent", ",", "node", ",", "new_node", ")", "return", "True", "else", ":", "return", "False" ]
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/tools/compatibility/ast_edits.py#L419-L430
ceph/ceph
959663007321a369c83218414a29bd9dbc8bda3a
qa/tasks/watch_notify_same_primary.py
python
task
(ctx, config)
Run watch_notify_same_primary The config should be as follows: watch_notify_same_primary: clients: [client list] The client list should contain 1 client The test requires 3 osds. example: tasks: - ceph: - watch_notify_same_primary: clients: [client.0] - interactive:
Run watch_notify_same_primary
[ "Run", "watch_notify_same_primary" ]
def task(ctx, config): """ Run watch_notify_same_primary The config should be as follows: watch_notify_same_primary: clients: [client list] The client list should contain 1 client The test requires 3 osds. example: tasks: - ceph: - watch_notify_same_primary: clients: [client.0] - interactive: """ log.info('Beginning watch_notify_same_primary...') assert isinstance(config, dict), \ "please list clients to run on" clients = config.get('clients', ['client.0']) assert len(clients) == 1 role = clients[0] assert isinstance(role, str) PREFIX = 'client.' assert role.startswith(PREFIX) (remote,) = ctx.cluster.only(role).remotes.keys() manager = ctx.managers['ceph'] manager.raw_cluster_cmd('osd', 'set', 'noout') pool = manager.create_pool_with_unique_name() def obj(n): return "foo-{num}".format(num=n) def start_watch(n): remote.run( args = [ "rados", "-p", pool, "put", obj(n), "/etc/resolv.conf"], logger=log.getChild('watch.{id}'.format(id=n))) proc = remote.run( args = [ "rados", "-p", pool, "watch", obj(n)], stdin=run.PIPE, stdout=StringIO(), stderr=StringIO(), wait=False) return proc num = 20 watches = [start_watch(i) for i in range(num)] # wait for them all to register for i in range(num): with safe_while() as proceed: while proceed(): lines = remote.sh( ["rados", "-p", pool, "listwatchers", obj(i)]) num_watchers = lines.count('watcher=') log.info('i see %d watchers for %s', num_watchers, obj(i)) if num_watchers >= 1: break def notify(n, msg): remote.run( args = [ "rados", "-p", pool, "notify", obj(n), msg], logger=log.getChild('notify.{id}'.format(id=n))) [notify(n, 'notify1') for n in range(len(watches))] manager.kill_osd(0) manager.mark_down_osd(0) [notify(n, 'notify2') for n in range(len(watches))] try: yield finally: log.info('joining watch_notify_stress') for watch in watches: watch.stdin.write("\n") run.wait(watches) for watch in watches: lines = watch.stdout.getvalue().split("\n") got1 = False got2 = False for l in lines: if 'notify1' in l: got1 = True if 'notify2' in l: got2 = True log.info(lines) assert got1 and got2 manager.revive_osd(0) manager.remove_pool(pool)
[ "def", "task", "(", "ctx", ",", "config", ")", ":", "log", ".", "info", "(", "'Beginning watch_notify_same_primary...'", ")", "assert", "isinstance", "(", "config", ",", "dict", ")", ",", "\"please list clients to run on\"", "clients", "=", "config", ".", "get", "(", "'clients'", ",", "[", "'client.0'", "]", ")", "assert", "len", "(", "clients", ")", "==", "1", "role", "=", "clients", "[", "0", "]", "assert", "isinstance", "(", "role", ",", "str", ")", "PREFIX", "=", "'client.'", "assert", "role", ".", "startswith", "(", "PREFIX", ")", "(", "remote", ",", ")", "=", "ctx", ".", "cluster", ".", "only", "(", "role", ")", ".", "remotes", ".", "keys", "(", ")", "manager", "=", "ctx", ".", "managers", "[", "'ceph'", "]", "manager", ".", "raw_cluster_cmd", "(", "'osd'", ",", "'set'", ",", "'noout'", ")", "pool", "=", "manager", ".", "create_pool_with_unique_name", "(", ")", "def", "obj", "(", "n", ")", ":", "return", "\"foo-{num}\"", ".", "format", "(", "num", "=", "n", ")", "def", "start_watch", "(", "n", ")", ":", "remote", ".", "run", "(", "args", "=", "[", "\"rados\"", ",", "\"-p\"", ",", "pool", ",", "\"put\"", ",", "obj", "(", "n", ")", ",", "\"/etc/resolv.conf\"", "]", ",", "logger", "=", "log", ".", "getChild", "(", "'watch.{id}'", ".", "format", "(", "id", "=", "n", ")", ")", ")", "proc", "=", "remote", ".", "run", "(", "args", "=", "[", "\"rados\"", ",", "\"-p\"", ",", "pool", ",", "\"watch\"", ",", "obj", "(", "n", ")", "]", ",", "stdin", "=", "run", ".", "PIPE", ",", "stdout", "=", "StringIO", "(", ")", ",", "stderr", "=", "StringIO", "(", ")", ",", "wait", "=", "False", ")", "return", "proc", "num", "=", "20", "watches", "=", "[", "start_watch", "(", "i", ")", "for", "i", "in", "range", "(", "num", ")", "]", "# wait for them all to register", "for", "i", "in", "range", "(", "num", ")", ":", "with", "safe_while", "(", ")", "as", "proceed", ":", "while", "proceed", "(", ")", ":", "lines", "=", "remote", ".", "sh", "(", "[", "\"rados\"", ",", "\"-p\"", ",", "pool", ",", "\"listwatchers\"", ",", "obj", "(", "i", ")", "]", ")", "num_watchers", "=", "lines", ".", "count", "(", "'watcher='", ")", "log", ".", "info", "(", "'i see %d watchers for %s'", ",", "num_watchers", ",", "obj", "(", "i", ")", ")", "if", "num_watchers", ">=", "1", ":", "break", "def", "notify", "(", "n", ",", "msg", ")", ":", "remote", ".", "run", "(", "args", "=", "[", "\"rados\"", ",", "\"-p\"", ",", "pool", ",", "\"notify\"", ",", "obj", "(", "n", ")", ",", "msg", "]", ",", "logger", "=", "log", ".", "getChild", "(", "'notify.{id}'", ".", "format", "(", "id", "=", "n", ")", ")", ")", "[", "notify", "(", "n", ",", "'notify1'", ")", "for", "n", "in", "range", "(", "len", "(", "watches", ")", ")", "]", "manager", ".", "kill_osd", "(", "0", ")", "manager", ".", "mark_down_osd", "(", "0", ")", "[", "notify", "(", "n", ",", "'notify2'", ")", "for", "n", "in", "range", "(", "len", "(", "watches", ")", ")", "]", "try", ":", "yield", "finally", ":", "log", ".", "info", "(", "'joining watch_notify_stress'", ")", "for", "watch", "in", "watches", ":", "watch", ".", "stdin", ".", "write", "(", "\"\\n\"", ")", "run", ".", "wait", "(", "watches", ")", "for", "watch", "in", "watches", ":", "lines", "=", "watch", ".", "stdout", ".", "getvalue", "(", ")", ".", "split", "(", "\"\\n\"", ")", "got1", "=", "False", "got2", "=", "False", "for", "l", "in", "lines", ":", "if", "'notify1'", "in", "l", ":", "got1", "=", "True", "if", "'notify2'", "in", "l", ":", "got2", "=", "True", "log", ".", "info", "(", "lines", ")", "assert", "got1", "and", "got2", "manager", ".", "revive_osd", "(", "0", ")", "manager", ".", "remove_pool", "(", "pool", ")" ]
https://github.com/ceph/ceph/blob/959663007321a369c83218414a29bd9dbc8bda3a/qa/tasks/watch_notify_same_primary.py#L17-L129
apple/swift-lldb
d74be846ef3e62de946df343e8c234bde93a8912
utils/vim-lldb/python-vim-lldb/vim_ui.py
python
UI.update_pc
(self, process, buffers, goto_file)
Place the PC sign on the PC location of each thread's selected frame
Place the PC sign on the PC location of each thread's selected frame
[ "Place", "the", "PC", "sign", "on", "the", "PC", "location", "of", "each", "thread", "s", "selected", "frame" ]
def update_pc(self, process, buffers, goto_file): """ Place the PC sign on the PC location of each thread's selected frame """ def GetPCSourceLocation(thread): """ Returns a tuple (thread_index, file, line, column) that represents where the PC sign should be placed for a thread. """ frame = thread.GetSelectedFrame() frame_num = frame.GetFrameID() le = frame.GetLineEntry() while not le.IsValid() and frame_num < thread.GetNumFrames(): frame_num += 1 le = thread.GetFrameAtIndex(frame_num).GetLineEntry() if le.IsValid(): path = os.path.join( le.GetFileSpec().GetDirectory(), le.GetFileSpec().GetFilename()) return ( thread.GetIndexID(), path, le.GetLine(), le.GetColumn()) return None # Clear all existing PC signs del_list = [] for sign in self.pcSigns: sign.hide() del_list.append(sign) for sign in del_list: self.pcSigns.remove(sign) del sign # Select a user (non-lldb) window if not self.paneCol.selectWindow(False): # No user window found; avoid clobbering by splitting vim.command(":vsp") # Show a PC marker for each thread for thread in process: loc = GetPCSourceLocation(thread) if not loc: # no valid source locations for PCs. hide all existing PC # markers continue buf = None (tid, fname, line, col) = loc buffers = self.get_user_buffers(fname) is_selected = thread.GetIndexID() == process.GetSelectedThread().GetIndexID() if len(buffers) == 1: buf = buffers[0] if buf != vim.current.buffer: # Vim has an open buffer to the required file: select it vim.command('execute ":%db"' % buf.number) elif is_selected and vim.current.buffer.name not in fname and os.path.exists(fname) and goto_file: # FIXME: If current buffer is modified, vim will complain when we try to switch away. # Find a way to detect if the current buffer is modified, # and...warn instead? vim.command('execute ":e %s"' % fname) buf = vim.current.buffer elif len(buffers) > 1 and goto_file: # FIXME: multiple open buffers match PC location continue else: continue self.pcSigns.append(PCSign(buf, line, is_selected)) if is_selected and goto_file: # if the selected file has a PC marker, move the cursor there # too curname = vim.current.buffer.name if curname is not None and is_same_file(curname, fname): move_cursor(line, 0) elif move_cursor: print("FIXME: not sure where to move cursor because %s != %s " % (vim.current.buffer.name, fname))
[ "def", "update_pc", "(", "self", ",", "process", ",", "buffers", ",", "goto_file", ")", ":", "def", "GetPCSourceLocation", "(", "thread", ")", ":", "\"\"\" Returns a tuple (thread_index, file, line, column) that represents where\n the PC sign should be placed for a thread.\n \"\"\"", "frame", "=", "thread", ".", "GetSelectedFrame", "(", ")", "frame_num", "=", "frame", ".", "GetFrameID", "(", ")", "le", "=", "frame", ".", "GetLineEntry", "(", ")", "while", "not", "le", ".", "IsValid", "(", ")", "and", "frame_num", "<", "thread", ".", "GetNumFrames", "(", ")", ":", "frame_num", "+=", "1", "le", "=", "thread", ".", "GetFrameAtIndex", "(", "frame_num", ")", ".", "GetLineEntry", "(", ")", "if", "le", ".", "IsValid", "(", ")", ":", "path", "=", "os", ".", "path", ".", "join", "(", "le", ".", "GetFileSpec", "(", ")", ".", "GetDirectory", "(", ")", ",", "le", ".", "GetFileSpec", "(", ")", ".", "GetFilename", "(", ")", ")", "return", "(", "thread", ".", "GetIndexID", "(", ")", ",", "path", ",", "le", ".", "GetLine", "(", ")", ",", "le", ".", "GetColumn", "(", ")", ")", "return", "None", "# Clear all existing PC signs", "del_list", "=", "[", "]", "for", "sign", "in", "self", ".", "pcSigns", ":", "sign", ".", "hide", "(", ")", "del_list", ".", "append", "(", "sign", ")", "for", "sign", "in", "del_list", ":", "self", ".", "pcSigns", ".", "remove", "(", "sign", ")", "del", "sign", "# Select a user (non-lldb) window", "if", "not", "self", ".", "paneCol", ".", "selectWindow", "(", "False", ")", ":", "# No user window found; avoid clobbering by splitting", "vim", ".", "command", "(", "\":vsp\"", ")", "# Show a PC marker for each thread", "for", "thread", "in", "process", ":", "loc", "=", "GetPCSourceLocation", "(", "thread", ")", "if", "not", "loc", ":", "# no valid source locations for PCs. hide all existing PC", "# markers", "continue", "buf", "=", "None", "(", "tid", ",", "fname", ",", "line", ",", "col", ")", "=", "loc", "buffers", "=", "self", ".", "get_user_buffers", "(", "fname", ")", "is_selected", "=", "thread", ".", "GetIndexID", "(", ")", "==", "process", ".", "GetSelectedThread", "(", ")", ".", "GetIndexID", "(", ")", "if", "len", "(", "buffers", ")", "==", "1", ":", "buf", "=", "buffers", "[", "0", "]", "if", "buf", "!=", "vim", ".", "current", ".", "buffer", ":", "# Vim has an open buffer to the required file: select it", "vim", ".", "command", "(", "'execute \":%db\"'", "%", "buf", ".", "number", ")", "elif", "is_selected", "and", "vim", ".", "current", ".", "buffer", ".", "name", "not", "in", "fname", "and", "os", ".", "path", ".", "exists", "(", "fname", ")", "and", "goto_file", ":", "# FIXME: If current buffer is modified, vim will complain when we try to switch away.", "# Find a way to detect if the current buffer is modified,", "# and...warn instead?", "vim", ".", "command", "(", "'execute \":e %s\"'", "%", "fname", ")", "buf", "=", "vim", ".", "current", ".", "buffer", "elif", "len", "(", "buffers", ")", ">", "1", "and", "goto_file", ":", "# FIXME: multiple open buffers match PC location", "continue", "else", ":", "continue", "self", ".", "pcSigns", ".", "append", "(", "PCSign", "(", "buf", ",", "line", ",", "is_selected", ")", ")", "if", "is_selected", "and", "goto_file", ":", "# if the selected file has a PC marker, move the cursor there", "# too", "curname", "=", "vim", ".", "current", ".", "buffer", ".", "name", "if", "curname", "is", "not", "None", "and", "is_same_file", "(", "curname", ",", "fname", ")", ":", "move_cursor", "(", "line", ",", "0", ")", "elif", "move_cursor", ":", "print", "(", "\"FIXME: not sure where to move cursor because %s != %s \"", "%", "(", "vim", ".", "current", ".", "buffer", ".", "name", ",", "fname", ")", ")" ]
https://github.com/apple/swift-lldb/blob/d74be846ef3e62de946df343e8c234bde93a8912/utils/vim-lldb/python-vim-lldb/vim_ui.py#L70-L148
huzheng001/stardict-3
96b96d89eab5f0ad9246c2569a807d6d7982aa84
tools/src/stardict_images.py
python
create_icon
(origImage, visibleLayers, props)
return iconImage
visibleLayers - a list of layers that must be visible props - tuple of image properties in format ((size, bpp), ...) where: size - size of the icon in pixels, bpp - bits per pixel, None to leave by default return value - new image
visibleLayers - a list of layers that must be visible props - tuple of image properties in format ((size, bpp), ...) where: size - size of the icon in pixels, bpp - bits per pixel, None to leave by default return value - new image
[ "visibleLayers", "-", "a", "list", "of", "layers", "that", "must", "be", "visible", "props", "-", "tuple", "of", "image", "properties", "in", "format", "((", "size", "bpp", ")", "...", ")", "where", ":", "size", "-", "size", "of", "the", "icon", "in", "pixels", "bpp", "-", "bits", "per", "pixel", "None", "to", "leave", "by", "default", "return", "value", "-", "new", "image" ]
def create_icon(origImage, visibleLayers, props): """visibleLayers - a list of layers that must be visible props - tuple of image properties in format ((size, bpp), ...) where: size - size of the icon in pixels, bpp - bits per pixel, None to leave by default return value - new image """ iconImage = None i = 0 for prop in props: image = gimp.pdb.gimp_image_duplicate(origImage) prepare_image(image, visibleLayers, prop[0], prop[1]) image.layers[0].name = 's{0}'.format(i) if iconImage == None: iconImage = image else: newLayer = gimp.pdb.gimp_layer_new_from_drawable(image.layers[0], iconImage) gimp.pdb.gimp_image_add_layer(iconImage, newLayer, -1) gimp.delete(image) i += 1 return iconImage
[ "def", "create_icon", "(", "origImage", ",", "visibleLayers", ",", "props", ")", ":", "iconImage", "=", "None", "i", "=", "0", "for", "prop", "in", "props", ":", "image", "=", "gimp", ".", "pdb", ".", "gimp_image_duplicate", "(", "origImage", ")", "prepare_image", "(", "image", ",", "visibleLayers", ",", "prop", "[", "0", "]", ",", "prop", "[", "1", "]", ")", "image", ".", "layers", "[", "0", "]", ".", "name", "=", "'s{0}'", ".", "format", "(", "i", ")", "if", "iconImage", "==", "None", ":", "iconImage", "=", "image", "else", ":", "newLayer", "=", "gimp", ".", "pdb", ".", "gimp_layer_new_from_drawable", "(", "image", ".", "layers", "[", "0", "]", ",", "iconImage", ")", "gimp", ".", "pdb", ".", "gimp_image_add_layer", "(", "iconImage", ",", "newLayer", ",", "-", "1", ")", "gimp", ".", "delete", "(", "image", ")", "i", "+=", "1", "return", "iconImage" ]
https://github.com/huzheng001/stardict-3/blob/96b96d89eab5f0ad9246c2569a807d6d7982aa84/tools/src/stardict_images.py#L42-L64
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/aui.py
python
PyAuiTabArt.GetSelectedFont
(*args, **kwargs)
return _aui.PyAuiTabArt_GetSelectedFont(*args, **kwargs)
GetSelectedFont(self) -> Font
GetSelectedFont(self) -> Font
[ "GetSelectedFont", "(", "self", ")", "-", ">", "Font" ]
def GetSelectedFont(*args, **kwargs): """GetSelectedFont(self) -> Font""" return _aui.PyAuiTabArt_GetSelectedFont(*args, **kwargs)
[ "def", "GetSelectedFont", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_aui", ".", "PyAuiTabArt_GetSelectedFont", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/aui.py#L2439-L2441
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/protobuf/py3/google/protobuf/internal/python_message.py
python
_AddIsInitializedMethod
(message_descriptor, cls)
Adds the IsInitialized and FindInitializationError methods to the protocol message class.
Adds the IsInitialized and FindInitializationError methods to the protocol message class.
[ "Adds", "the", "IsInitialized", "and", "FindInitializationError", "methods", "to", "the", "protocol", "message", "class", "." ]
def _AddIsInitializedMethod(message_descriptor, cls): """Adds the IsInitialized and FindInitializationError methods to the protocol message class.""" required_fields = [field for field in message_descriptor.fields if field.label == _FieldDescriptor.LABEL_REQUIRED] def IsInitialized(self, errors=None): """Checks if all required fields of a message are set. Args: errors: A list which, if provided, will be populated with the field paths of all missing required fields. Returns: True iff the specified message has all required fields set. """ # Performance is critical so we avoid HasField() and ListFields(). for field in required_fields: if (field not in self._fields or (field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE and not self._fields[field]._is_present_in_parent)): if errors is not None: errors.extend(self.FindInitializationErrors()) return False for field, value in list(self._fields.items()): # dict can change size! if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE: if field.label == _FieldDescriptor.LABEL_REPEATED: if (field.message_type.has_options and field.message_type.GetOptions().map_entry): continue for element in value: if not element.IsInitialized(): if errors is not None: errors.extend(self.FindInitializationErrors()) return False elif value._is_present_in_parent and not value.IsInitialized(): if errors is not None: errors.extend(self.FindInitializationErrors()) return False return True cls.IsInitialized = IsInitialized def FindInitializationErrors(self): """Finds required fields which are not initialized. Returns: A list of strings. Each string is a path to an uninitialized field from the top-level message, e.g. "foo.bar[5].baz". """ errors = [] # simplify things for field in required_fields: if not self.HasField(field.name): errors.append(field.name) for field, value in self.ListFields(): if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE: if field.is_extension: name = '(%s)' % field.full_name else: name = field.name if _IsMapField(field): if _IsMessageMapField(field): for key in value: element = value[key] prefix = '%s[%s].' % (name, key) sub_errors = element.FindInitializationErrors() errors += [prefix + error for error in sub_errors] else: # ScalarMaps can't have any initialization errors. pass elif field.label == _FieldDescriptor.LABEL_REPEATED: for i in range(len(value)): element = value[i] prefix = '%s[%d].' % (name, i) sub_errors = element.FindInitializationErrors() errors += [prefix + error for error in sub_errors] else: prefix = name + '.' sub_errors = value.FindInitializationErrors() errors += [prefix + error for error in sub_errors] return errors cls.FindInitializationErrors = FindInitializationErrors
[ "def", "_AddIsInitializedMethod", "(", "message_descriptor", ",", "cls", ")", ":", "required_fields", "=", "[", "field", "for", "field", "in", "message_descriptor", ".", "fields", "if", "field", ".", "label", "==", "_FieldDescriptor", ".", "LABEL_REQUIRED", "]", "def", "IsInitialized", "(", "self", ",", "errors", "=", "None", ")", ":", "\"\"\"Checks if all required fields of a message are set.\n\n Args:\n errors: A list which, if provided, will be populated with the field\n paths of all missing required fields.\n\n Returns:\n True iff the specified message has all required fields set.\n \"\"\"", "# Performance is critical so we avoid HasField() and ListFields().", "for", "field", "in", "required_fields", ":", "if", "(", "field", "not", "in", "self", ".", "_fields", "or", "(", "field", ".", "cpp_type", "==", "_FieldDescriptor", ".", "CPPTYPE_MESSAGE", "and", "not", "self", ".", "_fields", "[", "field", "]", ".", "_is_present_in_parent", ")", ")", ":", "if", "errors", "is", "not", "None", ":", "errors", ".", "extend", "(", "self", ".", "FindInitializationErrors", "(", ")", ")", "return", "False", "for", "field", ",", "value", "in", "list", "(", "self", ".", "_fields", ".", "items", "(", ")", ")", ":", "# dict can change size!", "if", "field", ".", "cpp_type", "==", "_FieldDescriptor", ".", "CPPTYPE_MESSAGE", ":", "if", "field", ".", "label", "==", "_FieldDescriptor", ".", "LABEL_REPEATED", ":", "if", "(", "field", ".", "message_type", ".", "has_options", "and", "field", ".", "message_type", ".", "GetOptions", "(", ")", ".", "map_entry", ")", ":", "continue", "for", "element", "in", "value", ":", "if", "not", "element", ".", "IsInitialized", "(", ")", ":", "if", "errors", "is", "not", "None", ":", "errors", ".", "extend", "(", "self", ".", "FindInitializationErrors", "(", ")", ")", "return", "False", "elif", "value", ".", "_is_present_in_parent", "and", "not", "value", ".", "IsInitialized", "(", ")", ":", "if", "errors", "is", "not", "None", ":", "errors", ".", "extend", "(", "self", ".", "FindInitializationErrors", "(", ")", ")", "return", "False", "return", "True", "cls", ".", "IsInitialized", "=", "IsInitialized", "def", "FindInitializationErrors", "(", "self", ")", ":", "\"\"\"Finds required fields which are not initialized.\n\n Returns:\n A list of strings. Each string is a path to an uninitialized field from\n the top-level message, e.g. \"foo.bar[5].baz\".\n \"\"\"", "errors", "=", "[", "]", "# simplify things", "for", "field", "in", "required_fields", ":", "if", "not", "self", ".", "HasField", "(", "field", ".", "name", ")", ":", "errors", ".", "append", "(", "field", ".", "name", ")", "for", "field", ",", "value", "in", "self", ".", "ListFields", "(", ")", ":", "if", "field", ".", "cpp_type", "==", "_FieldDescriptor", ".", "CPPTYPE_MESSAGE", ":", "if", "field", ".", "is_extension", ":", "name", "=", "'(%s)'", "%", "field", ".", "full_name", "else", ":", "name", "=", "field", ".", "name", "if", "_IsMapField", "(", "field", ")", ":", "if", "_IsMessageMapField", "(", "field", ")", ":", "for", "key", "in", "value", ":", "element", "=", "value", "[", "key", "]", "prefix", "=", "'%s[%s].'", "%", "(", "name", ",", "key", ")", "sub_errors", "=", "element", ".", "FindInitializationErrors", "(", ")", "errors", "+=", "[", "prefix", "+", "error", "for", "error", "in", "sub_errors", "]", "else", ":", "# ScalarMaps can't have any initialization errors.", "pass", "elif", "field", ".", "label", "==", "_FieldDescriptor", ".", "LABEL_REPEATED", ":", "for", "i", "in", "range", "(", "len", "(", "value", ")", ")", ":", "element", "=", "value", "[", "i", "]", "prefix", "=", "'%s[%d].'", "%", "(", "name", ",", "i", ")", "sub_errors", "=", "element", ".", "FindInitializationErrors", "(", ")", "errors", "+=", "[", "prefix", "+", "error", "for", "error", "in", "sub_errors", "]", "else", ":", "prefix", "=", "name", "+", "'.'", "sub_errors", "=", "value", ".", "FindInitializationErrors", "(", ")", "errors", "+=", "[", "prefix", "+", "error", "for", "error", "in", "sub_errors", "]", "return", "errors", "cls", ".", "FindInitializationErrors", "=", "FindInitializationErrors" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/protobuf/py3/google/protobuf/internal/python_message.py#L1213-L1305
Cisco-Talos/moflow
ed71dfb0540d9e0d7a4c72f0881b58958d573728
BAP-0.7-moflow/libtracewrap/libtrace/protobuf/python/mox.py
python
MockMethod.InAnyOrder
(self, group_name="default")
return self._CheckAndCreateNewGroup(group_name, UnorderedGroup)
Move this method into a group of unordered calls. A group of unordered calls must be defined together, and must be executed in full before the next expected method can be called. There can be multiple groups that are expected serially, if they are given different group names. The same group name can be reused if there is a standard method call, or a group with a different name, spliced between usages. Args: group_name: the name of the unordered group. Returns: self
Move this method into a group of unordered calls.
[ "Move", "this", "method", "into", "a", "group", "of", "unordered", "calls", "." ]
def InAnyOrder(self, group_name="default"): """Move this method into a group of unordered calls. A group of unordered calls must be defined together, and must be executed in full before the next expected method can be called. There can be multiple groups that are expected serially, if they are given different group names. The same group name can be reused if there is a standard method call, or a group with a different name, spliced between usages. Args: group_name: the name of the unordered group. Returns: self """ return self._CheckAndCreateNewGroup(group_name, UnorderedGroup)
[ "def", "InAnyOrder", "(", "self", ",", "group_name", "=", "\"default\"", ")", ":", "return", "self", ".", "_CheckAndCreateNewGroup", "(", "group_name", ",", "UnorderedGroup", ")" ]
https://github.com/Cisco-Talos/moflow/blob/ed71dfb0540d9e0d7a4c72f0881b58958d573728/BAP-0.7-moflow/libtracewrap/libtrace/protobuf/python/mox.py#L686-L702
ApolloAuto/apollo-platform
86d9dc6743b496ead18d597748ebabd34a513289
ros/third_party/lib_x86_64/python2.7/dist-packages/numpy/matrixlib/defmatrix.py
python
matrix.argmin
(self, axis=None, out=None)
return N.ndarray.argmin(self, axis, out)._align(axis)
Return the indices of the minimum values along an axis. Parameters ---------- See `numpy.argmin` for complete descriptions. See Also -------- numpy.argmin Notes ----- This is the same as `ndarray.argmin`, but returns a `matrix` object where `ndarray.argmin` would return an `ndarray`. Examples -------- >>> x = -np.matrix(np.arange(12).reshape((3,4))); x matrix([[ 0, -1, -2, -3], [ -4, -5, -6, -7], [ -8, -9, -10, -11]]) >>> x.argmin() 11 >>> x.argmin(0) matrix([[2, 2, 2, 2]]) >>> x.argmin(1) matrix([[3], [3], [3]])
Return the indices of the minimum values along an axis.
[ "Return", "the", "indices", "of", "the", "minimum", "values", "along", "an", "axis", "." ]
def argmin(self, axis=None, out=None): """ Return the indices of the minimum values along an axis. Parameters ---------- See `numpy.argmin` for complete descriptions. See Also -------- numpy.argmin Notes ----- This is the same as `ndarray.argmin`, but returns a `matrix` object where `ndarray.argmin` would return an `ndarray`. Examples -------- >>> x = -np.matrix(np.arange(12).reshape((3,4))); x matrix([[ 0, -1, -2, -3], [ -4, -5, -6, -7], [ -8, -9, -10, -11]]) >>> x.argmin() 11 >>> x.argmin(0) matrix([[2, 2, 2, 2]]) >>> x.argmin(1) matrix([[3], [3], [3]]) """ return N.ndarray.argmin(self, axis, out)._align(axis)
[ "def", "argmin", "(", "self", ",", "axis", "=", "None", ",", "out", "=", "None", ")", ":", "return", "N", ".", "ndarray", ".", "argmin", "(", "self", ",", "axis", ",", "out", ")", ".", "_align", "(", "axis", ")" ]
https://github.com/ApolloAuto/apollo-platform/blob/86d9dc6743b496ead18d597748ebabd34a513289/ros/third_party/lib_x86_64/python2.7/dist-packages/numpy/matrixlib/defmatrix.py#L760-L793
zhaoweicai/cascade-rcnn
2252f46158ea6555868ca6fa5c221ea71d9b5e6c
scripts/cpp_lint.py
python
FilesBelongToSameModule
(filename_cc, filename_h)
return files_belong_to_same_module, common_path
Check if these two filenames belong to the same module. The concept of a 'module' here is a as follows: foo.h, foo-inl.h, foo.cc, foo_test.cc and foo_unittest.cc belong to the same 'module' if they are in the same directory. some/path/public/xyzzy and some/path/internal/xyzzy are also considered to belong to the same module here. If the filename_cc contains a longer path than the filename_h, for example, '/absolute/path/to/base/sysinfo.cc', and this file would include 'base/sysinfo.h', this function also produces the prefix needed to open the header. This is used by the caller of this function to more robustly open the header file. We don't have access to the real include paths in this context, so we need this guesswork here. Known bugs: tools/base/bar.cc and base/bar.h belong to the same module according to this implementation. Because of this, this function gives some false positives. This should be sufficiently rare in practice. Args: filename_cc: is the path for the .cc file filename_h: is the path for the header path Returns: Tuple with a bool and a string: bool: True if filename_cc and filename_h belong to the same module. string: the additional prefix needed to open the header file.
Check if these two filenames belong to the same module.
[ "Check", "if", "these", "two", "filenames", "belong", "to", "the", "same", "module", "." ]
def FilesBelongToSameModule(filename_cc, filename_h): """Check if these two filenames belong to the same module. The concept of a 'module' here is a as follows: foo.h, foo-inl.h, foo.cc, foo_test.cc and foo_unittest.cc belong to the same 'module' if they are in the same directory. some/path/public/xyzzy and some/path/internal/xyzzy are also considered to belong to the same module here. If the filename_cc contains a longer path than the filename_h, for example, '/absolute/path/to/base/sysinfo.cc', and this file would include 'base/sysinfo.h', this function also produces the prefix needed to open the header. This is used by the caller of this function to more robustly open the header file. We don't have access to the real include paths in this context, so we need this guesswork here. Known bugs: tools/base/bar.cc and base/bar.h belong to the same module according to this implementation. Because of this, this function gives some false positives. This should be sufficiently rare in practice. Args: filename_cc: is the path for the .cc file filename_h: is the path for the header path Returns: Tuple with a bool and a string: bool: True if filename_cc and filename_h belong to the same module. string: the additional prefix needed to open the header file. """ if not filename_cc.endswith('.cc'): return (False, '') filename_cc = filename_cc[:-len('.cc')] if filename_cc.endswith('_unittest'): filename_cc = filename_cc[:-len('_unittest')] elif filename_cc.endswith('_test'): filename_cc = filename_cc[:-len('_test')] filename_cc = filename_cc.replace('/public/', '/') filename_cc = filename_cc.replace('/internal/', '/') if not filename_h.endswith('.h'): return (False, '') filename_h = filename_h[:-len('.h')] if filename_h.endswith('-inl'): filename_h = filename_h[:-len('-inl')] filename_h = filename_h.replace('/public/', '/') filename_h = filename_h.replace('/internal/', '/') files_belong_to_same_module = filename_cc.endswith(filename_h) common_path = '' if files_belong_to_same_module: common_path = filename_cc[:-len(filename_h)] return files_belong_to_same_module, common_path
[ "def", "FilesBelongToSameModule", "(", "filename_cc", ",", "filename_h", ")", ":", "if", "not", "filename_cc", ".", "endswith", "(", "'.cc'", ")", ":", "return", "(", "False", ",", "''", ")", "filename_cc", "=", "filename_cc", "[", ":", "-", "len", "(", "'.cc'", ")", "]", "if", "filename_cc", ".", "endswith", "(", "'_unittest'", ")", ":", "filename_cc", "=", "filename_cc", "[", ":", "-", "len", "(", "'_unittest'", ")", "]", "elif", "filename_cc", ".", "endswith", "(", "'_test'", ")", ":", "filename_cc", "=", "filename_cc", "[", ":", "-", "len", "(", "'_test'", ")", "]", "filename_cc", "=", "filename_cc", ".", "replace", "(", "'/public/'", ",", "'/'", ")", "filename_cc", "=", "filename_cc", ".", "replace", "(", "'/internal/'", ",", "'/'", ")", "if", "not", "filename_h", ".", "endswith", "(", "'.h'", ")", ":", "return", "(", "False", ",", "''", ")", "filename_h", "=", "filename_h", "[", ":", "-", "len", "(", "'.h'", ")", "]", "if", "filename_h", ".", "endswith", "(", "'-inl'", ")", ":", "filename_h", "=", "filename_h", "[", ":", "-", "len", "(", "'-inl'", ")", "]", "filename_h", "=", "filename_h", ".", "replace", "(", "'/public/'", ",", "'/'", ")", "filename_h", "=", "filename_h", ".", "replace", "(", "'/internal/'", ",", "'/'", ")", "files_belong_to_same_module", "=", "filename_cc", ".", "endswith", "(", "filename_h", ")", "common_path", "=", "''", "if", "files_belong_to_same_module", ":", "common_path", "=", "filename_cc", "[", ":", "-", "len", "(", "filename_h", ")", "]", "return", "files_belong_to_same_module", ",", "common_path" ]
https://github.com/zhaoweicai/cascade-rcnn/blob/2252f46158ea6555868ca6fa5c221ea71d9b5e6c/scripts/cpp_lint.py#L4403-L4455
windystrife/UnrealEngine_NVIDIAGameWorks
b50e6338a7c5b26374d66306ebc7807541ff815e
Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/site-packages/pkg_resources.py
python
WorkingSet.iter_entry_points
(self, group, name=None)
Yield entry point objects from `group` matching `name` If `name` is None, yields all entry points in `group` from all distributions in the working set, otherwise only ones matching both `group` and `name` are yielded (in distribution order).
Yield entry point objects from `group` matching `name`
[ "Yield", "entry", "point", "objects", "from", "group", "matching", "name" ]
def iter_entry_points(self, group, name=None): """Yield entry point objects from `group` matching `name` If `name` is None, yields all entry points in `group` from all distributions in the working set, otherwise only ones matching both `group` and `name` are yielded (in distribution order). """ for dist in self: entries = dist.get_entry_map(group) if name is None: for ep in entries.values(): yield ep elif name in entries: yield entries[name]
[ "def", "iter_entry_points", "(", "self", ",", "group", ",", "name", "=", "None", ")", ":", "for", "dist", "in", "self", ":", "entries", "=", "dist", ".", "get_entry_map", "(", "group", ")", "if", "name", "is", "None", ":", "for", "ep", "in", "entries", ".", "values", "(", ")", ":", "yield", "ep", "elif", "name", "in", "entries", ":", "yield", "entries", "[", "name", "]" ]
https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/site-packages/pkg_resources.py#L471-L484
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/Jinja2/py3/jinja2/lexer.py
python
describe_token_expr
(expr: str)
return _describe_token_type(type)
Like `describe_token` but for token expressions.
Like `describe_token` but for token expressions.
[ "Like", "describe_token", "but", "for", "token", "expressions", "." ]
def describe_token_expr(expr: str) -> str: """Like `describe_token` but for token expressions.""" if ":" in expr: type, value = expr.split(":", 1) if type == TOKEN_NAME: return value else: type = expr return _describe_token_type(type)
[ "def", "describe_token_expr", "(", "expr", ":", "str", ")", "->", "str", ":", "if", "\":\"", "in", "expr", ":", "type", ",", "value", "=", "expr", ".", "split", "(", "\":\"", ",", "1", ")", "if", "type", "==", "TOKEN_NAME", ":", "return", "value", "else", ":", "type", "=", "expr", "return", "_describe_token_type", "(", "type", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/Jinja2/py3/jinja2/lexer.py#L191-L201
windystrife/UnrealEngine_NVIDIAGameWorks
b50e6338a7c5b26374d66306ebc7807541ff815e
Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/compiler/pycodegen.py
python
CodeGenerator._implicitNameOp
(self, prefix, name)
Emit name ops for names generated implicitly by for loops The interpreter generates names that start with a period or dollar sign. The symbol table ignores these names because they aren't present in the program text.
Emit name ops for names generated implicitly by for loops
[ "Emit", "name", "ops", "for", "names", "generated", "implicitly", "by", "for", "loops" ]
def _implicitNameOp(self, prefix, name): """Emit name ops for names generated implicitly by for loops The interpreter generates names that start with a period or dollar sign. The symbol table ignores these names because they aren't present in the program text. """ if self.optimized: self.emit(prefix + '_FAST', name) else: self.emit(prefix + '_NAME', name)
[ "def", "_implicitNameOp", "(", "self", ",", "prefix", ",", "name", ")", ":", "if", "self", ".", "optimized", ":", "self", ".", "emit", "(", "prefix", "+", "'_FAST'", ",", "name", ")", "else", ":", "self", ".", "emit", "(", "prefix", "+", "'_NAME'", ",", "name", ")" ]
https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/compiler/pycodegen.py#L299-L309
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/Pygments/py3/pygments/lexers/__init__.py
python
get_lexer_for_mimetype
(_mime, **options)
Get a lexer for a mimetype. Raises ClassNotFound if not found.
Get a lexer for a mimetype.
[ "Get", "a", "lexer", "for", "a", "mimetype", "." ]
def get_lexer_for_mimetype(_mime, **options): """Get a lexer for a mimetype. Raises ClassNotFound if not found. """ for modname, name, _, _, mimetypes in LEXERS.values(): if _mime in mimetypes: if name not in _lexer_cache: _load_lexers(modname) return _lexer_cache[name](**options) for cls in find_plugin_lexers(): if _mime in cls.mimetypes: return cls(**options) raise ClassNotFound('no lexer for mimetype %r found' % _mime)
[ "def", "get_lexer_for_mimetype", "(", "_mime", ",", "*", "*", "options", ")", ":", "for", "modname", ",", "name", ",", "_", ",", "_", ",", "mimetypes", "in", "LEXERS", ".", "values", "(", ")", ":", "if", "_mime", "in", "mimetypes", ":", "if", "name", "not", "in", "_lexer_cache", ":", "_load_lexers", "(", "modname", ")", "return", "_lexer_cache", "[", "name", "]", "(", "*", "*", "options", ")", "for", "cls", "in", "find_plugin_lexers", "(", ")", ":", "if", "_mime", "in", "cls", ".", "mimetypes", ":", "return", "cls", "(", "*", "*", "options", ")", "raise", "ClassNotFound", "(", "'no lexer for mimetype %r found'", "%", "_mime", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/Pygments/py3/pygments/lexers/__init__.py#L213-L226
tensorflow/tensorflow
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
tensorflow/python/framework/convert_to_constants.py
python
_FunctionConverterDataInGraph.__init__
(self, func, lower_control_flow, aggressive_inlining, variable_names_allowlist=None, variable_names_denylist=None, session=None)
Creates the conversion data for the given function. Args: func: ConcreteFunction. lower_control_flow: Boolean indicating whether or not to lower control flow ops such as If and While. aggressive_inlining: Boolean indicating whether or not to do aggressive function inlining (might be unsafe if function has stateful ops, not properly connected to control outputs). variable_names_allowlist: The set of variable names to convert (by default, all variables are converted). variable_names_denylist: The set of variable names to omit converting to constants. session: Session object.
Creates the conversion data for the given function.
[ "Creates", "the", "conversion", "data", "for", "the", "given", "function", "." ]
def __init__(self, func, lower_control_flow, aggressive_inlining, variable_names_allowlist=None, variable_names_denylist=None, session=None): """Creates the conversion data for the given function. Args: func: ConcreteFunction. lower_control_flow: Boolean indicating whether or not to lower control flow ops such as If and While. aggressive_inlining: Boolean indicating whether or not to do aggressive function inlining (might be unsafe if function has stateful ops, not properly connected to control outputs). variable_names_allowlist: The set of variable names to convert (by default, all variables are converted). variable_names_denylist: The set of variable names to omit converting to constants. session: Session object. """ self._session = session session.run(variables.global_variables_initializer()) # Run extra assignment ops if needed. # These assignments are run sequentially to ensure order. for op in ops.get_default_graph().get_collection(VAR_ASSIGN_COLLECTION): session.run(op) super(_FunctionConverterDataInGraph, self).__init__( func, lower_control_flow, aggressive_inlining, variable_names_allowlist, variable_names_denylist)
[ "def", "__init__", "(", "self", ",", "func", ",", "lower_control_flow", ",", "aggressive_inlining", ",", "variable_names_allowlist", "=", "None", ",", "variable_names_denylist", "=", "None", ",", "session", "=", "None", ")", ":", "self", ".", "_session", "=", "session", "session", ".", "run", "(", "variables", ".", "global_variables_initializer", "(", ")", ")", "# Run extra assignment ops if needed.", "# These assignments are run sequentially to ensure order.", "for", "op", "in", "ops", ".", "get_default_graph", "(", ")", ".", "get_collection", "(", "VAR_ASSIGN_COLLECTION", ")", ":", "session", ".", "run", "(", "op", ")", "super", "(", "_FunctionConverterDataInGraph", ",", "self", ")", ".", "__init__", "(", "func", ",", "lower_control_flow", ",", "aggressive_inlining", ",", "variable_names_allowlist", ",", "variable_names_denylist", ")" ]
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/framework/convert_to_constants.py#L874-L909
tensorflow/tensorflow
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
tensorflow/python/keras/saving/saved_model/serialized_attributes.py
python
SerializedAttributes.set_and_validate_objects
(self, object_dict)
return self.checkpointable_objects
Saves objects to a dictionary, and validates the values.
Saves objects to a dictionary, and validates the values.
[ "Saves", "objects", "to", "a", "dictionary", "and", "validates", "the", "values", "." ]
def set_and_validate_objects(self, object_dict): """Saves objects to a dictionary, and validates the values.""" for key in self.all_checkpointable_objects: if key in object_dict: if not isinstance(object_dict[key], trackable.Trackable): raise ValueError( 'Object dictionary contained a non-trackable object: {} (for key' ' {})'.format(object_dict[key], key)) self._object_dict[key] = object_dict[key] setattr(self._keras_trackable, key, object_dict[key]) else: raise ValueError( 'Object {} missing from serialized object dict.'.format(key)) return self.checkpointable_objects
[ "def", "set_and_validate_objects", "(", "self", ",", "object_dict", ")", ":", "for", "key", "in", "self", ".", "all_checkpointable_objects", ":", "if", "key", "in", "object_dict", ":", "if", "not", "isinstance", "(", "object_dict", "[", "key", "]", ",", "trackable", ".", "Trackable", ")", ":", "raise", "ValueError", "(", "'Object dictionary contained a non-trackable object: {} (for key'", "' {})'", ".", "format", "(", "object_dict", "[", "key", "]", ",", "key", ")", ")", "self", ".", "_object_dict", "[", "key", "]", "=", "object_dict", "[", "key", "]", "setattr", "(", "self", ".", "_keras_trackable", ",", "key", ",", "object_dict", "[", "key", "]", ")", "else", ":", "raise", "ValueError", "(", "'Object {} missing from serialized object dict.'", ".", "format", "(", "key", ")", ")", "return", "self", ".", "checkpointable_objects" ]
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/keras/saving/saved_model/serialized_attributes.py#L210-L223
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/ipython/py2/IPython/core/formatters.py
python
BaseFormatter.__call__
(self, obj)
Compute the format for an object.
Compute the format for an object.
[ "Compute", "the", "format", "for", "an", "object", "." ]
def __call__(self, obj): """Compute the format for an object.""" if self.enabled: # lookup registered printer try: printer = self.lookup(obj) except KeyError: pass else: return printer(obj) # Finally look for special method names method = get_real_method(obj, self.print_method) if method is not None: return method() return None else: return None
[ "def", "__call__", "(", "self", ",", "obj", ")", ":", "if", "self", ".", "enabled", ":", "# lookup registered printer", "try", ":", "printer", "=", "self", ".", "lookup", "(", "obj", ")", "except", "KeyError", ":", "pass", "else", ":", "return", "printer", "(", "obj", ")", "# Finally look for special method names", "method", "=", "get_real_method", "(", "obj", ",", "self", ".", "print_method", ")", "if", "method", "is", "not", "None", ":", "return", "method", "(", ")", "return", "None", "else", ":", "return", "None" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/ipython/py2/IPython/core/formatters.py#L325-L341
microsoft/checkedc-clang
a173fefde5d7877b7750e7ce96dd08cf18baebf2
lldb/examples/python/symbolication.py
python
Symbolicator.InitWithSBTarget
(cls, target)
return obj
Initialize a new Symbolicator with an existing SBTarget.
Initialize a new Symbolicator with an existing SBTarget.
[ "Initialize", "a", "new", "Symbolicator", "with", "an", "existing", "SBTarget", "." ]
def InitWithSBTarget(cls, target): """Initialize a new Symbolicator with an existing SBTarget.""" obj = cls(target=target) triple = target.triple if triple: arch = triple.split('-')[0] if "arm" in arch: obj.addr_mask = 0xfffffffffffffffe for module in target.modules: image = Image.InitWithSBTargetAndSBModule(target, module) obj.images.append(image) return obj
[ "def", "InitWithSBTarget", "(", "cls", ",", "target", ")", ":", "obj", "=", "cls", "(", "target", "=", "target", ")", "triple", "=", "target", ".", "triple", "if", "triple", ":", "arch", "=", "triple", ".", "split", "(", "'-'", ")", "[", "0", "]", "if", "\"arm\"", "in", "arch", ":", "obj", ".", "addr_mask", "=", "0xfffffffffffffffe", "for", "module", "in", "target", ".", "modules", ":", "image", "=", "Image", ".", "InitWithSBTargetAndSBModule", "(", "target", ",", "module", ")", "obj", ".", "images", ".", "append", "(", "image", ")", "return", "obj" ]
https://github.com/microsoft/checkedc-clang/blob/a173fefde5d7877b7750e7ce96dd08cf18baebf2/lldb/examples/python/symbolication.py#L453-L465
kitao/pyxel
f58bd6fe84153219a1e5edc506ae9606614883dc
pyxel/examples/07_snake.py
python
Snake.death_event
(self)
Kill the game (bring up end screen).
Kill the game (bring up end screen).
[ "Kill", "the", "game", "(", "bring", "up", "end", "screen", ")", "." ]
def death_event(self): """Kill the game (bring up end screen).""" self.death = True # Check having run into self pyxel.stop() pyxel.play(0, 1)
[ "def", "death_event", "(", "self", ")", ":", "self", ".", "death", "=", "True", "# Check having run into self", "pyxel", ".", "stop", "(", ")", "pyxel", ".", "play", "(", "0", ",", "1", ")" ]
https://github.com/kitao/pyxel/blob/f58bd6fe84153219a1e5edc506ae9606614883dc/pyxel/examples/07_snake.py#L153-L158
ivansafrin/Polycode
37a40fefe194ec7f6e9d1257f3bb3517b0a168bc
Bindings/Scripts/create_lua_library/CppHeaderParser3.py
python
t_COMMENT_SINGLELINE
(t)
r'\/\/.*\n
r'\/\/.*\n
[ "r", "\\", "/", "\\", "/", ".", "*", "\\", "n" ]
def t_COMMENT_SINGLELINE(t): r'\/\/.*\n' global doxygenCommentCache if t.value.startswith("///") or t.value.startswith("//!"): if doxygenCommentCache: doxygenCommentCache += "\n" if t.value.endswith("\n"): doxygenCommentCache += t.value[:-1] else: doxygenCommentCache += t.value t.lexer.lineno += len([a for a in t.value if a=="\n"])
[ "def", "t_COMMENT_SINGLELINE", "(", "t", ")", ":", "global", "doxygenCommentCache", "if", "t", ".", "value", ".", "startswith", "(", "\"///\"", ")", "or", "t", ".", "value", ".", "startswith", "(", "\"//!\"", ")", ":", "if", "doxygenCommentCache", ":", "doxygenCommentCache", "+=", "\"\\n\"", "if", "t", ".", "value", ".", "endswith", "(", "\"\\n\"", ")", ":", "doxygenCommentCache", "+=", "t", ".", "value", "[", ":", "-", "1", "]", "else", ":", "doxygenCommentCache", "+=", "t", ".", "value", "t", ".", "lexer", ".", "lineno", "+=", "len", "(", "[", "a", "for", "a", "in", "t", ".", "value", "if", "a", "==", "\"\\n\"", "]", ")" ]
https://github.com/ivansafrin/Polycode/blob/37a40fefe194ec7f6e9d1257f3bb3517b0a168bc/Bindings/Scripts/create_lua_library/CppHeaderParser3.py#L118-L128
baidu-research/tensorflow-allreduce
66d5b855e90b0949e9fa5cca5599fd729a70e874
tensorflow/contrib/rnn/python/ops/rnn_cell.py
python
GridLSTMCell._make_tf_features
(self, input_feat, slice_offset=0)
return freq_inputs
Make the frequency features. Args: input_feat: input Tensor, 2D, [batch, num_units]. slice_offset: (optional) Python int, default 0, the slicing offset is only used for the backward processing in the BidirectionalGridLSTMCell. It specifies a different starting point instead of always 0 to enable the forward and backward processing look at different frequency blocks. Returns: A list of frequency features, with each element containing: - A 2D, [batch, output_dim], Tensor representing the time-frequency feature for that frequency index. Here output_dim is feature_size. Raises: ValueError: if input_size cannot be inferred from static shape inference.
Make the frequency features.
[ "Make", "the", "frequency", "features", "." ]
def _make_tf_features(self, input_feat, slice_offset=0): """Make the frequency features. Args: input_feat: input Tensor, 2D, [batch, num_units]. slice_offset: (optional) Python int, default 0, the slicing offset is only used for the backward processing in the BidirectionalGridLSTMCell. It specifies a different starting point instead of always 0 to enable the forward and backward processing look at different frequency blocks. Returns: A list of frequency features, with each element containing: - A 2D, [batch, output_dim], Tensor representing the time-frequency feature for that frequency index. Here output_dim is feature_size. Raises: ValueError: if input_size cannot be inferred from static shape inference. """ input_size = input_feat.get_shape().with_rank(2)[-1].value if input_size is None: raise ValueError("Cannot infer input_size from static shape inference.") if slice_offset > 0: # Padding to the end inputs = array_ops.pad( input_feat, array_ops.constant([0, 0, 0, slice_offset], shape=[2, 2], dtype=dtypes.int32), "CONSTANT") elif slice_offset < 0: # Padding to the front inputs = array_ops.pad( input_feat, array_ops.constant([0, 0, -slice_offset, 0], shape=[2, 2], dtype=dtypes.int32), "CONSTANT") slice_offset = 0 else: inputs = input_feat freq_inputs = [] if not self._start_freqindex_list: if len(self._num_frequency_blocks) != 1: raise ValueError("Length of num_frequency_blocks" " is not 1, but instead is %d", len(self._num_frequency_blocks)) num_feats = int((input_size - self._feature_size) / ( self._frequency_skip)) + 1 if num_feats != self._num_frequency_blocks[0]: raise ValueError( "Invalid num_frequency_blocks, requires %d but gets %d, please" " check the input size and filter config are correct." % ( self._num_frequency_blocks[0], num_feats)) block_inputs = [] for f in range(num_feats): cur_input = array_ops.slice( inputs, [0, slice_offset + f * self._frequency_skip], [-1, self._feature_size]) block_inputs.append(cur_input) freq_inputs.append(block_inputs) else: if len(self._start_freqindex_list) != len(self._end_freqindex_list): raise ValueError("Length of start and end freqindex_list" " does not match %d %d", len(self._start_freqindex_list), len(self._end_freqindex_list)) if len(self._num_frequency_blocks) != len(self._start_freqindex_list): raise ValueError("Length of num_frequency_blocks" " is not equal to start_freqindex_list %d %d", len(self._num_frequency_blocks), len(self._start_freqindex_list)) for b in range(len(self._start_freqindex_list)): start_index = self._start_freqindex_list[b] end_index = self._end_freqindex_list[b] cur_size = end_index - start_index block_feats = int((cur_size - self._feature_size) / ( self._frequency_skip)) + 1 if block_feats != self._num_frequency_blocks[b]: raise ValueError( "Invalid num_frequency_blocks, requires %d but gets %d, please" " check the input size and filter config are correct." % ( self._num_frequency_blocks[b], block_feats)) block_inputs = [] for f in range(block_feats): cur_input = array_ops.slice( inputs, [0, start_index + slice_offset + f * self._frequency_skip], [-1, self._feature_size]) block_inputs.append(cur_input) freq_inputs.append(block_inputs) return freq_inputs
[ "def", "_make_tf_features", "(", "self", ",", "input_feat", ",", "slice_offset", "=", "0", ")", ":", "input_size", "=", "input_feat", ".", "get_shape", "(", ")", ".", "with_rank", "(", "2", ")", "[", "-", "1", "]", ".", "value", "if", "input_size", "is", "None", ":", "raise", "ValueError", "(", "\"Cannot infer input_size from static shape inference.\"", ")", "if", "slice_offset", ">", "0", ":", "# Padding to the end", "inputs", "=", "array_ops", ".", "pad", "(", "input_feat", ",", "array_ops", ".", "constant", "(", "[", "0", ",", "0", ",", "0", ",", "slice_offset", "]", ",", "shape", "=", "[", "2", ",", "2", "]", ",", "dtype", "=", "dtypes", ".", "int32", ")", ",", "\"CONSTANT\"", ")", "elif", "slice_offset", "<", "0", ":", "# Padding to the front", "inputs", "=", "array_ops", ".", "pad", "(", "input_feat", ",", "array_ops", ".", "constant", "(", "[", "0", ",", "0", ",", "-", "slice_offset", ",", "0", "]", ",", "shape", "=", "[", "2", ",", "2", "]", ",", "dtype", "=", "dtypes", ".", "int32", ")", ",", "\"CONSTANT\"", ")", "slice_offset", "=", "0", "else", ":", "inputs", "=", "input_feat", "freq_inputs", "=", "[", "]", "if", "not", "self", ".", "_start_freqindex_list", ":", "if", "len", "(", "self", ".", "_num_frequency_blocks", ")", "!=", "1", ":", "raise", "ValueError", "(", "\"Length of num_frequency_blocks\"", "\" is not 1, but instead is %d\"", ",", "len", "(", "self", ".", "_num_frequency_blocks", ")", ")", "num_feats", "=", "int", "(", "(", "input_size", "-", "self", ".", "_feature_size", ")", "/", "(", "self", ".", "_frequency_skip", ")", ")", "+", "1", "if", "num_feats", "!=", "self", ".", "_num_frequency_blocks", "[", "0", "]", ":", "raise", "ValueError", "(", "\"Invalid num_frequency_blocks, requires %d but gets %d, please\"", "\" check the input size and filter config are correct.\"", "%", "(", "self", ".", "_num_frequency_blocks", "[", "0", "]", ",", "num_feats", ")", ")", "block_inputs", "=", "[", "]", "for", "f", "in", "range", "(", "num_feats", ")", ":", "cur_input", "=", "array_ops", ".", "slice", "(", "inputs", ",", "[", "0", ",", "slice_offset", "+", "f", "*", "self", ".", "_frequency_skip", "]", ",", "[", "-", "1", ",", "self", ".", "_feature_size", "]", ")", "block_inputs", ".", "append", "(", "cur_input", ")", "freq_inputs", ".", "append", "(", "block_inputs", ")", "else", ":", "if", "len", "(", "self", ".", "_start_freqindex_list", ")", "!=", "len", "(", "self", ".", "_end_freqindex_list", ")", ":", "raise", "ValueError", "(", "\"Length of start and end freqindex_list\"", "\" does not match %d %d\"", ",", "len", "(", "self", ".", "_start_freqindex_list", ")", ",", "len", "(", "self", ".", "_end_freqindex_list", ")", ")", "if", "len", "(", "self", ".", "_num_frequency_blocks", ")", "!=", "len", "(", "self", ".", "_start_freqindex_list", ")", ":", "raise", "ValueError", "(", "\"Length of num_frequency_blocks\"", "\" is not equal to start_freqindex_list %d %d\"", ",", "len", "(", "self", ".", "_num_frequency_blocks", ")", ",", "len", "(", "self", ".", "_start_freqindex_list", ")", ")", "for", "b", "in", "range", "(", "len", "(", "self", ".", "_start_freqindex_list", ")", ")", ":", "start_index", "=", "self", ".", "_start_freqindex_list", "[", "b", "]", "end_index", "=", "self", ".", "_end_freqindex_list", "[", "b", "]", "cur_size", "=", "end_index", "-", "start_index", "block_feats", "=", "int", "(", "(", "cur_size", "-", "self", ".", "_feature_size", ")", "/", "(", "self", ".", "_frequency_skip", ")", ")", "+", "1", "if", "block_feats", "!=", "self", ".", "_num_frequency_blocks", "[", "b", "]", ":", "raise", "ValueError", "(", "\"Invalid num_frequency_blocks, requires %d but gets %d, please\"", "\" check the input size and filter config are correct.\"", "%", "(", "self", ".", "_num_frequency_blocks", "[", "b", "]", ",", "block_feats", ")", ")", "block_inputs", "=", "[", "]", "for", "f", "in", "range", "(", "block_feats", ")", ":", "cur_input", "=", "array_ops", ".", "slice", "(", "inputs", ",", "[", "0", ",", "start_index", "+", "slice_offset", "+", "f", "*", "self", ".", "_frequency_skip", "]", ",", "[", "-", "1", ",", "self", ".", "_feature_size", "]", ")", "block_inputs", ".", "append", "(", "cur_input", ")", "freq_inputs", ".", "append", "(", "block_inputs", ")", "return", "freq_inputs" ]
https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/contrib/rnn/python/ops/rnn_cell.py#L801-L886
trilinos/Trilinos
6168be6dd51e35e1cd681e9c4b24433e709df140
packages/seacas/scripts/exomerge3.py
python
ExodusModel._missing_error
(self, name, entity)
Tell the user something does not exist and exit.
Tell the user something does not exist and exit.
[ "Tell", "the", "user", "something", "does", "not", "exist", "and", "exit", "." ]
def _missing_error(self, name, entity): """Tell the user something does not exist and exit.""" self._error( entity[0].upper() + entity[1:] + ' does not exist.', 'The specified %s "%s" does not exist.' % (entity, str(name)))
[ "def", "_missing_error", "(", "self", ",", "name", ",", "entity", ")", ":", "self", ".", "_error", "(", "entity", "[", "0", "]", ".", "upper", "(", ")", "+", "entity", "[", "1", ":", "]", "+", "' does not exist.'", ",", "'The specified %s \"%s\" does not exist.'", "%", "(", "entity", ",", "str", "(", "name", ")", ")", ")" ]
https://github.com/trilinos/Trilinos/blob/6168be6dd51e35e1cd681e9c4b24433e709df140/packages/seacas/scripts/exomerge3.py#L6014-L6018
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python3/src/Lib/ast.py
python
_Unparser.require_parens
(self, precedence, node)
return self.delimit_if("(", ")", self.get_precedence(node) > precedence)
Shortcut to adding precedence related parens
Shortcut to adding precedence related parens
[ "Shortcut", "to", "adding", "precedence", "related", "parens" ]
def require_parens(self, precedence, node): """Shortcut to adding precedence related parens""" return self.delimit_if("(", ")", self.get_precedence(node) > precedence)
[ "def", "require_parens", "(", "self", ",", "precedence", ",", "node", ")", ":", "return", "self", ".", "delimit_if", "(", "\"(\"", ",", "\")\"", ",", "self", ".", "get_precedence", "(", "node", ")", ">", "precedence", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/ast.py#L758-L760
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/plotting/_core.py
python
_find_backend
(backend: str)
Find a pandas plotting backend> Parameters ---------- backend : str The identifier for the backend. Either an entrypoint item registered with pkg_resources, or a module name. Notes ----- Modifies _backends with imported backends as a side effect. Returns ------- types.ModuleType The imported backend.
Find a pandas plotting backend>
[ "Find", "a", "pandas", "plotting", "backend", ">" ]
def _find_backend(backend: str): """ Find a pandas plotting backend> Parameters ---------- backend : str The identifier for the backend. Either an entrypoint item registered with pkg_resources, or a module name. Notes ----- Modifies _backends with imported backends as a side effect. Returns ------- types.ModuleType The imported backend. """ import pkg_resources # Delay import for performance. for entry_point in pkg_resources.iter_entry_points("pandas_plotting_backends"): if entry_point.name == "matplotlib": # matplotlib is an optional dependency. When # missing, this would raise. continue _backends[entry_point.name] = entry_point.load() try: return _backends[backend] except KeyError: # Fall back to unregisted, module name approach. try: module = importlib.import_module(backend) except ImportError: # We re-raise later on. pass else: if hasattr(module, "plot"): # Validate that the interface is implemented when the option # is set, rather than at plot time. _backends[backend] = module return module raise ValueError( f"Could not find plotting backend '{backend}'. Ensure that you've installed " f"the package providing the '{backend}' entrypoint, or that the package has a " "top-level `.plot` method." )
[ "def", "_find_backend", "(", "backend", ":", "str", ")", ":", "import", "pkg_resources", "# Delay import for performance.", "for", "entry_point", "in", "pkg_resources", ".", "iter_entry_points", "(", "\"pandas_plotting_backends\"", ")", ":", "if", "entry_point", ".", "name", "==", "\"matplotlib\"", ":", "# matplotlib is an optional dependency. When", "# missing, this would raise.", "continue", "_backends", "[", "entry_point", ".", "name", "]", "=", "entry_point", ".", "load", "(", ")", "try", ":", "return", "_backends", "[", "backend", "]", "except", "KeyError", ":", "# Fall back to unregisted, module name approach.", "try", ":", "module", "=", "importlib", ".", "import_module", "(", "backend", ")", "except", "ImportError", ":", "# We re-raise later on.", "pass", "else", ":", "if", "hasattr", "(", "module", ",", "\"plot\"", ")", ":", "# Validate that the interface is implemented when the option", "# is set, rather than at plot time.", "_backends", "[", "backend", "]", "=", "module", "return", "module", "raise", "ValueError", "(", "f\"Could not find plotting backend '{backend}'. Ensure that you've installed \"", "f\"the package providing the '{backend}' entrypoint, or that the package has a \"", "\"top-level `.plot` method.\"", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/plotting/_core.py#L1594-L1642
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/saved_model/load_v1_in_v2.py
python
_EagerSavedModelLoader.load_graph
(self, returns, meta_graph_def)
Called from wrap_function to import `meta_graph_def`.
Called from wrap_function to import `meta_graph_def`.
[ "Called", "from", "wrap_function", "to", "import", "meta_graph_def", "." ]
def load_graph(self, returns, meta_graph_def): """Called from wrap_function to import `meta_graph_def`.""" # pylint: disable=protected-access saver, _ = tf_saver._import_meta_graph_with_return_elements( meta_graph_def) # pylint: enable=protected-access returns[0] = saver
[ "def", "load_graph", "(", "self", ",", "returns", ",", "meta_graph_def", ")", ":", "# pylint: disable=protected-access", "saver", ",", "_", "=", "tf_saver", ".", "_import_meta_graph_with_return_elements", "(", "meta_graph_def", ")", "# pylint: enable=protected-access", "returns", "[", "0", "]", "=", "saver" ]
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/saved_model/load_v1_in_v2.py#L85-L91
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/_windows.py
python
Dialog.GetMainButtonIds
(*args, **kwargs)
return _windows_.Dialog_GetMainButtonIds(*args, **kwargs)
GetMainButtonIds(self) -> wxArrayInt
GetMainButtonIds(self) -> wxArrayInt
[ "GetMainButtonIds", "(", "self", ")", "-", ">", "wxArrayInt" ]
def GetMainButtonIds(*args, **kwargs): """GetMainButtonIds(self) -> wxArrayInt""" return _windows_.Dialog_GetMainButtonIds(*args, **kwargs)
[ "def", "GetMainButtonIds", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_windows_", ".", "Dialog_GetMainButtonIds", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_windows.py#L835-L837
LiquidPlayer/LiquidCore
9405979363f2353ac9a71ad8ab59685dd7f919c9
deps/boost_1_66_0/libs/mpl/preprocessed/boost_mpl_preprocess.py
python
adjust_container_limits_for_variadic_sequences
(headerDir, containers, maxElements)
Adjusts the limits of variadic sequence MPL-containers.
Adjusts the limits of variadic sequence MPL-containers.
[ "Adjusts", "the", "limits", "of", "variadic", "sequence", "MPL", "-", "containers", "." ]
def adjust_container_limits_for_variadic_sequences(headerDir, containers, maxElements): """Adjusts the limits of variadic sequence MPL-containers.""" for container in containers: headerFile = os.path.join( headerDir, "limits", container + ".hpp" ) regexMatch = r'(define\s+BOOST_MPL_LIMIT_' + container.upper() + r'_SIZE\s+)[0-9]+' regexReplace = r'\g<1>' + re.escape( str(maxElements) ) for line in fileinput.input( headerFile, inplace=1, mode="rU" ): line = re.sub(regexMatch, regexReplace, line.rstrip()) print(line)
[ "def", "adjust_container_limits_for_variadic_sequences", "(", "headerDir", ",", "containers", ",", "maxElements", ")", ":", "for", "container", "in", "containers", ":", "headerFile", "=", "os", ".", "path", ".", "join", "(", "headerDir", ",", "\"limits\"", ",", "container", "+", "\".hpp\"", ")", "regexMatch", "=", "r'(define\\s+BOOST_MPL_LIMIT_'", "+", "container", ".", "upper", "(", ")", "+", "r'_SIZE\\s+)[0-9]+'", "regexReplace", "=", "r'\\g<1>'", "+", "re", ".", "escape", "(", "str", "(", "maxElements", ")", ")", "for", "line", "in", "fileinput", ".", "input", "(", "headerFile", ",", "inplace", "=", "1", ",", "mode", "=", "\"rU\"", ")", ":", "line", "=", "re", ".", "sub", "(", "regexMatch", ",", "regexReplace", ",", "line", ".", "rstrip", "(", ")", ")", "print", "(", "line", ")" ]
https://github.com/LiquidPlayer/LiquidCore/blob/9405979363f2353ac9a71ad8ab59685dd7f919c9/deps/boost_1_66_0/libs/mpl/preprocessed/boost_mpl_preprocess.py#L70-L78
psi4/psi4
be533f7f426b6ccc263904e55122899b16663395
psi4/driver/qcdb/orient.py
python
OrientMols.__init__
(self, molPermanent, molChangeable)
Stores the shift, rotation, axis exchange, axis inversion, and atom remapping necessary to bring the geometry of *molChangeable* into coincidence with the geometry of *molPermanent*. *molPermanent* and *molChangeable* must be :py:class:`qcdb.Molecule` and represent the same geometry.
Stores the shift, rotation, axis exchange, axis inversion, and atom remapping necessary to bring the geometry of *molChangeable* into coincidence with the geometry of *molPermanent*. *molPermanent* and *molChangeable* must be :py:class:`qcdb.Molecule` and represent the same geometry.
[ "Stores", "the", "shift", "rotation", "axis", "exchange", "axis", "inversion", "and", "atom", "remapping", "necessary", "to", "bring", "the", "geometry", "of", "*", "molChangeable", "*", "into", "coincidence", "with", "the", "geometry", "of", "*", "molPermanent", "*", ".", "*", "molPermanent", "*", "and", "*", "molChangeable", "*", "must", "be", ":", "py", ":", "class", ":", "qcdb", ".", "Molecule", "and", "represent", "the", "same", "geometry", "." ]
def __init__(self, molPermanent, molChangeable): """Stores the shift, rotation, axis exchange, axis inversion, and atom remapping necessary to bring the geometry of *molChangeable* into coincidence with the geometry of *molPermanent*. *molPermanent* and *molChangeable* must be :py:class:`qcdb.Molecule` and represent the same geometry. """ # <<< Permanent (Psi4) >>> # Molecule self.Pmol = molPermanent # Vector to shift Pmol to center of mass self.Pshift = [] # Matrix to rotate Pmol to inertial frame self.Protate = [] # <<< Changeable (Cfour) >>> # Molecule self.Cmol = molChangeable # Vector to shift Cmol to center of mass self.Cshift = [] # Matrix to rotate Cmol to inertial frame self.Crotate = [] # Matrix to rotate Cmol to axis representation of Pmol self.Cexchflip = [] # Vector to map Cmol to atom ordering of Pmol self.Catommap = [] try: if ((self.Pmol.nallatom() == self.Cmol.nallatom()) and \ (abs(self.Pmol.nuclear_repulsion_energy() - self.Cmol.nuclear_repulsion_energy()) < 1.0e-3)): self.create_orientation_from_molecules(self.Pmol, self.Cmol) else: print('qcdb.orient.__init__ debug info') self.Pmol.print_out() print('natom', self.Pmol.natom(), 'NRE', self.Pmol.nuclear_repulsion_energy(), 'rotor', self.Pmol.rotor_type()) self.Cmol.print_out() print('natom', self.Cmol.natom(), 'NRE', self.Cmol.nuclear_repulsion_energy(), 'rotor', self.Cmol.rotor_type()) raise ValidationError("""OrientMols Molecule arguments differ fatally.""") except AttributeError: raise ValidationError("""OrientMols must be instantiated with two qcdb.Molecule objects.""")
[ "def", "__init__", "(", "self", ",", "molPermanent", ",", "molChangeable", ")", ":", "# <<< Permanent (Psi4) >>>", "# Molecule", "self", ".", "Pmol", "=", "molPermanent", "# Vector to shift Pmol to center of mass", "self", ".", "Pshift", "=", "[", "]", "# Matrix to rotate Pmol to inertial frame", "self", ".", "Protate", "=", "[", "]", "# <<< Changeable (Cfour) >>>", "# Molecule", "self", ".", "Cmol", "=", "molChangeable", "# Vector to shift Cmol to center of mass", "self", ".", "Cshift", "=", "[", "]", "# Matrix to rotate Cmol to inertial frame", "self", ".", "Crotate", "=", "[", "]", "# Matrix to rotate Cmol to axis representation of Pmol", "self", ".", "Cexchflip", "=", "[", "]", "# Vector to map Cmol to atom ordering of Pmol", "self", ".", "Catommap", "=", "[", "]", "try", ":", "if", "(", "(", "self", ".", "Pmol", ".", "nallatom", "(", ")", "==", "self", ".", "Cmol", ".", "nallatom", "(", ")", ")", "and", "(", "abs", "(", "self", ".", "Pmol", ".", "nuclear_repulsion_energy", "(", ")", "-", "self", ".", "Cmol", ".", "nuclear_repulsion_energy", "(", ")", ")", "<", "1.0e-3", ")", ")", ":", "self", ".", "create_orientation_from_molecules", "(", "self", ".", "Pmol", ",", "self", ".", "Cmol", ")", "else", ":", "print", "(", "'qcdb.orient.__init__ debug info'", ")", "self", ".", "Pmol", ".", "print_out", "(", ")", "print", "(", "'natom'", ",", "self", ".", "Pmol", ".", "natom", "(", ")", ",", "'NRE'", ",", "self", ".", "Pmol", ".", "nuclear_repulsion_energy", "(", ")", ",", "'rotor'", ",", "self", ".", "Pmol", ".", "rotor_type", "(", ")", ")", "self", ".", "Cmol", ".", "print_out", "(", ")", "print", "(", "'natom'", ",", "self", ".", "Cmol", ".", "natom", "(", ")", ",", "'NRE'", ",", "self", ".", "Cmol", ".", "nuclear_repulsion_energy", "(", ")", ",", "'rotor'", ",", "self", ".", "Cmol", ".", "rotor_type", "(", ")", ")", "raise", "ValidationError", "(", "\"\"\"OrientMols Molecule arguments differ fatally.\"\"\"", ")", "except", "AttributeError", ":", "raise", "ValidationError", "(", "\"\"\"OrientMols must be instantiated with two qcdb.Molecule objects.\"\"\"", ")" ]
https://github.com/psi4/psi4/blob/be533f7f426b6ccc263904e55122899b16663395/psi4/driver/qcdb/orient.py#L57-L99
gromacs/gromacs
7dec3a3f99993cf5687a122de3e12de31c21c399
python_packaging/src/gmxapi/operation.py
python
Future.result
(self)
Fetch data to the caller's Context. Returns an object of the concrete type specified according to the operation that produces this Result. Ensemble data are returned as a list. Scalar results or results from single member ensembles are returned as scalars.
Fetch data to the caller's Context.
[ "Fetch", "data", "to", "the", "caller", "s", "Context", "." ]
def result(self) -> ResultTypeVar: """Fetch data to the caller's Context. Returns an object of the concrete type specified according to the operation that produces this Result. Ensemble data are returned as a list. Scalar results or results from single member ensembles are returned as scalars. """ self.resource_manager.update_output() # Return ownership of concrete data handle = self.resource_manager.get(self.name) # For intuitive use in non-ensemble cases, we represent data as bare scalars # when possible. It is easier for users to cast scalars to lists of length 1 # than to introspect their own code to determine if a list of length 1 is # part of an ensemble or not. The data model will become clearer as we # develop more robust handling of multidimensional data and data flow topologies. # In the future, # we may distinguish between data of shape () and shape (1,), but we will need # to be careful with semantics. We are already starting to adopt a rule-of-thumb # that data objects assume the minimum dimensionality necessary unless told # otherwise, and we could make that a hard rule if it doesn't make other things # too difficult. if self.description.width == 1: return handle.data(member=0) else: return handle.data()
[ "def", "result", "(", "self", ")", "->", "ResultTypeVar", ":", "self", ".", "resource_manager", ".", "update_output", "(", ")", "# Return ownership of concrete data", "handle", "=", "self", ".", "resource_manager", ".", "get", "(", "self", ".", "name", ")", "# For intuitive use in non-ensemble cases, we represent data as bare scalars", "# when possible. It is easier for users to cast scalars to lists of length 1", "# than to introspect their own code to determine if a list of length 1 is", "# part of an ensemble or not. The data model will become clearer as we", "# develop more robust handling of multidimensional data and data flow topologies.", "# In the future,", "# we may distinguish between data of shape () and shape (1,), but we will need", "# to be careful with semantics. We are already starting to adopt a rule-of-thumb", "# that data objects assume the minimum dimensionality necessary unless told", "# otherwise, and we could make that a hard rule if it doesn't make other things", "# too difficult.", "if", "self", ".", "description", ".", "width", "==", "1", ":", "return", "handle", ".", "data", "(", "member", "=", "0", ")", "else", ":", "return", "handle", ".", "data", "(", ")" ]
https://github.com/gromacs/gromacs/blob/7dec3a3f99993cf5687a122de3e12de31c21c399/python_packaging/src/gmxapi/operation.py#L1409-L1436
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/_core.py
python
Window.GetBorder
(*args)
return _core_.Window_GetBorder(*args)
GetBorder(self, long flags) -> int GetBorder(self) -> int Get border for the flags of this window
GetBorder(self, long flags) -> int GetBorder(self) -> int
[ "GetBorder", "(", "self", "long", "flags", ")", "-", ">", "int", "GetBorder", "(", "self", ")", "-", ">", "int" ]
def GetBorder(*args): """ GetBorder(self, long flags) -> int GetBorder(self) -> int Get border for the flags of this window """ return _core_.Window_GetBorder(*args)
[ "def", "GetBorder", "(", "*", "args", ")", ":", "return", "_core_", ".", "Window_GetBorder", "(", "*", "args", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_core.py#L11096-L11103
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/sysconfig.py
python
get_platform
()
return "%s-%s-%s" % (osname, release, machine)
Return a string that identifies the current platform. This is used mainly to distinguish platform-specific build directories and platform-specific built distributions. Typically includes the OS name and version and the architecture (as supplied by 'os.uname()'), although the exact information included depends on the OS; eg. for IRIX the architecture isn't particularly important (IRIX only runs on SGI hardware), but for Linux the kernel version isn't particularly important. Examples of returned values: linux-i586 linux-alpha (?) solaris-2.6-sun4u irix-5.3 irix64-6.2 Windows will return one of: win-amd64 (64bit Windows on AMD64 (aka x86_64, Intel64, EM64T, etc) win-ia64 (64bit Windows on Itanium) win32 (all others - specifically, sys.platform is returned) For other non-POSIX platforms, currently just returns 'sys.platform'.
Return a string that identifies the current platform.
[ "Return", "a", "string", "that", "identifies", "the", "current", "platform", "." ]
def get_platform(): """Return a string that identifies the current platform. This is used mainly to distinguish platform-specific build directories and platform-specific built distributions. Typically includes the OS name and version and the architecture (as supplied by 'os.uname()'), although the exact information included depends on the OS; eg. for IRIX the architecture isn't particularly important (IRIX only runs on SGI hardware), but for Linux the kernel version isn't particularly important. Examples of returned values: linux-i586 linux-alpha (?) solaris-2.6-sun4u irix-5.3 irix64-6.2 Windows will return one of: win-amd64 (64bit Windows on AMD64 (aka x86_64, Intel64, EM64T, etc) win-ia64 (64bit Windows on Itanium) win32 (all others - specifically, sys.platform is returned) For other non-POSIX platforms, currently just returns 'sys.platform'. """ import re if os.name == 'nt': # sniff sys.version for architecture. prefix = " bit (" i = sys.version.find(prefix) if i == -1: return sys.platform j = sys.version.find(")", i) look = sys.version[i+len(prefix):j].lower() if look == 'amd64': return 'win-amd64' if look == 'itanium': return 'win-ia64' return sys.platform # Set for cross builds explicitly if "_PYTHON_HOST_PLATFORM" in os.environ: return os.environ["_PYTHON_HOST_PLATFORM"] if os.name != "posix" or not hasattr(os, 'uname'): # XXX what about the architecture? NT is Intel or Alpha, # Mac OS is M68k or PPC, etc. return sys.platform # Try to distinguish various flavours of Unix osname, host, release, version, machine = os.uname() # Convert the OS name to lowercase, remove '/' characters # (to accommodate BSD/OS), and translate spaces (for "Power Macintosh") osname = osname.lower().replace('/', '') machine = machine.replace(' ', '_') machine = machine.replace('/', '-') if osname[:5] == "linux": # At least on Linux/Intel, 'machine' is the processor -- # i386, etc. # XXX what about Alpha, SPARC, etc? return "%s-%s" % (osname, machine) elif osname[:5] == "sunos": if release[0] >= "5": # SunOS 5 == Solaris 2 osname = "solaris" release = "%d.%s" % (int(release[0]) - 3, release[2:]) # We can't use "platform.architecture()[0]" because a # bootstrap problem. We use a dict to get an error # if some suspicious happens. bitness = {2147483647:"32bit", 9223372036854775807:"64bit"} machine += ".%s" % bitness[sys.maxint] # fall through to standard osname-release-machine representation elif osname[:4] == "irix": # could be "irix64"! return "%s-%s" % (osname, release) elif osname[:3] == "aix": return "%s-%s.%s" % (osname, version, release) elif osname[:6] == "cygwin": osname = "cygwin" rel_re = re.compile (r'[\d.]+') m = rel_re.match(release) if m: release = m.group() elif osname[:6] == "darwin": import _osx_support osname, release, machine = _osx_support.get_platform_osx( get_config_vars(), osname, release, machine) return "%s-%s-%s" % (osname, release, machine)
[ "def", "get_platform", "(", ")", ":", "import", "re", "if", "os", ".", "name", "==", "'nt'", ":", "# sniff sys.version for architecture.", "prefix", "=", "\" bit (\"", "i", "=", "sys", ".", "version", ".", "find", "(", "prefix", ")", "if", "i", "==", "-", "1", ":", "return", "sys", ".", "platform", "j", "=", "sys", ".", "version", ".", "find", "(", "\")\"", ",", "i", ")", "look", "=", "sys", ".", "version", "[", "i", "+", "len", "(", "prefix", ")", ":", "j", "]", ".", "lower", "(", ")", "if", "look", "==", "'amd64'", ":", "return", "'win-amd64'", "if", "look", "==", "'itanium'", ":", "return", "'win-ia64'", "return", "sys", ".", "platform", "# Set for cross builds explicitly", "if", "\"_PYTHON_HOST_PLATFORM\"", "in", "os", ".", "environ", ":", "return", "os", ".", "environ", "[", "\"_PYTHON_HOST_PLATFORM\"", "]", "if", "os", ".", "name", "!=", "\"posix\"", "or", "not", "hasattr", "(", "os", ",", "'uname'", ")", ":", "# XXX what about the architecture? NT is Intel or Alpha,", "# Mac OS is M68k or PPC, etc.", "return", "sys", ".", "platform", "# Try to distinguish various flavours of Unix", "osname", ",", "host", ",", "release", ",", "version", ",", "machine", "=", "os", ".", "uname", "(", ")", "# Convert the OS name to lowercase, remove '/' characters", "# (to accommodate BSD/OS), and translate spaces (for \"Power Macintosh\")", "osname", "=", "osname", ".", "lower", "(", ")", ".", "replace", "(", "'/'", ",", "''", ")", "machine", "=", "machine", ".", "replace", "(", "' '", ",", "'_'", ")", "machine", "=", "machine", ".", "replace", "(", "'/'", ",", "'-'", ")", "if", "osname", "[", ":", "5", "]", "==", "\"linux\"", ":", "# At least on Linux/Intel, 'machine' is the processor --", "# i386, etc.", "# XXX what about Alpha, SPARC, etc?", "return", "\"%s-%s\"", "%", "(", "osname", ",", "machine", ")", "elif", "osname", "[", ":", "5", "]", "==", "\"sunos\"", ":", "if", "release", "[", "0", "]", ">=", "\"5\"", ":", "# SunOS 5 == Solaris 2", "osname", "=", "\"solaris\"", "release", "=", "\"%d.%s\"", "%", "(", "int", "(", "release", "[", "0", "]", ")", "-", "3", ",", "release", "[", "2", ":", "]", ")", "# We can't use \"platform.architecture()[0]\" because a", "# bootstrap problem. We use a dict to get an error", "# if some suspicious happens.", "bitness", "=", "{", "2147483647", ":", "\"32bit\"", ",", "9223372036854775807", ":", "\"64bit\"", "}", "machine", "+=", "\".%s\"", "%", "bitness", "[", "sys", ".", "maxint", "]", "# fall through to standard osname-release-machine representation", "elif", "osname", "[", ":", "4", "]", "==", "\"irix\"", ":", "# could be \"irix64\"!", "return", "\"%s-%s\"", "%", "(", "osname", ",", "release", ")", "elif", "osname", "[", ":", "3", "]", "==", "\"aix\"", ":", "return", "\"%s-%s.%s\"", "%", "(", "osname", ",", "version", ",", "release", ")", "elif", "osname", "[", ":", "6", "]", "==", "\"cygwin\"", ":", "osname", "=", "\"cygwin\"", "rel_re", "=", "re", ".", "compile", "(", "r'[\\d.]+'", ")", "m", "=", "rel_re", ".", "match", "(", "release", ")", "if", "m", ":", "release", "=", "m", ".", "group", "(", ")", "elif", "osname", "[", ":", "6", "]", "==", "\"darwin\"", ":", "import", "_osx_support", "osname", ",", "release", ",", "machine", "=", "_osx_support", ".", "get_platform_osx", "(", "get_config_vars", "(", ")", ",", "osname", ",", "release", ",", "machine", ")", "return", "\"%s-%s-%s\"", "%", "(", "osname", ",", "release", ",", "machine", ")" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/sysconfig.py#L534-L623
gem5/gem5
141cc37c2d4b93959d4c249b8f7e6a8b2ef75338
util/minorview/model.py
python
TwoDColours.elems
(self)
return ret
Get a flat list of all elements
Get a flat list of all elements
[ "Get", "a", "flat", "list", "of", "all", "elements" ]
def elems(self): """Get a flat list of all elements""" ret = [] for blocks in self.blockss: ret += blocks return ret
[ "def", "elems", "(", "self", ")", ":", "ret", "=", "[", "]", "for", "blocks", "in", "self", ".", "blockss", ":", "ret", "+=", "blocks", "return", "ret" ]
https://github.com/gem5/gem5/blob/141cc37c2d4b93959d4c249b8f7e6a8b2ef75338/util/minorview/model.py#L327-L332
apache/incubator-mxnet
f03fb23f1d103fec9541b5ae59ee06b1734a51d9
python/mxnet/onnx/mx2onnx/_op_translations/_op_translations_opset13.py
python
convert_slice_channel
(node, **kwargs)
return nodes
Map MXNet's SliceChannel operator attributes to onnx's Squeeze or Split operator based on squeeze_axis attribute and return the created node.
Map MXNet's SliceChannel operator attributes to onnx's Squeeze or Split operator based on squeeze_axis attribute and return the created node.
[ "Map", "MXNet", "s", "SliceChannel", "operator", "attributes", "to", "onnx", "s", "Squeeze", "or", "Split", "operator", "based", "on", "squeeze_axis", "attribute", "and", "return", "the", "created", "node", "." ]
def convert_slice_channel(node, **kwargs): """Map MXNet's SliceChannel operator attributes to onnx's Squeeze or Split operator based on squeeze_axis attribute and return the created node. """ from onnx.helper import make_node name, input_nodes, attrs = get_inputs(node, kwargs) num_outputs = int(attrs.get('num_outputs')) axis = int(attrs.get('axis', 1)) squeeze_axis = attrs.get('squeeze_axis', 'False') create_tensor([axis], name+'_axis', kwargs['initializer']) nodes = [] if squeeze_axis in ['True', '1']: nodes += [ make_node('Split', [input_nodes[0]], [name+str(i)+'_' for i in range(num_outputs)], axis=axis) ] for i in range(num_outputs): nodes += [ make_node('Squeeze', [name+str(i)+'_', name+'_axis'], [name+str(i)]) ] else: nodes += [ make_node('Split', [input_nodes[0]], [name+str(i) for i in range(num_outputs)], axis=axis) ] return nodes
[ "def", "convert_slice_channel", "(", "node", ",", "*", "*", "kwargs", ")", ":", "from", "onnx", ".", "helper", "import", "make_node", "name", ",", "input_nodes", ",", "attrs", "=", "get_inputs", "(", "node", ",", "kwargs", ")", "num_outputs", "=", "int", "(", "attrs", ".", "get", "(", "'num_outputs'", ")", ")", "axis", "=", "int", "(", "attrs", ".", "get", "(", "'axis'", ",", "1", ")", ")", "squeeze_axis", "=", "attrs", ".", "get", "(", "'squeeze_axis'", ",", "'False'", ")", "create_tensor", "(", "[", "axis", "]", ",", "name", "+", "'_axis'", ",", "kwargs", "[", "'initializer'", "]", ")", "nodes", "=", "[", "]", "if", "squeeze_axis", "in", "[", "'True'", ",", "'1'", "]", ":", "nodes", "+=", "[", "make_node", "(", "'Split'", ",", "[", "input_nodes", "[", "0", "]", "]", ",", "[", "name", "+", "str", "(", "i", ")", "+", "'_'", "for", "i", "in", "range", "(", "num_outputs", ")", "]", ",", "axis", "=", "axis", ")", "]", "for", "i", "in", "range", "(", "num_outputs", ")", ":", "nodes", "+=", "[", "make_node", "(", "'Squeeze'", ",", "[", "name", "+", "str", "(", "i", ")", "+", "'_'", ",", "name", "+", "'_axis'", "]", ",", "[", "name", "+", "str", "(", "i", ")", "]", ")", "]", "else", ":", "nodes", "+=", "[", "make_node", "(", "'Split'", ",", "[", "input_nodes", "[", "0", "]", "]", ",", "[", "name", "+", "str", "(", "i", ")", "for", "i", "in", "range", "(", "num_outputs", ")", "]", ",", "axis", "=", "axis", ")", "]", "return", "nodes" ]
https://github.com/apache/incubator-mxnet/blob/f03fb23f1d103fec9541b5ae59ee06b1734a51d9/python/mxnet/onnx/mx2onnx/_op_translations/_op_translations_opset13.py#L1436-L1466
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/init_ops.py
python
Initializer.get_config
(self)
return {}
Returns the configuration of the initializer as a JSON-serializable dict. Returns: A JSON-serializable Python dict.
Returns the configuration of the initializer as a JSON-serializable dict.
[ "Returns", "the", "configuration", "of", "the", "initializer", "as", "a", "JSON", "-", "serializable", "dict", "." ]
def get_config(self): """Returns the configuration of the initializer as a JSON-serializable dict. Returns: A JSON-serializable Python dict. """ return {}
[ "def", "get_config", "(", "self", ")", ":", "return", "{", "}" ]
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/init_ops.py#L70-L76
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/distutils/ccompiler.py
python
CCompiler.find_library_file
(self, dirs, lib, debug=0)
Search the specified list of directories for a static or shared library file 'lib' and return the full path to that file. If 'debug' true, look for a debugging version (if that makes sense on the current platform). Return None if 'lib' wasn't found in any of the specified directories.
Search the specified list of directories for a static or shared library file 'lib' and return the full path to that file. If 'debug' true, look for a debugging version (if that makes sense on the current platform). Return None if 'lib' wasn't found in any of the specified directories.
[ "Search", "the", "specified", "list", "of", "directories", "for", "a", "static", "or", "shared", "library", "file", "lib", "and", "return", "the", "full", "path", "to", "that", "file", ".", "If", "debug", "true", "look", "for", "a", "debugging", "version", "(", "if", "that", "makes", "sense", "on", "the", "current", "platform", ")", ".", "Return", "None", "if", "lib", "wasn", "t", "found", "in", "any", "of", "the", "specified", "directories", "." ]
def find_library_file (self, dirs, lib, debug=0): """Search the specified list of directories for a static or shared library file 'lib' and return the full path to that file. If 'debug' true, look for a debugging version (if that makes sense on the current platform). Return None if 'lib' wasn't found in any of the specified directories. """ raise NotImplementedError
[ "def", "find_library_file", "(", "self", ",", "dirs", ",", "lib", ",", "debug", "=", "0", ")", ":", "raise", "NotImplementedError" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/distutils/ccompiler.py#L804-L811
kungfu-origin/kungfu
90c84b2b590855654cb9a6395ed050e0f7763512
core/deps/SQLiteCpp-2.3.0/cpplint.py
python
_CppLintState.SetCountingStyle
(self, counting_style)
Sets the module's counting options.
Sets the module's counting options.
[ "Sets", "the", "module", "s", "counting", "options", "." ]
def SetCountingStyle(self, counting_style): """Sets the module's counting options.""" self.counting = counting_style
[ "def", "SetCountingStyle", "(", "self", ",", "counting_style", ")", ":", "self", ".", "counting", "=", "counting_style" ]
https://github.com/kungfu-origin/kungfu/blob/90c84b2b590855654cb9a6395ed050e0f7763512/core/deps/SQLiteCpp-2.3.0/cpplint.py#L701-L703
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/prompt-toolkit/py3/prompt_toolkit/layout/controls.py
python
UIControl.get_key_bindings
(self)
The key bindings that are specific for this user control. Return a :class:`.KeyBindings` object if some key bindings are specified, or `None` otherwise.
The key bindings that are specific for this user control.
[ "The", "key", "bindings", "that", "are", "specific", "for", "this", "user", "control", "." ]
def get_key_bindings(self) -> Optional["KeyBindingsBase"]: """ The key bindings that are specific for this user control. Return a :class:`.KeyBindings` object if some key bindings are specified, or `None` otherwise. """
[ "def", "get_key_bindings", "(", "self", ")", "->", "Optional", "[", "\"KeyBindingsBase\"", "]", ":" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/prompt-toolkit/py3/prompt_toolkit/layout/controls.py#L129-L135
klzgrad/naiveproxy
ed2c513637c77b18721fe428d7ed395b4d284c83
src/build/android/gyp/util/diff_utils.py
python
_GenerateDiffWithOnlyAdditons
(expected_path, actual_data)
return ''.join(filtered_diff)
Generate a diff that only contains additions
Generate a diff that only contains additions
[ "Generate", "a", "diff", "that", "only", "contains", "additions" ]
def _GenerateDiffWithOnlyAdditons(expected_path, actual_data): """Generate a diff that only contains additions""" # Ignore blank lines when creating the diff to cut down on whitespace-only # lines in the diff. Also remove trailing whitespaces and add the new lines # manually (ndiff expects new lines but we don't care about trailing # whitespace). with open(expected_path) as expected: expected_lines = [l for l in expected.readlines() if l.strip()] actual_lines = [ '{}\n'.format(l.rstrip()) for l in actual_data.splitlines() if l.strip() ] diff = difflib.ndiff(expected_lines, actual_lines) filtered_diff = (l for l in diff if l.startswith('+')) return ''.join(filtered_diff)
[ "def", "_GenerateDiffWithOnlyAdditons", "(", "expected_path", ",", "actual_data", ")", ":", "# Ignore blank lines when creating the diff to cut down on whitespace-only", "# lines in the diff. Also remove trailing whitespaces and add the new lines", "# manually (ndiff expects new lines but we don't care about trailing", "# whitespace).", "with", "open", "(", "expected_path", ")", "as", "expected", ":", "expected_lines", "=", "[", "l", "for", "l", "in", "expected", ".", "readlines", "(", ")", "if", "l", ".", "strip", "(", ")", "]", "actual_lines", "=", "[", "'{}\\n'", ".", "format", "(", "l", ".", "rstrip", "(", ")", ")", "for", "l", "in", "actual_data", ".", "splitlines", "(", ")", "if", "l", ".", "strip", "(", ")", "]", "diff", "=", "difflib", ".", "ndiff", "(", "expected_lines", ",", "actual_lines", ")", "filtered_diff", "=", "(", "l", "for", "l", "in", "diff", "if", "l", ".", "startswith", "(", "'+'", ")", ")", "return", "''", ".", "join", "(", "filtered_diff", ")" ]
https://github.com/klzgrad/naiveproxy/blob/ed2c513637c77b18721fe428d7ed395b4d284c83/src/build/android/gyp/util/diff_utils.py#L25-L39
natanielruiz/android-yolo
1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f
jni-build/jni/include/tensorflow/python/training/supervisor.py
python
Supervisor._init_summary_op
(self, summary_op=USE_DEFAULT)
Initilizes summary_op. Args: summary_op: An Operation that returns a Summary for the event logs. If set to USE_DEFAULT, create an op that merges all the summaries.
Initilizes summary_op.
[ "Initilizes", "summary_op", "." ]
def _init_summary_op(self, summary_op=USE_DEFAULT): """Initilizes summary_op. Args: summary_op: An Operation that returns a Summary for the event logs. If set to USE_DEFAULT, create an op that merges all the summaries. """ if summary_op is Supervisor.USE_DEFAULT: summary_op = self._get_first_op_from_collection(ops.GraphKeys.SUMMARY_OP) if summary_op is None: summary_op = logging_ops.merge_all_summaries() if summary_op is not None: ops.add_to_collection(ops.GraphKeys.SUMMARY_OP, summary_op) self._summary_op = summary_op
[ "def", "_init_summary_op", "(", "self", ",", "summary_op", "=", "USE_DEFAULT", ")", ":", "if", "summary_op", "is", "Supervisor", ".", "USE_DEFAULT", ":", "summary_op", "=", "self", ".", "_get_first_op_from_collection", "(", "ops", ".", "GraphKeys", ".", "SUMMARY_OP", ")", "if", "summary_op", "is", "None", ":", "summary_op", "=", "logging_ops", ".", "merge_all_summaries", "(", ")", "if", "summary_op", "is", "not", "None", ":", "ops", ".", "add_to_collection", "(", "ops", ".", "GraphKeys", ".", "SUMMARY_OP", ",", "summary_op", ")", "self", ".", "_summary_op", "=", "summary_op" ]
https://github.com/natanielruiz/android-yolo/blob/1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f/jni-build/jni/include/tensorflow/python/training/supervisor.py#L426-L439
trailofbits/llvm-sanitizer-tutorial
d29dfeec7f51fbf234fd0080f28f2b30cd0b6e99
llvm/projects/compiler-rt/lib/sanitizer_common/scripts/cpplint.py
python
Match
(pattern, s)
return _regexp_compile_cache[pattern].match(s)
Matches the string with the pattern, caching the compiled regexp.
Matches the string with the pattern, caching the compiled regexp.
[ "Matches", "the", "string", "with", "the", "pattern", "caching", "the", "compiled", "regexp", "." ]
def Match(pattern, s): """Matches the string with the pattern, caching the compiled regexp.""" # The regexp compilation caching is inlined in both Match and Search for # performance reasons; factoring it out into a separate function turns out # to be noticeably expensive. if not pattern in _regexp_compile_cache: _regexp_compile_cache[pattern] = sre_compile.compile(pattern) return _regexp_compile_cache[pattern].match(s)
[ "def", "Match", "(", "pattern", ",", "s", ")", ":", "# The regexp compilation caching is inlined in both Match and Search for", "# performance reasons; factoring it out into a separate function turns out", "# to be noticeably expensive.", "if", "not", "pattern", "in", "_regexp_compile_cache", ":", "_regexp_compile_cache", "[", "pattern", "]", "=", "sre_compile", ".", "compile", "(", "pattern", ")", "return", "_regexp_compile_cache", "[", "pattern", "]", ".", "match", "(", "s", ")" ]
https://github.com/trailofbits/llvm-sanitizer-tutorial/blob/d29dfeec7f51fbf234fd0080f28f2b30cd0b6e99/llvm/projects/compiler-rt/lib/sanitizer_common/scripts/cpplint.py#L409-L416
tensorflow/tensorflow
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
tensorflow/lite/python/util.py
python
_convert_tflite_enum_type_to_tf_type
(tflite_enum_type)
return tf_type
Converts tflite enum type (eg: 0) to tf type (eg: tf.float32). Args: tflite_enum_type: tflite enum type (eg: 0, that corresponds to float32) Raises: ValueError: If an invalid tflite enum type is provided. Returns: tf type (eg: tf.float32)
Converts tflite enum type (eg: 0) to tf type (eg: tf.float32).
[ "Converts", "tflite", "enum", "type", "(", "eg", ":", "0", ")", "to", "tf", "type", "(", "eg", ":", "tf", ".", "float32", ")", "." ]
def _convert_tflite_enum_type_to_tf_type(tflite_enum_type): """Converts tflite enum type (eg: 0) to tf type (eg: tf.float32). Args: tflite_enum_type: tflite enum type (eg: 0, that corresponds to float32) Raises: ValueError: If an invalid tflite enum type is provided. Returns: tf type (eg: tf.float32) """ tf_type = _MAP_TFLITE_ENUM_TO_TF_TYPES.get(tflite_enum_type) if tf_type is None: raise ValueError( "Unsupported enum {}. The valid map of enum to tf types is : {}" .format(tflite_enum_type, _MAP_TFLITE_ENUM_TO_TF_TYPES)) return tf_type
[ "def", "_convert_tflite_enum_type_to_tf_type", "(", "tflite_enum_type", ")", ":", "tf_type", "=", "_MAP_TFLITE_ENUM_TO_TF_TYPES", ".", "get", "(", "tflite_enum_type", ")", "if", "tf_type", "is", "None", ":", "raise", "ValueError", "(", "\"Unsupported enum {}. The valid map of enum to tf types is : {}\"", ".", "format", "(", "tflite_enum_type", ",", "_MAP_TFLITE_ENUM_TO_TF_TYPES", ")", ")", "return", "tf_type" ]
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/lite/python/util.py#L86-L103
miyosuda/TensorFlowAndroidMNIST
7b5a4603d2780a8a2834575706e9001977524007
jni-build/jni/include/tensorflow/python/ops/variable_scope.py
python
VariableScope.set_regularizer
(self, regularizer)
Set regularizer for this scope.
Set regularizer for this scope.
[ "Set", "regularizer", "for", "this", "scope", "." ]
def set_regularizer(self, regularizer): """Set regularizer for this scope.""" self._regularizer = regularizer
[ "def", "set_regularizer", "(", "self", ",", "regularizer", ")", ":", "self", ".", "_regularizer", "=", "regularizer" ]
https://github.com/miyosuda/TensorFlowAndroidMNIST/blob/7b5a4603d2780a8a2834575706e9001977524007/jni-build/jni/include/tensorflow/python/ops/variable_scope.py#L648-L650
PaddlePaddle/Paddle
1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c
python/paddle/tensor/math.py
python
clip_
(x, min=None, max=None, name=None)
return _C_ops.clip_(x, "min", min, "max", max)
Inplace version of ``clip`` API, the output Tensor will be inplaced with input ``x``. Please refer to :ref:`api_tensor_clip`.
Inplace version of ``clip`` API, the output Tensor will be inplaced with input ``x``. Please refer to :ref:`api_tensor_clip`.
[ "Inplace", "version", "of", "clip", "API", "the", "output", "Tensor", "will", "be", "inplaced", "with", "input", "x", ".", "Please", "refer", "to", ":", "ref", ":", "api_tensor_clip", "." ]
def clip_(x, min=None, max=None, name=None): """ Inplace version of ``clip`` API, the output Tensor will be inplaced with input ``x``. Please refer to :ref:`api_tensor_clip`. """ fmin = float(np.finfo(np.float32).min) fmax = float(np.finfo(np.float32).max) if isinstance(min, Variable): min = min.numpy().item(0) if isinstance(max, Variable): max = max.numpy().item(0) min = fmin if min is None else min max = fmax if max is None else max return _C_ops.clip_(x, "min", min, "max", max)
[ "def", "clip_", "(", "x", ",", "min", "=", "None", ",", "max", "=", "None", ",", "name", "=", "None", ")", ":", "fmin", "=", "float", "(", "np", ".", "finfo", "(", "np", ".", "float32", ")", ".", "min", ")", "fmax", "=", "float", "(", "np", ".", "finfo", "(", "np", ".", "float32", ")", ".", "max", ")", "if", "isinstance", "(", "min", ",", "Variable", ")", ":", "min", "=", "min", ".", "numpy", "(", ")", ".", "item", "(", "0", ")", "if", "isinstance", "(", "max", ",", "Variable", ")", ":", "max", "=", "max", ".", "numpy", "(", ")", ".", "item", "(", "0", ")", "min", "=", "fmin", "if", "min", "is", "None", "else", "min", "max", "=", "fmax", "if", "max", "is", "None", "else", "max", "return", "_C_ops", ".", "clip_", "(", "x", ",", "\"min\"", ",", "min", ",", "\"max\"", ",", "max", ")" ]
https://github.com/PaddlePaddle/Paddle/blob/1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c/python/paddle/tensor/math.py#L2256-L2269
trilinos/Trilinos
6168be6dd51e35e1cd681e9c4b24433e709df140
packages/seacas/libraries/ioss/src/visualization/catalyst/phactori/phactori.py
python
GetXyzForNodeOrElementParallel
(inParaViewSource, inIdIsNode, inGlobalId, outXyz, inLocalProcessCouldDetect = True)
given a node or element id, get item xyz location in parallel Recurses through all structures on all processes to find a node or element, then does allreduce to spread that information to all processes (for use in pointing cameras at a node or element with a given id; if this process has the element with the id inGlobalId, it will set outXyz and send the info around, if this process does not have inGlobalId, it will expect to receive the proper outXyz from the node that does.
given a node or element id, get item xyz location in parallel
[ "given", "a", "node", "or", "element", "id", "get", "item", "xyz", "location", "in", "parallel" ]
def GetXyzForNodeOrElementParallel(inParaViewSource, inIdIsNode, inGlobalId, outXyz, inLocalProcessCouldDetect = True): """given a node or element id, get item xyz location in parallel Recurses through all structures on all processes to find a node or element, then does allreduce to spread that information to all processes (for use in pointing cameras at a node or element with a given id; if this process has the element with the id inGlobalId, it will set outXyz and send the info around, if this process does not have inGlobalId, it will expect to receive the proper outXyz from the node that does. """ if PhactoriDbg(100): myDebugPrint3("GetXyzForNodeOrElementParallel entered, IdIsNode: " + str(inIdIsNode) + " id: " + str(inGlobalId) + "\n", 100) #theSource = GetCurrentSource() #theSource = GetActiveSource() if inLocalProcessCouldDetect: csData = inParaViewSource.GetClientSideObject().GetOutputDataObject(0) found = GetXyzForNodeOrElementParallelRecurse1(csData, inIdIsNode, inGlobalId, outXyz) else: found = False if found: if PhactoriDbg(): myDebugPrint3(" this process has GlobalId " + str(inGlobalId) + ", doing broadcast of info\n") UseReduceToSpreadValues(outXyz) #GetXyzForNodeParallelBroadcast(thePointArrays, outXyz) else: if PhactoriDbg(): myDebugPrint3(" this process does not have GlobalId " + str(inGlobalId) + ", doing receive of info\n") UseReduceToSpreadValues(outXyz) #GetXyzForNodeParallelReceive(outXyz) if PhactoriDbg(100): myDebugPrint3("GetXyzForNodeOrElementParallel returning\n", 100)
[ "def", "GetXyzForNodeOrElementParallel", "(", "inParaViewSource", ",", "inIdIsNode", ",", "inGlobalId", ",", "outXyz", ",", "inLocalProcessCouldDetect", "=", "True", ")", ":", "if", "PhactoriDbg", "(", "100", ")", ":", "myDebugPrint3", "(", "\"GetXyzForNodeOrElementParallel entered, IdIsNode: \"", "+", "str", "(", "inIdIsNode", ")", "+", "\" id: \"", "+", "str", "(", "inGlobalId", ")", "+", "\"\\n\"", ",", "100", ")", "#theSource = GetCurrentSource()", "#theSource = GetActiveSource()", "if", "inLocalProcessCouldDetect", ":", "csData", "=", "inParaViewSource", ".", "GetClientSideObject", "(", ")", ".", "GetOutputDataObject", "(", "0", ")", "found", "=", "GetXyzForNodeOrElementParallelRecurse1", "(", "csData", ",", "inIdIsNode", ",", "inGlobalId", ",", "outXyz", ")", "else", ":", "found", "=", "False", "if", "found", ":", "if", "PhactoriDbg", "(", ")", ":", "myDebugPrint3", "(", "\" this process has GlobalId \"", "+", "str", "(", "inGlobalId", ")", "+", "\", doing broadcast of info\\n\"", ")", "UseReduceToSpreadValues", "(", "outXyz", ")", "#GetXyzForNodeParallelBroadcast(thePointArrays, outXyz)", "else", ":", "if", "PhactoriDbg", "(", ")", ":", "myDebugPrint3", "(", "\" this process does not have GlobalId \"", "+", "str", "(", "inGlobalId", ")", "+", "\", doing receive of info\\n\"", ")", "UseReduceToSpreadValues", "(", "outXyz", ")", "#GetXyzForNodeParallelReceive(outXyz)", "if", "PhactoriDbg", "(", "100", ")", ":", "myDebugPrint3", "(", "\"GetXyzForNodeOrElementParallel returning\\n\"", ",", "100", ")" ]
https://github.com/trilinos/Trilinos/blob/6168be6dd51e35e1cd681e9c4b24433e709df140/packages/seacas/libraries/ioss/src/visualization/catalyst/phactori/phactori.py#L2967-L3006
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/windows/Lib/xmlrpc/server.py
python
SimpleXMLRPCDispatcher.system_methodSignature
(self, method_name)
return 'signatures not supported'
system.methodSignature('add') => [double, int, int] Returns a list describing the signature of the method. In the above example, the add method takes two integers as arguments and returns a double result. This server does NOT support system.methodSignature.
system.methodSignature('add') => [double, int, int]
[ "system", ".", "methodSignature", "(", "add", ")", "=", ">", "[", "double", "int", "int", "]" ]
def system_methodSignature(self, method_name): """system.methodSignature('add') => [double, int, int] Returns a list describing the signature of the method. In the above example, the add method takes two integers as arguments and returns a double result. This server does NOT support system.methodSignature.""" # See http://xmlrpc.usefulinc.com/doc/sysmethodsig.html return 'signatures not supported'
[ "def", "system_methodSignature", "(", "self", ",", "method_name", ")", ":", "# See http://xmlrpc.usefulinc.com/doc/sysmethodsig.html", "return", "'signatures not supported'" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/xmlrpc/server.py#L303-L314
natanielruiz/android-yolo
1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f
jni-build/jni/include/tensorflow/python/ops/gradients.py
python
gradients
(ys, xs, grad_ys=None, name="gradients", colocate_gradients_with_ops=False, gate_gradients=False, aggregation_method=None)
return [_GetGrad(grads, x) for x in xs]
Constructs symbolic partial derivatives of sum of `ys` w.r.t. x in `xs`. `ys` and `xs` are each a `Tensor` or a list of tensors. `grad_ys` is a list of `Tensor`, holding the gradients received by the `ys`. The list must be the same length as `ys`. `gradients()` adds ops to the graph to output the partial derivatives of `ys` with respect to `xs`. It returns a list of `Tensor` of length `len(xs)` where each tensor is the `sum(dy/dx)` for y in `ys`. `grad_ys` is a list of tensors of the same length as `ys` that holds the initial gradients for each y in `ys`. When `grad_ys` is None, we fill in a tensor of '1's of the shape of y for each y in `ys`. A user can provide their own initial `grad_ys` to compute the derivatives using a different initial gradient for each y (e.g., if one wanted to weight the gradient differently for each value in each y). Args: ys: A `Tensor` or list of tensors to be differentiated. xs: A `Tensor` or list of tensors to be used for differentiation. grad_ys: Optional. A `Tensor` or list of tensors the same size as `ys` and holding the gradients computed for each y in `ys`. name: Optional name to use for grouping all the gradient ops together. defaults to 'gradients'. colocate_gradients_with_ops: If True, try colocating gradients with the corresponding op. gate_gradients: If True, add a tuple around the gradients returned for an operations. This avoids some race conditions. aggregation_method: Specifies the method used to combine gradient terms. Accepted values are constants defined in the class `AggregationMethod`. Returns: A list of `sum(dy/dx)` for each x in `xs`. Raises: LookupError: if one of the operations between `x` and `y` does not have a registered gradient function. ValueError: if the arguments are invalid.
Constructs symbolic partial derivatives of sum of `ys` w.r.t. x in `xs`.
[ "Constructs", "symbolic", "partial", "derivatives", "of", "sum", "of", "ys", "w", ".", "r", ".", "t", ".", "x", "in", "xs", "." ]
def gradients(ys, xs, grad_ys=None, name="gradients", colocate_gradients_with_ops=False, gate_gradients=False, aggregation_method=None): """Constructs symbolic partial derivatives of sum of `ys` w.r.t. x in `xs`. `ys` and `xs` are each a `Tensor` or a list of tensors. `grad_ys` is a list of `Tensor`, holding the gradients received by the `ys`. The list must be the same length as `ys`. `gradients()` adds ops to the graph to output the partial derivatives of `ys` with respect to `xs`. It returns a list of `Tensor` of length `len(xs)` where each tensor is the `sum(dy/dx)` for y in `ys`. `grad_ys` is a list of tensors of the same length as `ys` that holds the initial gradients for each y in `ys`. When `grad_ys` is None, we fill in a tensor of '1's of the shape of y for each y in `ys`. A user can provide their own initial `grad_ys` to compute the derivatives using a different initial gradient for each y (e.g., if one wanted to weight the gradient differently for each value in each y). Args: ys: A `Tensor` or list of tensors to be differentiated. xs: A `Tensor` or list of tensors to be used for differentiation. grad_ys: Optional. A `Tensor` or list of tensors the same size as `ys` and holding the gradients computed for each y in `ys`. name: Optional name to use for grouping all the gradient ops together. defaults to 'gradients'. colocate_gradients_with_ops: If True, try colocating gradients with the corresponding op. gate_gradients: If True, add a tuple around the gradients returned for an operations. This avoids some race conditions. aggregation_method: Specifies the method used to combine gradient terms. Accepted values are constants defined in the class `AggregationMethod`. Returns: A list of `sum(dy/dx)` for each x in `xs`. Raises: LookupError: if one of the operations between `x` and `y` does not have a registered gradient function. ValueError: if the arguments are invalid. """ ys = _AsList(ys) xs = _AsList(xs) if grad_ys is None: grad_ys = [None] * len(ys) else: grad_ys = _AsList(grad_ys) with ops.op_scope(ys + xs + grad_ys, name, "gradients"): ys = ops.convert_n_to_tensor_or_indexed_slices(ys, name="y") xs = ops.convert_n_to_tensor_or_indexed_slices(xs, name="x") grad_ys = _DefaultGradYs(grad_ys, ys, colocate_gradients_with_ops) # The approach we take here is as follows: Create a list of all ops in the # subgraph between the ys and xs. Visit these ops in reverse order of ids # to ensure that when we visit an op the gradients w.r.t its outputs have # been collected. Then aggregate these gradients if needed, call the op's # gradient function, and add the generated gradients to the gradients for # its input. # Initialize the pending count for ops in the connected subgraph from ys # to the xs. to_ops = [t.op for t in ys] from_ops = [t.op for t in xs] pending_count, loop_state = _PendingCount(ops.get_default_graph(), to_ops, from_ops, colocate_gradients_with_ops) # Iterate over the collected ops. # # grads: op => list of gradients received on each output endpoint of the # op. The gradients for each endpoint are initially collected as a list. # When it is time to call the op's gradient function, for each endpoint we # aggregate the list of received gradients into a Add() Operation if there # is more than one. grads = {} # Add the initial gradients for the ys. for y, grad_y in zip(ys, grad_ys): _SetGrad(grads, y, grad_y) # Initialize queue with to_ops. queue = collections.deque() # Add the ops in 'to_ops' into the queue. to_ops_set = set() for op in to_ops: # 'ready' handles the case where one output gradient relies on # another output's gradient. # pylint: disable=protected-access ready = (pending_count[op._id] == 0) if ready and op._id not in to_ops_set: to_ops_set.add(op._id) queue.append(op) if loop_state: # The "unused" exits of the loops are added to ys. As an example, # people often write: # v1, _ = While(p, b, [x1, x2]) # result = gradients(v1, x1) # The exit node of x2 is not included by the betweenness analysis. # But we need it if x2 is involved in computing v1. So we add it # back in backprop with a zeros_like gradient. loop_exits = loop_state.GetAllLoopExits() for y in loop_exits: if pending_count[y.op._id] == 0 and y.op._id not in to_ops_set: if _IsFloat(y): # Floating-point outputs get a zero gradient. _SetGrad(grads, y, loop_state.ZerosLikeForExit(y)) queue.append(y.op) # The set of 'from_ops'. stop_ops = _StopOps(from_ops, pending_count) while queue: # generate gradient subgraph for op. op = queue.popleft() with _maybe_colocate_with(op, colocate_gradients_with_ops): if loop_state: loop_state.EnterGradWhileContext(op, before=True) out_grads = _AggregatedGrads(grads, op, loop_state, aggregation_method) if loop_state: loop_state.ExitGradWhileContext(op, before=True) grad_fn = None # pylint: disable=protected-access is_func_call = ops.get_default_graph()._is_function(op.type) has_out_grads = any(isinstance(g, ops.Tensor) or g for g in out_grads) if has_out_grads and (op._id not in stop_ops): if is_func_call: grad_fn = ops.get_default_graph()._function_python_gradient.get( op.type, None) # pylint: enable=protected-access else: # A grad_fn must be defined, either as a function or as None # for ops that do not have gradients. try: grad_fn = ops.get_gradient_function(op) except LookupError: raise LookupError( "No gradient defined for operation '%s' (op type: %s)" % (op.name, op.type)) if loop_state: loop_state.EnterGradWhileContext(op, before=False) if (grad_fn or is_func_call) and has_out_grads: # NOTE: If _AggregatedGrads didn't compute a value for the i'th # output, it means that the cost does not depend on output[i], # therefore dC/doutput[i] is 0. for i, out_grad in enumerate(out_grads): if (not isinstance(out_grad, ops.Tensor) and not out_grad) and _IsFloat(op.outputs[i]): # Only floating-point outputs get a zero gradient. Gradient # functions should ignore the gradient for other outputs. if loop_state: out_grads[i] = loop_state.ZerosLike(op, i) else: out_grads[i] = control_flow_ops.ZerosLikeOutsideLoop(op, i) with ops.name_scope(op.name + "_grad"): # pylint: disable=protected-access with ops.get_default_graph()._original_op(op): # pylint: enable=protected-access if grad_fn: # If grad_fn was found, do not use SymbolicGradient even for # functions. in_grads = _AsList(grad_fn(op, *out_grads)) else: # For function call ops, we add a 'SymbolicGradient' # node to the graph to compute gradients. f_in = [x for x in op.inputs] + out_grads f_types = [x.dtype for x in op.inputs] # pylint: disable=protected-access in_grads = _AsList(functional_ops._symbolic_gradient( f_in, f_types, op.type)) # pylint: enable=protected-access _VerifyGeneratedGradients(in_grads, op) if gate_gradients and len( [x for x in in_grads if x is not None]) > 1: in_grads = control_flow_ops.tuple(in_grads) _LogOpGradients(op, out_grads, in_grads) else: # If no grad_fn is defined or none of out_grads is available, # just propagates a list of None backwards. in_grads = [None] * len(op.inputs) for t_in, in_grad in zip(op.inputs, in_grads): if in_grad is not None: if isinstance(in_grad, ops.Tensor): in_grad.set_shape(t_in.get_shape()) _SetGrad(grads, t_in, in_grad) if loop_state: loop_state.ExitGradWhileContext(op, before=False) # update pending count for the inputs of op and enqueue ready ops. # pylint: disable=protected-access for x in op.inputs: pending_count[x.op._id] -= 1 ready = (pending_count[x.op._id] == 0) if loop_state and not ready: ready = (pending_count[x.op._id] > 0 and control_flow_ops.IsLoopSwitch(x.op)) if ready: queue.append(x.op) # pylint: enable=protected-access if loop_state: loop_state.PostProcessing() return [_GetGrad(grads, x) for x in xs]
[ "def", "gradients", "(", "ys", ",", "xs", ",", "grad_ys", "=", "None", ",", "name", "=", "\"gradients\"", ",", "colocate_gradients_with_ops", "=", "False", ",", "gate_gradients", "=", "False", ",", "aggregation_method", "=", "None", ")", ":", "ys", "=", "_AsList", "(", "ys", ")", "xs", "=", "_AsList", "(", "xs", ")", "if", "grad_ys", "is", "None", ":", "grad_ys", "=", "[", "None", "]", "*", "len", "(", "ys", ")", "else", ":", "grad_ys", "=", "_AsList", "(", "grad_ys", ")", "with", "ops", ".", "op_scope", "(", "ys", "+", "xs", "+", "grad_ys", ",", "name", ",", "\"gradients\"", ")", ":", "ys", "=", "ops", ".", "convert_n_to_tensor_or_indexed_slices", "(", "ys", ",", "name", "=", "\"y\"", ")", "xs", "=", "ops", ".", "convert_n_to_tensor_or_indexed_slices", "(", "xs", ",", "name", "=", "\"x\"", ")", "grad_ys", "=", "_DefaultGradYs", "(", "grad_ys", ",", "ys", ",", "colocate_gradients_with_ops", ")", "# The approach we take here is as follows: Create a list of all ops in the", "# subgraph between the ys and xs. Visit these ops in reverse order of ids", "# to ensure that when we visit an op the gradients w.r.t its outputs have", "# been collected. Then aggregate these gradients if needed, call the op's", "# gradient function, and add the generated gradients to the gradients for", "# its input.", "# Initialize the pending count for ops in the connected subgraph from ys", "# to the xs.", "to_ops", "=", "[", "t", ".", "op", "for", "t", "in", "ys", "]", "from_ops", "=", "[", "t", ".", "op", "for", "t", "in", "xs", "]", "pending_count", ",", "loop_state", "=", "_PendingCount", "(", "ops", ".", "get_default_graph", "(", ")", ",", "to_ops", ",", "from_ops", ",", "colocate_gradients_with_ops", ")", "# Iterate over the collected ops.", "#", "# grads: op => list of gradients received on each output endpoint of the", "# op. The gradients for each endpoint are initially collected as a list.", "# When it is time to call the op's gradient function, for each endpoint we", "# aggregate the list of received gradients into a Add() Operation if there", "# is more than one.", "grads", "=", "{", "}", "# Add the initial gradients for the ys.", "for", "y", ",", "grad_y", "in", "zip", "(", "ys", ",", "grad_ys", ")", ":", "_SetGrad", "(", "grads", ",", "y", ",", "grad_y", ")", "# Initialize queue with to_ops.", "queue", "=", "collections", ".", "deque", "(", ")", "# Add the ops in 'to_ops' into the queue.", "to_ops_set", "=", "set", "(", ")", "for", "op", "in", "to_ops", ":", "# 'ready' handles the case where one output gradient relies on", "# another output's gradient.", "# pylint: disable=protected-access", "ready", "=", "(", "pending_count", "[", "op", ".", "_id", "]", "==", "0", ")", "if", "ready", "and", "op", ".", "_id", "not", "in", "to_ops_set", ":", "to_ops_set", ".", "add", "(", "op", ".", "_id", ")", "queue", ".", "append", "(", "op", ")", "if", "loop_state", ":", "# The \"unused\" exits of the loops are added to ys. As an example,", "# people often write:", "# v1, _ = While(p, b, [x1, x2])", "# result = gradients(v1, x1)", "# The exit node of x2 is not included by the betweenness analysis.", "# But we need it if x2 is involved in computing v1. So we add it", "# back in backprop with a zeros_like gradient.", "loop_exits", "=", "loop_state", ".", "GetAllLoopExits", "(", ")", "for", "y", "in", "loop_exits", ":", "if", "pending_count", "[", "y", ".", "op", ".", "_id", "]", "==", "0", "and", "y", ".", "op", ".", "_id", "not", "in", "to_ops_set", ":", "if", "_IsFloat", "(", "y", ")", ":", "# Floating-point outputs get a zero gradient.", "_SetGrad", "(", "grads", ",", "y", ",", "loop_state", ".", "ZerosLikeForExit", "(", "y", ")", ")", "queue", ".", "append", "(", "y", ".", "op", ")", "# The set of 'from_ops'.", "stop_ops", "=", "_StopOps", "(", "from_ops", ",", "pending_count", ")", "while", "queue", ":", "# generate gradient subgraph for op.", "op", "=", "queue", ".", "popleft", "(", ")", "with", "_maybe_colocate_with", "(", "op", ",", "colocate_gradients_with_ops", ")", ":", "if", "loop_state", ":", "loop_state", ".", "EnterGradWhileContext", "(", "op", ",", "before", "=", "True", ")", "out_grads", "=", "_AggregatedGrads", "(", "grads", ",", "op", ",", "loop_state", ",", "aggregation_method", ")", "if", "loop_state", ":", "loop_state", ".", "ExitGradWhileContext", "(", "op", ",", "before", "=", "True", ")", "grad_fn", "=", "None", "# pylint: disable=protected-access", "is_func_call", "=", "ops", ".", "get_default_graph", "(", ")", ".", "_is_function", "(", "op", ".", "type", ")", "has_out_grads", "=", "any", "(", "isinstance", "(", "g", ",", "ops", ".", "Tensor", ")", "or", "g", "for", "g", "in", "out_grads", ")", "if", "has_out_grads", "and", "(", "op", ".", "_id", "not", "in", "stop_ops", ")", ":", "if", "is_func_call", ":", "grad_fn", "=", "ops", ".", "get_default_graph", "(", ")", ".", "_function_python_gradient", ".", "get", "(", "op", ".", "type", ",", "None", ")", "# pylint: enable=protected-access", "else", ":", "# A grad_fn must be defined, either as a function or as None", "# for ops that do not have gradients.", "try", ":", "grad_fn", "=", "ops", ".", "get_gradient_function", "(", "op", ")", "except", "LookupError", ":", "raise", "LookupError", "(", "\"No gradient defined for operation '%s' (op type: %s)\"", "%", "(", "op", ".", "name", ",", "op", ".", "type", ")", ")", "if", "loop_state", ":", "loop_state", ".", "EnterGradWhileContext", "(", "op", ",", "before", "=", "False", ")", "if", "(", "grad_fn", "or", "is_func_call", ")", "and", "has_out_grads", ":", "# NOTE: If _AggregatedGrads didn't compute a value for the i'th", "# output, it means that the cost does not depend on output[i],", "# therefore dC/doutput[i] is 0.", "for", "i", ",", "out_grad", "in", "enumerate", "(", "out_grads", ")", ":", "if", "(", "not", "isinstance", "(", "out_grad", ",", "ops", ".", "Tensor", ")", "and", "not", "out_grad", ")", "and", "_IsFloat", "(", "op", ".", "outputs", "[", "i", "]", ")", ":", "# Only floating-point outputs get a zero gradient. Gradient", "# functions should ignore the gradient for other outputs.", "if", "loop_state", ":", "out_grads", "[", "i", "]", "=", "loop_state", ".", "ZerosLike", "(", "op", ",", "i", ")", "else", ":", "out_grads", "[", "i", "]", "=", "control_flow_ops", ".", "ZerosLikeOutsideLoop", "(", "op", ",", "i", ")", "with", "ops", ".", "name_scope", "(", "op", ".", "name", "+", "\"_grad\"", ")", ":", "# pylint: disable=protected-access", "with", "ops", ".", "get_default_graph", "(", ")", ".", "_original_op", "(", "op", ")", ":", "# pylint: enable=protected-access", "if", "grad_fn", ":", "# If grad_fn was found, do not use SymbolicGradient even for", "# functions.", "in_grads", "=", "_AsList", "(", "grad_fn", "(", "op", ",", "*", "out_grads", ")", ")", "else", ":", "# For function call ops, we add a 'SymbolicGradient'", "# node to the graph to compute gradients.", "f_in", "=", "[", "x", "for", "x", "in", "op", ".", "inputs", "]", "+", "out_grads", "f_types", "=", "[", "x", ".", "dtype", "for", "x", "in", "op", ".", "inputs", "]", "# pylint: disable=protected-access", "in_grads", "=", "_AsList", "(", "functional_ops", ".", "_symbolic_gradient", "(", "f_in", ",", "f_types", ",", "op", ".", "type", ")", ")", "# pylint: enable=protected-access", "_VerifyGeneratedGradients", "(", "in_grads", ",", "op", ")", "if", "gate_gradients", "and", "len", "(", "[", "x", "for", "x", "in", "in_grads", "if", "x", "is", "not", "None", "]", ")", ">", "1", ":", "in_grads", "=", "control_flow_ops", ".", "tuple", "(", "in_grads", ")", "_LogOpGradients", "(", "op", ",", "out_grads", ",", "in_grads", ")", "else", ":", "# If no grad_fn is defined or none of out_grads is available,", "# just propagates a list of None backwards.", "in_grads", "=", "[", "None", "]", "*", "len", "(", "op", ".", "inputs", ")", "for", "t_in", ",", "in_grad", "in", "zip", "(", "op", ".", "inputs", ",", "in_grads", ")", ":", "if", "in_grad", "is", "not", "None", ":", "if", "isinstance", "(", "in_grad", ",", "ops", ".", "Tensor", ")", ":", "in_grad", ".", "set_shape", "(", "t_in", ".", "get_shape", "(", ")", ")", "_SetGrad", "(", "grads", ",", "t_in", ",", "in_grad", ")", "if", "loop_state", ":", "loop_state", ".", "ExitGradWhileContext", "(", "op", ",", "before", "=", "False", ")", "# update pending count for the inputs of op and enqueue ready ops.", "# pylint: disable=protected-access", "for", "x", "in", "op", ".", "inputs", ":", "pending_count", "[", "x", ".", "op", ".", "_id", "]", "-=", "1", "ready", "=", "(", "pending_count", "[", "x", ".", "op", ".", "_id", "]", "==", "0", ")", "if", "loop_state", "and", "not", "ready", ":", "ready", "=", "(", "pending_count", "[", "x", ".", "op", ".", "_id", "]", ">", "0", "and", "control_flow_ops", ".", "IsLoopSwitch", "(", "x", ".", "op", ")", ")", "if", "ready", ":", "queue", ".", "append", "(", "x", ".", "op", ")", "# pylint: enable=protected-access", "if", "loop_state", ":", "loop_state", ".", "PostProcessing", "(", ")", "return", "[", "_GetGrad", "(", "grads", ",", "x", ")", "for", "x", "in", "xs", "]" ]
https://github.com/natanielruiz/android-yolo/blob/1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f/jni-build/jni/include/tensorflow/python/ops/gradients.py#L306-L517
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/stc.py
python
StyledTextCtrl.ReplaceSelection
(*args, **kwargs)
return _stc.StyledTextCtrl_ReplaceSelection(*args, **kwargs)
ReplaceSelection(self, String text) Replace the selected text with the argument text.
ReplaceSelection(self, String text)
[ "ReplaceSelection", "(", "self", "String", "text", ")" ]
def ReplaceSelection(*args, **kwargs): """ ReplaceSelection(self, String text) Replace the selected text with the argument text. """ return _stc.StyledTextCtrl_ReplaceSelection(*args, **kwargs)
[ "def", "ReplaceSelection", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_stc", ".", "StyledTextCtrl_ReplaceSelection", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/stc.py#L3633-L3639
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/_core.py
python
PyApp_SetMacExitMenuItemId
(*args, **kwargs)
return _core_.PyApp_SetMacExitMenuItemId(*args, **kwargs)
PyApp_SetMacExitMenuItemId(long val)
PyApp_SetMacExitMenuItemId(long val)
[ "PyApp_SetMacExitMenuItemId", "(", "long", "val", ")" ]
def PyApp_SetMacExitMenuItemId(*args, **kwargs): """PyApp_SetMacExitMenuItemId(long val)""" return _core_.PyApp_SetMacExitMenuItemId(*args, **kwargs)
[ "def", "PyApp_SetMacExitMenuItemId", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_core_", ".", "PyApp_SetMacExitMenuItemId", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_core.py#L8306-L8308
deepdrive/deepdrive-sim
5c260ee7948f38f3ac50be796d2368bfdbf167be
Packaging/old/package.py
python
package_sim
()
Package sim in Development mode to get yummy command line tools but with Shipping performance
Package sim in Development mode to get yummy command line tools but with Shipping performance
[ "Package", "sim", "in", "Development", "mode", "to", "get", "yummy", "command", "line", "tools", "but", "with", "Shipping", "performance" ]
def package_sim(): """ Package sim in Development mode to get yummy command line tools but with Shipping performance """ manager = UnrealManagerFactory.create() # Monkey patch build orig_build = manager.buildProject manager.buildProject = functools.partial(orig_build, dir=SIM_DIR) manager.packageProject(configuration='Development', # TODO: Determine effect of these removed args and the added -allmaps arg # extraArgs=['-nocompileeditor', # '-clean'] ) # Restore original build manager.buildProject = orig_build
[ "def", "package_sim", "(", ")", ":", "manager", "=", "UnrealManagerFactory", ".", "create", "(", ")", "# Monkey patch build", "orig_build", "=", "manager", ".", "buildProject", "manager", ".", "buildProject", "=", "functools", ".", "partial", "(", "orig_build", ",", "dir", "=", "SIM_DIR", ")", "manager", ".", "packageProject", "(", "configuration", "=", "'Development'", ",", "# TODO: Determine effect of these removed args and the added -allmaps arg", "# extraArgs=['-nocompileeditor',", "# '-clean']", ")", "# Restore original build", "manager", ".", "buildProject", "=", "orig_build" ]
https://github.com/deepdrive/deepdrive-sim/blob/5c260ee7948f38f3ac50be796d2368bfdbf167be/Packaging/old/package.py#L203-L220
baidu-research/tensorflow-allreduce
66d5b855e90b0949e9fa5cca5599fd729a70e874
tensorflow/python/training/saver.py
python
Saver._MetaGraphFilename
(self, checkpoint_filename, meta_graph_suffix="meta")
return meta_graph_filename
Returns the meta graph filename. Args: checkpoint_filename: Name of the checkpoint file. meta_graph_suffix: Suffix for `MetaGraphDef` file. Defaults to 'meta'. Returns: MetaGraph file name.
Returns the meta graph filename.
[ "Returns", "the", "meta", "graph", "filename", "." ]
def _MetaGraphFilename(self, checkpoint_filename, meta_graph_suffix="meta"): """Returns the meta graph filename. Args: checkpoint_filename: Name of the checkpoint file. meta_graph_suffix: Suffix for `MetaGraphDef` file. Defaults to 'meta'. Returns: MetaGraph file name. """ # If the checkpoint_filename is sharded, the checkpoint_filename could # be of format model.ckpt-step#-?????-of-shard#. For example, # model.ckpt-123456-?????-of-00005, or model.ckpt-123456-00001-of-00002. basename = re.sub(r"-[\d\?]+-of-\d+$", "", checkpoint_filename) meta_graph_filename = ".".join([basename, meta_graph_suffix]) return meta_graph_filename
[ "def", "_MetaGraphFilename", "(", "self", ",", "checkpoint_filename", ",", "meta_graph_suffix", "=", "\"meta\"", ")", ":", "# If the checkpoint_filename is sharded, the checkpoint_filename could", "# be of format model.ckpt-step#-?????-of-shard#. For example,", "# model.ckpt-123456-?????-of-00005, or model.ckpt-123456-00001-of-00002.", "basename", "=", "re", ".", "sub", "(", "r\"-[\\d\\?]+-of-\\d+$\"", ",", "\"\"", ",", "checkpoint_filename", ")", "meta_graph_filename", "=", "\".\"", ".", "join", "(", "[", "basename", ",", "meta_graph_suffix", "]", ")", "return", "meta_graph_filename" ]
https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/python/training/saver.py#L1213-L1228
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/tools/Editra/src/ed_shelf.py
python
EdShelfBook.OnTabMenu
(self, evt)
Handle tab menu events
Handle tab menu events
[ "Handle", "tab", "menu", "events" ]
def OnTabMenu(self, evt): """Handle tab menu events""" handler = self._menu.GetHandler(evt.Id) if handler is not None: handler(self.GetCurrentPage(), evt) else: evt.Skip()
[ "def", "OnTabMenu", "(", "self", ",", "evt", ")", ":", "handler", "=", "self", ".", "_menu", ".", "GetHandler", "(", "evt", ".", "Id", ")", "if", "handler", "is", "not", "None", ":", "handler", "(", "self", ".", "GetCurrentPage", "(", ")", ",", "evt", ")", "else", ":", "evt", ".", "Skip", "(", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/src/ed_shelf.py#L190-L196
windystrife/UnrealEngine_NVIDIAGameWorks
b50e6338a7c5b26374d66306ebc7807541ff815e
Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/bisect.py
python
bisect_right
(a, x, lo=0, hi=None)
return lo
Return the index where to insert item x in list a, assuming a is sorted. The return value i is such that all e in a[:i] have e <= x, and all e in a[i:] have e > x. So if x already appears in the list, a.insert(x) will insert just after the rightmost x already there. Optional args lo (default 0) and hi (default len(a)) bound the slice of a to be searched.
Return the index where to insert item x in list a, assuming a is sorted.
[ "Return", "the", "index", "where", "to", "insert", "item", "x", "in", "list", "a", "assuming", "a", "is", "sorted", "." ]
def bisect_right(a, x, lo=0, hi=None): """Return the index where to insert item x in list a, assuming a is sorted. The return value i is such that all e in a[:i] have e <= x, and all e in a[i:] have e > x. So if x already appears in the list, a.insert(x) will insert just after the rightmost x already there. Optional args lo (default 0) and hi (default len(a)) bound the slice of a to be searched. """ if lo < 0: raise ValueError('lo must be non-negative') if hi is None: hi = len(a) while lo < hi: mid = (lo+hi)//2 if x < a[mid]: hi = mid else: lo = mid+1 return lo
[ "def", "bisect_right", "(", "a", ",", "x", ",", "lo", "=", "0", ",", "hi", "=", "None", ")", ":", "if", "lo", "<", "0", ":", "raise", "ValueError", "(", "'lo must be non-negative'", ")", "if", "hi", "is", "None", ":", "hi", "=", "len", "(", "a", ")", "while", "lo", "<", "hi", ":", "mid", "=", "(", "lo", "+", "hi", ")", "//", "2", "if", "x", "<", "a", "[", "mid", "]", ":", "hi", "=", "mid", "else", ":", "lo", "=", "mid", "+", "1", "return", "lo" ]
https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/bisect.py#L24-L43
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/windows/Lib/xml/etree/ElementTree.py
python
ProcessingInstruction
(target, text=None)
return element
Processing Instruction element factory. This function creates a special element which the standard serializer serializes as an XML comment. *target* is a string containing the processing instruction, *text* is a string containing the processing instruction contents, if any.
Processing Instruction element factory.
[ "Processing", "Instruction", "element", "factory", "." ]
def ProcessingInstruction(target, text=None): """Processing Instruction element factory. This function creates a special element which the standard serializer serializes as an XML comment. *target* is a string containing the processing instruction, *text* is a string containing the processing instruction contents, if any. """ element = Element(ProcessingInstruction) element.text = target if text: element.text = element.text + " " + text return element
[ "def", "ProcessingInstruction", "(", "target", ",", "text", "=", "None", ")", ":", "element", "=", "Element", "(", "ProcessingInstruction", ")", "element", ".", "text", "=", "target", "if", "text", ":", "element", ".", "text", "=", "element", ".", "text", "+", "\" \"", "+", "text", "return", "element" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/xml/etree/ElementTree.py#L476-L490
LiquidPlayer/LiquidCore
9405979363f2353ac9a71ad8ab59685dd7f919c9
deps/node-10.15.3/tools/gyp/pylib/gyp/MSVSUtil.py
python
_SuffixName
(name, suffix)
return '#'.join(parts)
Add a suffix to the end of a target. Arguments: name: name of the target (foo#target) suffix: the suffix to be added Returns: Target name with suffix added (foo_suffix#target)
Add a suffix to the end of a target.
[ "Add", "a", "suffix", "to", "the", "end", "of", "a", "target", "." ]
def _SuffixName(name, suffix): """Add a suffix to the end of a target. Arguments: name: name of the target (foo#target) suffix: the suffix to be added Returns: Target name with suffix added (foo_suffix#target) """ parts = name.rsplit('#', 1) parts[0] = '%s_%s' % (parts[0], suffix) return '#'.join(parts)
[ "def", "_SuffixName", "(", "name", ",", "suffix", ")", ":", "parts", "=", "name", ".", "rsplit", "(", "'#'", ",", "1", ")", "parts", "[", "0", "]", "=", "'%s_%s'", "%", "(", "parts", "[", "0", "]", ",", "suffix", ")", "return", "'#'", ".", "join", "(", "parts", ")" ]
https://github.com/LiquidPlayer/LiquidCore/blob/9405979363f2353ac9a71ad8ab59685dd7f919c9/deps/node-10.15.3/tools/gyp/pylib/gyp/MSVSUtil.py#L48-L59
OAID/Caffe-HRT
aae71e498ab842c6f92bcc23fc668423615a4d65
scripts/cpp_lint.py
python
ProcessFile
(filename, vlevel, extra_check_functions=[])
Does google-lint on a single file. Args: filename: The name of the file to parse. vlevel: The level of errors to report. Every error of confidence >= verbose_level will be reported. 0 is a good default. extra_check_functions: An array of additional check functions that will be run on each source line. Each function takes 4 arguments: filename, clean_lines, line, error
Does google-lint on a single file.
[ "Does", "google", "-", "lint", "on", "a", "single", "file", "." ]
def ProcessFile(filename, vlevel, extra_check_functions=[]): """Does google-lint on a single file. Args: filename: The name of the file to parse. vlevel: The level of errors to report. Every error of confidence >= verbose_level will be reported. 0 is a good default. extra_check_functions: An array of additional check functions that will be run on each source line. Each function takes 4 arguments: filename, clean_lines, line, error """ _SetVerboseLevel(vlevel) try: # Support the UNIX convention of using "-" for stdin. Note that # we are not opening the file with universal newline support # (which codecs doesn't support anyway), so the resulting lines do # contain trailing '\r' characters if we are reading a file that # has CRLF endings. # If after the split a trailing '\r' is present, it is removed # below. If it is not expected to be present (i.e. os.linesep != # '\r\n' as in Windows), a warning is issued below if this file # is processed. if filename == '-': lines = codecs.StreamReaderWriter(sys.stdin, codecs.getreader('utf8'), codecs.getwriter('utf8'), 'replace').read().split('\n') else: lines = codecs.open(filename, 'r', 'utf8', 'replace').read().split('\n') carriage_return_found = False # Remove trailing '\r'. for linenum in range(len(lines)): if lines[linenum].endswith('\r'): lines[linenum] = lines[linenum].rstrip('\r') carriage_return_found = True except IOError: sys.stderr.write( "Skipping input '%s': Can't open for reading\n" % filename) return # Note, if no dot is found, this will give the entire filename as the ext. file_extension = filename[filename.rfind('.') + 1:] # When reading from stdin, the extension is unknown, so no cpplint tests # should rely on the extension. if filename != '-' and file_extension not in _valid_extensions: sys.stderr.write('Ignoring %s; not a valid file name ' '(%s)\n' % (filename, ', '.join(_valid_extensions))) else: ProcessFileData(filename, file_extension, lines, Error, extra_check_functions) if carriage_return_found and os.linesep != '\r\n': # Use 0 for linenum since outputting only one error for potentially # several lines. Error(filename, 0, 'whitespace/newline', 1, 'One or more unexpected \\r (^M) found;' 'better to use only a \\n') sys.stderr.write('Done processing %s\n' % filename)
[ "def", "ProcessFile", "(", "filename", ",", "vlevel", ",", "extra_check_functions", "=", "[", "]", ")", ":", "_SetVerboseLevel", "(", "vlevel", ")", "try", ":", "# Support the UNIX convention of using \"-\" for stdin. Note that", "# we are not opening the file with universal newline support", "# (which codecs doesn't support anyway), so the resulting lines do", "# contain trailing '\\r' characters if we are reading a file that", "# has CRLF endings.", "# If after the split a trailing '\\r' is present, it is removed", "# below. If it is not expected to be present (i.e. os.linesep !=", "# '\\r\\n' as in Windows), a warning is issued below if this file", "# is processed.", "if", "filename", "==", "'-'", ":", "lines", "=", "codecs", ".", "StreamReaderWriter", "(", "sys", ".", "stdin", ",", "codecs", ".", "getreader", "(", "'utf8'", ")", ",", "codecs", ".", "getwriter", "(", "'utf8'", ")", ",", "'replace'", ")", ".", "read", "(", ")", ".", "split", "(", "'\\n'", ")", "else", ":", "lines", "=", "codecs", ".", "open", "(", "filename", ",", "'r'", ",", "'utf8'", ",", "'replace'", ")", ".", "read", "(", ")", ".", "split", "(", "'\\n'", ")", "carriage_return_found", "=", "False", "# Remove trailing '\\r'.", "for", "linenum", "in", "range", "(", "len", "(", "lines", ")", ")", ":", "if", "lines", "[", "linenum", "]", ".", "endswith", "(", "'\\r'", ")", ":", "lines", "[", "linenum", "]", "=", "lines", "[", "linenum", "]", ".", "rstrip", "(", "'\\r'", ")", "carriage_return_found", "=", "True", "except", "IOError", ":", "sys", ".", "stderr", ".", "write", "(", "\"Skipping input '%s': Can't open for reading\\n\"", "%", "filename", ")", "return", "# Note, if no dot is found, this will give the entire filename as the ext.", "file_extension", "=", "filename", "[", "filename", ".", "rfind", "(", "'.'", ")", "+", "1", ":", "]", "# When reading from stdin, the extension is unknown, so no cpplint tests", "# should rely on the extension.", "if", "filename", "!=", "'-'", "and", "file_extension", "not", "in", "_valid_extensions", ":", "sys", ".", "stderr", ".", "write", "(", "'Ignoring %s; not a valid file name '", "'(%s)\\n'", "%", "(", "filename", ",", "', '", ".", "join", "(", "_valid_extensions", ")", ")", ")", "else", ":", "ProcessFileData", "(", "filename", ",", "file_extension", ",", "lines", ",", "Error", ",", "extra_check_functions", ")", "if", "carriage_return_found", "and", "os", ".", "linesep", "!=", "'\\r\\n'", ":", "# Use 0 for linenum since outputting only one error for potentially", "# several lines.", "Error", "(", "filename", ",", "0", ",", "'whitespace/newline'", ",", "1", ",", "'One or more unexpected \\\\r (^M) found;'", "'better to use only a \\\\n'", ")", "sys", ".", "stderr", ".", "write", "(", "'Done processing %s\\n'", "%", "filename", ")" ]
https://github.com/OAID/Caffe-HRT/blob/aae71e498ab842c6f92bcc23fc668423615a4d65/scripts/cpp_lint.py#L4689-L4754
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python3/src/Lib/ipaddress.py
python
_split_optional_netmask
(address)
return addr
Helper to split the netmask and raise AddressValueError if needed
Helper to split the netmask and raise AddressValueError if needed
[ "Helper", "to", "split", "the", "netmask", "and", "raise", "AddressValueError", "if", "needed" ]
def _split_optional_netmask(address): """Helper to split the netmask and raise AddressValueError if needed""" addr = str(address).split('/') if len(addr) > 2: raise AddressValueError("Only one '/' permitted in %r" % address) return addr
[ "def", "_split_optional_netmask", "(", "address", ")", ":", "addr", "=", "str", "(", "address", ")", ".", "split", "(", "'/'", ")", "if", "len", "(", "addr", ")", ">", "2", ":", "raise", "AddressValueError", "(", "\"Only one '/' permitted in %r\"", "%", "address", ")", "return", "addr" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/ipaddress.py#L158-L163
natanielruiz/android-yolo
1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f
jni-build/jni/include/tensorflow/python/client/timeline.py
python
_ChromeTraceFormatter._create_event
(self, ph, category, name, pid, tid, timestamp)
return event
Creates a new Chrome Trace event. For details of the file format, see: https://github.com/catapult-project/catapult/blob/master/tracing/README.md Args: ph: The type of event - usually a single character. category: The event category as a string. name: The event name as a string. pid: Identifier of the process generating this event as an integer. tid: Identifier of the thread generating this event as an integer. timestamp: The timestamp of this event as a long integer. Returns: A JSON compatible event object.
Creates a new Chrome Trace event.
[ "Creates", "a", "new", "Chrome", "Trace", "event", "." ]
def _create_event(self, ph, category, name, pid, tid, timestamp): """Creates a new Chrome Trace event. For details of the file format, see: https://github.com/catapult-project/catapult/blob/master/tracing/README.md Args: ph: The type of event - usually a single character. category: The event category as a string. name: The event name as a string. pid: Identifier of the process generating this event as an integer. tid: Identifier of the thread generating this event as an integer. timestamp: The timestamp of this event as a long integer. Returns: A JSON compatible event object. """ event = {} event['ph'] = ph event['cat'] = category event['name'] = name event['pid'] = pid event['tid'] = tid event['ts'] = timestamp return event
[ "def", "_create_event", "(", "self", ",", "ph", ",", "category", ",", "name", ",", "pid", ",", "tid", ",", "timestamp", ")", ":", "event", "=", "{", "}", "event", "[", "'ph'", "]", "=", "ph", "event", "[", "'cat'", "]", "=", "category", "event", "[", "'name'", "]", "=", "name", "event", "[", "'pid'", "]", "=", "pid", "event", "[", "'tid'", "]", "=", "tid", "event", "[", "'ts'", "]", "=", "timestamp", "return", "event" ]
https://github.com/natanielruiz/android-yolo/blob/1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f/jni-build/jni/include/tensorflow/python/client/timeline.py#L65-L89
weolar/miniblink49
1c4678db0594a4abde23d3ebbcc7cd13c3170777
third_party/WebKit/Tools/Scripts/webkitpy/thirdparty/coverage/cmdline.py
python
CmdOptionParser.__init__
(self, action, options=None, defaults=None, usage=None, cmd=None, description=None )
Create an OptionParser for a coverage command. `action` is the slug to put into `options.actions`. `options` is a list of Option's for the command. `defaults` is a dict of default value for options. `usage` is the usage string to display in help. `cmd` is the command name, if different than `action`. `description` is the description of the command, for the help text.
Create an OptionParser for a coverage command.
[ "Create", "an", "OptionParser", "for", "a", "coverage", "command", "." ]
def __init__(self, action, options=None, defaults=None, usage=None, cmd=None, description=None ): """Create an OptionParser for a coverage command. `action` is the slug to put into `options.actions`. `options` is a list of Option's for the command. `defaults` is a dict of default value for options. `usage` is the usage string to display in help. `cmd` is the command name, if different than `action`. `description` is the description of the command, for the help text. """ if usage: usage = "%prog " + usage super(CmdOptionParser, self).__init__( prog="coverage %s" % (cmd or action), usage=usage, description=description, ) self.set_defaults(actions=[action], **(defaults or {})) if options: self.add_options(options) self.cmd = cmd or action
[ "def", "__init__", "(", "self", ",", "action", ",", "options", "=", "None", ",", "defaults", "=", "None", ",", "usage", "=", "None", ",", "cmd", "=", "None", ",", "description", "=", "None", ")", ":", "if", "usage", ":", "usage", "=", "\"%prog \"", "+", "usage", "super", "(", "CmdOptionParser", ",", "self", ")", ".", "__init__", "(", "prog", "=", "\"coverage %s\"", "%", "(", "cmd", "or", "action", ")", ",", "usage", "=", "usage", ",", "description", "=", "description", ",", ")", "self", ".", "set_defaults", "(", "actions", "=", "[", "action", "]", ",", "*", "*", "(", "defaults", "or", "{", "}", ")", ")", "if", "options", ":", "self", ".", "add_options", "(", "options", ")", "self", ".", "cmd", "=", "cmd", "or", "action" ]
https://github.com/weolar/miniblink49/blob/1c4678db0594a4abde23d3ebbcc7cd13c3170777/third_party/WebKit/Tools/Scripts/webkitpy/thirdparty/coverage/cmdline.py#L199-L222
apple/turicreate
cce55aa5311300e3ce6af93cb45ba791fd1bdf49
src/python/turicreate/data_structures/sketch.py
python
Sketch.num_elements_processed
(self)
Returns the number of elements processed so far. If the sketch is created with background == False (default), this will always return the length of the input array. Otherwise, this will return the number of elements processed so far.
Returns the number of elements processed so far. If the sketch is created with background == False (default), this will always return the length of the input array. Otherwise, this will return the number of elements processed so far.
[ "Returns", "the", "number", "of", "elements", "processed", "so", "far", ".", "If", "the", "sketch", "is", "created", "with", "background", "==", "False", "(", "default", ")", "this", "will", "always", "return", "the", "length", "of", "the", "input", "array", ".", "Otherwise", "this", "will", "return", "the", "number", "of", "elements", "processed", "so", "far", "." ]
def num_elements_processed(self): """ Returns the number of elements processed so far. If the sketch is created with background == False (default), this will always return the length of the input array. Otherwise, this will return the number of elements processed so far. """ with cython_context(): return self.__proxy__.num_elements_processed()
[ "def", "num_elements_processed", "(", "self", ")", ":", "with", "cython_context", "(", ")", ":", "return", "self", ".", "__proxy__", ".", "num_elements_processed", "(", ")" ]
https://github.com/apple/turicreate/blob/cce55aa5311300e3ce6af93cb45ba791fd1bdf49/src/python/turicreate/data_structures/sketch.py#L502-L510
livecode/livecode
4606a10ea10b16d5071d0f9f263ccdd7ede8b31d
gyp/pylib/gyp/ordered_dict.py
python
OrderedDict.__reversed__
(self)
od.__reversed__() <==> reversed(od)
od.__reversed__() <==> reversed(od)
[ "od", ".", "__reversed__", "()", "<", "==", ">", "reversed", "(", "od", ")" ]
def __reversed__(self): 'od.__reversed__() <==> reversed(od)' root = self.__root curr = root[0] while curr is not root: yield curr[2] curr = curr[0]
[ "def", "__reversed__", "(", "self", ")", ":", "root", "=", "self", ".", "__root", "curr", "=", "root", "[", "0", "]", "while", "curr", "is", "not", "root", ":", "yield", "curr", "[", "2", "]", "curr", "=", "curr", "[", "0", "]" ]
https://github.com/livecode/livecode/blob/4606a10ea10b16d5071d0f9f263ccdd7ede8b31d/gyp/pylib/gyp/ordered_dict.py#L98-L104
ppizarro/coursera
b39847928df4d9d5986b801085c025e8e9122b6a
Learn to Program: Crafting Quality Code/assignment 2/rat_race.py
python
main
()
Prompt for a maze file, read the maze, and start the game.
Prompt for a maze file, read the maze, and start the game.
[ "Prompt", "for", "a", "maze", "file", "read", "the", "maze", "and", "start", "the", "game", "." ]
def main(): """ Prompt for a maze file, read the maze, and start the game. """ root = tkinter.Tk() maze_filename = tkinter.filedialog.askopenfilename() with open(maze_filename, 'r') as maze_file: maze_list = read_maze(maze_file) rat_1, rat_2 = find_rats_replace_hallway(maze_list) the_maze = a2.Maze(maze_list, rat_1, rat_2) app = MazeApp(root, the_maze) app.mainloop()
[ "def", "main", "(", ")", ":", "root", "=", "tkinter", ".", "Tk", "(", ")", "maze_filename", "=", "tkinter", ".", "filedialog", ".", "askopenfilename", "(", ")", "with", "open", "(", "maze_filename", ",", "'r'", ")", "as", "maze_file", ":", "maze_list", "=", "read_maze", "(", "maze_file", ")", "rat_1", ",", "rat_2", "=", "find_rats_replace_hallway", "(", "maze_list", ")", "the_maze", "=", "a2", ".", "Maze", "(", "maze_list", ",", "rat_1", ",", "rat_2", ")", "app", "=", "MazeApp", "(", "root", ",", "the_maze", ")", "app", ".", "mainloop", "(", ")" ]
https://github.com/ppizarro/coursera/blob/b39847928df4d9d5986b801085c025e8e9122b6a/Learn to Program: Crafting Quality Code/assignment 2/rat_race.py#L204-L217
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/_windows.py
python
MultiChoiceDialog.__init__
(self, *args, **kwargs)
__init__(self, Window parent, String message, String caption, List choices=EmptyList, long style=CHOICEDLG_STYLE, Point pos=DefaultPosition) -> MultiChoiceDialog Constructor. Use the `ShowModal` method to show the dialog. :param parent: The parent window. :param message: Text to display above the list of selections. :param caption: Text to use in the title bar of the dialog. :param choices: A list of strings or unicode objects that the user is allowed to choose from. :param style: Styles to apply to the dialog. The default value is equivallent to wx.DEFAULT_DIALOG_STYLE|wx.RESIZE_BORDER|wx.OK|wx.CANCEL|wx.CENTER. :param pos: Where to position the dialog (not used on Windows)
__init__(self, Window parent, String message, String caption, List choices=EmptyList, long style=CHOICEDLG_STYLE, Point pos=DefaultPosition) -> MultiChoiceDialog
[ "__init__", "(", "self", "Window", "parent", "String", "message", "String", "caption", "List", "choices", "=", "EmptyList", "long", "style", "=", "CHOICEDLG_STYLE", "Point", "pos", "=", "DefaultPosition", ")", "-", ">", "MultiChoiceDialog" ]
def __init__(self, *args, **kwargs): """ __init__(self, Window parent, String message, String caption, List choices=EmptyList, long style=CHOICEDLG_STYLE, Point pos=DefaultPosition) -> MultiChoiceDialog Constructor. Use the `ShowModal` method to show the dialog. :param parent: The parent window. :param message: Text to display above the list of selections. :param caption: Text to use in the title bar of the dialog. :param choices: A list of strings or unicode objects that the user is allowed to choose from. :param style: Styles to apply to the dialog. The default value is equivallent to wx.DEFAULT_DIALOG_STYLE|wx.RESIZE_BORDER|wx.OK|wx.CANCEL|wx.CENTER. :param pos: Where to position the dialog (not used on Windows) """ _windows_.MultiChoiceDialog_swiginit(self,_windows_.new_MultiChoiceDialog(*args, **kwargs)) self._setOORInfo(self)
[ "def", "__init__", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "_windows_", ".", "MultiChoiceDialog_swiginit", "(", "self", ",", "_windows_", ".", "new_MultiChoiceDialog", "(", "*", "args", ",", "*", "*", "kwargs", ")", ")", "self", ".", "_setOORInfo", "(", "self", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_windows.py#L3281-L3301
NeoGeographyToolkit/StereoPipeline
eedf54a919fb5cce1ab0e280bb0df4050763aa11
src/asp/IceBridge/icebridge_common.py
python
getJpegs
(folder)
return files
Get jpeg files in given directory. This returns the files without sorting or the folder name prepended to them.
Get jpeg files in given directory. This returns the files without sorting or the folder name prepended to them.
[ "Get", "jpeg", "files", "in", "given", "directory", ".", "This", "returns", "the", "files", "without", "sorting", "or", "the", "folder", "name", "prepended", "to", "them", "." ]
def getJpegs(folder): # TODO: This function should not be used as it is not robust. # Rather, look up the index, and read only files listed there. '''Get jpeg files in given directory. This returns the files without sorting or the folder name prepended to them.''' files = [] for f in os.listdir(folder): ext = os.path.splitext(f)[1] if ext != '.JPG': continue files.append(f) return files
[ "def", "getJpegs", "(", "folder", ")", ":", "# TODO: This function should not be used as it is not robust.", "# Rather, look up the index, and read only files listed there.", "files", "=", "[", "]", "for", "f", "in", "os", ".", "listdir", "(", "folder", ")", ":", "ext", "=", "os", ".", "path", ".", "splitext", "(", "f", ")", "[", "1", "]", "if", "ext", "!=", "'.JPG'", ":", "continue", "files", ".", "append", "(", "f", ")", "return", "files" ]
https://github.com/NeoGeographyToolkit/StereoPipeline/blob/eedf54a919fb5cce1ab0e280bb0df4050763aa11/src/asp/IceBridge/icebridge_common.py#L917-L931
apache/kudu
90895ce76590f10730ad7aac3613b69d89ff5422
build-support/kudu_util.py
python
check_output
(*popenargs, **kwargs)
return output
r"""Run command with arguments and return its output as a byte string. Backported from Python 2.7 as it's implemented as pure python on stdlib. >>> check_output(['/usr/bin/python', '--version']) Python 2.6.2
r"""Run command with arguments and return its output as a byte string. Backported from Python 2.7 as it's implemented as pure python on stdlib. >>> check_output(['/usr/bin/python', '--version']) Python 2.6.2
[ "r", "Run", "command", "with", "arguments", "and", "return", "its", "output", "as", "a", "byte", "string", ".", "Backported", "from", "Python", "2", ".", "7", "as", "it", "s", "implemented", "as", "pure", "python", "on", "stdlib", ".", ">>>", "check_output", "(", "[", "/", "usr", "/", "bin", "/", "python", "--", "version", "]", ")", "Python", "2", ".", "6", ".", "2" ]
def check_output(*popenargs, **kwargs): r"""Run command with arguments and return its output as a byte string. Backported from Python 2.7 as it's implemented as pure python on stdlib. >>> check_output(['/usr/bin/python', '--version']) Python 2.6.2 """ process = subprocess.Popen(stdout=subprocess.PIPE, *popenargs, **kwargs) output, unused_err = process.communicate() retcode = process.poll() if retcode: cmd = kwargs.get("args") if cmd is None: cmd = popenargs[0] error = subprocess.CalledProcessError(retcode, cmd) error.output = output raise error return output
[ "def", "check_output", "(", "*", "popenargs", ",", "*", "*", "kwargs", ")", ":", "process", "=", "subprocess", ".", "Popen", "(", "stdout", "=", "subprocess", ".", "PIPE", ",", "*", "popenargs", ",", "*", "*", "kwargs", ")", "output", ",", "unused_err", "=", "process", ".", "communicate", "(", ")", "retcode", "=", "process", ".", "poll", "(", ")", "if", "retcode", ":", "cmd", "=", "kwargs", ".", "get", "(", "\"args\"", ")", "if", "cmd", "is", "None", ":", "cmd", "=", "popenargs", "[", "0", "]", "error", "=", "subprocess", ".", "CalledProcessError", "(", "retcode", ",", "cmd", ")", "error", ".", "output", "=", "output", "raise", "error", "return", "output" ]
https://github.com/apache/kudu/blob/90895ce76590f10730ad7aac3613b69d89ff5422/build-support/kudu_util.py#L74-L90
google/VoltAir
88bc3c8e09420d600d0b3d6d6c6eea75ebe0c5f2
build/build_android.py
python
RenameApk
(dst_apk)
Run the 'mv' command which moves the APK to a more reasonable name. Args: dst_apk: name of destination apk
Run the 'mv' command which moves the APK to a more reasonable name.
[ "Run", "the", "mv", "command", "which", "moves", "the", "APK", "to", "a", "more", "reasonable", "name", "." ]
def RenameApk(dst_apk): """Run the 'mv' command which moves the APK to a more reasonable name. Args: dst_apk: name of destination apk """ src_apk = os.getcwd() + "/android-build/bin/QtApp-release.apk" print >> sys.stderr, "Renaming %s to %s" % (src_apk, dst_apk) os.rename(src_apk, dst_apk)
[ "def", "RenameApk", "(", "dst_apk", ")", ":", "src_apk", "=", "os", ".", "getcwd", "(", ")", "+", "\"/android-build/bin/QtApp-release.apk\"", "print", ">>", "sys", ".", "stderr", ",", "\"Renaming %s to %s\"", "%", "(", "src_apk", ",", "dst_apk", ")", "os", ".", "rename", "(", "src_apk", ",", "dst_apk", ")" ]
https://github.com/google/VoltAir/blob/88bc3c8e09420d600d0b3d6d6c6eea75ebe0c5f2/build/build_android.py#L183-L192
francinexue/xuefu
b6ff79747a42e020588c0c0a921048e08fe4680c
api/ctpx/ctptd.py
python
CtpTd.onRspQryOrder
(self, OrderField, RspInfoField, requestId, final)
请求查询报单响应
请求查询报单响应
[ "请求查询报单响应" ]
def onRspQryOrder(self, OrderField, RspInfoField, requestId, final): """请求查询报单响应""" if OrderField: #这个字段也可能为空 logger.debug(u"onRspQryOrder --- brokerID:{0}, orderRef:{1}, limitPrice:{2}, volume:{3}, orderPriceType:{4}," u"direction: {5}, combOffsetFlag: {6}, combHedgeFlag:{7}, contingentCondition: {8}, forceCloseReason: {9}," u"isAutoSuspend: {10}, timeCondition: {11}, volumeCondition:{12}, minVolume: {13}, instrumentID: {14}" .format(OrderField.brokerID, OrderField.orderRef, OrderField.limitPrice, OrderField.volumeTotalOriginal, OrderField.orderPriceType, OrderField.direction, OrderField.combOffsetFlag, OrderField.combHedgeFlag, OrderField.contingentCondition, OrderField.forceCloseReason, OrderField.isAutoSuspend, OrderField.timeCondition, OrderField.volumeCondition, OrderField.minVolume, OrderField.instrumentID)) self.__rspQryOrder_dic[OrderField.orderRef] = OrderField if final: for listener in self._barEventListeners: listener.onRspQryOrder(self.__rspQryOrder_dic,requestId) self.__rspQryOrder_dic = {} if RspInfoField: #这个字段竟然能能返回为空 logger.debug(u"onRspQryOrder --- errorCode: {0}, errorMsg:{1}.".format( RspInfoField.errorID, RspInfoField.errorMsg.decode("gbk")))
[ "def", "onRspQryOrder", "(", "self", ",", "OrderField", ",", "RspInfoField", ",", "requestId", ",", "final", ")", ":", "if", "OrderField", ":", "#这个字段也可能为空", "logger", ".", "debug", "(", "u\"onRspQryOrder --- brokerID:{0}, orderRef:{1}, limitPrice:{2}, volume:{3}, orderPriceType:{4},\"", "u\"direction: {5}, combOffsetFlag: {6}, combHedgeFlag:{7}, contingentCondition: {8}, forceCloseReason: {9},\"", "u\"isAutoSuspend: {10}, timeCondition: {11}, volumeCondition:{12}, minVolume: {13}, instrumentID: {14}\"", ".", "format", "(", "OrderField", ".", "brokerID", ",", "OrderField", ".", "orderRef", ",", "OrderField", ".", "limitPrice", ",", "OrderField", ".", "volumeTotalOriginal", ",", "OrderField", ".", "orderPriceType", ",", "OrderField", ".", "direction", ",", "OrderField", ".", "combOffsetFlag", ",", "OrderField", ".", "combHedgeFlag", ",", "OrderField", ".", "contingentCondition", ",", "OrderField", ".", "forceCloseReason", ",", "OrderField", ".", "isAutoSuspend", ",", "OrderField", ".", "timeCondition", ",", "OrderField", ".", "volumeCondition", ",", "OrderField", ".", "minVolume", ",", "OrderField", ".", "instrumentID", ")", ")", "self", ".", "__rspQryOrder_dic", "[", "OrderField", ".", "orderRef", "]", "=", "OrderField", "if", "final", ":", "for", "listener", "in", "self", ".", "_barEventListeners", ":", "listener", ".", "onRspQryOrder", "(", "self", ".", "__rspQryOrder_dic", ",", "requestId", ")", "self", ".", "__rspQryOrder_dic", "=", "{", "}", "if", "RspInfoField", ":", "#这个字段竟然能能返回为空", "logger", ".", "debug", "(", "u\"onRspQryOrder --- errorCode: {0}, errorMsg:{1}.\"", ".", "format", "(", "RspInfoField", ".", "errorID", ",", "RspInfoField", ".", "errorMsg", ".", "decode", "(", "\"gbk\"", ")", ")", ")" ]
https://github.com/francinexue/xuefu/blob/b6ff79747a42e020588c0c0a921048e08fe4680c/api/ctpx/ctptd.py#L172-L189
tensorflow/tensorflow
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
tensorflow/python/ops/array_ops.py
python
batch_gather_nd
(params, indices, batch_dims, name=None)
return out
gather_nd implementation with batch support.
gather_nd implementation with batch support.
[ "gather_nd", "implementation", "with", "batch", "support", "." ]
def batch_gather_nd(params, indices, batch_dims, name=None): """gather_nd implementation with batch support.""" with ops.name_scope(name, "BatchGatherND", [params, indices]): indices = ops.convert_to_tensor(indices, name="indices") params = ops.convert_to_tensor(params, name="params") if not isinstance(batch_dims, int): raise TypeError(f"Argument `batch_dims` must be an int; got {batch_dims}") if batch_dims < 0: raise ValueError("tf.gather_nd does not allow negative batch_dims.") params_ndims = params.shape.ndims indices_ndims = indices.shape.ndims if indices_ndims is not None and batch_dims >= indices_ndims: raise ValueError(f"Argument `batch_dims` = {batch_dims} must be " f"less than rank(`indices`) = {indices_ndims}") if params_ndims is not None and batch_dims >= params_ndims: raise ValueError(f"Argument `batch_dims` = {batch_dims} must be " f"less than rank(`params`) = {params_ndims}") expand = batch_dims == 0 if expand: # Normally gather_nd will be called when batch_dims == 0. # But if this function is called with batch_dims = 0, e.g. for testing # purposes, this adds a dummy batch dimension to make batch_dims = 1. params = expand_dims(params, axis=0) indices = expand_dims(indices, axis=0) batch_dims = 1 params_shape = shape(params) indices_shape = shape(indices) batch_shape = params_shape[:batch_dims] batch_size = gen_math_ops.prod(batch_shape, [0]) index_internal_ndims = rank(indices) - batch_dims - 1 indices_internal_shape = indices_shape[batch_dims:-1] # Assuming a 'params' with shape [b1, ..., bM, g1, ..., gN] and an 'indices' # with shape [b1, ..., bM, i1, ..., iK, C], where C <= N, we need to modify # 'indices' s.t. it has shape [i1, ..., iK, D], where D <= M + N and slices # to the entire 'params' tensor. # Assuming we have a batch of shape [B1, B2], we use meshgrid to create a # grid of size B1 x B2. batch_dim_list = unstack(batch_shape, axis=0) dim_ranges = [ gen_math_ops.cast(gen_math_ops._range(0, x, 1), indices.dtype) for x in batch_dim_list ] mesh_list = meshgrid(*dim_ranges, indexing="ij") if dim_ranges else [] # Then we flatten and stack the tensors to form a (B1.B2) by 2 matrix. flat_list = [reshape(x, shape=(-1,)) for x in mesh_list] index_grid = transpose(stack(flat_list, axis=0)) # We need to concatenate these batch coordinates with the internal indices. # concat -> index_grid [B1.B2, 2] with indices [i1, ..., iK, C] # So we reshape them both to [(B1.B2), i1, ..., iK, *] index_grid_shape = shape(index_grid) index_grid = reshape( index_grid, concat([ index_grid_shape[:1], ones(index_internal_ndims, dtype=dtypes.int32), index_grid_shape[1:] ], axis=0)) tile_shape = concat(((1,), indices_internal_shape, (1,)), axis=0) index_grid = tile(index_grid, multiples=tile_shape) # index_grid now has shape [(B1.B2), i1, ..., iK, 2] flat_shape = concat(([batch_size], indices_shape[batch_dims:]), axis=0) flat_indices = reshape(indices, shape=flat_shape) # flat_indices now has shape [(B1.B2), i1, ..., iK, C] indices = concat((index_grid, flat_indices), axis=-1) # indices has shape [(B1.B2), i1, ..., iK, 2+C] out = gen_array_ops.gather_nd(params, indices) # out has shape [(B1.B2), i1, ..., iK, N-C]. Now we reshape batch to # its original form. out_shape = shape(out) out = reshape(out, shape=concat((batch_shape, out_shape[1:]), axis=0)) if expand: out = squeeze(out, axis=0) return out
[ "def", "batch_gather_nd", "(", "params", ",", "indices", ",", "batch_dims", ",", "name", "=", "None", ")", ":", "with", "ops", ".", "name_scope", "(", "name", ",", "\"BatchGatherND\"", ",", "[", "params", ",", "indices", "]", ")", ":", "indices", "=", "ops", ".", "convert_to_tensor", "(", "indices", ",", "name", "=", "\"indices\"", ")", "params", "=", "ops", ".", "convert_to_tensor", "(", "params", ",", "name", "=", "\"params\"", ")", "if", "not", "isinstance", "(", "batch_dims", ",", "int", ")", ":", "raise", "TypeError", "(", "f\"Argument `batch_dims` must be an int; got {batch_dims}\"", ")", "if", "batch_dims", "<", "0", ":", "raise", "ValueError", "(", "\"tf.gather_nd does not allow negative batch_dims.\"", ")", "params_ndims", "=", "params", ".", "shape", ".", "ndims", "indices_ndims", "=", "indices", ".", "shape", ".", "ndims", "if", "indices_ndims", "is", "not", "None", "and", "batch_dims", ">=", "indices_ndims", ":", "raise", "ValueError", "(", "f\"Argument `batch_dims` = {batch_dims} must be \"", "f\"less than rank(`indices`) = {indices_ndims}\"", ")", "if", "params_ndims", "is", "not", "None", "and", "batch_dims", ">=", "params_ndims", ":", "raise", "ValueError", "(", "f\"Argument `batch_dims` = {batch_dims} must be \"", "f\"less than rank(`params`) = {params_ndims}\"", ")", "expand", "=", "batch_dims", "==", "0", "if", "expand", ":", "# Normally gather_nd will be called when batch_dims == 0.", "# But if this function is called with batch_dims = 0, e.g. for testing", "# purposes, this adds a dummy batch dimension to make batch_dims = 1.", "params", "=", "expand_dims", "(", "params", ",", "axis", "=", "0", ")", "indices", "=", "expand_dims", "(", "indices", ",", "axis", "=", "0", ")", "batch_dims", "=", "1", "params_shape", "=", "shape", "(", "params", ")", "indices_shape", "=", "shape", "(", "indices", ")", "batch_shape", "=", "params_shape", "[", ":", "batch_dims", "]", "batch_size", "=", "gen_math_ops", ".", "prod", "(", "batch_shape", ",", "[", "0", "]", ")", "index_internal_ndims", "=", "rank", "(", "indices", ")", "-", "batch_dims", "-", "1", "indices_internal_shape", "=", "indices_shape", "[", "batch_dims", ":", "-", "1", "]", "# Assuming a 'params' with shape [b1, ..., bM, g1, ..., gN] and an 'indices'", "# with shape [b1, ..., bM, i1, ..., iK, C], where C <= N, we need to modify", "# 'indices' s.t. it has shape [i1, ..., iK, D], where D <= M + N and slices", "# to the entire 'params' tensor.", "# Assuming we have a batch of shape [B1, B2], we use meshgrid to create a", "# grid of size B1 x B2.", "batch_dim_list", "=", "unstack", "(", "batch_shape", ",", "axis", "=", "0", ")", "dim_ranges", "=", "[", "gen_math_ops", ".", "cast", "(", "gen_math_ops", ".", "_range", "(", "0", ",", "x", ",", "1", ")", ",", "indices", ".", "dtype", ")", "for", "x", "in", "batch_dim_list", "]", "mesh_list", "=", "meshgrid", "(", "*", "dim_ranges", ",", "indexing", "=", "\"ij\"", ")", "if", "dim_ranges", "else", "[", "]", "# Then we flatten and stack the tensors to form a (B1.B2) by 2 matrix.", "flat_list", "=", "[", "reshape", "(", "x", ",", "shape", "=", "(", "-", "1", ",", ")", ")", "for", "x", "in", "mesh_list", "]", "index_grid", "=", "transpose", "(", "stack", "(", "flat_list", ",", "axis", "=", "0", ")", ")", "# We need to concatenate these batch coordinates with the internal indices.", "# concat -> index_grid [B1.B2, 2] with indices [i1, ..., iK, C]", "# So we reshape them both to [(B1.B2), i1, ..., iK, *]", "index_grid_shape", "=", "shape", "(", "index_grid", ")", "index_grid", "=", "reshape", "(", "index_grid", ",", "concat", "(", "[", "index_grid_shape", "[", ":", "1", "]", ",", "ones", "(", "index_internal_ndims", ",", "dtype", "=", "dtypes", ".", "int32", ")", ",", "index_grid_shape", "[", "1", ":", "]", "]", ",", "axis", "=", "0", ")", ")", "tile_shape", "=", "concat", "(", "(", "(", "1", ",", ")", ",", "indices_internal_shape", ",", "(", "1", ",", ")", ")", ",", "axis", "=", "0", ")", "index_grid", "=", "tile", "(", "index_grid", ",", "multiples", "=", "tile_shape", ")", "# index_grid now has shape [(B1.B2), i1, ..., iK, 2]", "flat_shape", "=", "concat", "(", "(", "[", "batch_size", "]", ",", "indices_shape", "[", "batch_dims", ":", "]", ")", ",", "axis", "=", "0", ")", "flat_indices", "=", "reshape", "(", "indices", ",", "shape", "=", "flat_shape", ")", "# flat_indices now has shape [(B1.B2), i1, ..., iK, C]", "indices", "=", "concat", "(", "(", "index_grid", ",", "flat_indices", ")", ",", "axis", "=", "-", "1", ")", "# indices has shape [(B1.B2), i1, ..., iK, 2+C]", "out", "=", "gen_array_ops", ".", "gather_nd", "(", "params", ",", "indices", ")", "# out has shape [(B1.B2), i1, ..., iK, N-C]. Now we reshape batch to", "# its original form.", "out_shape", "=", "shape", "(", "out", ")", "out", "=", "reshape", "(", "out", ",", "shape", "=", "concat", "(", "(", "batch_shape", ",", "out_shape", "[", "1", ":", "]", ")", ",", "axis", "=", "0", ")", ")", "if", "expand", ":", "out", "=", "squeeze", "(", "out", ",", "axis", "=", "0", ")", "return", "out" ]
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/ops/array_ops.py#L5702-L5778
oracle/graaljs
36a56e8e993d45fc40939a3a4d9c0c24990720f1
graal-nodejs/tools/gyp/pylib/gyp/generator/make.py
python
MakefileWriter.WriteList
(self, value_list, variable=None, prefix="", quoter=QuoteIfNecessary)
Write a variable definition that is a list of values. E.g. WriteList(['a','b'], 'foo', prefix='blah') writes out foo = blaha blahb but in a pretty-printed style.
Write a variable definition that is a list of values.
[ "Write", "a", "variable", "definition", "that", "is", "a", "list", "of", "values", "." ]
def WriteList(self, value_list, variable=None, prefix="", quoter=QuoteIfNecessary): """Write a variable definition that is a list of values. E.g. WriteList(['a','b'], 'foo', prefix='blah') writes out foo = blaha blahb but in a pretty-printed style. """ values = "" if value_list: value_list = [quoter(prefix + value) for value in value_list] values = " \\\n\t" + " \\\n\t".join(value_list) self.fp.write(f"{variable} :={values}\n\n")
[ "def", "WriteList", "(", "self", ",", "value_list", ",", "variable", "=", "None", ",", "prefix", "=", "\"\"", ",", "quoter", "=", "QuoteIfNecessary", ")", ":", "values", "=", "\"\"", "if", "value_list", ":", "value_list", "=", "[", "quoter", "(", "prefix", "+", "value", ")", "for", "value", "in", "value_list", "]", "values", "=", "\" \\\\\\n\\t\"", "+", "\" \\\\\\n\\t\"", ".", "join", "(", "value_list", ")", "self", ".", "fp", ".", "write", "(", "f\"{variable} :={values}\\n\\n\"", ")" ]
https://github.com/oracle/graaljs/blob/36a56e8e993d45fc40939a3a4d9c0c24990720f1/graal-nodejs/tools/gyp/pylib/gyp/generator/make.py#L1899-L1910
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/third_party/gsutil/third_party/oauth2client/oauth2client/service_account.py
python
_get_private_key
(private_key_pkcs8_text)
return rsa.PrivateKey.load_pkcs1( asn1_private_key.getComponentByName('privateKey').asOctets(), format='DER')
Get an RSA private key object from a pkcs8 representation.
Get an RSA private key object from a pkcs8 representation.
[ "Get", "an", "RSA", "private", "key", "object", "from", "a", "pkcs8", "representation", "." ]
def _get_private_key(private_key_pkcs8_text): """Get an RSA private key object from a pkcs8 representation.""" if not isinstance(private_key_pkcs8_text, six.binary_type): private_key_pkcs8_text = private_key_pkcs8_text.encode('ascii') der = rsa.pem.load_pem(private_key_pkcs8_text, 'PRIVATE KEY') asn1_private_key, _ = decoder.decode(der, asn1Spec=PrivateKeyInfo()) return rsa.PrivateKey.load_pkcs1( asn1_private_key.getComponentByName('privateKey').asOctets(), format='DER')
[ "def", "_get_private_key", "(", "private_key_pkcs8_text", ")", ":", "if", "not", "isinstance", "(", "private_key_pkcs8_text", ",", "six", ".", "binary_type", ")", ":", "private_key_pkcs8_text", "=", "private_key_pkcs8_text", ".", "encode", "(", "'ascii'", ")", "der", "=", "rsa", ".", "pem", ".", "load_pem", "(", "private_key_pkcs8_text", ",", "'PRIVATE KEY'", ")", "asn1_private_key", ",", "_", "=", "decoder", ".", "decode", "(", "der", ",", "asn1Spec", "=", "PrivateKeyInfo", "(", ")", ")", "return", "rsa", ".", "PrivateKey", ".", "load_pkcs1", "(", "asn1_private_key", ".", "getComponentByName", "(", "'privateKey'", ")", ".", "asOctets", "(", ")", ",", "format", "=", "'DER'", ")" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/gsutil/third_party/oauth2client/oauth2client/service_account.py#L130-L139
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/pkg_resources/__init__.py
python
WorkingSet.find
(self, req)
return dist
Find a distribution matching requirement `req` If there is an active distribution for the requested project, this returns it as long as it meets the version requirement specified by `req`. But, if there is an active distribution for the project and it does *not* meet the `req` requirement, ``VersionConflict`` is raised. If there is no active distribution for the requested project, ``None`` is returned.
Find a distribution matching requirement `req`
[ "Find", "a", "distribution", "matching", "requirement", "req" ]
def find(self, req): """Find a distribution matching requirement `req` If there is an active distribution for the requested project, this returns it as long as it meets the version requirement specified by `req`. But, if there is an active distribution for the project and it does *not* meet the `req` requirement, ``VersionConflict`` is raised. If there is no active distribution for the requested project, ``None`` is returned. """ dist = self.by_key.get(req.key) if dist is not None and dist not in req: # XXX add more info raise VersionConflict(dist, req) return dist
[ "def", "find", "(", "self", ",", "req", ")", ":", "dist", "=", "self", ".", "by_key", ".", "get", "(", "req", ".", "key", ")", "if", "dist", "is", "not", "None", "and", "dist", "not", "in", "req", ":", "# XXX add more info", "raise", "VersionConflict", "(", "dist", ",", "req", ")", "return", "dist" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/pkg_resources/__init__.py#L631-L645
nvdla/sw
79538ba1b52b040a4a4645f630e457fa01839e90
umd/external/protobuf-2.6/python/mox.py
python
In.__init__
(self, key)
Initialize. Args: # key is any thing that could be in a list or a key in a dict
Initialize.
[ "Initialize", "." ]
def __init__(self, key): """Initialize. Args: # key is any thing that could be in a list or a key in a dict """ self._key = key
[ "def", "__init__", "(", "self", ",", "key", ")", ":", "self", ".", "_key", "=", "key" ]
https://github.com/nvdla/sw/blob/79538ba1b52b040a4a4645f630e457fa01839e90/umd/external/protobuf-2.6/python/mox.py#L946-L953
RamadhanAmizudin/malware
2c6c53c8b0d556f5d8078d6ca0fc4448f4697cf1
Fuzzbunch/fuzzbunch/pyreadline/modes/basemode.py
python
BaseMode.backward_delete_char
(self, e)
Delete the character behind the cursor. A numeric argument means to kill the characters instead of deleting them.
Delete the character behind the cursor. A numeric argument means to kill the characters instead of deleting them.
[ "Delete", "the", "character", "behind", "the", "cursor", ".", "A", "numeric", "argument", "means", "to", "kill", "the", "characters", "instead", "of", "deleting", "them", "." ]
def backward_delete_char(self, e): # (Rubout) '''Delete the character behind the cursor. A numeric argument means to kill the characters instead of deleting them.''' self.l_buffer.backward_delete_char(self.argument_reset)
[ "def", "backward_delete_char", "(", "self", ",", "e", ")", ":", "# (Rubout)", "self", ".", "l_buffer", ".", "backward_delete_char", "(", "self", ".", "argument_reset", ")" ]
https://github.com/RamadhanAmizudin/malware/blob/2c6c53c8b0d556f5d8078d6ca0fc4448f4697cf1/Fuzzbunch/fuzzbunch/pyreadline/modes/basemode.py#L353-L356
apache/incubator-mxnet
f03fb23f1d103fec9541b5ae59ee06b1734a51d9
python/mxnet/util.py
python
dtype_from_number
(number)
Get the data type from the given int or float number
Get the data type from the given int or float number
[ "Get", "the", "data", "type", "from", "the", "given", "int", "or", "float", "number" ]
def dtype_from_number(number): """Get the data type from the given int or float number """ assert isinstance(number, numeric_types),\ "The input number should be either int for float types" import numpy as _np if isinstance(number, (int, long)): if number > _MAX_VALUE_64_BIT_UNSIGNED_: raise OverflowError("Integer out of bounds") if number > _MAX_VALUE_64_BIT_SIGNED_: return _np.uint64 elif calcsize("P") == 8: return _np.int64 else: return _np.int32 elif isinstance(number, float): if abs(number) > _MAX_VALUE_FLOAT32_REPRESENT_ or \ ((not _np.isnan(number)) and \ (_np.float32(number) == int(number)) and \ (number != int(number))): return _np.float64 else: return _np.float64 if is_np_default_dtype() else _np.float32 elif isinstance(number, _np.generic): return number.dtype raise TypeError('type {} not supported'.format(str(type(number))))
[ "def", "dtype_from_number", "(", "number", ")", ":", "assert", "isinstance", "(", "number", ",", "numeric_types", ")", ",", "\"The input number should be either int for float types\"", "import", "numpy", "as", "_np", "if", "isinstance", "(", "number", ",", "(", "int", ",", "long", ")", ")", ":", "if", "number", ">", "_MAX_VALUE_64_BIT_UNSIGNED_", ":", "raise", "OverflowError", "(", "\"Integer out of bounds\"", ")", "if", "number", ">", "_MAX_VALUE_64_BIT_SIGNED_", ":", "return", "_np", ".", "uint64", "elif", "calcsize", "(", "\"P\"", ")", "==", "8", ":", "return", "_np", ".", "int64", "else", ":", "return", "_np", ".", "int32", "elif", "isinstance", "(", "number", ",", "float", ")", ":", "if", "abs", "(", "number", ")", ">", "_MAX_VALUE_FLOAT32_REPRESENT_", "or", "(", "(", "not", "_np", ".", "isnan", "(", "number", ")", ")", "and", "(", "_np", ".", "float32", "(", "number", ")", "==", "int", "(", "number", ")", ")", "and", "(", "number", "!=", "int", "(", "number", ")", ")", ")", ":", "return", "_np", ".", "float64", "else", ":", "return", "_np", ".", "float64", "if", "is_np_default_dtype", "(", ")", "else", "_np", ".", "float32", "elif", "isinstance", "(", "number", ",", "_np", ".", "generic", ")", ":", "return", "number", ".", "dtype", "raise", "TypeError", "(", "'type {} not supported'", ".", "format", "(", "str", "(", "type", "(", "number", ")", ")", ")", ")" ]
https://github.com/apache/incubator-mxnet/blob/f03fb23f1d103fec9541b5ae59ee06b1734a51d9/python/mxnet/util.py#L1336-L1361
PaddlePaddle/Paddle
1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c
python/paddle/distributed/auto_parallel/completion.py
python
compute_compatible_dims_mapping
(dims_mapping_list)
return compatible_result
Compute the compatible dims mapping given a list of dims mapping. Each of dims mapping is also a list.
Compute the compatible dims mapping given a list of dims mapping. Each of dims mapping is also a list.
[ "Compute", "the", "compatible", "dims", "mapping", "given", "a", "list", "of", "dims", "mapping", ".", "Each", "of", "dims", "mapping", "is", "also", "a", "list", "." ]
def compute_compatible_dims_mapping(dims_mapping_list): """Compute the compatible dims mapping given a list of dims mapping. Each of dims mapping is also a list. """ if not dims_mapping_list: return None length = len(dims_mapping_list[0]) for dims_mapping in dims_mapping_list: if dims_mapping is None: return None if len(dims_mapping) != length: return None compatible_result = [] for dim_mappings in zip(*dims_mapping_list): compatible_dim_mapping = compute_compatible_dim_mapping( list(dim_mappings)) if compatible_dim_mapping is None: return None compatible_result.append(compatible_dim_mapping) return compatible_result
[ "def", "compute_compatible_dims_mapping", "(", "dims_mapping_list", ")", ":", "if", "not", "dims_mapping_list", ":", "return", "None", "length", "=", "len", "(", "dims_mapping_list", "[", "0", "]", ")", "for", "dims_mapping", "in", "dims_mapping_list", ":", "if", "dims_mapping", "is", "None", ":", "return", "None", "if", "len", "(", "dims_mapping", ")", "!=", "length", ":", "return", "None", "compatible_result", "=", "[", "]", "for", "dim_mappings", "in", "zip", "(", "*", "dims_mapping_list", ")", ":", "compatible_dim_mapping", "=", "compute_compatible_dim_mapping", "(", "list", "(", "dim_mappings", ")", ")", "if", "compatible_dim_mapping", "is", "None", ":", "return", "None", "compatible_result", ".", "append", "(", "compatible_dim_mapping", ")", "return", "compatible_result" ]
https://github.com/PaddlePaddle/Paddle/blob/1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c/python/paddle/distributed/auto_parallel/completion.py#L89-L108
benoitsteiner/tensorflow-opencl
cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5
tensorflow/contrib/training/python/training/sequence_queueing_state_saver.py
python
NextQueuedSequenceBatch.total_length
(self)
return self._state_saver._received_total_length
The lengths of the original (non-truncated) unrolled examples. Returns: An integer vector of length `batch_size`, the total lengths.
The lengths of the original (non-truncated) unrolled examples.
[ "The", "lengths", "of", "the", "original", "(", "non", "-", "truncated", ")", "unrolled", "examples", "." ]
def total_length(self): """The lengths of the original (non-truncated) unrolled examples. Returns: An integer vector of length `batch_size`, the total lengths. """ return self._state_saver._received_total_length
[ "def", "total_length", "(", "self", ")", ":", "return", "self", ".", "_state_saver", ".", "_received_total_length" ]
https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/contrib/training/python/training/sequence_queueing_state_saver.py#L369-L375
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/math_grad.py
python
_ImagGrad
(_, grad)
return math_ops.complex(zero, grad)
Returns 'grad' as the imaginary part and set the real part 0.
Returns 'grad' as the imaginary part and set the real part 0.
[ "Returns", "grad", "as", "the", "imaginary", "part", "and", "set", "the", "real", "part", "0", "." ]
def _ImagGrad(_, grad): """Returns 'grad' as the imaginary part and set the real part 0.""" zero = constant_op.constant(0, dtype=grad.dtype) return math_ops.complex(zero, grad)
[ "def", "_ImagGrad", "(", "_", ",", "grad", ")", ":", "zero", "=", "constant_op", ".", "constant", "(", "0", ",", "dtype", "=", "grad", ".", "dtype", ")", "return", "math_ops", ".", "complex", "(", "zero", ",", "grad", ")" ]
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/math_grad.py#L1760-L1763
tpfister/caffe-heatmap
4db69ef53e6b8a0b3b4ebb29328b0ab3dbf67c4e
scripts/cpp_lint.py
python
CheckForHeaderGuard
(filename, lines, error)
Checks that the file contains a header guard. Logs an error if no #ifndef header guard is present. For other headers, checks that the full pathname is used. Args: filename: The name of the C++ header file. lines: An array of strings, each representing a line of the file. error: The function to call with any errors found.
Checks that the file contains a header guard.
[ "Checks", "that", "the", "file", "contains", "a", "header", "guard", "." ]
def CheckForHeaderGuard(filename, lines, error): """Checks that the file contains a header guard. Logs an error if no #ifndef header guard is present. For other headers, checks that the full pathname is used. Args: filename: The name of the C++ header file. lines: An array of strings, each representing a line of the file. error: The function to call with any errors found. """ cppvar = GetHeaderGuardCPPVariable(filename) ifndef = None ifndef_linenum = 0 define = None endif = None endif_linenum = 0 for linenum, line in enumerate(lines): linesplit = line.split() if len(linesplit) >= 2: # find the first occurrence of #ifndef and #define, save arg if not ifndef and linesplit[0] == '#ifndef': # set ifndef to the header guard presented on the #ifndef line. ifndef = linesplit[1] ifndef_linenum = linenum if not define and linesplit[0] == '#define': define = linesplit[1] # find the last occurrence of #endif, save entire line if line.startswith('#endif'): endif = line endif_linenum = linenum if not ifndef: error(filename, 0, 'build/header_guard', 5, 'No #ifndef header guard found, suggested CPP variable is: %s' % cppvar) return if not define: error(filename, 0, 'build/header_guard', 5, 'No #define header guard found, suggested CPP variable is: %s' % cppvar) return # The guard should be PATH_FILE_H_, but we also allow PATH_FILE_H__ # for backward compatibility. if ifndef != cppvar: error_level = 0 if ifndef != cppvar + '_': error_level = 5 ParseNolintSuppressions(filename, lines[ifndef_linenum], ifndef_linenum, error) error(filename, ifndef_linenum, 'build/header_guard', error_level, '#ifndef header guard has wrong style, please use: %s' % cppvar) if define != ifndef: error(filename, 0, 'build/header_guard', 5, '#ifndef and #define don\'t match, suggested CPP variable is: %s' % cppvar) return if endif != ('#endif // %s' % cppvar): error_level = 0 if endif != ('#endif // %s' % (cppvar + '_')): error_level = 5 ParseNolintSuppressions(filename, lines[endif_linenum], endif_linenum, error) error(filename, endif_linenum, 'build/header_guard', error_level, '#endif line should be "#endif // %s"' % cppvar)
[ "def", "CheckForHeaderGuard", "(", "filename", ",", "lines", ",", "error", ")", ":", "cppvar", "=", "GetHeaderGuardCPPVariable", "(", "filename", ")", "ifndef", "=", "None", "ifndef_linenum", "=", "0", "define", "=", "None", "endif", "=", "None", "endif_linenum", "=", "0", "for", "linenum", ",", "line", "in", "enumerate", "(", "lines", ")", ":", "linesplit", "=", "line", ".", "split", "(", ")", "if", "len", "(", "linesplit", ")", ">=", "2", ":", "# find the first occurrence of #ifndef and #define, save arg", "if", "not", "ifndef", "and", "linesplit", "[", "0", "]", "==", "'#ifndef'", ":", "# set ifndef to the header guard presented on the #ifndef line.", "ifndef", "=", "linesplit", "[", "1", "]", "ifndef_linenum", "=", "linenum", "if", "not", "define", "and", "linesplit", "[", "0", "]", "==", "'#define'", ":", "define", "=", "linesplit", "[", "1", "]", "# find the last occurrence of #endif, save entire line", "if", "line", ".", "startswith", "(", "'#endif'", ")", ":", "endif", "=", "line", "endif_linenum", "=", "linenum", "if", "not", "ifndef", ":", "error", "(", "filename", ",", "0", ",", "'build/header_guard'", ",", "5", ",", "'No #ifndef header guard found, suggested CPP variable is: %s'", "%", "cppvar", ")", "return", "if", "not", "define", ":", "error", "(", "filename", ",", "0", ",", "'build/header_guard'", ",", "5", ",", "'No #define header guard found, suggested CPP variable is: %s'", "%", "cppvar", ")", "return", "# The guard should be PATH_FILE_H_, but we also allow PATH_FILE_H__", "# for backward compatibility.", "if", "ifndef", "!=", "cppvar", ":", "error_level", "=", "0", "if", "ifndef", "!=", "cppvar", "+", "'_'", ":", "error_level", "=", "5", "ParseNolintSuppressions", "(", "filename", ",", "lines", "[", "ifndef_linenum", "]", ",", "ifndef_linenum", ",", "error", ")", "error", "(", "filename", ",", "ifndef_linenum", ",", "'build/header_guard'", ",", "error_level", ",", "'#ifndef header guard has wrong style, please use: %s'", "%", "cppvar", ")", "if", "define", "!=", "ifndef", ":", "error", "(", "filename", ",", "0", ",", "'build/header_guard'", ",", "5", ",", "'#ifndef and #define don\\'t match, suggested CPP variable is: %s'", "%", "cppvar", ")", "return", "if", "endif", "!=", "(", "'#endif // %s'", "%", "cppvar", ")", ":", "error_level", "=", "0", "if", "endif", "!=", "(", "'#endif // %s'", "%", "(", "cppvar", "+", "'_'", ")", ")", ":", "error_level", "=", "5", "ParseNolintSuppressions", "(", "filename", ",", "lines", "[", "endif_linenum", "]", ",", "endif_linenum", ",", "error", ")", "error", "(", "filename", ",", "endif_linenum", ",", "'build/header_guard'", ",", "error_level", ",", "'#endif line should be \"#endif // %s\"'", "%", "cppvar", ")" ]
https://github.com/tpfister/caffe-heatmap/blob/4db69ef53e6b8a0b3b4ebb29328b0ab3dbf67c4e/scripts/cpp_lint.py#L1408-L1480
apple/turicreate
cce55aa5311300e3ce6af93cb45ba791fd1bdf49
deps/src/libxml2-2.9.1/python/libxml2.py
python
xmlNode.lsCountNode
(self)
return ret
Count the children of @node.
Count the children of
[ "Count", "the", "children", "of" ]
def lsCountNode(self): """Count the children of @node. """ ret = libxml2mod.xmlLsCountNode(self._o) return ret
[ "def", "lsCountNode", "(", "self", ")", ":", "ret", "=", "libxml2mod", ".", "xmlLsCountNode", "(", "self", ".", "_o", ")", "return", "ret" ]
https://github.com/apple/turicreate/blob/cce55aa5311300e3ce6af93cb45ba791fd1bdf49/deps/src/libxml2-2.9.1/python/libxml2.py#L3058-L3061
y123456yz/reading-and-annotate-mongodb-3.6
93280293672ca7586dc24af18132aa61e4ed7fcf
mongo/buildscripts/packager.py
python
Spec.metadata_gitspec
(self)
Git revision to use for spec+control+init+manpage files. The default is the release tag for the version being packaged.
Git revision to use for spec+control+init+manpage files. The default is the release tag for the version being packaged.
[ "Git", "revision", "to", "use", "for", "spec", "+", "control", "+", "init", "+", "manpage", "files", ".", "The", "default", "is", "the", "release", "tag", "for", "the", "version", "being", "packaged", "." ]
def metadata_gitspec(self): """Git revision to use for spec+control+init+manpage files. The default is the release tag for the version being packaged.""" if(self.gitspec): return self.gitspec else: return 'r' + self.version()
[ "def", "metadata_gitspec", "(", "self", ")", ":", "if", "(", "self", ".", "gitspec", ")", ":", "return", "self", ".", "gitspec", "else", ":", "return", "'r'", "+", "self", ".", "version", "(", ")" ]
https://github.com/y123456yz/reading-and-annotate-mongodb-3.6/blob/93280293672ca7586dc24af18132aa61e4ed7fcf/mongo/buildscripts/packager.py#L77-L83
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemDefectReporter/v1/AWS/common-code/Lib/setuptools/config.py
python
ConfigMetadataHandler._parse_version
(self, value)
return version
Parses `version` option value. :param value: :rtype: str
Parses `version` option value.
[ "Parses", "version", "option", "value", "." ]
def _parse_version(self, value): """Parses `version` option value. :param value: :rtype: str """ version = self._parse_attr(value) if callable(version): version = version() if not isinstance(version, string_types): if hasattr(version, '__iter__'): version = '.'.join(map(str, version)) else: version = '%s' % version return version
[ "def", "_parse_version", "(", "self", ",", "value", ")", ":", "version", "=", "self", ".", "_parse_attr", "(", "value", ")", "if", "callable", "(", "version", ")", ":", "version", "=", "version", "(", ")", "if", "not", "isinstance", "(", "version", ",", "string_types", ")", ":", "if", "hasattr", "(", "version", ",", "'__iter__'", ")", ":", "version", "=", "'.'", ".", "join", "(", "map", "(", "str", ",", "version", ")", ")", "else", ":", "version", "=", "'%s'", "%", "version", "return", "version" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemDefectReporter/v1/AWS/common-code/Lib/setuptools/config.py#L423-L441
qgis/QGIS
15a77662d4bb712184f6aa60d0bd663010a76a75
python/plugins/MetaSearch/pavement.py
python
package
()
return package_file
create zip file of plugin
create zip file of plugin
[ "create", "zip", "file", "of", "plugin" ]
def package(): """create zip file of plugin""" skip_files = [ 'AUTHORS.txt', 'CMakeLists.txt', 'requirements.txt', 'requirements-dev.txt', 'pavement.txt' ] package_file = get_package_filename() if not os.path.exists(options.base.tmp): options.base.tmp.mkdir() if os.path.exists(package_file): os.unlink(package_file) with zipfile.ZipFile(package_file, 'w', zipfile.ZIP_DEFLATED) as zipf: for root, dirs, files in os.walk(options.base.plugin): for file_add in files: if file_add.endswith('.pyc') or file_add in skip_files: continue filepath = os.path.join(root, file_add) relpath = os.path.join(PLUGIN_NAME, os.path.relpath(filepath)) zipf.write(filepath, relpath) return package_file
[ "def", "package", "(", ")", ":", "skip_files", "=", "[", "'AUTHORS.txt'", ",", "'CMakeLists.txt'", ",", "'requirements.txt'", ",", "'requirements-dev.txt'", ",", "'pavement.txt'", "]", "package_file", "=", "get_package_filename", "(", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "options", ".", "base", ".", "tmp", ")", ":", "options", ".", "base", ".", "tmp", ".", "mkdir", "(", ")", "if", "os", ".", "path", ".", "exists", "(", "package_file", ")", ":", "os", ".", "unlink", "(", "package_file", ")", "with", "zipfile", ".", "ZipFile", "(", "package_file", ",", "'w'", ",", "zipfile", ".", "ZIP_DEFLATED", ")", "as", "zipf", ":", "for", "root", ",", "dirs", ",", "files", "in", "os", ".", "walk", "(", "options", ".", "base", ".", "plugin", ")", ":", "for", "file_add", "in", "files", ":", "if", "file_add", ".", "endswith", "(", "'.pyc'", ")", "or", "file_add", "in", "skip_files", ":", "continue", "filepath", "=", "os", ".", "path", ".", "join", "(", "root", ",", "file_add", ")", "relpath", "=", "os", ".", "path", ".", "join", "(", "PLUGIN_NAME", ",", "os", ".", "path", ".", "relpath", "(", "filepath", ")", ")", "zipf", ".", "write", "(", "filepath", ",", "relpath", ")", "return", "package_file" ]
https://github.com/qgis/QGIS/blob/15a77662d4bb712184f6aa60d0bd663010a76a75/python/plugins/MetaSearch/pavement.py#L103-L128
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/jedi/jedi/api/classes.py
python
defined_names
(evaluator, context)
return [Definition(evaluator, n) for n in _sort_names_by_start_pos(names)]
List sub-definitions (e.g., methods in class). :type scope: Scope :rtype: list of Definition
List sub-definitions (e.g., methods in class).
[ "List", "sub", "-", "definitions", "(", "e", ".", "g", ".", "methods", "in", "class", ")", "." ]
def defined_names(evaluator, context): """ List sub-definitions (e.g., methods in class). :type scope: Scope :rtype: list of Definition """ filter = next(context.get_filters(search_global=True)) names = [name for name in filter.values()] return [Definition(evaluator, n) for n in _sort_names_by_start_pos(names)]
[ "def", "defined_names", "(", "evaluator", ",", "context", ")", ":", "filter", "=", "next", "(", "context", ".", "get_filters", "(", "search_global", "=", "True", ")", ")", "names", "=", "[", "name", "for", "name", "in", "filter", ".", "values", "(", ")", "]", "return", "[", "Definition", "(", "evaluator", ",", "n", ")", "for", "n", "in", "_sort_names_by_start_pos", "(", "names", ")", "]" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/jedi/jedi/api/classes.py#L25-L34
epam/Indigo
30e40b4b1eb9bae0207435a26cfcb81ddcc42be1
api/python/indigo/__init__.py
python
Indigo.writeFile
(self, filename)
return self.IndigoObject( self, self._checkResult( Indigo._lib.indigoWriteFile(filename.encode(ENCODE_ENCODING)) ), )
Creates file writer object Args: filename (str): full path to the file Returns: IndigoObject: file writer object
Creates file writer object
[ "Creates", "file", "writer", "object" ]
def writeFile(self, filename): """Creates file writer object Args: filename (str): full path to the file Returns: IndigoObject: file writer object """ self._setSessionId() return self.IndigoObject( self, self._checkResult( Indigo._lib.indigoWriteFile(filename.encode(ENCODE_ENCODING)) ), )
[ "def", "writeFile", "(", "self", ",", "filename", ")", ":", "self", ".", "_setSessionId", "(", ")", "return", "self", ".", "IndigoObject", "(", "self", ",", "self", ".", "_checkResult", "(", "Indigo", ".", "_lib", ".", "indigoWriteFile", "(", "filename", ".", "encode", "(", "ENCODE_ENCODING", ")", ")", ")", ",", ")" ]
https://github.com/epam/Indigo/blob/30e40b4b1eb9bae0207435a26cfcb81ddcc42be1/api/python/indigo/__init__.py#L5440-L5455
BitMEX/api-connectors
37a3a5b806ad5d0e0fc975ab86d9ed43c3bcd812
auto-generated/python/swagger_client/models/announcement.py
python
Announcement._date
(self)
return self.__date
Gets the _date of this Announcement. # noqa: E501 :return: The _date of this Announcement. # noqa: E501 :rtype: datetime
Gets the _date of this Announcement. # noqa: E501
[ "Gets", "the", "_date", "of", "this", "Announcement", ".", "#", "noqa", ":", "E501" ]
def _date(self): """Gets the _date of this Announcement. # noqa: E501 :return: The _date of this Announcement. # noqa: E501 :rtype: datetime """ return self.__date
[ "def", "_date", "(", "self", ")", ":", "return", "self", ".", "__date" ]
https://github.com/BitMEX/api-connectors/blob/37a3a5b806ad5d0e0fc975ab86d9ed43c3bcd812/auto-generated/python/swagger_client/models/announcement.py#L156-L163
regomne/chinesize
2ae555445046cd28d60a514e30ac1d6eca1c442a
N2System/nsbparser/nsbParser.py
python
NsbParser.p9b
(self)
case
case
[ "case" ]
def p9b(self): 'case' self.text.append('\t'*self.tabcount+'case '+self.readarg()) self.readarg() self.readarg()
[ "def", "p9b", "(", "self", ")", ":", "self", ".", "text", ".", "append", "(", "'\\t'", "*", "self", ".", "tabcount", "+", "'case '", "+", "self", ".", "readarg", "(", ")", ")", "self", ".", "readarg", "(", ")", "self", ".", "readarg", "(", ")" ]
https://github.com/regomne/chinesize/blob/2ae555445046cd28d60a514e30ac1d6eca1c442a/N2System/nsbparser/nsbParser.py#L100-L104
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/layers/python/layers/rev_block_lib.py
python
RevBlock._forward
(self, x1, x2)
Run forward through the reversible layers.
Run forward through the reversible layers.
[ "Run", "forward", "through", "the", "reversible", "layers", "." ]
def _forward(self, x1, x2): """Run forward through the reversible layers.""" side_inputs = [self.f_side_input, self.g_side_input] flat_side_inputs = nest.flatten(side_inputs) def _forward_wrap(x1_, x2_, *flat_side_inputs): f_side, g_side = nest.pack_sequence_as(side_inputs, flat_side_inputs) return _rev_block_forward( x1_, x2_, self.f, self.g, num_layers=self.num_layers, f_side_input=f_side, g_side_input=g_side, gate_outputs=self._use_efficient_backprop) @custom_gradient.custom_gradient def _forward_with_custom_grad(*args): out = _forward_wrap(*args) # pylint: disable=no-value-for-parameter grad_fn = self._make_efficient_grad_fn(args, out) return out, grad_fn if self._use_efficient_backprop: return _forward_with_custom_grad(x1, x2, *flat_side_inputs) else: return _forward_wrap(x1, x2, *flat_side_inputs)
[ "def", "_forward", "(", "self", ",", "x1", ",", "x2", ")", ":", "side_inputs", "=", "[", "self", ".", "f_side_input", ",", "self", ".", "g_side_input", "]", "flat_side_inputs", "=", "nest", ".", "flatten", "(", "side_inputs", ")", "def", "_forward_wrap", "(", "x1_", ",", "x2_", ",", "*", "flat_side_inputs", ")", ":", "f_side", ",", "g_side", "=", "nest", ".", "pack_sequence_as", "(", "side_inputs", ",", "flat_side_inputs", ")", "return", "_rev_block_forward", "(", "x1_", ",", "x2_", ",", "self", ".", "f", ",", "self", ".", "g", ",", "num_layers", "=", "self", ".", "num_layers", ",", "f_side_input", "=", "f_side", ",", "g_side_input", "=", "g_side", ",", "gate_outputs", "=", "self", ".", "_use_efficient_backprop", ")", "@", "custom_gradient", ".", "custom_gradient", "def", "_forward_with_custom_grad", "(", "*", "args", ")", ":", "out", "=", "_forward_wrap", "(", "*", "args", ")", "# pylint: disable=no-value-for-parameter", "grad_fn", "=", "self", ".", "_make_efficient_grad_fn", "(", "args", ",", "out", ")", "return", "out", ",", "grad_fn", "if", "self", ".", "_use_efficient_backprop", ":", "return", "_forward_with_custom_grad", "(", "x1", ",", "x2", ",", "*", "flat_side_inputs", ")", "else", ":", "return", "_forward_wrap", "(", "x1", ",", "x2", ",", "*", "flat_side_inputs", ")" ]
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/layers/python/layers/rev_block_lib.py#L335-L362
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/pip/_vendor/urllib3/poolmanager.py
python
PoolManager.connection_from_context
(self, request_context)
return self.connection_from_pool_key(pool_key, request_context=request_context)
Get a :class:`urllib3.connectionpool.ConnectionPool` based on the request context. ``request_context`` must at least contain the ``scheme`` key and its value must be a key in ``key_fn_by_scheme`` instance variable.
[]
def connection_from_context(self, request_context): """ Get a :class:`urllib3.connectionpool.ConnectionPool` based on the request context. ``request_context`` must at least contain the ``scheme`` key and its value must be a key in ``key_fn_by_scheme`` instance variable. """ scheme = request_context["scheme"].lower() pool_key_constructor = self.key_fn_by_scheme.get(scheme) if not pool_key_constructor: raise URLSchemeUnknown(scheme) pool_key = pool_key_constructor(request_context) return self.connection_from_pool_key(pool_key, request_context=request_context)
[ "def", "connection_from_context", "(", "self", ",", "request_context", ")", ":", "scheme", "=", "request_context", "[", "\"scheme\"", "]", ".", "lower", "(", ")", "pool_key_constructor", "=", "self", ".", "key_fn_by_scheme", ".", "get", "(", "scheme", ")", "if", "not", "pool_key_constructor", ":", "raise", "URLSchemeUnknown", "(", "scheme", ")", "pool_key", "=", "pool_key_constructor", "(", "request_context", ")", "return", "self", ".", "connection_from_pool_key", "(", "pool_key", ",", "request_context", "=", "request_context", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/pip/_vendor/urllib3/poolmanager.py#L493-L519
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/tools/XRCed/presenter.py
python
_Presenter.deleteMany
(self, items)
Delete selected object(s).
Delete selected object(s).
[ "Delete", "selected", "object", "(", "s", ")", "." ]
def deleteMany(self, items): '''Delete selected object(s).''' for item in items: if not item.IsOk(): continue # child already deleted parentItem = view.tree.GetItemParent(item) parentNode = view.tree.GetPyData(parentItem) node = view.tree.GetPyData(item) node = self.container.removeChild(parentNode, node) node.unlink() # delete completely view.tree.Delete(item) self.setApplied() self.unselect() self.setModified()
[ "def", "deleteMany", "(", "self", ",", "items", ")", ":", "for", "item", "in", "items", ":", "if", "not", "item", ".", "IsOk", "(", ")", ":", "continue", "# child already deleted", "parentItem", "=", "view", ".", "tree", ".", "GetItemParent", "(", "item", ")", "parentNode", "=", "view", ".", "tree", ".", "GetPyData", "(", "parentItem", ")", "node", "=", "view", ".", "tree", ".", "GetPyData", "(", "item", ")", "node", "=", "self", ".", "container", ".", "removeChild", "(", "parentNode", ",", "node", ")", "node", ".", "unlink", "(", ")", "# delete completely", "view", ".", "tree", ".", "Delete", "(", "item", ")", "self", ".", "setApplied", "(", ")", "self", ".", "unselect", "(", ")", "self", ".", "setModified", "(", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/XRCed/presenter.py#L399-L411
BlzFans/wke
b0fa21158312e40c5fbd84682d643022b6c34a93
cygwin/lib/python2.6/logging/__init__.py
python
Filterer.removeFilter
(self, filter)
Remove the specified filter from this handler.
Remove the specified filter from this handler.
[ "Remove", "the", "specified", "filter", "from", "this", "handler", "." ]
def removeFilter(self, filter): """ Remove the specified filter from this handler. """ if filter in self.filters: self.filters.remove(filter)
[ "def", "removeFilter", "(", "self", ",", "filter", ")", ":", "if", "filter", "in", "self", ".", "filters", ":", "self", ".", "filters", ".", "remove", "(", "filter", ")" ]
https://github.com/BlzFans/wke/blob/b0fa21158312e40c5fbd84682d643022b6c34a93/cygwin/lib/python2.6/logging/__init__.py#L553-L558
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/_controls.py
python
PreTreebook
(*args, **kwargs)
return val
PreTreebook() -> Treebook
PreTreebook() -> Treebook
[ "PreTreebook", "()", "-", ">", "Treebook" ]
def PreTreebook(*args, **kwargs): """PreTreebook() -> Treebook""" val = _controls_.new_PreTreebook(*args, **kwargs) return val
[ "def", "PreTreebook", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "val", "=", "_controls_", ".", "new_PreTreebook", "(", "*", "args", ",", "*", "*", "kwargs", ")", "return", "val" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_controls.py#L3346-L3349
gem5/gem5
141cc37c2d4b93959d4c249b8f7e6a8b2ef75338
ext/ply/example/BASIC/basparse.py
python
p_expr_variable
(p)
expr : variable
expr : variable
[ "expr", ":", "variable" ]
def p_expr_variable(p): '''expr : variable''' p[0] = ('VAR',p[1])
[ "def", "p_expr_variable", "(", "p", ")", ":", "p", "[", "0", "]", "=", "(", "'VAR'", ",", "p", "[", "1", "]", ")" ]
https://github.com/gem5/gem5/blob/141cc37c2d4b93959d4c249b8f7e6a8b2ef75338/ext/ply/example/BASIC/basparse.py#L296-L298
manutdzou/KITTI_SSD
5b620c2f291d36a0fe14489214f22a992f173f44
scripts/cpp_lint.py
python
CheckComment
(comment, filename, linenum, error)
Checks for common mistakes in TODO comments. Args: comment: The text of the comment from the line in question. filename: The name of the current file. linenum: The number of the line to check. error: The function to call with any errors found.
Checks for common mistakes in TODO comments.
[ "Checks", "for", "common", "mistakes", "in", "TODO", "comments", "." ]
def CheckComment(comment, filename, linenum, error): """Checks for common mistakes in TODO comments. Args: comment: The text of the comment from the line in question. filename: The name of the current file. linenum: The number of the line to check. error: The function to call with any errors found. """ match = _RE_PATTERN_TODO.match(comment) if match: # One whitespace is correct; zero whitespace is handled elsewhere. leading_whitespace = match.group(1) if len(leading_whitespace) > 1: error(filename, linenum, 'whitespace/todo', 2, 'Too many spaces before TODO') username = match.group(2) if not username: error(filename, linenum, 'readability/todo', 2, 'Missing username in TODO; it should look like ' '"// TODO(my_username): Stuff."') middle_whitespace = match.group(3) # Comparisons made explicit for correctness -- pylint: disable=g-explicit-bool-comparison if middle_whitespace != ' ' and middle_whitespace != '': error(filename, linenum, 'whitespace/todo', 2, 'TODO(my_username) should be followed by a space')
[ "def", "CheckComment", "(", "comment", ",", "filename", ",", "linenum", ",", "error", ")", ":", "match", "=", "_RE_PATTERN_TODO", ".", "match", "(", "comment", ")", "if", "match", ":", "# One whitespace is correct; zero whitespace is handled elsewhere.", "leading_whitespace", "=", "match", ".", "group", "(", "1", ")", "if", "len", "(", "leading_whitespace", ")", ">", "1", ":", "error", "(", "filename", ",", "linenum", ",", "'whitespace/todo'", ",", "2", ",", "'Too many spaces before TODO'", ")", "username", "=", "match", ".", "group", "(", "2", ")", "if", "not", "username", ":", "error", "(", "filename", ",", "linenum", ",", "'readability/todo'", ",", "2", ",", "'Missing username in TODO; it should look like '", "'\"// TODO(my_username): Stuff.\"'", ")", "middle_whitespace", "=", "match", ".", "group", "(", "3", ")", "# Comparisons made explicit for correctness -- pylint: disable=g-explicit-bool-comparison", "if", "middle_whitespace", "!=", "' '", "and", "middle_whitespace", "!=", "''", ":", "error", "(", "filename", ",", "linenum", ",", "'whitespace/todo'", ",", "2", ",", "'TODO(my_username) should be followed by a space'", ")" ]
https://github.com/manutdzou/KITTI_SSD/blob/5b620c2f291d36a0fe14489214f22a992f173f44/scripts/cpp_lint.py#L2461-L2488
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/_core.py
python
Window.FindWindowByName
(*args, **kwargs)
return _core_.Window_FindWindowByName(*args, **kwargs)
FindWindowByName(self, String name) -> Window Find a child of this window by name
FindWindowByName(self, String name) -> Window
[ "FindWindowByName", "(", "self", "String", "name", ")", "-", ">", "Window" ]
def FindWindowByName(*args, **kwargs): """ FindWindowByName(self, String name) -> Window Find a child of this window by name """ return _core_.Window_FindWindowByName(*args, **kwargs)
[ "def", "FindWindowByName", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_core_", ".", "Window_FindWindowByName", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_core.py#L10339-L10345
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
base/android/jni_generator/jni_generator.py
python
InlHeaderFileGenerator.GetParamsInDeclaration
(self, native)
return ',\n '.join(self.GetJNIFirstParam(native, True) + [JavaDataTypeToCForDeclaration(param.datatype) + ' ' + param.name for param in native.params])
Returns the params for the forward declaration. Args: native: the native dictionary describing the method. Returns: A string containing the params.
Returns the params for the forward declaration.
[ "Returns", "the", "params", "for", "the", "forward", "declaration", "." ]
def GetParamsInDeclaration(self, native): """Returns the params for the forward declaration. Args: native: the native dictionary describing the method. Returns: A string containing the params. """ return ',\n '.join(self.GetJNIFirstParam(native, True) + [JavaDataTypeToCForDeclaration(param.datatype) + ' ' + param.name for param in native.params])
[ "def", "GetParamsInDeclaration", "(", "self", ",", "native", ")", ":", "return", "',\\n '", ".", "join", "(", "self", ".", "GetJNIFirstParam", "(", "native", ",", "True", ")", "+", "[", "JavaDataTypeToCForDeclaration", "(", "param", ".", "datatype", ")", "+", "' '", "+", "param", ".", "name", "for", "param", "in", "native", ".", "params", "]", ")" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/base/android/jni_generator/jni_generator.py#L911-L923
benoitsteiner/tensorflow-opencl
cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5
tensorflow/python/feature_column/feature_column.py
python
_DenseColumn._variable_shape
(self)
`TensorShape` of `_get_dense_tensor`, without batch dimension.
`TensorShape` of `_get_dense_tensor`, without batch dimension.
[ "TensorShape", "of", "_get_dense_tensor", "without", "batch", "dimension", "." ]
def _variable_shape(self): """`TensorShape` of `_get_dense_tensor`, without batch dimension.""" pass
[ "def", "_variable_shape", "(", "self", ")", ":", "pass" ]
https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/python/feature_column/feature_column.py#L1372-L1374
eclipse/sumo
7132a9b8b6eea734bdec38479026b4d8c4336d03
tools/traci/_polygon.py
python
PolygonDomain.getLineWidth
(self, polygonID)
return self._getUniversal(tc.VAR_WIDTH, polygonID)
getLineWidth(string) -> double Returns drawing width of unfilled polygon
getLineWidth(string) -> double Returns drawing width of unfilled polygon
[ "getLineWidth", "(", "string", ")", "-", ">", "double", "Returns", "drawing", "width", "of", "unfilled", "polygon" ]
def getLineWidth(self, polygonID): """getLineWidth(string) -> double Returns drawing width of unfilled polygon """ return self._getUniversal(tc.VAR_WIDTH, polygonID)
[ "def", "getLineWidth", "(", "self", ",", "polygonID", ")", ":", "return", "self", ".", "_getUniversal", "(", "tc", ".", "VAR_WIDTH", ",", "polygonID", ")" ]
https://github.com/eclipse/sumo/blob/7132a9b8b6eea734bdec38479026b4d8c4336d03/tools/traci/_polygon.py#L60-L64
mindspore-ai/mindspore
fb8fd3338605bb34fa5cea054e535a8b1d753fab
mindspore/python/mindspore/ops/_op_impl/tbe/gelu_ds.py
python
_gelu_ds_tbe
()
return
GeLU TBE register
GeLU TBE register
[ "GeLU", "TBE", "register" ]
def _gelu_ds_tbe(): """GeLU TBE register""" return
[ "def", "_gelu_ds_tbe", "(", ")", ":", "return" ]
https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/ops/_op_impl/tbe/gelu_ds.py#L36-L38
google/mysql-protobuf
467cda676afaa49e762c5c9164a43f6ad31a1fbf
protobuf/python/google/protobuf/internal/python_message.py
python
_IsPresent
(item)
Given a (FieldDescriptor, value) tuple from _fields, return true if the value should be included in the list returned by ListFields().
Given a (FieldDescriptor, value) tuple from _fields, return true if the value should be included in the list returned by ListFields().
[ "Given", "a", "(", "FieldDescriptor", "value", ")", "tuple", "from", "_fields", "return", "true", "if", "the", "value", "should", "be", "included", "in", "the", "list", "returned", "by", "ListFields", "()", "." ]
def _IsPresent(item): """Given a (FieldDescriptor, value) tuple from _fields, return true if the value should be included in the list returned by ListFields().""" if item[0].label == _FieldDescriptor.LABEL_REPEATED: return bool(item[1]) elif item[0].cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE: return item[1]._is_present_in_parent else: return True
[ "def", "_IsPresent", "(", "item", ")", ":", "if", "item", "[", "0", "]", ".", "label", "==", "_FieldDescriptor", ".", "LABEL_REPEATED", ":", "return", "bool", "(", "item", "[", "1", "]", ")", "elif", "item", "[", "0", "]", ".", "cpp_type", "==", "_FieldDescriptor", ".", "CPPTYPE_MESSAGE", ":", "return", "item", "[", "1", "]", ".", "_is_present_in_parent", "else", ":", "return", "True" ]
https://github.com/google/mysql-protobuf/blob/467cda676afaa49e762c5c9164a43f6ad31a1fbf/protobuf/python/google/protobuf/internal/python_message.py#L717-L726