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
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python3/src/Lib/datetime.py
python
_days_in_month
(year, month)
return _DAYS_IN_MONTH[month]
year, month -> number of days in that month in that year.
year, month -> number of days in that month in that year.
[ "year", "month", "-", ">", "number", "of", "days", "in", "that", "month", "in", "that", "year", "." ]
def _days_in_month(year, month): "year, month -> number of days in that month in that year." assert 1 <= month <= 12, month if month == 2 and _is_leap(year): return 29 return _DAYS_IN_MONTH[month]
[ "def", "_days_in_month", "(", "year", ",", "month", ")", ":", "assert", "1", "<=", "month", "<=", "12", ",", "month", "if", "month", "==", "2", "and", "_is_leap", "(", "year", ")", ":", "return", "29", "return", "_DAYS_IN_MONTH", "[", "month", "]" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/datetime.py#L50-L55
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/ftplib.py
python
FTP.connect
(self, host='', port=0, timeout=-999, source_address=None)
return self.welcome
Connect to host. Arguments are: - host: hostname to connect to (string, default previous host) - port: port to connect to (integer, default previous port) - timeout: the timeout to set against the ftp socket(s) - source_address: a 2-tuple (host, port) for the socket to bind to as its source address before connecting.
Connect to host. Arguments are: - host: hostname to connect to (string, default previous host) - port: port to connect to (integer, default previous port) - timeout: the timeout to set against the ftp socket(s) - source_address: a 2-tuple (host, port) for the socket to bind to as its source address before connecting.
[ "Connect", "to", "host", ".", "Arguments", "are", ":", "-", "host", ":", "hostname", "to", "connect", "to", "(", "string", "default", "previous", "host", ")", "-", "port", ":", "port", "to", "connect", "to", "(", "integer", "default", "previous", "port", ")", "-", "timeout", ":", "the", "timeout", "to", "set", "against", "the", "ftp", "socket", "(", "s", ")", "-", "source_address", ":", "a", "2", "-", "tuple", "(", "host", "port", ")", "for", "the", "socket", "to", "bind", "to", "as", "its", "source", "address", "before", "connecting", "." ]
def connect(self, host='', port=0, timeout=-999, source_address=None): '''Connect to host. Arguments are: - host: hostname to connect to (string, default previous host) - port: port to connect to (integer, default previous port) - timeout: the timeout to set against the ftp socket(s) - source_address: a 2-tuple (host, port) for the socket to bind to as its source address before connecting. ''' if host != '': self.host = host if port > 0: self.port = port if timeout != -999: self.timeout = timeout if source_address is not None: self.source_address = source_address self.sock = socket.create_connection((self.host, self.port), self.timeout, source_address=self.source_address) self.af = self.sock.family self.file = self.sock.makefile('r', encoding=self.encoding) self.welcome = self.getresp() return self.welcome
[ "def", "connect", "(", "self", ",", "host", "=", "''", ",", "port", "=", "0", ",", "timeout", "=", "-", "999", ",", "source_address", "=", "None", ")", ":", "if", "host", "!=", "''", ":", "self", ".", "host", "=", "host", "if", "port", ">", "0", ":", "self", ".", "port", "=", "port", "if", "timeout", "!=", "-", "999", ":", "self", ".", "timeout", "=", "timeout", "if", "source_address", "is", "not", "None", ":", "self", ".", "source_address", "=", "source_address", "self", ".", "sock", "=", "socket", ".", "create_connection", "(", "(", "self", ".", "host", ",", "self", ".", "port", ")", ",", "self", ".", "timeout", ",", "source_address", "=", "self", ".", "source_address", ")", "self", ".", "af", "=", "self", ".", "sock", ".", "family", "self", ".", "file", "=", "self", ".", "sock", ".", "makefile", "(", "'r'", ",", "encoding", "=", "self", ".", "encoding", ")", "self", ".", "welcome", "=", "self", ".", "getresp", "(", ")", "return", "self", ".", "welcome" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/ftplib.py#L135-L156
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/tracemalloc.py
python
get_object_traceback
(obj)
Get the traceback where the Python object *obj* was allocated. Return a Traceback instance. Return None if the tracemalloc module is not tracing memory allocations or did not trace the allocation of the object.
Get the traceback where the Python object *obj* was allocated. Return a Traceback instance.
[ "Get", "the", "traceback", "where", "the", "Python", "object", "*", "obj", "*", "was", "allocated", ".", "Return", "a", "Traceback", "instance", "." ]
def get_object_traceback(obj): """ Get the traceback where the Python object *obj* was allocated. Return a Traceback instance. Return None if the tracemalloc module is not tracing memory allocations or did not trace the allocation of the object. """ frames = _get_object_traceback(obj) if frames is not None: return Traceback(frames) else: return None
[ "def", "get_object_traceback", "(", "obj", ")", ":", "frames", "=", "_get_object_traceback", "(", "obj", ")", "if", "frames", "is", "not", "None", ":", "return", "Traceback", "(", "frames", ")", "else", ":", "return", "None" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/tracemalloc.py#L235-L247
ApolloAuto/apollo-platform
86d9dc6743b496ead18d597748ebabd34a513289
ros/third_party/lib_x86_64/python2.7/dist-packages/catkin_pkg/package_templates.py
python
_safe_write_files
(newfiles, target_dir)
writes file contents to target_dir/filepath for all entries of newfiles. Aborts early if files exist in places for new files or directories :param newfiles: a dict {filepath: contents} :param target_dir: a string
writes file contents to target_dir/filepath for all entries of newfiles. Aborts early if files exist in places for new files or directories
[ "writes", "file", "contents", "to", "target_dir", "/", "filepath", "for", "all", "entries", "of", "newfiles", ".", "Aborts", "early", "if", "files", "exist", "in", "places", "for", "new", "files", "or", "directories" ]
def _safe_write_files(newfiles, target_dir): """ writes file contents to target_dir/filepath for all entries of newfiles. Aborts early if files exist in places for new files or directories :param newfiles: a dict {filepath: contents} :param target_dir: a string """ # first check no filename conflict exists for filename in newfiles: target_file = os.path.join(target_dir, filename) if os.path.exists(target_file): raise ValueError('File exists: %s' % target_file) dirname = os.path.dirname(target_file) while(dirname != target_dir): if os.path.isfile(dirname): raise ValueError('Cannot create directory, file exists: %s' % dirname) dirname = os.path.dirname(dirname) for filename, content in newfiles.items(): target_file = os.path.join(target_dir, filename) dirname = os.path.dirname(target_file) if not os.path.exists(dirname): os.makedirs(dirname) # print(target_file, content) with open(target_file, 'ab') as fhand: fhand.write(content.encode()) print('Created file %s' % os.path.relpath(target_file, os.path.dirname(target_dir)))
[ "def", "_safe_write_files", "(", "newfiles", ",", "target_dir", ")", ":", "# first check no filename conflict exists", "for", "filename", "in", "newfiles", ":", "target_file", "=", "os", ".", "path", ".", "join", "(", "target_dir", ",", "filename", ")", "if", "os", ".", "path", ".", "exists", "(", "target_file", ")", ":", "raise", "ValueError", "(", "'File exists: %s'", "%", "target_file", ")", "dirname", "=", "os", ".", "path", ".", "dirname", "(", "target_file", ")", "while", "(", "dirname", "!=", "target_dir", ")", ":", "if", "os", ".", "path", ".", "isfile", "(", "dirname", ")", ":", "raise", "ValueError", "(", "'Cannot create directory, file exists: %s'", "%", "dirname", ")", "dirname", "=", "os", ".", "path", ".", "dirname", "(", "dirname", ")", "for", "filename", ",", "content", "in", "newfiles", ".", "items", "(", ")", ":", "target_file", "=", "os", ".", "path", ".", "join", "(", "target_dir", ",", "filename", ")", "dirname", "=", "os", ".", "path", ".", "dirname", "(", "target_file", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "dirname", ")", ":", "os", ".", "makedirs", "(", "dirname", ")", "# print(target_file, content)", "with", "open", "(", "target_file", ",", "'ab'", ")", "as", "fhand", ":", "fhand", ".", "write", "(", "content", ".", "encode", "(", ")", ")", "print", "(", "'Created file %s'", "%", "os", ".", "path", ".", "relpath", "(", "target_file", ",", "os", ".", "path", ".", "dirname", "(", "target_dir", ")", ")", ")" ]
https://github.com/ApolloAuto/apollo-platform/blob/86d9dc6743b496ead18d597748ebabd34a513289/ros/third_party/lib_x86_64/python2.7/dist-packages/catkin_pkg/package_templates.py#L163-L191
tensorflow/tensorflow
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
tensorflow/python/client/timeline.py
python
Timeline._emit_tensor_snapshot
(self, tensor, timestamp, pid, tid, value)
Generate Chrome Trace snapshot event for a computed Tensor. Args: tensor: A 'TensorTracker' object. timestamp: The timestamp of this snapshot as a long integer. pid: The pid assigned for showing the device where this op ran. tid: The tid of the thread computing the tensor snapshot. value: A JSON-compliant snapshot of the object.
Generate Chrome Trace snapshot event for a computed Tensor.
[ "Generate", "Chrome", "Trace", "snapshot", "event", "for", "a", "computed", "Tensor", "." ]
def _emit_tensor_snapshot(self, tensor, timestamp, pid, tid, value): """Generate Chrome Trace snapshot event for a computed Tensor. Args: tensor: A 'TensorTracker' object. timestamp: The timestamp of this snapshot as a long integer. pid: The pid assigned for showing the device where this op ran. tid: The tid of the thread computing the tensor snapshot. value: A JSON-compliant snapshot of the object. """ desc = str(value.tensor_description).replace('"', '') snapshot = {'tensor_description': desc} self._chrome_trace.emit_obj_snapshot('Tensor', tensor.name, timestamp, pid, tid, tensor.object_id, snapshot)
[ "def", "_emit_tensor_snapshot", "(", "self", ",", "tensor", ",", "timestamp", ",", "pid", ",", "tid", ",", "value", ")", ":", "desc", "=", "str", "(", "value", ".", "tensor_description", ")", ".", "replace", "(", "'\"'", ",", "''", ")", "snapshot", "=", "{", "'tensor_description'", ":", "desc", "}", "self", ".", "_chrome_trace", ".", "emit_obj_snapshot", "(", "'Tensor'", ",", "tensor", ".", "name", ",", "timestamp", ",", "pid", ",", "tid", ",", "tensor", ".", "object_id", ",", "snapshot", ")" ]
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/client/timeline.py#L454-L467
kamyu104/LeetCode-Solutions
77605708a927ea3b85aee5a479db733938c7c211
Python/number-of-ships-in-a-rectangle.py
python
Solution.countShips
(self, sea, topRight, bottomLeft)
return result
:type sea: Sea :type topRight: Point :type bottomLeft: Point :rtype: integer
:type sea: Sea :type topRight: Point :type bottomLeft: Point :rtype: integer
[ ":", "type", "sea", ":", "Sea", ":", "type", "topRight", ":", "Point", ":", "type", "bottomLeft", ":", "Point", ":", "rtype", ":", "integer" ]
def countShips(self, sea, topRight, bottomLeft): """ :type sea: Sea :type topRight: Point :type bottomLeft: Point :rtype: integer """ result = 0 if topRight.x >= bottomLeft.x and \ topRight.y >= bottomLeft.y and \ sea.hasShips(topRight, bottomLeft): if (topRight.x, topRight.y) == (bottomLeft.x, bottomLeft.y): return 1 mid_x, mid_y = (topRight.x+bottomLeft.x)//2, (topRight.y+bottomLeft.y)//2 result += self.countShips(sea, topRight, Point(mid_x+1, mid_y+1)) result += self.countShips(sea, Point(mid_x, topRight.y), Point(bottomLeft.x, mid_y+1)) result += self.countShips(sea, Point(topRight.x, mid_y), Point(mid_x+1, bottomLeft.y)) result += self.countShips(sea, Point(mid_x, mid_y), bottomLeft) return result
[ "def", "countShips", "(", "self", ",", "sea", ",", "topRight", ",", "bottomLeft", ")", ":", "result", "=", "0", "if", "topRight", ".", "x", ">=", "bottomLeft", ".", "x", "and", "topRight", ".", "y", ">=", "bottomLeft", ".", "y", "and", "sea", ".", "hasShips", "(", "topRight", ",", "bottomLeft", ")", ":", "if", "(", "topRight", ".", "x", ",", "topRight", ".", "y", ")", "==", "(", "bottomLeft", ".", "x", ",", "bottomLeft", ".", "y", ")", ":", "return", "1", "mid_x", ",", "mid_y", "=", "(", "topRight", ".", "x", "+", "bottomLeft", ".", "x", ")", "//", "2", ",", "(", "topRight", ".", "y", "+", "bottomLeft", ".", "y", ")", "//", "2", "result", "+=", "self", ".", "countShips", "(", "sea", ",", "topRight", ",", "Point", "(", "mid_x", "+", "1", ",", "mid_y", "+", "1", ")", ")", "result", "+=", "self", ".", "countShips", "(", "sea", ",", "Point", "(", "mid_x", ",", "topRight", ".", "y", ")", ",", "Point", "(", "bottomLeft", ".", "x", ",", "mid_y", "+", "1", ")", ")", "result", "+=", "self", ".", "countShips", "(", "sea", ",", "Point", "(", "topRight", ".", "x", ",", "mid_y", ")", ",", "Point", "(", "mid_x", "+", "1", ",", "bottomLeft", ".", "y", ")", ")", "result", "+=", "self", ".", "countShips", "(", "sea", ",", "Point", "(", "mid_x", ",", "mid_y", ")", ",", "bottomLeft", ")", "return", "result" ]
https://github.com/kamyu104/LeetCode-Solutions/blob/77605708a927ea3b85aee5a479db733938c7c211/Python/number-of-ships-in-a-rectangle.py#L23-L41
ChromiumWebApps/chromium
c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7
tools/telemetry/telemetry/core/bitmap.py
python
Bitmap.ColorHistogram
(self, ignore_color=None, tolerance=0)
return self._PrepareTools().Histogram(ignore_color, tolerance)
Computes a histogram of the pixel colors in this Bitmap. Args: ignore_color: An RgbaColor to exclude from the bucket counts. tolerance: A tolerance for the ignore_color. Returns: A ColorHistogram namedtuple with 256 integers in each field: r, g, and b.
Computes a histogram of the pixel colors in this Bitmap. Args: ignore_color: An RgbaColor to exclude from the bucket counts. tolerance: A tolerance for the ignore_color.
[ "Computes", "a", "histogram", "of", "the", "pixel", "colors", "in", "this", "Bitmap", ".", "Args", ":", "ignore_color", ":", "An", "RgbaColor", "to", "exclude", "from", "the", "bucket", "counts", ".", "tolerance", ":", "A", "tolerance", "for", "the", "ignore_color", "." ]
def ColorHistogram(self, ignore_color=None, tolerance=0): """Computes a histogram of the pixel colors in this Bitmap. Args: ignore_color: An RgbaColor to exclude from the bucket counts. tolerance: A tolerance for the ignore_color. Returns: A ColorHistogram namedtuple with 256 integers in each field: r, g, and b. """ return self._PrepareTools().Histogram(ignore_color, tolerance)
[ "def", "ColorHistogram", "(", "self", ",", "ignore_color", "=", "None", ",", "tolerance", "=", "0", ")", ":", "return", "self", ".", "_PrepareTools", "(", ")", ".", "Histogram", "(", "ignore_color", ",", "tolerance", ")" ]
https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/tools/telemetry/telemetry/core/bitmap.py#L340-L349
giuspen/cherrytree
84712f206478fcf9acf30174009ad28c648c6344
pygtk2/modules/machines.py
python
XMLHandler.dom_to_treestore
(self, ctd, discard_ids, tree_father=None)
Parse an XML Cherry Tree Document file and build the Tree
Parse an XML Cherry Tree Document file and build the Tree
[ "Parse", "an", "XML", "Cherry", "Tree", "Document", "file", "and", "build", "the", "Tree" ]
def dom_to_treestore(self, ctd, discard_ids, tree_father=None): """Parse an XML Cherry Tree Document file and build the Tree""" dom = xml.dom.minidom.parseString(ctd) cherrytree = dom.firstChild if cherrytree.nodeName != cons.APP_NAME: return False else: dom_iter = cherrytree.firstChild node_sequence = self.dad.nodes_sequences_get_max_siblings(tree_father) next_id_box = [self.dad.node_id_get()] while dom_iter!= None: if dom_iter.nodeName == "node": node_sequence += 1 self.append_tree_node(dom_iter, tree_father, discard_ids, node_sequence, next_id_box) elif dom_iter.nodeName == "bookmarks": if dom_iter.attributes['list'].value: self.dad.bookmarks = dom_iter.attributes['list'].value.split(",") dom_iter = dom_iter.nextSibling return True
[ "def", "dom_to_treestore", "(", "self", ",", "ctd", ",", "discard_ids", ",", "tree_father", "=", "None", ")", ":", "dom", "=", "xml", ".", "dom", ".", "minidom", ".", "parseString", "(", "ctd", ")", "cherrytree", "=", "dom", ".", "firstChild", "if", "cherrytree", ".", "nodeName", "!=", "cons", ".", "APP_NAME", ":", "return", "False", "else", ":", "dom_iter", "=", "cherrytree", ".", "firstChild", "node_sequence", "=", "self", ".", "dad", ".", "nodes_sequences_get_max_siblings", "(", "tree_father", ")", "next_id_box", "=", "[", "self", ".", "dad", ".", "node_id_get", "(", ")", "]", "while", "dom_iter", "!=", "None", ":", "if", "dom_iter", ".", "nodeName", "==", "\"node\"", ":", "node_sequence", "+=", "1", "self", ".", "append_tree_node", "(", "dom_iter", ",", "tree_father", ",", "discard_ids", ",", "node_sequence", ",", "next_id_box", ")", "elif", "dom_iter", ".", "nodeName", "==", "\"bookmarks\"", ":", "if", "dom_iter", ".", "attributes", "[", "'list'", "]", ".", "value", ":", "self", ".", "dad", ".", "bookmarks", "=", "dom_iter", ".", "attributes", "[", "'list'", "]", ".", "value", ".", "split", "(", "\",\"", ")", "dom_iter", "=", "dom_iter", ".", "nextSibling", "return", "True" ]
https://github.com/giuspen/cherrytree/blob/84712f206478fcf9acf30174009ad28c648c6344/pygtk2/modules/machines.py#L102-L119
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/lib/agw/thumbnailctrl.py
python
ScrolledThumbnail.GetThumbInfo
(self, thumb=-1)
return thumbinfo
Returns the thumbnail information. :param `thumb`: the index of the thumbnail for which we are collecting information.
Returns the thumbnail information.
[ "Returns", "the", "thumbnail", "information", "." ]
def GetThumbInfo(self, thumb=-1): """ Returns the thumbnail information. :param `thumb`: the index of the thumbnail for which we are collecting information. """ thumbinfo = None if thumb >= 0: thumbinfo = "Name: " + self._items[thumb].GetFileName() + "\n" \ "Size: " + self._items[thumb].GetFileSize() + "\n" \ "Modified: " + self._items[thumb].GetCreationDate() + "\n" \ "Dimensions: " + str(self._items[thumb].GetOriginalSize()) + "\n" \ "Thumb: " + str(self.GetThumbSize()[0:2]) return thumbinfo
[ "def", "GetThumbInfo", "(", "self", ",", "thumb", "=", "-", "1", ")", ":", "thumbinfo", "=", "None", "if", "thumb", ">=", "0", ":", "thumbinfo", "=", "\"Name: \"", "+", "self", ".", "_items", "[", "thumb", "]", ".", "GetFileName", "(", ")", "+", "\"\\n\"", "\"Size: \"", "+", "self", ".", "_items", "[", "thumb", "]", ".", "GetFileSize", "(", ")", "+", "\"\\n\"", "\"Modified: \"", "+", "self", ".", "_items", "[", "thumb", "]", ".", "GetCreationDate", "(", ")", "+", "\"\\n\"", "\"Dimensions: \"", "+", "str", "(", "self", ".", "_items", "[", "thumb", "]", ".", "GetOriginalSize", "(", ")", ")", "+", "\"\\n\"", "\"Thumb: \"", "+", "str", "(", "self", ".", "GetThumbSize", "(", ")", "[", "0", ":", "2", "]", ")", "return", "thumbinfo" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/thumbnailctrl.py#L1418-L1434
tensorflow/tensorflow
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
tensorflow/python/training/saver.py
python
BaseSaverBuilder.bulk_restore
(self, filename_tensor, saveables, preferred_shard, restore_sequentially)
return all_tensors
Restore all tensors contained in saveables. By default, this issues separate calls to `restore_op` for each saveable. Subclasses may override to load multiple saveables in a single call. Args: filename_tensor: String Tensor. saveables: List of BaseSaverBuilder.SaveableObject objects. preferred_shard: Int. Shard to open first when loading a sharded file. restore_sequentially: Unused. Bool. If true, each restore is sequential. Returns: A list of Tensors resulting from reading 'saveable' from 'filename'.
Restore all tensors contained in saveables.
[ "Restore", "all", "tensors", "contained", "in", "saveables", "." ]
def bulk_restore(self, filename_tensor, saveables, preferred_shard, restore_sequentially): """Restore all tensors contained in saveables. By default, this issues separate calls to `restore_op` for each saveable. Subclasses may override to load multiple saveables in a single call. Args: filename_tensor: String Tensor. saveables: List of BaseSaverBuilder.SaveableObject objects. preferred_shard: Int. Shard to open first when loading a sharded file. restore_sequentially: Unused. Bool. If true, each restore is sequential. Returns: A list of Tensors resulting from reading 'saveable' from 'filename'. """ del restore_sequentially all_tensors = [] for saveable in saveables: if saveable.device: device = saveable_object_util.set_cpu0(saveable.device) else: device = None with ops.device(device): all_tensors.extend( self.restore_op(filename_tensor, saveable, preferred_shard)) return all_tensors
[ "def", "bulk_restore", "(", "self", ",", "filename_tensor", ",", "saveables", ",", "preferred_shard", ",", "restore_sequentially", ")", ":", "del", "restore_sequentially", "all_tensors", "=", "[", "]", "for", "saveable", "in", "saveables", ":", "if", "saveable", ".", "device", ":", "device", "=", "saveable_object_util", ".", "set_cpu0", "(", "saveable", ".", "device", ")", "else", ":", "device", "=", "None", "with", "ops", ".", "device", "(", "device", ")", ":", "all_tensors", ".", "extend", "(", "self", ".", "restore_op", "(", "filename_tensor", ",", "saveable", ",", "preferred_shard", ")", ")", "return", "all_tensors" ]
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/training/saver.py#L153-L181
Polidea/SiriusObfuscator
b0e590d8130e97856afe578869b83a209e2b19be
SymbolExtractorAndRenamer/lldb/scripts/Python/static-binding/lldb.py
python
SBTarget.AttachToProcessWithID
(self, *args)
return _lldb.SBTarget_AttachToProcessWithID(self, *args)
AttachToProcessWithID(self, SBListener listener, pid_t pid, SBError error) -> SBProcess Attach to process with pid. @param[in] listener An optional listener that will receive all process events. If listener is valid then listener will listen to all process events. If not valid, then this target's debugger (SBTarget::GetDebugger()) will listen to all process events. @param[in] pid The process ID to attach to. @param[out] An error explaining what went wrong if attach fails. @return A process object for the attached process.
AttachToProcessWithID(self, SBListener listener, pid_t pid, SBError error) -> SBProcess
[ "AttachToProcessWithID", "(", "self", "SBListener", "listener", "pid_t", "pid", "SBError", "error", ")", "-", ">", "SBProcess" ]
def AttachToProcessWithID(self, *args): """ AttachToProcessWithID(self, SBListener listener, pid_t pid, SBError error) -> SBProcess Attach to process with pid. @param[in] listener An optional listener that will receive all process events. If listener is valid then listener will listen to all process events. If not valid, then this target's debugger (SBTarget::GetDebugger()) will listen to all process events. @param[in] pid The process ID to attach to. @param[out] An error explaining what went wrong if attach fails. @return A process object for the attached process. """ return _lldb.SBTarget_AttachToProcessWithID(self, *args)
[ "def", "AttachToProcessWithID", "(", "self", ",", "*", "args", ")", ":", "return", "_lldb", ".", "SBTarget_AttachToProcessWithID", "(", "self", ",", "*", "args", ")" ]
https://github.com/Polidea/SiriusObfuscator/blob/b0e590d8130e97856afe578869b83a209e2b19be/SymbolExtractorAndRenamer/lldb/scripts/Python/static-binding/lldb.py#L8770-L8791
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/setuptools/py2/setuptools/_vendor/ordered_set.py
python
OrderedSet.index
(self, key)
return self.map[key]
Get the index of a given entry, raising an IndexError if it's not present. `key` can be an iterable of entries that is not a string, in which case this returns a list of indices. Example: >>> oset = OrderedSet([1, 2, 3]) >>> oset.index(2) 1
Get the index of a given entry, raising an IndexError if it's not present.
[ "Get", "the", "index", "of", "a", "given", "entry", "raising", "an", "IndexError", "if", "it", "s", "not", "present", "." ]
def index(self, key): """ Get the index of a given entry, raising an IndexError if it's not present. `key` can be an iterable of entries that is not a string, in which case this returns a list of indices. Example: >>> oset = OrderedSet([1, 2, 3]) >>> oset.index(2) 1 """ if is_iterable(key): return [self.index(subkey) for subkey in key] return self.map[key]
[ "def", "index", "(", "self", ",", "key", ")", ":", "if", "is_iterable", "(", "key", ")", ":", "return", "[", "self", ".", "index", "(", "subkey", ")", "for", "subkey", "in", "key", "]", "return", "self", ".", "map", "[", "key", "]" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/setuptools/py2/setuptools/_vendor/ordered_set.py#L188-L203
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/ipython/py3/IPython/paths.py
python
get_ipython_module_path
(module_str)
return py3compat.cast_unicode(the_path, fs_encoding)
Find the path to an IPython module in this version of IPython. This will always find the version of the module that is in this importable IPython package. This will always return the path to the ``.py`` version of the module.
Find the path to an IPython module in this version of IPython.
[ "Find", "the", "path", "to", "an", "IPython", "module", "in", "this", "version", "of", "IPython", "." ]
def get_ipython_module_path(module_str): """Find the path to an IPython module in this version of IPython. This will always find the version of the module that is in this importable IPython package. This will always return the path to the ``.py`` version of the module. """ if module_str == 'IPython': return os.path.join(get_ipython_package_dir(), '__init__.py') mod = import_item(module_str) the_path = mod.__file__.replace('.pyc', '.py') the_path = the_path.replace('.pyo', '.py') return py3compat.cast_unicode(the_path, fs_encoding)
[ "def", "get_ipython_module_path", "(", "module_str", ")", ":", "if", "module_str", "==", "'IPython'", ":", "return", "os", ".", "path", ".", "join", "(", "get_ipython_package_dir", "(", ")", ",", "'__init__.py'", ")", "mod", "=", "import_item", "(", "module_str", ")", "the_path", "=", "mod", ".", "__file__", ".", "replace", "(", "'.pyc'", ",", "'.py'", ")", "the_path", "=", "the_path", ".", "replace", "(", "'.pyo'", ",", "'.py'", ")", "return", "py3compat", ".", "cast_unicode", "(", "the_path", ",", "fs_encoding", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/ipython/py3/IPython/paths.py#L96-L108
mongodb/mongo
d8ff665343ad29cf286ee2cf4a1960d29371937b
buildscripts/libdeps/libdeps/analyzer.py
python
GraphPaths.report
(self, report)
Add the path list to the report.
Add the path list to the report.
[ "Add", "the", "path", "list", "to", "the", "report", "." ]
def report(self, report): """Add the path list to the report.""" if DependsReportTypes.GRAPH_PATHS.name not in report: report[DependsReportTypes.GRAPH_PATHS.name] = {} report[DependsReportTypes.GRAPH_PATHS.name][tuple([self._from_node, self._to_node])] = self.run()
[ "def", "report", "(", "self", ",", "report", ")", ":", "if", "DependsReportTypes", ".", "GRAPH_PATHS", ".", "name", "not", "in", "report", ":", "report", "[", "DependsReportTypes", ".", "GRAPH_PATHS", ".", "name", "]", "=", "{", "}", "report", "[", "DependsReportTypes", ".", "GRAPH_PATHS", ".", "name", "]", "[", "tuple", "(", "[", "self", ".", "_from_node", ",", "self", ".", "_to_node", "]", ")", "]", "=", "self", ".", "run", "(", ")" ]
https://github.com/mongodb/mongo/blob/d8ff665343ad29cf286ee2cf4a1960d29371937b/buildscripts/libdeps/libdeps/analyzer.py#L523-L529
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/collections/__init__.py
python
Counter.__pos__
(self)
return result
Adds an empty counter, effectively stripping negative and zero counts
Adds an empty counter, effectively stripping negative and zero counts
[ "Adds", "an", "empty", "counter", "effectively", "stripping", "negative", "and", "zero", "counts" ]
def __pos__(self): 'Adds an empty counter, effectively stripping negative and zero counts' result = Counter() for elem, count in self.items(): if count > 0: result[elem] = count return result
[ "def", "__pos__", "(", "self", ")", ":", "result", "=", "Counter", "(", ")", "for", "elem", ",", "count", "in", "self", ".", "items", "(", ")", ":", "if", "count", ">", "0", ":", "result", "[", "elem", "]", "=", "count", "return", "result" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/collections/__init__.py#L799-L805
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/dataview.py
python
DataViewVirtualListModel.GetItem
(*args, **kwargs)
return _dataview.DataViewVirtualListModel_GetItem(*args, **kwargs)
GetItem(self, unsigned int row) -> DataViewItem Returns the DataViewItem for the item at row.
GetItem(self, unsigned int row) -> DataViewItem
[ "GetItem", "(", "self", "unsigned", "int", "row", ")", "-", ">", "DataViewItem" ]
def GetItem(*args, **kwargs): """ GetItem(self, unsigned int row) -> DataViewItem Returns the DataViewItem for the item at row. """ return _dataview.DataViewVirtualListModel_GetItem(*args, **kwargs)
[ "def", "GetItem", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_dataview", ".", "DataViewVirtualListModel_GetItem", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/dataview.py#L1072-L1078
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/x86/toolchain/lib/python2.7/ast.py
python
parse
(source, filename='<unknown>', mode='exec')
return compile(source, filename, mode, PyCF_ONLY_AST)
Parse the source into an AST node. Equivalent to compile(source, filename, mode, PyCF_ONLY_AST).
Parse the source into an AST node. Equivalent to compile(source, filename, mode, PyCF_ONLY_AST).
[ "Parse", "the", "source", "into", "an", "AST", "node", ".", "Equivalent", "to", "compile", "(", "source", "filename", "mode", "PyCF_ONLY_AST", ")", "." ]
def parse(source, filename='<unknown>', mode='exec'): """ Parse the source into an AST node. Equivalent to compile(source, filename, mode, PyCF_ONLY_AST). """ return compile(source, filename, mode, PyCF_ONLY_AST)
[ "def", "parse", "(", "source", ",", "filename", "=", "'<unknown>'", ",", "mode", "=", "'exec'", ")", ":", "return", "compile", "(", "source", ",", "filename", ",", "mode", ",", "PyCF_ONLY_AST", ")" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/ast.py#L32-L37
nsnam/ns-3-dev-git
efdb2e21f45c0a87a60b47c547b68fa140a7b686
waf-tools/misc.py
python
apply_cmd
(self)
call a command every time
call a command every time
[ "call", "a", "command", "every", "time" ]
def apply_cmd(self): "call a command every time" if not self.fun: raise Errors.WafError('cmdobj needs a function!') tsk = Task.TaskBase() tsk.fun = self.fun tsk.env = self.env self.tasks.append(tsk) tsk.install_path = self.install_path
[ "def", "apply_cmd", "(", "self", ")", ":", "if", "not", "self", ".", "fun", ":", "raise", "Errors", ".", "WafError", "(", "'cmdobj needs a function!'", ")", "tsk", "=", "Task", ".", "TaskBase", "(", ")", "tsk", ".", "fun", "=", "self", ".", "fun", "tsk", ".", "env", "=", "self", ".", "env", "self", ".", "tasks", ".", "append", "(", "tsk", ")", "tsk", ".", "install_path", "=", "self", ".", "install_path" ]
https://github.com/nsnam/ns-3-dev-git/blob/efdb2e21f45c0a87a60b47c547b68fa140a7b686/waf-tools/misc.py#L47-L54
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/_windows.py
python
SashEvent.SetDragStatus
(*args, **kwargs)
return _windows_.SashEvent_SetDragStatus(*args, **kwargs)
SetDragStatus(self, int status)
SetDragStatus(self, int status)
[ "SetDragStatus", "(", "self", "int", "status", ")" ]
def SetDragStatus(*args, **kwargs): """SetDragStatus(self, int status)""" return _windows_.SashEvent_SetDragStatus(*args, **kwargs)
[ "def", "SetDragStatus", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_windows_", ".", "SashEvent_SetDragStatus", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_windows.py#L1918-L1920
facebookincubator/BOLT
88c70afe9d388ad430cc150cc158641701397f70
lldb/examples/python/gdbremote.py
python
TerminalColors.default
(self, fg=True)
return ''
Set the foreground or background color to the default. The foreground color will be set if "fg" tests True. The background color will be set if "fg" tests False.
Set the foreground or background color to the default. The foreground color will be set if "fg" tests True. The background color will be set if "fg" tests False.
[ "Set", "the", "foreground", "or", "background", "color", "to", "the", "default", ".", "The", "foreground", "color", "will", "be", "set", "if", "fg", "tests", "True", ".", "The", "background", "color", "will", "be", "set", "if", "fg", "tests", "False", "." ]
def default(self, fg=True): '''Set the foreground or background color to the default. The foreground color will be set if "fg" tests True. The background color will be set if "fg" tests False.''' if self.enabled: if fg: return "\x1b[39m" else: return "\x1b[49m" return ''
[ "def", "default", "(", "self", ",", "fg", "=", "True", ")", ":", "if", "self", ".", "enabled", ":", "if", "fg", ":", "return", "\"\\x1b[39m\"", "else", ":", "return", "\"\\x1b[49m\"", "return", "''" ]
https://github.com/facebookincubator/BOLT/blob/88c70afe9d388ad430cc150cc158641701397f70/lldb/examples/python/gdbremote.py#L181-L189
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/grid.py
python
Grid.GetColLabelSize
(*args, **kwargs)
return _grid.Grid_GetColLabelSize(*args, **kwargs)
GetColLabelSize(self) -> int
GetColLabelSize(self) -> int
[ "GetColLabelSize", "(", "self", ")", "-", ">", "int" ]
def GetColLabelSize(*args, **kwargs): """GetColLabelSize(self) -> int""" return _grid.Grid_GetColLabelSize(*args, **kwargs)
[ "def", "GetColLabelSize", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_grid", ".", "Grid_GetColLabelSize", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/grid.py#L1482-L1484
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python3/src/Lib/telnetlib.py
python
Telnet.close
(self)
Close the connection.
Close the connection.
[ "Close", "the", "connection", "." ]
def close(self): """Close the connection.""" sock = self.sock self.sock = None self.eof = True self.iacseq = b'' self.sb = 0 if sock: sock.close()
[ "def", "close", "(", "self", ")", ":", "sock", "=", "self", ".", "sock", "self", ".", "sock", "=", "None", "self", ".", "eof", "=", "True", "self", ".", "iacseq", "=", "b''", "self", ".", "sb", "=", "0", "if", "sock", ":", "sock", ".", "close", "(", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/telnetlib.py#L263-L271
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/windows/Lib/pickletools.py
python
read_int4
(f)
r""" >>> import io >>> read_int4(io.BytesIO(b'\xff\x00\x00\x00')) 255 >>> read_int4(io.BytesIO(b'\x00\x00\x00\x80')) == -(2**31) True
r""" >>> import io >>> read_int4(io.BytesIO(b'\xff\x00\x00\x00')) 255 >>> read_int4(io.BytesIO(b'\x00\x00\x00\x80')) == -(2**31) True
[ "r", ">>>", "import", "io", ">>>", "read_int4", "(", "io", ".", "BytesIO", "(", "b", "\\", "xff", "\\", "x00", "\\", "x00", "\\", "x00", "))", "255", ">>>", "read_int4", "(", "io", ".", "BytesIO", "(", "b", "\\", "x00", "\\", "x00", "\\", "x00", "\\", "x80", "))", "==", "-", "(", "2", "**", "31", ")", "True" ]
def read_int4(f): r""" >>> import io >>> read_int4(io.BytesIO(b'\xff\x00\x00\x00')) 255 >>> read_int4(io.BytesIO(b'\x00\x00\x00\x80')) == -(2**31) True """ data = f.read(4) if len(data) == 4: return _unpack("<i", data)[0] raise ValueError("not enough data in stream to read int4")
[ "def", "read_int4", "(", "f", ")", ":", "data", "=", "f", ".", "read", "(", "4", ")", "if", "len", "(", "data", ")", "==", "4", ":", "return", "_unpack", "(", "\"<i\"", ",", "data", ")", "[", "0", "]", "raise", "ValueError", "(", "\"not enough data in stream to read int4\"", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/pickletools.py#L252-L264
rrwick/Porechop
109e437280436d1ec27e5a5b7a34ffb752176390
ez_setup.py
python
main
()
return _install(archive, _build_install_args(options))
Install or upgrade setuptools and EasyInstall.
Install or upgrade setuptools and EasyInstall.
[ "Install", "or", "upgrade", "setuptools", "and", "EasyInstall", "." ]
def main(): """Install or upgrade setuptools and EasyInstall.""" options = _parse_args() archive = download_setuptools(**_download_args(options)) return _install(archive, _build_install_args(options))
[ "def", "main", "(", ")", ":", "options", "=", "_parse_args", "(", ")", "archive", "=", "download_setuptools", "(", "*", "*", "_download_args", "(", "options", ")", ")", "return", "_install", "(", "archive", ",", "_build_install_args", "(", "options", ")", ")" ]
https://github.com/rrwick/Porechop/blob/109e437280436d1ec27e5a5b7a34ffb752176390/ez_setup.py#L407-L411
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/multiprocessing/pool.py
python
Pool._maintain_pool
(self)
Clean up any exited workers and start replacements for them.
Clean up any exited workers and start replacements for them.
[ "Clean", "up", "any", "exited", "workers", "and", "start", "replacements", "for", "them", "." ]
def _maintain_pool(self): """Clean up any exited workers and start replacements for them. """ if self._join_exited_workers(): self._repopulate_pool()
[ "def", "_maintain_pool", "(", "self", ")", ":", "if", "self", ".", "_join_exited_workers", "(", ")", ":", "self", ".", "_repopulate_pool", "(", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/multiprocessing/pool.py#L244-L248
mysql/mysql-workbench
2f35f9034f015cbcd22139a60e1baa2e3e8e795c
modules/db.sql92/db_sql92_re_grt.py
python
Sql92ReverseEngineering.reverseEngineerTablePK
(cls, connection, table)
return 0
Reverse engineers the primary key(s) for the given table.
Reverse engineers the primary key(s) for the given table.
[ "Reverse", "engineers", "the", "primary", "key", "(", "s", ")", "for", "the", "given", "table", "." ]
def reverseEngineerTablePK(cls, connection, table): """Reverse engineers the primary key(s) for the given table.""" schema = table.owner catalog = schema.owner query = """SELECT tc.CONSTRAINT_NAME, kcu.COLUMN_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS AS tc JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE AS kcu ON kcu.CONSTRAINT_SCHEMA = tc.CONSTRAINT_SCHEMA AND kcu.CONSTRAINT_NAME = tc.CONSTRAINT_NAME AND kcu.TABLE_SCHEMA = tc.TABLE_SCHEMA AND kcu.TABLE_NAME = tc.TABLE_NAME WHERE tc.CONSTRAINT_TYPE='PRIMARY KEY' AND tc.TABLE_CATALOG = '%s' AND tc.TABLE_SCHEMA = '%s' AND tc.TABLE_NAME = '%s' ORDER BY tc.CONSTRAINT_NAME, kcu.ORDINAL_POSITION""" % (catalog.name, schema.name, table.name) if len(table.columns) == 0: # Table must have columns reverse engineered before we can rev eng its primary key(s) grt.send_error('%s reverseEngineerTablePK: Reverse engineer of table %s was attempted but the table has ' 'no columns attribute' % (cls.getTargetDBMSName(), table.name)) return 1 fk_rows = cls.execute_query(connection, query).fetchall() if fk_rows: index = grt.classes.db_Index() index.name = fk_rows[0][0] index.isPrimary = 1 index.unique = 1 index.indexType = 'PRIMARY' for _, pk_col in fk_rows: table_column = find_object_with_name(table.columns, pk_col) if not table_column: grt.send_warning('%s reverseEngineerTablePK: Could not find column "%s" in table "%s" referenced ' 'by primary key constraint "%s". The primary key will not be added.' % (cls.getTargetDBMSName(), pk_col, table.name, index.name) ) return 0 index_column = grt.classes.db_IndexColumn() index_column.name = index.name + '.' + pk_col index_column.referencedColumn = table_column index.columns.append(index_column) table.primaryKey = index table.addIndex(index) return 0
[ "def", "reverseEngineerTablePK", "(", "cls", ",", "connection", ",", "table", ")", ":", "schema", "=", "table", ".", "owner", "catalog", "=", "schema", ".", "owner", "query", "=", "\"\"\"SELECT tc.CONSTRAINT_NAME, kcu.COLUMN_NAME\n FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS AS tc\n JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE AS kcu\n ON kcu.CONSTRAINT_SCHEMA = tc.CONSTRAINT_SCHEMA\n AND kcu.CONSTRAINT_NAME = tc.CONSTRAINT_NAME\n AND kcu.TABLE_SCHEMA = tc.TABLE_SCHEMA\n AND kcu.TABLE_NAME = tc.TABLE_NAME\n WHERE tc.CONSTRAINT_TYPE='PRIMARY KEY' AND tc.TABLE_CATALOG = '%s' AND tc.TABLE_SCHEMA = '%s' AND tc.TABLE_NAME = '%s'\n ORDER BY tc.CONSTRAINT_NAME, kcu.ORDINAL_POSITION\"\"\"", "%", "(", "catalog", ".", "name", ",", "schema", ".", "name", ",", "table", ".", "name", ")", "if", "len", "(", "table", ".", "columns", ")", "==", "0", ":", "# Table must have columns reverse engineered before we can rev eng its primary key(s)", "grt", ".", "send_error", "(", "'%s reverseEngineerTablePK: Reverse engineer of table %s was attempted but the table has '", "'no columns attribute'", "%", "(", "cls", ".", "getTargetDBMSName", "(", ")", ",", "table", ".", "name", ")", ")", "return", "1", "fk_rows", "=", "cls", ".", "execute_query", "(", "connection", ",", "query", ")", ".", "fetchall", "(", ")", "if", "fk_rows", ":", "index", "=", "grt", ".", "classes", ".", "db_Index", "(", ")", "index", ".", "name", "=", "fk_rows", "[", "0", "]", "[", "0", "]", "index", ".", "isPrimary", "=", "1", "index", ".", "unique", "=", "1", "index", ".", "indexType", "=", "'PRIMARY'", "for", "_", ",", "pk_col", "in", "fk_rows", ":", "table_column", "=", "find_object_with_name", "(", "table", ".", "columns", ",", "pk_col", ")", "if", "not", "table_column", ":", "grt", ".", "send_warning", "(", "'%s reverseEngineerTablePK: Could not find column \"%s\" in table \"%s\" referenced '", "'by primary key constraint \"%s\". The primary key will not be added.'", "%", "(", "cls", ".", "getTargetDBMSName", "(", ")", ",", "pk_col", ",", "table", ".", "name", ",", "index", ".", "name", ")", ")", "return", "0", "index_column", "=", "grt", ".", "classes", ".", "db_IndexColumn", "(", ")", "index_column", ".", "name", "=", "index", ".", "name", "+", "'.'", "+", "pk_col", "index_column", ".", "referencedColumn", "=", "table_column", "index", ".", "columns", ".", "append", "(", "index_column", ")", "table", ".", "primaryKey", "=", "index", "table", ".", "addIndex", "(", "index", ")", "return", "0" ]
https://github.com/mysql/mysql-workbench/blob/2f35f9034f015cbcd22139a60e1baa2e3e8e795c/modules/db.sql92/db_sql92_re_grt.py#L169-L213
rbgirshick/caffe-fast-rcnn
28a579eaf0668850705598b3075b8969f22226d9
scripts/cpp_lint.py
python
CheckForNonStandardConstructs
(filename, clean_lines, linenum, nesting_state, error)
r"""Logs an error if we see certain non-ANSI constructs ignored by gcc-2. Complain about several constructs which gcc-2 accepts, but which are not standard C++. Warning about these in lint is one way to ease the transition to new compilers. - put storage class first (e.g. "static const" instead of "const static"). - "%lld" instead of %qd" in printf-type functions. - "%1$d" is non-standard in printf-type functions. - "\%" is an undefined character escape sequence. - text after #endif is not allowed. - invalid inner-style forward declaration. - >? and <? operators, and their >?= and <?= cousins. Additionally, check for constructor/destructor style violations and reference members, as it is very convenient to do so while checking for gcc-2 compliance. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. nesting_state: A _NestingState instance which maintains information about the current stack of nested blocks being parsed. error: A callable to which errors are reported, which takes 4 arguments: filename, line number, error level, and message
r"""Logs an error if we see certain non-ANSI constructs ignored by gcc-2.
[ "r", "Logs", "an", "error", "if", "we", "see", "certain", "non", "-", "ANSI", "constructs", "ignored", "by", "gcc", "-", "2", "." ]
def CheckForNonStandardConstructs(filename, clean_lines, linenum, nesting_state, error): r"""Logs an error if we see certain non-ANSI constructs ignored by gcc-2. Complain about several constructs which gcc-2 accepts, but which are not standard C++. Warning about these in lint is one way to ease the transition to new compilers. - put storage class first (e.g. "static const" instead of "const static"). - "%lld" instead of %qd" in printf-type functions. - "%1$d" is non-standard in printf-type functions. - "\%" is an undefined character escape sequence. - text after #endif is not allowed. - invalid inner-style forward declaration. - >? and <? operators, and their >?= and <?= cousins. Additionally, check for constructor/destructor style violations and reference members, as it is very convenient to do so while checking for gcc-2 compliance. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. nesting_state: A _NestingState instance which maintains information about the current stack of nested blocks being parsed. error: A callable to which errors are reported, which takes 4 arguments: filename, line number, error level, and message """ # Remove comments from the line, but leave in strings for now. line = clean_lines.lines[linenum] if Search(r'printf\s*\(.*".*%[-+ ]?\d*q', line): error(filename, linenum, 'runtime/printf_format', 3, '%q in format strings is deprecated. Use %ll instead.') if Search(r'printf\s*\(.*".*%\d+\$', line): error(filename, linenum, 'runtime/printf_format', 2, '%N$ formats are unconventional. Try rewriting to avoid them.') # Remove escaped backslashes before looking for undefined escapes. line = line.replace('\\\\', '') if Search(r'("|\').*\\(%|\[|\(|{)', line): error(filename, linenum, 'build/printf_format', 3, '%, [, (, and { are undefined character escapes. Unescape them.') # For the rest, work with both comments and strings removed. line = clean_lines.elided[linenum] if Search(r'\b(const|volatile|void|char|short|int|long' r'|float|double|signed|unsigned' r'|schar|u?int8|u?int16|u?int32|u?int64)' r'\s+(register|static|extern|typedef)\b', line): error(filename, linenum, 'build/storage_class', 5, 'Storage class (static, extern, typedef, etc) should be first.') if Match(r'\s*#\s*endif\s*[^/\s]+', line): error(filename, linenum, 'build/endif_comment', 5, 'Uncommented text after #endif is non-standard. Use a comment.') if Match(r'\s*class\s+(\w+\s*::\s*)+\w+\s*;', line): error(filename, linenum, 'build/forward_decl', 5, 'Inner-style forward declarations are invalid. Remove this line.') if Search(r'(\w+|[+-]?\d+(\.\d*)?)\s*(<|>)\?=?\s*(\w+|[+-]?\d+)(\.\d*)?', line): error(filename, linenum, 'build/deprecated', 3, '>? and <? (max and min) operators are non-standard and deprecated.') if Search(r'^\s*const\s*string\s*&\s*\w+\s*;', line): # TODO(unknown): Could it be expanded safely to arbitrary references, # without triggering too many false positives? The first # attempt triggered 5 warnings for mostly benign code in the regtest, hence # the restriction. # Here's the original regexp, for the reference: # type_name = r'\w+((\s*::\s*\w+)|(\s*<\s*\w+?\s*>))?' # r'\s*const\s*' + type_name + '\s*&\s*\w+\s*;' error(filename, linenum, 'runtime/member_string_references', 2, 'const string& members are dangerous. It is much better to use ' 'alternatives, such as pointers or simple constants.') # Everything else in this function operates on class declarations. # Return early if the top of the nesting stack is not a class, or if # the class head is not completed yet. classinfo = nesting_state.InnermostClass() if not classinfo or not classinfo.seen_open_brace: return # The class may have been declared with namespace or classname qualifiers. # The constructor and destructor will not have those qualifiers. base_classname = classinfo.name.split('::')[-1] # Look for single-argument constructors that aren't marked explicit. # Technically a valid construct, but against style. args = Match(r'\s+(?:inline\s+)?%s\s*\(([^,()]+)\)' % re.escape(base_classname), line) if (args and args.group(1) != 'void' and not Match(r'(const\s+)?%s(\s+const)?\s*(?:<\w+>\s*)?&' % re.escape(base_classname), args.group(1).strip())): error(filename, linenum, 'runtime/explicit', 5, 'Single-argument constructors should be marked explicit.')
[ "def", "CheckForNonStandardConstructs", "(", "filename", ",", "clean_lines", ",", "linenum", ",", "nesting_state", ",", "error", ")", ":", "# Remove comments from the line, but leave in strings for now.", "line", "=", "clean_lines", ".", "lines", "[", "linenum", "]", "if", "Search", "(", "r'printf\\s*\\(.*\".*%[-+ ]?\\d*q'", ",", "line", ")", ":", "error", "(", "filename", ",", "linenum", ",", "'runtime/printf_format'", ",", "3", ",", "'%q in format strings is deprecated. Use %ll instead.'", ")", "if", "Search", "(", "r'printf\\s*\\(.*\".*%\\d+\\$'", ",", "line", ")", ":", "error", "(", "filename", ",", "linenum", ",", "'runtime/printf_format'", ",", "2", ",", "'%N$ formats are unconventional. Try rewriting to avoid them.'", ")", "# Remove escaped backslashes before looking for undefined escapes.", "line", "=", "line", ".", "replace", "(", "'\\\\\\\\'", ",", "''", ")", "if", "Search", "(", "r'(\"|\\').*\\\\(%|\\[|\\(|{)'", ",", "line", ")", ":", "error", "(", "filename", ",", "linenum", ",", "'build/printf_format'", ",", "3", ",", "'%, [, (, and { are undefined character escapes. Unescape them.'", ")", "# For the rest, work with both comments and strings removed.", "line", "=", "clean_lines", ".", "elided", "[", "linenum", "]", "if", "Search", "(", "r'\\b(const|volatile|void|char|short|int|long'", "r'|float|double|signed|unsigned'", "r'|schar|u?int8|u?int16|u?int32|u?int64)'", "r'\\s+(register|static|extern|typedef)\\b'", ",", "line", ")", ":", "error", "(", "filename", ",", "linenum", ",", "'build/storage_class'", ",", "5", ",", "'Storage class (static, extern, typedef, etc) should be first.'", ")", "if", "Match", "(", "r'\\s*#\\s*endif\\s*[^/\\s]+'", ",", "line", ")", ":", "error", "(", "filename", ",", "linenum", ",", "'build/endif_comment'", ",", "5", ",", "'Uncommented text after #endif is non-standard. Use a comment.'", ")", "if", "Match", "(", "r'\\s*class\\s+(\\w+\\s*::\\s*)+\\w+\\s*;'", ",", "line", ")", ":", "error", "(", "filename", ",", "linenum", ",", "'build/forward_decl'", ",", "5", ",", "'Inner-style forward declarations are invalid. Remove this line.'", ")", "if", "Search", "(", "r'(\\w+|[+-]?\\d+(\\.\\d*)?)\\s*(<|>)\\?=?\\s*(\\w+|[+-]?\\d+)(\\.\\d*)?'", ",", "line", ")", ":", "error", "(", "filename", ",", "linenum", ",", "'build/deprecated'", ",", "3", ",", "'>? and <? (max and min) operators are non-standard and deprecated.'", ")", "if", "Search", "(", "r'^\\s*const\\s*string\\s*&\\s*\\w+\\s*;'", ",", "line", ")", ":", "# TODO(unknown): Could it be expanded safely to arbitrary references,", "# without triggering too many false positives? The first", "# attempt triggered 5 warnings for mostly benign code in the regtest, hence", "# the restriction.", "# Here's the original regexp, for the reference:", "# type_name = r'\\w+((\\s*::\\s*\\w+)|(\\s*<\\s*\\w+?\\s*>))?'", "# r'\\s*const\\s*' + type_name + '\\s*&\\s*\\w+\\s*;'", "error", "(", "filename", ",", "linenum", ",", "'runtime/member_string_references'", ",", "2", ",", "'const string& members are dangerous. It is much better to use '", "'alternatives, such as pointers or simple constants.'", ")", "# Everything else in this function operates on class declarations.", "# Return early if the top of the nesting stack is not a class, or if", "# the class head is not completed yet.", "classinfo", "=", "nesting_state", ".", "InnermostClass", "(", ")", "if", "not", "classinfo", "or", "not", "classinfo", ".", "seen_open_brace", ":", "return", "# The class may have been declared with namespace or classname qualifiers.", "# The constructor and destructor will not have those qualifiers.", "base_classname", "=", "classinfo", ".", "name", ".", "split", "(", "'::'", ")", "[", "-", "1", "]", "# Look for single-argument constructors that aren't marked explicit.", "# Technically a valid construct, but against style.", "args", "=", "Match", "(", "r'\\s+(?:inline\\s+)?%s\\s*\\(([^,()]+)\\)'", "%", "re", ".", "escape", "(", "base_classname", ")", ",", "line", ")", "if", "(", "args", "and", "args", ".", "group", "(", "1", ")", "!=", "'void'", "and", "not", "Match", "(", "r'(const\\s+)?%s(\\s+const)?\\s*(?:<\\w+>\\s*)?&'", "%", "re", ".", "escape", "(", "base_classname", ")", ",", "args", ".", "group", "(", "1", ")", ".", "strip", "(", ")", ")", ")", ":", "error", "(", "filename", ",", "linenum", ",", "'runtime/explicit'", ",", "5", ",", "'Single-argument constructors should be marked explicit.'", ")" ]
https://github.com/rbgirshick/caffe-fast-rcnn/blob/28a579eaf0668850705598b3075b8969f22226d9/scripts/cpp_lint.py#L2194-L2298
rdkit/rdkit
ede860ae316d12d8568daf5ee800921c3389c84e
Contrib/AtomAtomSimilarity/AtomAtomPathSimilarity.py
python
FindAllPathsOfLengthMToN_Gobbi
(mol, minlength, maxlength, rootedAtAtom=-1, uniquepaths=True)
this function returns the same set of bond paths as the Gobbi paper. These differ a little from the rdkit FindAllPathsOfLengthMToN function
this function returns the same set of bond paths as the Gobbi paper. These differ a little from the rdkit FindAllPathsOfLengthMToN function
[ "this", "function", "returns", "the", "same", "set", "of", "bond", "paths", "as", "the", "Gobbi", "paper", ".", "These", "differ", "a", "little", "from", "the", "rdkit", "FindAllPathsOfLengthMToN", "function" ]
def FindAllPathsOfLengthMToN_Gobbi(mol, minlength, maxlength, rootedAtAtom=-1, uniquepaths=True): '''this function returns the same set of bond paths as the Gobbi paper. These differ a little from the rdkit FindAllPathsOfLengthMToN function''' paths = [] for atom in mol.GetAtoms(): if rootedAtAtom == -1 or atom.GetIdx() == rootedAtAtom: path = [] visited = set([atom.GetIdx()]) # visited = set() _FindAllPathsOfLengthMToN_Gobbi(atom, path, minlength, maxlength, visited, paths) if uniquepaths: uniquepathlist = [] seen = set() for path in paths: if path not in seen: reversepath = tuple([i for i in path[::-1]]) if reversepath not in seen: uniquepathlist.append(path) seen.add(path) return uniquepathlist else: return paths
[ "def", "FindAllPathsOfLengthMToN_Gobbi", "(", "mol", ",", "minlength", ",", "maxlength", ",", "rootedAtAtom", "=", "-", "1", ",", "uniquepaths", "=", "True", ")", ":", "paths", "=", "[", "]", "for", "atom", "in", "mol", ".", "GetAtoms", "(", ")", ":", "if", "rootedAtAtom", "==", "-", "1", "or", "atom", ".", "GetIdx", "(", ")", "==", "rootedAtAtom", ":", "path", "=", "[", "]", "visited", "=", "set", "(", "[", "atom", ".", "GetIdx", "(", ")", "]", ")", "#\t\t\tvisited = set()", "_FindAllPathsOfLengthMToN_Gobbi", "(", "atom", ",", "path", ",", "minlength", ",", "maxlength", ",", "visited", ",", "paths", ")", "if", "uniquepaths", ":", "uniquepathlist", "=", "[", "]", "seen", "=", "set", "(", ")", "for", "path", "in", "paths", ":", "if", "path", "not", "in", "seen", ":", "reversepath", "=", "tuple", "(", "[", "i", "for", "i", "in", "path", "[", ":", ":", "-", "1", "]", "]", ")", "if", "reversepath", "not", "in", "seen", ":", "uniquepathlist", ".", "append", "(", "path", ")", "seen", ".", "add", "(", "path", ")", "return", "uniquepathlist", "else", ":", "return", "paths" ]
https://github.com/rdkit/rdkit/blob/ede860ae316d12d8568daf5ee800921c3389c84e/Contrib/AtomAtomSimilarity/AtomAtomPathSimilarity.py#L34-L55
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/pip/_internal/operations/install/wheel.py
python
get_csv_rows_for_installed
( old_csv_rows, # type: List[List[str]] installed, # type: Dict[RecordPath, RecordPath] changed, # type: Set[RecordPath] generated, # type: List[str] lib_dir, # type: str )
return installed_rows
:param installed: A map from archive RECORD path to installation RECORD path.
[]
def get_csv_rows_for_installed( old_csv_rows, # type: List[List[str]] installed, # type: Dict[RecordPath, RecordPath] changed, # type: Set[RecordPath] generated, # type: List[str] lib_dir, # type: str ): # type: (...) -> List[InstalledCSVRow] """ :param installed: A map from archive RECORD path to installation RECORD path. """ installed_rows = [] # type: List[InstalledCSVRow] for row in old_csv_rows: if len(row) > 3: logger.warning('RECORD line has more than three elements: %s', row) old_record_path = _parse_record_path(row[0]) new_record_path = installed.pop(old_record_path, old_record_path) if new_record_path in changed: digest, length = rehash(_record_to_fs_path(new_record_path)) else: digest = row[1] if len(row) > 1 else '' length = row[2] if len(row) > 2 else '' installed_rows.append((new_record_path, digest, length)) for f in generated: path = _fs_to_record_path(f, lib_dir) digest, length = rehash(f) installed_rows.append((path, digest, length)) for installed_record_path in installed.values(): installed_rows.append((installed_record_path, '', '')) return installed_rows
[ "def", "get_csv_rows_for_installed", "(", "old_csv_rows", ",", "# type: List[List[str]]", "installed", ",", "# type: Dict[RecordPath, RecordPath]", "changed", ",", "# type: Set[RecordPath]", "generated", ",", "# type: List[str]", "lib_dir", ",", "# type: str", ")", ":", "# type: (...) -> List[InstalledCSVRow]", "installed_rows", "=", "[", "]", "# type: List[InstalledCSVRow]", "for", "row", "in", "old_csv_rows", ":", "if", "len", "(", "row", ")", ">", "3", ":", "logger", ".", "warning", "(", "'RECORD line has more than three elements: %s'", ",", "row", ")", "old_record_path", "=", "_parse_record_path", "(", "row", "[", "0", "]", ")", "new_record_path", "=", "installed", ".", "pop", "(", "old_record_path", ",", "old_record_path", ")", "if", "new_record_path", "in", "changed", ":", "digest", ",", "length", "=", "rehash", "(", "_record_to_fs_path", "(", "new_record_path", ")", ")", "else", ":", "digest", "=", "row", "[", "1", "]", "if", "len", "(", "row", ")", ">", "1", "else", "''", "length", "=", "row", "[", "2", "]", "if", "len", "(", "row", ")", ">", "2", "else", "''", "installed_rows", ".", "append", "(", "(", "new_record_path", ",", "digest", ",", "length", ")", ")", "for", "f", "in", "generated", ":", "path", "=", "_fs_to_record_path", "(", "f", ",", "lib_dir", ")", "digest", ",", "length", "=", "rehash", "(", "f", ")", "installed_rows", ".", "append", "(", "(", "path", ",", "digest", ",", "length", ")", ")", "for", "installed_record_path", "in", "installed", ".", "values", "(", ")", ":", "installed_rows", ".", "append", "(", "(", "installed_record_path", ",", "''", ",", "''", ")", ")", "return", "installed_rows" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/pip/_internal/operations/install/wheel.py#L549-L609
Samsung/veles
95ed733c2e49bc011ad98ccf2416ecec23fbf352
veles/external/pydot.py
python
Edge.__eq__
(self, edge)
return False
Compare two edges. If the parent graph is directed, arcs linking node A to B are considered equal and A->B != B->A If the parent graph is undirected, any edge connecting two nodes is equal to any other edge connecting the same nodes, A->B == B->A
Compare two edges. If the parent graph is directed, arcs linking node A to B are considered equal and A->B != B->A If the parent graph is undirected, any edge connecting two nodes is equal to any other edge connecting the same nodes, A->B == B->A
[ "Compare", "two", "edges", ".", "If", "the", "parent", "graph", "is", "directed", "arcs", "linking", "node", "A", "to", "B", "are", "considered", "equal", "and", "A", "-", ">", "B", "!", "=", "B", "-", ">", "A", "If", "the", "parent", "graph", "is", "undirected", "any", "edge", "connecting", "two", "nodes", "is", "equal", "to", "any", "other", "edge", "connecting", "the", "same", "nodes", "A", "-", ">", "B", "==", "B", "-", ">", "A" ]
def __eq__(self, edge): """Compare two edges. If the parent graph is directed, arcs linking node A to B are considered equal and A->B != B->A If the parent graph is undirected, any edge connecting two nodes is equal to any other edge connecting the same nodes, A->B == B->A """ if not isinstance(edge, Edge): raise Error("Can't compare and edge to a non-edge object.") if self.get_parent_graph().get_top_graph_type() == 'graph': # If the graph is undirected, the edge has neither # source nor destination. # if ((self.get_source() == edge.get_source() and self.get_destination() == edge.get_destination()) or (edge.get_source() == self.get_destination() and edge.get_destination() == self.get_source())): return True else: if self.get_source() == edge.get_source() and self.get_destination() == edge.get_destination() : return True return False
[ "def", "__eq__", "(", "self", ",", "edge", ")", ":", "if", "not", "isinstance", "(", "edge", ",", "Edge", ")", ":", "raise", "Error", "(", "\"Can't compare and edge to a non-edge object.\"", ")", "if", "self", ".", "get_parent_graph", "(", ")", ".", "get_top_graph_type", "(", ")", "==", "'graph'", ":", "# If the graph is undirected, the edge has neither", "# source nor destination.", "#", "if", "(", "(", "self", ".", "get_source", "(", ")", "==", "edge", ".", "get_source", "(", ")", "and", "self", ".", "get_destination", "(", ")", "==", "edge", ".", "get_destination", "(", ")", ")", "or", "(", "edge", ".", "get_source", "(", ")", "==", "self", ".", "get_destination", "(", ")", "and", "edge", ".", "get_destination", "(", ")", "==", "self", ".", "get_source", "(", ")", ")", ")", ":", "return", "True", "else", ":", "if", "self", ".", "get_source", "(", ")", "==", "edge", ".", "get_source", "(", ")", "and", "self", ".", "get_destination", "(", ")", "==", "edge", ".", "get_destination", "(", ")", ":", "return", "True", "return", "False" ]
https://github.com/Samsung/veles/blob/95ed733c2e49bc011ad98ccf2416ecec23fbf352/veles/external/pydot.py#L900-L928
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/meta_graph_transform/meta_graph_transform.py
python
_gtt_transforms
(graph_def, input_names, output_names, initializer_names, transforms)
return _graph_transforms.TransformGraph(graph_def, input_names, all_output_names, transforms)
Pass through gtt transforms, applying them to the graph_def. Args: graph_def: A GraphDef proto to be transformed. input_names: Names of input nodes. output_names: Names of output nodes. initializer_names: Dictionary of the "infrastructural" nodes (initializers, save and restore ops, etc.) that should be retained even if they are not transitively reachable from output nodes. The keys in this dictionary indicate the collection where these nodes were obtained from. transforms: A list of strings naming the graph transforms to be applied in order. Returns: The transformed GraphDef.
Pass through gtt transforms, applying them to the graph_def.
[ "Pass", "through", "gtt", "transforms", "applying", "them", "to", "the", "graph_def", "." ]
def _gtt_transforms(graph_def, input_names, output_names, initializer_names, transforms): """Pass through gtt transforms, applying them to the graph_def. Args: graph_def: A GraphDef proto to be transformed. input_names: Names of input nodes. output_names: Names of output nodes. initializer_names: Dictionary of the "infrastructural" nodes (initializers, save and restore ops, etc.) that should be retained even if they are not transitively reachable from output nodes. The keys in this dictionary indicate the collection where these nodes were obtained from. transforms: A list of strings naming the graph transforms to be applied in order. Returns: The transformed GraphDef. """ if not transforms: transformed_graph_def = _graph_pb2.GraphDef() transformed_graph_def.CopyFrom(graph_def) return transformed_graph_def initializer_names_flat = sorted( [k for l in initializer_names.values() for k in l]) all_output_names = output_names + initializer_names_flat return _graph_transforms.TransformGraph(graph_def, input_names, all_output_names, transforms)
[ "def", "_gtt_transforms", "(", "graph_def", ",", "input_names", ",", "output_names", ",", "initializer_names", ",", "transforms", ")", ":", "if", "not", "transforms", ":", "transformed_graph_def", "=", "_graph_pb2", ".", "GraphDef", "(", ")", "transformed_graph_def", ".", "CopyFrom", "(", "graph_def", ")", "return", "transformed_graph_def", "initializer_names_flat", "=", "sorted", "(", "[", "k", "for", "l", "in", "initializer_names", ".", "values", "(", ")", "for", "k", "in", "l", "]", ")", "all_output_names", "=", "output_names", "+", "initializer_names_flat", "return", "_graph_transforms", ".", "TransformGraph", "(", "graph_def", ",", "input_names", ",", "all_output_names", ",", "transforms", ")" ]
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/meta_graph_transform/meta_graph_transform.py#L74-L100
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/tools/Editra/src/eclib/finddlg.py
python
FindPanel.OnOption
(self, evt)
Update search flags @param evt: wx.EVT_CHECKBOX
Update search flags @param evt: wx.EVT_CHECKBOX
[ "Update", "search", "flags", "@param", "evt", ":", "wx", ".", "EVT_CHECKBOX" ]
def OnOption(self, evt): """Update search flags @param evt: wx.EVT_CHECKBOX """ fmap = { ID_MATCH_CASE : AFR_MATCHCASE, ID_WHOLE_WORD : AFR_WHOLEWORD, ID_REGEX : AFR_REGEX, ID_RECURSE : AFR_RECURSIVE, wx.ID_UP : AFR_UP } eid = evt.Id eobj = evt.EventObject if eid in fmap: if eobj.GetValue(): self.SetFlag(fmap[eid]) else: self.ClearFlag(fmap[eid]) self.FireEvent(ID_OPTION_CHANGE) elif eid == wx.ID_DOWN: self.ClearFlag(fmap[wx.ID_UP]) self.FireEvent(ID_OPTION_CHANGE) else: evt.Skip()
[ "def", "OnOption", "(", "self", ",", "evt", ")", ":", "fmap", "=", "{", "ID_MATCH_CASE", ":", "AFR_MATCHCASE", ",", "ID_WHOLE_WORD", ":", "AFR_WHOLEWORD", ",", "ID_REGEX", ":", "AFR_REGEX", ",", "ID_RECURSE", ":", "AFR_RECURSIVE", ",", "wx", ".", "ID_UP", ":", "AFR_UP", "}", "eid", "=", "evt", ".", "Id", "eobj", "=", "evt", ".", "EventObject", "if", "eid", "in", "fmap", ":", "if", "eobj", ".", "GetValue", "(", ")", ":", "self", ".", "SetFlag", "(", "fmap", "[", "eid", "]", ")", "else", ":", "self", ".", "ClearFlag", "(", "fmap", "[", "eid", "]", ")", "self", ".", "FireEvent", "(", "ID_OPTION_CHANGE", ")", "elif", "eid", "==", "wx", ".", "ID_DOWN", ":", "self", ".", "ClearFlag", "(", "fmap", "[", "wx", ".", "ID_UP", "]", ")", "self", ".", "FireEvent", "(", "ID_OPTION_CHANGE", ")", "else", ":", "evt", ".", "Skip", "(", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/src/eclib/finddlg.py#L1153-L1175
mindspore-ai/mindspore
fb8fd3338605bb34fa5cea054e535a8b1d753fab
mindspore/python/mindspore/_extends/graph_kernel/model/graph_parallel.py
python
ScheduleAnalyzer.analyze
(self)
analyze ops
analyze ops
[ "analyze", "ops" ]
def analyze(self): """analyze ops""" def _ops_type(ops, dom_op): have_reduce = any( [PrimLib.iter_type(op) == PrimLib.REDUCE for op in ops]) if have_reduce: return True return PrimLib.iter_type(dom_op[0]) dom_type = _ops_type(self.ops, self.dom_op) if dom_type in (PrimLib.ELEMWISE, PrimLib.BROADCAST): self.injective_analyze() elif dom_type == PrimLib.REDUCE: self.reduce_analyze() else: self.default_analyze()
[ "def", "analyze", "(", "self", ")", ":", "def", "_ops_type", "(", "ops", ",", "dom_op", ")", ":", "have_reduce", "=", "any", "(", "[", "PrimLib", ".", "iter_type", "(", "op", ")", "==", "PrimLib", ".", "REDUCE", "for", "op", "in", "ops", "]", ")", "if", "have_reduce", ":", "return", "True", "return", "PrimLib", ".", "iter_type", "(", "dom_op", "[", "0", "]", ")", "dom_type", "=", "_ops_type", "(", "self", ".", "ops", ",", "self", ".", "dom_op", ")", "if", "dom_type", "in", "(", "PrimLib", ".", "ELEMWISE", ",", "PrimLib", ".", "BROADCAST", ")", ":", "self", ".", "injective_analyze", "(", ")", "elif", "dom_type", "==", "PrimLib", ".", "REDUCE", ":", "self", ".", "reduce_analyze", "(", ")", "else", ":", "self", ".", "default_analyze", "(", ")" ]
https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/_extends/graph_kernel/model/graph_parallel.py#L124-L139
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/lib/pydocview.py
python
DocService.__init__
(self)
Initializes the DocService.
Initializes the DocService.
[ "Initializes", "the", "DocService", "." ]
def __init__(self): """Initializes the DocService.""" pass
[ "def", "__init__", "(", "self", ")", ":", "pass" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/pydocview.py#L1283-L1285
apple/swift-lldb
d74be846ef3e62de946df343e8c234bde93a8912
scripts/Python/static-binding/lldb.py
python
SBListener.PeekAtNextEventForBroadcasterWithType
(self, broadcaster, event_type_mask, sb_event)
return _lldb.SBListener_PeekAtNextEventForBroadcasterWithType(self, broadcaster, event_type_mask, sb_event)
PeekAtNextEventForBroadcasterWithType(SBListener self, SBBroadcaster broadcaster, uint32_t event_type_mask, SBEvent sb_event) -> bool
PeekAtNextEventForBroadcasterWithType(SBListener self, SBBroadcaster broadcaster, uint32_t event_type_mask, SBEvent sb_event) -> bool
[ "PeekAtNextEventForBroadcasterWithType", "(", "SBListener", "self", "SBBroadcaster", "broadcaster", "uint32_t", "event_type_mask", "SBEvent", "sb_event", ")", "-", ">", "bool" ]
def PeekAtNextEventForBroadcasterWithType(self, broadcaster, event_type_mask, sb_event): """PeekAtNextEventForBroadcasterWithType(SBListener self, SBBroadcaster broadcaster, uint32_t event_type_mask, SBEvent sb_event) -> bool""" return _lldb.SBListener_PeekAtNextEventForBroadcasterWithType(self, broadcaster, event_type_mask, sb_event)
[ "def", "PeekAtNextEventForBroadcasterWithType", "(", "self", ",", "broadcaster", ",", "event_type_mask", ",", "sb_event", ")", ":", "return", "_lldb", ".", "SBListener_PeekAtNextEventForBroadcasterWithType", "(", "self", ",", "broadcaster", ",", "event_type_mask", ",", "sb_event", ")" ]
https://github.com/apple/swift-lldb/blob/d74be846ef3e62de946df343e8c234bde93a8912/scripts/Python/static-binding/lldb.py#L6880-L6882
y123456yz/reading-and-annotate-mongodb-3.6
93280293672ca7586dc24af18132aa61e4ed7fcf
mongo/src/third_party/scons-2.5.0/scons-local-2.5.0/SCons/Node/FS.py
python
Dir.glob
(self, pathname, ondisk=True, source=False, strings=False, exclude=None)
return sorted(result, key=lambda a: str(a))
Returns a list of Nodes (or strings) matching a specified pathname pattern. Pathname patterns follow UNIX shell semantics: * matches any-length strings of any characters, ? matches any character, and [] can enclose lists or ranges of characters. Matches do not span directory separators. The matches take into account Repositories, returning local Nodes if a corresponding entry exists in a Repository (either an in-memory Node or something on disk). By defafult, the glob() function matches entries that exist on-disk, in addition to in-memory Nodes. Setting the "ondisk" argument to False (or some other non-true value) causes the glob() function to only match in-memory Nodes. The default behavior is to return both the on-disk and in-memory Nodes. The "source" argument, when true, specifies that corresponding source Nodes must be returned if you're globbing in a build directory (initialized with VariantDir()). The default behavior is to return Nodes local to the VariantDir(). The "strings" argument, when true, returns the matches as strings, not Nodes. The strings are path names relative to this directory. The "exclude" argument, if not None, must be a pattern or a list of patterns following the same UNIX shell semantics. Elements matching a least one pattern of this list will be excluded from the result. The underlying algorithm is adapted from the glob.glob() function in the Python library (but heavily modified), and uses fnmatch() under the covers.
Returns a list of Nodes (or strings) matching a specified pathname pattern.
[ "Returns", "a", "list", "of", "Nodes", "(", "or", "strings", ")", "matching", "a", "specified", "pathname", "pattern", "." ]
def glob(self, pathname, ondisk=True, source=False, strings=False, exclude=None): """ Returns a list of Nodes (or strings) matching a specified pathname pattern. Pathname patterns follow UNIX shell semantics: * matches any-length strings of any characters, ? matches any character, and [] can enclose lists or ranges of characters. Matches do not span directory separators. The matches take into account Repositories, returning local Nodes if a corresponding entry exists in a Repository (either an in-memory Node or something on disk). By defafult, the glob() function matches entries that exist on-disk, in addition to in-memory Nodes. Setting the "ondisk" argument to False (or some other non-true value) causes the glob() function to only match in-memory Nodes. The default behavior is to return both the on-disk and in-memory Nodes. The "source" argument, when true, specifies that corresponding source Nodes must be returned if you're globbing in a build directory (initialized with VariantDir()). The default behavior is to return Nodes local to the VariantDir(). The "strings" argument, when true, returns the matches as strings, not Nodes. The strings are path names relative to this directory. The "exclude" argument, if not None, must be a pattern or a list of patterns following the same UNIX shell semantics. Elements matching a least one pattern of this list will be excluded from the result. The underlying algorithm is adapted from the glob.glob() function in the Python library (but heavily modified), and uses fnmatch() under the covers. """ dirname, basename = os.path.split(pathname) if not dirname: result = self._glob1(basename, ondisk, source, strings) else: if has_glob_magic(dirname): list = self.glob(dirname, ondisk, source, False, exclude) else: list = [self.Dir(dirname, create=True)] result = [] for dir in list: r = dir._glob1(basename, ondisk, source, strings) if strings: r = [os.path.join(str(dir), x) for x in r] result.extend(r) if exclude: excludes = [] excludeList = SCons.Util.flatten(exclude) for x in excludeList: r = self.glob(x, ondisk, source, strings) excludes.extend(r) result = filter(lambda x: not any(fnmatch.fnmatch(str(x), str(e)) for e in SCons.Util.flatten(excludes)), result) return sorted(result, key=lambda a: str(a))
[ "def", "glob", "(", "self", ",", "pathname", ",", "ondisk", "=", "True", ",", "source", "=", "False", ",", "strings", "=", "False", ",", "exclude", "=", "None", ")", ":", "dirname", ",", "basename", "=", "os", ".", "path", ".", "split", "(", "pathname", ")", "if", "not", "dirname", ":", "result", "=", "self", ".", "_glob1", "(", "basename", ",", "ondisk", ",", "source", ",", "strings", ")", "else", ":", "if", "has_glob_magic", "(", "dirname", ")", ":", "list", "=", "self", ".", "glob", "(", "dirname", ",", "ondisk", ",", "source", ",", "False", ",", "exclude", ")", "else", ":", "list", "=", "[", "self", ".", "Dir", "(", "dirname", ",", "create", "=", "True", ")", "]", "result", "=", "[", "]", "for", "dir", "in", "list", ":", "r", "=", "dir", ".", "_glob1", "(", "basename", ",", "ondisk", ",", "source", ",", "strings", ")", "if", "strings", ":", "r", "=", "[", "os", ".", "path", ".", "join", "(", "str", "(", "dir", ")", ",", "x", ")", "for", "x", "in", "r", "]", "result", ".", "extend", "(", "r", ")", "if", "exclude", ":", "excludes", "=", "[", "]", "excludeList", "=", "SCons", ".", "Util", ".", "flatten", "(", "exclude", ")", "for", "x", "in", "excludeList", ":", "r", "=", "self", ".", "glob", "(", "x", ",", "ondisk", ",", "source", ",", "strings", ")", "excludes", ".", "extend", "(", "r", ")", "result", "=", "filter", "(", "lambda", "x", ":", "not", "any", "(", "fnmatch", ".", "fnmatch", "(", "str", "(", "x", ")", ",", "str", "(", "e", ")", ")", "for", "e", "in", "SCons", ".", "Util", ".", "flatten", "(", "excludes", ")", ")", ",", "result", ")", "return", "sorted", "(", "result", ",", "key", "=", "lambda", "a", ":", "str", "(", "a", ")", ")" ]
https://github.com/y123456yz/reading-and-annotate-mongodb-3.6/blob/93280293672ca7586dc24af18132aa61e4ed7fcf/mongo/src/third_party/scons-2.5.0/scons-local-2.5.0/SCons/Node/FS.py#L2133-L2191
jackaudio/jack2
21b293dbc37d42446141a08922cdec0d2550c6a0
waflib/Options.py
python
opt_parser.get_usage
(self)
return '''waf [commands] [options] Main commands (example: ./waf build -j4) %s ''' % ret
Builds the message to print on ``waf --help`` :rtype: string
Builds the message to print on ``waf --help``
[ "Builds", "the", "message", "to", "print", "on", "waf", "--", "help" ]
def get_usage(self): """ Builds the message to print on ``waf --help`` :rtype: string """ cmds_str = {} for cls in Context.classes: if not cls.cmd or cls.cmd == 'options' or cls.cmd.startswith( '_' ): continue s = cls.__doc__ or '' cmds_str[cls.cmd] = s if Context.g_module: for (k, v) in Context.g_module.__dict__.items(): if k in ('options', 'init', 'shutdown'): continue if type(v) is type(Context.create_context): if v.__doc__ and not k.startswith('_'): cmds_str[k] = v.__doc__ just = 0 for k in cmds_str: just = max(just, len(k)) lst = [' %s: %s' % (k.ljust(just), v) for (k, v) in cmds_str.items()] lst.sort() ret = '\n'.join(lst) return '''waf [commands] [options] Main commands (example: ./waf build -j4) %s ''' % ret
[ "def", "get_usage", "(", "self", ")", ":", "cmds_str", "=", "{", "}", "for", "cls", "in", "Context", ".", "classes", ":", "if", "not", "cls", ".", "cmd", "or", "cls", ".", "cmd", "==", "'options'", "or", "cls", ".", "cmd", ".", "startswith", "(", "'_'", ")", ":", "continue", "s", "=", "cls", ".", "__doc__", "or", "''", "cmds_str", "[", "cls", ".", "cmd", "]", "=", "s", "if", "Context", ".", "g_module", ":", "for", "(", "k", ",", "v", ")", "in", "Context", ".", "g_module", ".", "__dict__", ".", "items", "(", ")", ":", "if", "k", "in", "(", "'options'", ",", "'init'", ",", "'shutdown'", ")", ":", "continue", "if", "type", "(", "v", ")", "is", "type", "(", "Context", ".", "create_context", ")", ":", "if", "v", ".", "__doc__", "and", "not", "k", ".", "startswith", "(", "'_'", ")", ":", "cmds_str", "[", "k", "]", "=", "v", ".", "__doc__", "just", "=", "0", "for", "k", "in", "cmds_str", ":", "just", "=", "max", "(", "just", ",", "len", "(", "k", ")", ")", "lst", "=", "[", "' %s: %s'", "%", "(", "k", ".", "ljust", "(", "just", ")", ",", "v", ")", "for", "(", "k", ",", "v", ")", "in", "cmds_str", ".", "items", "(", ")", "]", "lst", ".", "sort", "(", ")", "ret", "=", "'\\n'", ".", "join", "(", "lst", ")", "return", "'''waf [commands] [options]\n\nMain commands (example: ./waf build -j4)\n%s\n'''", "%", "ret" ]
https://github.com/jackaudio/jack2/blob/21b293dbc37d42446141a08922cdec0d2550c6a0/waflib/Options.py#L68-L103
windystrife/UnrealEngine_NVIDIAGameWorks
b50e6338a7c5b26374d66306ebc7807541ff815e
Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/difflib.py
python
SequenceMatcher.real_quick_ratio
(self)
return _calculate_ratio(min(la, lb), la + lb)
Return an upper bound on ratio() very quickly. This isn't defined beyond that it is an upper bound on .ratio(), and is faster to compute than either .ratio() or .quick_ratio().
Return an upper bound on ratio() very quickly.
[ "Return", "an", "upper", "bound", "on", "ratio", "()", "very", "quickly", "." ]
def real_quick_ratio(self): """Return an upper bound on ratio() very quickly. This isn't defined beyond that it is an upper bound on .ratio(), and is faster to compute than either .ratio() or .quick_ratio(). """ la, lb = len(self.a), len(self.b) # can't have more matches than the number of elements in the # shorter sequence return _calculate_ratio(min(la, lb), la + lb)
[ "def", "real_quick_ratio", "(", "self", ")", ":", "la", ",", "lb", "=", "len", "(", "self", ".", "a", ")", ",", "len", "(", "self", ".", "b", ")", "# can't have more matches than the number of elements in the", "# shorter sequence", "return", "_calculate_ratio", "(", "min", "(", "la", ",", "lb", ")", ",", "la", "+", "lb", ")" ]
https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/difflib.py#L691-L701
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/pip/_vendor/pyparsing.py
python
Keyword.setDefaultKeywordChars
(chars)
Overrides the default Keyword chars
Overrides the default Keyword chars
[ "Overrides", "the", "default", "Keyword", "chars" ]
def setDefaultKeywordChars(chars): """Overrides the default Keyword chars """ Keyword.DEFAULT_KEYWORD_CHARS = chars
[ "def", "setDefaultKeywordChars", "(", "chars", ")", ":", "Keyword", ".", "DEFAULT_KEYWORD_CHARS", "=", "chars" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/pip/_vendor/pyparsing.py#L2977-L2980
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/tools/Editra/src/extern/pkg_resources.py
python
IMetadataProvider.metadata_listdir
(name)
List of metadata names in the directory (like ``os.listdir()``)
List of metadata names in the directory (like ``os.listdir()``)
[ "List", "of", "metadata", "names", "in", "the", "directory", "(", "like", "os", ".", "listdir", "()", ")" ]
def metadata_listdir(name): """List of metadata names in the directory (like ``os.listdir()``)"""
[ "def", "metadata_listdir", "(", "name", ")", ":" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/src/extern/pkg_resources.py#L270-L271
trilinos/Trilinos
6168be6dd51e35e1cd681e9c4b24433e709df140
packages/seacas/scripts/exomerge3.py
python
ExodusModel._get_inverted_face_mapping
(self, element_type)
return new_face
Return the connectivity pemutation to invert an element face.
Return the connectivity pemutation to invert an element face.
[ "Return", "the", "connectivity", "pemutation", "to", "invert", "an", "element", "face", "." ]
def _get_inverted_face_mapping(self, element_type): """Return the connectivity pemutation to invert an element face.""" face_mapping = self._get_face_mapping(element_type) inversion_mapping = self._get_inverted_connectivity(element_type) original_face = [set(face) for _, face in face_mapping] new_face = [ set(inversion_mapping[x] for x in face) for _, face in face_mapping ] try: new_face = [original_face.index(x) for x in new_face] except ValueError: self._bug( 'Unable to determine face mapping.', 'We were unable to determine how to map faces when ' 'inverting an element of type "%s".' % element_type) return new_face
[ "def", "_get_inverted_face_mapping", "(", "self", ",", "element_type", ")", ":", "face_mapping", "=", "self", ".", "_get_face_mapping", "(", "element_type", ")", "inversion_mapping", "=", "self", ".", "_get_inverted_connectivity", "(", "element_type", ")", "original_face", "=", "[", "set", "(", "face", ")", "for", "_", ",", "face", "in", "face_mapping", "]", "new_face", "=", "[", "set", "(", "inversion_mapping", "[", "x", "]", "for", "x", "in", "face", ")", "for", "_", ",", "face", "in", "face_mapping", "]", "try", ":", "new_face", "=", "[", "original_face", ".", "index", "(", "x", ")", "for", "x", "in", "new_face", "]", "except", "ValueError", ":", "self", ".", "_bug", "(", "'Unable to determine face mapping.'", ",", "'We were unable to determine how to map faces when '", "'inverting an element of type \"%s\".'", "%", "element_type", ")", "return", "new_face" ]
https://github.com/trilinos/Trilinos/blob/6168be6dd51e35e1cd681e9c4b24433e709df140/packages/seacas/scripts/exomerge3.py#L5897-L5912
ZhouWeikuan/DouDiZhu
0d84ff6c0bc54dba6ae37955de9ae9307513dc99
code/frameworks/cocos2d-x/tools/bindings-generator/generator.py
python
Generator._sorted_parents
(self, nclass)
return sorted_parents
returns the sorted list of parents for a native class
returns the sorted list of parents for a native class
[ "returns", "the", "sorted", "list", "of", "parents", "for", "a", "native", "class" ]
def _sorted_parents(self, nclass): ''' returns the sorted list of parents for a native class ''' sorted_parents = [] for p in nclass.parents: if p.class_name in self.generated_classes.keys(): sorted_parents += self._sorted_parents(p) if nclass.class_name in self.generated_classes.keys(): sorted_parents.append(nclass.class_name) return sorted_parents
[ "def", "_sorted_parents", "(", "self", ",", "nclass", ")", ":", "sorted_parents", "=", "[", "]", "for", "p", "in", "nclass", ".", "parents", ":", "if", "p", ".", "class_name", "in", "self", ".", "generated_classes", ".", "keys", "(", ")", ":", "sorted_parents", "+=", "self", ".", "_sorted_parents", "(", "p", ")", "if", "nclass", ".", "class_name", "in", "self", ".", "generated_classes", ".", "keys", "(", ")", ":", "sorted_parents", ".", "append", "(", "nclass", ".", "class_name", ")", "return", "sorted_parents" ]
https://github.com/ZhouWeikuan/DouDiZhu/blob/0d84ff6c0bc54dba6ae37955de9ae9307513dc99/code/frameworks/cocos2d-x/tools/bindings-generator/generator.py#L1160-L1170
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/_gdi.py
python
IconFromLocation
(*args, **kwargs)
return val
IconFromLocation(IconLocation loc) -> Icon
IconFromLocation(IconLocation loc) -> Icon
[ "IconFromLocation", "(", "IconLocation", "loc", ")", "-", ">", "Icon" ]
def IconFromLocation(*args, **kwargs): """IconFromLocation(IconLocation loc) -> Icon""" val = _gdi_.new_IconFromLocation(*args, **kwargs) return val
[ "def", "IconFromLocation", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "val", "=", "_gdi_", ".", "new_IconFromLocation", "(", "*", "args", ",", "*", "*", "kwargs", ")", "return", "val" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_gdi.py#L1327-L1330
OpenChemistry/tomviz
0a903679318f191cb7dd3eb5ff5bc3a7d3320d9a
tomviz/python/tomviz/io/dm.py
python
FileDM._encodedTypeDtype
(self, encodedType)
return Type
Translate the encodings used by DM to numpy dtypes according to: SHORT = 2 LONG = 3 USHORT = 4 ULONG = 5 FLOAT = 6 DOUBLE = 7 BOOLEAN = 8 CHAR = 9 OCTET = 10 uint64 = 12 -1 will signal an unlisted type Parameters ---------- encodedType : int The type value read from the header Returns ------- Type : numpy dtype The Numpy dtype corresponding to the DM encoded value.
Translate the encodings used by DM to numpy dtypes according to: SHORT = 2 LONG = 3 USHORT = 4 ULONG = 5 FLOAT = 6 DOUBLE = 7 BOOLEAN = 8 CHAR = 9 OCTET = 10 uint64 = 12 -1 will signal an unlisted type
[ "Translate", "the", "encodings", "used", "by", "DM", "to", "numpy", "dtypes", "according", "to", ":", "SHORT", "=", "2", "LONG", "=", "3", "USHORT", "=", "4", "ULONG", "=", "5", "FLOAT", "=", "6", "DOUBLE", "=", "7", "BOOLEAN", "=", "8", "CHAR", "=", "9", "OCTET", "=", "10", "uint64", "=", "12", "-", "1", "will", "signal", "an", "unlisted", "type" ]
def _encodedTypeDtype(self, encodedType): """Translate the encodings used by DM to numpy dtypes according to: SHORT = 2 LONG = 3 USHORT = 4 ULONG = 5 FLOAT = 6 DOUBLE = 7 BOOLEAN = 8 CHAR = 9 OCTET = 10 uint64 = 12 -1 will signal an unlisted type Parameters ---------- encodedType : int The type value read from the header Returns ------- Type : numpy dtype The Numpy dtype corresponding to the DM encoded value. """ try: Type = self._EncodedTypeDTypes[encodedType] except KeyError: Type = -1 # except: # raise return Type
[ "def", "_encodedTypeDtype", "(", "self", ",", "encodedType", ")", ":", "try", ":", "Type", "=", "self", ".", "_EncodedTypeDTypes", "[", "encodedType", "]", "except", "KeyError", ":", "Type", "=", "-", "1", "# except:", "# raise", "return", "Type" ]
https://github.com/OpenChemistry/tomviz/blob/0a903679318f191cb7dd3eb5ff5bc3a7d3320d9a/tomviz/python/tomviz/io/dm.py#L608-L641
pmq20/node-packer
12c46c6e44fbc14d9ee645ebd17d5296b324f7e0
lts/deps/v8/third_party/jinja2/filters.py
python
do_first
(environment, seq)
Return the first item of a sequence.
Return the first item of a sequence.
[ "Return", "the", "first", "item", "of", "a", "sequence", "." ]
def do_first(environment, seq): """Return the first item of a sequence.""" try: return next(iter(seq)) except StopIteration: return environment.undefined('No first item, sequence was empty.')
[ "def", "do_first", "(", "environment", ",", "seq", ")", ":", "try", ":", "return", "next", "(", "iter", "(", "seq", ")", ")", "except", "StopIteration", ":", "return", "environment", ".", "undefined", "(", "'No first item, sequence was empty.'", ")" ]
https://github.com/pmq20/node-packer/blob/12c46c6e44fbc14d9ee645ebd17d5296b324f7e0/lts/deps/v8/third_party/jinja2/filters.py#L433-L438
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/build/waf-1.7.13/platforms/platform_settings_win_x64_vs2019.py
python
inject_msvs_2019_command
(conf)
Make sure the msvs command is injected into the configuration context
Make sure the msvs command is injected into the configuration context
[ "Make", "sure", "the", "msvs", "command", "is", "injected", "into", "the", "configuration", "context" ]
def inject_msvs_2019_command(conf): """ Make sure the msvs command is injected into the configuration context """ platform_settings_win_x64.inject_msvs_command(conf, VS_VERSION)
[ "def", "inject_msvs_2019_command", "(", "conf", ")", ":", "platform_settings_win_x64", ".", "inject_msvs_command", "(", "conf", ",", "VS_VERSION", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/build/waf-1.7.13/platforms/platform_settings_win_x64_vs2019.py#L42-L46
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/windows/Lib/site-packages/setuptools/config.py
python
ConfigOptionsHandler.parse_section_package_data
(self, section_options)
Parses `package_data` configuration file section. :param dict section_options:
Parses `package_data` configuration file section.
[ "Parses", "package_data", "configuration", "file", "section", "." ]
def parse_section_package_data(self, section_options): """Parses `package_data` configuration file section. :param dict section_options: """ self['package_data'] = self._parse_package_data(section_options)
[ "def", "parse_section_package_data", "(", "self", ",", "section_options", ")", ":", "self", "[", "'package_data'", "]", "=", "self", ".", "_parse_package_data", "(", "section_options", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/site-packages/setuptools/config.py#L670-L675
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
tools/memory_inspector/memory_inspector/frontends/www_server.py
python
_GetProcessStats
(args, req_vars)
return _HTTP_OK, [], {'cpu': cpu_stats, 'mem': mem_stats}
Lists CPU / mem stats for a given process (and keeps history). The response is formatted according to the Google Charts DataTable format.
Lists CPU / mem stats for a given process (and keeps history).
[ "Lists", "CPU", "/", "mem", "stats", "for", "a", "given", "process", "(", "and", "keeps", "history", ")", "." ]
def _GetProcessStats(args, req_vars): # pylint: disable=W0613 """Lists CPU / mem stats for a given process (and keeps history). The response is formatted according to the Google Charts DataTable format. """ process = _GetProcess(args) if not process: return _HTTP_GONE, [], 'Device not found' proc_uri = '/'.join(args) cur_stats = process.GetStats() if proc_uri not in _proc_stats_history: _proc_stats_history[proc_uri] = collections.deque(maxlen=_STATS_HIST_SIZE) history = _proc_stats_history[proc_uri] history.append(cur_stats) cpu_stats = { 'cols': [ {'label': 'T', 'type':'string'}, {'label': 'CPU %', 'type':'number'}, {'label': '# Threads', 'type':'number'}, ], 'rows': [] } mem_stats = { 'cols': [ {'label': 'T', 'type':'string'}, {'label': 'Mem RSS Kb', 'type':'number'}, {'label': 'Page faults', 'type':'number'}, ], 'rows': [] } for stats in history: cpu_stats['rows'] += [{'c': [ {'v': str(datetime.timedelta(seconds=stats.run_time)), 'f': None}, {'v': stats.cpu_usage, 'f': None}, {'v': stats.threads, 'f': None}, ]}] mem_stats['rows'] += [{'c': [ {'v': str(datetime.timedelta(seconds=stats.run_time)), 'f': None}, {'v': stats.vm_rss, 'f': None}, {'v': stats.page_faults, 'f': None}, ]}] return _HTTP_OK, [], {'cpu': cpu_stats, 'mem': mem_stats}
[ "def", "_GetProcessStats", "(", "args", ",", "req_vars", ")", ":", "# pylint: disable=W0613", "process", "=", "_GetProcess", "(", "args", ")", "if", "not", "process", ":", "return", "_HTTP_GONE", ",", "[", "]", ",", "'Device not found'", "proc_uri", "=", "'/'", ".", "join", "(", "args", ")", "cur_stats", "=", "process", ".", "GetStats", "(", ")", "if", "proc_uri", "not", "in", "_proc_stats_history", ":", "_proc_stats_history", "[", "proc_uri", "]", "=", "collections", ".", "deque", "(", "maxlen", "=", "_STATS_HIST_SIZE", ")", "history", "=", "_proc_stats_history", "[", "proc_uri", "]", "history", ".", "append", "(", "cur_stats", ")", "cpu_stats", "=", "{", "'cols'", ":", "[", "{", "'label'", ":", "'T'", ",", "'type'", ":", "'string'", "}", ",", "{", "'label'", ":", "'CPU %'", ",", "'type'", ":", "'number'", "}", ",", "{", "'label'", ":", "'# Threads'", ",", "'type'", ":", "'number'", "}", ",", "]", ",", "'rows'", ":", "[", "]", "}", "mem_stats", "=", "{", "'cols'", ":", "[", "{", "'label'", ":", "'T'", ",", "'type'", ":", "'string'", "}", ",", "{", "'label'", ":", "'Mem RSS Kb'", ",", "'type'", ":", "'number'", "}", ",", "{", "'label'", ":", "'Page faults'", ",", "'type'", ":", "'number'", "}", ",", "]", ",", "'rows'", ":", "[", "]", "}", "for", "stats", "in", "history", ":", "cpu_stats", "[", "'rows'", "]", "+=", "[", "{", "'c'", ":", "[", "{", "'v'", ":", "str", "(", "datetime", ".", "timedelta", "(", "seconds", "=", "stats", ".", "run_time", ")", ")", ",", "'f'", ":", "None", "}", ",", "{", "'v'", ":", "stats", ".", "cpu_usage", ",", "'f'", ":", "None", "}", ",", "{", "'v'", ":", "stats", ".", "threads", ",", "'f'", ":", "None", "}", ",", "]", "}", "]", "mem_stats", "[", "'rows'", "]", "+=", "[", "{", "'c'", ":", "[", "{", "'v'", ":", "str", "(", "datetime", ".", "timedelta", "(", "seconds", "=", "stats", ".", "run_time", ")", ")", ",", "'f'", ":", "None", "}", ",", "{", "'v'", ":", "stats", ".", "vm_rss", ",", "'f'", ":", "None", "}", ",", "{", "'v'", ":", "stats", ".", "page_faults", ",", "'f'", ":", "None", "}", ",", "]", "}", "]", "return", "_HTTP_OK", ",", "[", "]", ",", "{", "'cpu'", ":", "cpu_stats", ",", "'mem'", ":", "mem_stats", "}" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/tools/memory_inspector/memory_inspector/frontends/www_server.py#L444-L490
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/core/ops/__init__.py
python
_get_op_name
(op, special)
return opname
Find the name to attach to this method according to conventions for special and non-special methods. Parameters ---------- op : binary operator special : bool Returns ------- op_name : str
Find the name to attach to this method according to conventions for special and non-special methods.
[ "Find", "the", "name", "to", "attach", "to", "this", "method", "according", "to", "conventions", "for", "special", "and", "non", "-", "special", "methods", "." ]
def _get_op_name(op, special): """ Find the name to attach to this method according to conventions for special and non-special methods. Parameters ---------- op : binary operator special : bool Returns ------- op_name : str """ opname = op.__name__.strip("_") if special: opname = f"__{opname}__" return opname
[ "def", "_get_op_name", "(", "op", ",", "special", ")", ":", "opname", "=", "op", ".", "__name__", ".", "strip", "(", "\"_\"", ")", "if", "special", ":", "opname", "=", "f\"__{opname}__\"", "return", "opname" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/core/ops/__init__.py#L292-L309
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/dataview.py
python
DataViewIconTextRenderer.__init__
(self, *args, **kwargs)
__init__(self, String varianttype="wxDataViewIconText", int mode=DATAVIEW_CELL_INERT, int align=DVR_DEFAULT_ALIGNMENT) -> DataViewIconTextRenderer The `DataViewIconTextRenderer` class is used to display text with a small icon next to it as it is typically done in a file manager. This class uses the `DataViewIconText` helper class to store its data.
__init__(self, String varianttype="wxDataViewIconText", int mode=DATAVIEW_CELL_INERT, int align=DVR_DEFAULT_ALIGNMENT) -> DataViewIconTextRenderer
[ "__init__", "(", "self", "String", "varianttype", "=", "wxDataViewIconText", "int", "mode", "=", "DATAVIEW_CELL_INERT", "int", "align", "=", "DVR_DEFAULT_ALIGNMENT", ")", "-", ">", "DataViewIconTextRenderer" ]
def __init__(self, *args, **kwargs): """ __init__(self, String varianttype="wxDataViewIconText", int mode=DATAVIEW_CELL_INERT, int align=DVR_DEFAULT_ALIGNMENT) -> DataViewIconTextRenderer The `DataViewIconTextRenderer` class is used to display text with a small icon next to it as it is typically done in a file manager. This class uses the `DataViewIconText` helper class to store its data. """ _dataview.DataViewIconTextRenderer_swiginit(self,_dataview.new_DataViewIconTextRenderer(*args, **kwargs))
[ "def", "__init__", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "_dataview", ".", "DataViewIconTextRenderer_swiginit", "(", "self", ",", "_dataview", ".", "new_DataViewIconTextRenderer", "(", "*", "args", ",", "*", "*", "kwargs", ")", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/dataview.py#L1286-L1296
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/linear_optimizer/python/ops/sdca_ops.py
python
SdcaModel.unregularized_loss
(self, examples)
Add operations to compute the loss (without the regularization loss). Args: examples: Examples to compute unregularized loss on. Returns: An Operation that computes mean (unregularized) loss for given set of examples. Raises: ValueError: if examples are not well defined.
Add operations to compute the loss (without the regularization loss).
[ "Add", "operations", "to", "compute", "the", "loss", "(", "without", "the", "regularization", "loss", ")", "." ]
def unregularized_loss(self, examples): """Add operations to compute the loss (without the regularization loss). Args: examples: Examples to compute unregularized loss on. Returns: An Operation that computes mean (unregularized) loss for given set of examples. Raises: ValueError: if examples are not well defined. """ self._assertSpecified([ 'example_labels', 'example_weights', 'sparse_features', 'dense_features' ], examples) self._assertList(['sparse_features', 'dense_features'], examples) with name_scope('sdca/unregularized_loss'): predictions = math_ops.cast( self._linear_predictions(examples), dtypes.float64) labels = math_ops.cast( internal_convert_to_tensor(examples['example_labels']), dtypes.float64) weights = math_ops.cast( internal_convert_to_tensor(examples['example_weights']), dtypes.float64) if self._options['loss_type'] == 'logistic_loss': return math_ops.reduce_sum(math_ops.multiply( sigmoid_cross_entropy_with_logits(labels=labels, logits=predictions), weights)) / math_ops.reduce_sum(weights) if self._options['loss_type'] == 'poisson_loss': return math_ops.reduce_sum(math_ops.multiply( log_poisson_loss(targets=labels, log_input=predictions), weights)) / math_ops.reduce_sum(weights) if self._options['loss_type'] in ['hinge_loss', 'smooth_hinge_loss']: # hinge_loss = max{0, 1 - y_i w*x} where y_i \in {-1, 1}. So, we need to # first convert 0/1 labels into -1/1 labels. all_ones = array_ops.ones_like(predictions) adjusted_labels = math_ops.subtract(2 * labels, all_ones) # Tensor that contains (unweighted) error (hinge loss) per # example. error = nn_ops.relu( math_ops.subtract(all_ones, math_ops.multiply(adjusted_labels, predictions))) weighted_error = math_ops.multiply(error, weights) return math_ops.reduce_sum(weighted_error) / math_ops.reduce_sum( weights) # squared loss err = math_ops.subtract(labels, predictions) weighted_squared_err = math_ops.multiply(math_ops.square(err), weights) # SDCA squared loss function is sum(err^2) / (2*sum(weights)) return (math_ops.reduce_sum(weighted_squared_err) / (2.0 * math_ops.reduce_sum(weights)))
[ "def", "unregularized_loss", "(", "self", ",", "examples", ")", ":", "self", ".", "_assertSpecified", "(", "[", "'example_labels'", ",", "'example_weights'", ",", "'sparse_features'", ",", "'dense_features'", "]", ",", "examples", ")", "self", ".", "_assertList", "(", "[", "'sparse_features'", ",", "'dense_features'", "]", ",", "examples", ")", "with", "name_scope", "(", "'sdca/unregularized_loss'", ")", ":", "predictions", "=", "math_ops", ".", "cast", "(", "self", ".", "_linear_predictions", "(", "examples", ")", ",", "dtypes", ".", "float64", ")", "labels", "=", "math_ops", ".", "cast", "(", "internal_convert_to_tensor", "(", "examples", "[", "'example_labels'", "]", ")", ",", "dtypes", ".", "float64", ")", "weights", "=", "math_ops", ".", "cast", "(", "internal_convert_to_tensor", "(", "examples", "[", "'example_weights'", "]", ")", ",", "dtypes", ".", "float64", ")", "if", "self", ".", "_options", "[", "'loss_type'", "]", "==", "'logistic_loss'", ":", "return", "math_ops", ".", "reduce_sum", "(", "math_ops", ".", "multiply", "(", "sigmoid_cross_entropy_with_logits", "(", "labels", "=", "labels", ",", "logits", "=", "predictions", ")", ",", "weights", ")", ")", "/", "math_ops", ".", "reduce_sum", "(", "weights", ")", "if", "self", ".", "_options", "[", "'loss_type'", "]", "==", "'poisson_loss'", ":", "return", "math_ops", ".", "reduce_sum", "(", "math_ops", ".", "multiply", "(", "log_poisson_loss", "(", "targets", "=", "labels", ",", "log_input", "=", "predictions", ")", ",", "weights", ")", ")", "/", "math_ops", ".", "reduce_sum", "(", "weights", ")", "if", "self", ".", "_options", "[", "'loss_type'", "]", "in", "[", "'hinge_loss'", ",", "'smooth_hinge_loss'", "]", ":", "# hinge_loss = max{0, 1 - y_i w*x} where y_i \\in {-1, 1}. So, we need to", "# first convert 0/1 labels into -1/1 labels.", "all_ones", "=", "array_ops", ".", "ones_like", "(", "predictions", ")", "adjusted_labels", "=", "math_ops", ".", "subtract", "(", "2", "*", "labels", ",", "all_ones", ")", "# Tensor that contains (unweighted) error (hinge loss) per", "# example.", "error", "=", "nn_ops", ".", "relu", "(", "math_ops", ".", "subtract", "(", "all_ones", ",", "math_ops", ".", "multiply", "(", "adjusted_labels", ",", "predictions", ")", ")", ")", "weighted_error", "=", "math_ops", ".", "multiply", "(", "error", ",", "weights", ")", "return", "math_ops", ".", "reduce_sum", "(", "weighted_error", ")", "/", "math_ops", ".", "reduce_sum", "(", "weights", ")", "# squared loss", "err", "=", "math_ops", ".", "subtract", "(", "labels", ",", "predictions", ")", "weighted_squared_err", "=", "math_ops", ".", "multiply", "(", "math_ops", ".", "square", "(", "err", ")", ",", "weights", ")", "# SDCA squared loss function is sum(err^2) / (2*sum(weights))", "return", "(", "math_ops", ".", "reduce_sum", "(", "weighted_squared_err", ")", "/", "(", "2.0", "*", "math_ops", ".", "reduce_sum", "(", "weights", ")", ")", ")" ]
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/linear_optimizer/python/ops/sdca_ops.py#L639-L697
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/venv/__init__.py
python
EnvBuilder.create
(self, env_dir)
Create a virtual environment in a directory. :param env_dir: The target directory to create an environment in.
Create a virtual environment in a directory.
[ "Create", "a", "virtual", "environment", "in", "a", "directory", "." ]
def create(self, env_dir): """ Create a virtual environment in a directory. :param env_dir: The target directory to create an environment in. """ env_dir = os.path.abspath(env_dir) context = self.ensure_directories(env_dir) # See issue 24875. We need system_site_packages to be False # until after pip is installed. true_system_site_packages = self.system_site_packages self.system_site_packages = False self.create_configuration(context) self.setup_python(context) if self.with_pip: self._setup_pip(context) if not self.upgrade: self.setup_scripts(context) self.post_setup(context) if true_system_site_packages: # We had set it to False before, now # restore it and rewrite the configuration self.system_site_packages = True self.create_configuration(context)
[ "def", "create", "(", "self", ",", "env_dir", ")", ":", "env_dir", "=", "os", ".", "path", ".", "abspath", "(", "env_dir", ")", "context", "=", "self", ".", "ensure_directories", "(", "env_dir", ")", "# See issue 24875. We need system_site_packages to be False", "# until after pip is installed.", "true_system_site_packages", "=", "self", ".", "system_site_packages", "self", ".", "system_site_packages", "=", "False", "self", ".", "create_configuration", "(", "context", ")", "self", ".", "setup_python", "(", "context", ")", "if", "self", ".", "with_pip", ":", "self", ".", "_setup_pip", "(", "context", ")", "if", "not", "self", ".", "upgrade", ":", "self", ".", "setup_scripts", "(", "context", ")", "self", ".", "post_setup", "(", "context", ")", "if", "true_system_site_packages", ":", "# We had set it to False before, now", "# restore it and rewrite the configuration", "self", ".", "system_site_packages", "=", "True", "self", ".", "create_configuration", "(", "context", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/venv/__init__.py#L52-L76
Cantera/cantera
0119484b261967ccb55a0066c020599cacc312e4
interfaces/cython/cantera/ctml2yaml.py
python
Phase.margules
( self, activity_coeffs: etree.Element )
return interactions
Process activity coefficients for a ``Margules`` phase-thermo type. :param activity_coeffs: XML ``activityCoefficients`` node. For the ``Margules`` phase-thermo type these are interaction parameters between the species in the phase. Returns a list of interaction data values. Margules does not require the ``binaryNeutralSpeciesParameters`` node to be present. Almost a superset of the Redlich-Kister parameters, but since the ``binaryNeutralSpeciesParameters`` are processed in a loop, there's no advantage to re-use Redlich-Kister processing because this function would have to go through the same nodes again.
Process activity coefficients for a ``Margules`` phase-thermo type.
[ "Process", "activity", "coefficients", "for", "a", "Margules", "phase", "-", "thermo", "type", "." ]
def margules( self, activity_coeffs: etree.Element ) -> List[Dict[str, List[Union[str, "QUANTITY"]]]]: """Process activity coefficients for a ``Margules`` phase-thermo type. :param activity_coeffs: XML ``activityCoefficients`` node. For the ``Margules`` phase-thermo type these are interaction parameters between the species in the phase. Returns a list of interaction data values. Margules does not require the ``binaryNeutralSpeciesParameters`` node to be present. Almost a superset of the Redlich-Kister parameters, but since the ``binaryNeutralSpeciesParameters`` are processed in a loop, there's no advantage to re-use Redlich-Kister processing because this function would have to go through the same nodes again. """ all_binary_params = activity_coeffs.findall("binaryNeutralSpeciesParameters") interactions = [] for binary_params in all_binary_params: species_A = binary_params.get("speciesA") species_B = binary_params.get("speciesB") if species_A is None or species_B is None: raise MissingXMLAttribute( "'binaryNeutralSpeciesParameters' node requires 'speciesA' and " "'speciesB' attributes", binary_params, ) this_node = { "species": FlowList([species_A, species_B]) } # type: Dict[str, List[Union[str, QUANTITY]]] excess_enthalpy_node = binary_params.find("excessEnthalpy") if excess_enthalpy_node is not None: excess_enthalpy = clean_node_text(excess_enthalpy_node).split(",") enthalpy_units = excess_enthalpy_node.get("units", "") if not enthalpy_units: this_node["excess-enthalpy"] = FlowList(map(float, excess_enthalpy)) else: this_node["excess-enthalpy"] = FlowList( [" ".join([e.strip(), enthalpy_units]) for e in excess_enthalpy] ) excess_entropy_node = binary_params.find("excessEntropy") if excess_entropy_node is not None: excess_entropy = clean_node_text(excess_entropy_node).split(",") entropy_units = excess_entropy_node.get("units", "") if not entropy_units: this_node["excess-entropy"] = FlowList(map(float, excess_entropy)) else: this_node["excess-entropy"] = FlowList( [" ".join([e.strip(), entropy_units]) for e in excess_entropy] ) excessvol_enth_node = binary_params.find("excessVolume_Enthalpy") if excessvol_enth_node is not None: excess_vol_enthalpy = clean_node_text(excessvol_enth_node).split(",") enthalpy_units = excessvol_enth_node.get("units", "") if not enthalpy_units: this_node["excess-volume-enthalpy"] = FlowList( map(float, excess_vol_enthalpy) ) else: this_node["excess-volume-enthalpy"] = FlowList( [ " ".join([e.strip(), enthalpy_units]) for e in excess_vol_enthalpy ] ) excessvol_entr_node = binary_params.find("excessVolume_Entropy") if excessvol_entr_node is not None: excess_vol_entropy = clean_node_text(excessvol_entr_node).split(",") entropy_units = excessvol_entr_node.get("units", "") if not entropy_units: this_node["excess-volume-entropy"] = FlowList( map(float, excess_vol_entropy) ) else: this_node["excess-volume-entropy"] = FlowList( [ " ".join([e.strip(), entropy_units]) for e in excess_vol_entropy ] ) interactions.append(this_node) return interactions
[ "def", "margules", "(", "self", ",", "activity_coeffs", ":", "etree", ".", "Element", ")", "->", "List", "[", "Dict", "[", "str", ",", "List", "[", "Union", "[", "str", ",", "\"QUANTITY\"", "]", "]", "]", "]", ":", "all_binary_params", "=", "activity_coeffs", ".", "findall", "(", "\"binaryNeutralSpeciesParameters\"", ")", "interactions", "=", "[", "]", "for", "binary_params", "in", "all_binary_params", ":", "species_A", "=", "binary_params", ".", "get", "(", "\"speciesA\"", ")", "species_B", "=", "binary_params", ".", "get", "(", "\"speciesB\"", ")", "if", "species_A", "is", "None", "or", "species_B", "is", "None", ":", "raise", "MissingXMLAttribute", "(", "\"'binaryNeutralSpeciesParameters' node requires 'speciesA' and \"", "\"'speciesB' attributes\"", ",", "binary_params", ",", ")", "this_node", "=", "{", "\"species\"", ":", "FlowList", "(", "[", "species_A", ",", "species_B", "]", ")", "}", "# type: Dict[str, List[Union[str, QUANTITY]]]", "excess_enthalpy_node", "=", "binary_params", ".", "find", "(", "\"excessEnthalpy\"", ")", "if", "excess_enthalpy_node", "is", "not", "None", ":", "excess_enthalpy", "=", "clean_node_text", "(", "excess_enthalpy_node", ")", ".", "split", "(", "\",\"", ")", "enthalpy_units", "=", "excess_enthalpy_node", ".", "get", "(", "\"units\"", ",", "\"\"", ")", "if", "not", "enthalpy_units", ":", "this_node", "[", "\"excess-enthalpy\"", "]", "=", "FlowList", "(", "map", "(", "float", ",", "excess_enthalpy", ")", ")", "else", ":", "this_node", "[", "\"excess-enthalpy\"", "]", "=", "FlowList", "(", "[", "\" \"", ".", "join", "(", "[", "e", ".", "strip", "(", ")", ",", "enthalpy_units", "]", ")", "for", "e", "in", "excess_enthalpy", "]", ")", "excess_entropy_node", "=", "binary_params", ".", "find", "(", "\"excessEntropy\"", ")", "if", "excess_entropy_node", "is", "not", "None", ":", "excess_entropy", "=", "clean_node_text", "(", "excess_entropy_node", ")", ".", "split", "(", "\",\"", ")", "entropy_units", "=", "excess_entropy_node", ".", "get", "(", "\"units\"", ",", "\"\"", ")", "if", "not", "entropy_units", ":", "this_node", "[", "\"excess-entropy\"", "]", "=", "FlowList", "(", "map", "(", "float", ",", "excess_entropy", ")", ")", "else", ":", "this_node", "[", "\"excess-entropy\"", "]", "=", "FlowList", "(", "[", "\" \"", ".", "join", "(", "[", "e", ".", "strip", "(", ")", ",", "entropy_units", "]", ")", "for", "e", "in", "excess_entropy", "]", ")", "excessvol_enth_node", "=", "binary_params", ".", "find", "(", "\"excessVolume_Enthalpy\"", ")", "if", "excessvol_enth_node", "is", "not", "None", ":", "excess_vol_enthalpy", "=", "clean_node_text", "(", "excessvol_enth_node", ")", ".", "split", "(", "\",\"", ")", "enthalpy_units", "=", "excessvol_enth_node", ".", "get", "(", "\"units\"", ",", "\"\"", ")", "if", "not", "enthalpy_units", ":", "this_node", "[", "\"excess-volume-enthalpy\"", "]", "=", "FlowList", "(", "map", "(", "float", ",", "excess_vol_enthalpy", ")", ")", "else", ":", "this_node", "[", "\"excess-volume-enthalpy\"", "]", "=", "FlowList", "(", "[", "\" \"", ".", "join", "(", "[", "e", ".", "strip", "(", ")", ",", "enthalpy_units", "]", ")", "for", "e", "in", "excess_vol_enthalpy", "]", ")", "excessvol_entr_node", "=", "binary_params", ".", "find", "(", "\"excessVolume_Entropy\"", ")", "if", "excessvol_entr_node", "is", "not", "None", ":", "excess_vol_entropy", "=", "clean_node_text", "(", "excessvol_entr_node", ")", ".", "split", "(", "\",\"", ")", "entropy_units", "=", "excessvol_entr_node", ".", "get", "(", "\"units\"", ",", "\"\"", ")", "if", "not", "entropy_units", ":", "this_node", "[", "\"excess-volume-entropy\"", "]", "=", "FlowList", "(", "map", "(", "float", ",", "excess_vol_entropy", ")", ")", "else", ":", "this_node", "[", "\"excess-volume-entropy\"", "]", "=", "FlowList", "(", "[", "\" \"", ".", "join", "(", "[", "e", ".", "strip", "(", ")", ",", "entropy_units", "]", ")", "for", "e", "in", "excess_vol_entropy", "]", ")", "interactions", ".", "append", "(", "this_node", ")", "return", "interactions" ]
https://github.com/Cantera/cantera/blob/0119484b261967ccb55a0066c020599cacc312e4/interfaces/cython/cantera/ctml2yaml.py#L680-L763
tensorflow/tensorflow
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
tensorflow/python/framework/ops.py
python
RegisterStatistics.__init__
(self, op_type, statistic_type)
Saves the `op_type` as the `Operation` type.
Saves the `op_type` as the `Operation` type.
[ "Saves", "the", "op_type", "as", "the", "Operation", "type", "." ]
def __init__(self, op_type, statistic_type): """Saves the `op_type` as the `Operation` type.""" if not isinstance(op_type, six.string_types): raise TypeError("op_type must be a string.") if "," in op_type: raise TypeError("op_type must not contain a comma.") self._op_type = op_type if not isinstance(statistic_type, six.string_types): raise TypeError("statistic_type must be a string.") if "," in statistic_type: raise TypeError("statistic_type must not contain a comma.") self._statistic_type = statistic_type
[ "def", "__init__", "(", "self", ",", "op_type", ",", "statistic_type", ")", ":", "if", "not", "isinstance", "(", "op_type", ",", "six", ".", "string_types", ")", ":", "raise", "TypeError", "(", "\"op_type must be a string.\"", ")", "if", "\",\"", "in", "op_type", ":", "raise", "TypeError", "(", "\"op_type must not contain a comma.\"", ")", "self", ".", "_op_type", "=", "op_type", "if", "not", "isinstance", "(", "statistic_type", ",", "six", ".", "string_types", ")", ":", "raise", "TypeError", "(", "\"statistic_type must be a string.\"", ")", "if", "\",\"", "in", "statistic_type", ":", "raise", "TypeError", "(", "\"statistic_type must not contain a comma.\"", ")", "self", ".", "_statistic_type", "=", "statistic_type" ]
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/framework/ops.py#L2971-L2982
mongodb/mongo
d8ff665343ad29cf286ee2cf4a1960d29371937b
buildscripts/gdb/mongo_lock.py
python
Graph.find_node
(self, node)
return None
Find node in graph.
Find node in graph.
[ "Find", "node", "in", "graph", "." ]
def find_node(self, node): """Find node in graph.""" if node.key() in self.nodes: return self.nodes[node.key()] return None
[ "def", "find_node", "(", "self", ",", "node", ")", ":", "if", "node", ".", "key", "(", ")", "in", "self", ".", "nodes", ":", "return", "self", ".", "nodes", "[", "node", ".", "key", "(", ")", "]", "return", "None" ]
https://github.com/mongodb/mongo/blob/d8ff665343ad29cf286ee2cf4a1960d29371937b/buildscripts/gdb/mongo_lock.py#L119-L123
mantidproject/mantid
03deeb89254ec4289edb8771e0188c2090a02f32
scripts/Diffraction/isis_powder/routines/common.py
python
generate_sample_material
(sample_details)
return material_json
Generates the expected input for sample material using the SampleDetails class :param sample_details: Instance of SampleDetails containing details about sample geometry and material :return: A map of the sample material
Generates the expected input for sample material using the SampleDetails class :param sample_details: Instance of SampleDetails containing details about sample geometry and material :return: A map of the sample material
[ "Generates", "the", "expected", "input", "for", "sample", "material", "using", "the", "SampleDetails", "class", ":", "param", "sample_details", ":", "Instance", "of", "SampleDetails", "containing", "details", "about", "sample", "geometry", "and", "material", ":", "return", ":", "A", "map", "of", "the", "sample", "material" ]
def generate_sample_material(sample_details): """ Generates the expected input for sample material using the SampleDetails class :param sample_details: Instance of SampleDetails containing details about sample geometry and material :return: A map of the sample material """ material = sample_details.material_object # See SetSampleMaterial for documentation on this dictionary material_json = {'ChemicalFormula': material.chemical_formula} if material.number_density: material_json["SampleNumberDensity"] = material.number_density if material.absorption_cross_section: material_json["AttenuationXSection"] = material.absorption_cross_section if material.scattering_cross_section: material_json["ScatteringXSection"] = material.scattering_cross_section return material_json
[ "def", "generate_sample_material", "(", "sample_details", ")", ":", "material", "=", "sample_details", ".", "material_object", "# See SetSampleMaterial for documentation on this dictionary", "material_json", "=", "{", "'ChemicalFormula'", ":", "material", ".", "chemical_formula", "}", "if", "material", ".", "number_density", ":", "material_json", "[", "\"SampleNumberDensity\"", "]", "=", "material", ".", "number_density", "if", "material", ".", "absorption_cross_section", ":", "material_json", "[", "\"AttenuationXSection\"", "]", "=", "material", ".", "absorption_cross_section", "if", "material", ".", "scattering_cross_section", ":", "material_json", "[", "\"ScatteringXSection\"", "]", "=", "material", ".", "scattering_cross_section", "return", "material_json" ]
https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/scripts/Diffraction/isis_powder/routines/common.py#L705-L721
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/tools/Editra/plugins/codebrowser/codebrowser/gentag/phptags.py
python
GenerateTags
(buff)
return rtags
Create a DocStruct object that represents a Php Script @param buff: a file like buffer object (StringIO)
Create a DocStruct object that represents a Php Script @param buff: a file like buffer object (StringIO)
[ "Create", "a", "DocStruct", "object", "that", "represents", "a", "Php", "Script", "@param", "buff", ":", "a", "file", "like", "buffer", "object", "(", "StringIO", ")" ]
def GenerateTags(buff): """Create a DocStruct object that represents a Php Script @param buff: a file like buffer object (StringIO) """ rtags = taglib.DocStruct() # Setup document structure rtags.SetElementDescription('function', "Function Definitions") inphp = False # Are we in a php section or not inclass = False # Inside a class defintion incomment = False # Inside a comment infundef = False # Inside a function definition lastclass = None lastfun = None instring = False openb = 0 # Keep track of open brackets for lnum, line in enumerate(buff): line = line.strip() llen = len(line) idx = 0 while idx < len(line): # Skip Whitespace idx = parselib.SkipWhitespace(line, idx) # Walk through strings ignoring contents if instring or line[idx] in (u"'", u'"'): idx, instring = parselib.FindStringEnd(line[idx:], idx) # For multiline strings if instring: continue # Check if in a <?php ?> block or not if line[idx:].startswith(u'<?'): idx += 2 if line[idx:].startswith(u'php'): idx += 5 inphp = True elif line[idx:].startswith(u'?>'): idx += 2 inphp = False # Skip anything not in side of a php section if not inphp: idx += 1 continue # Check for coments if line[idx:].startswith(u'/*'): idx += 2 incomment = True elif line[idx:].startswith(u'//') or line[idx:].startswith(u'#'): break # go to next line elif line[idx:].startswith(u'*/'): idx += 2 incomment = False # At end of line if idx >= llen: break # Look for tags if incomment: idx += 1 elif line[idx] == u'{': idx += 1 openb += 1 # Class name must be followed by a { if not inclass and lastclass is not None: inclass = True rtags.AddClass(lastclass) elif lastfun is not None: infundef = True lastfun = None else: pass elif line[idx] == u'}': idx += 1 openb -= 1 if inclass and openb == 0: inclass = False lastclass = None elif infundef and inclass and openb == 1: infundef = False elif infundef and openb == 0: infundef = False lastfun = None else: pass elif not infundef and parselib.IsToken(line, idx, u'class'): # Skip whitespace idx = parselib.SkipWhitespace(line, idx + 5) name = parselib.GetFirstIdentifier(line[idx:]) if name is not None: idx += len(name) # Move past the class name lastclass = taglib.Class(name, lnum) elif parselib.IsToken(line, idx, u'function'): # Skip whitespace idx = parselib.SkipWhitespace(line, idx + 8) name = parselib.GetFirstIdentifier(line[idx:]) if name is not None: lastfun = name # Skip whitespace idx = parselib.SkipWhitespace(line, idx + len(name)) if line[idx] != u'(': continue if inclass and lastclass is not None: lastclass.AddMethod(taglib.Method(name, lnum, lastclass.GetName())) else: rtags.AddFunction(taglib.Function(name, lnum)) elif inclass and parselib.IsToken(line, idx, u'var'): # Look for class variables idx += 3 parts = line[idx:].split() if len(parts) and parts[0].startswith(u'$'): name = parselib.GetFirstIdentifier(parts[0][1:]) if name is not None and lastclass is not None: name = u'$' + name lastclass.AddVariable(taglib.Variable(name, lnum, lastclass.GetName())) idx += len(name) else: idx += 1 return rtags
[ "def", "GenerateTags", "(", "buff", ")", ":", "rtags", "=", "taglib", ".", "DocStruct", "(", ")", "# Setup document structure", "rtags", ".", "SetElementDescription", "(", "'function'", ",", "\"Function Definitions\"", ")", "inphp", "=", "False", "# Are we in a php section or not", "inclass", "=", "False", "# Inside a class defintion", "incomment", "=", "False", "# Inside a comment", "infundef", "=", "False", "# Inside a function definition", "lastclass", "=", "None", "lastfun", "=", "None", "instring", "=", "False", "openb", "=", "0", "# Keep track of open brackets", "for", "lnum", ",", "line", "in", "enumerate", "(", "buff", ")", ":", "line", "=", "line", ".", "strip", "(", ")", "llen", "=", "len", "(", "line", ")", "idx", "=", "0", "while", "idx", "<", "len", "(", "line", ")", ":", "# Skip Whitespace", "idx", "=", "parselib", ".", "SkipWhitespace", "(", "line", ",", "idx", ")", "# Walk through strings ignoring contents", "if", "instring", "or", "line", "[", "idx", "]", "in", "(", "u\"'\"", ",", "u'\"'", ")", ":", "idx", ",", "instring", "=", "parselib", ".", "FindStringEnd", "(", "line", "[", "idx", ":", "]", ",", "idx", ")", "# For multiline strings", "if", "instring", ":", "continue", "# Check if in a <?php ?> block or not", "if", "line", "[", "idx", ":", "]", ".", "startswith", "(", "u'<?'", ")", ":", "idx", "+=", "2", "if", "line", "[", "idx", ":", "]", ".", "startswith", "(", "u'php'", ")", ":", "idx", "+=", "5", "inphp", "=", "True", "elif", "line", "[", "idx", ":", "]", ".", "startswith", "(", "u'?>'", ")", ":", "idx", "+=", "2", "inphp", "=", "False", "# Skip anything not in side of a php section", "if", "not", "inphp", ":", "idx", "+=", "1", "continue", "# Check for coments", "if", "line", "[", "idx", ":", "]", ".", "startswith", "(", "u'/*'", ")", ":", "idx", "+=", "2", "incomment", "=", "True", "elif", "line", "[", "idx", ":", "]", ".", "startswith", "(", "u'//'", ")", "or", "line", "[", "idx", ":", "]", ".", "startswith", "(", "u'#'", ")", ":", "break", "# go to next line", "elif", "line", "[", "idx", ":", "]", ".", "startswith", "(", "u'*/'", ")", ":", "idx", "+=", "2", "incomment", "=", "False", "# At end of line", "if", "idx", ">=", "llen", ":", "break", "# Look for tags", "if", "incomment", ":", "idx", "+=", "1", "elif", "line", "[", "idx", "]", "==", "u'{'", ":", "idx", "+=", "1", "openb", "+=", "1", "# Class name must be followed by a {", "if", "not", "inclass", "and", "lastclass", "is", "not", "None", ":", "inclass", "=", "True", "rtags", ".", "AddClass", "(", "lastclass", ")", "elif", "lastfun", "is", "not", "None", ":", "infundef", "=", "True", "lastfun", "=", "None", "else", ":", "pass", "elif", "line", "[", "idx", "]", "==", "u'}'", ":", "idx", "+=", "1", "openb", "-=", "1", "if", "inclass", "and", "openb", "==", "0", ":", "inclass", "=", "False", "lastclass", "=", "None", "elif", "infundef", "and", "inclass", "and", "openb", "==", "1", ":", "infundef", "=", "False", "elif", "infundef", "and", "openb", "==", "0", ":", "infundef", "=", "False", "lastfun", "=", "None", "else", ":", "pass", "elif", "not", "infundef", "and", "parselib", ".", "IsToken", "(", "line", ",", "idx", ",", "u'class'", ")", ":", "# Skip whitespace", "idx", "=", "parselib", ".", "SkipWhitespace", "(", "line", ",", "idx", "+", "5", ")", "name", "=", "parselib", ".", "GetFirstIdentifier", "(", "line", "[", "idx", ":", "]", ")", "if", "name", "is", "not", "None", ":", "idx", "+=", "len", "(", "name", ")", "# Move past the class name", "lastclass", "=", "taglib", ".", "Class", "(", "name", ",", "lnum", ")", "elif", "parselib", ".", "IsToken", "(", "line", ",", "idx", ",", "u'function'", ")", ":", "# Skip whitespace", "idx", "=", "parselib", ".", "SkipWhitespace", "(", "line", ",", "idx", "+", "8", ")", "name", "=", "parselib", ".", "GetFirstIdentifier", "(", "line", "[", "idx", ":", "]", ")", "if", "name", "is", "not", "None", ":", "lastfun", "=", "name", "# Skip whitespace", "idx", "=", "parselib", ".", "SkipWhitespace", "(", "line", ",", "idx", "+", "len", "(", "name", ")", ")", "if", "line", "[", "idx", "]", "!=", "u'('", ":", "continue", "if", "inclass", "and", "lastclass", "is", "not", "None", ":", "lastclass", ".", "AddMethod", "(", "taglib", ".", "Method", "(", "name", ",", "lnum", ",", "lastclass", ".", "GetName", "(", ")", ")", ")", "else", ":", "rtags", ".", "AddFunction", "(", "taglib", ".", "Function", "(", "name", ",", "lnum", ")", ")", "elif", "inclass", "and", "parselib", ".", "IsToken", "(", "line", ",", "idx", ",", "u'var'", ")", ":", "# Look for class variables", "idx", "+=", "3", "parts", "=", "line", "[", "idx", ":", "]", ".", "split", "(", ")", "if", "len", "(", "parts", ")", "and", "parts", "[", "0", "]", ".", "startswith", "(", "u'$'", ")", ":", "name", "=", "parselib", ".", "GetFirstIdentifier", "(", "parts", "[", "0", "]", "[", "1", ":", "]", ")", "if", "name", "is", "not", "None", "and", "lastclass", "is", "not", "None", ":", "name", "=", "u'$'", "+", "name", "lastclass", ".", "AddVariable", "(", "taglib", ".", "Variable", "(", "name", ",", "lnum", ",", "lastclass", ".", "GetName", "(", ")", ")", ")", "idx", "+=", "len", "(", "name", ")", "else", ":", "idx", "+=", "1", "return", "rtags" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/plugins/codebrowser/codebrowser/gentag/phptags.py#L31-L158
takemaru/graphillion
51879f92bb96b53ef8f914ef37a05252ce383617
graphillion/graphset.py
python
GraphSet.remove
(self, obj)
return None
Removes a given graph, edge, or vertex from `self`. If a graph is given, the graph is just removed from `self` GraphSet. If an edge is given, the edge is removed from all the graphs in `self`. The `self` will be changed. Examples: >>> graph1 = [(1, 2), (1, 4)] >>> graph2 = [(2, 3)] >>> gs = GraphSet([graph1, graph2]) >>> edge = (1, 2) >>> gs.remove(edge) >>> gs GraphSet([[(1, 4)], [(2, 3)]]) Args: obj: A graph (an edge list), an edge, or a vertex in the universe. Returns: None. Raises: KeyError: If a given edge or vertex is not found in the universe, or if the given graph is not stored in `self`. See Also: add(), discard(), pop()
Removes a given graph, edge, or vertex from `self`.
[ "Removes", "a", "given", "graph", "edge", "or", "vertex", "from", "self", "." ]
def remove(self, obj): """Removes a given graph, edge, or vertex from `self`. If a graph is given, the graph is just removed from `self` GraphSet. If an edge is given, the edge is removed from all the graphs in `self`. The `self` will be changed. Examples: >>> graph1 = [(1, 2), (1, 4)] >>> graph2 = [(2, 3)] >>> gs = GraphSet([graph1, graph2]) >>> edge = (1, 2) >>> gs.remove(edge) >>> gs GraphSet([[(1, 4)], [(2, 3)]]) Args: obj: A graph (an edge list), an edge, or a vertex in the universe. Returns: None. Raises: KeyError: If a given edge or vertex is not found in the universe, or if the given graph is not stored in `self`. See Also: add(), discard(), pop() """ type, obj = GraphSet._conv_arg(obj) if type == 'graph' or type == 'edge': self._ss.remove(obj) elif type == 'vertex': for edge in obj: self.remove(edge) else: raise TypeError(obj) return None
[ "def", "remove", "(", "self", ",", "obj", ")", ":", "type", ",", "obj", "=", "GraphSet", ".", "_conv_arg", "(", "obj", ")", "if", "type", "==", "'graph'", "or", "type", "==", "'edge'", ":", "self", ".", "_ss", ".", "remove", "(", "obj", ")", "elif", "type", "==", "'vertex'", ":", "for", "edge", "in", "obj", ":", "self", ".", "remove", "(", "edge", ")", "else", ":", "raise", "TypeError", "(", "obj", ")", "return", "None" ]
https://github.com/takemaru/graphillion/blob/51879f92bb96b53ef8f914ef37a05252ce383617/graphillion/graphset.py#L835-L873
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/third_party/gsutil/third_party/boto/boto/swf/layer1.py
python
Layer1.get_workflow_execution_history
(self, domain, run_id, workflow_id, maximum_page_size=None, next_page_token=None, reverse_order=None)
return self.json_request('GetWorkflowExecutionHistory', { 'domain': domain, 'execution': {'runId': run_id, 'workflowId': workflow_id}, 'maximumPageSize': maximum_page_size, 'nextPageToken': next_page_token, 'reverseOrder': reverse_order, })
Returns the history of the specified workflow execution. The results may be split into multiple pages. To retrieve subsequent pages, make the call again using the nextPageToken returned by the initial call. :type domain: string :param domain: The name of the domain containing the workflow execution. :type run_id: string :param run_id: A system generated unique identifier for the workflow execution. :type workflow_id: string :param workflow_id: The user defined identifier associated with the workflow execution. :type maximum_page_size: integer :param maximum_page_size: Specifies the maximum number of history events returned in one page. The next page in the result is identified by the NextPageToken returned. By default 100 history events are returned in a page but the caller can override this value to a page size smaller than the default. You cannot specify a page size larger than 100. :type next_page_token: string :param next_page_token: If a NextPageToken is returned, the result has more than one pages. To get the next page, repeat the call and specify the nextPageToken with all other arguments unchanged. :type reverse_order: boolean :param reverse_order: When set to true, returns the events in reverse order. By default the results are returned in ascending order of the eventTimeStamp of the events. :raises: UnknownResourceFault, SWFOperationNotPermittedError
Returns the history of the specified workflow execution. The results may be split into multiple pages. To retrieve subsequent pages, make the call again using the nextPageToken returned by the initial call.
[ "Returns", "the", "history", "of", "the", "specified", "workflow", "execution", ".", "The", "results", "may", "be", "split", "into", "multiple", "pages", ".", "To", "retrieve", "subsequent", "pages", "make", "the", "call", "again", "using", "the", "nextPageToken", "returned", "by", "the", "initial", "call", "." ]
def get_workflow_execution_history(self, domain, run_id, workflow_id, maximum_page_size=None, next_page_token=None, reverse_order=None): """ Returns the history of the specified workflow execution. The results may be split into multiple pages. To retrieve subsequent pages, make the call again using the nextPageToken returned by the initial call. :type domain: string :param domain: The name of the domain containing the workflow execution. :type run_id: string :param run_id: A system generated unique identifier for the workflow execution. :type workflow_id: string :param workflow_id: The user defined identifier associated with the workflow execution. :type maximum_page_size: integer :param maximum_page_size: Specifies the maximum number of history events returned in one page. The next page in the result is identified by the NextPageToken returned. By default 100 history events are returned in a page but the caller can override this value to a page size smaller than the default. You cannot specify a page size larger than 100. :type next_page_token: string :param next_page_token: If a NextPageToken is returned, the result has more than one pages. To get the next page, repeat the call and specify the nextPageToken with all other arguments unchanged. :type reverse_order: boolean :param reverse_order: When set to true, returns the events in reverse order. By default the results are returned in ascending order of the eventTimeStamp of the events. :raises: UnknownResourceFault, SWFOperationNotPermittedError """ return self.json_request('GetWorkflowExecutionHistory', { 'domain': domain, 'execution': {'runId': run_id, 'workflowId': workflow_id}, 'maximumPageSize': maximum_page_size, 'nextPageToken': next_page_token, 'reverseOrder': reverse_order, })
[ "def", "get_workflow_execution_history", "(", "self", ",", "domain", ",", "run_id", ",", "workflow_id", ",", "maximum_page_size", "=", "None", ",", "next_page_token", "=", "None", ",", "reverse_order", "=", "None", ")", ":", "return", "self", ".", "json_request", "(", "'GetWorkflowExecutionHistory'", ",", "{", "'domain'", ":", "domain", ",", "'execution'", ":", "{", "'runId'", ":", "run_id", ",", "'workflowId'", ":", "workflow_id", "}", ",", "'maximumPageSize'", ":", "maximum_page_size", ",", "'nextPageToken'", ":", "next_page_token", ",", "'reverseOrder'", ":", "reverse_order", ",", "}", ")" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/gsutil/third_party/boto/boto/swf/layer1.py#L1038-L1088
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/pandas/py3/pandas/core/arrays/categorical.py
python
Categorical.__contains__
(self, key)
return contains(self, key, container=self._codes)
Returns True if `key` is in this Categorical.
Returns True if `key` is in this Categorical.
[ "Returns", "True", "if", "key", "is", "in", "this", "Categorical", "." ]
def __contains__(self, key) -> bool: """ Returns True if `key` is in this Categorical. """ # if key is a NaN, check if any NaN is in self. if is_valid_na_for_dtype(key, self.categories.dtype): return bool(self.isna().any()) return contains(self, key, container=self._codes)
[ "def", "__contains__", "(", "self", ",", "key", ")", "->", "bool", ":", "# if key is a NaN, check if any NaN is in self.", "if", "is_valid_na_for_dtype", "(", "key", ",", "self", ".", "categories", ".", "dtype", ")", ":", "return", "bool", "(", "self", ".", "isna", "(", ")", ".", "any", "(", ")", ")", "return", "contains", "(", "self", ",", "key", ",", "container", "=", "self", ".", "_codes", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py3/pandas/core/arrays/categorical.py#L1892-L1900
windystrife/UnrealEngine_NVIDIAGameWorks
b50e6338a7c5b26374d66306ebc7807541ff815e
Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/site-packages/pip/vendor/distlib/_backport/tarfile.py
python
TarFile.chown
(self, tarinfo, targetpath)
Set owner of targetpath according to tarinfo.
Set owner of targetpath according to tarinfo.
[ "Set", "owner", "of", "targetpath", "according", "to", "tarinfo", "." ]
def chown(self, tarinfo, targetpath): """Set owner of targetpath according to tarinfo. """ if pwd and hasattr(os, "geteuid") and os.geteuid() == 0: # We have to be root to do so. try: g = grp.getgrnam(tarinfo.gname)[2] except KeyError: g = tarinfo.gid try: u = pwd.getpwnam(tarinfo.uname)[2] except KeyError: u = tarinfo.uid try: if tarinfo.issym() and hasattr(os, "lchown"): os.lchown(targetpath, u, g) else: if sys.platform != "os2emx": os.chown(targetpath, u, g) except EnvironmentError as e: raise ExtractError("could not change owner")
[ "def", "chown", "(", "self", ",", "tarinfo", ",", "targetpath", ")", ":", "if", "pwd", "and", "hasattr", "(", "os", ",", "\"geteuid\"", ")", "and", "os", ".", "geteuid", "(", ")", "==", "0", ":", "# We have to be root to do so.", "try", ":", "g", "=", "grp", ".", "getgrnam", "(", "tarinfo", ".", "gname", ")", "[", "2", "]", "except", "KeyError", ":", "g", "=", "tarinfo", ".", "gid", "try", ":", "u", "=", "pwd", ".", "getpwnam", "(", "tarinfo", ".", "uname", ")", "[", "2", "]", "except", "KeyError", ":", "u", "=", "tarinfo", ".", "uid", "try", ":", "if", "tarinfo", ".", "issym", "(", ")", "and", "hasattr", "(", "os", ",", "\"lchown\"", ")", ":", "os", ".", "lchown", "(", "targetpath", ",", "u", ",", "g", ")", "else", ":", "if", "sys", ".", "platform", "!=", "\"os2emx\"", ":", "os", ".", "chown", "(", "targetpath", ",", "u", ",", "g", ")", "except", "EnvironmentError", "as", "e", ":", "raise", "ExtractError", "(", "\"could not change owner\"", ")" ]
https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/site-packages/pip/vendor/distlib/_backport/tarfile.py#L2372-L2392
GXYM/DRRG
9e074fa9052de8d131f55ca1f6ae6673c1bfeca4
util/misc.py
python
mkdirs
(newdir)
make directory with parent path :param newdir: target path
make directory with parent path :param newdir: target path
[ "make", "directory", "with", "parent", "path", ":", "param", "newdir", ":", "target", "path" ]
def mkdirs(newdir): """ make directory with parent path :param newdir: target path """ try: if not os.path.exists(newdir): os.makedirs(newdir) except OSError as err: # Reraise the error unless it's about an already existing directory if err.errno != errno.EEXIST or not os.path.isdir(newdir): raise
[ "def", "mkdirs", "(", "newdir", ")", ":", "try", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "newdir", ")", ":", "os", ".", "makedirs", "(", "newdir", ")", "except", "OSError", "as", "err", ":", "# Reraise the error unless it's about an already existing directory", "if", "err", ".", "errno", "!=", "errno", ".", "EEXIST", "or", "not", "os", ".", "path", ".", "isdir", "(", "newdir", ")", ":", "raise" ]
https://github.com/GXYM/DRRG/blob/9e074fa9052de8d131f55ca1f6ae6673c1bfeca4/util/misc.py#L16-L27
SequoiaDB/SequoiaDB
2894ed7e5bd6fe57330afc900cf76d0ff0df9f64
tools/server/php_linux/libxml2/lib/python2.4/site-packages/libxml2.py
python
parserCtxt.parsePI
(self)
parse an XML Processing Instruction. [16] PI ::= '<?' PITarget (S (Char* - (Char* '?>' Char*)))? '?>' The processing is transfered to SAX once parsed.
parse an XML Processing Instruction. [16] PI ::= '<?' PITarget (S (Char* - (Char* '?>' Char*)))? '?>' The processing is transfered to SAX once parsed.
[ "parse", "an", "XML", "Processing", "Instruction", ".", "[", "16", "]", "PI", "::", "=", "<?", "PITarget", "(", "S", "(", "Char", "*", "-", "(", "Char", "*", "?", ">", "Char", "*", ")))", "?", "?", ">", "The", "processing", "is", "transfered", "to", "SAX", "once", "parsed", "." ]
def parsePI(self): """parse an XML Processing Instruction. [16] PI ::= '<?' PITarget (S (Char* - (Char* '?>' Char*)))? '?>' The processing is transfered to SAX once parsed. """ libxml2mod.xmlParsePI(self._o)
[ "def", "parsePI", "(", "self", ")", ":", "libxml2mod", ".", "xmlParsePI", "(", "self", ".", "_o", ")" ]
https://github.com/SequoiaDB/SequoiaDB/blob/2894ed7e5bd6fe57330afc900cf76d0ff0df9f64/tools/server/php_linux/libxml2/lib/python2.4/site-packages/libxml2.py#L5335-L5339
miyosuda/TensorFlowAndroidMNIST
7b5a4603d2780a8a2834575706e9001977524007
jni-build/jni/include/tensorflow/python/client/timeline.py
python
Timeline.generate_chrome_trace_format
(self, show_dataflow=True, show_memory=False)
return step_stats_analysis.chrome_trace.format_to_string(pretty=True)
Produces a trace in Chrome Trace Format. Args: show_dataflow: (Optional.) If True, add flow events to the trace connecting producers and consumers of tensors. show_memory: (Optional.) If True, add object snapshot events to the trace showing the sizes and lifetimes of tensors. Returns: A JSON formatted string in Chrome Trace format.
Produces a trace in Chrome Trace Format.
[ "Produces", "a", "trace", "in", "Chrome", "Trace", "Format", "." ]
def generate_chrome_trace_format(self, show_dataflow=True, show_memory=False): """Produces a trace in Chrome Trace Format. Args: show_dataflow: (Optional.) If True, add flow events to the trace connecting producers and consumers of tensors. show_memory: (Optional.) If True, add object snapshot events to the trace showing the sizes and lifetimes of tensors. Returns: A JSON formatted string in Chrome Trace format. """ step_stats_analysis = self.analyze_step_stats( show_dataflow=show_dataflow, show_memory=show_memory) return step_stats_analysis.chrome_trace.format_to_string(pretty=True)
[ "def", "generate_chrome_trace_format", "(", "self", ",", "show_dataflow", "=", "True", ",", "show_memory", "=", "False", ")", ":", "step_stats_analysis", "=", "self", ".", "analyze_step_stats", "(", "show_dataflow", "=", "show_dataflow", ",", "show_memory", "=", "show_memory", ")", "return", "step_stats_analysis", ".", "chrome_trace", ".", "format_to_string", "(", "pretty", "=", "True", ")" ]
https://github.com/miyosuda/TensorFlowAndroidMNIST/blob/7b5a4603d2780a8a2834575706e9001977524007/jni-build/jni/include/tensorflow/python/client/timeline.py#L615-L630
hughperkins/tf-coriander
970d3df6c11400ad68405f22b0c42a52374e94ca
tensorflow/contrib/lookup/lookup_ops.py
python
LookupInterface.size
(self, name=None)
Compute the number of elements in this table.
Compute the number of elements in this table.
[ "Compute", "the", "number", "of", "elements", "in", "this", "table", "." ]
def size(self, name=None): """Compute the number of elements in this table.""" raise NotImplementedError
[ "def", "size", "(", "self", ",", "name", "=", "None", ")", ":", "raise", "NotImplementedError" ]
https://github.com/hughperkins/tf-coriander/blob/970d3df6c11400ad68405f22b0c42a52374e94ca/tensorflow/contrib/lookup/lookup_ops.py#L65-L67
Cisco-Talos/moflow
ed71dfb0540d9e0d7a4c72f0881b58958d573728
BAP-0.7-moflow/libtracewrap/libtrace/protobuf/python/google/protobuf/internal/containers.py
python
RepeatedScalarFieldContainer.__init__
(self, message_listener, type_checker)
Args: message_listener: A MessageListener implementation. The RepeatedScalarFieldContainer will call this object's Modified() method when it is modified. type_checker: A type_checkers.ValueChecker instance to run on elements inserted into this container.
Args: message_listener: A MessageListener implementation. The RepeatedScalarFieldContainer will call this object's Modified() method when it is modified. type_checker: A type_checkers.ValueChecker instance to run on elements inserted into this container.
[ "Args", ":", "message_listener", ":", "A", "MessageListener", "implementation", ".", "The", "RepeatedScalarFieldContainer", "will", "call", "this", "object", "s", "Modified", "()", "method", "when", "it", "is", "modified", ".", "type_checker", ":", "A", "type_checkers", ".", "ValueChecker", "instance", "to", "run", "on", "elements", "inserted", "into", "this", "container", "." ]
def __init__(self, message_listener, type_checker): """ Args: message_listener: A MessageListener implementation. The RepeatedScalarFieldContainer will call this object's Modified() method when it is modified. type_checker: A type_checkers.ValueChecker instance to run on elements inserted into this container. """ super(RepeatedScalarFieldContainer, self).__init__(message_listener) self._type_checker = type_checker
[ "def", "__init__", "(", "self", ",", "message_listener", ",", "type_checker", ")", ":", "super", "(", "RepeatedScalarFieldContainer", ",", "self", ")", ".", "__init__", "(", "message_listener", ")", "self", ".", "_type_checker", "=", "type_checker" ]
https://github.com/Cisco-Talos/moflow/blob/ed71dfb0540d9e0d7a4c72f0881b58958d573728/BAP-0.7-moflow/libtracewrap/libtrace/protobuf/python/google/protobuf/internal/containers.py#L92-L102
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/tools/Editra/src/extern/aui/auibook.py
python
CommandNotebookEvent.GetDragSource
(self)
return self.drag_source
Returns the drag and drop source.
Returns the drag and drop source.
[ "Returns", "the", "drag", "and", "drop", "source", "." ]
def GetDragSource(self): """ Returns the drag and drop source. """ return self.drag_source
[ "def", "GetDragSource", "(", "self", ")", ":", "return", "self", ".", "drag_source" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/src/extern/aui/auibook.py#L434-L437
Netflix/NfWebCrypto
499faf4eb9f9ccf0b21dc728e974970f54bd6c52
plugin/ppapi/ppapi/native_client/src/untrusted/pnacl_support_extension/pnacl_component_crx_gen.py
python
CopyFlattenDirsAndPrefix
(src_dir, arch, dest_dir)
Copy files from src_dir to dest_dir. When copying, also rename the files such that they match the white-listing pattern in chrome/browser/nacl_host/pnacl_file_host.cc.
Copy files from src_dir to dest_dir.
[ "Copy", "files", "from", "src_dir", "to", "dest_dir", "." ]
def CopyFlattenDirsAndPrefix(src_dir, arch, dest_dir): """ Copy files from src_dir to dest_dir. When copying, also rename the files such that they match the white-listing pattern in chrome/browser/nacl_host/pnacl_file_host.cc. """ for (root, dirs, files) in os.walk(src_dir, followlinks=True): for f in files: # Assume a flat directory. assert (f == os.path.basename(f)) full_name = J(root, f) target_name = UseWhitelistedChars(f, arch) shutil.copy2(full_name, J(dest_dir, target_name))
[ "def", "CopyFlattenDirsAndPrefix", "(", "src_dir", ",", "arch", ",", "dest_dir", ")", ":", "for", "(", "root", ",", "dirs", ",", "files", ")", "in", "os", ".", "walk", "(", "src_dir", ",", "followlinks", "=", "True", ")", ":", "for", "f", "in", "files", ":", "# Assume a flat directory.", "assert", "(", "f", "==", "os", ".", "path", ".", "basename", "(", "f", ")", ")", "full_name", "=", "J", "(", "root", ",", "f", ")", "target_name", "=", "UseWhitelistedChars", "(", "f", ",", "arch", ")", "shutil", ".", "copy2", "(", "full_name", ",", "J", "(", "dest_dir", ",", "target_name", ")", ")" ]
https://github.com/Netflix/NfWebCrypto/blob/499faf4eb9f9ccf0b21dc728e974970f54bd6c52/plugin/ppapi/ppapi/native_client/src/untrusted/pnacl_support_extension/pnacl_component_crx_gen.py#L498-L510
facebookincubator/BOLT
88c70afe9d388ad430cc150cc158641701397f70
clang/tools/scan-build-py/lib/libscanbuild/analyze.py
python
create_global_ctu_extdef_map
(extdef_map_lines)
return mangled_ast_pairs
Takes iterator of individual external definition maps and creates a global map keeping only unique names. We leave conflicting names out of CTU. :param extdef_map_lines: Contains the id of a definition (mangled name) and the originating source (the corresponding AST file) name. :type extdef_map_lines: Iterator of str. :returns: Mangled name - AST file pairs. :rtype: List of (str, str) tuples.
Takes iterator of individual external definition maps and creates a global map keeping only unique names. We leave conflicting names out of CTU.
[ "Takes", "iterator", "of", "individual", "external", "definition", "maps", "and", "creates", "a", "global", "map", "keeping", "only", "unique", "names", ".", "We", "leave", "conflicting", "names", "out", "of", "CTU", "." ]
def create_global_ctu_extdef_map(extdef_map_lines): """ Takes iterator of individual external definition maps and creates a global map keeping only unique names. We leave conflicting names out of CTU. :param extdef_map_lines: Contains the id of a definition (mangled name) and the originating source (the corresponding AST file) name. :type extdef_map_lines: Iterator of str. :returns: Mangled name - AST file pairs. :rtype: List of (str, str) tuples. """ mangled_to_asts = defaultdict(set) for line in extdef_map_lines: mangled_name, ast_file = line.strip().split(' ', 1) mangled_to_asts[mangled_name].add(ast_file) mangled_ast_pairs = [] for mangled_name, ast_files in mangled_to_asts.items(): if len(ast_files) == 1: mangled_ast_pairs.append((mangled_name, next(iter(ast_files)))) return mangled_ast_pairs
[ "def", "create_global_ctu_extdef_map", "(", "extdef_map_lines", ")", ":", "mangled_to_asts", "=", "defaultdict", "(", "set", ")", "for", "line", "in", "extdef_map_lines", ":", "mangled_name", ",", "ast_file", "=", "line", ".", "strip", "(", ")", ".", "split", "(", "' '", ",", "1", ")", "mangled_to_asts", "[", "mangled_name", "]", ".", "add", "(", "ast_file", ")", "mangled_ast_pairs", "=", "[", "]", "for", "mangled_name", ",", "ast_files", "in", "mangled_to_asts", ".", "items", "(", ")", ":", "if", "len", "(", "ast_files", ")", "==", "1", ":", "mangled_ast_pairs", ".", "append", "(", "(", "mangled_name", ",", "next", "(", "iter", "(", "ast_files", ")", ")", ")", ")", "return", "mangled_ast_pairs" ]
https://github.com/facebookincubator/BOLT/blob/88c70afe9d388ad430cc150cc158641701397f70/clang/tools/scan-build-py/lib/libscanbuild/analyze.py#L139-L163
genn-team/genn
75e1eb218cafa228bf36ae4613d1ce26e877b12c
pygenn/genn_model.py
python
GeNNModel.timestep
(self)
return self._slm.get_timestep()
Simulation time step
Simulation time step
[ "Simulation", "time", "step" ]
def timestep(self): """Simulation time step""" return self._slm.get_timestep()
[ "def", "timestep", "(", "self", ")", ":", "return", "self", ".", "_slm", ".", "get_timestep", "(", ")" ]
https://github.com/genn-team/genn/blob/75e1eb218cafa228bf36ae4613d1ce26e877b12c/pygenn/genn_model.py#L284-L286
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/cuda/random.py
python
xoroshiro128p_uniform_float64
(states, index)
return uint64_to_unit_float64(xoroshiro128p_next(states, index))
Return a float64 in range [0.0, 1.0) and advance ``states[index]``. :type states: 1D array, dtype=xoroshiro128p_dtype :param states: array of RNG states :type index: int64 :param index: offset in states to update :rtype: float64
Return a float64 in range [0.0, 1.0) and advance ``states[index]``.
[ "Return", "a", "float64", "in", "range", "[", "0", ".", "0", "1", ".", "0", ")", "and", "advance", "states", "[", "index", "]", "." ]
def xoroshiro128p_uniform_float64(states, index): '''Return a float64 in range [0.0, 1.0) and advance ``states[index]``. :type states: 1D array, dtype=xoroshiro128p_dtype :param states: array of RNG states :type index: int64 :param index: offset in states to update :rtype: float64 ''' index = int64(index) return uint64_to_unit_float64(xoroshiro128p_next(states, index))
[ "def", "xoroshiro128p_uniform_float64", "(", "states", ",", "index", ")", ":", "index", "=", "int64", "(", "index", ")", "return", "uint64_to_unit_float64", "(", "xoroshiro128p_next", "(", "states", ",", "index", ")", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/cuda/random.py#L150-L160
mantidproject/mantid
03deeb89254ec4289edb8771e0188c2090a02f32
Framework/PythonInterface/mantid/plots/utility.py
python
convert_color_to_hex
(color)
Convert a matplotlib color to its hex form
Convert a matplotlib color to its hex form
[ "Convert", "a", "matplotlib", "color", "to", "its", "hex", "form" ]
def convert_color_to_hex(color): """Convert a matplotlib color to its hex form""" try: return colors.cnames[color] except (KeyError, TypeError): rgb = colors.colorConverter.to_rgb(color) return colors.rgb2hex(rgb)
[ "def", "convert_color_to_hex", "(", "color", ")", ":", "try", ":", "return", "colors", ".", "cnames", "[", "color", "]", "except", "(", "KeyError", ",", "TypeError", ")", ":", "rgb", "=", "colors", ".", "colorConverter", ".", "to_rgb", "(", "color", ")", "return", "colors", ".", "rgb2hex", "(", "rgb", ")" ]
https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/Framework/PythonInterface/mantid/plots/utility.py#L259-L265
ChromiumWebApps/chromium
c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7
build/android/buildbot/bb_annotations.py
python
PrintSummaryText
(msg)
Appends |msg| to main build summary. Visible from waterfall. Args: msg: String to be appended.
Appends |msg| to main build summary. Visible from waterfall.
[ "Appends", "|msg|", "to", "main", "build", "summary", ".", "Visible", "from", "waterfall", "." ]
def PrintSummaryText(msg): """Appends |msg| to main build summary. Visible from waterfall. Args: msg: String to be appended. """ print '@@@STEP_SUMMARY_TEXT@%s@@@' % msg
[ "def", "PrintSummaryText", "(", "msg", ")", ":", "print", "'@@@STEP_SUMMARY_TEXT@%s@@@'", "%", "msg" ]
https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/build/android/buildbot/bb_annotations.py#L26-L32
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/tkinter/__init__.py
python
Canvas.delete
(self, *args)
Delete items identified by all tag or ids contained in ARGS.
Delete items identified by all tag or ids contained in ARGS.
[ "Delete", "items", "identified", "by", "all", "tag", "or", "ids", "contained", "in", "ARGS", "." ]
def delete(self, *args): """Delete items identified by all tag or ids contained in ARGS.""" self.tk.call((self._w, 'delete') + args)
[ "def", "delete", "(", "self", ",", "*", "args", ")", ":", "self", ".", "tk", ".", "call", "(", "(", "self", ".", "_w", ",", "'delete'", ")", "+", "args", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/tkinter/__init__.py#L2512-L2514
facebook/openr
ed38bdfd6bf290084bfab4821b59f83e7b59315d
build/fbcode_builder/getdeps/subcmd.py
python
add_subcommands
(parser, common_args, cmd_table=CmdTable)
Register parsers for the defined commands with the provided parser
Register parsers for the defined commands with the provided parser
[ "Register", "parsers", "for", "the", "defined", "commands", "with", "the", "provided", "parser" ]
def add_subcommands(parser, common_args, cmd_table=CmdTable): """Register parsers for the defined commands with the provided parser""" for cls in cmd_table: command = cls() command_parser = parser.add_parser( command.NAME, help=command.HELP, parents=[common_args] ) command.setup_parser(command_parser) command_parser.set_defaults(func=command.run)
[ "def", "add_subcommands", "(", "parser", ",", "common_args", ",", "cmd_table", "=", "CmdTable", ")", ":", "for", "cls", "in", "cmd_table", ":", "command", "=", "cls", "(", ")", "command_parser", "=", "parser", ".", "add_parser", "(", "command", ".", "NAME", ",", "help", "=", "command", ".", "HELP", ",", "parents", "=", "[", "common_args", "]", ")", "command", ".", "setup_parser", "(", "command_parser", ")", "command_parser", ".", "set_defaults", "(", "func", "=", "command", ".", "run", ")" ]
https://github.com/facebook/openr/blob/ed38bdfd6bf290084bfab4821b59f83e7b59315d/build/fbcode_builder/getdeps/subcmd.py#L24-L32
FreeCAD/FreeCAD
ba42231b9c6889b89e064d6d563448ed81e376ec
src/Mod/Drawing/DrawingPatterns.py
python
getPatternNames
()
return Patterns.keys()
getPatternNames : returns available pattern names
getPatternNames : returns available pattern names
[ "getPatternNames", ":", "returns", "available", "pattern", "names" ]
def getPatternNames(): """getPatternNames : returns available pattern names""" return Patterns.keys()
[ "def", "getPatternNames", "(", ")", ":", "return", "Patterns", ".", "keys", "(", ")" ]
https://github.com/FreeCAD/FreeCAD/blob/ba42231b9c6889b89e064d6d563448ed81e376ec/src/Mod/Drawing/DrawingPatterns.py#L285-L289
zju3dv/clean-pvnet
5870c509e3cc205e1bb28910a7b1a9a3c8add9a8
lib/utils/pysixd/transform.py
python
random_quaternion
(rand=None)
return numpy.array([numpy.cos(t2)*r2, numpy.sin(t1)*r1, numpy.cos(t1)*r1, numpy.sin(t2)*r2])
Return uniform random unit quaternion. rand: array like or None Three independent random variables that are uniformly distributed between 0 and 1. >>> q = random_quaternion() >>> numpy.allclose(1, vector_norm(q)) True >>> q = random_quaternion(numpy.random.random(3)) >>> len(q.shape), q.shape[0]==4 (1, True)
Return uniform random unit quaternion.
[ "Return", "uniform", "random", "unit", "quaternion", "." ]
def random_quaternion(rand=None): """Return uniform random unit quaternion. rand: array like or None Three independent random variables that are uniformly distributed between 0 and 1. >>> q = random_quaternion() >>> numpy.allclose(1, vector_norm(q)) True >>> q = random_quaternion(numpy.random.random(3)) >>> len(q.shape), q.shape[0]==4 (1, True) """ if rand is None: rand = numpy.random.rand(3) else: assert len(rand) == 3 r1 = numpy.sqrt(1.0 - rand[0]) r2 = numpy.sqrt(rand[0]) pi2 = math.pi * 2.0 t1 = pi2 * rand[1] t2 = pi2 * rand[2] return numpy.array([numpy.cos(t2)*r2, numpy.sin(t1)*r1, numpy.cos(t1)*r1, numpy.sin(t2)*r2])
[ "def", "random_quaternion", "(", "rand", "=", "None", ")", ":", "if", "rand", "is", "None", ":", "rand", "=", "numpy", ".", "random", ".", "rand", "(", "3", ")", "else", ":", "assert", "len", "(", "rand", ")", "==", "3", "r1", "=", "numpy", ".", "sqrt", "(", "1.0", "-", "rand", "[", "0", "]", ")", "r2", "=", "numpy", ".", "sqrt", "(", "rand", "[", "0", "]", ")", "pi2", "=", "math", ".", "pi", "*", "2.0", "t1", "=", "pi2", "*", "rand", "[", "1", "]", "t2", "=", "pi2", "*", "rand", "[", "2", "]", "return", "numpy", ".", "array", "(", "[", "numpy", ".", "cos", "(", "t2", ")", "*", "r2", ",", "numpy", ".", "sin", "(", "t1", ")", "*", "r1", ",", "numpy", ".", "cos", "(", "t1", ")", "*", "r1", ",", "numpy", ".", "sin", "(", "t2", ")", "*", "r2", "]", ")" ]
https://github.com/zju3dv/clean-pvnet/blob/5870c509e3cc205e1bb28910a7b1a9a3c8add9a8/lib/utils/pysixd/transform.py#L1463-L1488
FlightGear/flightgear
cf4801e11c5b69b107f87191584eefda3c5a9b26
scripts/python/FlightGear.py
python
FlightGear.__getitem__
(self,key)
Get a FlightGear property value. Where possible the value is converted to the equivalent Python type.
Get a FlightGear property value. Where possible the value is converted to the equivalent Python type.
[ "Get", "a", "FlightGear", "property", "value", ".", "Where", "possible", "the", "value", "is", "converted", "to", "the", "equivalent", "Python", "type", "." ]
def __getitem__(self,key): """Get a FlightGear property value. Where possible the value is converted to the equivalent Python type. """ s = self.telnet.get(key)[0] match = re.compile( r'[^=]*=\s*\'([^\']*)\'\s*([^\r]*)\r').match( s ) if not match: return None value,type = match.groups() #value = match.group(1) #type = match.group(2) if value == '': return None if type == '(double)': return float(value) elif type == '(int)': return int(value) elif type == '(bool)': if value == 'true': return 1 else: return 0 else: return value
[ "def", "__getitem__", "(", "self", ",", "key", ")", ":", "s", "=", "self", ".", "telnet", ".", "get", "(", "key", ")", "[", "0", "]", "match", "=", "re", ".", "compile", "(", "r'[^=]*=\\s*\\'([^\\']*)\\'\\s*([^\\r]*)\\r'", ")", ".", "match", "(", "s", ")", "if", "not", "match", ":", "return", "None", "value", ",", "type", "=", "match", ".", "groups", "(", ")", "#value = match.group(1)", "#type = match.group(2)", "if", "value", "==", "''", ":", "return", "None", "if", "type", "==", "'(double)'", ":", "return", "float", "(", "value", ")", "elif", "type", "==", "'(int)'", ":", "return", "int", "(", "value", ")", "elif", "type", "==", "'(bool)'", ":", "if", "value", "==", "'true'", ":", "return", "1", "else", ":", "return", "0", "else", ":", "return", "value" ]
https://github.com/FlightGear/flightgear/blob/cf4801e11c5b69b107f87191584eefda3c5a9b26/scripts/python/FlightGear.py#L142-L166
nasa/fprime
595cf3682d8365943d86c1a6fe7c78f0a116acf0
cmake/docs/docs.py
python
process_file
(file_name, outdir)
Process a file
Process a file
[ "Process", "a", "file" ]
def process_file(file_name, outdir): """Process a file""" # Read a line, and output it out_fn = file_name if os.path.basename(out_fn) == "CMakeLists.txt": out_fn = os.path.dirname(file_name) out_fn = out_fn.replace(".cmake", "").replace(".template", "") + ( "-template.md" if out_fn.endswith(".template") else ".md" ) if out_fn == file_name: raise AssertionError("File collision imminent") relative_fn = out_fn out_fn = os.path.join(outdir, out_fn) os.makedirs(os.path.dirname(out_fn), exist_ok=True) # Open both files, and loop over all the lines reading and writing each print("[{}]({})".format(os.path.basename(out_fn).replace(".md", ""), relative_fn)) with open(file_name, "r") as in_file_handle: with open(out_fn, "w") as out_file_handle: state = DocState.SEARCH next_state = DocState.SEARCH out_file_handle.write( "**Note:** auto-generated from comments in: {0}\n\n".format(file_name) ) for line in in_file_handle.readlines(): state = next_state next_state = state # If we see '####' the next state changes if line.startswith("####") and state == DocState.SEARCH: next_state = DocState.HEADER elif line.startswith("####"): next_state = DocState.SEARCH line = LINE_RE.sub("", line).rstrip() # print("State: ", state, "Next State:", next_state) # print(line) # Now output, if not searching, and not blank and not searching if next_state == DocState.SEARCH: if state == DocState.CLOSING: out_file_handle.write("\n\n") continue if next_state == DocState.HEADER: out_file_handle.write("## ") next_state = DocState.CLOSING # Header printed continue out_file_handle.write(line) out_file_handle.write("\n")
[ "def", "process_file", "(", "file_name", ",", "outdir", ")", ":", "# Read a line, and output it", "out_fn", "=", "file_name", "if", "os", ".", "path", ".", "basename", "(", "out_fn", ")", "==", "\"CMakeLists.txt\"", ":", "out_fn", "=", "os", ".", "path", ".", "dirname", "(", "file_name", ")", "out_fn", "=", "out_fn", ".", "replace", "(", "\".cmake\"", ",", "\"\"", ")", ".", "replace", "(", "\".template\"", ",", "\"\"", ")", "+", "(", "\"-template.md\"", "if", "out_fn", ".", "endswith", "(", "\".template\"", ")", "else", "\".md\"", ")", "if", "out_fn", "==", "file_name", ":", "raise", "AssertionError", "(", "\"File collision imminent\"", ")", "relative_fn", "=", "out_fn", "out_fn", "=", "os", ".", "path", ".", "join", "(", "outdir", ",", "out_fn", ")", "os", ".", "makedirs", "(", "os", ".", "path", ".", "dirname", "(", "out_fn", ")", ",", "exist_ok", "=", "True", ")", "# Open both files, and loop over all the lines reading and writing each", "print", "(", "\"[{}]({})\"", ".", "format", "(", "os", ".", "path", ".", "basename", "(", "out_fn", ")", ".", "replace", "(", "\".md\"", ",", "\"\"", ")", ",", "relative_fn", ")", ")", "with", "open", "(", "file_name", ",", "\"r\"", ")", "as", "in_file_handle", ":", "with", "open", "(", "out_fn", ",", "\"w\"", ")", "as", "out_file_handle", ":", "state", "=", "DocState", ".", "SEARCH", "next_state", "=", "DocState", ".", "SEARCH", "out_file_handle", ".", "write", "(", "\"**Note:** auto-generated from comments in: {0}\\n\\n\"", ".", "format", "(", "file_name", ")", ")", "for", "line", "in", "in_file_handle", ".", "readlines", "(", ")", ":", "state", "=", "next_state", "next_state", "=", "state", "# If we see '####' the next state changes", "if", "line", ".", "startswith", "(", "\"####\"", ")", "and", "state", "==", "DocState", ".", "SEARCH", ":", "next_state", "=", "DocState", ".", "HEADER", "elif", "line", ".", "startswith", "(", "\"####\"", ")", ":", "next_state", "=", "DocState", ".", "SEARCH", "line", "=", "LINE_RE", ".", "sub", "(", "\"\"", ",", "line", ")", ".", "rstrip", "(", ")", "# print(\"State: \", state, \"Next State:\", next_state)", "# print(line)", "# Now output, if not searching, and not blank and not searching", "if", "next_state", "==", "DocState", ".", "SEARCH", ":", "if", "state", "==", "DocState", ".", "CLOSING", ":", "out_file_handle", ".", "write", "(", "\"\\n\\n\"", ")", "continue", "if", "next_state", "==", "DocState", ".", "HEADER", ":", "out_file_handle", ".", "write", "(", "\"## \"", ")", "next_state", "=", "DocState", ".", "CLOSING", "# Header printed", "continue", "out_file_handle", ".", "write", "(", "line", ")", "out_file_handle", ".", "write", "(", "\"\\n\"", ")" ]
https://github.com/nasa/fprime/blob/595cf3682d8365943d86c1a6fe7c78f0a116acf0/cmake/docs/docs.py#L61-L105
desura/Desurium
7d218139682cf1ddcc64beffdcecc984955436f0
third_party/courgette/tools/file_util.py
python
read_file
(name, normalize = True)
Function for reading a file.
Function for reading a file.
[ "Function", "for", "reading", "a", "file", "." ]
def read_file(name, normalize = True): """ Function for reading a file. """ try: f = open(name, 'r') # read the data data = f.read() if normalize: # normalize line endings data = data.replace("\r\n", "\n") return data except IOError, (errno, strerror): sys.stderr.write('Failed to read file '+filename+': '+strerror) raise else: f.close()
[ "def", "read_file", "(", "name", ",", "normalize", "=", "True", ")", ":", "try", ":", "f", "=", "open", "(", "name", ",", "'r'", ")", "# read the data", "data", "=", "f", ".", "read", "(", ")", "if", "normalize", ":", "# normalize line endings", "data", "=", "data", ".", "replace", "(", "\"\\r\\n\"", ",", "\"\\n\"", ")", "return", "data", "except", "IOError", ",", "(", "errno", ",", "strerror", ")", ":", "sys", ".", "stderr", ".", "write", "(", "'Failed to read file '", "+", "filename", "+", "': '", "+", "strerror", ")", "raise", "else", ":", "f", ".", "close", "(", ")" ]
https://github.com/desura/Desurium/blob/7d218139682cf1ddcc64beffdcecc984955436f0/third_party/courgette/tools/file_util.py#L10-L24
BlzFans/wke
b0fa21158312e40c5fbd84682d643022b6c34a93
cygwin/lib/python2.6/mailbox.py
python
_singlefileMailbox.__init__
(self, path, factory=None, create=True)
Initialize a single-file mailbox.
Initialize a single-file mailbox.
[ "Initialize", "a", "single", "-", "file", "mailbox", "." ]
def __init__(self, path, factory=None, create=True): """Initialize a single-file mailbox.""" Mailbox.__init__(self, path, factory, create) try: f = open(self._path, 'rb+') except IOError, e: if e.errno == errno.ENOENT: if create: f = open(self._path, 'wb+') else: raise NoSuchMailboxError(self._path) elif e.errno == errno.EACCES: f = open(self._path, 'rb') else: raise self._file = f self._toc = None self._next_key = 0 self._pending = False # No changes require rewriting the file. self._locked = False self._file_length = None
[ "def", "__init__", "(", "self", ",", "path", ",", "factory", "=", "None", ",", "create", "=", "True", ")", ":", "Mailbox", ".", "__init__", "(", "self", ",", "path", ",", "factory", ",", "create", ")", "try", ":", "f", "=", "open", "(", "self", ".", "_path", ",", "'rb+'", ")", "except", "IOError", ",", "e", ":", "if", "e", ".", "errno", "==", "errno", ".", "ENOENT", ":", "if", "create", ":", "f", "=", "open", "(", "self", ".", "_path", ",", "'wb+'", ")", "else", ":", "raise", "NoSuchMailboxError", "(", "self", ".", "_path", ")", "elif", "e", ".", "errno", "==", "errno", ".", "EACCES", ":", "f", "=", "open", "(", "self", ".", "_path", ",", "'rb'", ")", "else", ":", "raise", "self", ".", "_file", "=", "f", "self", ".", "_toc", "=", "None", "self", ".", "_next_key", "=", "0", "self", ".", "_pending", "=", "False", "# No changes require rewriting the file.", "self", ".", "_locked", "=", "False", "self", ".", "_file_length", "=", "None" ]
https://github.com/BlzFans/wke/blob/b0fa21158312e40c5fbd84682d643022b6c34a93/cygwin/lib/python2.6/mailbox.py#L504-L524
Kitware/ParaView
f760af9124ff4634b23ebbeab95a4f56e0261955
Examples/Catalyst/CxxMultiPieceExample/SampleScripts/feslicescript.py
python
DoCoProcessing
(datadescription)
Callback to do co-processing for current timestep
Callback to do co-processing for current timestep
[ "Callback", "to", "do", "co", "-", "processing", "for", "current", "timestep" ]
def DoCoProcessing(datadescription): "Callback to do co-processing for current timestep" global coprocessor # Update the coprocessor by providing it the newly generated simulation data. # If the pipeline hasn't been setup yet, this will setup the pipeline. coprocessor.UpdateProducers(datadescription) # Write output data, if appropriate. coprocessor.WriteData(datadescription); # Write image capture (Last arg: rescale lookup table), if appropriate. coprocessor.WriteImages(datadescription, rescale_lookuptable=False) # Live Visualization, if enabled. coprocessor.DoLiveVisualization(datadescription, "localhost", 22222)
[ "def", "DoCoProcessing", "(", "datadescription", ")", ":", "global", "coprocessor", "# Update the coprocessor by providing it the newly generated simulation data.", "# If the pipeline hasn't been setup yet, this will setup the pipeline.", "coprocessor", ".", "UpdateProducers", "(", "datadescription", ")", "# Write output data, if appropriate.", "coprocessor", ".", "WriteData", "(", "datadescription", ")", "# Write image capture (Last arg: rescale lookup table), if appropriate.", "coprocessor", ".", "WriteImages", "(", "datadescription", ",", "rescale_lookuptable", "=", "False", ")", "# Live Visualization, if enabled.", "coprocessor", ".", "DoLiveVisualization", "(", "datadescription", ",", "\"localhost\"", ",", "22222", ")" ]
https://github.com/Kitware/ParaView/blob/f760af9124ff4634b23ebbeab95a4f56e0261955/Examples/Catalyst/CxxMultiPieceExample/SampleScripts/feslicescript.py#L78-L93
miyosuda/TensorFlowAndroidDemo
35903e0221aa5f109ea2dbef27f20b52e317f42d
jni-build/jni/include/external/bazel_tools/third_party/py/gflags/gflags2man.py
python
ProgramInfo.Filter
(self)
Filter parsed data to create derived fields.
Filter parsed data to create derived fields.
[ "Filter", "parsed", "data", "to", "create", "derived", "fields", "." ]
def Filter(self): """Filter parsed data to create derived fields.""" if not self.desc: self.short_desc = '' return for i in range(len(self.desc)): # replace full path with name if self.desc[i].find(self.executable) >= 0: self.desc[i] = self.desc[i].replace(self.executable, self.name) self.short_desc = self.desc[0] word_list = self.short_desc.split(' ') all_names = [ self.name, self.short_name, ] # Since the short_desc is always listed right after the name, # trim it from the short_desc while word_list and (word_list[0] in all_names or word_list[0].lower() in all_names): del word_list[0] self.short_desc = '' # signal need to reconstruct if not self.short_desc and word_list: self.short_desc = ' '.join(word_list)
[ "def", "Filter", "(", "self", ")", ":", "if", "not", "self", ".", "desc", ":", "self", ".", "short_desc", "=", "''", "return", "for", "i", "in", "range", "(", "len", "(", "self", ".", "desc", ")", ")", ":", "# replace full path with name", "if", "self", ".", "desc", "[", "i", "]", ".", "find", "(", "self", ".", "executable", ")", ">=", "0", ":", "self", ".", "desc", "[", "i", "]", "=", "self", ".", "desc", "[", "i", "]", ".", "replace", "(", "self", ".", "executable", ",", "self", ".", "name", ")", "self", ".", "short_desc", "=", "self", ".", "desc", "[", "0", "]", "word_list", "=", "self", ".", "short_desc", ".", "split", "(", "' '", ")", "all_names", "=", "[", "self", ".", "name", ",", "self", ".", "short_name", ",", "]", "# Since the short_desc is always listed right after the name,", "# trim it from the short_desc", "while", "word_list", "and", "(", "word_list", "[", "0", "]", "in", "all_names", "or", "word_list", "[", "0", "]", ".", "lower", "(", ")", "in", "all_names", ")", ":", "del", "word_list", "[", "0", "]", "self", ".", "short_desc", "=", "''", "# signal need to reconstruct", "if", "not", "self", ".", "short_desc", "and", "word_list", ":", "self", ".", "short_desc", "=", "' '", ".", "join", "(", "word_list", ")" ]
https://github.com/miyosuda/TensorFlowAndroidDemo/blob/35903e0221aa5f109ea2dbef27f20b52e317f42d/jni-build/jni/include/external/bazel_tools/third_party/py/gflags/gflags2man.py#L411-L431
psnonis/FinBERT
c0c555d833a14e2316a3701e59c0b5156f804b4e
bert-gpu/tokenization.py
python
printable_text
(text)
Returns text encoded in a way suitable for print or `tf.logging`.
Returns text encoded in a way suitable for print or `tf.logging`.
[ "Returns", "text", "encoded", "in", "a", "way", "suitable", "for", "print", "or", "tf", ".", "logging", "." ]
def printable_text(text): """Returns text encoded in a way suitable for print or `tf.logging`.""" # These functions want `str` for both Python2 and Python3, but in one case # it's a Unicode string and in the other it's a byte string. if six.PY3: if isinstance(text, str): return text elif isinstance(text, bytes): return text.decode("utf-8", "ignore") else: raise ValueError("Unsupported string type: %s" % (type(text))) elif six.PY2: if isinstance(text, str): return text elif isinstance(text, unicode): return text.encode("utf-8") else: raise ValueError("Unsupported string type: %s" % (type(text))) else: raise ValueError("Not running on Python2 or Python 3?")
[ "def", "printable_text", "(", "text", ")", ":", "# These functions want `str` for both Python2 and Python3, but in one case", "# it's a Unicode string and in the other it's a byte string.", "if", "six", ".", "PY3", ":", "if", "isinstance", "(", "text", ",", "str", ")", ":", "return", "text", "elif", "isinstance", "(", "text", ",", "bytes", ")", ":", "return", "text", ".", "decode", "(", "\"utf-8\"", ",", "\"ignore\"", ")", "else", ":", "raise", "ValueError", "(", "\"Unsupported string type: %s\"", "%", "(", "type", "(", "text", ")", ")", ")", "elif", "six", ".", "PY2", ":", "if", "isinstance", "(", "text", ",", "str", ")", ":", "return", "text", "elif", "isinstance", "(", "text", ",", "unicode", ")", ":", "return", "text", ".", "encode", "(", "\"utf-8\"", ")", "else", ":", "raise", "ValueError", "(", "\"Unsupported string type: %s\"", "%", "(", "type", "(", "text", ")", ")", ")", "else", ":", "raise", "ValueError", "(", "\"Not running on Python2 or Python 3?\"", ")" ]
https://github.com/psnonis/FinBERT/blob/c0c555d833a14e2316a3701e59c0b5156f804b4e/bert-gpu/tokenization.py#L98-L118
pytorch/xla
93174035e8149d5d03cee446486de861f56493e1
torch_xla/distributed/cluster.py
python
ClusterResolver.__init__
(self, tpu, vms=None, zone=None, project=None)
Creates a new ClusterResolver object.
Creates a new ClusterResolver object.
[ "Creates", "a", "new", "ClusterResolver", "object", "." ]
def __init__(self, tpu, vms=None, zone=None, project=None): """Creates a new ClusterResolver object.""" if not tpu: raise ValueError('tpu must be a non-empty string') if vms: if not isinstance(vms, list) or len(vms) == 0: raise ValueError('vms must be a non-empty list if provided') self._tpus = tpu if isinstance(tpu, list) else [tpu] self._vms = vms self._zone = zone self._project = project self._tpuvm_mode = None self._tpuvm_mode_with_remote_coordinator = None self._set_tpuvm_mode() self._compute_service = discovery.build( 'compute', 'v1', credentials=GoogleCredentials.get_application_default(), cache_discovery=False) if project is None: self._project = ClusterResolver.get_instance_metadata( 'project/project-id') if zone is None: zone_path = ClusterResolver.get_instance_metadata('instance/zone') self._zone = ClusterResolver._parse_resource_url(zone_path, 'zones') self._vm_master = ClusterResolver.get_instance_metadata('instance/name')
[ "def", "__init__", "(", "self", ",", "tpu", ",", "vms", "=", "None", ",", "zone", "=", "None", ",", "project", "=", "None", ")", ":", "if", "not", "tpu", ":", "raise", "ValueError", "(", "'tpu must be a non-empty string'", ")", "if", "vms", ":", "if", "not", "isinstance", "(", "vms", ",", "list", ")", "or", "len", "(", "vms", ")", "==", "0", ":", "raise", "ValueError", "(", "'vms must be a non-empty list if provided'", ")", "self", ".", "_tpus", "=", "tpu", "if", "isinstance", "(", "tpu", ",", "list", ")", "else", "[", "tpu", "]", "self", ".", "_vms", "=", "vms", "self", ".", "_zone", "=", "zone", "self", ".", "_project", "=", "project", "self", ".", "_tpuvm_mode", "=", "None", "self", ".", "_tpuvm_mode_with_remote_coordinator", "=", "None", "self", ".", "_set_tpuvm_mode", "(", ")", "self", ".", "_compute_service", "=", "discovery", ".", "build", "(", "'compute'", ",", "'v1'", ",", "credentials", "=", "GoogleCredentials", ".", "get_application_default", "(", ")", ",", "cache_discovery", "=", "False", ")", "if", "project", "is", "None", ":", "self", ".", "_project", "=", "ClusterResolver", ".", "get_instance_metadata", "(", "'project/project-id'", ")", "if", "zone", "is", "None", ":", "zone_path", "=", "ClusterResolver", ".", "get_instance_metadata", "(", "'instance/zone'", ")", "self", ".", "_zone", "=", "ClusterResolver", ".", "_parse_resource_url", "(", "zone_path", ",", "'zones'", ")", "self", ".", "_vm_master", "=", "ClusterResolver", ".", "get_instance_metadata", "(", "'instance/name'", ")" ]
https://github.com/pytorch/xla/blob/93174035e8149d5d03cee446486de861f56493e1/torch_xla/distributed/cluster.py#L253-L282
apache/incubator-mxnet
f03fb23f1d103fec9541b5ae59ee06b1734a51d9
python/mxnet/recordio.py
python
pack
(header, s)
return s
Pack a string into MXImageRecord. Parameters ---------- header : IRHeader Header of the image record. ``header.label`` can be a number or an array. See more detail in ``IRHeader``. s : str Raw image string to be packed. Returns ------- s : str The packed string. Examples -------- >>> label = 4 # label can also be a 1-D array, for example: label = [1,2,3] >>> id = 2574 >>> header = mx.recordio.IRHeader(0, label, id, 0) >>> with open(path, 'r') as file: ... s = file.read() >>> packed_s = mx.recordio.pack(header, s)
Pack a string into MXImageRecord.
[ "Pack", "a", "string", "into", "MXImageRecord", "." ]
def pack(header, s): """Pack a string into MXImageRecord. Parameters ---------- header : IRHeader Header of the image record. ``header.label`` can be a number or an array. See more detail in ``IRHeader``. s : str Raw image string to be packed. Returns ------- s : str The packed string. Examples -------- >>> label = 4 # label can also be a 1-D array, for example: label = [1,2,3] >>> id = 2574 >>> header = mx.recordio.IRHeader(0, label, id, 0) >>> with open(path, 'r') as file: ... s = file.read() >>> packed_s = mx.recordio.pack(header, s) """ header = IRHeader(*header) if isinstance(header.label, numbers.Number): header = header._replace(flag=0) else: label = np.asarray(header.label, dtype=np.float32) header = header._replace(flag=label.size, label=0) s = label.tostring() + s s = struct.pack(_IR_FORMAT, *header) + s return s
[ "def", "pack", "(", "header", ",", "s", ")", ":", "header", "=", "IRHeader", "(", "*", "header", ")", "if", "isinstance", "(", "header", ".", "label", ",", "numbers", ".", "Number", ")", ":", "header", "=", "header", ".", "_replace", "(", "flag", "=", "0", ")", "else", ":", "label", "=", "np", ".", "asarray", "(", "header", ".", "label", ",", "dtype", "=", "np", ".", "float32", ")", "header", "=", "header", ".", "_replace", "(", "flag", "=", "label", ".", "size", ",", "label", "=", "0", ")", "s", "=", "label", ".", "tostring", "(", ")", "+", "s", "s", "=", "struct", ".", "pack", "(", "_IR_FORMAT", ",", "*", "header", ")", "+", "s", "return", "s" ]
https://github.com/apache/incubator-mxnet/blob/f03fb23f1d103fec9541b5ae59ee06b1734a51d9/python/mxnet/recordio.py#L362-L395
CRYTEK/CRYENGINE
232227c59a220cbbd311576f0fbeba7bb53b2a8c
Editor/Python/windows/Lib/site-packages/pip/_vendor/ipaddress.py
python
v6_int_to_packed
(address)
Represent an address as 16 packed bytes in network (big-endian) order. Args: address: An integer representation of an IPv6 IP address. Returns: The integer address packed as 16 bytes in network (big-endian) order.
Represent an address as 16 packed bytes in network (big-endian) order.
[ "Represent", "an", "address", "as", "16", "packed", "bytes", "in", "network", "(", "big", "-", "endian", ")", "order", "." ]
def v6_int_to_packed(address): """Represent an address as 16 packed bytes in network (big-endian) order. Args: address: An integer representation of an IPv6 IP address. Returns: The integer address packed as 16 bytes in network (big-endian) order. """ try: return _compat_to_bytes(address, 16, 'big') except: raise ValueError("Address negative or too large for IPv6")
[ "def", "v6_int_to_packed", "(", "address", ")", ":", "try", ":", "return", "_compat_to_bytes", "(", "address", ",", "16", ",", "'big'", ")", "except", ":", "raise", "ValueError", "(", "\"Address negative or too large for IPv6\"", ")" ]
https://github.com/CRYTEK/CRYENGINE/blob/232227c59a220cbbd311576f0fbeba7bb53b2a8c/Editor/Python/windows/Lib/site-packages/pip/_vendor/ipaddress.py#L206-L219
waymo-research/waymo-open-dataset
5de359f3429e1496761790770868296140161b66
waymo_open_dataset/latency/examples/tensorflow/multiframe/wod_latency_submission/model.py
python
get_model
()
return tf.keras.Model(inputs=inp, outputs={'boxes': boxes, 'scores': scores})
Returns a basic PointNet detection model in Keras. Returns: Keras model that implements a PointNet that outputs 50 detections. Its input is a 1 x N x 6 float32 point cloud and it ouptuts a dictionary with the following key-value pairs: "boxes": 1 x N x 7 float32 array "scores": 1 x N float32 array
Returns a basic PointNet detection model in Keras.
[ "Returns", "a", "basic", "PointNet", "detection", "model", "in", "Keras", "." ]
def get_model(): """Returns a basic PointNet detection model in Keras. Returns: Keras model that implements a PointNet that outputs 50 detections. Its input is a 1 x N x 6 float32 point cloud and it ouptuts a dictionary with the following key-value pairs: "boxes": 1 x N x 7 float32 array "scores": 1 x N float32 array """ # (1, N, 6) inp = tf.keras.Input(shape=(None, 6)) # Run three per-point FC layers. feat = inp for i, layer_size in enumerate((128, 256, 512)): # (1, N, D) feat = tf.keras.layers.Dense(layer_size, activation='relu', name=f'linear_{i + 1}')(feat) # Run the global max pool and an FC layer on the global features. # (1, 512) global_feat = tf.keras.layers.GlobalMaxPool1D()(feat) global_feat = tf.keras.layers.Dense(512, activation='relu', name='global_mlp')(global_feat) # FC layers for each of the detection heads. Note that we regress each of the # 7 box dimensions separately since they require different activation # functions to constrain them to the appropriate ranges. num_boxes = 50 # (1, 50) center_x = tf.keras.layers.Dense(num_boxes, name='center_x')(global_feat) center_y = tf.keras.layers.Dense(num_boxes, name='center_y')(global_feat) center_z = tf.keras.layers.Dense(num_boxes, name='center_z')(global_feat) length = tf.keras.layers.Dense(num_boxes, activation='softplus', name='length')(global_feat) width = tf.keras.layers.Dense(num_boxes, activation='softplus', name='width')(global_feat) height = tf.keras.layers.Dense(num_boxes, activation='softplus', name='height')(global_feat) heading = np.pi * tf.keras.layers.Dense(num_boxes, activation='tanh', name='heading')(global_feat) scores = tf.keras.layers.Dense(num_boxes, activation='sigmoid', name='scores')(global_feat) # Combine the 7 box features into a single 1 x 50 x 7 box tensor. box_feats = [center_x, center_y, center_z, length, width, height, heading] reshape_layer = tf.keras.layers.Reshape((num_boxes, 1)) for i in range(len(box_feats)): box_feats[i] = reshape_layer(box_feats[i]) # (1, 50, 7) boxes = tf.keras.layers.Concatenate()(box_feats) return tf.keras.Model(inputs=inp, outputs={'boxes': boxes, 'scores': scores})
[ "def", "get_model", "(", ")", ":", "# (1, N, 6)", "inp", "=", "tf", ".", "keras", ".", "Input", "(", "shape", "=", "(", "None", ",", "6", ")", ")", "# Run three per-point FC layers.", "feat", "=", "inp", "for", "i", ",", "layer_size", "in", "enumerate", "(", "(", "128", ",", "256", ",", "512", ")", ")", ":", "# (1, N, D)", "feat", "=", "tf", ".", "keras", ".", "layers", ".", "Dense", "(", "layer_size", ",", "activation", "=", "'relu'", ",", "name", "=", "f'linear_{i + 1}'", ")", "(", "feat", ")", "# Run the global max pool and an FC layer on the global features.", "# (1, 512)", "global_feat", "=", "tf", ".", "keras", ".", "layers", ".", "GlobalMaxPool1D", "(", ")", "(", "feat", ")", "global_feat", "=", "tf", ".", "keras", ".", "layers", ".", "Dense", "(", "512", ",", "activation", "=", "'relu'", ",", "name", "=", "'global_mlp'", ")", "(", "global_feat", ")", "# FC layers for each of the detection heads. Note that we regress each of the", "# 7 box dimensions separately since they require different activation", "# functions to constrain them to the appropriate ranges.", "num_boxes", "=", "50", "# (1, 50)", "center_x", "=", "tf", ".", "keras", ".", "layers", ".", "Dense", "(", "num_boxes", ",", "name", "=", "'center_x'", ")", "(", "global_feat", ")", "center_y", "=", "tf", ".", "keras", ".", "layers", ".", "Dense", "(", "num_boxes", ",", "name", "=", "'center_y'", ")", "(", "global_feat", ")", "center_z", "=", "tf", ".", "keras", ".", "layers", ".", "Dense", "(", "num_boxes", ",", "name", "=", "'center_z'", ")", "(", "global_feat", ")", "length", "=", "tf", ".", "keras", ".", "layers", ".", "Dense", "(", "num_boxes", ",", "activation", "=", "'softplus'", ",", "name", "=", "'length'", ")", "(", "global_feat", ")", "width", "=", "tf", ".", "keras", ".", "layers", ".", "Dense", "(", "num_boxes", ",", "activation", "=", "'softplus'", ",", "name", "=", "'width'", ")", "(", "global_feat", ")", "height", "=", "tf", ".", "keras", ".", "layers", ".", "Dense", "(", "num_boxes", ",", "activation", "=", "'softplus'", ",", "name", "=", "'height'", ")", "(", "global_feat", ")", "heading", "=", "np", ".", "pi", "*", "tf", ".", "keras", ".", "layers", ".", "Dense", "(", "num_boxes", ",", "activation", "=", "'tanh'", ",", "name", "=", "'heading'", ")", "(", "global_feat", ")", "scores", "=", "tf", ".", "keras", ".", "layers", ".", "Dense", "(", "num_boxes", ",", "activation", "=", "'sigmoid'", ",", "name", "=", "'scores'", ")", "(", "global_feat", ")", "# Combine the 7 box features into a single 1 x 50 x 7 box tensor.", "box_feats", "=", "[", "center_x", ",", "center_y", ",", "center_z", ",", "length", ",", "width", ",", "height", ",", "heading", "]", "reshape_layer", "=", "tf", ".", "keras", ".", "layers", ".", "Reshape", "(", "(", "num_boxes", ",", "1", ")", ")", "for", "i", "in", "range", "(", "len", "(", "box_feats", ")", ")", ":", "box_feats", "[", "i", "]", "=", "reshape_layer", "(", "box_feats", "[", "i", "]", ")", "# (1, 50, 7)", "boxes", "=", "tf", ".", "keras", ".", "layers", ".", "Concatenate", "(", ")", "(", "box_feats", ")", "return", "tf", ".", "keras", ".", "Model", "(", "inputs", "=", "inp", ",", "outputs", "=", "{", "'boxes'", ":", "boxes", ",", "'scores'", ":", "scores", "}", ")" ]
https://github.com/waymo-research/waymo-open-dataset/blob/5de359f3429e1496761790770868296140161b66/waymo_open_dataset/latency/examples/tensorflow/multiframe/wod_latency_submission/model.py#L76-L129
mantidproject/mantid
03deeb89254ec4289edb8771e0188c2090a02f32
qt/python/mantidqtinterfaces/mantidqtinterfaces/HFIR_4Circle_Reduction/hfctables.py
python
SinglePtIntegrationTable.set_fwhm
(self, scan_number, pt_number, fwhm)
return
:param pt_number: :param fwhm: :return:
[]
def set_fwhm(self, scan_number, pt_number, fwhm): """ :param pt_number: :param fwhm: :return: """ row_number = self._pt_row_dict[scan_number, pt_number] self.update_cell_value(row_number, self._fwhm_index, fwhm) return
[ "def", "set_fwhm", "(", "self", ",", "scan_number", ",", "pt_number", ",", "fwhm", ")", ":", "row_number", "=", "self", ".", "_pt_row_dict", "[", "scan_number", ",", "pt_number", "]", "self", ".", "update_cell_value", "(", "row_number", ",", "self", ".", "_fwhm_index", ",", "fwhm", ")", "return" ]
https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/qt/python/mantidqtinterfaces/mantidqtinterfaces/HFIR_4Circle_Reduction/hfctables.py#L1623-L1634
yyzybb537/libgo
4af17b7c67643c4d54aa354dcc77963ea07847d0
third_party/boost.context/tools/build/src/build/engine.py
python
Engine.set_target_variable
(self, targets, variable, value, append=0)
Sets a target variable. The 'variable' will be available to bjam when it decides where to generate targets, and will also be available to updating rule for that 'taret'.
Sets a target variable.
[ "Sets", "a", "target", "variable", "." ]
def set_target_variable (self, targets, variable, value, append=0): """ Sets a target variable. The 'variable' will be available to bjam when it decides where to generate targets, and will also be available to updating rule for that 'taret'. """ if isinstance (targets, str): targets = [targets] if isinstance(value, str): value = [value] assert is_iterable(targets) assert isinstance(variable, basestring) assert is_iterable(value) for target in targets: self.do_set_target_variable (target, variable, value, append)
[ "def", "set_target_variable", "(", "self", ",", "targets", ",", "variable", ",", "value", ",", "append", "=", "0", ")", ":", "if", "isinstance", "(", "targets", ",", "str", ")", ":", "targets", "=", "[", "targets", "]", "if", "isinstance", "(", "value", ",", "str", ")", ":", "value", "=", "[", "value", "]", "assert", "is_iterable", "(", "targets", ")", "assert", "isinstance", "(", "variable", ",", "basestring", ")", "assert", "is_iterable", "(", "value", ")", "for", "target", "in", "targets", ":", "self", ".", "do_set_target_variable", "(", "target", ",", "variable", ",", "value", ",", "append", ")" ]
https://github.com/yyzybb537/libgo/blob/4af17b7c67643c4d54aa354dcc77963ea07847d0/third_party/boost.context/tools/build/src/build/engine.py#L121-L138
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/tools/Editra/src/plugin.py
python
PluginMeta.__new__
(mcs, name, bases, d)
return new_obj
Initialize the MetaClass @param mcs: Class instance @param name: Name of object @param bases: Plugin base classes @param d: Items dictionary
Initialize the MetaClass @param mcs: Class instance @param name: Name of object @param bases: Plugin base classes @param d: Items dictionary
[ "Initialize", "the", "MetaClass", "@param", "mcs", ":", "Class", "instance", "@param", "name", ":", "Name", "of", "object", "@param", "bases", ":", "Plugin", "base", "classes", "@param", "d", ":", "Items", "dictionary" ]
def __new__(mcs, name, bases, d): """Initialize the MetaClass @param mcs: Class instance @param name: Name of object @param bases: Plugin base classes @param d: Items dictionary """ d['_implements'] = _implements[:] del _implements[:] new_obj = type.__new__(mcs, name, bases, d) if name == 'Plugin': return new_obj init = d.get("__init__") if not init: for init in [b.__init__._original for b in new_obj.mro() if issubclass(b, Plugin) and '__init__' in b.__dict__]: break PluginMeta._plugins.append(new_obj) for interface in d.get('_implements', []): PluginMeta._registry.setdefault(interface, []).append(new_obj) for base in [base for base in bases if hasattr(base, '_implements')]: for interface in base._implements: PluginMeta._registry.setdefault(interface, []).append(new_obj) return new_obj
[ "def", "__new__", "(", "mcs", ",", "name", ",", "bases", ",", "d", ")", ":", "d", "[", "'_implements'", "]", "=", "_implements", "[", ":", "]", "del", "_implements", "[", ":", "]", "new_obj", "=", "type", ".", "__new__", "(", "mcs", ",", "name", ",", "bases", ",", "d", ")", "if", "name", "==", "'Plugin'", ":", "return", "new_obj", "init", "=", "d", ".", "get", "(", "\"__init__\"", ")", "if", "not", "init", ":", "for", "init", "in", "[", "b", ".", "__init__", ".", "_original", "for", "b", "in", "new_obj", ".", "mro", "(", ")", "if", "issubclass", "(", "b", ",", "Plugin", ")", "and", "'__init__'", "in", "b", ".", "__dict__", "]", ":", "break", "PluginMeta", ".", "_plugins", ".", "append", "(", "new_obj", ")", "for", "interface", "in", "d", ".", "get", "(", "'_implements'", ",", "[", "]", ")", ":", "PluginMeta", ".", "_registry", ".", "setdefault", "(", "interface", ",", "[", "]", ")", ".", "append", "(", "new_obj", ")", "for", "base", "in", "[", "base", "for", "base", "in", "bases", "if", "hasattr", "(", "base", ",", "'_implements'", ")", "]", ":", "for", "interface", "in", "base", ".", "_implements", ":", "PluginMeta", ".", "_registry", ".", "setdefault", "(", "interface", ",", "[", "]", ")", ".", "append", "(", "new_obj", ")", "return", "new_obj" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/src/plugin.py#L145-L172
gem5/gem5
141cc37c2d4b93959d4c249b8f7e6a8b2ef75338
src/cpu/BaseCPU.py
python
BaseCPU.generateDeviceTree
(self, state)
Generate cpu nodes for each thread and the corresponding part of the cpu-map node. Note that this implementation does not support clusters of clusters. Note that GEM5 is not compatible with the official way of numbering cores as defined in the Device Tree documentation. Where the cpu_id needs to reset to 0 for each cluster by specification, GEM5 expects the cpu_id to be globally unique and incremental. This generated node adheres the GEM5 way of doing things.
Generate cpu nodes for each thread and the corresponding part of the cpu-map node. Note that this implementation does not support clusters of clusters. Note that GEM5 is not compatible with the official way of numbering cores as defined in the Device Tree documentation. Where the cpu_id needs to reset to 0 for each cluster by specification, GEM5 expects the cpu_id to be globally unique and incremental. This generated node adheres the GEM5 way of doing things.
[ "Generate", "cpu", "nodes", "for", "each", "thread", "and", "the", "corresponding", "part", "of", "the", "cpu", "-", "map", "node", ".", "Note", "that", "this", "implementation", "does", "not", "support", "clusters", "of", "clusters", ".", "Note", "that", "GEM5", "is", "not", "compatible", "with", "the", "official", "way", "of", "numbering", "cores", "as", "defined", "in", "the", "Device", "Tree", "documentation", ".", "Where", "the", "cpu_id", "needs", "to", "reset", "to", "0", "for", "each", "cluster", "by", "specification", "GEM5", "expects", "the", "cpu_id", "to", "be", "globally", "unique", "and", "incremental", ".", "This", "generated", "node", "adheres", "the", "GEM5", "way", "of", "doing", "things", "." ]
def generateDeviceTree(self, state): """Generate cpu nodes for each thread and the corresponding part of the cpu-map node. Note that this implementation does not support clusters of clusters. Note that GEM5 is not compatible with the official way of numbering cores as defined in the Device Tree documentation. Where the cpu_id needs to reset to 0 for each cluster by specification, GEM5 expects the cpu_id to be globally unique and incremental. This generated node adheres the GEM5 way of doing things.""" if bool(self.switched_out): return cpus_node = FdtNode('cpus') cpus_node.append(state.CPUCellsProperty()) #Special size override of 0 cpus_node.append(FdtPropertyWords('#size-cells', [0])) # Generate cpu nodes for i in range(int(self.numThreads)): reg = (int(self.socket_id)<<8) + int(self.cpu_id) + i node = FdtNode("cpu@%x" % reg) node.append(FdtPropertyStrings("device_type", "cpu")) node.appendCompatible(["gem5,arm-cpu"]) node.append(FdtPropertyWords("reg", state.CPUAddrCells(reg))) platform, found = self.system.unproxy(self).find_any(Platform) if found: platform.annotateCpuDeviceNode(node, state) else: warn("Platform not found for device tree generation; " \ "system or multiple CPUs may not start") freq = int(self.clk_domain.unproxy(self).clock[0].frequency) node.append(FdtPropertyWords("clock-frequency", freq)) # Unique key for this CPU phandle_key = self.createPhandleKey(i) node.appendPhandle(phandle_key) cpus_node.append(node) yield cpus_node # Generate nodes from the BaseCPU children (hence under the root node, # and don't add them as subnode). Please note: this is mainly needed # for the ISA class, to generate the PMU entry in the DTB. for child_node in self.recurseDeviceTree(state): yield child_node
[ "def", "generateDeviceTree", "(", "self", ",", "state", ")", ":", "if", "bool", "(", "self", ".", "switched_out", ")", ":", "return", "cpus_node", "=", "FdtNode", "(", "'cpus'", ")", "cpus_node", ".", "append", "(", "state", ".", "CPUCellsProperty", "(", ")", ")", "#Special size override of 0", "cpus_node", ".", "append", "(", "FdtPropertyWords", "(", "'#size-cells'", ",", "[", "0", "]", ")", ")", "# Generate cpu nodes", "for", "i", "in", "range", "(", "int", "(", "self", ".", "numThreads", ")", ")", ":", "reg", "=", "(", "int", "(", "self", ".", "socket_id", ")", "<<", "8", ")", "+", "int", "(", "self", ".", "cpu_id", ")", "+", "i", "node", "=", "FdtNode", "(", "\"cpu@%x\"", "%", "reg", ")", "node", ".", "append", "(", "FdtPropertyStrings", "(", "\"device_type\"", ",", "\"cpu\"", ")", ")", "node", ".", "appendCompatible", "(", "[", "\"gem5,arm-cpu\"", "]", ")", "node", ".", "append", "(", "FdtPropertyWords", "(", "\"reg\"", ",", "state", ".", "CPUAddrCells", "(", "reg", ")", ")", ")", "platform", ",", "found", "=", "self", ".", "system", ".", "unproxy", "(", "self", ")", ".", "find_any", "(", "Platform", ")", "if", "found", ":", "platform", ".", "annotateCpuDeviceNode", "(", "node", ",", "state", ")", "else", ":", "warn", "(", "\"Platform not found for device tree generation; \"", "\"system or multiple CPUs may not start\"", ")", "freq", "=", "int", "(", "self", ".", "clk_domain", ".", "unproxy", "(", "self", ")", ".", "clock", "[", "0", "]", ".", "frequency", ")", "node", ".", "append", "(", "FdtPropertyWords", "(", "\"clock-frequency\"", ",", "freq", ")", ")", "# Unique key for this CPU", "phandle_key", "=", "self", ".", "createPhandleKey", "(", "i", ")", "node", ".", "appendPhandle", "(", "phandle_key", ")", "cpus_node", ".", "append", "(", "node", ")", "yield", "cpus_node", "# Generate nodes from the BaseCPU children (hence under the root node,", "# and don't add them as subnode). Please note: this is mainly needed", "# for the ISA class, to generate the PMU entry in the DTB.", "for", "child_node", "in", "self", ".", "recurseDeviceTree", "(", "state", ")", ":", "yield", "child_node" ]
https://github.com/gem5/gem5/blob/141cc37c2d4b93959d4c249b8f7e6a8b2ef75338/src/cpu/BaseCPU.py#L261-L305
thalium/icebox
99d147d5b9269222225443ce171b4fd46d8985d4
third_party/virtualbox/src/libs/libxml2-2.9.4/python/libxml2.py
python
uCSIsCypriotSyllabary
(code)
return ret
Check whether the character is part of CypriotSyllabary UCS Block
Check whether the character is part of CypriotSyllabary UCS Block
[ "Check", "whether", "the", "character", "is", "part", "of", "CypriotSyllabary", "UCS", "Block" ]
def uCSIsCypriotSyllabary(code): """Check whether the character is part of CypriotSyllabary UCS Block """ ret = libxml2mod.xmlUCSIsCypriotSyllabary(code) return ret
[ "def", "uCSIsCypriotSyllabary", "(", "code", ")", ":", "ret", "=", "libxml2mod", ".", "xmlUCSIsCypriotSyllabary", "(", "code", ")", "return", "ret" ]
https://github.com/thalium/icebox/blob/99d147d5b9269222225443ce171b4fd46d8985d4/third_party/virtualbox/src/libs/libxml2-2.9.4/python/libxml2.py#L2467-L2471
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/lib/combotreebox.py
python
BaseComboTreeBox.SetValue
(self, value)
Sets the text for the combobox text field. NB: For a combobox with wxCB_READONLY style the string must be in the combobox choices list, otherwise the call to SetValue() is ignored. :param string `value`: set the combobox text field
Sets the text for the combobox text field.
[ "Sets", "the", "text", "for", "the", "combobox", "text", "field", "." ]
def SetValue(self, value): """ Sets the text for the combobox text field. NB: For a combobox with wxCB_READONLY style the string must be in the combobox choices list, otherwise the call to SetValue() is ignored. :param string `value`: set the combobox text field """ item = self._tree.GetSelection() if not item or self._tree.GetItemText(item) != value: item = self.FindString(value) if self._readOnly and not item: return if self._text == self: super(BaseComboTreeBox, self).SetValue(value) else: self._text.SetValue(value) if item: if self._tree.GetSelection() != item: self._tree.SelectItem(item) else: self._tree.Unselect()
[ "def", "SetValue", "(", "self", ",", "value", ")", ":", "item", "=", "self", ".", "_tree", ".", "GetSelection", "(", ")", "if", "not", "item", "or", "self", ".", "_tree", ".", "GetItemText", "(", "item", ")", "!=", "value", ":", "item", "=", "self", ".", "FindString", "(", "value", ")", "if", "self", ".", "_readOnly", "and", "not", "item", ":", "return", "if", "self", ".", "_text", "==", "self", ":", "super", "(", "BaseComboTreeBox", ",", "self", ")", ".", "SetValue", "(", "value", ")", "else", ":", "self", ".", "_text", ".", "SetValue", "(", "value", ")", "if", "item", ":", "if", "self", ".", "_tree", ".", "GetSelection", "(", ")", "!=", "item", ":", "self", ".", "_tree", ".", "SelectItem", "(", "item", ")", "else", ":", "self", ".", "_tree", ".", "Unselect", "(", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/combotreebox.py#L734-L758
dicecco1/fpga_caffe
7a191704efd7873071cfef35772d7e7bf3e3cfd6
scripts/cpp_lint.py
python
FileInfo.IsSource
(self)
return self.Extension()[1:] in ('c', 'cc', 'cpp', 'cxx')
File has a source file extension.
File has a source file extension.
[ "File", "has", "a", "source", "file", "extension", "." ]
def IsSource(self): """File has a source file extension.""" return self.Extension()[1:] in ('c', 'cc', 'cpp', 'cxx')
[ "def", "IsSource", "(", "self", ")", ":", "return", "self", ".", "Extension", "(", ")", "[", "1", ":", "]", "in", "(", "'c'", ",", "'cc'", ",", "'cpp'", ",", "'cxx'", ")" ]
https://github.com/dicecco1/fpga_caffe/blob/7a191704efd7873071cfef35772d7e7bf3e3cfd6/scripts/cpp_lint.py#L960-L962
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python3/src/Lib/logging/handlers.py
python
BaseRotatingHandler.__init__
(self, filename, mode, encoding=None, delay=False, errors=None)
Use the specified filename for streamed logging
Use the specified filename for streamed logging
[ "Use", "the", "specified", "filename", "for", "streamed", "logging" ]
def __init__(self, filename, mode, encoding=None, delay=False, errors=None): """ Use the specified filename for streamed logging """ logging.FileHandler.__init__(self, filename, mode=mode, encoding=encoding, delay=delay, errors=errors) self.mode = mode self.encoding = encoding self.errors = errors
[ "def", "__init__", "(", "self", ",", "filename", ",", "mode", ",", "encoding", "=", "None", ",", "delay", "=", "False", ",", "errors", "=", "None", ")", ":", "logging", ".", "FileHandler", ".", "__init__", "(", "self", ",", "filename", ",", "mode", "=", "mode", ",", "encoding", "=", "encoding", ",", "delay", "=", "delay", ",", "errors", "=", "errors", ")", "self", ".", "mode", "=", "mode", "self", ".", "encoding", "=", "encoding", "self", ".", "errors", "=", "errors" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/logging/handlers.py#L54-L63
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/ipython/py3/IPython/utils/ipstruct.py
python
Struct.__sub__
(self,other)
return sout
s1 - s2 -> remove keys in s2 from s1. Examples -------- >>> s1 = Struct(a=10,b=30) >>> s2 = Struct(a=40) >>> s = s1 - s2 >>> s {'b': 30}
s1 - s2 -> remove keys in s2 from s1.
[ "s1", "-", "s2", "-", ">", "remove", "keys", "in", "s2", "from", "s1", "." ]
def __sub__(self,other): """s1 - s2 -> remove keys in s2 from s1. Examples -------- >>> s1 = Struct(a=10,b=30) >>> s2 = Struct(a=40) >>> s = s1 - s2 >>> s {'b': 30} """ sout = self.copy() sout -= other return sout
[ "def", "__sub__", "(", "self", ",", "other", ")", ":", "sout", "=", "self", ".", "copy", "(", ")", "sout", "-=", "other", "return", "sout" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/ipython/py3/IPython/utils/ipstruct.py#L184-L198
metashell/metashell
f4177e4854ea00c8dbc722cadab26ef413d798ea
3rd/templight/clang/tools/scan-build-py/libscanbuild/__init__.py
python
command_entry_point
(function)
return wrapper
Decorator for command entry methods. The decorator initialize/shutdown logging and guard on programming errors (catch exceptions). The decorated method can have arbitrary parameters, the return value will be the exit code of the process.
Decorator for command entry methods.
[ "Decorator", "for", "command", "entry", "methods", "." ]
def command_entry_point(function): """ Decorator for command entry methods. The decorator initialize/shutdown logging and guard on programming errors (catch exceptions). The decorated method can have arbitrary parameters, the return value will be the exit code of the process. """ @functools.wraps(function) def wrapper(*args, **kwargs): """ Do housekeeping tasks and execute the wrapped method. """ try: logging.basicConfig(format='%(name)s: %(message)s', level=logging.WARNING, stream=sys.stdout) # This hack to get the executable name as %(name). logging.getLogger().name = os.path.basename(sys.argv[0]) return function(*args, **kwargs) except KeyboardInterrupt: logging.warning('Keyboard interrupt') return 130 # Signal received exit code for bash. except Exception: logging.exception('Internal error.') if logging.getLogger().isEnabledFor(logging.DEBUG): logging.error("Please report this bug and attach the output " "to the bug report") else: logging.error("Please run this command again and turn on " "verbose mode (add '-vvvv' as argument).") return 64 # Some non used exit code for internal errors. finally: logging.shutdown() return wrapper
[ "def", "command_entry_point", "(", "function", ")", ":", "@", "functools", ".", "wraps", "(", "function", ")", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "\"\"\" Do housekeeping tasks and execute the wrapped method. \"\"\"", "try", ":", "logging", ".", "basicConfig", "(", "format", "=", "'%(name)s: %(message)s'", ",", "level", "=", "logging", ".", "WARNING", ",", "stream", "=", "sys", ".", "stdout", ")", "# This hack to get the executable name as %(name).", "logging", ".", "getLogger", "(", ")", ".", "name", "=", "os", ".", "path", ".", "basename", "(", "sys", ".", "argv", "[", "0", "]", ")", "return", "function", "(", "*", "args", ",", "*", "*", "kwargs", ")", "except", "KeyboardInterrupt", ":", "logging", ".", "warning", "(", "'Keyboard interrupt'", ")", "return", "130", "# Signal received exit code for bash.", "except", "Exception", ":", "logging", ".", "exception", "(", "'Internal error.'", ")", "if", "logging", ".", "getLogger", "(", ")", ".", "isEnabledFor", "(", "logging", ".", "DEBUG", ")", ":", "logging", ".", "error", "(", "\"Please report this bug and attach the output \"", "\"to the bug report\"", ")", "else", ":", "logging", ".", "error", "(", "\"Please run this command again and turn on \"", "\"verbose mode (add '-vvvv' as argument).\"", ")", "return", "64", "# Some non used exit code for internal errors.", "finally", ":", "logging", ".", "shutdown", "(", ")", "return", "wrapper" ]
https://github.com/metashell/metashell/blob/f4177e4854ea00c8dbc722cadab26ef413d798ea/3rd/templight/clang/tools/scan-build-py/libscanbuild/__init__.py#L106-L141
rsummers11/CADLab
976ed959a0b5208bb4173127a7ef732ac73a9b6f
LymphNodeRFCNNPipeline/pyconvnet/ordereddict.py
python
OrderedDict.viewvalues
(self)
return ValuesView(self)
od.viewvalues() -> an object providing a view on od's values
od.viewvalues() -> an object providing a view on od's values
[ "od", ".", "viewvalues", "()", "-", ">", "an", "object", "providing", "a", "view", "on", "od", "s", "values" ]
def viewvalues(self): "od.viewvalues() -> an object providing a view on od's values" return ValuesView(self)
[ "def", "viewvalues", "(", "self", ")", ":", "return", "ValuesView", "(", "self", ")" ]
https://github.com/rsummers11/CADLab/blob/976ed959a0b5208bb4173127a7ef732ac73a9b6f/LymphNodeRFCNNPipeline/pyconvnet/ordereddict.py#L252-L254
emscripten-core/emscripten
0d413d3c5af8b28349682496edc14656f5700c2f
third_party/ply/example/BASIC/basparse.py
python
p_command_gosub
(p)
command : GOSUB INTEGER
command : GOSUB INTEGER
[ "command", ":", "GOSUB", "INTEGER" ]
def p_command_gosub(p): '''command : GOSUB INTEGER''' p[0] = ('GOSUB',int(p[2]))
[ "def", "p_command_gosub", "(", "p", ")", ":", "p", "[", "0", "]", "=", "(", "'GOSUB'", ",", "int", "(", "p", "[", "2", "]", ")", ")" ]
https://github.com/emscripten-core/emscripten/blob/0d413d3c5af8b28349682496edc14656f5700c2f/third_party/ply/example/BASIC/basparse.py#L235-L237